mirocode 0.14.3 → 0.15.0

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/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames}=Object;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule||!__hasOwnProp.call(mod,"default")?__defProp(target,"default",{value:mod,enumerable:!0}):target;if(mod&&typeof mod==="object"||typeof mod==="function"){for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0})}if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};var __promiseAll=(args)=>Promise.all(args);var __exportCjs=(target,getters,setters)=>{for(var name in getters)__defProp(target,name,{get:getters[name],set:setters[name],enumerable:!0,configurable:!0})},__require=createRequire(import.meta.url);function ansiRegex({onlyFirst=!1}={}){return new RegExp("(?:(?:\\u001B\\]|\\u009D)[^\\u0007\\u001B\\u009C\\u009D]*(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]",onlyFirst?void 0:"g")}function stripAnsi(string){if(typeof string!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof string}\``);if(!string.includes("\x1B")&&!string.includes("›"))return string;return string.replace(regex,"")}var regex;var init_strip_ansi=__esm(()=>{regex=ansiRegex()});var ambiguousMinimalCodePoint=161,ambiguousMaximumCodePoint=1114109,ambiguousRanges,fullwidthMinimalCodePoint=12288,fullwidthMaximumCodePoint=65510,fullwidthRanges,wideMinimalCodePoint=4352,wideMaximumCodePoint=262141,wideRanges;var init_lookup_data=__esm(()=>{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],fullwidthRanges=[12288,12288,65281,65376,65504,65510],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,101594,101631,101664,101760,101874,101888,102801,102816,102866,110576,110579,110581,110587,110589,110590,110592,110888,110898,110898,110928,110930,110933,110933,110948,110952,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127406,127406,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,128729,128732,128735,128747,128748,128756,128764,128986,128986,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129734,129736,129736,129740,129757,129759,129771,129775,129786,131072,196605,196608,262141]});var isInRange=(ranges,codePoint)=>{let low=0,high=Math.floor(ranges.length/2)-1;while(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};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];if(end-start>fastPathEnd-fastPathStart)fastPathStart=start,fastPathEnd=end}return[fastPathStart,fastPathEnd]}var commonCjkCodePoint=19968,wideFastPathStart,wideFastPathEnd,isAmbiguous=(codePoint)=>{if(codePoint<ambiguousMinimalCodePoint||codePoint>ambiguousMaximumCodePoint)return!1;return isInRange(ambiguousRanges,codePoint)},isFullwidth=(codePoint)=>{if(codePoint<fullwidthMinimalCodePoint||codePoint>fullwidthMaximumCodePoint)return!1;return isInRange(fullwidthRanges,codePoint)},isWide=(codePoint)=>{if(codePoint>=wideFastPathStart&&codePoint<=wideFastPathEnd)return!0;if(codePoint<wideMinimalCodePoint||codePoint>wideMaximumCodePoint)return!1;return isInRange(wideRanges,codePoint)};var init_lookup=__esm(()=>{init_lookup_data();[wideFastPathStart,wideFastPathEnd]=findWideFastPathRange(wideRanges)});function validate(codePoint){if(!Number.isSafeInteger(codePoint))throw TypeError(`Expected a code point, got \`${typeof codePoint}\`.`)}function eastAsianWidth(codePoint,{ambiguousAsWide=!1}={}){if(validate(codePoint),isFullwidth(codePoint)||isWide(codePoint)||ambiguousAsWide&&isAmbiguous(codePoint))return 2;return 1}var init_get_east_asian_width=__esm(()=>{init_lookup();init_lookup()});function isDoubleWidthNonRgiEmojiSequence(segment){if(segment.length>50)return!1;if(unqualifiedKeycapRegex.test(segment))return!0;if(segment.includes("‍")){let pictographics=segment.match(extendedPictographicRegex);return pictographics!==null&&pictographics.length>=2}return!1}function baseVisible(segment){let index=segment.search(visibleCharacterRegex);return index===-1?void 0:segment.slice(index)}function isHangulLeadingJamo(codePoint){return codePoint>=4352&&codePoint<=4447||codePoint>=43360&&codePoint<=43388}function isHangulVowelJamo(codePoint){return codePoint>=4448&&codePoint<=4519||codePoint>=55216&&codePoint<=55238}function isHangulTrailingJamo(codePoint){return codePoint>=4520&&codePoint<=4607||codePoint>=55243&&codePoint<=55291}function isHangulJamo(codePoint){return isHangulLeadingJamo(codePoint)||isHangulVowelJamo(codePoint)||isHangulTrailingJamo(codePoint)}function hangulClusterWidth(visibleSegment,eastAsianWidthOptions){let codePoints=[];for(let character of visibleSegment){if(!visibleCharacterRegex.test(character))continue;codePoints.push(character.codePointAt(0))}if(codePoints.length===0)return;let width=0;for(let index=0;index<codePoints.length;index++){let codePoint=codePoints[index];if(!isHangulJamo(codePoint)){if(width===0)return;for(let remaining=index;remaining<codePoints.length;remaining++)width+=eastAsianWidth(codePoints[remaining],eastAsianWidthOptions);return width}if(isHangulLeadingJamo(codePoint)&&isHangulVowelJamo(codePoints[index+1])){width+=2,index+=isHangulTrailingJamo(codePoints[index+2])?2:1;continue}width+=eastAsianWidth(codePoint,eastAsianWidthOptions)}return width}function trailingWidth(visibleSegment,eastAsianWidthOptions){let extra=0,first=!0;for(let character of visibleSegment){if(first){first=!1;continue}if(spacingMarkRegex.test(character)||character>="＀"&&character<="￯")extra+=eastAsianWidth(character.codePointAt(0),eastAsianWidthOptions)}return extra}function stringWidth(input,options={}){if(typeof input!=="string"||input.length===0)return 0;let{ambiguousIsNarrow=!0,countAnsiEscapeCodes=!1}=options,string=input;if(!countAnsiEscapeCodes&&(string.includes("\x1B")||string.includes("›")))string=stripAnsi(string);if(string.length===0)return 0;if(/^[\u0020-\u007E]*$/.test(string))return string.length;let width=0,eastAsianWidthOptions={ambiguousAsWide:!ambiguousIsNarrow};for(let{segment}of segmenter.segment(string)){let visibleSegment=baseVisible(segment);if(visibleSegment===void 0)continue;if(rgiEmojiRegex.test(segment)||isDoubleWidthNonRgiEmojiSequence(segment)){width+=2;continue}let hangulWidth=hangulClusterWidth(visibleSegment,eastAsianWidthOptions);if(hangulWidth!==void 0){width+=hangulWidth;continue}let codePoint=visibleSegment.codePointAt(0);width+=eastAsianWidth(codePoint,eastAsianWidthOptions),width+=trailingWidth(visibleSegment,eastAsianWidthOptions)}return width}var segmenter,visibleCharacterRegex,spacingMarkRegex,rgiEmojiRegex,unqualifiedKeycapRegex,extendedPictographicRegex;var init_string_width=__esm(()=>{init_strip_ansi();init_get_east_asian_width();segmenter=new Intl.Segmenter,visibleCharacterRegex=/[^\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Nonspacing_Mark}\p{Enclosing_Mark}\p{Surrogate}]/v,spacingMarkRegex=/\p{Spacing_Mark}/v,rgiEmojiRegex=/^\p{RGI_Emoji}$/v,unqualifiedKeycapRegex=/^[\d#*]\u20E3$/,extendedPictographicRegex=/\p{Extended_Pictographic}/gu});function assembleStyles(){let codes=new Map;for(let[groupName,group]of Object.entries(styles)){for(let[styleName,style]of Object.entries(group))styles[styleName]={open:`\x1B[${style[0]}m`,close:`\x1B[${style[1]}m`},group[styleName]=styles[styleName],codes.set(style[0],style[1]);Object.defineProperty(styles,groupName,{value:group,enumerable:!1})}return Object.defineProperty(styles,"codes",{value:codes,enumerable:!1}),styles.color.close="\x1B[39m",styles.bgColor.close="\x1B[49m",styles.color.ansi=wrapAnsi16(),styles.color.ansi256=wrapAnsi256(),styles.color.ansi16m=wrapAnsi16m(),styles.bgColor.ansi=wrapAnsi16(10),styles.bgColor.ansi256=wrapAnsi256(10),styles.bgColor.ansi16m=wrapAnsi16m(10),Object.defineProperties(styles,{rgbToAnsi256:{value(red,green,blue){if(red===green&&green===blue){if(red<8)return 16;if(red>248)return 231;return Math.round((red-8)/247*24)+232}return 16+36*Math.round(red/255*5)+6*Math.round(green/255*5)+Math.round(blue/255*5)},enumerable:!1},hexToRgb:{value(hex){let matches=/[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));if(!matches)return[0,0,0];let[colorString]=matches;if(colorString.length===3)colorString=[...colorString].map((character)=>character+character).join("");let integer=Number.parseInt(colorString,16);return[integer>>16&255,integer>>8&255,integer&255]},enumerable:!1},hexToAnsi256:{value:(hex)=>styles.rgbToAnsi256(...styles.hexToRgb(hex)),enumerable:!1},ansi256ToAnsi:{value(code){if(code<8)return 30+code;if(code<16)return 90+(code-8);let red,green,blue;if(code>=232)red=((code-232)*10+8)/255,green=red,blue=red;else{code-=16;let remainder=code%36;red=Math.floor(code/36)/5,green=Math.floor(remainder/6)/5,blue=remainder%6/5}let value=Math.max(red,green,blue)*2;if(value===0)return 30;let result=30+(Math.round(blue)<<2|Math.round(green)<<1|Math.round(red));if(value===2)result+=60;return result},enumerable:!1},rgbToAnsi:{value:(red,green,blue)=>styles.ansi256ToAnsi(styles.rgbToAnsi256(red,green,blue)),enumerable:!1},hexToAnsi:{value:(hex)=>styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),enumerable:!1}}),styles}var wrapAnsi16=(offset=0)=>(code)=>`\x1B[${code+offset}m`,wrapAnsi256=(offset=0)=>(code)=>`\x1B[${38+offset};5;${code}m`,wrapAnsi16m=(offset=0)=>(red,green,blue)=>`\x1B[${38+offset};2;${red};${green};${blue}m`,styles,modifierNames,foregroundColorNames,backgroundColorNames,colorNames,ansiStyles,ansi_styles_default;var init_ansi_styles=__esm(()=>{styles={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},modifierNames=Object.keys(styles.modifier),foregroundColorNames=Object.keys(styles.color),backgroundColorNames=Object.keys(styles.bgColor),colorNames=[...foregroundColorNames,...backgroundColorNames];ansiStyles=assembleStyles(),ansi_styles_default=ansiStyles});function wrapAnsi(string,columns,options){return normalizeText(String(string)).replaceAll(`\r
2
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames}=Object;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule||!__hasOwnProp.call(mod,"default")?__defProp(target,"default",{value:mod,enumerable:!0}):target;if(mod&&typeof mod==="object"||typeof mod==="function"){for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0})}if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};var __require=createRequire(import.meta.url);function ansiRegex({onlyFirst=!1}={}){return new RegExp("(?:(?:\\u001B\\]|\\u009D)[^\\u0007\\u001B\\u009C\\u009D]*(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]",onlyFirst?void 0:"g")}function stripAnsi(string){if(typeof string!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof string}\``);if(!string.includes("\x1B")&&!string.includes("›"))return string;return string.replace(regex,"")}var regex;var init_strip_ansi=__esm(()=>{regex=ansiRegex()});var ambiguousMinimalCodePoint=161,ambiguousMaximumCodePoint=1114109,ambiguousRanges,fullwidthMinimalCodePoint=12288,fullwidthMaximumCodePoint=65510,fullwidthRanges,wideMinimalCodePoint=4352,wideMaximumCodePoint=262141,wideRanges;var init_lookup_data=__esm(()=>{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],fullwidthRanges=[12288,12288,65281,65376,65504,65510],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,101594,101631,101664,101760,101874,101888,102801,102816,102866,110576,110579,110581,110587,110589,110590,110592,110888,110898,110898,110928,110930,110933,110933,110948,110952,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127406,127406,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,128729,128732,128735,128747,128748,128756,128764,128986,128986,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129734,129736,129736,129740,129757,129759,129771,129775,129786,131072,196605,196608,262141]});var isInRange=(ranges,codePoint)=>{let low=0,high=Math.floor(ranges.length/2)-1;while(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};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];if(end-start>fastPathEnd-fastPathStart)fastPathStart=start,fastPathEnd=end}return[fastPathStart,fastPathEnd]}var commonCjkCodePoint=19968,wideFastPathStart,wideFastPathEnd,isAmbiguous=(codePoint)=>{if(codePoint<ambiguousMinimalCodePoint||codePoint>ambiguousMaximumCodePoint)return!1;return isInRange(ambiguousRanges,codePoint)},isFullwidth=(codePoint)=>{if(codePoint<fullwidthMinimalCodePoint||codePoint>fullwidthMaximumCodePoint)return!1;return isInRange(fullwidthRanges,codePoint)},isWide=(codePoint)=>{if(codePoint>=wideFastPathStart&&codePoint<=wideFastPathEnd)return!0;if(codePoint<wideMinimalCodePoint||codePoint>wideMaximumCodePoint)return!1;return isInRange(wideRanges,codePoint)};var init_lookup=__esm(()=>{init_lookup_data();[wideFastPathStart,wideFastPathEnd]=findWideFastPathRange(wideRanges)});function validate(codePoint){if(!Number.isSafeInteger(codePoint))throw TypeError(`Expected a code point, got \`${typeof codePoint}\`.`)}function eastAsianWidth(codePoint,{ambiguousAsWide=!1}={}){if(validate(codePoint),isFullwidth(codePoint)||isWide(codePoint)||ambiguousAsWide&&isAmbiguous(codePoint))return 2;return 1}var init_get_east_asian_width=__esm(()=>{init_lookup()});function isDoubleWidthNonRgiEmojiSequence(segment){if(segment.length>50)return!1;if(unqualifiedKeycapRegex.test(segment))return!0;if(segment.includes("‍")){let pictographics=segment.match(extendedPictographicRegex);return pictographics!==null&&pictographics.length>=2}return!1}function baseVisible(segment){let index=segment.search(visibleCharacterRegex);return index===-1?void 0:segment.slice(index)}function isHangulLeadingJamo(codePoint){return codePoint>=4352&&codePoint<=4447||codePoint>=43360&&codePoint<=43388}function isHangulVowelJamo(codePoint){return codePoint>=4448&&codePoint<=4519||codePoint>=55216&&codePoint<=55238}function isHangulTrailingJamo(codePoint){return codePoint>=4520&&codePoint<=4607||codePoint>=55243&&codePoint<=55291}function isHangulJamo(codePoint){return isHangulLeadingJamo(codePoint)||isHangulVowelJamo(codePoint)||isHangulTrailingJamo(codePoint)}function hangulClusterWidth(visibleSegment,eastAsianWidthOptions){let codePoints=[];for(let character of visibleSegment){if(!visibleCharacterRegex.test(character))continue;codePoints.push(character.codePointAt(0))}if(codePoints.length===0)return;let width=0;for(let index=0;index<codePoints.length;index++){let codePoint=codePoints[index];if(!isHangulJamo(codePoint)){if(width===0)return;for(let remaining=index;remaining<codePoints.length;remaining++)width+=eastAsianWidth(codePoints[remaining],eastAsianWidthOptions);return width}if(isHangulLeadingJamo(codePoint)&&isHangulVowelJamo(codePoints[index+1])){width+=2,index+=isHangulTrailingJamo(codePoints[index+2])?2:1;continue}width+=eastAsianWidth(codePoint,eastAsianWidthOptions)}return width}function trailingWidth(visibleSegment,eastAsianWidthOptions){let extra=0,first=!0;for(let character of visibleSegment){if(first){first=!1;continue}if(spacingMarkRegex.test(character)||character>="＀"&&character<="￯")extra+=eastAsianWidth(character.codePointAt(0),eastAsianWidthOptions)}return extra}function stringWidth(input,options={}){if(typeof input!=="string"||input.length===0)return 0;let{ambiguousIsNarrow=!0,countAnsiEscapeCodes=!1}=options,string=input;if(!countAnsiEscapeCodes&&(string.includes("\x1B")||string.includes("›")))string=stripAnsi(string);if(string.length===0)return 0;if(/^[\u0020-\u007E]*$/.test(string))return string.length;let width=0,eastAsianWidthOptions={ambiguousAsWide:!ambiguousIsNarrow};for(let{segment}of segmenter.segment(string)){let visibleSegment=baseVisible(segment);if(visibleSegment===void 0)continue;if(rgiEmojiRegex.test(segment)||isDoubleWidthNonRgiEmojiSequence(segment)){width+=2;continue}let hangulWidth=hangulClusterWidth(visibleSegment,eastAsianWidthOptions);if(hangulWidth!==void 0){width+=hangulWidth;continue}let codePoint=visibleSegment.codePointAt(0);width+=eastAsianWidth(codePoint,eastAsianWidthOptions),width+=trailingWidth(visibleSegment,eastAsianWidthOptions)}return width}var segmenter,visibleCharacterRegex,spacingMarkRegex,rgiEmojiRegex,unqualifiedKeycapRegex,extendedPictographicRegex;var init_string_width=__esm(()=>{init_strip_ansi();init_get_east_asian_width();segmenter=new Intl.Segmenter,visibleCharacterRegex=/[^\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Nonspacing_Mark}\p{Enclosing_Mark}\p{Surrogate}]/v,spacingMarkRegex=/\p{Spacing_Mark}/v,rgiEmojiRegex=/^\p{RGI_Emoji}$/v,unqualifiedKeycapRegex=/^[\d#*]\u20E3$/,extendedPictographicRegex=/\p{Extended_Pictographic}/gu});function assembleStyles(){let codes=new Map;for(let[groupName,group]of Object.entries(styles)){for(let[styleName,style]of Object.entries(group))styles[styleName]={open:`\x1B[${style[0]}m`,close:`\x1B[${style[1]}m`},group[styleName]=styles[styleName],codes.set(style[0],style[1]);Object.defineProperty(styles,groupName,{value:group,enumerable:!1})}return Object.defineProperty(styles,"codes",{value:codes,enumerable:!1}),styles.color.close="\x1B[39m",styles.bgColor.close="\x1B[49m",styles.color.ansi=wrapAnsi16(),styles.color.ansi256=wrapAnsi256(),styles.color.ansi16m=wrapAnsi16m(),styles.bgColor.ansi=wrapAnsi16(10),styles.bgColor.ansi256=wrapAnsi256(10),styles.bgColor.ansi16m=wrapAnsi16m(10),Object.defineProperties(styles,{rgbToAnsi256:{value(red,green,blue){if(red===green&&green===blue){if(red<8)return 16;if(red>248)return 231;return Math.round((red-8)/247*24)+232}return 16+36*Math.round(red/255*5)+6*Math.round(green/255*5)+Math.round(blue/255*5)},enumerable:!1},hexToRgb:{value(hex){let matches=/[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));if(!matches)return[0,0,0];let[colorString]=matches;if(colorString.length===3)colorString=[...colorString].map((character)=>character+character).join("");let integer=Number.parseInt(colorString,16);return[integer>>16&255,integer>>8&255,integer&255]},enumerable:!1},hexToAnsi256:{value:(hex)=>styles.rgbToAnsi256(...styles.hexToRgb(hex)),enumerable:!1},ansi256ToAnsi:{value(code){if(code<8)return 30+code;if(code<16)return 90+(code-8);let red,green,blue;if(code>=232)red=((code-232)*10+8)/255,green=red,blue=red;else{code-=16;let remainder=code%36;red=Math.floor(code/36)/5,green=Math.floor(remainder/6)/5,blue=remainder%6/5}let value=Math.max(red,green,blue)*2;if(value===0)return 30;let result=30+(Math.round(blue)<<2|Math.round(green)<<1|Math.round(red));if(value===2)result+=60;return result},enumerable:!1},rgbToAnsi:{value:(red,green,blue)=>styles.ansi256ToAnsi(styles.rgbToAnsi256(red,green,blue)),enumerable:!1},hexToAnsi:{value:(hex)=>styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),enumerable:!1}}),styles}var wrapAnsi16=(offset=0)=>(code)=>`\x1B[${code+offset}m`,wrapAnsi256=(offset=0)=>(code)=>`\x1B[${38+offset};5;${code}m`,wrapAnsi16m=(offset=0)=>(red,green,blue)=>`\x1B[${38+offset};2;${red};${green};${blue}m`,styles,modifierNames,foregroundColorNames,backgroundColorNames,colorNames,ansiStyles,ansi_styles_default;var init_ansi_styles=__esm(()=>{styles={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},modifierNames=Object.keys(styles.modifier),foregroundColorNames=Object.keys(styles.color),backgroundColorNames=Object.keys(styles.bgColor),colorNames=[...foregroundColorNames,...backgroundColorNames];ansiStyles=assembleStyles(),ansi_styles_default=ansiStyles});function wrapAnsi(string,columns,options){return normalizeText(String(string)).replaceAll(`\r
3
3
  `,`
4
4
  `).split(`
5
5
  `).map((line)=>exec(expandTabs(line),columns,options)).join(`
@@ -7,7 +7,7 @@ import{createRequire}from"node:module";var __create=Object.create;var{getPrototy
7
7
  `){let escape2=matchAnsiEscape(preString,index);if(!escape2){index++;continue}let{groups}=escape2;if(groups.sgr!==void 0)applySgrParameters(groups.sgr,activeStyles);else if(groups.uri!==void 0)activeHyperlink=groups.uri.length===0?void 0:{parameters:groups.parameters,uri:groups.uri};index+=escape2[0].length;continue}if(returnValue+=preString.slice(copiedIndex,index),index>copiedIndex){if(activeHyperlink)returnValue+=wrapAnsiHyperlink("");returnValue+=getClosingSgrSequence(activeStyles)}if(returnValue+=`
8
8
  `,index++,copiedIndex=index,index<preString.length&&preString[index]!==`
9
9
  `){let openingStyles=[...activeStyles];if(applyLeadingSgrResets(preString,index,openingStyles),returnValue+=getOpeningSgrSequence(openingStyles),activeHyperlink)returnValue+=wrapAnsiHyperlink(activeHyperlink.uri,activeHyperlink.parameters)}}return returnValue+preString.slice(copiedIndex)},exec=(string,columns,options={})=>{if(options.trim!==!1&&string.trim()==="")return"";let words=splitWords(string),rows=[""],rowLength=0,trimmedRowIndex=-1,isFirstWord=!0;for(let word of words){let rowIndex=rows.length-1;if(options.trim!==!1&&trimmedRowIndex!==rowIndex){let row=rows[rowIndex],trimmedRow=row.trimStart();if(trimmedRow.length!==row.length)rows[rowIndex]=trimmedRow,rowLength=getWidth(trimmedRow);if(trimmedRow.length>0)trimmedRowIndex=rowIndex}if(isFirstWord)isFirstWord=!1;else{if(rowLength>=columns&&(options.wordWrap===!1||options.trim===!1))rows.push(""),rowLength=0;if(rowLength>0||options.trim===!1)rows[rows.length-1]+=" ",rowLength++}if(options.hard&&options.wordWrap!==!1&&word.width>columns){let remainingColumns=columns-rowLength,breaksStartingThisLine=1+Math.floor((word.width-remainingColumns-1)/columns);if(Math.floor((word.width-1)/columns)<breaksStartingThisLine)rows.push(""),rowLength=0;rowLength=wrapWord(rows,word.value,columns,rowLength);continue}if(rowLength+word.width>columns&&rowLength>0&&word.width>0){if(options.wordWrap===!1&&rowLength<columns){rowLength=wrapWord(rows,word.value,columns,rowLength);continue}rows.push(""),rowLength=0}if(rowLength+word.width>columns&&options.wordWrap===!1){rowLength=wrapWord(rows,word.value,columns,rowLength);continue}rows[rows.length-1]+=word.value,rowLength+=word.width}if(options.trim!==!1)rows=rows.map((row)=>stringVisibleTrimSpacesRight(row));return restoreStylesAcrossRows(rows.join(`
10
- `))},normalizeText=(string)=>{let normalizedString="";return forEachSegment(string,(plainText)=>{normalizedString+=plainText.normalize()},(escape2)=>{normalizedString+=escape2}),normalizedString};var init_wrap_ansi=__esm(()=>{init_string_width();init_ansi_styles();ANSI_ESCAPE_LINK=`${ANSI_OSC}8;`,ESCAPES=new Set([ANSI_ESCAPE,C1_CSI]),ESCAPE_CHARACTERS=[...ESCAPES].join(""),CSI_INTRODUCER=`(?:${ANSI_ESCAPE}\\${ANSI_CSI}|${C1_CSI})`,SGR_PARAMETERS=`(?<sgr>[0-9;:]*)${ANSI_SGR_TERMINATOR}`,OSC_STRING_TERMINATOR=`(?:${ANSI_ESCAPE_BELL}|${ANSI_ESCAPE}\\\\)`,OSC_STRING_PAYLOAD=String.raw`[^\u0000-\u001F\u007F-\u009F]*`,LINK_PARAMETERS=String.raw`8;(?<parameters>[^;\u0000-\u001F\u007F-\u009F]*);(?<uri>${OSC_STRING_PAYLOAD})${OSC_STRING_TERMINATOR}`,OSC_STRING=`${OSC_STRING_PAYLOAD}${OSC_STRING_TERMINATOR}`,ANSI_ESCAPE_REGEX=new RegExp(`${CSI_INTRODUCER}(?:${SGR_PARAMETERS}|${CSI_PARAMETERS})|${ANSI_ESCAPE}\\${ANSI_OSC}(?:${LINK_PARAMETERS}|${OSC_STRING})`,"y"),ANSI_SGR_MODIFIER_CLOSE_CODES=new Set(ansi_styles_default.codes.values());ANSI_SGR_MODIFIER_CLOSE_CODES.delete(ANSI_SGR_RESET);segmenter2=new Intl.Segmenter,ESCAPE_INTRODUCER_REGEX=new RegExp(`[${ESCAPE_CHARACTERS}]`,"g"),ROW_BOUNDARY_REGEX=new RegExp(`[\\n${ESCAPE_CHARACTERS}]`,"g"),ASCII_PRINTABLE_REGEX=/^[ -~]*$/});import path from"node:path";function normalizePermissionMode(value){if(typeof value!=="string")return DEFAULT_PERMISSION_MODE;let normalized=value.trim().toLowerCase();return PERMISSION_MODES.includes(normalized)?normalized:DEFAULT_PERMISSION_MODE}function isAuto(mode){return normalizePermissionMode(mode)==="auto"}function isManual(mode){return normalizePermissionMode(mode)==="manual"}function permissionScope({name,kind,rawInput,cwd}){if(name==="mcp_call")return`${name}:${JSON.stringify({server:rawInput?.server,name:rawInput?.name,arguments:rawInput?.arguments})}`;if(kind==="execute"){let command=typeof rawInput?.command==="string"?rawInput.command.trim():"",workdir=resolveWorkdir(cwd,rawInput),sandbox=rawInput?.sandbox!==!1,domains=Array.isArray(rawInput?.allowedDomains)?rawInput.allowedDomains.filter((domain)=>typeof domain==="string").map((domain)=>domain.trim()).sort():[];return`${name}:${JSON.stringify({command,workdir,sandbox,domains})}`}let target=resolveTargetPath(cwd,rawInput);return target==null?name:`${name}:${path.resolve(target)}`}function resolveTargetPath(cwd,rawInput){let raw=typeof rawInput?.path==="string"?rawInput.path:null;if(!raw)return null;return raw.startsWith("/")?raw:`${cwd}/${raw}`.replace(/\/{2,}/g,"/")}function resolveWorkdir(cwd,rawInput){let raw=typeof rawInput?.workdir==="string"?rawInput.workdir.trim():"";if(!raw)return cwd;return raw.startsWith("/")?raw:`${cwd}/${raw}`.replace(/\/{2,}/g,"/")}function permissionModeMessage(value){return PERMISSION_MODE_MESSAGES[normalizePermissionMode(value)]}function matchPermissionMode(query){if(query==null)return null;let lower=String(query).trim().toLowerCase();if(!lower)return null;return PERMISSION_MODE_CHOICES.find((choice)=>choice.value===lower)??PERMISSION_MODE_CHOICES.find((choice)=>choice.name.toLowerCase()===lower)??null}var PERMISSION_MODES,DEFAULT_PERMISSION_MODE="auto",AUTO_WARNING="miro: AUTO mode is on — tools run without user approval. High-risk terminal commands and sandbox opt-outs receive an isolated safety review and are denied when the reviewer cannot approve them.",MANUAL_WARNING="miro: MANUAL mode is on — writes, edits, deletes, moves, and commands require approval and are denied in non-interactive mode. Read-only tools run without confirmation.",PERMISSION_MODE_CHOICES,PERMISSION_MODE_MESSAGES;var init_permission_mode=__esm(()=>{PERMISSION_MODES=["auto","manual"];PERMISSION_MODE_CHOICES=[{value:"auto",name:"Auto",description:"Run without prompts; auto-review high-risk or unsandboxed terminal calls"},{value:"manual",name:"Manual",description:"Ask before writes, edits, deletes, moves, and commands"}],PERMISSION_MODE_MESSAGES={auto:"Permission mode: Auto — tools run without user prompts; high-risk terminal commands and sandbox opt-outs are reviewed automatically and denied unless approved.",manual:"Permission mode: Manual — writes, edits, deletes, moves, and commands require approval; read-only tools run without confirmation. There is no OS sandbox."}});function isMiroProvider(provider){return provider?.kind==="miro"||provider?.id===MIRO_PROVIDER_ID}var APP_NAME="miro",APP_VERSION="0.14.3",PROVIDERS,MIRO_PROVIDER_ID="miro",MAX_TRANSCRIPT_LENGTH=500000,CLEAR_TERMINAL="\x1B[2J\x1B[3J\x1B[H",BASH_PREVIEW_LINES=20,DYNAMIC_BASH_PREVIEW_LINES=8,THOUGHT_PREVIEW_LINES=6,COMMAND_PREVIEW_ROWS=3,THOUGHT_UI_FLUSH_MS=50,THOUGHT_STAT_SAMPLE_TICKS=5,PLAN_MAX_ROWS=20,HELP=`Miro CLI
10
+ `))},normalizeText=(string)=>{let normalizedString="";return forEachSegment(string,(plainText)=>{normalizedString+=plainText.normalize()},(escape2)=>{normalizedString+=escape2}),normalizedString};var init_wrap_ansi=__esm(()=>{init_string_width();init_ansi_styles();ANSI_ESCAPE_LINK=`${ANSI_OSC}8;`,ESCAPES=new Set([ANSI_ESCAPE,C1_CSI]),ESCAPE_CHARACTERS=[...ESCAPES].join(""),CSI_INTRODUCER=`(?:${ANSI_ESCAPE}\\${ANSI_CSI}|${C1_CSI})`,SGR_PARAMETERS=`(?<sgr>[0-9;:]*)${ANSI_SGR_TERMINATOR}`,OSC_STRING_TERMINATOR=`(?:${ANSI_ESCAPE_BELL}|${ANSI_ESCAPE}\\\\)`,OSC_STRING_PAYLOAD=String.raw`[^\u0000-\u001F\u007F-\u009F]*`,LINK_PARAMETERS=String.raw`8;(?<parameters>[^;\u0000-\u001F\u007F-\u009F]*);(?<uri>${OSC_STRING_PAYLOAD})${OSC_STRING_TERMINATOR}`,OSC_STRING=`${OSC_STRING_PAYLOAD}${OSC_STRING_TERMINATOR}`,ANSI_ESCAPE_REGEX=new RegExp(`${CSI_INTRODUCER}(?:${SGR_PARAMETERS}|${CSI_PARAMETERS})|${ANSI_ESCAPE}\\${ANSI_OSC}(?:${LINK_PARAMETERS}|${OSC_STRING})`,"y"),ANSI_SGR_MODIFIER_CLOSE_CODES=new Set(ansi_styles_default.codes.values());ANSI_SGR_MODIFIER_CLOSE_CODES.delete(ANSI_SGR_RESET);segmenter2=new Intl.Segmenter,ESCAPE_INTRODUCER_REGEX=new RegExp(`[${ESCAPE_CHARACTERS}]`,"g"),ROW_BOUNDARY_REGEX=new RegExp(`[\\n${ESCAPE_CHARACTERS}]`,"g"),ASCII_PRINTABLE_REGEX=/^[ -~]*$/});import path from"node:path";function normalizePermissionMode(value){if(typeof value!=="string")return DEFAULT_PERMISSION_MODE;let normalized=value.trim().toLowerCase();return PERMISSION_MODES.includes(normalized)?normalized:DEFAULT_PERMISSION_MODE}function isAuto(mode){return normalizePermissionMode(mode)==="auto"}function isManual(mode){return normalizePermissionMode(mode)==="manual"}function permissionScope({name,kind,rawInput,cwd}){if(name==="mcp_call")return`${name}:${JSON.stringify({server:rawInput?.server,name:rawInput?.name,arguments:rawInput?.arguments})}`;if(kind==="execute"){let command=typeof rawInput?.command==="string"?rawInput.command.trim():"",workdir=resolveWorkdir(cwd,rawInput),sandbox=rawInput?.sandbox!==!1,domains=Array.isArray(rawInput?.allowedDomains)?rawInput.allowedDomains.filter((domain)=>typeof domain==="string").map((domain)=>domain.trim()).sort():[];return`${name}:${JSON.stringify({command,workdir,sandbox,domains})}`}let target=resolveTargetPath(cwd,rawInput);return target==null?name:`${name}:${path.resolve(target)}`}function resolveTargetPath(cwd,rawInput){let raw=typeof rawInput?.path==="string"?rawInput.path:null;if(!raw)return null;return raw.startsWith("/")?raw:`${cwd}/${raw}`.replace(/\/{2,}/g,"/")}function resolveWorkdir(cwd,rawInput){let raw=typeof rawInput?.workdir==="string"?rawInput.workdir.trim():"";if(!raw)return cwd;return raw.startsWith("/")?raw:`${cwd}/${raw}`.replace(/\/{2,}/g,"/")}function permissionModeMessage(value){return PERMISSION_MODE_MESSAGES[normalizePermissionMode(value)]}function matchPermissionMode(query){if(query==null)return null;let lower=String(query).trim().toLowerCase();if(!lower)return null;return PERMISSION_MODE_CHOICES.find((choice)=>choice.value===lower)??PERMISSION_MODE_CHOICES.find((choice)=>choice.name.toLowerCase()===lower)??null}var PERMISSION_MODES,DEFAULT_PERMISSION_MODE="auto",AUTO_WARNING="miro: AUTO mode is on — tools run without user approval. High-risk terminal commands and sandbox opt-outs receive an isolated safety review and are denied when the reviewer cannot approve them.",MANUAL_WARNING="miro: MANUAL mode is on — writes, edits, deletes, moves, and commands require approval and are denied in non-interactive mode. Read-only tools run without confirmation.",PERMISSION_MODE_CHOICES,PERMISSION_MODE_MESSAGES;var init_permission_mode=__esm(()=>{PERMISSION_MODES=["auto","manual"];PERMISSION_MODE_CHOICES=[{value:"auto",name:"Auto",description:"Run without prompts; auto-review high-risk or unsandboxed terminal calls"},{value:"manual",name:"Manual",description:"Ask before writes, edits, deletes, moves, and commands"}],PERMISSION_MODE_MESSAGES={auto:"Permission mode: Auto — tools run without user prompts; high-risk terminal commands and sandbox opt-outs are reviewed automatically and denied unless approved.",manual:"Permission mode: Manual — writes, edits, deletes, moves, and commands require approval; read-only tools run without confirmation. There is no OS sandbox."}});function isMiroProvider(provider){return provider?.kind==="miro"||provider?.id===MIRO_PROVIDER_ID}var APP_NAME="miro",APP_VERSION="0.15.0",PROVIDERS,MIRO_PROVIDER_ID="miro",MAX_TRANSCRIPT_LENGTH=500000,BASH_PREVIEW_LINES=20,DYNAMIC_BASH_PREVIEW_LINES=8,THOUGHT_PREVIEW_LINES=6,COMMAND_PREVIEW_ROWS=3,THOUGHT_UI_FLUSH_MS=50,THOUGHT_STAT_SAMPLE_TICKS=5,PLAN_MAX_ROWS=20,HELP=`Miro CLI
11
11
 
12
12
  An interactive and non-interactive terminal client with a built-in coding agent
13
13
  and optional ACP-compatible providers.
@@ -1273,64 +1273,48 @@ ${parsed.args}`}var SKILL_FILE="SKILL.md",NAME_PATTERN,MAX_NAME_LENGTH=64,MAX_DE
1273
1273
  `:`
1274
1274
  `)+postfix,endIndex=index+1,index=string.indexOf(`
1275
1275
  `,endIndex)}while(index!==-1);return returnValue+=string.slice(endIndex),returnValue}function assembleStyles2(){let codes=new Map;for(let[groupName,group]of Object.entries(styles2)){for(let[styleName,style]of Object.entries(group))styles2[styleName]={open:`\x1B[${style[0]}m`,close:`\x1B[${style[1]}m`},group[styleName]=styles2[styleName],codes.set(Number.parseInt(style[0],10),style[1]);Object.defineProperty(styles2,groupName,{value:group,enumerable:!1})}return Object.defineProperty(styles2,"codes",{value:codes,enumerable:!1}),styles2.color.close="\x1B[39m",styles2.bgColor.close="\x1B[49m",styles2.underlineColor.close="\x1B[59m",styles2.color.ansi=wrapAnsi162(),styles2.color.ansi256=wrapAnsi2562(),styles2.color.ansi16m=wrapAnsi16m2(),styles2.bgColor.ansi=wrapAnsi162(10),styles2.bgColor.ansi256=wrapAnsi2562(10),styles2.bgColor.ansi16m=wrapAnsi16m2(10),styles2.underlineColor.ansi=wrapUnderlineAnsi,styles2.underlineColor.ansi256=wrapAnsi2562(20),styles2.underlineColor.ansi16m=wrapAnsi16m2(20),Object.defineProperties(styles2,{rgbToAnsi256:{value(red,green,blue){if(red===green&&green===blue){if(red<8)return 16;if(red>248)return 231;return Math.round((red-8)/247*24)+232}return 16+36*Math.round(red/255*5)+6*Math.round(green/255*5)+Math.round(blue/255*5)},enumerable:!1},hexToRgb:{value(hex){let matches=/[\da-f]{6}|[\da-f]{3}/i.exec(hex.toString(16));if(!matches)return[0,0,0];let[colorString]=matches;if(colorString.length===3)colorString=[...colorString].map((character)=>character+character).join("");let integer=Number.parseInt(colorString,16);return[integer>>16&255,integer>>8&255,integer&255]},enumerable:!1},hexToAnsi256:{value:(hex)=>styles2.rgbToAnsi256(...styles2.hexToRgb(hex)),enumerable:!1},ansi256ToAnsi:{value(code){if(code<8)return 30+code;if(code<16)return 90+(code-8);let red,green,blue;if(code>=232)red=((code-232)*10+8)/255,green=red,blue=red;else{code-=16;let remainder=code%36;red=Math.floor(code/36)/5,green=Math.floor(remainder/6)/5,blue=remainder%6/5}let value=Math.max(red,green,blue)*2;if(value===0)return 30;let result=30+(Math.round(blue)<<2|Math.round(green)<<1|Math.round(red));if(value===2)result+=60;return result},enumerable:!1},rgbToAnsi:{value:(red,green,blue)=>styles2.ansi256ToAnsi(styles2.rgbToAnsi256(red,green,blue)),enumerable:!1},hexToAnsi:{value:(hex)=>styles2.ansi256ToAnsi(styles2.hexToAnsi256(hex)),enumerable:!1}}),styles2}var wrapAnsi162=(offset=0)=>(code)=>`\x1B[${code+offset}m`,wrapAnsi2562=(offset=0)=>(code)=>`\x1B[${38+offset};5;${code}m`,wrapAnsi16m2=(offset=0)=>(red,green,blue)=>`\x1B[${38+offset};2;${red};${green};${blue}m`,wrapUnderlineAnsi=(code)=>`\x1B[58;5;${code<90?code-30:code-90+8}m`,styles2,modifierNames2,foregroundColorNames2,backgroundColorNames2,underlineColorNames,colorNames2,ansiStyles2,ansi_styles_default2;var init_ansi_styles2=__esm(()=>{styles2={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],underlineDouble:["4:2",24],underlineCurly:["4:3",24],underlineDotted:["4:4",24],underlineDashed:["4:5",24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]},underlineColor:{underlineBlack:["58;5;0",59],underlineRed:["58;5;1",59],underlineGreen:["58;5;2",59],underlineYellow:["58;5;3",59],underlineBlue:["58;5;4",59],underlineMagenta:["58;5;5",59],underlineCyan:["58;5;6",59],underlineWhite:["58;5;7",59],underlineBlackBright:["58;5;8",59],underlineGray:["58;5;8",59],underlineGrey:["58;5;8",59],underlineRedBright:["58;5;9",59],underlineGreenBright:["58;5;10",59],underlineYellowBright:["58;5;11",59],underlineBlueBright:["58;5;12",59],underlineMagentaBright:["58;5;13",59],underlineCyanBright:["58;5;14",59],underlineWhiteBright:["58;5;15",59]}},modifierNames2=Object.keys(styles2.modifier),foregroundColorNames2=Object.keys(styles2.color),backgroundColorNames2=Object.keys(styles2.bgColor),underlineColorNames=Object.keys(styles2.underlineColor),colorNames2=[...foregroundColorNames2,...backgroundColorNames2];ansiStyles2=assembleStyles2(),ansi_styles_default2=ansiStyles2});import process14 from"node:process";import os9 from"node:os";import tty from"node:tty";function hasFlag(flag,argv=globalThis.Deno?globalThis.Deno.args:process14.argv){let prefix=flag.startsWith("-")?"":flag.length===1?"-":"--",position=argv.indexOf(prefix+flag),terminatorPosition=argv.indexOf("--");return position!==-1&&(terminatorPosition===-1||position<terminatorPosition)}function hasNumericForceColor(){return/^\d+$/.test(env3.FORCE_COLOR)}function envForceColor(){if(!("FORCE_COLOR"in env3))return;if(env3.FORCE_COLOR==="false")return 0;if(env3.FORCE_COLOR==="true"||env3.FORCE_COLOR.length===0)return 1;if(!hasNumericForceColor())return;return Math.min(Number.parseInt(env3.FORCE_COLOR,10),3)}function translateLevel(level){if(level===0)return!1;return{level,hasBasic:!0,has256:level>=2,has16m:level>=3}}function _supportsColor(haveStream,{streamIsTTY,sniffFlags=!0}={}){let noFlagForceColor=envForceColor();if(noFlagForceColor!==void 0)flagForceColor=noFlagForceColor;let forceColor=sniffFlags?flagForceColor:noFlagForceColor;if(forceColor===0)return 0;if(sniffFlags){if(hasFlag("color=16m")||hasFlag("color=full")||hasFlag("color=truecolor"))return 3;if(hasFlag("color=256"))return 2}if(forceColor!==void 0&&hasNumericForceColor())return forceColor;if("TF_BUILD"in env3&&"AGENT_NAME"in env3)return 1;if(haveStream&&!streamIsTTY&&forceColor===void 0)return 0;let min=forceColor||0;if(env3.TERM==="dumb")return min;if(process14.platform==="win32"){let osRelease=os9.release().split(".");if(Number(osRelease[0])>=10&&Number(osRelease[2])>=10586)return Number(osRelease[2])>=14931?3:2;return 1}if("CI"in env3){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some((key)=>(key in env3)))return 3;if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((sign)=>(sign in env3))||env3.CI_NAME==="codeship")return 1;return min}if("TEAMCITY_VERSION"in env3)return/^(?:9\.0*[1-9]\d*\.|\d{2,}\.)/.test(env3.TEAMCITY_VERSION)?1:0;if(env3.COLORTERM==="truecolor")return 3;if(env3.TERM==="xterm-kitty")return 3;if(env3.TERM==="xterm-ghostty")return 3;if(env3.TERM==="wezterm")return 3;if("TERM_PROGRAM"in env3){let version=Number.parseInt((env3.TERM_PROGRAM_VERSION||"").split(".",1)[0],10);switch(env3.TERM_PROGRAM){case"iTerm.app":return version>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(?:color)?$/i.test(env3.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env3.TERM))return 1;if("COLORTERM"in env3)return 1;return min}function createSupportsColor(stream,options={}){let level=_supportsColor(stream,{streamIsTTY:stream&&stream.isTTY,...options});return translateLevel(level)}var env3,flagForceColor,supportsColor,supports_color_default;var init_supports_color=__esm(()=>{({env:env3}=process14);if(hasFlag("no-color")||hasFlag("no-colors")||hasFlag("color=false")||hasFlag("color=never"))flagForceColor=0;else if(hasFlag("color")||hasFlag("colors")||hasFlag("color=true")||hasFlag("color=always"))flagForceColor=1;supportsColor={stdout:createSupportsColor({isTTY:tty.isatty(1)}),stderr:createSupportsColor({isTTY:tty.isatty(2)})},supports_color_default=supportsColor});function createChalk(options){return chalkFactory(options)}var stdoutColor,stderrColor,GENERATOR,STYLER,IS_EMPTY,LEVEL,styles3,assertValidLevel=(level)=>{if(!Number.isSafeInteger(level)||level<0||level>3)throw Error("The `level` should be an integer from 0 to 3")},levelDescriptor,applyOptions=(object,options={})=>{if(options.level!==void 0)assertValidLevel(options.level);let colorLevel=stdoutColor?stdoutColor.level:0;object[LEVEL]=options.level===void 0?colorLevel:options.level},chalkFactory=(options)=>{let chalk=(...strings)=>strings.join(" ");return applyOptions(chalk,options),Object.setPrototypeOf(chalk,createChalk.prototype),chalk},createModelConverters=(model,type)=>{let style=ansi_styles_default2[type];if(model==="rgb"){let ansi=(red,green,blue)=>style.ansi(ansi_styles_default2.rgbToAnsi(red,green,blue));return[ansi,ansi,(red,green,blue)=>style.ansi256(ansi_styles_default2.rgbToAnsi256(red,green,blue)),style.ansi16m]}if(model==="hex"){let ansi=(hex)=>style.ansi(ansi_styles_default2.hexToAnsi(hex));return[ansi,ansi,(hex)=>style.ansi256(ansi_styles_default2.hexToAnsi256(hex)),(hex)=>style.ansi16m(...ansi_styles_default2.hexToRgb(hex))]}let ansi=(code)=>style.ansi(ansi_styles_default2.ansi256ToAnsi(code));return[ansi,ansi,style.ansi256,style.ansi256]},usedModels,proto,createStyler=(open,close,parent)=>{let openAll,closeAll;if(parent===void 0)openAll=open,closeAll=close;else openAll=parent.openAll+open,closeAll=close+parent.closeAll;return{open,close,openAll,closeAll,parent}},createBuilder=(self2,_styler,_isEmpty)=>{let builder=(...arguments_)=>{if(arguments_.length===1)return applyStyle(builder,""+arguments_[0]);if(arguments_.length===2)return applyStyle(builder,`${arguments_[0]??""} ${arguments_[1]??""}`);return applyStyle(builder,arguments_.join(" "))};return Object.setPrototypeOf(builder,proto),builder[GENERATOR]=self2[GENERATOR]??self2,builder[STYLER]=_styler,builder[IS_EMPTY]=_isEmpty,builder},applyStyle=(self2,string)=>{if(self2[GENERATOR][LEVEL]<=0||!string)return self2[IS_EMPTY]?"":string;let styler=self2[STYLER];if(styler===void 0)return string;let{openAll,closeAll}=styler;if(string.includes("\x1B"))while(styler!==void 0)string=stringReplaceAll(string,styler.close,styler.open),styler=styler.parent;let lfIndex=string.indexOf(`
1276
- `);if(lfIndex!==-1)string=stringEncaseCRLFWithFirstIndex(string,closeAll,openAll,lfIndex);return openAll+string+closeAll},chalk,chalkStderr,source_default;var init_source2=__esm(()=>{init_ansi_styles2();init_supports_color();init_ansi_styles2();({stdout:stdoutColor,stderr:stderrColor}=supports_color_default),GENERATOR=Symbol("GENERATOR"),STYLER=Symbol("STYLER"),IS_EMPTY=Symbol("IS_EMPTY"),LEVEL=Symbol("LEVEL"),styles3=Object.create(null),levelDescriptor={enumerable:!0,get(){return this[LEVEL]},set(level){assertValidLevel(level),this[LEVEL]=level}};Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(let[styleName,style]of Object.entries(ansi_styles_default2))styles3[styleName]={get(){let builder=createBuilder(this,createStyler(style.open,style.close,this[STYLER]),this[IS_EMPTY]);return Object.defineProperty(this,styleName,{value:builder}),builder}};styles3.visible={get(){let builder=createBuilder(this,this[STYLER],!0);return Object.defineProperty(this,"visible",{value:builder}),builder}};usedModels=["rgb","hex","ansi256"];for(let model of usedModels){let capitalizedModel=model[0].toUpperCase()+model.slice(1);for(let[styleName,type]of[[model,"color"],["bg"+capitalizedModel,"bgColor"],["underline"+capitalizedModel,"underlineColor"]]){let{close}=ansi_styles_default2[type],converters=createModelConverters(model,type);styles3[styleName]={get(){let styleFunction=function(first,second,third){let open=converters[this.level](first,second,third);return createBuilder(this,createStyler(open,close,this[STYLER]),this[IS_EMPTY])};return Object.defineProperty(this,styleName,{value:styleFunction}),styleFunction}}}}proto=Object.defineProperties(()=>{},{...styles3,level:{enumerable:!0,get(){return this[GENERATOR].level},set(level){this[GENERATOR].level=level}}});Object.defineProperties(createChalk.prototype,{...styles3,level:levelDescriptor});chalk=createChalk(),chalkStderr=createChalk({level:stderrColor?stderrColor.level:0}),source_default=chalk});function Component(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}function ComponentDummy(){}function PureComponent(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}function ReactElement(type,key,props){var refProp=props.ref;return{$$typeof:REACT_ELEMENT_TYPE,type,key,ref:refProp!==void 0?refProp:null,props}}var REACT_ELEMENT_TYPE,REACT_CONSUMER_TYPE,REACT_CONTEXT_TYPE,REACT_FORWARD_REF_TYPE,REACT_MEMO_TYPE,ReactNoopUpdateQueue,assign2,emptyObject,pureComponentPrototype,ReactSharedInternals,hasOwnProperty,$PureComponent,$__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,$createContext=function(defaultValue){return defaultValue={$$typeof:REACT_CONTEXT_TYPE,_currentValue:defaultValue,_currentValue2:defaultValue,_threadCount:0,Provider:null,Consumer:null},defaultValue.Provider=defaultValue,defaultValue.Consumer={$$typeof:REACT_CONSUMER_TYPE,_context:defaultValue},defaultValue},$createElement=function(type,config,children){var propName,props={},key=null;if(config!=null)for(propName in config.key!==void 0&&(key=""+config.key),config)hasOwnProperty.call(config,propName)&&propName!=="key"&&propName!=="__self"&&propName!=="__source"&&(props[propName]=config[propName]);var childrenLength=arguments.length-2;if(childrenLength===1)props.children=children;else if(1<childrenLength){for(var childArray=Array(childrenLength),i=0;i<childrenLength;i++)childArray[i]=arguments[i+2];props.children=childArray}if(type&&type.defaultProps)for(propName in childrenLength=type.defaultProps,childrenLength)props[propName]===void 0&&(props[propName]=childrenLength[propName]);return ReactElement(type,key,props)},$forwardRef=function(render){return{$$typeof:REACT_FORWARD_REF_TYPE,render}},$memo=function(type,compare){return{$$typeof:REACT_MEMO_TYPE,type,compare:compare===void 0?null:compare}},$use=function(usable){return ReactSharedInternals.H.use(usable)},$useCallback=function(callback,deps){return ReactSharedInternals.H.useCallback(callback,deps)},$useDebugValue=function(){},$useEffect=function(create,deps){return ReactSharedInternals.H.useEffect(create,deps)},$useEffectEvent=function(callback){return ReactSharedInternals.H.useEffectEvent(callback)},$useInsertionEffect=function(create,deps){return ReactSharedInternals.H.useInsertionEffect(create,deps)},$useLayoutEffect=function(create,deps){return ReactSharedInternals.H.useLayoutEffect(create,deps)},$useMemo=function(create,deps){return ReactSharedInternals.H.useMemo(create,deps)},$useReducer=function(reducer,initialArg,init){return ReactSharedInternals.H.useReducer(reducer,initialArg,init)},$useRef=function(initialValue){return ReactSharedInternals.H.useRef(initialValue)},$useState=function(initialState){return ReactSharedInternals.H.useState(initialState)},$useSyncExternalStore=function(subscribe,getSnapshot,getServerSnapshot){return ReactSharedInternals.H.useSyncExternalStore(subscribe,getSnapshot,getServerSnapshot)},$version="19.3.1";var init_react_production=__esm(()=>{REACT_ELEMENT_TYPE=Symbol.for("react.transitional.element"),REACT_CONSUMER_TYPE=Symbol.for("react.consumer"),REACT_CONTEXT_TYPE=Symbol.for("react.context"),REACT_FORWARD_REF_TYPE=Symbol.for("react.forward_ref"),REACT_MEMO_TYPE=Symbol.for("react.memo"),ReactNoopUpdateQueue={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},assign2=Object.assign,emptyObject={};Component.prototype.isReactComponent={};Component.prototype.setState=function(partialState,callback){if(typeof partialState!=="object"&&typeof partialState!=="function"&&partialState!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,partialState,callback,"setState")};Component.prototype.forceUpdate=function(callback){this.updater.enqueueForceUpdate(this,callback,"forceUpdate")};ComponentDummy.prototype=Component.prototype;pureComponentPrototype=PureComponent.prototype=new ComponentDummy;pureComponentPrototype.constructor=PureComponent;assign2(pureComponentPrototype,Component.prototype);pureComponentPrototype.isPureReactComponent=!0;ReactSharedInternals={H:null,A:null,T:null,S:null},hasOwnProperty=Object.prototype.hasOwnProperty;$PureComponent=PureComponent,$__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=ReactSharedInternals});function debounce(func,debounceMs,{signal,edges}={}){let pendingThis=void 0,pendingArgs=null,leading=edges!=null&&edges.includes("leading"),trailing=edges==null||edges.includes("trailing"),invoke=()=>{if(pendingArgs!==null)func.apply(pendingThis,pendingArgs),pendingThis=void 0,pendingArgs=null},onTimerEnd=()=>{if(trailing)invoke();cancel()},timeoutId=null,schedule=()=>{if(timeoutId!=null)clearTimeout(timeoutId);timeoutId=setTimeout(()=>{timeoutId=null,onTimerEnd()},debounceMs)},cancelTimer=()=>{if(timeoutId!==null)clearTimeout(timeoutId),timeoutId=null},cancel=()=>{cancelTimer(),pendingThis=void 0,pendingArgs=null},flush=()=>{invoke()},debounced=function(...args){if(signal?.aborted)return;pendingThis=this,pendingArgs=args;let isFirstCall=timeoutId==null;if(schedule(),leading&&isFirstCall)invoke()};return debounced.schedule=schedule,debounced.cancel=cancel,debounced.flush=flush,signal?.addEventListener("abort",cancel,{once:!0}),debounced}var init_debounce=()=>{};function debounce2(func,debounceMs=0,options={}){if(typeof options!=="object")options={};let{leading=!1,trailing=!0,maxWait}=options,edges=Array(2);if(leading)edges[0]="leading";if(trailing)edges[1]="trailing";let result=void 0,pendingAt=null,_debounced=debounce(function(...args){result=func.apply(this,args),pendingAt=null},debounceMs,{edges}),debounced=function(...args){if(maxWait!=null){if(pendingAt===null)pendingAt=Date.now();if(Date.now()-pendingAt>=maxWait){if(leading||trailing)result=func.apply(this,args);return pendingAt=Date.now(),_debounced.cancel(),_debounced.schedule(),result}}return _debounced.apply(this,args),result},flush=()=>(_debounced.flush(),result);return debounced.cancel=_debounced.cancel,debounced.flush=flush,debounced}var init_debounce2=__esm(()=>{init_debounce()});function throttle(func,throttleMs=0,options={}){let{leading=!0,trailing=!0}=options;return debounce2(func,throttleMs,{leading,maxWait:throttleMs,trailing})}var init_throttle=__esm(()=>{init_debounce2()});var init_compat2=__esm(()=>{init_throttle()});var isBrowser,isNode,isBun,isDeno,isElectron,isJsDom,isWebWorker,isDedicatedWorker,isSharedWorker,isServiceWorker,platform,isMacOs,isWindows,isLinux,isIos,isAndroid;var init_environment3=__esm(()=>{isBrowser=globalThis.window?.document!==void 0,isNode=globalThis.process?.versions?.node!==void 0,isBun=globalThis.process?.versions?.bun!==void 0,isDeno=globalThis.Deno?.version?.deno!==void 0,isElectron=globalThis.process?.versions?.electron!==void 0,isJsDom=globalThis.navigator?.userAgent?.includes("jsdom")===!0,isWebWorker=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,isDedicatedWorker=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,isSharedWorker=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,isServiceWorker=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,platform=globalThis.navigator?.userAgentData?.platform,isMacOs=platform==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",isWindows=platform==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",isLinux=platform==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",isIos=platform==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),isAndroid=platform==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android"});import process15 from"node:process";import os10 from"node:os";var ESC="\x1B[",SEP=";",isTerminalApp,isWindows2,isTmux,cwdFunction,cursorTo=(x,y)=>{if(typeof x!=="number")throw TypeError("The `x` argument is required");if(typeof y!=="number")return ESC+(x+1)+"G";return ESC+(y+1)+SEP+(x+1)+"H"},cursorMove=(x,y)=>{if(typeof x!=="number")throw TypeError("The `x` argument is required");let returnValue="";if(x<0)returnValue+=ESC+-x+"D";else if(x>0)returnValue+=ESC+x+"C";if(y<0)returnValue+=ESC+-y+"A";else if(y>0)returnValue+=ESC+y+"B";return returnValue},cursorUp=(count=1)=>ESC+count+"A",cursorDown=(count=1)=>ESC+count+"B",cursorLeft,cursorSavePosition,cursorRestorePosition,cursorGetPosition,cursorNextLine,cursorPrevLine,cursorHide,cursorShow,eraseLines=(count)=>{let clear="";for(let i=0;i<count;i++)clear+=eraseLine+(i<count-1?cursorUp():"");if(count)clear+=cursorLeft;return clear},eraseEndLine,eraseStartLine,eraseLine,eraseDown,eraseUp,eraseScreen,scrollUp,scrollDown,clearViewport,isOldWindows=()=>{if(isBrowser||!isWindows2)return!1;let parts=os10.release().split("."),major=Number(parts[0]),build=Number(parts[2]??0);if(major<10)return!0;if(major===10&&build<10586)return!0;return!1},clearTerminal,enterAlternativeScreen,exitAlternativeScreen,beginSynchronizedOutput,endSynchronizedOutput;var init_base=__esm(()=>{init_environment3();isTerminalApp=!isBrowser&&process15.env.TERM_PROGRAM==="Apple_Terminal",isWindows2=!isBrowser&&process15.platform==="win32",isTmux=!isBrowser&&(process15.env.TERM?.startsWith("screen")||process15.env.TERM?.startsWith("tmux")||process15.env.TMUX!==void 0),cwdFunction=isBrowser?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:process15.cwd,cursorLeft=ESC+"G",cursorSavePosition=isTerminalApp?"\x1B7":ESC+"s",cursorRestorePosition=isTerminalApp?"\x1B8":ESC+"u",cursorGetPosition=ESC+"6n",cursorNextLine=ESC+"E",cursorPrevLine=ESC+"F",cursorHide=ESC+"?25l",cursorShow=ESC+"?25h",eraseEndLine=ESC+"K",eraseStartLine=ESC+"1K",eraseLine=ESC+"2K",eraseDown=ESC+"J",eraseUp=ESC+"1J",eraseScreen=ESC+"2J",scrollUp=ESC+"S",scrollDown=ESC+"T",clearViewport=`${eraseScreen}${ESC}H`,clearTerminal=isOldWindows()?`${eraseScreen}${ESC}0f`:`${eraseScreen}${ESC}3J${ESC}H`,enterAlternativeScreen=ESC+"?1049h",exitAlternativeScreen=ESC+"?1049l",beginSynchronizedOutput=ESC+"?2026h",endSynchronizedOutput=ESC+"?2026l"});var init_ansi_escapes=__esm(()=>{init_base();init_base()});import{env as env4}from"node:process";var check5=(key)=>(key in env4)&&env4[key]!=="0"&&env4[key]!=="false",isInCi,is_in_ci_default;var init_is_in_ci=__esm(()=>{isInCi=check5("CI")||check5("CONTINUOUS_INTEGRATION"),is_in_ci_default=isInCi});function autoBind(self2,{include,exclude}={}){let filter=(key)=>{let match=(pattern)=>typeof pattern==="string"?key===pattern:pattern.test(key);if(include)return include.some(match);if(exclude)return!exclude.some(match);return!0};for(let[object,key]of getAllProperties(self2.constructor.prototype)){if(key==="constructor"||!filter(key))continue;let descriptor=Reflect.getOwnPropertyDescriptor(object,key);if(descriptor&&typeof descriptor.value==="function")self2[key]=self2[key].bind(self2)}return self2}var getAllProperties=(object)=>{let properties=new Set;do for(let key of Reflect.ownKeys(object))properties.add([object,key]);while((object=Reflect.getPrototypeOf(object))&&object!==Object.prototype);return properties};var require_signals=__commonJS(function(exports,module){module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var require_signal_exit=__commonJS(function(exports,module){var process2=global.process,processOk=function(process2){return process2&&typeof process2==="object"&&typeof process2.removeListener==="function"&&typeof process2.emit==="function"&&typeof process2.reallyExit==="function"&&typeof process2.listeners==="function"&&typeof process2.kill==="function"&&typeof process2.pid==="number"&&typeof process2.on==="function"};if(!processOk(process2))module.exports=function(){return function(){}};else{if(assert=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process2.platform),EE=__require("events"),typeof EE!=="function")EE=EE.EventEmitter;if(process2.__signal_exit_emitter__)emitter=process2.__signal_exit_emitter__;else emitter=process2.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={};if(!emitter.infinite)emitter.setMaxListeners(1/0),emitter.infinite=!0;module.exports=function(cb,opts){if(!processOk(global.process))return function(){};if(assert.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1)load();var ev="exit";if(opts&&opts.alwaysLast)ev="afterexit";var remove=function(){if(emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0)unload()};return emitter.on(ev,cb),remove},unload=function(){if(!loaded||!processOk(global.process))return;loaded=!1,signals.forEach(function(sig){try{process2.removeListener(sig,sigListeners[sig])}catch(er){}}),process2.emit=originalProcessEmit,process2.reallyExit=originalProcessReallyExit,emitter.count-=1},module.exports.unload=unload,emit=function(event,code,signal){if(emitter.emitted[event])return;emitter.emitted[event]=!0,emitter.emit(event,code,signal)},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(!processOk(global.process))return;var listeners=process2.listeners(sig);if(listeners.length===emitter.count){if(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP")sig="SIGINT";process2.kill(process2.pid,sig)}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){if(loaded||!processOk(global.process))return;loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process2.on(sig,sigListeners[sig]),!0}catch(er){return!1}}),process2.emit=processEmit,process2.reallyExit=processReallyExit},module.exports.load=load,originalProcessReallyExit=process2.reallyExit,processReallyExit=function(code){if(!processOk(global.process))return;process2.exitCode=code||0,emit("exit",process2.exitCode,null),emit("afterexit",process2.exitCode,null),originalProcessReallyExit.call(process2,process2.exitCode)},originalProcessEmit=process2.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){if(arg!==void 0)process2.exitCode=arg;var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process2.exitCode,null),emit("afterexit",process2.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}}var assert,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit});import{PassThrough as PassThrough2}from"node:stream";var consoleMethods,originalMethods,patchConsole=(callback)=>{let stdout=new PassThrough2,stderr=new PassThrough2;stdout.write=(data)=>{callback("stdout",data)},stderr.write=(data)=>{callback("stderr",data)};let internalConsole=new console.Console(stdout,stderr);for(let method of consoleMethods)originalMethods[method]=console[method],console[method]=internalConsole[method];return()=>{for(let method of consoleMethods)console[method]=originalMethods[method];originalMethods={}}},dist_default;var init_dist7=__esm(()=>{consoleMethods=["assert","count","countReset","debug","dir","dirxml","error","group","groupCollapsed","groupEnd","info","log","table","time","timeEnd","timeLog","trace","warn"],originalMethods={},dist_default=patchConsole});var $ConcurrentRoot=1,$DefaultEventPriority=32,$LegacyRoot=0,$NoEventPriority=0;var init_react_reconciler_constants_production=()=>{};var loadYoga,yoga_wasm_base64_esm_default;var init_yoga_wasm_base64_esm=__esm(()=>{loadYoga=(()=>{var _scriptDir=import.meta.url;return function(loadYoga){loadYoga=loadYoga||{};var h;h||(h=typeof loadYoga<"u"?loadYoga:{});var aa,ca;h.ready=new Promise(function(a,b){aa=a,ca=b});var da=Object.assign({},h),q="";typeof document<"u"&&document.currentScript&&(q=document.currentScript.src),_scriptDir&&(q=_scriptDir),q.indexOf("blob:")!==0?q=q.substr(0,q.replace(/[?#].*/,"").lastIndexOf("/")+1):q="";var ea=h.print||console.log.bind(console),v=h.printErr||console.warn.bind(console);Object.assign(h,da),da=null;var w;h.wasmBinary&&(w=h.wasmBinary);var noExitRuntime=h.noExitRuntime||!0;typeof WebAssembly!="object"&&x("no native wasm support detected");var fa,ha=!1;function z(a,b,c){c=b+c;for(var d="";!(b>=c);){var e=a[b++];if(!e)break;if(e&128){var f=a[b++]&63;if((e&224)==192)d+=String.fromCharCode((e&31)<<6|f);else{var g=a[b++]&63;e=(e&240)==224?(e&15)<<12|f<<6|g:(e&7)<<18|f<<12|g<<6|a[b++]&63,65536>e?d+=String.fromCharCode(e):(e-=65536,d+=String.fromCharCode(55296|e>>10,56320|e&1023))}}else d+=String.fromCharCode(e)}return d}var ia,ja,A,C,ka,D,E,la,ma;function na(){var a=fa.buffer;ia=a,h.HEAP8=ja=new Int8Array(a),h.HEAP16=C=new Int16Array(a),h.HEAP32=D=new Int32Array(a),h.HEAPU8=A=new Uint8Array(a),h.HEAPU16=ka=new Uint16Array(a),h.HEAPU32=E=new Uint32Array(a),h.HEAPF32=la=new Float32Array(a),h.HEAPF64=ma=new Float64Array(a)}var oa,pa=[],qa=[],ra=[];function sa(){var a=h.preRun.shift();pa.unshift(a)}var F=0,ta=null,G=null;function x(a){if(h.onAbort)h.onAbort(a);throw a="Aborted("+a+")",v(a),ha=!0,a=new WebAssembly.RuntimeError(a+". Build with -sASSERTIONS for more info."),ca(a),a}function ua(a){return a.startsWith("data:application/octet-stream;base64,")}var H="data:application/octet-stream;base64,AGFzbQEAAAABugM3YAF/AGACf38AYAF/AX9gA39/fwBgAn98AGACf38Bf2ADf39/AX9gBH9/f30BfWADf398AGAAAGAEf39/fwBgAX8BfGACf38BfGAFf39/f38Bf2AAAX9gA39/fwF9YAZ/f31/fX8AYAV/f39/fwBgAn9/AX1gBX9/f319AX1gAX8BfWADf35/AX5gB39/f39/f38AYAZ/f39/f38AYAR/f39/AX9gBn9/f319fQF9YAR/f31/AGADf399AX1gBn98f39/fwF/YAR/fHx/AGACf30AYAh/f39/f39/fwBgDX9/f39/f39/f39/f38AYAp/f39/f39/f39/AGAFf39/f38BfGAEfHx/fwF9YA1/fX1/f399fX9/f39/AX9gB39/f319f38AYAJ+fwF/YAN/fX0BfWABfAF8YAN/fHwAYAR/f319AGAHf39/fX19fQF9YA1/fX99f31/fX19fX1/AX9gC39/f39/f399fX19AX9gCH9/f39/f319AGAEf39+fgBgB39/f39/f38Bf2ACfH8BfGAFf398fH8AYAN/f38BfGAEf39/fABgA39/fQBgBn9/fX99fwF/ArUBHgFhAWEAHwFhAWIAAwFhAWMACQFhAWQAFgFhAWUAEQFhAWYAIAFhAWcAAAFhAWgAIQFhAWkAAwFhAWoA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NBAWsgAToAACACQQNJDQAgACABOgACIAAgAToAASADQQNrIAE6AAAgA0ECayABOgAAIAJBB0kNACAAIAE6AAMgA0EEayABOgAAIAJBCUkNACAAQQAgAGtBA3EiBGoiAyABQf8BcUGBgoQIbCIBNgIAIAMgAiAEa0F8cSIEaiICQQRrIAE2AgAgBEEJSQ0AIAMgATYCCCADIAE2AgQgAkEIayABNgIAIAJBDGsgATYCACAEQRlJDQAgAyABNgIYIAMgATYCFCADIAE2AhAgAyABNgIMIAJBEGsgATYCACACQRRrIAE2AgAgAkEYayABNgIAIAJBHGsgATYCACAEIANBBHFBGHIiBGsiAkEgSQ0AIAGtQoGAgIAQfiEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkEgayICQR9LDQALCyAAC4AEAQN/IAJBgARPBEAgACABIAIQFyAADwsgACACaiEDAkAgACABc0EDcUUEQAJAIABBA3FFBEAgACECDAELIAJFBEAgACECDAELIAAhAgNAIAIgAS0AADoAACABQQFqIQEgAkEBaiICQQNxRQ0BIAIgA0kNAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgACADQQRrIgRLBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiAD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YoAhAhAwsgBiADQQFqNgIQIAYoAgwgA0EDdkH8////AXFqIgAgACgCAEF+IAN3cTYCACABLwAAIQMLIANBB3EgC0EEdHJBCHIhAwsgASADOwAAIAhBEGokAAuPAQIBfwF9IwBBEGsiAyQAIANBCGogAEHoAGogAEHUAEHWACABQf4BcUECRhtqLwEAIgEgAC8BWCABQQdxGxAfQwAAwH8hBAJAAkACQCADLQAMQQFrDgIAAQILIAMqAgghBAwBCyADKgIIIAKUQwrXIzyUIQQLIANBEGokACAEQwAAAACXQwAAAAAgBCAEWxsL2AICBH8BfSMAQSBrIgMkAAJAIAAoAgwiAQRAIAAgACoClAMgACoCmAMgAREnACIFIAVbDQEgA0GqHjYCACAAQQVB2CUgAxAsECQACyADQRBqIAAQMgJAIAMoAhAiAiADKAIUIgFyRQ0AAkADQCABIAIoAuwDIAIoAugDIgJrQQJ1SQRAIAIgAUECdGooAgAiASgC3AMNAyABLwAVIAEtABdBEHRyIgJBgOAAcUGAwABHBEAgAkEIdkEPcSICBH8gAgUgAC0AFUEEdgtBBUYEQCAALQAUQQhxDQQLIAEtAABBAnENAyAEIAEgBBshBAsgA0EQahAuIAMoAhQiASADKAIQIgJyDQEMAwsLEAIACyABIQQLIAMoAhgiAQRAA0AgASgCACECIAEQIyACIgENAAsLIARFBEAgACoCmAMhBQwBCyAEEE4gBCoCoAOSIQULIANBIGokACAFC6EDAQh/AkAgACgC6AMiBSAAKALsAyIHRwRAA0AgACAFKAIAIgIoAuQDRwRAAkAgACgC9AMoAgAiAQRAIAIgACAGIAERBgAiAQ0BC0GIBBAeIgEgAigCEDYCECABIAIpAgg3AgggASACKQIANwIAIAFBFGogAkEUakHoABArGiABQgA3AoABIAFB/ABqIgNBADsBACABQgA3AogBIAFCADcCkAEgAyACQfwAahCgASABQZgBaiACQZgBakHQAhArGiABQQA2AvADIAFCADcC6AMgAigC7AMiAyACKALoAyIERwRAIAMgBGsiBEEASA0FIAEgBBAeIgM2AuwDIAEgAzYC6AMgASADIARqN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AS8BABAfAkACQCADKgIIIgcgAioCACIGXARAIAcgB1sEQCACLQAEIQIMAgsgBiAGXCEECyACLQAEIQIgBEUNACADLQAMIAJB/wFxRg0BCyAFIAEgBiACEDkDQCAALQAAIgFBBHENASAAIAFBBHI6AAAgACgCECIBBEAgACABEQAACyAAQYCAgP4HNgKcASAAKALkAyIADQALCyADQRBqJAALDwAgASAAKAIAaiACOQMACw0AIAEgACgCAGorAwALCwAgAARAIAAQIwsLxwECBH8CfSMAQRBrIgIkACACQQhqIABB/ABqIgQgAEEeaiIFLwEAEB9BASEDAkACQCACKgIIIgcgASoCACIGXARAIAcgB1sEQCABLQAEIQEMAgsgBiAGXCEDCyABLQAEIQEgA0UNACACLQAMIAFB/wFxRg0BCyAEIAUgBiABEDkDQCAALQAAIgFBBHENASAAIAFBBHI6AAAgACgCECIBBEAgACABEQAACyAAQYCAgP4HNgKcASAAKALkAyIADQALCyACQRBqJAALlgMCA34CfyAAvSICQjSIp0H/D3EiBEH/D0YEQCAARAAAAAAAAPA/oiIAIACjDwsgAkIBhiIBQoCAgICAgIDw/wBYBEAgAEQAAAAAAAAAAKIgACABQoCAgICAgIDw/wBRGw8LAn4gBEUEQEEAIQQgAkIMhiIBQgBZBEADQCAEQQFrIQQgAUIBhiIBQgBZDQALCyACQQEgBGuthgwBCyACQv////////8Hg0KAgICAgICACIQLIQEgBEH/B0oEQANAAkAgAUKAgICAgICACH0iA0IAUw0AIAMiAUIAUg0AIABEAAAAAAAAAACiDwsgAUIBhiEBIARBAWsiBEH/B0oNAAtB/wchBAsCQCABQoCAgICAgIAIfSIDQgBTDQAgAyIBQgBSDQAgAEQAAAAAAAAAAKIPCyABQv////////8HWARAA0AgBEEBayEEIAFCgICAgICAgARUIQUgAUIBhiEBIAUNAAsLIAJCgICAgICAgICAf4MgAUKAgICAgICACH0gBK1CNIaEIAFBASAEa62IIARBAEobhL8LiwEBA38DQCAAQQR0IgFB5DJqIAFB4DJqIgI2AgAgAUHoMmogAjYCACAAQQ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4ApwDCyAJQRBqJAALcAIBfwF9IwBBEGsiBCQAIARBCGogACABQQJ0QewlaigCACACEDZDAADAfyEFAkACQAJAIAQtAAxBAWsOAgABAgsgBCoCCCEFDAELIAQqAgggA5RDCtcjPJQhBQsgBEEQaiQAIAVDAAAAACAFIAVbGwscACAAIAFBCCACpyACQiCIpyADpyADQiCIpxAVCwUAEFgACzkAIABFBEBBAA8LAn8gAUGAf3FBgL8DRiABQf8ATXJFBEBB/DtBGTYCAEF/DAELIAAgAToAAEEBCwvEAgACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCABQQlrDhIACgsMCgsCAwQFDAsMDAoLBwgJCyACIAIoAgAiAUEEajYCACAAIAEoAgA2AgAPCwALIAIgAigCACIBQQRqNgIAIAAgATIBADcDAA8LIAIgAigCACIBQQRqNgIAIAAgATMBADcDAA8LIAIgAigCACIBQQRqNgIAIAAgATAAADcDAA8LIAIgAigCACIBQQRqNgIAIAAgATEAADcDAA8LAAsgAiACKAIAQQdqQXhxIgFBCGo2AgAgACABKwMAOQMADwsgACACIAMRAQALDwsgAiACKAIAIgFBBGo2AgAgACABNAIANwMADwsgAiACKAIAIgFBBGo2AgAgACABNQIANwMADwsgAiACKAIAQQdqQXhxIgFBCGo2AgAgACABKQMANwMAC84BAgN/An0jAEEQayIDJABBASEEIANBCGogAEH8AGoiBSAAIAFBAXRqQegAaiIBLwEAEB8CQAJAIAMqAggiByACKgIAIgZcBEAgByAHWwRAIAItAAQhAgwCCyAGIAZcIQQLIAItAAQhAiAERQ0AIAMtAAwgAkH/AXFGDQELIAUgASAGIAIQOQNAIAAtAAAiAUEEcQ0BIAAgAUEEcjoAACAAKAIQIgEEQCAAIAERAAALIABBgICA/gc2ApwBIAAoAuQDIgANAAsLIANBEGokAAtdAQR/IAAoAgAhAgNAIAIsAAAiAxBXBEBBfyEEIAAgAkEBaiICNgIAIAFBzJmz5gBNBH9BfyADQTBrIgMgAUEKbCIEaiADIARB/////wdzShsFIAQLIQEMAQsLIAEL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AgAoAgQRAAALIAAoAgQhASAAQQA2AgQgAQRAIAEgASgCACgCBBEAAAsgBkEgaiQAIAAQIwsLtQEBAX8jAEEQayICJAACfyABBEAgASgCACEBQYgEEB4gARBcIAENARogAkH3GTYCACACEHIQJAALQZQ7LQAARQRAQfg6QQM2AgBBiDtCgICAgICAgMA/NwIAQYA7QgA3AgBBlDtBAToAAEH8OkH8Oi0AAEH+AXE6AABB9DpBADYCAEGQO0EANgIAC0GIBBAeQfQ6EFwLIQEgAEIANwIEIAAgATYCACABIAA2AgQgAkEQaiQAIAALGwEBfyAABEAgACgCACIBBEAgARAjCyAAECMLC0kBAn9BBBAeIQFBIBAeIgBBADYCHCAAQoCAgICAgIDAPzcCFCAAQgA3AgwgAEEAOgAIIABBAzYCBCAAQQA2AgAgASAANgIAIAELIAAgAkEFR0EAIAIbRQRAQbgwIAMgBBBJDwsgAyAEEHALIgEBfiABIAKtIAOtQiCGhCAEIAARFQAiBUIgiKckASAFpwuoAQEFfyAAKAJUIgMoAgAhBSADKAIEIgQgACgCFCAAKAIcIgdrIgYgBCAGSRsiBgRAIAUgByAGECsaIAMgAygCACAGaiIFNgIAIAMgAygCBCAGayIENgIECyAEIAIgAiAESxsiBARAIAUgASAEECsaIAMgAygCACAEaiIFNgIAIAMgAygCBCAEazYCBAsgBUEAOgAAIAAgACgCLCIBNgIcIAAgATYCFCACCwQAQgALBABBAAuKBQIGfgJ/IAEgASgCAEEHakF4cSIBQRBqNgIAIAAhCSABKQMAIQMgASkDCCEGIwBBIGsiCCQAAkAgBkL///////////8AgyIEQoCAgICAgMCAPH0gBEKAgICAgIDA/8MAfVQEQCAGQgSGIANCPIiEIQQgA0L//////////w+DIgNCgYCAgICAgIAIWgRAIARCgYCAgICAgIDAAHwhAgwCCyAEQoCAgICAgICAQH0hAiADQoCAgICAgICACFINASACIARCAYN8IQIMAQsgA1AgBEKAgICAgIDA//8AVCAEQoCAgICAgMD//wBRG0UEQCAGQgSGIANCPIiEQv////////8Dg0KAgICAgICA/P8AhCECDAELQoCAgICAgID4/wAhAiAEQv///////7//wwBWDQBCACECIARCMIinIgBBkfcASQ0AIAMhAiAGQv///////z+DQoCAgICAgMAAhCIFIQcCQCAAQYH3AGsiAUHAAHEEQCACIAFBQGqthiEHQgAhAgwBCyABRQ0AIAcgAa0iBIYgAkHAACABa62IhCEHIAIgBIYhAgsgCCACNwMQIAggBzcDGAJAQYH4ACAAayIAQcAAcQRAIAUgAEFAaq2IIQNCACEFDAELIABFDQAgBUHAACAAa62GIAMgAK0iAoiEIQMgBSACiCEFCyAIIAM3AwAgCCAFNwMIIAgpAwhCBIYgCCkDACIDQjyIhCECIAgpAxAgCCkDGIRCAFKtIANC//////////8Pg4QiA0KBgICAgICAgAhaBEAgAkIBfCECDAELIANCgICAgICAgIAIUg0AIAJCAYMgAnwhAgsgCEEgaiQAIAkgAiAGQoCAgICAgICAgH+DhL85AwALmRgDEn8BfAN+IwBBsARrIgwkACAMQQA2AiwCQCABvSIZQgBTBEBBASERQZkJIRMgAZoiAb0hGQwBCyAEQYAQcQRAQQEhEUGcCSETDAELQZ8JQZoJIARBAXEiERshEyARRSEVCwJAIBlCgICAgICAgPj/AINCgICAgICAgPj/AFEEQCAAQSAgAiARQQNqIgMgBEH//3txECkgACATIBEQJiAAQe0VQdweIAVBIHEiBRtB4RpB4B4gBRsgASABYhtBAxAmIABBICACIAMgBEGAwABzECkgAyACIAIgA0gbIQoMAQsgDEEQaiESAkACfwJAIAEgDEEsahCMASIBIAGgIgFEAAAAAAAAAABiBEAgDCAMKAIsIgZBAWs2AiwgBUEgciIOQeEARw0BDAMLIAVBIHIiDkHhAEYNAiAMKAIsIQlBBiADIANBAEgbDAELIAwgBkEdayIJNgIsIAFEAAAAAAAAsEGiIQFBBiADIANBAEgbCyELIAxBMGpBoAJBACAJQQBOG2oiDSEHA0AgBwJ/IAFEAAAAAAAA8EFjIAFEAAAAAAAAAABmcQRAIAGrDAELQQALIgM2AgAgB0EEaiEHIAEgA7ihRAAA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IAALNwEBfyABIAAoAgQiA0EBdWohASAAKAIAIQAgASACIANBAXEEfyABKAIAIABqKAIABSAACxEEAAs5AQF/IAEgACgCBCIEQQF1aiEBIAAoAgAhACABIAIgAyAEQQFxBH8gASgCACAAaigCAAUgAAsRCAALCQAgASAAEQIACwUAQcM7Cw8AIAEgACgCAGogAjYCAAsNACABIAAoAgBqKAIACxgBAX9BEBAeIgBCADcDCCAAQQA2AgAgAAsYAQF/QRAQHiIAQgA3AwAgAEIANwMIIAALDABBMBAeQQBBMBAqCzcBAX8gASAAKAIEIgNBAXVqIQEgACgCACEAIAEgAiADQQFxBH8gASgCACAAaigCAAUgAAsRHgALBQBBvjsLIQAgACABKAIAIAEgASwAC0EASBtBuzsgAigCABAQNgIACyoBAX9BDBAeIgFBADoABCABIAAoAgA2AgggAEEANgIAIAFB2Cc2AgAgAQsFAEG7OwsFAEG4OwshACAAIAEoAgAgASABLAALQQBIG0GkOyACKAIAEBA2AgAL2AEBBH8jAEEgayIDJAAgASgCACIEQfD///8HSQRAAkACQCAEQQtPBEAgBEEPckEBaiIFEB4hBiADIAVBgICAgHhyNgIQIAMgBjYCCCADIAQ2AgwgBCAGaiEFDAELIAMgBDoAEyADQQhqIgYgBGohBSAERQ0BCyAGIAFBBGogBBArGgsgBUEAOgAAIAMgAjYCACADQRhqIANBCGogAyAAEQMAIAMoAhgQHSADKAIYIgAQBiADKAIAEAYgAywAE0EASARAIAMoAggQIwsgA0EgaiQAIAAPCxACAAsqAQF/QQwQHiIBQQA6AAQgASAAKAIANgIIIABBADYCACABQeAmNgIAIAELBQBBpDsLaQECfyMAQRBrIgYkACABIAAoAgQiB0EBdWohASAAKAIAIQAgBiABIAIgAyAEIAUgB0EBcQR/IAEoAgAgAGooAgAFIAALERAAQRAQHiIAIAYpAwg3AwggACAGKQMANwMAIAZBEGokACAACwUAQaA7Cx0AIAAoAgAiACAALQAAQfcBcUEIQQAgARtyOgAAC6oBAgJ/AX0jAEEQayICJAAgACgCACEAIAFB/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ECAiCiAHIAUvAHoQICILWw0BIAogClsNACALIAtcDQELIAFBFGogBUEUakHoABArGiABQfwAaiAFQfwAahCgAQNAIAEtAAAiAEEEcQ0BIAEgAEEEcjoAACABKAIQIgAEQCABIAARAAALIAFBgICA/gc2ApwBIAEoAuQDIgENAAsLIAJBEGokAAvGAwEEfyMAQaAEayICJAAgACgCBCEBIABBADYCBCABBEAgASABKAIAKAIEEQAACyAAKAIIIQEgAEEANgIIIAEEQCABIAEoAgAoAgQRAAALAkAgACgCACIAKALoAyAAKALsA0YEQCAAKALkAw0BIAAgAkEYaiAAKAL0AxBcIgEpAgA3AgAgACABKAIQNgIQIAAgASkCCDcCCCAAQRRqIAFBFGpB6AAQKxogACABKQKMATcCjAEgACABKQKEATcChAEgACABKQJ8NwJ8IAEoApQBIQQgAUEANgKUASAAKAKUASEDIAAgBDYClAEgAwRAIAMQWwsgAEGYAWogAUGYAWpB0AIQKxogACgC6AMiAwRAIAAgAzYC7AMgAxAjCyAAIAEoAugDNgLoAyAAIAEoAuwDNgLsAyAAIAEoAvADNgLwAyABQQA2AvADIAFCADcC6AMgACABKQL8AzcC/AMgACABKQL0AzcC9AMgACABKAKEBDYChAQgASgClAEhACABQQA2ApQBIAAEQCAAEFsLIAJBoARqJAAPCyACQfAcNgIQIABBBUHYJSACQRBqECwQJAALIAJB5hE2AgAgAEEFQdglIAIQLBAkAAsLAEEMEB4gABCiAQsLAEEMEB5BABCiAQsNACAAKAIALQAIQQFxCwoAIAAoAgAoAhQLGQAgAUH/AXEEQBACAAsgACgCACgCEEEBcQsYACAAKAIAIgAgAC0ACEH+AXEgAXI6AAgLJgAgASAAKAIAIgAoAhRHBEAgACABNgIUIAAgACgCDEEBajYCDAsLkgEBAn8jAEEQayICJAAgACgCACEAIAFDAAAAAGAEQCABIAAqAhhcBEAgACABOAIYIAAgACgCDEEBajYCDAsgAkEQaiQADwsgAkGIFDYCACMAQRBrIgMkACADIAI2AgwCQCAARQRAQbgwQdglIAIQSRoMAQsg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gAAABoaGgBBgi4LDhoAAAAaGhoAAAAAAAAJAEGzLgsBFABBvy4LFRcAAAAAFwAAAAAJFAAAAAAAFAAAFABB7S4LARYAQfkuCycVAAAAABUAAAAACRYAAAAAABYAABYAADAxMjM0NTY3ODlBQkNERUYAQcQvCwHSAEHsLwsI//////////8AQbAwCwkQIgEAAAAAAAUAQcQwCwHNAEHcMAsKzgAAAM8AAAD8HQBB9DALAQIAQYQxCwj//////////wBByDELAQUAQdQxCwHQAEHsMQsOzgAAANEAAAAIHgAAAAQAQYQyCwEBAEGUMgsF/////woAQdgyCwHT";if(!ua(H)){var va=H;H=h.locateFile?h.locateFile(va,q):q+va}function wa(){var a=H;try{if(a==H&&w)return new Uint8Array(w);if(ua(a))try{var b=xa(a.slice(37)),c=new Uint8Array(b.length);for(a=0;a<b.length;++a)c[a]=b.charCodeAt(a);var d=c}catch(f){throw Error("Converting base64 string to bytes failed.")}else d=void 0;var e=d;if(e)return e;throw"both async and sync fetching of the wasm failed"}catch(f){x(f)}}function ya(){return w||typeof fetch!="function"?Promise.resolve().then(function(){return wa()}):fetch(H,{credentials:"same-origin"}).then(function(a){if(!a.ok)throw"failed to load wasm binary file at '"+H+"'";return a.arrayBuffer()}).catch(function(){return wa()})}function za(a){for(;0<a.length;)a.shift()(h)}function Aa(a){if(a===void 0)return"_unknown";a=a.replace(/[^a-zA-Z0-9_]/g,"$");var b=a.charCodeAt(0);return 48<=b&&57>=b?"_"+a:a}function Ba(a,b){return a=Aa(a),function(){return b.apply(this,arguments)}}var J=[{},{value:void 0},{value:null},{value:!0},{value:!1}],Ca=[];function Da(a){var b=Error,c=Ba(a,function(d){this.name=a,this.message=d,d=Error(d).stack,d!==void 0&&(this.stack=this.toString()+`
1277
- `+d.replace(/^Error(:[^\n]*)?\n/,""))});return c.prototype=Object.create(b.prototype),c.prototype.constructor=c,c.prototype.toString=function(){return this.message===void 0?this.name:this.name+": "+this.message},c}var K=void 0;function L(a){throw new K(a)}var M=(a)=>(a||L("Cannot use deleted val. handle = "+a),J[a].value),Ea=(a)=>{switch(a){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:var b=Ca.length?Ca.pop():J.length;return J[b]={ga:1,value:a},b}},Fa=void 0,Ga=void 0;function N(a){for(var b="";A[a];)b+=Ga[A[a++]];return b}var O=[];function Ha(){for(;O.length;){var a=O.pop();a.M.$=!1,a.delete()}}var P=void 0,Q={};function Ia(a,b){for(b===void 0&&L("ptr should not be undefined");a.R;)b=a.ba(b),a=a.R;return b}var R={};function Ja(a){a=Ka(a);var b=N(a);return S(a),b}function La(a,b){var c=R[a];return c===void 0&&L(b+" has unknown type "+Ja(a)),c}function Ma(){}var Na=!1;function Oa(a){--a.count.value,a.count.value===0&&(a.T?a.U.W(a.T):a.P.N.W(a.O))}function Pa(a,b,c){if(b===c)return a;if(c.R===void 0)return null;return a=Pa(a,b,c.R),a===null?null:c.na(a)}var Qa={};function Ra(a,b){return b=Ia(a,b),Q[b]}var Sa=void 0;function Ta(a){throw new Sa(a)}function Ua(a,b){return b.P&&b.O||Ta("makeClassHandle requires ptr and ptrType"),!!b.U!==!!b.T&&Ta("Both smartPtrType and smartPtr must be specified"),b.count={value:1},T(Object.create(a,{M:{value:b}}))}function T(a){if(typeof FinalizationRegistry>"u")return T=(b)=>b,a;return Na=new FinalizationRegistry((b)=>{Oa(b.M)}),T=(b)=>{var c=b.M;return c.T&&Na.register(b,{M:c},b),b},Ma=(b)=>{Na.unregister(b)},T(a)}var Va={};function Wa(a){for(;a.length;){var b=a.pop();a.pop()(b)}}function Xa(a){return this.fromWireType(D[a>>2])}var U={},Ya={};function V(a,b,c){function d(k){k=c(k),k.length!==a.length&&Ta("Mismatched type converter count");for(var m=0;m<a.length;++m)W(a[m],k[m])}a.forEach(function(k){Ya[k]=b});var e=Array(b.length),f=[],g=0;b.forEach((k,m)=>{R.hasOwnProperty(k)?e[m]=R[k]:(f.push(k),U.hasOwnProperty(k)||(U[k]=[]),U[k].push(()=>{e[m]=R[k],++g,g===f.length&&d(e)}))}),f.length===0&&d(e)}function Za(a){switch(a){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw TypeError("Unknown type size: "+a)}}function W(a,b,c={}){if(!("argPackAdvance"in b))throw TypeError("registerType registeredInstance requires argPackAdvance");var d=b.name;if(a||L('type "'+d+'" must have a positive integer typeid pointer'),R.hasOwnProperty(a)){if(c.ua)return;L("Cannot register type '"+d+"' twice")}R[a]=b,delete Ya[a],U.hasOwnProperty(a)&&(b=U[a],delete U[a],b.forEach((e)=>e()))}function $a(a){L(a.M.P.N.name+" instance already deleted")}function X(){}function ab(a,b,c){if(a[b].S===void 0){var d=a[b];a[b]=function(){return a[b].S.hasOwnProperty(arguments.length)||L("Function '"+c+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+a[b].S+")!"),a[b].S[arguments.length].apply(this,arguments)},a[b].S=[],a[b].S[d.Z]=d}}function bb(a,b){h.hasOwnProperty(a)?(L("Cannot register public name '"+a+"' twice"),ab(h,a,a),h.hasOwnProperty(void 0)&&L("Cannot register multiple overloads of a function with the same number of arguments (undefined)!"),h[a].S[void 0]=b):h[a]=b}function cb(a,b,c,d,e,f,g,k){this.name=a,this.constructor=b,this.X=c,this.W=d,this.R=e,this.pa=f,this.ba=g,this.na=k,this.ja=[]}function db(a,b,c){for(;b!==c;)b.ba||L("Expected null or instance of "+c.name+", got an instance of "+b.name),a=b.ba(a),b=b.R;return a}function eb(a,b){if(b===null)return this.ea&&L("null is not a valid "+this.name),0;return b.M||L('Cannot pass "'+fb(b)+'" as a '+this.name),b.M.O||L("Cannot pass deleted object as a pointer of type "+this.name),db(b.M.O,b.M.P.N,this.N)}function gb(a,b){if(b===null){if(this.ea&&L("null is not a valid "+this.name),this.da){var c=this.fa();return a!==null&&a.push(this.W,c),c}return 0}if(b.M||L('Cannot pass "'+fb(b)+'" as a '+this.name),b.M.O||L("Cannot pass deleted object as a pointer of type "+this.name),!this.ca&&b.M.P.ca&&L("Cannot convert argument of type "+(b.M.U?b.M.U.name:b.M.P.name)+" to parameter type "+this.name),c=db(b.M.O,b.M.P.N,this.N),this.da)switch(b.M.T===void 0&&L("Passing raw pointer to smart pointer is illegal"),this.Ba){case 0:b.M.U===this?c=b.M.T:L("Cannot convert argument of type "+(b.M.U?b.M.U.name:b.M.P.name)+" to parameter type "+this.name);break;case 1:c=b.M.T;break;case 2:if(b.M.U===this)c=b.M.T;else{var d=b.clone();c=this.xa(c,Ea(function(){d.delete()})),a!==null&&a.push(this.W,c)}break;default:L("Unsupporting sharing policy")}return c}function hb(a,b){if(b===null)return this.ea&&L("null is not a valid "+this.name),0;return b.M||L('Cannot pass "'+fb(b)+'" as a '+this.name),b.M.O||L("Cannot pass deleted object as a pointer of type "+this.name),b.M.P.ca&&L("Cannot convert argument of type "+b.M.P.name+" to parameter type "+this.name),db(b.M.O,b.M.P.N,this.N)}function Y(a,b,c,d){this.name=a,this.N=b,this.ea=c,this.ca=d,this.da=!1,this.W=this.xa=this.fa=this.ka=this.Ba=this.wa=void 0,b.R!==void 0?this.toWireType=gb:(this.toWireType=d?eb:hb,this.V=null)}function ib(a,b){h.hasOwnProperty(a)||Ta("Replacing nonexistant public symbol"),h[a]=b,h[a].Z=void 0}function jb(a,b){var c=[];return function(){if(c.length=0,Object.assign(c,arguments),a.includes("j")){var d=h["dynCall_"+a];d=c&&c.length?d.apply(null,[b].concat(c)):d.call(null,b)}else d=oa.get(b).apply(null,c);return d}}function Z(a,b){a=N(a);var c=a.includes("j")?jb(a,b):oa.get(b);return typeof c!="function"&&L("unknown function pointer with signature "+a+": "+b),c}var mb=void 0;function nb(a,b){function c(f){e[f]||R[f]||(Ya[f]?Ya[f].forEach(c):(d.push(f),e[f]=!0))}var d=[],e={};throw b.forEach(c),new mb(a+": "+d.map(Ja).join([", "]))}function ob(a,b,c,d,e){var f=b.length;2>f&&L("argTypes array size mismatch! Must at least get return value and 'this' types!");var g=b[1]!==null&&c!==null,k=!1;for(c=1;c<b.length;++c)if(b[c]!==null&&b[c].V===void 0){k=!0;break}var m=b[0].name!=="void",l=f-2,n=Array(l),p=[],r=[];return function(){if(arguments.length!==l&&L("function "+a+" called with "+arguments.length+" arguments, expected "+l+" args!"),r.length=0,p.length=g?2:1,p[0]=e,g){var u=b[1].toWireType(r,this);p[1]=u}for(var t=0;t<l;++t)n[t]=b[t+2].toWireType(r,arguments[t]),p.push(n[t]);if(t=d.apply(null,p),k)Wa(r);else for(var y=g?1:2;y<b.length;y++){var B=y===1?u:n[y-2];b[y].V!==null&&b[y].V(B)}return u=m?b[0].fromWireType(t):void 0,u}}function pb(a,b){for(var c=[],d=0;d<a;d++)c.push(E[b+4*d>>2]);return c}function qb(a){4<a&&--J[a].ga===0&&(J[a]=void 0,Ca.push(a))}function fb(a){if(a===null)return"null";var b=typeof a;return b==="object"||b==="array"||b==="function"?a.toString():""+a}function rb(a,b){switch(b){case 2:return function(c){return this.fromWireType(la[c>>2])};case 3:return function(c){return this.fromWireType(ma[c>>3])};default:throw TypeError("Unknown float type: "+a)}}function sb(a,b,c){switch(b){case 0:return c?function(d){return ja[d]}:function(d){return A[d]};case 1:return c?function(d){return C[d>>1]}:function(d){return ka[d>>1]};case 2:return c?function(d){return D[d>>2]}:function(d){return E[d>>2]};default:throw TypeError("Unknown integer type: "+a)}}function tb(a,b){for(var c="",d=0;!(d>=b/2);++d){var e=C[a+2*d>>1];if(e==0)break;c+=String.fromCharCode(e)}return c}function ub(a,b,c){if(c===void 0&&(c=2147483647),2>c)return 0;c-=2;var d=b;c=c<2*a.length?c/2:a.length;for(var e=0;e<c;++e)C[b>>1]=a.charCodeAt(e),b+=2;return C[b>>1]=0,b-d}function vb(a){return 2*a.length}function wb(a,b){for(var c=0,d="";!(c>=b/4);){var e=D[a+4*c>>2];if(e==0)break;++c,65536<=e?(e-=65536,d+=String.fromCharCode(55296|e>>10,56320|e&1023)):d+=String.fromCharCode(e)}return d}function xb(a,b,c){if(c===void 0&&(c=2147483647),4>c)return 0;var d=b;c=d+c-4;for(var e=0;e<a.length;++e){var f=a.charCodeAt(e);if(55296<=f&&57343>=f){var g=a.charCodeAt(++e);f=65536+((f&1023)<<10)|g&1023}if(D[b>>2]=f,b+=4,b+4>c)break}return D[b>>2]=0,b-d}function yb(a){for(var b=0,c=0;c<a.length;++c){var d=a.charCodeAt(c);55296<=d&&57343>=d&&++c,b+=4}return b}var zb={};function Ab(a){var b=zb[a];return b===void 0?N(a):b}var Bb=[];function Cb(a){var b=Bb.length;return Bb.push(a),b}function Db(a,b){for(var c=Array(a),d=0;d<a;++d)c[d]=La(E[b+4*d>>2],"parameter "+d);return c}var Eb=[],Fb=[null,[],[]];K=h.BindingError=Da("BindingError"),h.count_emval_handles=function(){for(var a=0,b=5;b<J.length;++b)J[b]!==void 0&&++a;return a},h.get_first_emval=function(){for(var a=5;a<J.length;++a)if(J[a]!==void 0)return J[a];return null},Fa=h.PureVirtualError=Da("PureVirtualError");for(var Gb=Array(256),Hb=0;256>Hb;++Hb)Gb[Hb]=String.fromCharCode(Hb);Ga=Gb,h.getInheritedInstanceCount=function(){return Object.keys(Q).length},h.getLiveInheritedInstances=function(){var a=[],b;for(b in Q)Q.hasOwnProperty(b)&&a.push(Q[b]);return a},h.flushPendingDeletes=Ha,h.setDelayFunction=function(a){P=a,O.length&&P&&P(Ha)},Sa=h.InternalError=Da("InternalError"),X.prototype.isAliasOf=function(a){if(!(this instanceof X&&a instanceof X))return!1;var b=this.M.P.N,c=this.M.O,d=a.M.P.N;for(a=a.M.O;b.R;)c=b.ba(c),b=b.R;for(;d.R;)a=d.ba(a),d=d.R;return b===d&&c===a},X.prototype.clone=function(){if(this.M.O||$a(this),this.M.aa)return this.M.count.value+=1,this;var a=T,b=Object,c=b.create,d=Object.getPrototypeOf(this),e=this.M;return a=a(c.call(b,d,{M:{value:{count:e.count,$:e.$,aa:e.aa,O:e.O,P:e.P,T:e.T,U:e.U}}})),a.M.count.value+=1,a.M.$=!1,a},X.prototype.delete=function(){this.M.O||$a(this),this.M.$&&!this.M.aa&&L("Object already scheduled for deletion"),Ma(this),Oa(this.M),this.M.aa||(this.M.T=void 0,this.M.O=void 0)},X.prototype.isDeleted=function(){return!this.M.O},X.prototype.deleteLater=function(){return this.M.O||$a(this),this.M.$&&!this.M.aa&&L("Object already scheduled for deletion"),O.push(this),O.length===1&&P&&P(Ha),this.M.$=!0,this},Y.prototype.qa=function(a){return this.ka&&(a=this.ka(a)),a},Y.prototype.ha=function(a){this.W&&this.W(a)},Y.prototype.argPackAdvance=8,Y.prototype.readValueFromPointer=Xa,Y.prototype.deleteObject=function(a){if(a!==null)a.delete()},Y.prototype.fromWireType=function(a){function b(){return this.da?Ua(this.N.X,{P:this.wa,O:c,U:this,T:a}):Ua(this.N.X,{P:this,O:a})}var c=this.qa(a);if(!c)return this.ha(a),null;var d=Ra(this.N,c);if(d!==void 0){if(d.M.count.value===0)return d.M.O=c,d.M.T=a,d.clone();return d=d.clone(),this.ha(a),d}if(d=this.N.pa(c),d=Qa[d],!d)return b.call(this);d=this.ca?d.la:d.pointerType;var e=Pa(c,this.N,d.N);return e===null?b.call(this):this.da?Ua(d.N.X,{P:d,O:e,U:this,T:a}):Ua(d.N.X,{P:d,O:e})},mb=h.UnboundTypeError=Da("UnboundTypeError");var xa=typeof atob=="function"?atob:function(a){var b="",c=0;a=a.replace(/[^A-Za-z0-9\+\/=]/g,"");do{var d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c++)),e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c++)),f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c++)),g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a.charAt(c++));d=d<<2|e>>4,e=(e&15)<<4|f>>2;var k=(f&3)<<6|g;b+=String.fromCharCode(d),f!==64&&(b+=String.fromCharCode(e)),g!==64&&(b+=String.fromCharCode(k))}while(c<a.length);return b},Jb={l:function(a,b,c,d){x("Assertion failed: "+(a?z(A,a):"")+", at: "+[b?b?z(A,b):"":"unknown filename",c,d?d?z(A,d):"":"unknown function"])},q:function(a,b,c){a=N(a),b=La(b,"wrapper"),c=M(c);var d=[].slice,e=b.N,f=e.X,g=e.R.X,k=e.R.constructor;a=Ba(a,function(){e.R.ja.forEach(function(l){if(this[l]===g[l])throw new Fa("Pure virtual function "+l+" must be implemented in JavaScript")}.bind(this)),Object.defineProperty(this,"__parent",{value:f}),this.__construct.apply(this,d.call(arguments))}),f.__construct=function(){this===f&&L("Pass correct 'this' to __construct");var l=k.implement.apply(void 0,[this].concat(d.call(arguments)));Ma(l);var n=l.M;l.notifyOnDestruction(),n.aa=!0,Object.defineProperties(this,{M:{value:n}}),T(this),l=n.O,l=Ia(e,l),Q.hasOwnProperty(l)?L("Tried to register registered instance: "+l):Q[l]=this},f.__destruct=function(){this===f&&L("Pass correct 'this' to __destruct"),Ma(this);var l=this.M.O;l=Ia(e,l),Q.hasOwnProperty(l)?delete Q[l]:L("Tried to unregister unregistered instance: "+l)},a.prototype=Object.create(f);for(var m in c)a.prototype[m]=c[m];return Ea(a)},j:function(a){var b=Va[a];delete Va[a];var{fa:c,W:d,ia:e}=b,f=e.map((g)=>g.ta).concat(e.map((g)=>g.za));V([a],f,(g)=>{var k={};return e.forEach((m,l)=>{var n=g[l],{ra:p,sa:r}=m,u=g[l+e.length],{ya:t,Aa:y}=m;k[m.oa]={read:(B)=>n.fromWireType(p(r,B)),write:(B,ba)=>{var I=[];t(y,B,u.toWireType(I,ba)),Wa(I)}}}),[{name:b.name,fromWireType:function(m){var l={},n;for(n in k)l[n]=k[n].read(m);return d(m),l},toWireType:function(m,l){for(var n in k)if(!(n in l))throw TypeError('Missing field: "'+n+'"');var p=c();for(n in k)k[n].write(p,l[n]);return m!==null&&m.push(d,p),p},argPackAdvance:8,readValueFromPointer:Xa,V:d}]})},v:function(){},B:function(a,b,c,d,e){var f=Za(c);b=N(b),W(a,{name:b,fromWireType:function(g){return!!g},toWireType:function(g,k){return k?d:e},argPackAdvance:8,readValueFromPointer:function(g){if(c===1)var k=ja;else if(c===2)k=C;else if(c===4)k=D;else throw TypeError("Unknown boolean type size: "+b);return this.fromWireType(k[g>>f])},V:null})},f:function(a,b,c,d,e,f,g,k,m,l,n,p,r){n=N(n),f=Z(e,f),k&&(k=Z(g,k)),l&&(l=Z(m,l)),r=Z(p,r);var u=Aa(n);bb(u,function(){nb("Cannot construct "+n+" due to unbound types",[d])}),V([a,b,c],d?[d]:[],function(t){if(t=t[0],d)var y=t.N,B=y.X;else B=X.prototype;t=Ba(u,function(){if(Object.getPrototypeOf(this)!==ba)throw new K("Use 'new' to construct "+n);if(I.Y===void 0)throw new K(n+" has no accessible constructor");var kb=I.Y[arguments.length];if(kb===void 0)throw new K("Tried to invoke ctor of "+n+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(I.Y).toString()+") parameters instead!");return kb.apply(this,arguments)});var ba=Object.create(B,{constructor:{value:t}});t.prototype=ba;var I=new cb(n,t,ba,r,y,f,k,l);y=new Y(n,I,!0,!1),B=new Y(n+"*",I,!1,!1);var lb=new Y(n+" const*",I,!1,!0);return Qa[a]={pointerType:B,la:lb},ib(u,t),[y,B,lb]})},d:function(a,b,c,d,e,f,g){var k=pb(c,d);b=N(b),f=Z(e,f),V([],[a],function(m){function l(){nb("Cannot call "+n+" due to unbound types",k)}m=m[0];var n=m.name+"."+b;b.startsWith("@@")&&(b=Symbol[b.substring(2)]);var p=m.N.constructor;return p[b]===void 0?(l.Z=c-1,p[b]=l):(ab(p,b,n),p[b].S[c-1]=l),V([],k,function(r){return r=ob(n,[r[0],null].concat(r.slice(1)),null,f,g),p[b].S===void 0?(r.Z=c-1,p[b]=r):p[b].S[c-1]=r,[]}),[]})},p:function(a,b,c,d,e,f){0<b||x();var g=pb(b,c);e=Z(d,e),V([],[a],function(k){k=k[0];var m="constructor "+k.name;if(k.N.Y===void 0&&(k.N.Y=[]),k.N.Y[b-1]!==void 0)throw new K("Cannot register multiple constructors with identical number of parameters ("+(b-1)+") for class '"+k.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return k.N.Y[b-1]=()=>{nb("Cannot construct "+k.name+" due to unbound types",g)},V([],g,function(l){return l.splice(1,0,null),k.N.Y[b-1]=ob(m,l,null,e,f),[]}),[]})},a:function(a,b,c,d,e,f,g,k){var m=pb(c,d);b=N(b),f=Z(e,f),V([],[a],function(l){function n(){nb("Cannot call "+p+" due to unbound types",m)}l=l[0];var p=l.name+"."+b;b.startsWith("@@")&&(b=Symbol[b.substring(2)]),k&&l.N.ja.push(b);var r=l.N.X,u=r[b];return u===void 0||u.S===void 0&&u.className!==l.name&&u.Z===c-2?(n.Z=c-2,n.className=l.name,r[b]=n):(ab(r,b,p),r[b].S[c-2]=n),V([],m,function(t){return t=ob(p,t,l,f,g),r[b].S===void 0?(t.Z=c-2,r[b]=t):r[b].S[c-2]=t,[]}),[]})},A:function(a,b){b=N(b),W(a,{name:b,fromWireType:function(c){var d=M(c);return qb(c),d},toWireType:function(c,d){return Ea(d)},argPackAdvance:8,readValueFromPointer:Xa,V:null})},n:function(a,b,c){c=Za(c),b=N(b),W(a,{name:b,fromWireType:function(d){return d},toWireType:function(d,e){return e},argPackAdvance:8,readValueFromPointer:rb(b,c),V:null})},e:function(a,b,c,d,e){b=N(b),e===-1&&(e=4294967295),e=Za(c);var f=(k)=>k;if(d===0){var g=32-8*c;f=(k)=>k<<g>>>g}c=b.includes("unsigned")?function(k,m){return m>>>0}:function(k,m){return m},W(a,{name:b,fromWireType:f,toWireType:c,argPackAdvance:8,readValueFromPointer:sb(b,e,d!==0),V:null})},b:function(a,b,c){function d(f){f>>=2;var g=E;return new e(ia,g[f+1],g[f])}var e=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][b];c=N(c),W(a,{name:c,fromWireType:d,argPackAdvance:8,readValueFromPointer:d},{ua:!0})},o:function(a,b){b=N(b);var c=b==="std::string";W(a,{name:b,fromWireType:function(d){var e=E[d>>2],f=d+4;if(c)for(var g=f,k=0;k<=e;++k){var m=f+k;if(k==e||A[m]==0){if(g=g?z(A,g,m-g):"",l===void 0)var l=g;else l+=String.fromCharCode(0),l+=g;g=m+1}}else{l=Array(e);for(k=0;k<e;++k)l[k]=String.fromCharCode(A[f+k]);l=l.join("")}return S(d),l},toWireType:function(d,e){e instanceof ArrayBuffer&&(e=new Uint8Array(e));var f,g=typeof e=="string";if(g||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int8Array||L("Cannot pass non-string to std::string"),c&&g){var k=0;for(f=0;f<e.length;++f){var m=e.charCodeAt(f);127>=m?k++:2047>=m?k+=2:55296<=m&&57343>=m?(k+=4,++f):k+=3}f=k}else f=e.length;if(k=Ib(4+f+1),m=k+4,E[k>>2]=f,c&&g){if(g=m,m=f+1,f=A,0<m){m=g+m-1;for(var l=0;l<e.length;++l){var n=e.charCodeAt(l);if(55296<=n&&57343>=n){var p=e.charCodeAt(++l);n=65536+((n&1023)<<10)|p&1023}if(127>=n){if(g>=m)break;f[g++]=n}else{if(2047>=n){if(g+1>=m)break;f[g++]=192|n>>6}else{if(65535>=n){if(g+2>=m)break;f[g++]=224|n>>12}else{if(g+3>=m)break;f[g++]=240|n>>18,f[g++]=128|n>>12&63}f[g++]=128|n>>6&63}f[g++]=128|n&63}}f[g]=0}}else if(g)for(g=0;g<f;++g)l=e.charCodeAt(g),255<l&&(S(m),L("String has UTF-16 code units that do not fit in 8 bits")),A[m+g]=l;else for(g=0;g<f;++g)A[m+g]=e[g];return d!==null&&d.push(S,k),k},argPackAdvance:8,readValueFromPointer:Xa,V:function(d){S(d)}})},i:function(a,b,c){if(c=N(c),b===2)var d=tb,e=ub,f=vb,g=()=>ka,k=1;else b===4&&(d=wb,e=xb,f=yb,g=()=>E,k=2);W(a,{name:c,fromWireType:function(m){for(var l=E[m>>2],n=g(),p,r=m+4,u=0;u<=l;++u){var t=m+4+u*b;if(u==l||n[t>>k]==0)r=d(r,t-r),p===void 0?p=r:(p+=String.fromCharCode(0),p+=r),r=t+b}return S(m),p},toWireType:function(m,l){typeof l!="string"&&L("Cannot pass non-string to C++ string type "+c);var n=f(l),p=Ib(4+n+b);return E[p>>2]=n>>k,e(l,p+4,n+b),m!==null&&m.push(S,p),p},argPackAdvance:8,readValueFromPointer:Xa,V:function(m){S(m)}})},k:function(a,b,c,d,e,f){Va[a]={name:N(b),fa:Z(c,d),W:Z(e,f),ia:[]}},h:function(a,b,c,d,e,f,g,k,m,l){Va[a].ia.push({oa:N(b),ta:c,ra:Z(d,e),sa:f,za:g,ya:Z(k,m),Aa:l})},C:function(a,b){b=N(b),W(a,{va:!0,name:b,argPackAdvance:0,fromWireType:function(){},toWireType:function(){}})},s:function(a,b,c,d,e){a=Bb[a],b=M(b),c=Ab(c);var f=[];return E[d>>2]=Ea(f),a(b,c,f,e)},t:function(a,b,c,d){a=Bb[a],b=M(b),c=Ab(c),a(b,c,null,d)},g:qb,m:function(a,b){var c=Db(a,b),d=c[0];b=d.name+"_$"+c.slice(1).map(function(g){return g.name}).join("_")+"$";var e=Eb[b];if(e!==void 0)return e;var f=Array(a-1);return e=Cb((g,k,m,l)=>{for(var n=0,p=0;p<a-1;++p)f[p]=c[p+1].readValueFromPointer(l+n),n+=c[p+1].argPackAdvance;g=g[k].apply(g,f);for(p=0;p<a-1;++p)c[p+1].ma&&c[p+1].ma(f[p]);if(!d.va)return d.toWireType(m,g)}),Eb[b]=e},D:function(a){4<a&&(J[a].ga+=1)},r:function(a){var b=M(a);Wa(b),qb(a)},c:function(){x("")},x:function(a,b,c){A.copyWithin(a,b,b+c)},w:function(a){var b=A.length;if(a>>>=0,2147483648<a)return!1;for(var c=1;4>=c;c*=2){var d=b*(1+0.2/c);d=Math.min(d,a+100663296);var e=Math;d=Math.max(a,d),e=e.min.call(e,2147483648,d+(65536-d%65536)%65536);a:{try{fa.grow(e-ia.byteLength+65535>>>16),na();var f=1;break a}catch(g){}f=void 0}if(f)return!0}return!1},z:function(){return 52},u:function(){return 70},y:function(a,b,c,d){for(var e=0,f=0;f<c;f++){var g=E[b>>2],k=E[b+4>>2];b+=8;for(var m=0;m<k;m++){var l=A[g+m],n=Fb[a];l===0||l===10?((a===1?ea:v)(z(n,0)),n.length=0):n.push(l)}e+=k}return E[d>>2]=e,0}};(function(){function a(e){h.asm=e.exports,fa=h.asm.E,na(),oa=h.asm.J,qa.unshift(h.asm.F),F--,h.monitorRunDependencies&&h.monitorRunDependencies(F),F==0&&(ta!==null&&(clearInterval(ta),ta=null),G&&(e=G,G=null,e()))}function b(e){a(e.instance)}function c(e){return ya().then(function(f){return WebAssembly.instantiate(f,d)}).then(function(f){return f}).then(e,function(f){v("failed to asynchronously prepare wasm: "+f),x(f)})}var d={a:Jb};if(F++,h.monitorRunDependencies&&h.monitorRunDependencies(F),h.instantiateWasm)try{return h.instantiateWasm(d,a)}catch(e){v("Module.instantiateWasm callback failed with error: "+e),ca(e)}return function(){return w||typeof WebAssembly.instantiateStreaming!="function"||ua(H)||typeof fetch!="function"?c(b):fetch(H,{credentials:"same-origin"}).then(function(e){return WebAssembly.instantiateStreaming(e,d).then(b,function(f){return v("wasm streaming compile failed: "+f),v("falling back to ArrayBuffer instantiation"),c(b)})})}().catch(ca),{}})(),h.___wasm_call_ctors=function(){return(h.___wasm_call_ctors=h.asm.F).apply(null,arguments)};var Ka=h.___getTypeName=function(){return(Ka=h.___getTypeName=h.asm.G).apply(null,arguments)};h.__embind_initialize_bindings=function(){return(h.__embind_initialize_bindings=h.asm.H).apply(null,arguments)};var Ib=h._malloc=function(){return(Ib=h._malloc=h.asm.I).apply(null,arguments)},S=h._free=function(){return(S=h._free=h.asm.K).apply(null,arguments)};h.dynCall_jiji=function(){return(h.dynCall_jiji=h.asm.L).apply(null,arguments)};var Kb;G=function Lb(){Kb||Mb(),Kb||(G=Lb)};function Mb(){function a(){if(!Kb&&(Kb=!0,h.calledRun=!0,!ha)){if(za(qa),aa(h),h.onRuntimeInitialized)h.onRuntimeInitialized();if(h.postRun)for(typeof h.postRun=="function"&&(h.postRun=[h.postRun]);h.postRun.length;){var b=h.postRun.shift();ra.unshift(b)}za(ra)}}if(!(0<F)){if(h.preRun)for(typeof h.preRun=="function"&&(h.preRun=[h.preRun]);h.preRun.length;)sa();za(pa),0<F||(h.setStatus?(h.setStatus("Running..."),setTimeout(function(){setTimeout(function(){h.setStatus("")},1),a()},1)):a())}}if(h.preInit)for(typeof h.preInit=="function"&&(h.preInit=[h.preInit]);0<h.preInit.length;)h.preInit.pop()();return Mb(),loadYoga.ready}})(),yoga_wasm_base64_esm_default=loadYoga});var Align,BoxSizing,Dimension,Direction,Display,Edge,Errata,ExperimentalFeature,FlexDirection,Gutter,Justify,LogLevel,MeasureMode,NodeType,Overflow,PositionType,Unit,Wrap,constants3,YGEnums_default;var init_YGEnums=__esm(()=>{Align=function(Align){return Align[Align.Auto=0]="Auto",Align[Align.FlexStart=1]="FlexStart",Align[Align.Center=2]="Center",Align[Align.FlexEnd=3]="FlexEnd",Align[Align.Stretch=4]="Stretch",Align[Align.Baseline=5]="Baseline",Align[Align.SpaceBetween=6]="SpaceBetween",Align[Align.SpaceAround=7]="SpaceAround",Align[Align.SpaceEvenly=8]="SpaceEvenly",Align}({}),BoxSizing=function(BoxSizing){return BoxSizing[BoxSizing.BorderBox=0]="BorderBox",BoxSizing[BoxSizing.ContentBox=1]="ContentBox",BoxSizing}({}),Dimension=function(Dimension){return Dimension[Dimension.Width=0]="Width",Dimension[Dimension.Height=1]="Height",Dimension}({}),Direction=function(Direction){return Direction[Direction.Inherit=0]="Inherit",Direction[Direction.LTR=1]="LTR",Direction[Direction.RTL=2]="RTL",Direction}({}),Display=function(Display){return Display[Display.Flex=0]="Flex",Display[Display.None=1]="None",Display[Display.Contents=2]="Contents",Display}({}),Edge=function(Edge){return Edge[Edge.Left=0]="Left",Edge[Edge.Top=1]="Top",Edge[Edge.Right=2]="Right",Edge[Edge.Bottom=3]="Bottom",Edge[Edge.Start=4]="Start",Edge[Edge.End=5]="End",Edge[Edge.Horizontal=6]="Horizontal",Edge[Edge.Vertical=7]="Vertical",Edge[Edge.All=8]="All",Edge}({}),Errata=function(Errata){return Errata[Errata.None=0]="None",Errata[Errata.StretchFlexBasis=1]="StretchFlexBasis",Errata[Errata.AbsolutePositionWithoutInsetsExcludesPadding=2]="AbsolutePositionWithoutInsetsExcludesPadding",Errata[Errata.AbsolutePercentAgainstInnerSize=4]="AbsolutePercentAgainstInnerSize",Errata[Errata.All=2147483647]="All",Errata[Errata.Classic=2147483646]="Classic",Errata}({}),ExperimentalFeature=function(ExperimentalFeature){return ExperimentalFeature[ExperimentalFeature.WebFlexBasis=0]="WebFlexBasis",ExperimentalFeature}({}),FlexDirection=function(FlexDirection){return FlexDirection[FlexDirection.Column=0]="Column",FlexDirection[FlexDirection.ColumnReverse=1]="ColumnReverse",FlexDirection[FlexDirection.Row=2]="Row",FlexDirection[FlexDirection.RowReverse=3]="RowReverse",FlexDirection}({}),Gutter=function(Gutter){return Gutter[Gutter.Column=0]="Column",Gutter[Gutter.Row=1]="Row",Gutter[Gutter.All=2]="All",Gutter}({}),Justify=function(Justify){return Justify[Justify.FlexStart=0]="FlexStart",Justify[Justify.Center=1]="Center",Justify[Justify.FlexEnd=2]="FlexEnd",Justify[Justify.SpaceBetween=3]="SpaceBetween",Justify[Justify.SpaceAround=4]="SpaceAround",Justify[Justify.SpaceEvenly=5]="SpaceEvenly",Justify}({}),LogLevel=function(LogLevel){return LogLevel[LogLevel.Error=0]="Error",LogLevel[LogLevel.Warn=1]="Warn",LogLevel[LogLevel.Info=2]="Info",LogLevel[LogLevel.Debug=3]="Debug",LogLevel[LogLevel.Verbose=4]="Verbose",LogLevel[LogLevel.Fatal=5]="Fatal",LogLevel}({}),MeasureMode=function(MeasureMode){return MeasureMode[MeasureMode.Undefined=0]="Undefined",MeasureMode[MeasureMode.Exactly=1]="Exactly",MeasureMode[MeasureMode.AtMost=2]="AtMost",MeasureMode}({}),NodeType=function(NodeType){return NodeType[NodeType.Default=0]="Default",NodeType[NodeType.Text=1]="Text",NodeType}({}),Overflow=function(Overflow){return Overflow[Overflow.Visible=0]="Visible",Overflow[Overflow.Hidden=1]="Hidden",Overflow[Overflow.Scroll=2]="Scroll",Overflow}({}),PositionType=function(PositionType){return PositionType[PositionType.Static=0]="Static",PositionType[PositionType.Relative=1]="Relative",PositionType[PositionType.Absolute=2]="Absolute",PositionType}({}),Unit=function(Unit){return Unit[Unit.Undefined=0]="Undefined",Unit[Unit.Point=1]="Point",Unit[Unit.Percent=2]="Percent",Unit[Unit.Auto=3]="Auto",Unit}({}),Wrap=function(Wrap){return Wrap[Wrap.NoWrap=0]="NoWrap",Wrap[Wrap.Wrap=1]="Wrap",Wrap[Wrap.WrapReverse=2]="WrapReverse",Wrap}({}),constants3={ALIGN_AUTO:Align.Auto,ALIGN_FLEX_START:Align.FlexStart,ALIGN_CENTER:Align.Center,ALIGN_FLEX_END:Align.FlexEnd,ALIGN_STRETCH:Align.Stretch,ALIGN_BASELINE:Align.Baseline,ALIGN_SPACE_BETWEEN:Align.SpaceBetween,ALIGN_SPACE_AROUND:Align.SpaceAround,ALIGN_SPACE_EVENLY:Align.SpaceEvenly,BOX_SIZING_BORDER_BOX:BoxSizing.BorderBox,BOX_SIZING_CONTENT_BOX:BoxSizing.ContentBox,DIMENSION_WIDTH:Dimension.Width,DIMENSION_HEIGHT:Dimension.Height,DIRECTION_INHERIT:Direction.Inherit,DIRECTION_LTR:Direction.LTR,DIRECTION_RTL:Direction.RTL,DISPLAY_FLEX:Display.Flex,DISPLAY_NONE:Display.None,DISPLAY_CONTENTS:Display.Contents,EDGE_LEFT:Edge.Left,EDGE_TOP:Edge.Top,EDGE_RIGHT:Edge.Right,EDGE_BOTTOM:Edge.Bottom,EDGE_START:Edge.Start,EDGE_END:Edge.End,EDGE_HORIZONTAL:Edge.Horizontal,EDGE_VERTICAL:Edge.Vertical,EDGE_ALL:Edge.All,ERRATA_NONE:Errata.None,ERRATA_STRETCH_FLEX_BASIS:Errata.StretchFlexBasis,ERRATA_ABSOLUTE_POSITION_WITHOUT_INSETS_EXCLUDES_PADDING:Errata.AbsolutePositionWithoutInsetsExcludesPadding,ERRATA_ABSOLUTE_PERCENT_AGAINST_INNER_SIZE:Errata.AbsolutePercentAgainstInnerSize,ERRATA_ALL:Errata.All,ERRATA_CLASSIC:Errata.Classic,EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS:ExperimentalFeature.WebFlexBasis,FLEX_DIRECTION_COLUMN:FlexDirection.Column,FLEX_DIRECTION_COLUMN_REVERSE:FlexDirection.ColumnReverse,FLEX_DIRECTION_ROW:FlexDirection.Row,FLEX_DIRECTION_ROW_REVERSE:FlexDirection.RowReverse,GUTTER_COLUMN:Gutter.Column,GUTTER_ROW:Gutter.Row,GUTTER_ALL:Gutter.All,JUSTIFY_FLEX_START:Justify.FlexStart,JUSTIFY_CENTER:Justify.Center,JUSTIFY_FLEX_END:Justify.FlexEnd,JUSTIFY_SPACE_BETWEEN:Justify.SpaceBetween,JUSTIFY_SPACE_AROUND:Justify.SpaceAround,JUSTIFY_SPACE_EVENLY:Justify.SpaceEvenly,LOG_LEVEL_ERROR:LogLevel.Error,LOG_LEVEL_WARN:LogLevel.Warn,LOG_LEVEL_INFO:LogLevel.Info,LOG_LEVEL_DEBUG:LogLevel.Debug,LOG_LEVEL_VERBOSE:LogLevel.Verbose,LOG_LEVEL_FATAL:LogLevel.Fatal,MEASURE_MODE_UNDEFINED:MeasureMode.Undefined,MEASURE_MODE_EXACTLY:MeasureMode.Exactly,MEASURE_MODE_AT_MOST:MeasureMode.AtMost,NODE_TYPE_DEFAULT:NodeType.Default,NODE_TYPE_TEXT:NodeType.Text,OVERFLOW_VISIBLE:Overflow.Visible,OVERFLOW_HIDDEN:Overflow.Hidden,OVERFLOW_SCROLL:Overflow.Scroll,POSITION_TYPE_STATIC:PositionType.Static,POSITION_TYPE_RELATIVE:PositionType.Relative,POSITION_TYPE_ABSOLUTE:PositionType.Absolute,UNIT_UNDEFINED:Unit.Undefined,UNIT_POINT:Unit.Point,UNIT_PERCENT:Unit.Percent,UNIT_AUTO:Unit.Auto,WRAP_NO_WRAP:Wrap.NoWrap,WRAP_WRAP:Wrap.Wrap,WRAP_WRAP_REVERSE:Wrap.WrapReverse},YGEnums_default=constants3});function wrapAssembly(lib){function patch(prototype,name,fn){let original=prototype[name];prototype[name]=function(){for(var _len=arguments.length,args=Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return fn.call(this,original,...args)}}for(let fnName of["setPosition","setMargin","setFlexBasis","setWidth","setHeight","setMinWidth","setMinHeight","setMaxWidth","setMaxHeight","setPadding","setGap"]){let methods={[Unit.Point]:lib.Node.prototype[fnName],[Unit.Percent]:lib.Node.prototype[`${fnName}Percent`],[Unit.Auto]:lib.Node.prototype[`${fnName}Auto`]};patch(lib.Node.prototype,fnName,function(original){for(var _len2=arguments.length,args=Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++)args[_key2-1]=arguments[_key2];let value=args.pop(),unit,asNumber;if(value==="auto")unit=Unit.Auto,asNumber=void 0;else if(typeof value==="object")unit=value.unit,asNumber=value.valueOf();else if(unit=typeof value==="string"&&value.endsWith("%")?Unit.Percent:Unit.Point,asNumber=parseFloat(value),value!==void 0&&!Number.isNaN(value)&&Number.isNaN(asNumber))throw Error(`Invalid value ${value} for ${fnName}`);if(!methods[unit])throw Error(`Failed to execute "${fnName}": Unsupported unit '${value}'`);if(asNumber!==void 0)return methods[unit].call(this,...args,asNumber);else return methods[unit].call(this,...args)})}function wrapMeasureFunction(measureFunction){return lib.MeasureCallback.implement({measure:function(){let{width,height}=measureFunction(...arguments);return{width:width??NaN,height:height??NaN}}})}patch(lib.Node.prototype,"setMeasureFunc",function(original,measureFunc){if(measureFunc)return original.call(this,wrapMeasureFunction(measureFunc));else return this.unsetMeasureFunc()});function wrapDirtiedFunc(dirtiedFunction){return lib.DirtiedCallback.implement({dirtied:dirtiedFunction})}return patch(lib.Node.prototype,"setDirtiedFunc",function(original,dirtiedFunc){original.call(this,wrapDirtiedFunc(dirtiedFunc))}),patch(lib.Config.prototype,"free",function(){lib.Config.destroy(this)}),patch(lib.Node,"create",(_,config)=>config?lib.Node.createWithConfig(config):lib.Node.createDefault()),patch(lib.Node.prototype,"free",function(){lib.Node.destroy(this)}),patch(lib.Node.prototype,"freeRecursive",function(){for(let t=0,T=this.getChildCount();t<T;++t)this.getChild(0).freeRecursive();this.free()}),patch(lib.Node.prototype,"calculateLayout",function(original){let width=arguments.length>1&&arguments[1]!==void 0?arguments[1]:NaN,height=arguments.length>2&&arguments[2]!==void 0?arguments[2]:NaN,direction=arguments.length>3&&arguments[3]!==void 0?arguments[3]:Direction.LTR;return original.call(this,width,height,direction)}),{Config:lib.Config,Node:lib.Node,...YGEnums_default}}var init_wrapAssembly=__esm(()=>{init_YGEnums();init_YGEnums()});var Yoga,src_default;var init_src=__esm(async()=>{init_yoga_wasm_base64_esm();init_wrapAssembly();init_YGEnums();Yoga=wrapAssembly(await yoga_wasm_base64_esm_default()),src_default=Yoga});import process16 from"node:process";import{execFileSync}from"node:child_process";import fs15 from"node:fs";import tty2 from"node:tty";function terminalSize(){let{env,stdout,stderr}=process16;if(stdout?.columns&&stdout?.rows)return create6(stdout.columns,stdout.rows);if(stderr?.columns&&stderr?.rows)return create6(stderr.columns,stderr.rows);if(env.COLUMNS&&env.LINES)return create6(env.COLUMNS,env.LINES);let fallback={columns:defaultColumns,rows:defaultRows};if(process16.platform==="win32")return tput()??fallback;if(process16.platform==="darwin")return devTty()??tput()??fallback;return devTty()??tput()??resize()??fallback}var defaultColumns=80,defaultRows=24,exec3=(command,arguments_,{shell,env}={})=>execFileSync(command,arguments_,{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:500,shell,env}).trim(),create6=(columns,rows)=>({columns:Number.parseInt(columns,10),rows:Number.parseInt(rows,10)}),createIfNotDefault=(maybeColumns,maybeRows)=>{let{columns,rows}=create6(maybeColumns,maybeRows);if(Number.isNaN(columns)||Number.isNaN(rows))return;if(columns===defaultColumns&&rows===defaultRows)return;return{columns,rows}},isForegroundProcess=()=>{if(process16.platform!=="linux")return!0;try{let statContents=fs15.readFileSync("/proc/self/stat","utf8"),closingParenthesisIndex=statContents.lastIndexOf(") ");if(closingParenthesisIndex===-1)return!1;let statFields=statContents.slice(closingParenthesisIndex+2).trim().split(/\s+/),processGroupId=Number.parseInt(statFields[2],10),foregroundProcessGroupId=Number.parseInt(statFields[5],10);if(Number.isNaN(processGroupId)||Number.isNaN(foregroundProcessGroupId))return!1;if(foregroundProcessGroupId<=0)return!1;return processGroupId===foregroundProcessGroupId}catch{return!1}},devTty=()=>{try{let flags=process16.platform==="darwin"?fs15.constants.O_EVTONLY|fs15.constants.O_NONBLOCK:fs15.constants.O_NONBLOCK,{columns,rows}=tty2.WriteStream(fs15.openSync("/dev/tty",flags));return{columns,rows}}catch{}},tput=()=>{try{let columns=exec3("tput",["cols"],{env:{TERM:"dumb",...process16.env}}),rows=exec3("tput",["lines"],{env:{TERM:"dumb",...process16.env}});if(columns&&rows)return createIfNotDefault(columns,rows)}catch{}},resize=()=>{try{if(!isForegroundProcess())return;let size=exec3("resize",["-u"]).match(/\d+/g);if(size.length===2)return createIfNotDefault(size[0],size[1])}catch{}};var init_terminal_size=()=>{};var resolveDimension=(value,fallback,defaultValue)=>{if(value!==void 0&&value>0)return value;return fallback!==void 0&&fallback>0?fallback:defaultValue},getWindowSize=(stdout)=>{let columns=stdout.columns??0,rows=stdout.rows??0;if(Boolean(columns)&&Boolean(rows))return{columns,rows};let fallbackSize=terminalSize();return{columns:resolveDimension(columns,fallbackSize.columns,80),rows:resolveDimension(rows,fallbackSize.rows,24)}};var init_utils5=__esm(()=>{init_terminal_size()});var exports_scheduler_production={};__exportCjs(exports_scheduler_production,{unstable_now:()=>$unstable_now,unstable_IdlePriority:()=>$unstable_IdlePriority,unstable_ImmediatePriority:()=>$unstable_ImmediatePriority,unstable_LowPriority:()=>$unstable_LowPriority,unstable_NormalPriority:()=>$unstable_NormalPriority,unstable_Profiling:()=>$unstable_Profiling,unstable_UserBlockingPriority:()=>$unstable_UserBlockingPriority,unstable_cancelCallback:()=>$unstable_cancelCallback,unstable_forceFrameRate:()=>$unstable_forceFrameRate,unstable_getCurrentPriorityLevel:()=>$unstable_getCurrentPriorityLevel,unstable_next:()=>$unstable_next,unstable_requestPaint:()=>$unstable_requestPaint,unstable_runWithPriority:()=>$unstable_runWithPriority,unstable_scheduleCallback:()=>$unstable_scheduleCallback,unstable_shouldYield:()=>$unstable_shouldYield,unstable_wrapCallback:()=>$unstable_wrapCallback},{unstable_now:(value)=>$unstable_now=value,unstable_IdlePriority:(value)=>$unstable_IdlePriority=value,unstable_ImmediatePriority:(value)=>$unstable_ImmediatePriority=value,unstable_LowPriority:(value)=>$unstable_LowPriority=value,unstable_NormalPriority:(value)=>$unstable_NormalPriority=value,unstable_Profiling:(value)=>$unstable_Profiling=value,unstable_UserBlockingPriority:(value)=>$unstable_UserBlockingPriority=value,unstable_cancelCallback:(value)=>$unstable_cancelCallback=value,unstable_forceFrameRate:(value)=>$unstable_forceFrameRate=value,unstable_getCurrentPriorityLevel:(value)=>$unstable_getCurrentPriorityLevel=value,unstable_next:(value)=>$unstable_next=value,unstable_requestPaint:(value)=>$unstable_requestPaint=value,unstable_runWithPriority:(value)=>$unstable_runWithPriority=value,unstable_scheduleCallback:(value)=>$unstable_scheduleCallback=value,unstable_shouldYield:(value)=>$unstable_shouldYield=value,unstable_wrapCallback:(value)=>$unstable_wrapCallback=value});function push(heap,node){var index=heap.length;heap.push(node);a:for(;0<index;){var parentIndex=index-1>>>1,parent=heap[parentIndex];if(0<compare2(parent,node))heap[parentIndex]=node,heap[index]=parent,index=parentIndex;else break a}}function peek(heap){return heap.length===0?null:heap[0]}function pop(heap){if(heap.length===0)return null;var first=heap[0],last=heap.pop();if(last!==first){heap[0]=last;a:for(var index=0,length=heap.length,halfLength=length>>>1;index<halfLength;){var leftIndex=2*(index+1)-1,left=heap[leftIndex],rightIndex=leftIndex+1,right=heap[rightIndex];if(0>compare2(left,last))rightIndex<length&&0>compare2(right,left)?(heap[index]=right,heap[rightIndex]=last,index=rightIndex):(heap[index]=left,heap[leftIndex]=last,index=leftIndex);else if(rightIndex<length&&0>compare2(right,last))heap[index]=right,heap[rightIndex]=last,index=rightIndex;else break a}}return first}function compare2(a,b){var diff=a.sortIndex-b.sortIndex;return diff!==0?diff:a.id-b.id}function advanceTimers(currentTime){for(var timer=peek(timerQueue);timer!==null;){if(timer.callback===null)pop(timerQueue);else if(timer.startTime<=currentTime)pop(timerQueue),timer.sortIndex=timer.expirationTime,push(taskQueue,timer);else break;timer=peek(timerQueue)}}function handleTimeout(currentTime){if(isHostTimeoutScheduled=!1,advanceTimers(currentTime),!isHostCallbackScheduled)if(peek(taskQueue)!==null)isHostCallbackScheduled=!0,isMessageLoopRunning||(isMessageLoopRunning=!0,schedulePerformWorkUntilDeadline());else{var firstTimer=peek(timerQueue);firstTimer!==null&&requestHostTimeout(handleTimeout,firstTimer.startTime-currentTime)}}function shouldYieldToHost(){return needsPaint?!0:exports_scheduler_production.unstable_now()-startTime<frameInterval?!1:!0}function performWorkUntilDeadline(){if(needsPaint=!1,isMessageLoopRunning){var currentTime=exports_scheduler_production.unstable_now();startTime=currentTime;var hasMoreWork=!0;try{a:{isHostCallbackScheduled=!1,isHostTimeoutScheduled&&(isHostTimeoutScheduled=!1,localClearTimeout(taskTimeoutID),taskTimeoutID=-1),isPerformingWork=!0;var previousPriorityLevel=currentPriorityLevel;try{b:{advanceTimers(currentTime);for(currentTask=peek(taskQueue);currentTask!==null&&!(currentTask.expirationTime>currentTime&&shouldYieldToHost());){var callback=currentTask.callback;if(typeof callback==="function"){currentTask.callback=null,currentPriorityLevel=currentTask.priorityLevel;var continuationCallback=callback(currentTask.expirationTime<=currentTime);if(currentTime=exports_scheduler_production.unstable_now(),typeof continuationCallback==="function"){currentTask.callback=continuationCallback,advanceTimers(currentTime),hasMoreWork=!0;break b}currentTask===peek(taskQueue)&&pop(taskQueue),advanceTimers(currentTime)}else pop(taskQueue);currentTask=peek(taskQueue)}if(currentTask!==null)hasMoreWork=!0;else{var firstTimer=peek(timerQueue);firstTimer!==null&&requestHostTimeout(handleTimeout,firstTimer.startTime-currentTime),hasMoreWork=!1}}break a}finally{currentTask=null,currentPriorityLevel=previousPriorityLevel,isPerformingWork=!1}hasMoreWork=void 0}}finally{hasMoreWork?schedulePerformWorkUntilDeadline():isMessageLoopRunning=!1}}}function requestHostTimeout(callback,ms){taskTimeoutID=localSetTimeout(function(){callback(exports_scheduler_production.unstable_now())},ms)}var $unstable_now=void 0,localPerformance,localDate,initialTime,taskQueue,timerQueue,taskIdCounter=1,currentTask=null,currentPriorityLevel=3,isPerformingWork=!1,isHostCallbackScheduled=!1,isHostTimeoutScheduled=!1,needsPaint=!1,localSetTimeout,localClearTimeout,localSetImmediate,isMessageLoopRunning=!1,taskTimeoutID=-1,frameInterval=5,startTime=-1,schedulePerformWorkUntilDeadline,channel,port,$unstable_IdlePriority=5,$unstable_ImmediatePriority=1,$unstable_LowPriority=4,$unstable_NormalPriority=3,$unstable_Profiling=null,$unstable_UserBlockingPriority=2,$unstable_cancelCallback=function(task){task.callback=null},$unstable_forceFrameRate=function(fps){0>fps||125<fps?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):frameInterval=0<fps?Math.floor(1000/fps):5},$unstable_getCurrentPriorityLevel=function(){return currentPriorityLevel},$unstable_next=function(eventHandler){switch(currentPriorityLevel){case 1:case 2:case 3:var priorityLevel=3;break;default:priorityLevel=currentPriorityLevel}var previousPriorityLevel=currentPriorityLevel;currentPriorityLevel=priorityLevel;try{return eventHandler()}finally{currentPriorityLevel=previousPriorityLevel}},$unstable_requestPaint=function(){needsPaint=!0},$unstable_runWithPriority=function(priorityLevel,eventHandler){switch(priorityLevel){case 1:case 2:case 3:case 4:case 5:break;default:priorityLevel=3}var previousPriorityLevel=currentPriorityLevel;currentPriorityLevel=priorityLevel;try{return eventHandler()}finally{currentPriorityLevel=previousPriorityLevel}},$unstable_scheduleCallback=function(priorityLevel,callback,options){var currentTime=exports_scheduler_production.unstable_now();switch(typeof options==="object"&&options!==null?(options=options.delay,options=typeof options==="number"&&0<options?currentTime+options:currentTime):options=currentTime,priorityLevel){case 1:var timeout=-1;break;case 2:timeout=250;break;case 5:timeout=1073741823;break;case 4:timeout=1e4;break;default:timeout=5000}return timeout=options+timeout,priorityLevel={id:taskIdCounter++,callback,priorityLevel,startTime:options,expirationTime:timeout,sortIndex:-1},options>currentTime?(priorityLevel.sortIndex=options,push(timerQueue,priorityLevel),peek(taskQueue)===null&&priorityLevel===peek(timerQueue)&&(isHostTimeoutScheduled?(localClearTimeout(taskTimeoutID),taskTimeoutID=-1):isHostTimeoutScheduled=!0,requestHostTimeout(handleTimeout,options-currentTime))):(priorityLevel.sortIndex=timeout,push(taskQueue,priorityLevel),isHostCallbackScheduled||isPerformingWork||(isHostCallbackScheduled=!0,isMessageLoopRunning||(isMessageLoopRunning=!0,schedulePerformWorkUntilDeadline()))),priorityLevel},$unstable_shouldYield,$unstable_wrapCallback=function(callback){var parentPriorityLevel=currentPriorityLevel;return function(){var previousPriorityLevel=currentPriorityLevel;currentPriorityLevel=parentPriorityLevel;try{return callback.apply(this,arguments)}finally{currentPriorityLevel=previousPriorityLevel}}};var init_scheduler_production=__esm(()=>{if(typeof performance==="object"&&typeof performance.now==="function")localPerformance=performance,$unstable_now=function(){return localPerformance.now()};else localDate=Date,initialTime=localDate.now(),$unstable_now=function(){return localDate.now()-initialTime};taskQueue=[],timerQueue=[],localSetTimeout=typeof setTimeout==="function"?setTimeout:null,localClearTimeout=typeof clearTimeout==="function"?clearTimeout:null,localSetImmediate=typeof setImmediate<"u"?setImmediate:null;if(typeof localSetImmediate==="function")schedulePerformWorkUntilDeadline=function(){localSetImmediate(performWorkUntilDeadline)};else if(typeof MessageChannel<"u")channel=new MessageChannel,port=channel.port2,channel.port1.onmessage=performWorkUntilDeadline,schedulePerformWorkUntilDeadline=function(){port.postMessage(null)};else schedulePerformWorkUntilDeadline=function(){localSetTimeout(performWorkUntilDeadline,0)};$unstable_shouldYield=shouldYieldToHost});var require_react_reconciler_production=__commonJS(function(exports,module){init_react_production();init_scheduler_production();module.exports=function($$$config){function createFiber(tag,pendingProps,key,mode){return new FiberNode(tag,pendingProps,key,mode)}function noop(){}function formatProdErrorMessage(code){var url="https://react.dev/errors/"+code;if(1<arguments.length){url+="?args[]="+encodeURIComponent(arguments[1]);for(var i=2;i<arguments.length;i++)url+="&args[]="+encodeURIComponent(arguments[i])}return"Minified React error #"+code+"; visit "+url+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function getNearestMountedFiber(fiber){for(var node=fiber,nextNode=node;nextNode&&!nextNode.alternate;)node=nextNode,(node.flags&4098)!==0&&(fiber=node.return),nextNode=node.return;for(;node.return;)node=node.return;return node.tag===3?fiber:null}function assertIsMounted(fiber){if(getNearestMountedFiber(fiber)!==fiber)throw Error(formatProdErrorMessage(188))}function findCurrentFiberUsingSlowPath(fiber){var alternate=fiber.alternate;if(!alternate){if(alternate=getNearestMountedFiber(fiber),alternate===null)throw Error(formatProdErrorMessage(188));return alternate!==fiber?null:fiber}for(var a=fiber,b=alternate;;){var parentA=a.return;if(parentA===null)break;var parentB=parentA.alternate;if(parentB===null){if(b=parentA.return,b!==null){a=b;continue}break}if(parentA.child===parentB.child){for(parentB=parentA.child;parentB;){if(parentB===a)return assertIsMounted(parentA),fiber;if(parentB===b)return assertIsMounted(parentA),alternate;parentB=parentB.sibling}throw Error(formatProdErrorMessage(188))}if(a.return!==b.return)a=parentA,b=parentB;else{for(var didFindChild=!1,child$0=parentA.child;child$0;){if(child$0===a){didFindChild=!0,a=parentA,b=parentB;break}if(child$0===b){didFindChild=!0,b=parentA,a=parentB;break}child$0=child$0.sibling}if(!didFindChild){for(child$0=parentB.child;child$0;){if(child$0===a){didFindChild=!0,a=parentB,b=parentA;break}if(child$0===b){didFindChild=!0,b=parentB,a=parentA;break}child$0=child$0.sibling}if(!didFindChild)throw Error(formatProdErrorMessage(189))}}if(a.alternate!==b)throw Error(formatProdErrorMessage(190))}if(a.tag!==3)throw Error(formatProdErrorMessage(188));return a.stateNode.current===a?fiber:alternate}function findCurrentHostFiberImpl(node){var tag=node.tag;if(tag===5||tag===26||tag===27||tag===6)return node;for(node=node.child;node!==null;){if(tag=findCurrentHostFiberImpl(node),tag!==null)return tag;node=node.sibling}return null}function findCurrentHostFiberWithNoPortalsImpl(node){var tag=node.tag;if(tag===5||tag===26||tag===27||tag===6)return node;for(node=node.child;node!==null;){if(node.tag!==4&&(tag=findCurrentHostFiberWithNoPortalsImpl(node),tag!==null))return tag;node=node.sibling}return null}function getIteratorFn(maybeIterable){if(maybeIterable===null||typeof maybeIterable!=="object")return null;return maybeIterable=MAYBE_ITERATOR_SYMBOL&&maybeIterable[MAYBE_ITERATOR_SYMBOL]||maybeIterable["@@iterator"],typeof maybeIterable==="function"?maybeIterable:null}function getComponentNameFromType(type){if(type==null)return null;if(typeof type==="function")return type.$$typeof===REACT_CLIENT_REFERENCE?null:type.displayName||type.name||null;if(typeof type==="string")return type;switch(type){case REACT_FRAGMENT_TYPE:return"Fragment";case REACT_PROFILER_TYPE:return"Profiler";case REACT_STRICT_MODE_TYPE:return"StrictMode";case REACT_SUSPENSE_TYPE:return"Suspense";case REACT_SUSPENSE_LIST_TYPE:return"SuspenseList";case REACT_ACTIVITY_TYPE:return"Activity";case REACT_VIEW_TRANSITION_TYPE:return"ViewTransition"}if(typeof type==="object")switch(type.$$typeof){case REACT_PORTAL_TYPE:return"Portal";case REACT_CONTEXT_TYPE:return type.displayName||"Context";case REACT_CONSUMER_TYPE:return(type._context.displayName||"Context")+".Consumer";case REACT_FORWARD_REF_TYPE:var innerType=type.render;return type=type.displayName,type||(type=innerType.displayName||innerType.name||"",type=type!==""?"ForwardRef("+type+")":"ForwardRef"),type;case REACT_MEMO_TYPE:return innerType=type.displayName||null,innerType!==null?innerType:getComponentNameFromType(type.type)||"Memo";case REACT_LAZY_TYPE:innerType=type._payload,type=type._init;try{return getComponentNameFromType(type(innerType))}catch(x){}}return null}function createCursor(defaultValue){return{current:defaultValue}}function pop(cursor){0>index$jscomp$0||(cursor.current=valueStack[index$jscomp$0],valueStack[index$jscomp$0]=null,index$jscomp$0--)}function push(cursor,value){index$jscomp$0++,valueStack[index$jscomp$0]=cursor.current,cursor.current=value}function clz32Fallback(x){return x>>>=0,x===0?32:31-(log$1(x)/LN2|0)|0}function getHighestPriorityLanes(lanes){var pendingSyncLanes=lanes&42;if(pendingSyncLanes!==0)return pendingSyncLanes;switch(lanes&-lanes){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return lanes&-lanes;case 262144:case 524288:case 1048576:case 2097152:return lanes&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return lanes&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return lanes}}function getNextLanes(root,wipLanes,rootHasPendingCommit){var pendingLanes=root.pendingLanes;if(pendingLanes===0)return 0;var nextLanes=0,suspendedLanes=root.suspendedLanes,pingedLanes=root.pingedLanes;root=root.warmLanes;var nonIdlePendingLanes=pendingLanes&134217727;return nonIdlePendingLanes!==0?(pendingLanes=nonIdlePendingLanes&~suspendedLanes,pendingLanes!==0?nextLanes=getHighestPriorityLanes(pendingLanes):(pingedLanes&=nonIdlePendingLanes,pingedLanes!==0?nextLanes=getHighestPriorityLanes(pingedLanes):rootHasPendingCommit||(rootHasPendingCommit=nonIdlePendingLanes&~root,rootHasPendingCommit!==0&&(nextLanes=getHighestPriorityLanes(rootHasPendingCommit))))):(nonIdlePendingLanes=pendingLanes&~suspendedLanes,nonIdlePendingLanes!==0?nextLanes=getHighestPriorityLanes(nonIdlePendingLanes):pingedLanes!==0?nextLanes=getHighestPriorityLanes(pingedLanes):rootHasPendingCommit||(rootHasPendingCommit=pendingLanes&~root,rootHasPendingCommit!==0&&(nextLanes=getHighestPriorityLanes(rootHasPendingCommit)))),nextLanes===0?0:wipLanes!==0&&wipLanes!==nextLanes&&(wipLanes&suspendedLanes)===0&&(suspendedLanes=nextLanes&-nextLanes,rootHasPendingCommit=wipLanes&-wipLanes,suspendedLanes>=rootHasPendingCommit||suspendedLanes===32&&(rootHasPendingCommit&4194048)!==0)?wipLanes:nextLanes}function checkIfRootIsPrerendering(root,renderLanes){return(root.pendingLanes&~(root.suspendedLanes&~root.pingedLanes)&renderLanes)===0}function getEntangledLanes(root,renderLanes){(renderLanes&8)!==0&&(renderLanes|=renderLanes&32);var allEntangledLanes=root.entangledLanes;if(allEntangledLanes!==0)for(root=root.entanglements,allEntangledLanes&=renderLanes;0<allEntangledLanes;){var index$2=31-clz32(allEntangledLanes),lane=1<<index$2;renderLanes|=root[index$2],allEntangledLanes&=~lane}return renderLanes}function computeExpirationTime(lane,currentTime){switch(lane){case 1:case 2:case 4:case 8:case 64:return currentTime+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return currentTime+5000;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function claimNextRetryLane(){var lane=nextRetryLane;return nextRetryLane<<=1,(nextRetryLane&62914560)===0&&(nextRetryLane=4194304),lane}function createLaneMap(initial){for(var laneMap=[],i=0;31>i;i++)laneMap.push(initial);return laneMap}function markRootUpdated$1(root,updateLane){root.pendingLanes|=updateLane,updateLane!==268435456&&(root.suspendedLanes=0,root.pingedLanes=0,root.warmLanes=0)}function markRootFinished(root,finishedLanes,remainingLanes,spawnedLane,updatedLanes,suspendedRetryLanes){var previouslyPendingLanes=root.pendingLanes;root.pendingLanes=remainingLanes,root.suspendedLanes=0,root.pingedLanes=0,root.warmLanes=0,root.expiredLanes&=remainingLanes,root.entangledLanes&=remainingLanes,root.errorRecoveryDisabledLanes&=remainingLanes,root.shellSuspendCounter=0;var{entanglements,expirationTimes,hiddenUpdates}=root;for(remainingLanes=previouslyPendingLanes&~remainingLanes;0<remainingLanes;){var index$5=31-clz32(remainingLanes),lane=1<<index$5;entanglements[index$5]=0,expirationTimes[index$5]=-1;var hiddenUpdatesForLane=hiddenUpdates[index$5];if(hiddenUpdatesForLane!==null)for(hiddenUpdates[index$5]=null,index$5=0;index$5<hiddenUpdatesForLane.length;index$5++){var update=hiddenUpdatesForLane[index$5];update!==null&&(update.lane&=-536870913)}remainingLanes&=~lane}spawnedLane!==0&&markSpawnedDeferredLane(root,spawnedLane,0),suspendedRetryLanes!==0&&updatedLanes===0&&root.tag!==0&&(root.suspendedLanes|=suspendedRetryLanes&~(previouslyPendingLanes&~finishedLanes))}function markSpawnedDeferredLane(root,spawnedLane,entangledLanes){root.pendingLanes|=spawnedLane,root.suspendedLanes&=~spawnedLane;var spawnedLaneIndex=31-clz32(spawnedLane);root.entangledLanes|=spawnedLane,root.entanglements[spawnedLaneIndex]=root.entanglements[spawnedLaneIndex]|1073741824|entangledLanes&261930}function markRootEntangled(root,entangledLanes){var rootEntangledLanes=root.entangledLanes|=entangledLanes;for(root=root.entanglements;rootEntangledLanes;){var index$6=31-clz32(rootEntangledLanes),lane=1<<index$6;lane&entangledLanes|root[index$6]&entangledLanes&&(root[index$6]|=entangledLanes),rootEntangledLanes&=~lane}}function getBumpedLaneForHydration(root,renderLanes){var renderLane=renderLanes&-renderLanes;return renderLane=(renderLane&42)!==0?1:getBumpedLaneForHydrationByLane(renderLane),(renderLane&(root.suspendedLanes|renderLanes))!==0?0:renderLane}function getBumpedLaneForHydrationByLane(lane){switch(lane){case 2:lane=1;break;case 8:lane=4;break;case 32:lane=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:lane=128;break;case 268435456:lane=134217728;break;default:lane=0}return lane}function lanesToEventPriority(lanes){return lanes&=-lanes,2<lanes?8<lanes?(lanes&134217727)!==0?32:268435456:8:2}function setIsStrictModeForDevtools(newIsStrictMode){if(typeof log2==="function"&&unstable_setDisableYieldValue2(newIsStrictMode),injectedHook&&typeof injectedHook.setStrictMode==="function")try{injectedHook.setStrictMode(rendererID,newIsStrictMode)}catch(err){}}function getViewTransitionName(props,instance){if(props.name!=null&&props.name!=="auto")return props.name;if(instance.autoName!==null)return instance.autoName;props=pendingEffectsRoot.identifierPrefix;var globalClientId=globalClientIdCounter$1++;return props="_"+props+"t_"+globalClientId.toString(32)+"_",instance.autoName=props}function getClassNameByType(classByType){if(classByType==null||typeof classByType==="string")return classByType;var className=null,activeTypes=pendingTransitionTypes;if(activeTypes!==null)for(var i=0;i<activeTypes.length;i++){var match=classByType[activeTypes[i]];if(match!=null){if(match==="none")return"none";className=className==null?match:className+(" "+match)}}return className==null?classByType.default:className}function getViewTransitionClassName(defaultClass,eventClass){return defaultClass=getClassNameByType(defaultClass),eventClass=getClassNameByType(eventClass),eventClass==null?defaultClass==="auto"?null:defaultClass:eventClass==="auto"?null:eventClass}function is(x,y){return x===y&&(x!==0||1/x===1/y)||x!==x&&y!==y}function describeBuiltInComponentFrame(name){if(prefix===void 0)try{throw Error()}catch(x){var match=x.stack.trim().match(/\n( *(at )?)/);prefix=match&&match[1]||"",suffix=-1<x.stack.indexOf(`
1278
- at`)?" (<anonymous>)":-1<x.stack.indexOf("@")?"@unknown:0:0":""}return`
1279
- `+prefix+name+suffix}function describeNativeComponentFrame(fn,construct){if(!fn||reentry)return"";reentry=!0;var previousPrepareStackTrace=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var RunInRootFrame={DetermineComponentFrameRoot:function(){try{if(construct){var Fake=function(){throw Error()};if(Object.defineProperty(Fake.prototype,"props",{set:function(){throw Error()}}),typeof Reflect==="object"&&Reflect.construct){try{Reflect.construct(Fake,[])}catch(x){var control=x}Reflect.construct(fn,[],Fake)}else{try{Fake.call()}catch(x$8){control=x$8}Fake=!1;try{var prevProps=Object.getOwnPropertyDescriptor(fn.prototype,"props");Object.defineProperty(fn.prototype,"props",{configurable:!0,set:function(){throw Error()}}),Fake=!0,new fn}finally{Fake&&(prevProps!==void 0?Object.defineProperty(fn.prototype,"props",prevProps):delete fn.prototype.props)}}}else{try{throw Error()}catch(x$9){control=x$9}(Fake=fn())&&typeof Fake.catch==="function"&&Fake.catch(function(){})}}catch(sample){if(sample&&control&&typeof sample.stack==="string")return[sample.stack,control.stack]}return[null,null]}};RunInRootFrame.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var namePropDescriptor=Object.getOwnPropertyDescriptor(RunInRootFrame.DetermineComponentFrameRoot,"name");namePropDescriptor&&namePropDescriptor.configurable&&Object.defineProperty(RunInRootFrame.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var _RunInRootFrame$Deter=RunInRootFrame.DetermineComponentFrameRoot(),sampleStack=_RunInRootFrame$Deter[0],controlStack=_RunInRootFrame$Deter[1];if(sampleStack&&controlStack){var sampleLines=sampleStack.split(`
1280
- `),controlLines=controlStack.split(`
1281
- `);for(namePropDescriptor=RunInRootFrame=0;RunInRootFrame<sampleLines.length&&!sampleLines[RunInRootFrame].includes("DetermineComponentFrameRoot");)RunInRootFrame++;for(;namePropDescriptor<controlLines.length&&!controlLines[namePropDescriptor].includes("DetermineComponentFrameRoot");)namePropDescriptor++;if(RunInRootFrame===sampleLines.length||namePropDescriptor===controlLines.length)for(RunInRootFrame=sampleLines.length-1,namePropDescriptor=controlLines.length-1;1<=RunInRootFrame&&0<=namePropDescriptor&&sampleLines[RunInRootFrame]!==controlLines[namePropDescriptor];)namePropDescriptor--;for(;1<=RunInRootFrame&&0<=namePropDescriptor;RunInRootFrame--,namePropDescriptor--)if(sampleLines[RunInRootFrame]!==controlLines[namePropDescriptor]){if(RunInRootFrame!==1||namePropDescriptor!==1)do if(RunInRootFrame--,namePropDescriptor--,0>namePropDescriptor||sampleLines[RunInRootFrame]!==controlLines[namePropDescriptor]){var frame=`
1282
- `+sampleLines[RunInRootFrame].replace(" at new "," at ");return fn.displayName&&frame.includes("<anonymous>")&&(frame=frame.replace("<anonymous>",fn.displayName)),frame}while(1<=RunInRootFrame&&0<=namePropDescriptor);break}}}finally{reentry=!1,Error.prepareStackTrace=previousPrepareStackTrace}return(previousPrepareStackTrace=fn?fn.displayName||fn.name:"")?describeBuiltInComponentFrame(previousPrepareStackTrace):""}function describeFiber(fiber,childFiber){switch(fiber.tag){case 26:case 27:case 5:return describeBuiltInComponentFrame(fiber.type);case 16:return describeBuiltInComponentFrame("Lazy");case 13:return fiber.child!==childFiber&&childFiber!==null?describeBuiltInComponentFrame("Suspense Fallback"):describeBuiltInComponentFrame("Suspense");case 19:return describeBuiltInComponentFrame("SuspenseList");case 0:case 15:return describeNativeComponentFrame(fiber.type,!1);case 11:return describeNativeComponentFrame(fiber.type.render,!1);case 1:return describeNativeComponentFrame(fiber.type,!0);case 31:return describeBuiltInComponentFrame("Activity");case 30:return describeBuiltInComponentFrame("ViewTransition");default:return""}}function getStackByFiberInDevAndProd(workInProgress){try{var info="",previous=null;do info+=describeFiber(workInProgress,previous),previous=workInProgress,workInProgress=workInProgress.return;while(workInProgress);return info}catch(x){return`
1283
- Error generating stack: `+x.message+`
1284
- `+x.stack}}function createCapturedValueAtFiber(value,source){if(typeof value==="object"&&value!==null){var existing=CapturedStacks.get(value);if(existing!==void 0)return existing;return source={value,source,stack:getStackByFiberInDevAndProd(source)},CapturedStacks.set(value,source),source}return{value,source,stack:getStackByFiberInDevAndProd(source)}}function pushTreeFork(workInProgress,totalChildren){forkStack[forkStackIndex++]=treeForkCount,forkStack[forkStackIndex++]=treeForkProvider,treeForkProvider=workInProgress,treeForkCount=totalChildren}function pushTreeId(workInProgress,totalChildren,index){idStack[idStackIndex++]=treeContextId,idStack[idStackIndex++]=treeContextOverflow,idStack[idStackIndex++]=treeContextProvider,treeContextProvider=workInProgress;var baseIdWithLeadingBit=treeContextId;workInProgress=treeContextOverflow;var baseLength=32-clz32(baseIdWithLeadingBit)-1;baseIdWithLeadingBit&=~(1<<baseLength),index+=1;var length=32-clz32(totalChildren)+baseLength;if(30<length){var numberOfOverflowBits=baseLength-baseLength%5;length=(baseIdWithLeadingBit&(1<<numberOfOverflowBits)-1).toString(32),baseIdWithLeadingBit>>=numberOfOverflowBits,baseLength-=numberOfOverflowBits,treeContextId=1<<32-clz32(totalChildren)+baseLength|index<<baseLength|baseIdWithLeadingBit,treeContextOverflow=length+workInProgress}else treeContextId=1<<length|index<<baseLength|baseIdWithLeadingBit,treeContextOverflow=workInProgress}function pushMaterializedTreeId(workInProgress){workInProgress.return!==null&&(pushTreeFork(workInProgress,1),pushTreeId(workInProgress,1,0))}function popTreeContext(workInProgress){for(;workInProgress===treeForkProvider;)treeForkProvider=forkStack[--forkStackIndex],forkStack[forkStackIndex]=null,treeForkCount=forkStack[--forkStackIndex],forkStack[forkStackIndex]=null;for(;workInProgress===treeContextProvider;)treeContextProvider=idStack[--idStackIndex],idStack[idStackIndex]=null,treeContextOverflow=idStack[--idStackIndex],idStack[idStackIndex]=null,treeContextId=idStack[--idStackIndex],idStack[idStackIndex]=null}function restoreSuspendedTreeContext(workInProgress,suspendedContext){idStack[idStackIndex++]=treeContextId,idStack[idStackIndex++]=treeContextOverflow,idStack[idStackIndex++]=treeContextProvider,treeContextId=suspendedContext.id,treeContextOverflow=suspendedContext.overflow,treeContextProvider=workInProgress}function pushHostContainer(fiber,nextRootInstance){push(rootInstanceStackCursor,nextRootInstance),push(contextFiberStackCursor,fiber),push(contextStackCursor,null),fiber=getRootHostContext(nextRootInstance),pop(contextStackCursor),push(contextStackCursor,fiber)}function popHostContainer(){pop(contextStackCursor),pop(contextFiberStackCursor),pop(rootInstanceStackCursor)}function pushHostContext(fiber){var stateHook=fiber.memoizedState;stateHook!==null&&(stateHook=stateHook.memoizedState,isPrimaryRenderer?HostTransitionContext._currentValue=stateHook:HostTransitionContext._currentValue2=stateHook,push(hostTransitionProviderCursor,fiber)),stateHook=contextStackCursor.current;var nextContext=getChildHostContext(stateHook,fiber.type);stateHook!==nextContext&&(push(contextFiberStackCursor,fiber),push(contextStackCursor,nextContext))}function popHostContext(fiber){contextFiberStackCursor.current===fiber&&(pop(contextStackCursor),pop(contextFiberStackCursor)),hostTransitionProviderCursor.current===fiber&&(pop(hostTransitionProviderCursor),isPrimaryRenderer?HostTransitionContext._currentValue=NotPendingTransition:HostTransitionContext._currentValue2=NotPendingTransition)}function throwOnHydrationMismatch(fiber){var error=Error(formatProdErrorMessage(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?"text":"HTML",""));throw queueHydrationError(createCapturedValueAtFiber(error,fiber)),HydrationMismatchException}function prepareToHydrateHostInstance(fiber,hostContext){if(!supportsHydration)throw Error(formatProdErrorMessage(175));hydrateInstance(fiber.stateNode,fiber.type,fiber.memoizedProps,hostContext,fiber)||throwOnHydrationMismatch(fiber,!0)}function popToNextHostParent(fiber){for(hydrationParentFiber=fiber.return;hydrationParentFiber;)switch(hydrationParentFiber.tag){case 5:case 31:case 13:rootOrSingletonContext=!1;return;case 27:case 3:rootOrSingletonContext=!0;return;default:hydrationParentFiber=hydrationParentFiber.return}}function popHydrationState(fiber){if(!supportsHydration||fiber!==hydrationParentFiber)return!1;if(!isHydrating)return popToNextHostParent(fiber),isHydrating=!0,!1;var tag=fiber.tag;if(supportsSingletons?tag!==3&&tag!==27&&(tag!==5||shouldDeleteUnhydratedTailInstances(fiber.type)&&!shouldSetTextContent(fiber.type,fiber.memoizedProps))&&nextHydratableInstance&&throwOnHydrationMismatch(fiber):tag!==3&&(tag!==5||shouldDeleteUnhydratedTailInstances(fiber.type)&&!shouldSetTextContent(fiber.type,fiber.memoizedProps))&&nextHydratableInstance&&throwOnHydrationMismatch(fiber),popToNextHostParent(fiber),tag===13){if(!supportsHydration)throw Error(formatProdErrorMessage(316));if(fiber=fiber.memoizedState,fiber=fiber!==null?fiber.dehydrated:null,!fiber)throw Error(formatProdErrorMessage(317));nextHydratableInstance=getNextHydratableInstanceAfterSuspenseInstance(fiber)}else if(tag===31){if(fiber=fiber.memoizedState,fiber=fiber!==null?fiber.dehydrated:null,!fiber)throw Error(formatProdErrorMessage(317));nextHydratableInstance=getNextHydratableInstanceAfterActivityInstance(fiber)}else nextHydratableInstance=supportsSingletons&&tag===27?getNextHydratableSiblingAfterSingleton(fiber.type,nextHydratableInstance):hydrationParentFiber?getNextHydratableSibling(fiber.stateNode):null;return!0}function resetHydrationState(){supportsHydration&&(nextHydratableInstance=hydrationParentFiber=null,isHydrating=!1)}function upgradeHydrationErrorsToRecoverable(){var queuedErrors=hydrationErrors;return queuedErrors!==null&&(workInProgressRootRecoverableErrors===null?workInProgressRootRecoverableErrors=queuedErrors:workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors,queuedErrors),hydrationErrors=null),queuedErrors}function queueHydrationError(error){hydrationErrors===null?hydrationErrors=[error]:hydrationErrors.push(error)}function pushProvider(providerFiber,context,nextValue){isPrimaryRenderer?(push(valueCursor,context._currentValue),context._currentValue=nextValue):(push(valueCursor,context._currentValue2),context._currentValue2=nextValue)}function popProvider(context){var currentValue=valueCursor.current;isPrimaryRenderer?context._currentValue=currentValue:context._currentValue2=currentValue,pop(valueCursor)}function scheduleContextWorkOnParentPath(parent,renderLanes,propagationRoot){for(;parent!==null;){var alternate=parent.alternate;if((parent.childLanes&renderLanes)!==renderLanes?(parent.childLanes|=renderLanes,alternate!==null&&(alternate.childLanes|=renderLanes)):alternate!==null&&(alternate.childLanes&renderLanes)!==renderLanes&&(alternate.childLanes|=renderLanes),parent===propagationRoot)break;parent=parent.return}}function propagateContextChanges(workInProgress,contexts,renderLanes,forcePropagateEntireTree){var fiber=workInProgress.child;fiber!==null&&(fiber.return=workInProgress);for(;fiber!==null;){var list=fiber.dependencies;if(list!==null){var nextFiber=fiber.child;list=list.firstContext;a:for(;list!==null;){var dependency=list;list=fiber;for(var i=0;i<contexts.length;i++)if(dependency.context===contexts[i]){list.lanes|=renderLanes,dependency=list.alternate,dependency!==null&&(dependency.lanes|=renderLanes),scheduleContextWorkOnParentPath(list.return,renderLanes,workInProgress),forcePropagateEntireTree||(nextFiber=null);break a}list=dependency.next}}else if(fiber.tag===18){if(nextFiber=fiber.return,nextFiber===null)throw Error(formatProdErrorMessage(341));nextFiber.lanes|=renderLanes,list=nextFiber.alternate,list!==null&&(list.lanes|=renderLanes),scheduleContextWorkOnParentPath(nextFiber,renderLanes,workInProgress),nextFiber=null}else fiber.tag===13&&fiber.memoizedState!==null&&fiber.memoizedState.dehydrated===null?(fiber.lanes|=renderLanes,nextFiber=fiber.alternate,nextFiber!==null&&(nextFiber.lanes|=renderLanes),scheduleContextWorkOnParentPath(fiber.return,renderLanes,workInProgress),nextFiber=fiber.child,nextFiber=nextFiber!==null?nextFiber.sibling:null):nextFiber=fiber.child;if(nextFiber!==null)nextFiber.return=fiber;else for(nextFiber=fiber;nextFiber!==null;){if(nextFiber===workInProgress){nextFiber=null;break}if(fiber=nextFiber.sibling,fiber!==null){fiber.return=nextFiber.return,nextFiber=fiber;break}nextFiber=nextFiber.return}fiber=nextFiber}}function propagateParentContextChanges(current,workInProgress,renderLanes,forcePropagateEntireTree){current=null;for(var parent=workInProgress,isInsidePropagationBailout=!1;parent!==null;){if(!isInsidePropagationBailout){if((parent.flags&524288)!==0)isInsidePropagationBailout=!0;else if((parent.flags&262144)!==0)break}if(parent.tag===10){var currentParent=parent.alternate;if(currentParent===null)throw Error(formatProdErrorMessage(387));if(currentParent=currentParent.memoizedProps,currentParent!==null){var context=parent.type;objectIs(parent.pendingProps.value,currentParent.value)||(current!==null?current.push(context):current=[context])}}else if(parent===hostTransitionProviderCursor.current){if(currentParent=parent.alternate,currentParent===null)throw Error(formatProdErrorMessage(387));currentParent.memoizedState.memoizedState!==parent.memoizedState.memoizedState&&(current!==null?current.push(HostTransitionContext):current=[HostTransitionContext])}parent=parent.return}return current!==null&&propagateContextChanges(workInProgress,current,renderLanes,forcePropagateEntireTree),workInProgress.flags|=262144,current!==null}function checkIfContextChanged(currentDependencies){for(currentDependencies=currentDependencies.firstContext;currentDependencies!==null;){var context=currentDependencies.context;if(!objectIs(isPrimaryRenderer?context._currentValue:context._currentValue2,currentDependencies.memoizedValue))return!0;currentDependencies=currentDependencies.next}return!1}function prepareToReadContext(workInProgress){currentlyRenderingFiber$1=workInProgress,lastContextDependency=null,workInProgress=workInProgress.dependencies,workInProgress!==null&&(workInProgress.firstContext=null)}function readContext(context){return readContextForConsumer(currentlyRenderingFiber$1,context)}function readContextDuringReconciliation(consumer,context){return currentlyRenderingFiber$1===null&&prepareToReadContext(consumer),readContextForConsumer(consumer,context)}function readContextForConsumer(consumer,context){var value=isPrimaryRenderer?context._currentValue:context._currentValue2;if(context={context,memoizedValue:value,next:null},lastContextDependency===null){if(consumer===null)throw Error(formatProdErrorMessage(308));lastContextDependency=context,consumer.dependencies={lanes:0,firstContext:context},consumer.flags|=524288}else lastContextDependency=lastContextDependency.next=context;return value}function createCache(){return{controller:new AbortControllerLocal,data:new Map,refCount:0}}function releaseCache(cache){cache.refCount--,cache.refCount===0&&scheduleCallback$2(NormalPriority,function(){cache.controller.abort()})}function queueTransitionTypes(root,transitionTypes){if((root.pendingLanes&4194048)!==0){var queued=root.transitionTypes;queued===null&&(queued=root.transitionTypes=[]);for(root=0;root<transitionTypes.length;root++){var transitionType=transitionTypes[root];queued.indexOf(transitionType)===-1&&queued.push(transitionType)}}}function claimQueuedTransitionTypes(root){var claimed=root.transitionTypes;return root.transitionTypes=null,claimed}function noop$1(){}function ensureRootIsScheduled(root){root!==lastScheduledRoot&&root.next===null&&(lastScheduledRoot===null?firstScheduledRoot=lastScheduledRoot=root:lastScheduledRoot=lastScheduledRoot.next=root),mightHavePendingSyncWork=!0,didScheduleMicrotask||(didScheduleMicrotask=!0,scheduleImmediateRootScheduleTask())}function flushSyncWorkAcrossRoots_impl(syncTransitionLanes,onlyLegacy){if(!isFlushingWork&&mightHavePendingSyncWork){isFlushingWork=!0;do{var didPerformSomeWork=!1;for(var root=firstScheduledRoot;root!==null;){if(!onlyLegacy)if(syncTransitionLanes!==0){var pendingLanes=root.pendingLanes;if(pendingLanes===0)var JSCompiler_inline_result=0;else{var suspendedLanes=root.suspendedLanes,pingedLanes=root.pingedLanes;JSCompiler_inline_result=(1<<31-clz32(42|syncTransitionLanes)+1)-1,JSCompiler_inline_result&=pendingLanes&~(suspendedLanes&~pingedLanes),JSCompiler_inline_result=JSCompiler_inline_result&201326741?JSCompiler_inline_result&201326741|1:JSCompiler_inline_result?JSCompiler_inline_result|2:0}JSCompiler_inline_result!==0&&(didPerformSomeWork=!0,performSyncWorkOnRoot(root,JSCompiler_inline_result))}else JSCompiler_inline_result=workInProgressRootRenderLanes,JSCompiler_inline_result=getNextLanes(root,root===workInProgressRoot?JSCompiler_inline_result:0,root.cancelPendingCommit!==null||root.timeoutHandle!==noTimeout),(JSCompiler_inline_result&3)===0||checkIfRootIsPrerendering(root,JSCompiler_inline_result)||(didPerformSomeWork=!0,performSyncWorkOnRoot(root,JSCompiler_inline_result));root=root.next}}while(didPerformSomeWork);isFlushingWork=!1}}function processRootScheduleInImmediateTask(){processRootScheduleInMicrotask()}function processRootScheduleInMicrotask(){mightHavePendingSyncWork=didScheduleMicrotask=!1;var syncTransitionLanes=0;currentEventTransitionLane!==0&&shouldAttemptEagerTransition()&&(syncTransitionLanes=currentEventTransitionLane);for(var currentTime=now(),prev=null,root=firstScheduledRoot;root!==null;){var next=root.next,nextLanes=scheduleTaskForRootDuringMicrotask(root,currentTime);if(nextLanes===0)root.next=null,prev===null?firstScheduledRoot=next:prev.next=next,next===null&&(lastScheduledRoot=prev);else if(prev=root,syncTransitionLanes!==0||(nextLanes&3)!==0)mightHavePendingSyncWork=!0;root=next}pendingEffectsStatus!==0&&pendingEffectsStatus!==5||flushSyncWorkAcrossRoots_impl(syncTransitionLanes,!1),currentEventTransitionLane!==0&&(currentEventTransitionLane=0)}function scheduleTaskForRootDuringMicrotask(root,currentTime){for(var{suspendedLanes,pingedLanes,expirationTimes}=root,lanes=root.pendingLanes&-62914561;0<lanes;){var index$3=31-clz32(lanes),lane=1<<index$3,expirationTime=expirationTimes[index$3];if(expirationTime===-1){if((lane&suspendedLanes)===0||(lane&pingedLanes)!==0)expirationTimes[index$3]=computeExpirationTime(lane,currentTime)}else expirationTime<=currentTime&&(root.expiredLanes|=lane);lanes&=~lane}if(currentTime=workInProgressRoot,suspendedLanes=workInProgressRootRenderLanes,suspendedLanes=getNextLanes(root,root===currentTime?suspendedLanes:0,root.cancelPendingCommit!==null||root.timeoutHandle!==noTimeout),pingedLanes=root.callbackNode,suspendedLanes===0||root===currentTime&&(workInProgressSuspendedReason===2||workInProgressSuspendedReason===9)||root.cancelPendingCommit!==null)return pingedLanes!==null&&pingedLanes!==null&&cancelCallback$1(pingedLanes),root.callbackNode=null,root.callbackPriority=0;if((suspendedLanes&3)===0||checkIfRootIsPrerendering(root,suspendedLanes)){if(currentTime=suspendedLanes&-suspendedLanes,currentTime===root.callbackPriority)return currentTime;switch(pingedLanes!==null&&cancelCallback$1(pingedLanes),lanesToEventPriority(suspendedLanes)){case 2:case 8:suspendedLanes=UserBlockingPriority;break;case 32:suspendedLanes=NormalPriority$1;break;case 268435456:suspendedLanes=IdlePriority;break;default:suspendedLanes=NormalPriority$1}return pingedLanes=performWorkOnRootViaSchedulerTask.bind(null,root),suspendedLanes=scheduleCallback$3(suspendedLanes,pingedLanes),root.callbackPriority=currentTime,root.callbackNode=suspendedLanes,currentTime}return pingedLanes!==null&&pingedLanes!==null&&cancelCallback$1(pingedLanes),root.callbackPriority=2,root.callbackNode=null,2}function performWorkOnRootViaSchedulerTask(root,didTimeout){if(pendingEffectsStatus!==0&&pendingEffectsStatus!==5)return root.callbackNode=null,root.callbackPriority=0,null;var originalCallbackNode=root.callbackNode;if(flushPendingEffects()&&root.callbackNode!==originalCallbackNode)return null;var workInProgressRootRenderLanes$jscomp$0=workInProgressRootRenderLanes;if(workInProgressRootRenderLanes$jscomp$0=getNextLanes(root,root===workInProgressRoot?workInProgressRootRenderLanes$jscomp$0:0,root.cancelPendingCommit!==null||root.timeoutHandle!==noTimeout),workInProgressRootRenderLanes$jscomp$0===0)return null;return performWorkOnRoot(root,workInProgressRootRenderLanes$jscomp$0,didTimeout),scheduleTaskForRootDuringMicrotask(root,now()),root.callbackNode!=null&&root.callbackNode===originalCallbackNode?performWorkOnRootViaSchedulerTask.bind(null,root):null}function performSyncWorkOnRoot(root,lanes){if(flushPendingEffects())return null;performWorkOnRoot(root,lanes,!0)}function scheduleImmediateRootScheduleTask(){supportsMicrotasks?scheduleMicrotask(function(){(executionContext&6)!==0?scheduleCallback$3(ImmediatePriority,processRootScheduleInImmediateTask):processRootScheduleInMicrotask()}):scheduleCallback$3(ImmediatePriority,processRootScheduleInImmediateTask)}function requestTransitionLane(){if(currentEventTransitionLane===0){var actionScopeLane=currentEntangledLane;actionScopeLane===0&&(actionScopeLane=nextTransitionUpdateLane,nextTransitionUpdateLane<<=1,(nextTransitionUpdateLane&261888)===0&&(nextTransitionUpdateLane=256)),currentEventTransitionLane=actionScopeLane}return currentEventTransitionLane}function entangleAsyncAction(transition,thenable){if(currentEntangledListeners===null){var entangledListeners=currentEntangledListeners=[];currentEntangledPendingCount=0,currentEntangledLane=requestTransitionLane(),currentEntangledActionThenable={status:"pending",value:void 0,then:function(resolve){entangledListeners.push(resolve)}}}return currentEntangledPendingCount++,thenable.then(pingEngtangledActionScope,pingEngtangledActionScope),thenable}function pingEngtangledActionScope(){if(--currentEntangledPendingCount===0&&(entangledTransitionTypes=null,currentEntangledListeners!==null)){currentEntangledActionThenable!==null&&(currentEntangledActionThenable.status="fulfilled");var listeners=currentEntangledListeners;currentEntangledListeners=null,currentEntangledLane=0,currentEntangledActionThenable=null;for(var i=0;i<listeners.length;i++)(0,listeners[i])()}}function chainThenableValue(thenable,result){var listeners=[],thenableWithOverride={status:"pending",value:null,reason:null,then:function(resolve){listeners.push(resolve)}};return thenable.then(function(){thenableWithOverride.status="fulfilled",thenableWithOverride.value=result;for(var i=0;i<listeners.length;i++)(0,listeners[i])(result)},function(error){thenableWithOverride.status="rejected",thenableWithOverride.reason=error;for(error=0;error<listeners.length;error++)(0,listeners[error])(void 0)}),thenableWithOverride}function peekCacheFromPool(){var cacheResumedFromPreviousRender=resumedCache.current;return cacheResumedFromPreviousRender!==null?cacheResumedFromPreviousRender:workInProgressRoot.pooledCache}function pushTransition(offscreenWorkInProgress,prevCachePool){prevCachePool===null?push(resumedCache,resumedCache.current):push(resumedCache,prevCachePool.pool)}function getSuspendedCache(){var cacheFromPool=peekCacheFromPool();return cacheFromPool===null?null:{parent:isPrimaryRenderer?CacheContext._currentValue:CacheContext._currentValue2,pool:cacheFromPool}}function shallowEqual(objA,objB){if(objectIs(objA,objB))return!0;if(typeof objA!=="object"||objA===null||typeof objB!=="object"||objB===null)return!1;var keysA=Object.keys(objA),keysB=Object.keys(objB);if(keysA.length!==keysB.length)return!1;for(keysB=0;keysB<keysA.length;keysB++){var currentKey=keysA[keysB];if(!hasOwnProperty.call(objB,currentKey)||!objectIs(objA[currentKey],objB[currentKey]))return!1}return!0}function isThenableResolved(thenable){return thenable=thenable.status,thenable==="fulfilled"||thenable==="rejected"}function trackUsedThenable(thenableState,thenable,index){switch(index=thenableState[index],index===void 0?thenableState.push(thenable):index!==thenable&&(thenable.then(noop$1,noop$1),thenable=index),thenable.status){case"fulfilled":return thenable.value;case"rejected":if(thenableState=thenable.reason,checkIfUseWrappedInAsyncCatch(thenableState),thenableState===void 0&&!("reason"in thenable))throw Error(formatProdErrorMessage(600));throw thenableState;default:if(typeof thenable.status==="string")thenable.then(noop$1,noop$1);else{if(thenableState=workInProgressRoot,thenableState!==null&&100<thenableState.shellSuspendCounter)throw Error(formatProdErrorMessage(482));thenableState=thenable,thenableState.status="pending",thenableState.then(function(fulfilledValue){if(thenable.status==="pending"){var fulfilledThenable=thenable;fulfilledThenable.status="fulfilled",fulfilledThenable.value=fulfilledValue}},function(error){if(thenable.status==="pending"){var rejectedThenable=thenable;rejectedThenable.status="rejected",rejectedThenable.reason=error}})}switch(thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenableState=thenable.reason,checkIfUseWrappedInAsyncCatch(thenableState),thenableState}throw suspendedThenable=thenable,SuspenseException}}function resolveLazy(lazyType){try{var init=lazyType._init;return init(lazyType._payload)}catch(x){if(x!==null&&typeof x==="object"&&typeof x.then==="function")throw suspendedThenable=x,SuspenseException;throw x}}function getSuspendedThenable(){if(suspendedThenable===null)throw Error(formatProdErrorMessage(459));var thenable=suspendedThenable;return suspendedThenable=null,thenable}function checkIfUseWrappedInAsyncCatch(rejectedReason){if(rejectedReason===SuspenseException||rejectedReason===SuspenseActionException)throw Error(formatProdErrorMessage(483))}function unwrapThenable(thenable){var index=thenableIndexCounter$1;return thenableIndexCounter$1+=1,thenableState$1===null&&(thenableState$1=[]),trackUsedThenable(thenableState$1,thenable,index)}function coerceRef(workInProgress,element){element=element.props.ref,workInProgress.ref=element!==void 0?element:null}function throwOnInvalidObjectTypeImpl(returnFiber,newChild){if(newChild.$$typeof===REACT_LEGACY_ELEMENT_TYPE)throw Error(formatProdErrorMessage(525));throw returnFiber=Object.prototype.toString.call(newChild),Error(formatProdErrorMessage(31,returnFiber==="[object Object]"?"object with keys {"+Object.keys(newChild).join(", ")+"}":returnFiber))}function createChildReconciler(shouldTrackSideEffects){function deleteChild(returnFiber,childToDelete){if(shouldTrackSideEffects){var deletions=returnFiber.deletions;deletions===null?(returnFiber.deletions=[childToDelete],returnFiber.flags|=16):deletions.push(childToDelete)}}function deleteRemainingChildren(returnFiber,currentFirstChild){if(!shouldTrackSideEffects)return null;for(;currentFirstChild!==null;)deleteChild(returnFiber,currentFirstChild),currentFirstChild=currentFirstChild.sibling;return null}function mapRemainingChildren(currentFirstChild){for(var existingChildren=new Map;currentFirstChild!==null;)currentFirstChild.key===null?existingChildren.set(currentFirstChild.index,currentFirstChild):existingChildren.set(currentFirstChild.key,currentFirstChild),currentFirstChild=currentFirstChild.sibling;return existingChildren}function useFiber(fiber,pendingProps){return fiber=createWorkInProgress(fiber,pendingProps),fiber.index=0,fiber.sibling=null,fiber}function placeChild(newFiber,lastPlacedIndex,newIndex){if(newFiber.index=newIndex,!shouldTrackSideEffects)return newFiber.flags|=1048576,lastPlacedIndex;if(newIndex=newFiber.alternate,newIndex!==null)return newIndex=newIndex.index,newIndex<lastPlacedIndex?(newFiber.flags|=2,lastPlacedIndex):newIndex;return newFiber.flags|=134217730,lastPlacedIndex}function placeSingleChild(newFiber){return shouldTrackSideEffects&&newFiber.alternate===null&&(newFiber.flags|=134217730),newFiber}function updateTextNode(returnFiber,current,textContent,lanes){if(current===null||current.tag!==6)return current=createFiberFromText(textContent,returnFiber.mode,lanes),current.return=returnFiber,current;return current=useFiber(current,textContent),current.return=returnFiber,current}function updateElement(returnFiber,current,element,lanes){var elementType=element.type;if(elementType===REACT_FRAGMENT_TYPE)return returnFiber=updateFragment(returnFiber,current,element.props.children,lanes,element.key),coerceRef(returnFiber,element),returnFiber;if(current!==null&&(current.elementType===elementType||typeof elementType==="object"&&elementType!==null&&elementType.$$typeof===REACT_LAZY_TYPE&&resolveLazy(elementType)===current.type))return current=useFiber(current,element.props),coerceRef(current,element),current.return=returnFiber,current;return current=createFiberFromTypeAndProps(element.type,element.key,element.props,null,returnFiber.mode,lanes),coerceRef(current,element),current.return=returnFiber,current}function updatePortal(returnFiber,current,portal,lanes){if(current===null||current.tag!==4||current.stateNode.containerInfo!==portal.containerInfo||current.stateNode.implementation!==portal.implementation)return current=createFiberFromPortal(portal,returnFiber.mode,lanes),current.return=returnFiber,current;return current=useFiber(current,portal.children||[]),current.return=returnFiber,current}function updateFragment(returnFiber,current,fragment,lanes,key){if(current===null||current.tag!==7)return current=createFiberFromFragment(fragment,returnFiber.mode,lanes,key),current.return=returnFiber,current;return current=useFiber(current,fragment),current.return=returnFiber,current}function createChild(returnFiber,newChild,lanes){if(typeof newChild==="string"&&newChild!==""||typeof newChild==="number"||typeof newChild==="bigint")return newChild=createFiberFromText(""+newChild,returnFiber.mode,lanes),newChild.return=returnFiber,newChild;if(typeof newChild==="object"&&newChild!==null){switch(newChild.$$typeof){case REACT_ELEMENT_TYPE:return lanes=createFiberFromTypeAndProps(newChild.type,newChild.key,newChild.props,null,returnFiber.mode,lanes),coerceRef(lanes,newChild),lanes.return=returnFiber,lanes;case REACT_PORTAL_TYPE:return newChild=createFiberFromPortal(newChild,returnFiber.mode,lanes),newChild.return=returnFiber,newChild;case REACT_LAZY_TYPE:return newChild=resolveLazy(newChild),createChild(returnFiber,newChild,lanes)}if(isArrayImpl(newChild)||getIteratorFn(newChild))return newChild=createFiberFromFragment(newChild,returnFiber.mode,lanes,null),newChild.return=returnFiber,newChild;if(typeof newChild.then==="function")return createChild(returnFiber,unwrapThenable(newChild),lanes);if(newChild.$$typeof===REACT_CONTEXT_TYPE)return createChild(returnFiber,readContextDuringReconciliation(returnFiber,newChild),lanes);throwOnInvalidObjectTypeImpl(returnFiber,newChild)}return null}function updateSlot(returnFiber,oldFiber,newChild,lanes){var key=oldFiber!==null?oldFiber.key:null;if(typeof newChild==="string"&&newChild!==""||typeof newChild==="number"||typeof newChild==="bigint")return key!==null?null:updateTextNode(returnFiber,oldFiber,""+newChild,lanes);if(typeof newChild==="object"&&newChild!==null){switch(newChild.$$typeof){case REACT_ELEMENT_TYPE:return newChild.key===key?updateElement(returnFiber,oldFiber,newChild,lanes):null;case REACT_PORTAL_TYPE:return newChild.key===key?updatePortal(returnFiber,oldFiber,newChild,lanes):null;case REACT_LAZY_TYPE:return newChild=resolveLazy(newChild),updateSlot(returnFiber,oldFiber,newChild,lanes)}if(isArrayImpl(newChild)||getIteratorFn(newChild))return key!==null?null:updateFragment(returnFiber,oldFiber,newChild,lanes,null);if(typeof newChild.then==="function")return updateSlot(returnFiber,oldFiber,unwrapThenable(newChild),lanes);if(newChild.$$typeof===REACT_CONTEXT_TYPE)return updateSlot(returnFiber,oldFiber,readContextDuringReconciliation(returnFiber,newChild),lanes);throwOnInvalidObjectTypeImpl(returnFiber,newChild)}return null}function updateFromMap(existingChildren,returnFiber,newIdx,newChild,lanes){if(typeof newChild==="string"&&newChild!==""||typeof newChild==="number"||typeof newChild==="bigint")return existingChildren=existingChildren.get(newIdx)||null,updateTextNode(returnFiber,existingChildren,""+newChild,lanes);if(typeof newChild==="object"&&newChild!==null){switch(newChild.$$typeof){case REACT_ELEMENT_TYPE:return existingChildren=existingChildren.get(newChild.key===null?newIdx:newChild.key)||null,updateElement(returnFiber,existingChildren,newChild,lanes);case REACT_PORTAL_TYPE:return existingChildren=existingChildren.get(newChild.key===null?newIdx:newChild.key)||null,updatePortal(returnFiber,existingChildren,newChild,lanes);case REACT_LAZY_TYPE:return newChild=resolveLazy(newChild),updateFromMap(existingChildren,returnFiber,newIdx,newChild,lanes)}if(isArrayImpl(newChild)||getIteratorFn(newChild))return existingChildren=existingChildren.get(newIdx)||null,updateFragment(returnFiber,existingChildren,newChild,lanes,null);if(typeof newChild.then==="function")return updateFromMap(existingChildren,returnFiber,newIdx,unwrapThenable(newChild),lanes);if(newChild.$$typeof===REACT_CONTEXT_TYPE)return updateFromMap(existingChildren,returnFiber,newIdx,readContextDuringReconciliation(returnFiber,newChild),lanes);throwOnInvalidObjectTypeImpl(returnFiber,newChild)}return null}function reconcileChildrenArray(returnFiber,currentFirstChild,newChildren,lanes){for(var resultingFirstChild=null,previousNewFiber=null,oldFiber=currentFirstChild,newIdx=currentFirstChild=0,nextOldFiber=null;oldFiber!==null&&newIdx<newChildren.length;newIdx++){oldFiber.index>newIdx?(nextOldFiber=oldFiber,oldFiber=null):nextOldFiber=oldFiber.sibling;var newFiber=updateSlot(returnFiber,oldFiber,newChildren[newIdx],lanes);if(newFiber===null){oldFiber===null&&(oldFiber=nextOldFiber);break}shouldTrackSideEffects&&oldFiber&&newFiber.alternate===null&&deleteChild(returnFiber,oldFiber),currentFirstChild=placeChild(newFiber,currentFirstChild,newIdx),previousNewFiber===null?resultingFirstChild=newFiber:previousNewFiber.sibling=newFiber,previousNewFiber=newFiber,oldFiber=nextOldFiber}if(newIdx===newChildren.length)return deleteRemainingChildren(returnFiber,oldFiber),isHydrating&&pushTreeFork(returnFiber,newIdx),resultingFirstChild;if(oldFiber===null){for(;newIdx<newChildren.length;newIdx++)oldFiber=createChild(returnFiber,newChildren[newIdx],lanes),oldFiber!==null&&(currentFirstChild=placeChild(oldFiber,currentFirstChild,newIdx),previousNewFiber===null?resultingFirstChild=oldFiber:previousNewFiber.sibling=oldFiber,previousNewFiber=oldFiber);return isHydrating&&pushTreeFork(returnFiber,newIdx),resultingFirstChild}for(oldFiber=mapRemainingChildren(oldFiber);newIdx<newChildren.length;newIdx++)nextOldFiber=updateFromMap(oldFiber,returnFiber,newIdx,newChildren[newIdx],lanes),nextOldFiber!==null&&(shouldTrackSideEffects&&(newFiber=nextOldFiber.alternate,newFiber!==null&&oldFiber.delete(newFiber.key===null?newIdx:newFiber.key)),currentFirstChild=placeChild(nextOldFiber,currentFirstChild,newIdx),previousNewFiber===null?resultingFirstChild=nextOldFiber:previousNewFiber.sibling=nextOldFiber,previousNewFiber=nextOldFiber);return shouldTrackSideEffects&&oldFiber.forEach(function(child){return deleteChild(returnFiber,child)}),isHydrating&&pushTreeFork(returnFiber,newIdx),resultingFirstChild}function reconcileChildrenIterator(returnFiber,currentFirstChild,newChildren,lanes){if(newChildren==null)throw Error(formatProdErrorMessage(151));for(var resultingFirstChild=null,previousNewFiber=null,oldFiber=currentFirstChild,newIdx=currentFirstChild=0,nextOldFiber=null,step=newChildren.next();oldFiber!==null&&!step.done;newIdx++,step=newChildren.next()){oldFiber.index>newIdx?(nextOldFiber=oldFiber,oldFiber=null):nextOldFiber=oldFiber.sibling;var newFiber=updateSlot(returnFiber,oldFiber,step.value,lanes);if(newFiber===null){oldFiber===null&&(oldFiber=nextOldFiber);break}shouldTrackSideEffects&&oldFiber&&newFiber.alternate===null&&deleteChild(returnFiber,oldFiber),currentFirstChild=placeChild(newFiber,currentFirstChild,newIdx),previousNewFiber===null?resultingFirstChild=newFiber:previousNewFiber.sibling=newFiber,previousNewFiber=newFiber,oldFiber=nextOldFiber}if(step.done)return deleteRemainingChildren(returnFiber,oldFiber),isHydrating&&pushTreeFork(returnFiber,newIdx),resultingFirstChild;if(oldFiber===null){for(;!step.done;newIdx++,step=newChildren.next())step=createChild(returnFiber,step.value,lanes),step!==null&&(currentFirstChild=placeChild(step,currentFirstChild,newIdx),previousNewFiber===null?resultingFirstChild=step:previousNewFiber.sibling=step,previousNewFiber=step);return isHydrating&&pushTreeFork(returnFiber,newIdx),resultingFirstChild}for(oldFiber=mapRemainingChildren(oldFiber);!step.done;newIdx++,step=newChildren.next())step=updateFromMap(oldFiber,returnFiber,newIdx,step.value,lanes),step!==null&&(shouldTrackSideEffects&&(nextOldFiber=step.alternate,nextOldFiber!==null&&oldFiber.delete(nextOldFiber.key===null?newIdx:nextOldFiber.key)),currentFirstChild=placeChild(step,currentFirstChild,newIdx),previousNewFiber===null?resultingFirstChild=step:previousNewFiber.sibling=step,previousNewFiber=step);return shouldTrackSideEffects&&oldFiber.forEach(function(child){return deleteChild(returnFiber,child)}),isHydrating&&pushTreeFork(returnFiber,newIdx),resultingFirstChild}function reconcileChildFibersImpl(returnFiber,currentFirstChild,newChild,lanes){if(typeof newChild==="object"&&newChild!==null&&newChild.type===REACT_FRAGMENT_TYPE&&newChild.key===null&&newChild.props.ref===void 0&&(newChild=newChild.props.children),typeof newChild==="object"&&newChild!==null){switch(newChild.$$typeof){case REACT_ELEMENT_TYPE:a:{for(var key=newChild.key;currentFirstChild!==null;){if(currentFirstChild.key===key){if(key=newChild.type,key===REACT_FRAGMENT_TYPE){if(currentFirstChild.tag===7){deleteRemainingChildren(returnFiber,currentFirstChild.sibling),lanes=useFiber(currentFirstChild,newChild.props.children),coerceRef(lanes,newChild),lanes.return=returnFiber,returnFiber=lanes;break a}}else if(currentFirstChild.elementType===key||typeof key==="object"&&key!==null&&key.$$typeof===REACT_LAZY_TYPE&&resolveLazy(key)===currentFirstChild.type){deleteRemainingChildren(returnFiber,currentFirstChild.sibling),lanes=useFiber(currentFirstChild,newChild.props),coerceRef(lanes,newChild),lanes.return=returnFiber,returnFiber=lanes;break a}deleteRemainingChildren(returnFiber,currentFirstChild);break}else deleteChild(returnFiber,currentFirstChild);currentFirstChild=currentFirstChild.sibling}newChild.type===REACT_FRAGMENT_TYPE?(lanes=createFiberFromFragment(newChild.props.children,returnFiber.mode,lanes,newChild.key),coerceRef(lanes,newChild),lanes.return=returnFiber,returnFiber=lanes):(lanes=createFiberFromTypeAndProps(newChild.type,newChild.key,newChild.props,null,returnFiber.mode,lanes),coerceRef(lanes,newChild),lanes.return=returnFiber,returnFiber=lanes)}return placeSingleChild(returnFiber);case REACT_PORTAL_TYPE:a:{for(key=newChild.key;currentFirstChild!==null;){if(currentFirstChild.key===key)if(currentFirstChild.tag===4&&currentFirstChild.stateNode.containerInfo===newChild.containerInfo&&currentFirstChild.stateNode.implementation===newChild.implementation){deleteRemainingChildren(returnFiber,currentFirstChild.sibling),lanes=useFiber(currentFirstChild,newChild.children||[]),lanes.return=returnFiber,returnFiber=lanes;break a}else{deleteRemainingChildren(returnFiber,currentFirstChild);break}else deleteChild(returnFiber,currentFirstChild);currentFirstChild=currentFirstChild.sibling}lanes=createFiberFromPortal(newChild,returnFiber.mode,lanes),lanes.return=returnFiber,returnFiber=lanes}return placeSingleChild(returnFiber);case REACT_LAZY_TYPE:return newChild=resolveLazy(newChild),reconcileChildFibersImpl(returnFiber,currentFirstChild,newChild,lanes)}if(isArrayImpl(newChild))return reconcileChildrenArray(returnFiber,currentFirstChild,newChild,lanes);if(getIteratorFn(newChild)){if(key=getIteratorFn(newChild),typeof key!=="function")throw Error(formatProdErrorMessage(150));return newChild=key.call(newChild),reconcileChildrenIterator(returnFiber,currentFirstChild,newChild,lanes)}if(typeof newChild.then==="function")return reconcileChildFibersImpl(returnFiber,currentFirstChild,unwrapThenable(newChild),lanes);if(newChild.$$typeof===REACT_CONTEXT_TYPE)return reconcileChildFibersImpl(returnFiber,currentFirstChild,readContextDuringReconciliation(returnFiber,newChild),lanes);throwOnInvalidObjectTypeImpl(returnFiber,newChild)}return typeof newChild==="string"&&newChild!==""||typeof newChild==="number"||typeof newChild==="bigint"?(newChild=""+newChild,currentFirstChild!==null&&currentFirstChild.tag===6?(deleteRemainingChildren(returnFiber,currentFirstChild.sibling),lanes=useFiber(currentFirstChild,newChild),lanes.return=returnFiber,returnFiber=lanes):(deleteRemainingChildren(returnFiber,currentFirstChild),lanes=createFiberFromText(newChild,returnFiber.mode,lanes),lanes.return=returnFiber,returnFiber=lanes),placeSingleChild(returnFiber)):deleteRemainingChildren(returnFiber,currentFirstChild)}return function(returnFiber,currentFirstChild,newChild,lanes){try{thenableIndexCounter$1=0;var firstChildFiber=reconcileChildFibersImpl(returnFiber,currentFirstChild,newChild,lanes);return thenableState$1=null,firstChildFiber}catch(x){if(x===SuspenseException||x===SuspenseActionException)throw x;var fiber=createFiber(29,x,null,returnFiber.mode);return fiber.lanes=lanes,fiber.return=returnFiber,fiber}finally{}}}function finishQueueingConcurrentUpdates(){for(var endIndex=concurrentQueuesIndex,i=concurrentlyUpdatedLanes=concurrentQueuesIndex=0;i<endIndex;){var fiber=concurrentQueues[i];concurrentQueues[i++]=null;var queue=concurrentQueues[i];concurrentQueues[i++]=null;var update=concurrentQueues[i];concurrentQueues[i++]=null;var lane=concurrentQueues[i];if(concurrentQueues[i++]=null,queue!==null&&update!==null){var pending=queue.pending;pending===null?update.next=update:(update.next=pending.next,pending.next=update),queue.pending=update}lane!==0&&markUpdateLaneFromFiberToRoot(fiber,update,lane)}}function enqueueUpdate$1(fiber,queue,update,lane){concurrentQueues[concurrentQueuesIndex++]=fiber,concurrentQueues[concurrentQueuesIndex++]=queue,concurrentQueues[concurrentQueuesIndex++]=update,concurrentQueues[concurrentQueuesIndex++]=lane,concurrentlyUpdatedLanes|=lane,fiber.lanes|=lane,fiber=fiber.alternate,fiber!==null&&(fiber.lanes|=lane)}function enqueueConcurrentHookUpdate(fiber,queue,update,lane){return enqueueUpdate$1(fiber,queue,update,lane),getRootForUpdatedFiber(fiber)}function enqueueConcurrentRenderForLane(fiber,lane){return enqueueUpdate$1(fiber,null,null,lane),getRootForUpdatedFiber(fiber)}function markUpdateLaneFromFiberToRoot(sourceFiber,update,lane){sourceFiber.lanes|=lane;var alternate=sourceFiber.alternate;alternate!==null&&(alternate.lanes|=lane);for(var isHidden=!1,parent=sourceFiber.return;parent!==null;)parent.childLanes|=lane,alternate=parent.alternate,alternate!==null&&(alternate.childLanes|=lane),parent.tag===22&&(sourceFiber=parent.stateNode,sourceFiber===null||sourceFiber._visibility&1||(isHidden=!0)),sourceFiber=parent,parent=parent.return;return sourceFiber.tag===3?(parent=sourceFiber.stateNode,isHidden&&update!==null&&(isHidden=31-clz32(lane),sourceFiber=parent.hiddenUpdates,alternate=sourceFiber[isHidden],alternate===null?sourceFiber[isHidden]=[update]:alternate.push(update),update.lane=lane|536870912),parent):null}function getRootForUpdatedFiber(sourceFiber){if(50<nestedUpdateCount)throw nestedUpdateCount=0,rootWithNestedUpdates=null,Error(formatProdErrorMessage(185));for(var parent=sourceFiber.return;parent!==null;)sourceFiber=parent,parent=sourceFiber.return;return sourceFiber.tag===3?sourceFiber.stateNode:null}function initializeUpdateQueue(fiber){fiber.updateQueue={baseState:fiber.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function cloneUpdateQueue(current,workInProgress){current=current.updateQueue,workInProgress.updateQueue===current&&(workInProgress.updateQueue={baseState:current.baseState,firstBaseUpdate:current.firstBaseUpdate,lastBaseUpdate:current.lastBaseUpdate,shared:current.shared,callbacks:null})}function createUpdate(lane){return{lane,tag:0,payload:null,callback:null,next:null}}function enqueueUpdate(fiber,update,lane){var updateQueue=fiber.updateQueue;if(updateQueue===null)return null;if(updateQueue=updateQueue.shared,(executionContext&2)!==0){var pending=updateQueue.pending;return pending===null?update.next=update:(update.next=pending.next,pending.next=update),updateQueue.pending=update,update=getRootForUpdatedFiber(fiber),markUpdateLaneFromFiberToRoot(fiber,null,lane),update}return enqueueUpdate$1(fiber,updateQueue,update,lane),getRootForUpdatedFiber(fiber)}function entangleTransitions(root,fiber,lane){if(fiber=fiber.updateQueue,fiber!==null&&(fiber=fiber.shared,(lane&4194048)!==0)){var queueLanes=fiber.lanes;queueLanes&=root.pendingLanes,lane|=queueLanes,fiber.lanes=lane,markRootEntangled(root,lane)}}function enqueueCapturedUpdate(workInProgress,capturedUpdate){var queue=workInProgress.updateQueue,current=workInProgress.alternate;if(current!==null&&(current=current.updateQueue,queue===current)){var newFirst=null,newLast=null;if(queue=queue.firstBaseUpdate,queue!==null){do{var clone={lane:queue.lane,tag:queue.tag,payload:queue.payload,callback:null,next:null};newLast===null?newFirst=newLast=clone:newLast=newLast.next=clone,queue=queue.next}while(queue!==null);newLast===null?newFirst=newLast=capturedUpdate:newLast=newLast.next=capturedUpdate}else newFirst=newLast=capturedUpdate;queue={baseState:current.baseState,firstBaseUpdate:newFirst,lastBaseUpdate:newLast,shared:current.shared,callbacks:current.callbacks},workInProgress.updateQueue=queue;return}workInProgress=queue.lastBaseUpdate,workInProgress===null?queue.firstBaseUpdate=capturedUpdate:workInProgress.next=capturedUpdate,queue.lastBaseUpdate=capturedUpdate}function suspendIfUpdateReadFromEntangledAsyncAction(){if(didReadFromEntangledAsyncAction){var entangledActionThenable=currentEntangledActionThenable;if(entangledActionThenable!==null)throw entangledActionThenable}}function processUpdateQueue(workInProgress$jscomp$0,props,instance$jscomp$0,renderLanes){didReadFromEntangledAsyncAction=!1;var queue=workInProgress$jscomp$0.updateQueue;hasForceUpdate=!1;var{firstBaseUpdate,lastBaseUpdate}=queue,pendingQueue=queue.shared.pending;if(pendingQueue!==null){queue.shared.pending=null;var lastPendingUpdate=pendingQueue,firstPendingUpdate=lastPendingUpdate.next;lastPendingUpdate.next=null,lastBaseUpdate===null?firstBaseUpdate=firstPendingUpdate:lastBaseUpdate.next=firstPendingUpdate,lastBaseUpdate=lastPendingUpdate;var current=workInProgress$jscomp$0.alternate;current!==null&&(current=current.updateQueue,pendingQueue=current.lastBaseUpdate,pendingQueue!==lastBaseUpdate&&(pendingQueue===null?current.firstBaseUpdate=firstPendingUpdate:pendingQueue.next=firstPendingUpdate,current.lastBaseUpdate=lastPendingUpdate))}if(firstBaseUpdate!==null){var newState=queue.baseState;lastBaseUpdate=0,current=firstPendingUpdate=lastPendingUpdate=null,pendingQueue=firstBaseUpdate;do{var updateLane=pendingQueue.lane&-536870913,isHiddenUpdate=updateLane!==pendingQueue.lane;if(isHiddenUpdate?(workInProgressRootRenderLanes&updateLane)===updateLane:(renderLanes&updateLane)===updateLane){updateLane!==0&&updateLane===currentEntangledLane&&(didReadFromEntangledAsyncAction=!0),current!==null&&(current=current.next={lane:0,tag:pendingQueue.tag,payload:pendingQueue.payload,callback:null,next:null});a:{var workInProgress=workInProgress$jscomp$0,update=pendingQueue;updateLane=props;var instance=instance$jscomp$0;switch(update.tag){case 1:if(workInProgress=update.payload,typeof workInProgress==="function"){newState=workInProgress.call(instance,newState,updateLane);break a}newState=workInProgress;break a;case 3:workInProgress.flags=workInProgress.flags&-65537|128;case 0:if(workInProgress=update.payload,updateLane=typeof workInProgress==="function"?workInProgress.call(instance,newState,updateLane):workInProgress,updateLane===null||updateLane===void 0)break a;newState=assign({},newState,updateLane);break a;case 2:hasForceUpdate=!0}}updateLane=pendingQueue.callback,updateLane!==null&&(workInProgress$jscomp$0.flags|=64,isHiddenUpdate&&(workInProgress$jscomp$0.flags|=8192),isHiddenUpdate=queue.callbacks,isHiddenUpdate===null?queue.callbacks=[updateLane]:isHiddenUpdate.push(updateLane))}else isHiddenUpdate={lane:updateLane,tag:pendingQueue.tag,payload:pendingQueue.payload,callback:pendingQueue.callback,next:null},current===null?(firstPendingUpdate=current=isHiddenUpdate,lastPendingUpdate=newState):current=current.next=isHiddenUpdate,lastBaseUpdate|=updateLane;if(pendingQueue=pendingQueue.next,pendingQueue===null)if(pendingQueue=queue.shared.pending,pendingQueue===null)break;else isHiddenUpdate=pendingQueue,pendingQueue=isHiddenUpdate.next,isHiddenUpdate.next=null,queue.lastBaseUpdate=isHiddenUpdate,queue.shared.pending=null}while(1);current===null&&(lastPendingUpdate=newState),queue.baseState=lastPendingUpdate,queue.firstBaseUpdate=firstPendingUpdate,queue.lastBaseUpdate=current,firstBaseUpdate===null&&(queue.shared.lanes=0),workInProgressRootSkippedLanes|=lastBaseUpdate,workInProgress$jscomp$0.lanes=lastBaseUpdate,workInProgress$jscomp$0.memoizedState=newState}}function callCallback(callback,context){if(typeof callback!=="function")throw Error(formatProdErrorMessage(191,callback));callback.call(context)}function commitCallbacks(updateQueue,context){var callbacks=updateQueue.callbacks;if(callbacks!==null)for(updateQueue.callbacks=null,updateQueue=0;updateQueue<callbacks.length;updateQueue++)callCallback(callbacks[updateQueue],context)}function pushHiddenContext(fiber,context){fiber=entangledRenderLanes,push(prevEntangledRenderLanesCursor,fiber),push(currentTreeHiddenStackCursor,context),entangledRenderLanes=fiber|context.baseLanes}function reuseHiddenContextOnStack(){push(prevEntangledRenderLanesCursor,entangledRenderLanes),push(currentTreeHiddenStackCursor,currentTreeHiddenStackCursor.current)}function popHiddenContext(){entangledRenderLanes=prevEntangledRenderLanesCursor.current,pop(currentTreeHiddenStackCursor),pop(prevEntangledRenderLanesCursor)}function pushPrimaryTreeSuspenseHandler(handler){var current=handler.alternate;push(suspenseStackCursor,suspenseStackCursor.current&1),push(suspenseHandlerStackCursor,handler),shellBoundary===null&&(current===null||currentTreeHiddenStackCursor.current!==null?shellBoundary=handler:current.memoizedState!==null&&(shellBoundary=handler))}function pushDehydratedActivitySuspenseHandler(fiber){push(suspenseStackCursor,suspenseStackCursor.current),push(suspenseHandlerStackCursor,fiber),shellBoundary===null&&(shellBoundary=fiber)}function pushOffscreenSuspenseHandler(fiber){fiber.tag===22?(push(suspenseStackCursor,suspenseStackCursor.current),push(suspenseHandlerStackCursor,fiber),shellBoundary===null&&(shellBoundary=fiber)):reuseSuspenseHandlerOnStack()}function reuseSuspenseHandlerOnStack(){push(suspenseStackCursor,suspenseStackCursor.current),push(suspenseHandlerStackCursor,suspenseHandlerStackCursor.current)}function popSuspenseHandler(fiber){pop(suspenseHandlerStackCursor),shellBoundary===fiber&&(shellBoundary=null),pop(suspenseStackCursor)}function pushSuspenseListContext(fiber,newContext){push(suspenseHandlerStackCursor,suspenseHandlerStackCursor.current),push(suspenseStackCursor,newContext)}function popSuspenseListContext(fiber){pop(suspenseStackCursor),pop(suspenseHandlerStackCursor),shellBoundary===fiber&&(shellBoundary=null)}function findFirstSuspended(row){for(var node=row;node!==null;){if(node.tag===13){var state=node.memoizedState;if(state!==null&&(state=state.dehydrated,state===null||isSuspenseInstancePending(state)||isSuspenseInstanceFallback(state)))return node}else if(node.tag===19&&node.memoizedProps.revealOrder!=="independent"){if((node.flags&128)!==0)return node}else if(node.child!==null){node.child.return=node,node=node.child;continue}if(node===row)break;for(;node.sibling===null;){if(node.return===null||node.return===row)return null;node=node.return}node.sibling.return=node.return,node=node.sibling}return null}function throwInvalidHookError(){throw Error(formatProdErrorMessage(321))}function areHookInputsEqual(nextDeps,prevDeps){if(prevDeps===null)return!1;for(var i=0;i<prevDeps.length&&i<nextDeps.length;i++)if(!objectIs(nextDeps[i],prevDeps[i]))return!1;return!0}function renderWithHooks(current,workInProgress,Component,props,secondArg,nextRenderLanes){return renderLanes=nextRenderLanes,currentlyRenderingFiber=workInProgress,workInProgress.memoizedState=null,workInProgress.updateQueue=null,workInProgress.lanes=0,ReactSharedInternals.H=current===null||current.memoizedState===null?HooksDispatcherOnMount:HooksDispatcherOnUpdate,shouldDoubleInvokeUserFnsInHooksDEV=!1,nextRenderLanes=Component(props,secondArg),shouldDoubleInvokeUserFnsInHooksDEV=!1,didScheduleRenderPhaseUpdateDuringThisPass&&(nextRenderLanes=renderWithHooksAgain(workInProgress,Component,props,secondArg)),finishRenderingHooks(current),nextRenderLanes}function finishRenderingHooks(current){ReactSharedInternals.H=ContextOnlyDispatcher;var didRenderTooFewHooks=currentHook!==null&&currentHook.next!==null;if(renderLanes=0,workInProgressHook=currentHook=currentlyRenderingFiber=null,didScheduleRenderPhaseUpdate=!1,thenableIndexCounter=0,thenableState=null,didRenderTooFewHooks)throw Error(formatProdErrorMessage(300));current===null||didReceiveUpdate||(current=current.dependencies,current!==null&&checkIfContextChanged(current)&&(didReceiveUpdate=!0))}function renderWithHooksAgain(workInProgress,Component,props,secondArg){currentlyRenderingFiber=workInProgress;var numberOfReRenders=0;do{if(didScheduleRenderPhaseUpdateDuringThisPass&&(thenableState=null),thenableIndexCounter=0,didScheduleRenderPhaseUpdateDuringThisPass=!1,25<=numberOfReRenders)throw Error(formatProdErrorMessage(301));if(numberOfReRenders+=1,workInProgressHook=currentHook=null,workInProgress.updateQueue!=null){var children=workInProgress.updateQueue;children.lastEffect=null,children.events=null,children.stores=null,children.memoCache!=null&&(children.memoCache.index=0)}ReactSharedInternals.H=HooksDispatcherOnRerender,children=Component(props,secondArg)}while(didScheduleRenderPhaseUpdateDuringThisPass);return children}function TransitionAwareHostComponent(){var dispatcher=ReactSharedInternals.H,maybeThenable=dispatcher.useState()[0];return maybeThenable=typeof maybeThenable.then==="function"?useThenable(maybeThenable):maybeThenable,dispatcher=dispatcher.useState()[0],(currentHook!==null?currentHook.memoizedState:null)!==dispatcher&&(currentlyRenderingFiber.flags|=1024),maybeThenable}function checkDidRenderIdHook(){var didRenderIdHook=localIdCounter!==0;return localIdCounter=0,didRenderIdHook}function bailoutHooks(current,workInProgress,lanes){workInProgress.updateQueue=current.updateQueue,workInProgress.flags&=-2053,current.lanes&=~lanes}function resetHooksOnUnwind(workInProgress){if(didScheduleRenderPhaseUpdate){for(workInProgress=workInProgress.memoizedState;workInProgress!==null;){var queue=workInProgress.queue;queue!==null&&(queue.pending=null),workInProgress=workInProgress.next}didScheduleRenderPhaseUpdate=!1}renderLanes=0,workInProgressHook=currentHook=currentlyRenderingFiber=null,didScheduleRenderPhaseUpdateDuringThisPass=!1,thenableIndexCounter=localIdCounter=0,thenableState=null}function mountWorkInProgressHook(){var hook={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return workInProgressHook===null?currentlyRenderingFiber.memoizedState=workInProgressHook=hook:workInProgressHook=workInProgressHook.next=hook,workInProgressHook}function updateWorkInProgressHook(){if(currentHook===null){var nextCurrentHook=currentlyRenderingFiber.alternate;nextCurrentHook=nextCurrentHook!==null?nextCurrentHook.memoizedState:null}else nextCurrentHook=currentHook.next;var nextWorkInProgressHook=workInProgressHook===null?currentlyRenderingFiber.memoizedState:workInProgressHook.next;if(nextWorkInProgressHook!==null)workInProgressHook=nextWorkInProgressHook,currentHook=nextCurrentHook;else{if(nextCurrentHook===null){if(currentlyRenderingFiber.alternate===null)throw Error(formatProdErrorMessage(467));throw Error(formatProdErrorMessage(310))}currentHook=nextCurrentHook,nextCurrentHook={memoizedState:currentHook.memoizedState,baseState:currentHook.baseState,baseQueue:currentHook.baseQueue,queue:currentHook.queue,next:null},workInProgressHook===null?currentlyRenderingFiber.memoizedState=workInProgressHook=nextCurrentHook:workInProgressHook=workInProgressHook.next=nextCurrentHook}return workInProgressHook}function createFunctionComponentUpdateQueue(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function useThenable(thenable){var index=thenableIndexCounter;return thenableIndexCounter+=1,thenableState===null&&(thenableState=[]),thenable=trackUsedThenable(thenableState,thenable,index),index=currentlyRenderingFiber,(workInProgressHook===null?index.memoizedState:workInProgressHook.next)===null&&(index=index.alternate,ReactSharedInternals.H=index===null||index.memoizedState===null?HooksDispatcherOnMount:HooksDispatcherOnUpdate),thenable}function use(usable){if(usable!==null&&typeof usable==="object"){if(typeof usable.then==="function")return useThenable(usable);if(usable.$$typeof===REACT_RECOVERABLE_TYPE)return;if(usable.$$typeof===REACT_CONTEXT_TYPE)return readContext(usable)}throw Error(formatProdErrorMessage(438,String(usable)))}function useMemoCache(size){var memoCache=null,updateQueue=currentlyRenderingFiber.updateQueue;if(updateQueue!==null&&(memoCache=updateQueue.memoCache),memoCache==null){var current=currentlyRenderingFiber.alternate;current!==null&&(current=current.updateQueue,current!==null&&(current=current.memoCache,current!=null&&(memoCache={data:current.data.map(function(array){return array.slice()}),index:0})))}if(memoCache==null&&(memoCache={data:[],index:0}),updateQueue===null&&(updateQueue=createFunctionComponentUpdateQueue(),currentlyRenderingFiber.updateQueue=updateQueue),updateQueue.memoCache=memoCache,updateQueue=memoCache.data[memoCache.index],updateQueue===void 0)for(updateQueue=memoCache.data[memoCache.index]=Array(size),current=0;current<size;current++)updateQueue[current]=REACT_MEMO_CACHE_SENTINEL;return memoCache.index++,updateQueue}function basicStateReducer(state,action){return typeof action==="function"?action(state):action}function updateReducer(reducer){var hook=updateWorkInProgressHook();return updateReducerImpl(hook,currentHook,reducer)}function updateReducerImpl(hook,current,reducer){var queue=hook.queue;if(queue===null)throw Error(formatProdErrorMessage(311));queue.lastRenderedReducer=reducer;var baseQueue=hook.baseQueue,pendingQueue=queue.pending;if(pendingQueue!==null){if(baseQueue!==null){var baseFirst=baseQueue.next;baseQueue.next=pendingQueue.next,pendingQueue.next=baseFirst}current.baseQueue=baseQueue=pendingQueue,queue.pending=null}if(pendingQueue=hook.baseState,baseQueue===null)hook.memoizedState=pendingQueue;else{current=baseQueue.next;var newBaseQueueFirst=baseFirst=null,newBaseQueueLast=null,update=current,didReadFromEntangledAsyncAction$53=!1;do{var updateLane=update.lane&-536870913;if(updateLane!==update.lane?(workInProgressRootRenderLanes&updateLane)===updateLane:(renderLanes&updateLane)===updateLane){var revertLane=update.revertLane;if(revertLane===0)newBaseQueueLast!==null&&(newBaseQueueLast=newBaseQueueLast.next={lane:0,revertLane:0,gesture:null,action:update.action,hasEagerState:update.hasEagerState,eagerState:update.eagerState,next:null}),updateLane===currentEntangledLane&&(didReadFromEntangledAsyncAction$53=!0);else if((renderLanes&revertLane)===revertLane){update=update.next,revertLane===currentEntangledLane&&(didReadFromEntangledAsyncAction$53=!0);continue}else updateLane={lane:0,revertLane:update.revertLane,gesture:null,action:update.action,hasEagerState:update.hasEagerState,eagerState:update.eagerState,next:null},newBaseQueueLast===null?(newBaseQueueFirst=newBaseQueueLast=updateLane,baseFirst=pendingQueue):newBaseQueueLast=newBaseQueueLast.next=updateLane,currentlyRenderingFiber.lanes|=revertLane,workInProgressRootSkippedLanes|=revertLane;updateLane=update.action,shouldDoubleInvokeUserFnsInHooksDEV&&reducer(pendingQueue,updateLane),pendingQueue=update.hasEagerState?update.eagerState:reducer(pendingQueue,updateLane)}else revertLane={lane:updateLane,revertLane:update.revertLane,gesture:update.gesture,action:update.action,hasEagerState:update.hasEagerState,eagerState:update.eagerState,next:null},newBaseQueueLast===null?(newBaseQueueFirst=newBaseQueueLast=revertLane,baseFirst=pendingQueue):newBaseQueueLast=newBaseQueueLast.next=revertLane,currentlyRenderingFiber.lanes|=updateLane,workInProgressRootSkippedLanes|=updateLane;update=update.next}while(update!==null&&update!==current);if(newBaseQueueLast===null?baseFirst=pendingQueue:newBaseQueueLast.next=newBaseQueueFirst,!objectIs(pendingQueue,hook.memoizedState)&&(didReceiveUpdate=!0,didReadFromEntangledAsyncAction$53&&(reducer=currentEntangledActionThenable,reducer!==null)))throw reducer;hook.memoizedState=pendingQueue,hook.baseState=baseFirst,hook.baseQueue=newBaseQueueLast,queue.lastRenderedState=pendingQueue}return baseQueue===null&&(queue.lanes=0),[hook.memoizedState,queue.dispatch]}function rerenderReducer(reducer){var hook=updateWorkInProgressHook(),queue=hook.queue;if(queue===null)throw Error(formatProdErrorMessage(311));queue.lastRenderedReducer=reducer;var{dispatch,pending:lastRenderPhaseUpdate}=queue,newState=hook.memoizedState;if(lastRenderPhaseUpdate!==null){queue.pending=null;var update=lastRenderPhaseUpdate=lastRenderPhaseUpdate.next;do newState=reducer(newState,update.action),update=update.next;while(update!==lastRenderPhaseUpdate);objectIs(newState,hook.memoizedState)||(didReceiveUpdate=!0),hook.memoizedState=newState,hook.baseQueue===null&&(hook.baseState=newState),queue.lastRenderedState=newState}return[newState,dispatch]}function updateSyncExternalStore(subscribe,getSnapshot,getServerSnapshot){var fiber=currentlyRenderingFiber,hook=updateWorkInProgressHook(),isHydrating$jscomp$0=isHydrating;if(isHydrating$jscomp$0){if(getServerSnapshot===void 0)throw Error(formatProdErrorMessage(407));getServerSnapshot=getServerSnapshot()}else getServerSnapshot=getSnapshot();var snapshotChanged=!objectIs((currentHook||hook).memoizedState,getServerSnapshot);if(snapshotChanged&&(hook.memoizedState=getServerSnapshot,didReceiveUpdate=!0),hook=hook.queue,updateEffect(subscribeToStore.bind(null,fiber,hook,subscribe),[subscribe]),subscribe=hook.getSnapshot!==getSnapshot||snapshotChanged||workInProgressHook!==null&&(workInProgressHook.memoizedState.tag&1)!==0,pushSimpleEffect(subscribe?9:8,{destroy:void 0},updateStoreInstance.bind(null,fiber,hook,getServerSnapshot,getSnapshot),null),subscribe){if(fiber.flags|=2048,workInProgressRoot===null)throw Error(formatProdErrorMessage(349));isHydrating$jscomp$0||(renderLanes&127)!==0||pushStoreConsistencyCheck(fiber,getSnapshot,getServerSnapshot)}return getServerSnapshot}function pushStoreConsistencyCheck(fiber,getSnapshot,renderedSnapshot){fiber.flags|=16384,fiber={getSnapshot,value:renderedSnapshot},getSnapshot=currentlyRenderingFiber.updateQueue,getSnapshot===null?(getSnapshot=createFunctionComponentUpdateQueue(),currentlyRenderingFiber.updateQueue=getSnapshot,getSnapshot.stores=[fiber]):(renderedSnapshot=getSnapshot.stores,renderedSnapshot===null?getSnapshot.stores=[fiber]:renderedSnapshot.push(fiber))}function updateStoreInstance(fiber,inst,nextSnapshot,getSnapshot){inst.value=nextSnapshot,inst.getSnapshot=getSnapshot,checkIfSnapshotChanged(inst)&&forceStoreRerender(fiber)}function subscribeToStore(fiber,inst,subscribe){return subscribe(function(){checkIfSnapshotChanged(inst)&&forceStoreRerender(fiber)})}function checkIfSnapshotChanged(inst){var latestGetSnapshot=inst.getSnapshot;inst=inst.value;try{var nextValue=latestGetSnapshot();return!objectIs(inst,nextValue)}catch(error){return!0}}function forceStoreRerender(fiber){var root=enqueueConcurrentRenderForLane(fiber,2);root!==null&&scheduleUpdateOnFiber(root,fiber,2)}function mountStateImpl(initialState){var hook=mountWorkInProgressHook();if(typeof initialState==="function"){var initialStateInitializer=initialState;if(initialState=initialStateInitializer(),shouldDoubleInvokeUserFnsInHooksDEV){setIsStrictModeForDevtools(!0);try{initialStateInitializer()}finally{setIsStrictModeForDevtools(!1)}}}return hook.memoizedState=hook.baseState=initialState,hook.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:basicStateReducer,lastRenderedState:initialState},hook}function updateOptimisticImpl(hook,current,passthrough,reducer){return hook.baseState=passthrough,updateReducerImpl(hook,currentHook,typeof reducer==="function"?reducer:basicStateReducer)}function dispatchActionState(fiber,actionQueue,setPendingState,setState,payload){if(isRenderPhaseUpdate(fiber))throw Error(formatProdErrorMessage(485));if(fiber=actionQueue.action,fiber!==null){var actionNode={payload,action:fiber,next:null,isTransition:!0,status:"pending",value:null,reason:null,listeners:[],then:function(listener){actionNode.listeners.push(listener)}};ReactSharedInternals.T!==null?setPendingState(!0):actionNode.isTransition=!1,setState(actionNode),setPendingState=actionQueue.pending,setPendingState===null?(actionNode.next=actionQueue.pending=actionNode,runActionStateAction(actionQueue,actionNode)):(actionNode.next=setPendingState.next,actionQueue.pending=setPendingState.next=actionNode)}}function runActionStateAction(actionQueue,node){var{action,payload}=node,prevState=actionQueue.state;if(node.isTransition){var prevTransition=ReactSharedInternals.T,currentTransition={};currentTransition.types=prevTransition!==null?prevTransition.types:null,ReactSharedInternals.T=currentTransition;try{var returnValue=action(prevState,payload),onStartTransitionFinish=ReactSharedInternals.S;onStartTransitionFinish!==null&&onStartTransitionFinish(currentTransition,returnValue),handleActionReturnValue(actionQueue,node,returnValue)}catch(error){onActionError(actionQueue,node,error)}finally{prevTransition!==null&&currentTransition.types!==null&&(prevTransition.types=currentTransition.types),ReactSharedInternals.T=prevTransition}}else try{prevTransition=action(prevState,payload),handleActionReturnValue(actionQueue,node,prevTransition)}catch(error$57){onActionError(actionQueue,node,error$57)}}function handleActionReturnValue(actionQueue,node,returnValue){returnValue!==null&&typeof returnValue==="object"&&typeof returnValue.then==="function"?returnValue.then(function(nextState){onActionSuccess(actionQueue,node,nextState)},function(error){return onActionError(actionQueue,node,error)}):onActionSuccess(actionQueue,node,returnValue)}function onActionSuccess(actionQueue,actionNode,nextState){actionNode.status="fulfilled",actionNode.value=nextState,notifyActionListeners(actionNode),actionQueue.state=nextState,actionNode=actionQueue.pending,actionNode!==null&&(nextState=actionNode.next,nextState===actionNode?actionQueue.pending=null:(nextState=nextState.next,actionNode.next=nextState,runActionStateAction(actionQueue,nextState)))}function onActionError(actionQueue,actionNode,error){var last=actionQueue.pending;if(actionQueue.pending=null,last!==null){last=last.next;do actionNode.status="rejected",actionNode.reason=error,notifyActionListeners(actionNode),actionNode=actionNode.next;while(actionNode!==last)}actionQueue.action=null}function notifyActionListeners(actionNode){actionNode=actionNode.listeners;for(var i=0;i<actionNode.length;i++)(0,actionNode[i])()}function actionStateReducer(oldState,newState){return newState}function mountActionState(action,initialStateProp){if(isHydrating){var ssrFormState=workInProgressRoot.formState;if(ssrFormState!==null){a:{var JSCompiler_inline_result=currentlyRenderingFiber;if(isHydrating){if(nextHydratableInstance){var markerInstance=canHydrateFormStateMarker(nextHydratableInstance,rootOrSingletonContext);if(markerInstance){nextHydratableInstance=getNextHydratableSibling(markerInstance),JSCompiler_inline_result=isFormStateMarkerMatching(markerInstance);break a}}throwOnHydrationMismatch(JSCompiler_inline_result)}JSCompiler_inline_result=!1}JSCompiler_inline_result&&(initialStateProp=ssrFormState[0])}}ssrFormState=mountWorkInProgressHook(),ssrFormState.memoizedState=ssrFormState.baseState=initialStateProp,JSCompiler_inline_result={pending:null,lanes:0,dispatch:null,lastRenderedReducer:actionStateReducer,lastRenderedState:initialStateProp},ssrFormState.queue=JSCompiler_inline_result,ssrFormState=dispatchSetState.bind(null,currentlyRenderingFiber,JSCompiler_inline_result),JSCompiler_inline_result.dispatch=ssrFormState,JSCompiler_inline_result=mountStateImpl(!1);var setPendingState=dispatchOptimisticSetState.bind(null,currentlyRenderingFiber,!1,JSCompiler_inline_result.queue);return JSCompiler_inline_result=mountWorkInProgressHook(),markerInstance={state:initialStateProp,dispatch:null,action,pending:null},JSCompiler_inline_result.queue=markerInstance,ssrFormState=dispatchActionState.bind(null,currentlyRenderingFiber,markerInstance,setPendingState,ssrFormState),markerInstance.dispatch=ssrFormState,JSCompiler_inline_result.memoizedState=action,[initialStateProp,ssrFormState,!1]}function updateActionState(action){var stateHook=updateWorkInProgressHook();return updateActionStateImpl(stateHook,currentHook,action)}function updateActionStateImpl(stateHook,currentStateHook,action){if(currentStateHook=updateReducerImpl(stateHook,currentStateHook,actionStateReducer)[0],stateHook=updateReducer(basicStateReducer)[0],typeof currentStateHook==="object"&&currentStateHook!==null&&typeof currentStateHook.then==="function")try{var state=useThenable(currentStateHook)}catch(x){if(x===SuspenseException)throw SuspenseActionException;throw x}else state=currentStateHook;currentStateHook=updateWorkInProgressHook();var actionQueue=currentStateHook.queue,dispatch=actionQueue.dispatch;return action!==currentStateHook.memoizedState&&(currentlyRenderingFiber.flags|=2048,pushSimpleEffect(9,{destroy:void 0},actionStateActionEffect.bind(null,actionQueue,action),null)),[state,dispatch,stateHook]}function actionStateActionEffect(actionQueue,action){actionQueue.action=action}function rerenderActionState(action){var stateHook=updateWorkInProgressHook(),currentStateHook=currentHook;if(currentStateHook!==null)return updateActionStateImpl(stateHook,currentStateHook,action);updateWorkInProgressHook(),stateHook=stateHook.memoizedState,currentStateHook=updateWorkInProgressHook();var dispatch=currentStateHook.queue.dispatch;return currentStateHook.memoizedState=action,[stateHook,dispatch,!1]}function pushSimpleEffect(tag,inst,create,deps){return tag={tag,create,deps,inst,next:null},inst=currentlyRenderingFiber.updateQueue,inst===null&&(inst=createFunctionComponentUpdateQueue(),currentlyRenderingFiber.updateQueue=inst),create=inst.lastEffect,create===null?inst.lastEffect=tag.next=tag:(deps=create.next,create.next=tag,tag.next=deps,inst.lastEffect=tag),tag}function updateRef(){return updateWorkInProgressHook().memoizedState}function mountEffectImpl(fiberFlags,hookFlags,create,deps){var hook=mountWorkInProgressHook();currentlyRenderingFiber.flags|=fiberFlags,hook.memoizedState=pushSimpleEffect(1|hookFlags,{destroy:void 0},create,deps===void 0?null:deps)}function updateEffectImpl(fiberFlags,hookFlags,create,deps){var hook=updateWorkInProgressHook();deps=deps===void 0?null:deps;var inst=hook.memoizedState.inst;currentHook!==null&&deps!==null&&areHookInputsEqual(deps,currentHook.memoizedState.deps)?hook.memoizedState=pushSimpleEffect(hookFlags,inst,create,deps):(currentlyRenderingFiber.flags|=fiberFlags,hook.memoizedState=pushSimpleEffect(1|hookFlags,inst,create,deps))}function mountEffect(create,deps){mountEffectImpl(8390656,8,create,deps)}function updateEffect(create,deps){updateEffectImpl(2048,8,create,deps)}function useEffectEventImpl(payload){currentlyRenderingFiber.flags|=4;var componentUpdateQueue=currentlyRenderingFiber.updateQueue;if(componentUpdateQueue===null)componentUpdateQueue=createFunctionComponentUpdateQueue(),currentlyRenderingFiber.updateQueue=componentUpdateQueue,componentUpdateQueue.events=[payload];else{var events=componentUpdateQueue.events;events===null?componentUpdateQueue.events=[payload]:events.push(payload)}}function updateEvent(callback){var ref=updateWorkInProgressHook().memoizedState;return useEffectEventImpl({ref,nextImpl:callback}),function(){if((executionContext&2)!==0)throw Error(formatProdErrorMessage(440));return ref.impl.apply(void 0,arguments)}}function updateInsertionEffect(create,deps){return updateEffectImpl(4,2,create,deps)}function updateLayoutEffect(create,deps){return updateEffectImpl(4,4,create,deps)}function imperativeHandleEffect(create,ref){if(typeof ref==="function"){create=create();var refCleanup=ref(create);return function(){typeof refCleanup==="function"?refCleanup():ref(null)}}if(ref!==null&&ref!==void 0)return create=create(),ref.current=create,function(){ref.current=null}}function updateImperativeHandle(ref,create,deps){deps=deps!==null&&deps!==void 0?deps.concat([ref]):null,updateEffectImpl(4,4,imperativeHandleEffect.bind(null,create,ref),deps)}function mountDebugValue(){}function updateCallback(callback,deps){var hook=updateWorkInProgressHook();deps=deps===void 0?null:deps;var prevState=hook.memoizedState;if(deps!==null&&areHookInputsEqual(deps,prevState[1]))return prevState[0];return hook.memoizedState=[callback,deps],callback}function updateMemo(nextCreate,deps){var hook=updateWorkInProgressHook();deps=deps===void 0?null:deps;var prevState=hook.memoizedState;if(deps!==null&&areHookInputsEqual(deps,prevState[1]))return prevState[0];if(prevState=nextCreate(),shouldDoubleInvokeUserFnsInHooksDEV){setIsStrictModeForDevtools(!0);try{nextCreate()}finally{setIsStrictModeForDevtools(!1)}}return hook.memoizedState=[prevState,deps],prevState}function mountDeferredValueImpl(hook,value,initialValue){if(initialValue===void 0||(renderLanes&1073741824)!==0&&(workInProgressRootRenderLanes&261930)===0)return hook.memoizedState=value;return hook.memoizedState=initialValue,hook=requestDeferredLane(),currentlyRenderingFiber.lanes|=hook,workInProgressRootSkippedLanes|=hook,initialValue}function updateDeferredValueImpl(hook,prevValue,value,initialValue){if(objectIs(value,prevValue))return value;if(currentTreeHiddenStackCursor.current!==null)return hook=mountDeferredValueImpl(hook,value,initialValue),objectIs(hook,prevValue)||(didReceiveUpdate=!0),hook;if((renderLanes&106)===0||(renderLanes&1073741824)!==0&&(workInProgressRootRenderLanes&261930)===0)return didReceiveUpdate=!0,hook.memoizedState=value;return hook=requestDeferredLane(),currentlyRenderingFiber.lanes|=hook,workInProgressRootSkippedLanes|=hook,prevValue}function startTransition(fiber,queue,pendingState,finishedState,callback){var previousPriority=getCurrentUpdatePriority();setCurrentUpdatePriority(previousPriority!==0&&8>previousPriority?previousPriority:8);var prevTransition=ReactSharedInternals.T,currentTransition={};currentTransition.types=prevTransition!==null?prevTransition.types:null,ReactSharedInternals.T=currentTransition,dispatchOptimisticSetState(fiber,!1,queue,pendingState);try{var returnValue=callback(),onStartTransitionFinish=ReactSharedInternals.S;if(onStartTransitionFinish!==null&&onStartTransitionFinish(currentTransition,returnValue),returnValue!==null&&typeof returnValue==="object"&&typeof returnValue.then==="function"){var thenableForFinishedState=chainThenableValue(returnValue,finishedState);dispatchSetStateInternal(fiber,queue,thenableForFinishedState,requestUpdateLane(fiber))}else dispatchSetStateInternal(fiber,queue,finishedState,requestUpdateLane(fiber))}catch(error){dispatchSetStateInternal(fiber,queue,{then:function(){},status:"rejected",reason:error},requestUpdateLane())}finally{setCurrentUpdatePriority(previousPriority),prevTransition!==null&&currentTransition.types!==null&&(prevTransition.types=currentTransition.types),ReactSharedInternals.T=prevTransition}}function ensureFormComponentIsStateful(formFiber){var existingStateHook=formFiber.memoizedState;if(existingStateHook!==null)return existingStateHook;existingStateHook={memoizedState:NotPendingTransition,baseState:NotPendingTransition,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:basicStateReducer,lastRenderedState:NotPendingTransition},next:null};var initialResetState={};return existingStateHook.next={memoizedState:initialResetState,baseState:initialResetState,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:basicStateReducer,lastRenderedState:initialResetState},next:null},formFiber.memoizedState=existingStateHook,formFiber=formFiber.alternate,formFiber!==null&&(formFiber.memoizedState=existingStateHook),existingStateHook}function useHostTransitionStatus(){return readContext(HostTransitionContext)}function updateId(){return updateWorkInProgressHook().memoizedState}function updateRefresh(){return updateWorkInProgressHook().memoizedState}function refreshCache(fiber){for(var provider=fiber.return;provider!==null;){switch(provider.tag){case 24:case 3:var lane=requestUpdateLane();fiber=createUpdate(lane);var root=enqueueUpdate(provider,fiber,lane);root!==null&&(scheduleUpdateOnFiber(root,provider,lane),entangleTransitions(root,provider,lane)),provider={cache:createCache()},fiber.payload=provider;return}provider=provider.return}}function dispatchReducerAction(fiber,queue,action){var lane=requestUpdateLane();action={lane,revertLane:0,gesture:null,action,hasEagerState:!1,eagerState:null,next:null},isRenderPhaseUpdate(fiber)?enqueueRenderPhaseUpdate(queue,action):(action=enqueueConcurrentHookUpdate(fiber,queue,action,lane),action!==null&&(scheduleUpdateOnFiber(action,fiber,lane),entangleTransitionUpdate(action,queue,lane)))}function dispatchSetState(fiber,queue,action){var lane=requestUpdateLane();dispatchSetStateInternal(fiber,queue,action,lane)}function dispatchSetStateInternal(fiber,queue,action,lane){var update={lane,revertLane:0,gesture:null,action,hasEagerState:!1,eagerState:null,next:null};if(isRenderPhaseUpdate(fiber))enqueueRenderPhaseUpdate(queue,update);else{var alternate=fiber.alternate;if(fiber.lanes===0&&(alternate===null||alternate.lanes===0)&&(alternate=queue.lastRenderedReducer,alternate!==null))try{var currentState=queue.lastRenderedState,eagerState=alternate(currentState,action);if(update.hasEagerState=!0,update.eagerState=eagerState,objectIs(eagerState,currentState))return enqueueUpdate$1(fiber,queue,update,0),workInProgressRoot===null&&finishQueueingConcurrentUpdates(),!1}catch(error){}finally{}if(action=enqueueConcurrentHookUpdate(fiber,queue,update,lane),action!==null)return scheduleUpdateOnFiber(action,fiber,lane),entangleTransitionUpdate(action,queue,lane),!0}return!1}function dispatchOptimisticSetState(fiber,throwIfDuringRender,queue,action){if(action={lane:2,revertLane:requestTransitionLane(),gesture:null,action,hasEagerState:!1,eagerState:null,next:null},isRenderPhaseUpdate(fiber)){if(throwIfDuringRender)throw Error(formatProdErrorMessage(479))}else throwIfDuringRender=enqueueConcurrentHookUpdate(fiber,queue,action,2),throwIfDuringRender!==null&&scheduleUpdateOnFiber(throwIfDuringRender,fiber,2)}function isRenderPhaseUpdate(fiber){var alternate=fiber.alternate;return fiber===currentlyRenderingFiber||alternate!==null&&alternate===currentlyRenderingFiber}function enqueueRenderPhaseUpdate(queue,update){didScheduleRenderPhaseUpdateDuringThisPass=didScheduleRenderPhaseUpdate=!0;var pending=queue.pending;pending===null?update.next=update:(update.next=pending.next,pending.next=update),queue.pending=update}function entangleTransitionUpdate(root,queue,lane){if((lane&4194048)!==0){var queueLanes=queue.lanes;queueLanes&=root.pendingLanes,lane|=queueLanes,queue.lanes=lane,markRootEntangled(root,lane)}}function applyDerivedStateFromProps(workInProgress,ctor,getDerivedStateFromProps,nextProps){ctor=workInProgress.memoizedState,getDerivedStateFromProps=getDerivedStateFromProps(nextProps,ctor),getDerivedStateFromProps=getDerivedStateFromProps===null||getDerivedStateFromProps===void 0?ctor:assign({},ctor,getDerivedStateFromProps),workInProgress.memoizedState=getDerivedStateFromProps,workInProgress.lanes===0&&(workInProgress.updateQueue.baseState=getDerivedStateFromProps)}function checkShouldComponentUpdate(workInProgress,ctor,oldProps,newProps,oldState,newState,nextContext){return workInProgress=workInProgress.stateNode,typeof workInProgress.shouldComponentUpdate==="function"?workInProgress.shouldComponentUpdate(newProps,newState,nextContext):ctor.prototype&&ctor.prototype.isPureReactComponent?!shallowEqual(oldProps,newProps)||!shallowEqual(oldState,newState):!0}function callComponentWillReceiveProps(workInProgress,instance,newProps,nextContext){workInProgress=instance.state,typeof instance.componentWillReceiveProps==="function"&&instance.componentWillReceiveProps(newProps,nextContext),typeof instance.UNSAFE_componentWillReceiveProps==="function"&&instance.UNSAFE_componentWillReceiveProps(newProps,nextContext),instance.state!==workInProgress&&classComponentUpdater.enqueueReplaceState(instance,instance.state,null)}function resolveClassComponentProps(Component,baseProps){var newProps=baseProps;if("ref"in baseProps){newProps={};for(var propName in baseProps)propName!=="ref"&&(newProps[propName]=baseProps[propName])}if(Component=Component.defaultProps){newProps===baseProps&&(newProps=assign({},newProps));for(var propName$59 in Component)newProps[propName$59]===void 0&&(newProps[propName$59]=Component[propName$59])}return newProps}function logUncaughtError(root,errorInfo){try{var onUncaughtError=root.onUncaughtError;onUncaughtError(errorInfo.value,{componentStack:errorInfo.stack})}catch(e){setTimeout(function(){throw e})}}function logCaughtError(root,boundary,errorInfo){try{var onCaughtError=root.onCaughtError;onCaughtError(errorInfo.value,{componentStack:errorInfo.stack,errorBoundary:boundary.tag===1?boundary.stateNode:null})}catch(e){setTimeout(function(){throw e})}}function createRootErrorUpdate(root,errorInfo,lane){return lane=createUpdate(lane),lane.tag=3,lane.payload={element:null},lane.callback=function(){logUncaughtError(root,errorInfo)},lane}function createClassErrorUpdate(lane){return lane=createUpdate(lane),lane.tag=3,lane}function initializeClassErrorUpdate(update,root,fiber,errorInfo){var getDerivedStateFromError=fiber.type.getDerivedStateFromError;if(typeof getDerivedStateFromError==="function"){var error=errorInfo.value;update.payload=function(){return getDerivedStateFromError(error)},update.callback=function(){logCaughtError(root,fiber,errorInfo)}}var inst=fiber.stateNode;inst!==null&&typeof inst.componentDidCatch==="function"&&(update.callback=function(){logCaughtError(root,fiber,errorInfo),typeof getDerivedStateFromError!=="function"&&(legacyErrorBoundariesThatAlreadyFailed===null?legacyErrorBoundariesThatAlreadyFailed=new Set([this]):legacyErrorBoundariesThatAlreadyFailed.add(this));var stack=errorInfo.stack;this.componentDidCatch(errorInfo.value,{componentStack:stack!==null?stack:""})})}function throwException(root,returnFiber,sourceFiber,value,rootRenderLanes){if(sourceFiber.flags|=32768,value!==null&&typeof value==="object"&&typeof value.then==="function"){if(returnFiber=sourceFiber.alternate,returnFiber!==null&&propagateParentContextChanges(returnFiber,sourceFiber,rootRenderLanes,!0),sourceFiber=suspenseHandlerStackCursor.current,sourceFiber!==null){switch(sourceFiber.tag){case 31:case 13:case 19:return shellBoundary===null?renderDidSuspendDelayIfPossible():sourceFiber.alternate===null&&workInProgressRootExitStatus===0&&(workInProgressRootExitStatus=3),sourceFiber.flags&=-257,sourceFiber.flags|=65536,sourceFiber.lanes=rootRenderLanes,value===noopSuspenseyCommitThenable?sourceFiber.flags|=16384:(returnFiber=sourceFiber.updateQueue,returnFiber===null?sourceFiber.updateQueue=new Set([value]):returnFiber.add(value),attachPingListener(root,value,rootRenderLanes)),!1;case 22:return sourceFiber.flags|=65536,value===noopSuspenseyCommitThenable?sourceFiber.flags|=16384:(returnFiber=sourceFiber.updateQueue,returnFiber===null?(returnFiber={transitions:null,markerInstances:null,retryQueue:new Set([value])},sourceFiber.updateQueue=returnFiber):(sourceFiber=returnFiber.retryQueue,sourceFiber===null?returnFiber.retryQueue=new Set([value]):sourceFiber.add(value)),attachPingListener(root,value,rootRenderLanes)),!1}throw Error(formatProdErrorMessage(435,sourceFiber.tag))}return attachPingListener(root,value,rootRenderLanes),renderDidSuspendDelayIfPossible(),!1}if(isHydrating)return returnFiber=suspenseHandlerStackCursor.current,returnFiber!==null?((returnFiber.flags&65536)===0&&(returnFiber.flags|=256),returnFiber.flags|=65536,returnFiber.lanes=rootRenderLanes,value!==HydrationMismatchException&&(root=Error(formatProdErrorMessage(422),{cause:value}),queueHydrationError(createCapturedValueAtFiber(root,sourceFiber)))):(value!==HydrationMismatchException&&(returnFiber=Error(formatProdErrorMessage(423),{cause:value}),queueHydrationError(createCapturedValueAtFiber(returnFiber,sourceFiber))),root=root.current.alternate,root.flags|=65536,rootRenderLanes&=-rootRenderLanes,root.lanes|=rootRenderLanes,value=createCapturedValueAtFiber(value,sourceFiber),rootRenderLanes=createRootErrorUpdate(root.stateNode,value,rootRenderLanes),enqueueCapturedUpdate(root,rootRenderLanes),workInProgressRootExitStatus!==4&&(workInProgressRootExitStatus=2)),!1;var wrapperError=Error(formatProdErrorMessage(520),{cause:value});if(wrapperError=createCapturedValueAtFiber(wrapperError,sourceFiber),workInProgressRootConcurrentErrors===null?workInProgressRootConcurrentErrors=[wrapperError]:workInProgressRootConcurrentErrors.push(wrapperError),workInProgressRootExitStatus!==4&&(workInProgressRootExitStatus=2),returnFiber===null)return!0;value=createCapturedValueAtFiber(value,sourceFiber),sourceFiber=returnFiber;do{switch(sourceFiber.tag){case 3:return sourceFiber.flags|=65536,root=rootRenderLanes&-rootRenderLanes,sourceFiber.lanes|=root,root=createRootErrorUpdate(sourceFiber.stateNode,value,root),enqueueCapturedUpdate(sourceFiber,root),!1;case 1:if(returnFiber=sourceFiber.type,wrapperError=sourceFiber.stateNode,(sourceFiber.flags&128)===0&&(typeof returnFiber.getDerivedStateFromError==="function"||wrapperError!==null&&typeof wrapperError.componentDidCatch==="function"&&(legacyErrorBoundariesThatAlreadyFailed===null||!legacyErrorBoundariesThatAlreadyFailed.has(wrapperError))))return sourceFiber.flags|=65536,rootRenderLanes&=-rootRenderLanes,sourceFiber.lanes|=rootRenderLanes,rootRenderLanes=createClassErrorUpdate(rootRenderLanes),initializeClassErrorUpdate(rootRenderLanes,root,sourceFiber,value),enqueueCapturedUpdate(sourceFiber,rootRenderLanes),!1;break;case 22:if(sourceFiber.memoizedState!==null)return sourceFiber.flags|=65536,!1}sourceFiber=sourceFiber.return}while(sourceFiber!==null);return!1}function reconcileChildren(current,workInProgress,nextChildren,renderLanes){workInProgress.child=current===null?mountChildFibers(workInProgress,null,nextChildren,renderLanes):reconcileChildFibers(workInProgress,current.child,nextChildren,renderLanes)}function updateForwardRef(current,workInProgress,Component,nextProps,renderLanes){Component=Component.render;var ref=workInProgress.ref;if("ref"in nextProps){var propsWithoutRef={};for(var key in nextProps)key!=="ref"&&(propsWithoutRef[key]=nextProps[key])}else propsWithoutRef=nextProps;if(prepareToReadContext(workInProgress),nextProps=renderWithHooks(current,workInProgress,Component,propsWithoutRef,ref,renderLanes),key=checkDidRenderIdHook(),current!==null&&!didReceiveUpdate)return bailoutHooks(current,workInProgress,renderLanes),bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);return isHydrating&&key&&pushMaterializedTreeId(workInProgress),workInProgress.flags|=1,reconcileChildren(current,workInProgress,nextProps,renderLanes),workInProgress.child}function updateMemoComponent(current,workInProgress,Component,nextProps,renderLanes){if(current===null){var type=Component.type;if(typeof type==="function"&&!shouldConstruct(type)&&type.defaultProps===void 0&&Component.compare===null)return workInProgress.tag=15,workInProgress.type=type,updateSimpleMemoComponent(current,workInProgress,type,nextProps,renderLanes);return current=createFiberFromTypeAndProps(Component.type,null,nextProps,workInProgress,workInProgress.mode,renderLanes),current.ref=workInProgress.ref,current.return=workInProgress,workInProgress.child=current}if(type=current.child,!checkScheduledUpdateOrContext(current,renderLanes)){var prevProps=type.memoizedProps;if(Component=Component.compare,Component=Component!==null?Component:shallowEqual,Component(prevProps,nextProps)&&current.ref===workInProgress.ref)return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes)}return workInProgress.flags|=1,current=createWorkInProgress(type,nextProps),current.ref=workInProgress.ref,current.return=workInProgress,workInProgress.child=current}function updateSimpleMemoComponent(current,workInProgress,Component,nextProps,renderLanes){if(current!==null){var prevProps=current.memoizedProps;if(shallowEqual(prevProps,nextProps)&&current.ref===workInProgress.ref)if(didReceiveUpdate=!1,workInProgress.pendingProps=nextProps=prevProps,checkScheduledUpdateOrContext(current,renderLanes))(current.flags&131072)!==0&&(didReceiveUpdate=!0);else return workInProgress.lanes=current.lanes,bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes)}return updateFunctionComponent(current,workInProgress,Component,nextProps,renderLanes)}function updateOffscreenComponent(current,workInProgress,renderLanes,nextProps){var nextChildren=nextProps.children,prevState=current!==null?current.memoizedState:null;if(current===null&&workInProgress.stateNode===null&&(workInProgress.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),nextProps.mode==="hidden"){if((workInProgress.flags&128)!==0){if(prevState=prevState!==null?prevState.baseLanes|renderLanes:renderLanes,current!==null){nextProps=workInProgress.child=current.child;for(nextChildren=0;nextProps!==null;)nextChildren=nextChildren|nextProps.lanes|nextProps.childLanes,nextProps=nextProps.sibling;nextProps=nextChildren&~prevState}else nextProps=0,workInProgress.child=null;return deferHiddenOffscreenComponent(current,workInProgress,prevState,renderLanes,nextProps)}if((renderLanes&536870912)!==0)workInProgress.memoizedState={baseLanes:0,cachePool:null},current!==null&&pushTransition(workInProgress,prevState!==null?prevState.cachePool:null),prevState!==null?pushHiddenContext(workInProgress,prevState):reuseHiddenContextOnStack(),pushOffscreenSuspenseHandler(workInProgress);else return nextProps=workInProgress.lanes=536870912,deferHiddenOffscreenComponent(current,workInProgress,prevState!==null?prevState.baseLanes|renderLanes:renderLanes,renderLanes,nextProps)}else prevState!==null?(pushTransition(workInProgress,prevState.cachePool),pushHiddenContext(workInProgress,prevState),reuseSuspenseHandlerOnStack(),workInProgress.memoizedState=null):(current!==null&&pushTransition(workInProgress,null),reuseHiddenContextOnStack(),reuseSuspenseHandlerOnStack());return reconcileChildren(current,workInProgress,nextChildren,renderLanes),workInProgress.child}function bailoutOffscreenComponent(current,workInProgress){return current!==null&&current.tag===22||workInProgress.stateNode!==null||(workInProgress.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),workInProgress.sibling}function deferHiddenOffscreenComponent(current,workInProgress,nextBaseLanes,renderLanes,remainingChildLanes){var JSCompiler_inline_result=peekCacheFromPool();return JSCompiler_inline_result=JSCompiler_inline_result===null?null:{parent:isPrimaryRenderer?CacheContext._currentValue:CacheContext._currentValue2,pool:JSCompiler_inline_result},workInProgress.memoizedState={baseLanes:nextBaseLanes,cachePool:JSCompiler_inline_result},current!==null&&pushTransition(workInProgress,null),reuseHiddenContextOnStack(),pushOffscreenSuspenseHandler(workInProgress),current!==null&&propagateParentContextChanges(current,workInProgress,renderLanes,!0),workInProgress.childLanes=remainingChildLanes,null}function mountActivityChildren(workInProgress,nextProps){return nextProps=mountWorkInProgressOffscreenFiber({mode:nextProps.mode,children:nextProps.children},workInProgress.mode),nextProps.ref=workInProgress.ref,workInProgress.child=nextProps,nextProps.return=workInProgress,nextProps}function retryActivityComponentWithoutHydrating(current,workInProgress,renderLanes){return reconcileChildFibers(workInProgress,current.child,null,renderLanes),current=mountActivityChildren(workInProgress,workInProgress.pendingProps),current.flags|=2,popSuspenseHandler(workInProgress),workInProgress.memoizedState=null,current}function updateActivityComponent(current,workInProgress,renderLanes){var nextProps=workInProgress.pendingProps,didSuspend=(workInProgress.flags&128)!==0;if(workInProgress.flags&=-129,current===null){if(isHydrating){if(nextProps.mode==="hidden")return current=mountActivityChildren(workInProgress,nextProps),workInProgress.lanes=536870912,current.memoizedState={baseLanes:0,cachePool:null},bailoutOffscreenComponent(null,current);if(pushDehydratedActivitySuspenseHandler(workInProgress),(current=nextHydratableInstance)?(current=canHydrateActivityInstance(current,rootOrSingletonContext),current!==null&&(workInProgress.memoizedState={dehydrated:current,treeContext:treeContextProvider!==null?{id:treeContextId,overflow:treeContextOverflow}:null,retryLane:536870912,hydrationErrors:null},renderLanes=createFiberFromDehydratedFragment(current),renderLanes.return=workInProgress,workInProgress.child=renderLanes,hydrationParentFiber=workInProgress,nextHydratableInstance=null)):current=null,current===null)throw throwOnHydrationMismatch(workInProgress);return workInProgress.lanes=536870912,null}return mountActivityChildren(workInProgress,nextProps)}var prevState=current.memoizedState;if(prevState!==null){var dehydrated=prevState.dehydrated;if(pushDehydratedActivitySuspenseHandler(workInProgress),didSuspend)if(workInProgress.flags&256)workInProgress.flags&=-257,workInProgress=retryActivityComponentWithoutHydrating(current,workInProgress,renderLanes);else if(workInProgress.memoizedState!==null)workInProgress.child=current.child,workInProgress.flags|=128,workInProgress=null;else throw Error(formatProdErrorMessage(558));else if(didReceiveUpdate||propagateParentContextChanges(current,workInProgress,renderLanes,!1),didSuspend=(renderLanes&current.childLanes)!==0,didReceiveUpdate||didSuspend){if(currentTreeHiddenStackCursor.current===null){if(nextProps=workInProgressRoot,nextProps!==null&&(dehydrated=getBumpedLaneForHydration(nextProps,renderLanes),dehydrated!==0&&dehydrated!==prevState.retryLane))throw prevState.retryLane=dehydrated,enqueueConcurrentRenderForLane(current,dehydrated),scheduleUpdateOnFiber(nextProps,current,dehydrated),SelectiveHydrationException;renderDidSuspendDelayIfPossible()}workInProgress=retryActivityComponentWithoutHydrating(current,workInProgress,renderLanes)}else current=prevState.treeContext,supportsHydration&&(nextHydratableInstance=getFirstHydratableChildWithinActivityInstance(dehydrated),hydrationParentFiber=workInProgress,isHydrating=!0,hydrationErrors=null,rootOrSingletonContext=!1,current!==null&&restoreSuspendedTreeContext(workInProgress,current)),workInProgress=mountActivityChildren(workInProgress,nextProps),workInProgress.flags|=134221824;return workInProgress}return current=createWorkInProgress(current.child,{mode:nextProps.mode,children:nextProps.children}),current.ref=workInProgress.ref,workInProgress.child=current,current.return=workInProgress,current}function markRef(current,workInProgress){var ref=workInProgress.ref;if(ref===null)current!==null&&current.ref!==null&&(workInProgress.flags|=4194816);else{if(typeof ref!=="function"&&typeof ref!=="object")throw Error(formatProdErrorMessage(284));if(current===null||current.ref!==ref)workInProgress.flags|=4194816}}function updateFunctionComponent(current,workInProgress,Component,nextProps,renderLanes){if(prepareToReadContext(workInProgress),Component=renderWithHooks(current,workInProgress,Component,nextProps,void 0,renderLanes),nextProps=checkDidRenderIdHook(),current!==null&&!didReceiveUpdate)return bailoutHooks(current,workInProgress,renderLanes),bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);return isHydrating&&nextProps&&pushMaterializedTreeId(workInProgress),workInProgress.flags|=1,reconcileChildren(current,workInProgress,Component,renderLanes),workInProgress.child}function replayFunctionComponent(current,workInProgress,nextProps,Component,secondArg,renderLanes){if(prepareToReadContext(workInProgress),workInProgress.updateQueue=null,nextProps=renderWithHooksAgain(workInProgress,Component,nextProps,secondArg),finishRenderingHooks(current),Component=checkDidRenderIdHook(),current!==null&&!didReceiveUpdate)return bailoutHooks(current,workInProgress,renderLanes),bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);return isHydrating&&Component&&pushMaterializedTreeId(workInProgress),workInProgress.flags|=1,reconcileChildren(current,workInProgress,nextProps,renderLanes),workInProgress.child}function updateClassComponent(current,workInProgress,Component,nextProps,renderLanes){if(prepareToReadContext(workInProgress),workInProgress.stateNode===null){var context=emptyContextObject,contextType=Component.contextType;typeof contextType==="object"&&contextType!==null&&(context=readContext(contextType)),context=new Component(nextProps,context),workInProgress.memoizedState=context.state!==null&&context.state!==void 0?context.state:null,context.updater=classComponentUpdater,workInProgress.stateNode=context,context._reactInternals=workInProgress,context=workInProgress.stateNode,context.props=nextProps,context.state=workInProgress.memoizedState,context.refs={},initializeUpdateQueue(workInProgress),contextType=Component.contextType,context.context=typeof contextType==="object"&&contextType!==null?readContext(contextType):emptyContextObject,context.state=workInProgress.memoizedState,contextType=Component.getDerivedStateFromProps,typeof contextType==="function"&&(applyDerivedStateFromProps(workInProgress,Component,contextType,nextProps),context.state=workInProgress.memoizedState),typeof Component.getDerivedStateFromProps==="function"||typeof context.getSnapshotBeforeUpdate==="function"||typeof context.UNSAFE_componentWillMount!=="function"&&typeof context.componentWillMount!=="function"||(contextType=context.state,typeof context.componentWillMount==="function"&&context.componentWillMount(),typeof context.UNSAFE_componentWillMount==="function"&&context.UNSAFE_componentWillMount(),contextType!==context.state&&classComponentUpdater.enqueueReplaceState(context,context.state,null),processUpdateQueue(workInProgress,nextProps,context,renderLanes),suspendIfUpdateReadFromEntangledAsyncAction(),context.state=workInProgress.memoizedState),typeof context.componentDidMount==="function"&&(workInProgress.flags|=4194308),nextProps=!0}else if(current===null){context=workInProgress.stateNode;var unresolvedOldProps=workInProgress.memoizedProps,oldProps=resolveClassComponentProps(Component,unresolvedOldProps);context.props=oldProps;var oldContext=context.context,contextType$jscomp$0=Component.contextType;contextType=emptyContextObject,typeof contextType$jscomp$0==="object"&&contextType$jscomp$0!==null&&(contextType=readContext(contextType$jscomp$0));var getDerivedStateFromProps=Component.getDerivedStateFromProps;contextType$jscomp$0=typeof getDerivedStateFromProps==="function"||typeof context.getSnapshotBeforeUpdate==="function",unresolvedOldProps=workInProgress.pendingProps!==unresolvedOldProps,contextType$jscomp$0||typeof context.UNSAFE_componentWillReceiveProps!=="function"&&typeof context.componentWillReceiveProps!=="function"||(unresolvedOldProps||oldContext!==contextType)&&callComponentWillReceiveProps(workInProgress,context,nextProps,contextType),hasForceUpdate=!1;var oldState=workInProgress.memoizedState;context.state=oldState,processUpdateQueue(workInProgress,nextProps,context,renderLanes),suspendIfUpdateReadFromEntangledAsyncAction(),oldContext=workInProgress.memoizedState,unresolvedOldProps||oldState!==oldContext||hasForceUpdate?(typeof getDerivedStateFromProps==="function"&&(applyDerivedStateFromProps(workInProgress,Component,getDerivedStateFromProps,nextProps),oldContext=workInProgress.memoizedState),(oldProps=hasForceUpdate||checkShouldComponentUpdate(workInProgress,Component,oldProps,nextProps,oldState,oldContext,contextType))?(contextType$jscomp$0||typeof context.UNSAFE_componentWillMount!=="function"&&typeof context.componentWillMount!=="function"||(typeof context.componentWillMount==="function"&&context.componentWillMount(),typeof context.UNSAFE_componentWillMount==="function"&&context.UNSAFE_componentWillMount()),typeof context.componentDidMount==="function"&&(workInProgress.flags|=4194308)):(typeof context.componentDidMount==="function"&&(workInProgress.flags|=4194308),workInProgress.memoizedProps=nextProps,workInProgress.memoizedState=oldContext),context.props=nextProps,context.state=oldContext,context.context=contextType,nextProps=oldProps):(typeof context.componentDidMount==="function"&&(workInProgress.flags|=4194308),nextProps=!1)}else{context=workInProgress.stateNode,cloneUpdateQueue(current,workInProgress),contextType=workInProgress.memoizedProps,contextType$jscomp$0=resolveClassComponentProps(Component,contextType),context.props=contextType$jscomp$0,getDerivedStateFromProps=workInProgress.pendingProps,oldState=context.context,oldContext=Component.contextType,oldProps=emptyContextObject,typeof oldContext==="object"&&oldContext!==null&&(oldProps=readContext(oldContext)),unresolvedOldProps=Component.getDerivedStateFromProps,(oldContext=typeof unresolvedOldProps==="function"||typeof context.getSnapshotBeforeUpdate==="function")||typeof context.UNSAFE_componentWillReceiveProps!=="function"&&typeof context.componentWillReceiveProps!=="function"||(contextType!==getDerivedStateFromProps||oldState!==oldProps)&&callComponentWillReceiveProps(workInProgress,context,nextProps,oldProps),hasForceUpdate=!1,oldState=workInProgress.memoizedState,context.state=oldState,processUpdateQueue(workInProgress,nextProps,context,renderLanes),suspendIfUpdateReadFromEntangledAsyncAction();var newState=workInProgress.memoizedState;contextType!==getDerivedStateFromProps||oldState!==newState||hasForceUpdate||current!==null&&current.dependencies!==null&&checkIfContextChanged(current.dependencies)?(typeof unresolvedOldProps==="function"&&(applyDerivedStateFromProps(workInProgress,Component,unresolvedOldProps,nextProps),newState=workInProgress.memoizedState),(contextType$jscomp$0=hasForceUpdate||checkShouldComponentUpdate(workInProgress,Component,contextType$jscomp$0,nextProps,oldState,newState,oldProps)||current!==null&&current.dependencies!==null&&checkIfContextChanged(current.dependencies))?(oldContext||typeof context.UNSAFE_componentWillUpdate!=="function"&&typeof context.componentWillUpdate!=="function"||(typeof context.componentWillUpdate==="function"&&context.componentWillUpdate(nextProps,newState,oldProps),typeof context.UNSAFE_componentWillUpdate==="function"&&context.UNSAFE_componentWillUpdate(nextProps,newState,oldProps)),typeof context.componentDidUpdate==="function"&&(workInProgress.flags|=4),typeof context.getSnapshotBeforeUpdate==="function"&&(workInProgress.flags|=1024)):(typeof context.componentDidUpdate!=="function"||contextType===current.memoizedProps&&oldState===current.memoizedState||(workInProgress.flags|=4),typeof context.getSnapshotBeforeUpdate!=="function"||contextType===current.memoizedProps&&oldState===current.memoizedState||(workInProgress.flags|=1024),workInProgress.memoizedProps=nextProps,workInProgress.memoizedState=newState),context.props=nextProps,context.state=newState,context.context=oldProps,nextProps=contextType$jscomp$0):(typeof context.componentDidUpdate!=="function"||contextType===current.memoizedProps&&oldState===current.memoizedState||(workInProgress.flags|=4),typeof context.getSnapshotBeforeUpdate!=="function"||contextType===current.memoizedProps&&oldState===current.memoizedState||(workInProgress.flags|=1024),nextProps=!1)}return context=nextProps,markRef(current,workInProgress),nextProps=(workInProgress.flags&128)!==0,context||nextProps?(context=workInProgress.stateNode,Component=nextProps&&typeof Component.getDerivedStateFromError!=="function"?null:context.render(),workInProgress.flags|=1,current!==null&&nextProps?(workInProgress.child=reconcileChildFibers(workInProgress,current.child,null,renderLanes),workInProgress.child=reconcileChildFibers(workInProgress,null,Component,renderLanes)):reconcileChildren(current,workInProgress,Component,renderLanes),workInProgress.memoizedState=context.state,current=workInProgress.child):current=bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes),current}function mountHostRootWithoutHydrating(current,workInProgress,nextChildren,renderLanes){return resetHydrationState(),workInProgress.flags|=256,reconcileChildren(current,workInProgress,nextChildren,renderLanes),workInProgress.child}function mountSuspenseOffscreenState(renderLanes){return{baseLanes:renderLanes,cachePool:getSuspendedCache()}}function getRemainingWorkInPrimaryTree(current,primaryTreeDidDefer,renderLanes){return current=current!==null?current.childLanes&~renderLanes:0,primaryTreeDidDefer&&(current|=workInProgressDeferredLane),current}function updateSuspenseComponent(current,workInProgress,renderLanes){var nextProps=workInProgress.pendingProps,showFallback=!1,didSuspend=(workInProgress.flags&128)!==0,JSCompiler_temp;if((JSCompiler_temp=didSuspend)||(JSCompiler_temp=current!==null&&current.memoizedState===null?!1:(suspenseStackCursor.current&2)!==0),JSCompiler_temp&&(showFallback=!0,workInProgress.flags&=-129),JSCompiler_temp=(workInProgress.flags&32)!==0,workInProgress.flags&=-33,current===null){if(isHydrating){if(showFallback?pushPrimaryTreeSuspenseHandler(workInProgress):reuseSuspenseHandlerOnStack(),(current=nextHydratableInstance)?(current=canHydrateSuspenseInstance(current,rootOrSingletonContext),current!==null&&(workInProgress.memoizedState={dehydrated:current,treeContext:treeContextProvider!==null?{id:treeContextId,overflow:treeContextOverflow}:null,retryLane:536870912,hydrationErrors:null},renderLanes=createFiberFromDehydratedFragment(current),renderLanes.return=workInProgress,workInProgress.child=renderLanes,hydrationParentFiber=workInProgress,nextHydratableInstance=null)):current=null,current===null)throw throwOnHydrationMismatch(workInProgress);return isSuspenseInstanceFallback(current)?workInProgress.lanes=32:workInProgress.lanes=536870912,null}if(didSuspend=nextProps.children,nextProps=nextProps.fallback,showFallback)return reuseSuspenseHandlerOnStack(),showFallback=workInProgress.mode,didSuspend=mountWorkInProgressOffscreenFiber({mode:"hidden",children:didSuspend},showFallback),nextProps=createFiberFromFragment(nextProps,showFallback,renderLanes,null),didSuspend.return=workInProgress,nextProps.return=workInProgress,didSuspend.sibling=nextProps,workInProgress.child=didSuspend,nextProps=workInProgress.child,nextProps.memoizedState=mountSuspenseOffscreenState(renderLanes),nextProps.childLanes=getRemainingWorkInPrimaryTree(current,JSCompiler_temp,renderLanes),workInProgress.memoizedState=SUSPENDED_MARKER,bailoutOffscreenComponent(null,nextProps);return pushPrimaryTreeSuspenseHandler(workInProgress),mountSuspensePrimaryChildren(workInProgress,didSuspend)}var prevState=current.memoizedState;if(prevState!==null){var dehydrated$75=prevState.dehydrated;if(dehydrated$75!==null)return updateDehydratedSuspenseComponent(current,workInProgress,didSuspend,JSCompiler_temp,nextProps,dehydrated$75,prevState,renderLanes)}if(showFallback)return reuseSuspenseHandlerOnStack(),showFallback=nextProps.fallback,didSuspend=workInProgress.mode,prevState=current.child,dehydrated$75=prevState.sibling,nextProps=createWorkInProgress(prevState,{mode:"hidden",children:nextProps.children}),nextProps.subtreeFlags=prevState.subtreeFlags&1206910976,dehydrated$75!==null?showFallback=createWorkInProgress(dehydrated$75,showFallback):(showFallback=createFiberFromFragment(showFallback,didSuspend,renderLanes,null),showFallback.flags|=2),showFallback.return=workInProgress,nextProps.return=workInProgress,nextProps.sibling=showFallback,workInProgress.child=nextProps,bailoutOffscreenComponent(null,nextProps),nextProps=workInProgress.child,showFallback=current.child.memoizedState,showFallback===null?showFallback=mountSuspenseOffscreenState(renderLanes):(didSuspend=showFallback.cachePool,didSuspend!==null?(prevState=isPrimaryRenderer?CacheContext._currentValue:CacheContext._currentValue2,didSuspend=didSuspend.parent!==prevState?{parent:prevState,pool:prevState}:didSuspend):didSuspend=getSuspendedCache(),showFallback={baseLanes:showFallback.baseLanes|renderLanes,cachePool:didSuspend}),nextProps.memoizedState=showFallback,nextProps.childLanes=getRemainingWorkInPrimaryTree(current,JSCompiler_temp,renderLanes),workInProgress.memoizedState=SUSPENDED_MARKER,bailoutOffscreenComponent(current.child,nextProps);return pushPrimaryTreeSuspenseHandler(workInProgress),renderLanes=current.child,current=renderLanes.sibling,renderLanes=createWorkInProgress(renderLanes,{mode:"visible",children:nextProps.children}),renderLanes.return=workInProgress,renderLanes.sibling=null,current!==null&&(JSCompiler_temp=workInProgress.deletions,JSCompiler_temp===null?(workInProgress.deletions=[current],workInProgress.flags|=16):JSCompiler_temp.push(current)),workInProgress.child=renderLanes,workInProgress.memoizedState=null,renderLanes}function mountSuspensePrimaryChildren(workInProgress,primaryChildren){return primaryChildren=mountWorkInProgressOffscreenFiber({mode:"visible",children:primaryChildren},workInProgress.mode),primaryChildren.return=workInProgress,workInProgress.child=primaryChildren}function mountWorkInProgressOffscreenFiber(offscreenProps,mode){return offscreenProps=createFiber(22,offscreenProps,null,mode),offscreenProps.lanes=0,offscreenProps}function retrySuspenseComponentWithoutHydrating(current,workInProgress,renderLanes){return reconcileChildFibers(workInProgress,current.child,null,renderLanes),current=mountSuspensePrimaryChildren(workInProgress,workInProgress.pendingProps.children),current.flags|=2,workInProgress.memoizedState=null,current}function updateDehydratedSuspenseComponent(current,workInProgress,didSuspend,didPrimaryChildrenDefer,nextProps,suspenseInstance,suspenseState,renderLanes){if(didSuspend){if(workInProgress.flags&256)return pushPrimaryTreeSuspenseHandler(workInProgress),workInProgress.flags&=-257,retrySuspenseComponentWithoutHydrating(current,workInProgress,renderLanes);if(workInProgress.memoizedState!==null)return reuseSuspenseHandlerOnStack(),workInProgress.child=current.child,workInProgress.flags|=128,null;return reuseSuspenseHandlerOnStack(),suspenseInstance=nextProps.fallback,suspenseState=workInProgress.mode,nextProps=mountWorkInProgressOffscreenFiber({mode:"visible",children:nextProps.children},suspenseState),suspenseInstance=createFiberFromFragment(suspenseInstance,suspenseState,renderLanes,null),suspenseInstance.flags|=2,nextProps.return=workInProgress,suspenseInstance.return=workInProgress,nextProps.sibling=suspenseInstance,workInProgress.child=nextProps,reconcileChildFibers(workInProgress,current.child,null,renderLanes),nextProps=workInProgress.child,nextProps.memoizedState=mountSuspenseOffscreenState(renderLanes),nextProps.childLanes=getRemainingWorkInPrimaryTree(current,didPrimaryChildrenDefer,renderLanes),workInProgress.memoizedState=SUSPENDED_MARKER,bailoutOffscreenComponent(null,nextProps)}if(pushPrimaryTreeSuspenseHandler(workInProgress),isSuspenseInstanceFallback(suspenseInstance))return didPrimaryChildrenDefer=getSuspenseInstanceFallbackErrorDetails(suspenseInstance).digest,didPrimaryChildrenDefer!==""&&(nextProps=Error(formatProdErrorMessage(419)),nextProps.stack="",nextProps.digest=didPrimaryChildrenDefer,queueHydrationError({value:nextProps,source:null,stack:null})),retrySuspenseComponentWithoutHydrating(current,workInProgress,renderLanes);if(didReceiveUpdate||propagateParentContextChanges(current,workInProgress,renderLanes,!1),didPrimaryChildrenDefer=(renderLanes&current.childLanes)!==0,didReceiveUpdate||didPrimaryChildrenDefer){if(currentTreeHiddenStackCursor.current!==null)return retrySuspenseComponentWithoutHydrating(current,workInProgress,renderLanes);if(didPrimaryChildrenDefer=workInProgressRoot,didPrimaryChildrenDefer!==null&&(nextProps=getBumpedLaneForHydration(didPrimaryChildrenDefer,renderLanes),nextProps!==0&&nextProps!==suspenseState.retryLane))throw suspenseState.retryLane=nextProps,enqueueConcurrentRenderForLane(current,nextProps),scheduleUpdateOnFiber(didPrimaryChildrenDefer,current,nextProps),SelectiveHydrationException;return isSuspenseInstancePending(suspenseInstance)||renderDidSuspendDelayIfPossible(),retrySuspenseComponentWithoutHydrating(current,workInProgress,renderLanes)}if(isSuspenseInstancePending(suspenseInstance))return workInProgress.flags|=192,workInProgress.child=current.child,null;return current=suspenseState.treeContext,supportsHydration&&(nextHydratableInstance=getFirstHydratableChildWithinSuspenseInstance(suspenseInstance),hydrationParentFiber=workInProgress,isHydrating=!0,hydrationErrors=null,rootOrSingletonContext=!1,current!==null&&restoreSuspendedTreeContext(workInProgress,current)),workInProgress=mountSuspensePrimaryChildren(workInProgress,nextProps.children),workInProgress.flags|=134221824,workInProgress}function scheduleSuspenseWorkOnFiber(fiber,renderLanes,propagationRoot){fiber.lanes|=renderLanes;var alternate=fiber.alternate;alternate!==null&&(alternate.lanes|=renderLanes),scheduleContextWorkOnParentPath(fiber.return,renderLanes,propagationRoot)}function findLastContentRow(firstChild){for(var lastContentRow=null;firstChild!==null;){var currentRow=firstChild.alternate;currentRow!==null&&findFirstSuspended(currentRow)===null&&(lastContentRow=firstChild),firstChild=firstChild.sibling}return lastContentRow}function initSuspenseListRenderState(workInProgress,isBackwards,tail,lastContentRow,tailMode,treeForkCount){var renderState=workInProgress.memoizedState;renderState===null?workInProgress.memoizedState={isBackwards,rendering:null,renderingStartTime:0,last:lastContentRow,tail,tailMode,treeForkCount}:(renderState.isBackwards=isBackwards,renderState.rendering=null,renderState.renderingStartTime=0,renderState.last=lastContentRow,renderState.tail=tail,renderState.tailMode=tailMode,renderState.treeForkCount=treeForkCount)}function reverseChildren(fiber){var row=fiber.child;for(fiber.child=null;row!==null;){var nextRow=row.sibling;row.sibling=fiber.child,fiber.child=row,row=nextRow}}function updateSuspenseListComponent(current,workInProgress,renderLanes){var nextProps=workInProgress.pendingProps,revealOrder=nextProps.revealOrder,tailMode=nextProps.tail;nextProps=nextProps.children;var suspenseContext=suspenseStackCursor.current;if(workInProgress.flags&128)return pushSuspenseListContext(workInProgress,suspenseContext),null;var shouldForceFallback=(suspenseContext&2)!==0;if(shouldForceFallback?(suspenseContext=suspenseContext&1|2,workInProgress.flags|=128):suspenseContext&=1,pushSuspenseListContext(workInProgress,suspenseContext),revealOrder==="backwards"&&current!==null?(reverseChildren(current),reconcileChildren(current,workInProgress,nextProps,renderLanes),reverseChildren(current)):reconcileChildren(current,workInProgress,nextProps,renderLanes),nextProps=isHydrating?treeForkCount:0,!shouldForceFallback&&current!==null&&(current.flags&128)!==0)a:for(current=workInProgress.child;current!==null;){if(current.tag===13)current.memoizedState!==null&&scheduleSuspenseWorkOnFiber(current,renderLanes,workInProgress);else if(current.tag===19)scheduleSuspenseWorkOnFiber(current,renderLanes,workInProgress);else if(current.child!==null){current.child.return=current,current=current.child;continue}if(current===workInProgress)break a;for(;current.sibling===null;){if(current.return===null||current.return===workInProgress)break a;current=current.return}current.sibling.return=current.return,current=current.sibling}switch(revealOrder){case"backwards":renderLanes=findLastContentRow(workInProgress.child),renderLanes===null?(revealOrder=workInProgress.child,workInProgress.child=null):(revealOrder=renderLanes.sibling,renderLanes.sibling=null,reverseChildren(workInProgress)),initSuspenseListRenderState(workInProgress,!0,revealOrder,null,tailMode,nextProps);break;case"unstable_legacy-backwards":renderLanes=null,revealOrder=workInProgress.child;for(workInProgress.child=null;revealOrder!==null;){if(current=revealOrder.alternate,current!==null&&findFirstSuspended(current)===null){workInProgress.child=revealOrder;break}current=revealOrder.sibling,revealOrder.sibling=renderLanes,renderLanes=revealOrder,revealOrder=current}initSuspenseListRenderState(workInProgress,!0,renderLanes,null,tailMode,nextProps);break;case"together":initSuspenseListRenderState(workInProgress,!1,null,null,void 0,nextProps);break;case"independent":workInProgress.memoizedState=null;break;default:renderLanes=findLastContentRow(workInProgress.child),renderLanes===null?(revealOrder=workInProgress.child,workInProgress.child=null):(revealOrder=renderLanes.sibling,renderLanes.sibling=null),initSuspenseListRenderState(workInProgress,!1,revealOrder,renderLanes,tailMode,nextProps)}return workInProgress.child}function updateContextProvider(current,workInProgress,renderLanes){var newProps=workInProgress.pendingProps;return pushProvider(workInProgress,workInProgress.type,newProps.value),reconcileChildren(current,workInProgress,newProps.children,renderLanes),workInProgress.child}function bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes){if(current!==null&&(workInProgress.dependencies=current.dependencies),workInProgressRootSkippedLanes|=workInProgress.lanes,(renderLanes&workInProgress.childLanes)===0)if(current!==null){if(propagateParentContextChanges(current,workInProgress,renderLanes,!1),(renderLanes&workInProgress.childLanes)===0)return null}else return null;if(current!==null&&workInProgress.child!==current.child)throw Error(formatProdErrorMessage(153));if(workInProgress.child!==null){current=workInProgress.child,renderLanes=createWorkInProgress(current,current.pendingProps),workInProgress.child=renderLanes;for(renderLanes.return=workInProgress;current.sibling!==null;)current=current.sibling,renderLanes=renderLanes.sibling=createWorkInProgress(current,current.pendingProps),renderLanes.return=workInProgress;renderLanes.sibling=null}return workInProgress.child}function checkScheduledUpdateOrContext(current,renderLanes){if((current.lanes&renderLanes)!==0)return!0;return current=current.dependencies,current!==null&&checkIfContextChanged(current)?!0:!1}function attemptEarlyBailoutIfNoScheduledUpdate(current,workInProgress,renderLanes){switch(workInProgress.tag){case 3:pushHostContainer(workInProgress,workInProgress.stateNode.containerInfo),pushProvider(workInProgress,CacheContext,current.memoizedState.cache),resetHydrationState();break;case 27:case 5:pushHostContext(workInProgress);break;case 4:pushHostContainer(workInProgress,workInProgress.stateNode.containerInfo);break;case 10:pushProvider(workInProgress,workInProgress.type,workInProgress.memoizedProps.value);break;case 31:if(workInProgress.memoizedState!==null)return workInProgress.flags|=128,pushDehydratedActivitySuspenseHandler(workInProgress),null;break;case 13:var state$86=workInProgress.memoizedState;if(state$86!==null){if(state$86.dehydrated!==null)return pushPrimaryTreeSuspenseHandler(workInProgress),workInProgress.flags|=128,null;state$86=propagateParentContextChanges(current,workInProgress,renderLanes,!1);var primaryChildLanes=workInProgress.child.childLanes;if(state$86||(renderLanes&primaryChildLanes)!==0)return updateSuspenseComponent(current,workInProgress,renderLanes);return pushPrimaryTreeSuspenseHandler(workInProgress),current=bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes),current!==null?current.sibling:null}pushPrimaryTreeSuspenseHandler(workInProgress);break;case 19:if(workInProgress.flags&128)return updateSuspenseListComponent(current,workInProgress,renderLanes);if(primaryChildLanes=(current.flags&128)!==0,state$86=(renderLanes&workInProgress.childLanes)!==0,state$86||(propagateParentContextChanges(current,workInProgress,renderLanes,!1),state$86=(renderLanes&workInProgress.childLanes)!==0),primaryChildLanes){if(state$86)return updateSuspenseListComponent(current,workInProgress,renderLanes);workInProgress.flags|=128}if(primaryChildLanes=workInProgress.memoizedState,primaryChildLanes!==null&&(primaryChildLanes.rendering=null,primaryChildLanes.tail=null,primaryChildLanes.lastEffect=null),pushSuspenseListContext(workInProgress,suspenseStackCursor.current),state$86)break;else return null;case 22:return workInProgress.lanes=0,updateOffscreenComponent(current,workInProgress,renderLanes,workInProgress.pendingProps);case 24:pushProvider(workInProgress,CacheContext,current.memoizedState.cache)}return bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes)}function beginWork(current,workInProgress,renderLanes){if(current!==null)if(current.memoizedProps!==workInProgress.pendingProps)didReceiveUpdate=!0;else{if(!checkScheduledUpdateOrContext(current,renderLanes)&&(workInProgress.flags&128)===0)return didReceiveUpdate=!1,attemptEarlyBailoutIfNoScheduledUpdate(current,workInProgress,renderLanes);didReceiveUpdate=(current.flags&131072)!==0?!0:!1}else didReceiveUpdate=!1,isHydrating&&(workInProgress.flags&1048576)!==0&&pushTreeId(workInProgress,treeForkCount,workInProgress.index);switch(workInProgress.lanes=0,workInProgress.tag){case 16:a:{var props=workInProgress.pendingProps;if(current=resolveLazy(workInProgress.elementType),workInProgress.type=current,typeof current==="function")shouldConstruct(current)?(props=resolveClassComponentProps(current,props),workInProgress.tag=1,workInProgress=updateClassComponent(null,workInProgress,current,props,renderLanes)):(workInProgress.tag=0,workInProgress=updateFunctionComponent(null,workInProgress,current,props,renderLanes));else{if(current!==void 0&&current!==null){var $$typeof=current.$$typeof;if($$typeof===REACT_FORWARD_REF_TYPE){workInProgress.tag=11,workInProgress=updateForwardRef(null,workInProgress,current,props,renderLanes);break a}else if($$typeof===REACT_MEMO_TYPE){workInProgress.tag=14,workInProgress=updateMemoComponent(null,workInProgress,current,props,renderLanes);break a}else if($$typeof===REACT_CONTEXT_TYPE){workInProgress.tag=10,workInProgress.type=current,workInProgress=updateContextProvider(null,workInProgress,renderLanes);break a}}throw workInProgress=getComponentNameFromType(current)||current,Error(formatProdErrorMessage(306,workInProgress,""))}}return workInProgress;case 0:return updateFunctionComponent(current,workInProgress,workInProgress.type,workInProgress.pendingProps,renderLanes);case 1:return props=workInProgress.type,$$typeof=resolveClassComponentProps(props,workInProgress.pendingProps),updateClassComponent(current,workInProgress,props,$$typeof,renderLanes);case 3:a:{if(pushHostContainer(workInProgress,workInProgress.stateNode.containerInfo),current===null)throw Error(formatProdErrorMessage(387));var nextProps=workInProgress.pendingProps;$$typeof=workInProgress.memoizedState,props=$$typeof.element,cloneUpdateQueue(current,workInProgress),processUpdateQueue(workInProgress,nextProps,null,renderLanes);var nextState=workInProgress.memoizedState;if(nextProps=nextState.cache,pushProvider(workInProgress,CacheContext,nextProps),nextProps!==$$typeof.cache&&propagateContextChanges(workInProgress,[CacheContext],renderLanes,!0),suspendIfUpdateReadFromEntangledAsyncAction(),nextProps=nextState.element,supportsHydration&&$$typeof.isDehydrated)if($$typeof={element:nextProps,isDehydrated:!1,cache:nextState.cache},workInProgress.updateQueue.baseState=$$typeof,workInProgress.memoizedState=$$typeof,workInProgress.flags&256){workInProgress=mountHostRootWithoutHydrating(current,workInProgress,nextProps,renderLanes);break a}else if(nextProps!==props){props=createCapturedValueAtFiber(Error(formatProdErrorMessage(424)),workInProgress),queueHydrationError(props),workInProgress=mountHostRootWithoutHydrating(current,workInProgress,nextProps,renderLanes);break a}else for(supportsHydration&&(nextHydratableInstance=getFirstHydratableChildWithinContainer(workInProgress.stateNode.containerInfo),hydrationParentFiber=workInProgress,isHydrating=!0,hydrationErrors=null,rootOrSingletonContext=!0),renderLanes=mountChildFibers(workInProgress,null,nextProps,renderLanes),workInProgress.child=renderLanes;renderLanes;)renderLanes.flags=renderLanes.flags&-3|134221824,renderLanes=renderLanes.sibling;else{if(resetHydrationState(),nextProps===props){workInProgress=bailoutOnAlreadyFinishedWork(current,workInProgress,renderLanes);break a}reconcileChildren(current,workInProgress,nextProps,renderLanes)}workInProgress=workInProgress.child}return workInProgress;case 26:if(supportsResources)return markRef(current,workInProgress),current===null?(renderLanes=getResource(workInProgress.type,null,workInProgress.pendingProps,null))?workInProgress.memoizedState=renderLanes:isHydrating||(workInProgress.stateNode=createHoistableInstance(workInProgress.type,workInProgress.pendingProps,rootInstanceStackCursor.current,workInProgress)):workInProgress.memoizedState=getResource(workInProgress.type,current.memoizedProps,workInProgress.pendingProps,current.memoizedState),null;case 27:if(supportsSingletons)return pushHostContext(workInProgress),current===null&&supportsSingletons&&isHydrating&&(props=workInProgress.stateNode=resolveSingletonInstance(workInProgress.type,workInProgress.pendingProps,rootInstanceStackCursor.current,contextStackCursor.current,!1),hydrationParentFiber=workInProgress,rootOrSingletonContext=!0,nextHydratableInstance=getFirstHydratableChildWithinSingleton(workInProgress.type,props,nextHydratableInstance)),reconcileChildren(current,workInProgress,workInProgress.pendingProps.children,renderLanes),markRef(current,workInProgress),current===null&&(workInProgress.flags|=4194304),workInProgress.child;case 5:if(current===null&&isHydrating){if(validateHydratableInstance(workInProgress.type,workInProgress.pendingProps,contextStackCursor.current),$$typeof=props=nextHydratableInstance)props=canHydrateInstance(props,workInProgress.type,workInProgress.pendingProps,rootOrSingletonContext),props!==null?(workInProgress.stateNode=props,hydrationParentFiber=workInProgress,nextHydratableInstance=getFirstHydratableChild(props),rootOrSingletonContext=!1,$$typeof=!0):$$typeof=!1;$$typeof||throwOnHydrationMismatch(workInProgress)}return pushHostContext(workInProgress),$$typeof=workInProgress.type,nextProps=workInProgress.pendingProps,nextState=current!==null?current.memoizedProps:null,props=nextProps.children,shouldSetTextContent($$typeof,nextProps)?props=null:nextState!==null&&shouldSetTextContent($$typeof,nextState)&&(workInProgress.flags|=32),workInProgress.memoizedState!==null&&($$typeof=renderWithHooks(current,workInProgress,TransitionAwareHostComponent,null,null,renderLanes),isPrimaryRenderer?HostTransitionContext._currentValue=$$typeof:HostTransitionContext._currentValue2=$$typeof),markRef(current,workInProgress),reconcileChildren(current,workInProgress,props,renderLanes),workInProgress.child;case 6:if(current===null&&isHydrating){if(validateHydratableTextInstance(workInProgress.pendingProps,contextStackCursor.current),current=renderLanes=nextHydratableInstance)renderLanes=canHydrateTextInstance(renderLanes,workInProgress.pendingProps,rootOrSingletonContext),renderLanes!==null?(workInProgress.stateNode=renderLanes,hydrationParentFiber=workInProgress,nextHydratableInstance=null,current=!0):current=!1;current||throwOnHydrationMismatch(workInProgress)}return null;case 13:return updateSuspenseComponent(current,workInProgress,renderLanes);case 4:return pushHostContainer(workInProgress,workInProgress.stateNode.containerInfo),props=workInProgress.pendingProps,current===null?workInProgress.child=reconcileChildFibers(workInProgress,null,props,renderLanes):reconcileChildren(current,workInProgress,props,renderLanes),workInProgress.child;case 11:return updateForwardRef(current,workInProgress,workInProgress.type,workInProgress.pendingProps,renderLanes);case 7:return props=workInProgress.pendingProps,markRef(current,workInProgress),reconcileChildren(current,workInProgress,props,renderLanes),workInProgress.child;case 8:return reconcileChildren(current,workInProgress,workInProgress.pendingProps.children,renderLanes),workInProgress.child;case 12:return reconcileChildren(current,workInProgress,workInProgress.pendingProps.children,renderLanes),workInProgress.child;case 10:return updateContextProvider(current,workInProgress,renderLanes);case 9:return $$typeof=workInProgress.type._context,props=workInProgress.pendingProps.children,prepareToReadContext(workInProgress),$$typeof=readContext($$typeof),props=props($$typeof),workInProgress.flags|=1,reconcileChildren(current,workInProgress,props,renderLanes),workInProgress.child;case 14:return updateMemoComponent(current,workInProgress,workInProgress.type,workInProgress.pendingProps,renderLanes);case 15:return updateSimpleMemoComponent(current,workInProgress,workInProgress.type,workInProgress.pendingProps,renderLanes);case 19:return updateSuspenseListComponent(current,workInProgress,renderLanes);case 31:return updateActivityComponent(current,workInProgress,renderLanes);case 22:return updateOffscreenComponent(current,workInProgress,renderLanes,workInProgress.pendingProps);case 24:return prepareToReadContext(workInProgress),props=readContext(CacheContext),current===null?($$typeof=peekCacheFromPool(),$$typeof===null&&($$typeof=workInProgressRoot,nextProps=createCache(),$$typeof.pooledCache=nextProps,nextProps.refCount++,nextProps!==null&&($$typeof.pooledCacheLanes|=renderLanes),$$typeof=nextProps),workInProgress.memoizedState={parent:props,cache:$$typeof},initializeUpdateQueue(workInProgress),pushProvider(workInProgress,CacheContext,$$typeof)):((current.lanes&renderLanes)!==0&&(cloneUpdateQueue(current,workInProgress),processUpdateQueue(workInProgress,null,null,renderLanes),suspendIfUpdateReadFromEntangledAsyncAction()),$$typeof=current.memoizedState,nextProps=workInProgress.memoizedState,$$typeof.parent!==props?($$typeof={parent:props,cache:props},workInProgress.memoizedState=$$typeof,workInProgress.lanes===0&&(workInProgress.memoizedState=workInProgress.updateQueue.baseState=$$typeof),pushProvider(workInProgress,CacheContext,props)):(props=nextProps.cache,pushProvider(workInProgress,CacheContext,props),props!==$$typeof.cache&&propagateContextChanges(workInProgress,[CacheContext],renderLanes,!0))),reconcileChildren(current,workInProgress,workInProgress.pendingProps.children,renderLanes),workInProgress.child;case 30:return workInProgress.stateNode===null&&(workInProgress.stateNode={autoName:null,paired:null,clones:null,ref:null}),props=workInProgress.pendingProps,props.name!=null&&props.name!=="auto"?workInProgress.flags|=current===null?18882560:18874368:isHydrating&&pushMaterializedTreeId(workInProgress),current!==null&&current.memoizedProps.name!==props.name?workInProgress.flags|=4194816:markRef(current,workInProgress),reconcileChildren(current,workInProgress,props.children,renderLanes),workInProgress.child;case 29:throw workInProgress.pendingProps}throw Error(formatProdErrorMessage(156,workInProgress.tag))}function markUpdate(workInProgress){workInProgress.flags|=4}function markCloned(workInProgress){supportsPersistence&&(workInProgress.flags|=8)}function doesRequireClone(current,completedWork){if(current!==null&&current.child===completedWork.child)return!1;if((completedWork.flags&16)!==0)return!0;for(current=completedWork.child;current!==null;){if((current.flags&8218)!==0||(current.subtreeFlags&8218)!==0)return!0;current=current.sibling}return!1}function appendAllChildren(parent,workInProgress,needsVisibilityToggle,isHidden){if(supportsMutation)for(needsVisibilityToggle=workInProgress.child;needsVisibilityToggle!==null;){if(needsVisibilityToggle.tag===5||needsVisibilityToggle.tag===6)appendInitialChild(parent,needsVisibilityToggle.stateNode);else if(!(needsVisibilityToggle.tag===4||supportsSingletons&&needsVisibilityToggle.tag===27)&&needsVisibilityToggle.child!==null){needsVisibilityToggle.child.return=needsVisibilityToggle,needsVisibilityToggle=needsVisibilityToggle.child;continue}if(needsVisibilityToggle===workInProgress)break;for(;needsVisibilityToggle.sibling===null;){if(needsVisibilityToggle.return===null||needsVisibilityToggle.return===workInProgress)return;needsVisibilityToggle=needsVisibilityToggle.return}needsVisibilityToggle.sibling.return=needsVisibilityToggle.return,needsVisibilityToggle=needsVisibilityToggle.sibling}else if(supportsPersistence)for(var node$89=workInProgress.child;node$89!==null;){if(node$89.tag===5){var instance=node$89.stateNode;needsVisibilityToggle&&isHidden&&(instance=cloneHiddenInstance(instance,node$89.type,node$89.memoizedProps)),appendInitialChild(parent,instance)}else if(node$89.tag===6)instance=node$89.stateNode,needsVisibilityToggle&&isHidden&&(instance=cloneHiddenTextInstance(instance,node$89.memoizedProps)),appendInitialChild(parent,instance);else if(node$89.tag!==4){if(node$89.tag===22&&node$89.memoizedState!==null)instance=node$89.child,instance!==null&&(instance.return=node$89),appendAllChildren(parent,node$89,!0,!0);else if(node$89.child!==null){node$89.child.return=node$89,node$89=node$89.child;continue}}if(node$89===workInProgress)break;for(;node$89.sibling===null;){if(node$89.return===null||node$89.return===workInProgress)return;node$89=node$89.return}node$89.sibling.return=node$89.return,node$89=node$89.sibling}}function appendAllChildrenToContainer(containerChildSet,workInProgress,needsVisibilityToggle,isHidden){var hasOffscreenComponentChild=!1;if(supportsPersistence)for(var node=workInProgress.child;node!==null;){if(node.tag===5){var instance=node.stateNode;needsVisibilityToggle&&isHidden&&(instance=cloneHiddenInstance(instance,node.type,node.memoizedProps)),appendChildToContainerChildSet(containerChildSet,instance)}else if(node.tag===6)instance=node.stateNode,needsVisibilityToggle&&isHidden&&(instance=cloneHiddenTextInstance(instance,node.memoizedProps)),appendChildToContainerChildSet(containerChildSet,instance);else if(node.tag!==4){if(node.tag===22&&node.memoizedState!==null)hasOffscreenComponentChild=node.child,hasOffscreenComponentChild!==null&&(hasOffscreenComponentChild.return=node),appendAllChildrenToContainer(containerChildSet,node,!0,!0),hasOffscreenComponentChild=!0;else if(node.child!==null){node.child.return=node,node=node.child;continue}}if(node===workInProgress)break;for(;node.sibling===null;){if(node.return===null||node.return===workInProgress)return hasOffscreenComponentChild;node=node.return}node.sibling.return=node.return,node=node.sibling}return hasOffscreenComponentChild}function updateHostContainer(current,workInProgress){if(supportsPersistence&&doesRequireClone(current,workInProgress)){current=workInProgress.stateNode;var container=current.containerInfo,newChildSet=createContainerChildSet();appendAllChildrenToContainer(newChildSet,workInProgress,!1,!1),current.pendingChildren=newChildSet,markUpdate(workInProgress),finalizeContainerChildren(container,newChildSet)}}function updateHostComponent(current,workInProgress,type,newProps){if(supportsMutation)current.memoizedProps!==newProps&&markUpdate(workInProgress);else if(supportsPersistence){var currentInstance=current.stateNode,oldProps$92=current.memoizedProps;if((current=doesRequireClone(current,workInProgress))||oldProps$92!==newProps){var currentHostContext=contextStackCursor.current;oldProps$92=cloneInstance(currentInstance,type,oldProps$92,newProps,!current,null),oldProps$92===currentInstance?workInProgress.stateNode=currentInstance:(markCloned(workInProgress),finalizeInitialChildren(oldProps$92,type,newProps,currentHostContext)&&markUpdate(workInProgress),workInProgress.stateNode=oldProps$92,current&&appendAllChildren(oldProps$92,workInProgress,!1,!1))}else workInProgress.stateNode=currentInstance}}function preloadInstanceAndSuspendIfNeeded(workInProgress,type,oldProps,newProps,renderLanes){if((workInProgress.mode&32)!==0&&(oldProps===null?maySuspendCommit(type,newProps):maySuspendCommitOnUpdate(type,oldProps,newProps))){if(workInProgress.flags|=16777216,(renderLanes&335544128)===renderLanes||maySuspendCommitInSyncRender(type,newProps))if(preloadInstance(workInProgress.stateNode,type,newProps))workInProgress.flags|=8192;else if(shouldRemainOnPreviousScreen())workInProgress.flags|=8192;else throw suspendedThenable=noopSuspenseyCommitThenable,SuspenseyCommitException}else workInProgress.flags&=-16777217}function preloadResourceAndSuspendIfNeeded(workInProgress,resource){if(mayResourceSuspendCommit(resource)){if(workInProgress.flags|=16777216,!preloadResource(resource))if(shouldRemainOnPreviousScreen())workInProgress.flags|=8192;else throw suspendedThenable=noopSuspenseyCommitThenable,SuspenseyCommitException}else workInProgress.flags&=-16777217}function scheduleRetryEffect(workInProgress,retryQueue){retryQueue!==null&&(workInProgress.flags|=4),workInProgress.flags&16384&&(retryQueue=workInProgress.tag!==22?claimNextRetryLane():536870912,workInProgress.lanes|=retryQueue,workInProgressSuspendedRetryLanes|=retryQueue)}function cutOffTailIfNeeded(renderState,hasRenderedATailFallback){if(!isHydrating)switch(renderState.tailMode){case"visible":break;case"collapsed":for(var tailNode=renderState.tail,lastTailNode=null;tailNode!==null;)tailNode.alternate!==null&&(lastTailNode=tailNode),tailNode=tailNode.sibling;lastTailNode===null?hasRenderedATailFallback||renderState.tail===null?renderState.tail=null:renderState.tail.sibling=null:lastTailNode.sibling=null;break;default:hasRenderedATailFallback=renderState.tail;for(tailNode=null;hasRenderedATailFallback!==null;)hasRenderedATailFallback.alternate!==null&&(tailNode=hasRenderedATailFallback),hasRenderedATailFallback=hasRenderedATailFallback.sibling;tailNode===null?renderState.tail=null:tailNode.sibling=null}}function bubbleProperties(completedWork){var didBailout=completedWork.alternate!==null&&completedWork.alternate.child===completedWork.child,newChildLanes=0,subtreeFlags=0;if(didBailout)for(var child$95=completedWork.child;child$95!==null;)newChildLanes|=child$95.lanes|child$95.childLanes,subtreeFlags|=child$95.subtreeFlags&1206910976,subtreeFlags|=child$95.flags&1206910976,child$95.return=completedWork,child$95=child$95.sibling;else for(child$95=completedWork.child;child$95!==null;)newChildLanes|=child$95.lanes|child$95.childLanes,subtreeFlags|=child$95.subtreeFlags,subtreeFlags|=child$95.flags,child$95.return=completedWork,child$95=child$95.sibling;return completedWork.subtreeFlags|=subtreeFlags,completedWork.childLanes=newChildLanes,didBailout}function completeWork(current,workInProgress,renderLanes){var newProps=workInProgress.pendingProps;switch(popTreeContext(workInProgress),workInProgress.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return bubbleProperties(workInProgress),null;case 1:return bubbleProperties(workInProgress),null;case 3:if(renderLanes=workInProgress.stateNode,newProps=null,current!==null&&(newProps=current.memoizedState.cache),workInProgress.memoizedState.cache!==newProps&&(workInProgress.flags|=2048),popProvider(CacheContext),popHostContainer(),renderLanes.pendingContext&&(renderLanes.context=renderLanes.pendingContext,renderLanes.pendingContext=null),current===null||current.child===null)popHydrationState(workInProgress)?markUpdate(workInProgress):current===null||current.memoizedState.isDehydrated&&(workInProgress.flags&256)===0||(workInProgress.flags|=1024,upgradeHydrationErrorsToRecoverable());return updateHostContainer(current,workInProgress),bubbleProperties(workInProgress),null;case 26:if(supportsResources){var{type,memoizedState:nextResource}=workInProgress;return current===null?(markUpdate(workInProgress),nextResource!==null?(bubbleProperties(workInProgress),preloadResourceAndSuspendIfNeeded(workInProgress,nextResource)):(bubbleProperties(workInProgress),preloadInstanceAndSuspendIfNeeded(workInProgress,type,null,newProps,renderLanes))):nextResource?nextResource!==current.memoizedState?(markUpdate(workInProgress),bubbleProperties(workInProgress),preloadResourceAndSuspendIfNeeded(workInProgress,nextResource)):(bubbleProperties(workInProgress),workInProgress.flags&=-16777217):(nextResource=current.memoizedProps,supportsMutation?nextResource!==newProps&&markUpdate(workInProgress):updateHostComponent(current,workInProgress,type,newProps),bubbleProperties(workInProgress),preloadInstanceAndSuspendIfNeeded(workInProgress,type,nextResource,newProps,renderLanes)),null}case 27:if(supportsSingletons){if(popHostContext(workInProgress),renderLanes=rootInstanceStackCursor.current,type=workInProgress.type,current!==null&&workInProgress.stateNode!=null)supportsMutation?current.memoizedProps!==newProps&&markUpdate(workInProgress):updateHostComponent(current,workInProgress,type,newProps);else{if(!newProps){if(workInProgress.stateNode===null)throw Error(formatProdErrorMessage(166));return bubbleProperties(workInProgress),workInProgress.subtreeFlags&=-33554433,null}current=contextStackCursor.current,popHydrationState(workInProgress)?prepareToHydrateHostInstance(workInProgress,current):(current=resolveSingletonInstance(type,newProps,renderLanes,current,!0),workInProgress.stateNode=current,markUpdate(workInProgress))}return bubbleProperties(workInProgress),workInProgress.subtreeFlags&=-33554433,null}case 5:if(popHostContext(workInProgress),type=workInProgress.type,current!==null&&workInProgress.stateNode!=null)updateHostComponent(current,workInProgress,type,newProps);else{if(!newProps){if(workInProgress.stateNode===null)throw Error(formatProdErrorMessage(166));return bubbleProperties(workInProgress),workInProgress.subtreeFlags&=-33554433,null}if(nextResource=contextStackCursor.current,popHydrationState(workInProgress))prepareToHydrateHostInstance(workInProgress,nextResource),finalizeHydratedChildren(workInProgress.stateNode,type,newProps,nextResource)&&(workInProgress.flags|=64);else{var instance$105=createInstance(type,newProps,rootInstanceStackCursor.current,nextResource,workInProgress);markCloned(workInProgress),appendAllChildren(instance$105,workInProgress,!1,!1),workInProgress.stateNode=instance$105,finalizeInitialChildren(instance$105,type,newProps,nextResource)&&markUpdate(workInProgress)}}return bubbleProperties(workInProgress),workInProgress.subtreeFlags&=-33554433,preloadInstanceAndSuspendIfNeeded(workInProgress,workInProgress.type,current===null?null:current.memoizedProps,workInProgress.pendingProps,renderLanes),null;case 6:if(current&&workInProgress.stateNode!=null)renderLanes=current.memoizedProps,supportsMutation?renderLanes!==newProps&&markUpdate(workInProgress):supportsPersistence&&(renderLanes!==newProps?(current=rootInstanceStackCursor.current,renderLanes=contextStackCursor.current,markCloned(workInProgress),workInProgress.stateNode=createTextInstance(newProps,current,renderLanes,workInProgress)):workInProgress.stateNode=current.stateNode);else{if(typeof newProps!=="string"&&workInProgress.stateNode===null)throw Error(formatProdErrorMessage(166));if(current=rootInstanceStackCursor.current,renderLanes=contextStackCursor.current,popHydrationState(workInProgress)){if(!supportsHydration)throw Error(formatProdErrorMessage(176));if(current=workInProgress.stateNode,renderLanes=workInProgress.memoizedProps,newProps=null,type=hydrationParentFiber,type!==null)switch(type.tag){case 27:case 5:newProps=type.memoizedProps}hydrateTextInstance(current,renderLanes,workInProgress,newProps)||throwOnHydrationMismatch(workInProgress,!0)}else markCloned(workInProgress),workInProgress.stateNode=createTextInstance(newProps,current,renderLanes,workInProgress)}return bubbleProperties(workInProgress),null;case 31:if(renderLanes=workInProgress.memoizedState,current===null||current.memoizedState!==null){if(newProps=popHydrationState(workInProgress),renderLanes!==null){if(current===null){if(!newProps)throw Error(formatProdErrorMessage(318));if(!supportsHydration)throw Error(formatProdErrorMessage(556));if(current=workInProgress.memoizedState,current=current!==null?current.dehydrated:null,!current)throw Error(formatProdErrorMessage(557));hydrateActivityInstance(current,workInProgress)}else resetHydrationState(),(workInProgress.flags&128)===0&&(workInProgress.memoizedState=null),workInProgress.flags|=4;bubbleProperties(workInProgress),current=!1}else renderLanes=upgradeHydrationErrorsToRecoverable(),current!==null&&current.memoizedState!==null&&(current.memoizedState.hydrationErrors=renderLanes),current=!0;if(!current){if(workInProgress.flags&256)return popSuspenseHandler(workInProgress),workInProgress;return popSuspenseHandler(workInProgress),null}if((workInProgress.flags&128)!==0)throw Error(formatProdErrorMessage(558))}return bubbleProperties(workInProgress),null;case 13:if(newProps=workInProgress.memoizedState,current===null||current.memoizedState!==null&&current.memoizedState.dehydrated!==null){if(type=popHydrationState(workInProgress),newProps!==null&&newProps.dehydrated!==null){if(current===null){if(!type)throw Error(formatProdErrorMessage(318));if(!supportsHydration)throw Error(formatProdErrorMessage(344));if(type=workInProgress.memoizedState,type=type!==null?type.dehydrated:null,!type)throw Error(formatProdErrorMessage(317));hydrateSuspenseInstance(type,workInProgress)}else resetHydrationState(),(workInProgress.flags&128)===0&&(workInProgress.memoizedState=null),workInProgress.flags|=4;bubbleProperties(workInProgress),type=!1}else type=upgradeHydrationErrorsToRecoverable(),current!==null&&current.memoizedState!==null&&(current.memoizedState.hydrationErrors=type),type=!0;if(!type){if(workInProgress.flags&256)return popSuspenseHandler(workInProgress),workInProgress;return popSuspenseHandler(workInProgress),null}}if(popSuspenseHandler(workInProgress),(workInProgress.flags&128)!==0)return workInProgress.lanes=renderLanes,workInProgress;return renderLanes=newProps!==null,current=current!==null&&current.memoizedState!==null,renderLanes&&(newProps=workInProgress.child,type=null,newProps.alternate!==null&&newProps.alternate.memoizedState!==null&&newProps.alternate.memoizedState.cachePool!==null&&(type=newProps.alternate.memoizedState.cachePool.pool),nextResource=null,newProps.memoizedState!==null&&newProps.memoizedState.cachePool!==null&&(nextResource=newProps.memoizedState.cachePool.pool),nextResource!==type&&(newProps.flags|=2048)),renderLanes!==current&&renderLanes&&(workInProgress.child.flags|=8192),scheduleRetryEffect(workInProgress,workInProgress.updateQueue),bubbleProperties(workInProgress),null;case 4:return popHostContainer(),updateHostContainer(current,workInProgress),current===null&&preparePortalMount(workInProgress.stateNode.containerInfo),workInProgress.flags|=67108864,bubbleProperties(workInProgress),null;case 10:return popProvider(workInProgress.type),bubbleProperties(workInProgress),null;case 19:if(popSuspenseListContext(workInProgress),newProps=workInProgress.memoizedState,newProps===null)return bubbleProperties(workInProgress),null;if(type=(workInProgress.flags&128)!==0,nextResource=newProps.rendering,nextResource===null)if(type)cutOffTailIfNeeded(newProps,!1);else{if(workInProgressRootExitStatus!==0||current!==null&&(current.flags&128)!==0)for(current=workInProgress.child;current!==null;){if(nextResource=findFirstSuspended(current),nextResource!==null){workInProgress.flags|=128,cutOffTailIfNeeded(newProps,!1),current=nextResource.updateQueue,workInProgress.updateQueue=current,scheduleRetryEffect(workInProgress,current),workInProgress.subtreeFlags=0,current=renderLanes;for(renderLanes=workInProgress.child;renderLanes!==null;)resetWorkInProgress(renderLanes,current),renderLanes=renderLanes.sibling;return pushSuspenseListContext(workInProgress,suspenseStackCursor.current&1|2),isHydrating&&pushTreeFork(workInProgress,newProps.treeForkCount),workInProgress.child}current=current.sibling}newProps.tail!==null&&now()>workInProgressRootRenderTargetTime&&(workInProgress.flags|=128,type=!0,cutOffTailIfNeeded(newProps,!1),workInProgress.lanes=4194304)}else{if(!type)if(current=findFirstSuspended(nextResource),current!==null){if(workInProgress.flags|=128,type=!0,current=current.updateQueue,workInProgress.updateQueue=current,scheduleRetryEffect(workInProgress,current),cutOffTailIfNeeded(newProps,!0),newProps.tail===null&&newProps.tailMode!=="collapsed"&&newProps.tailMode!=="visible"&&!nextResource.alternate&&!isHydrating)return bubbleProperties(workInProgress),null}else 2*now()-newProps.renderingStartTime>workInProgressRootRenderTargetTime&&renderLanes!==536870912&&(workInProgress.flags|=128,type=!0,cutOffTailIfNeeded(newProps,!1),workInProgress.lanes=4194304);newProps.isBackwards?(nextResource.sibling=workInProgress.child,workInProgress.child=nextResource):(current=newProps.last,current!==null?current.sibling=nextResource:workInProgress.child=nextResource,newProps.last=nextResource)}if(newProps.tail!==null){current=newProps.tail;a:{for(renderLanes=current;renderLanes!==null;){if(renderLanes.alternate!==null){renderLanes=!1;break a}renderLanes=renderLanes.sibling}renderLanes=!0}return newProps.rendering=current,newProps.tail=current.sibling,newProps.renderingStartTime=now(),current.sibling=null,nextResource=suspenseStackCursor.current,nextResource=type?nextResource&1|2:nextResource&1,newProps.tailMode==="visible"||newProps.tailMode==="collapsed"||!renderLanes||isHydrating?pushSuspenseListContext(workInProgress,nextResource):(renderLanes=nextResource,push(suspenseHandlerStackCursor,workInProgress),push(suspenseStackCursor,renderLanes),shellBoundary===null&&(shellBoundary=workInProgress)),isHydrating&&pushTreeFork(workInProgress,newProps.treeForkCount),current}return bubbleProperties(workInProgress),null;case 22:case 23:return popSuspenseHandler(workInProgress),popHiddenContext(),newProps=workInProgress.memoizedState!==null,current!==null?current.memoizedState!==null!==newProps&&(workInProgress.flags|=8192):newProps&&(workInProgress.flags|=8192),newProps?(renderLanes&536870912)!==0&&(workInProgress.flags&128)===0&&(bubbleProperties(workInProgress),workInProgress.subtreeFlags&6&&(workInProgress.flags|=8192)):bubbleProperties(workInProgress),renderLanes=workInProgress.updateQueue,renderLanes!==null&&scheduleRetryEffect(workInProgress,renderLanes.retryQueue),renderLanes=null,current!==null&&current.memoizedState!==null&&current.memoizedState.cachePool!==null&&(renderLanes=current.memoizedState.cachePool.pool),newProps=null,workInProgress.memoizedState!==null&&workInProgress.memoizedState.cachePool!==null&&(newProps=workInProgress.memoizedState.cachePool.pool),newProps!==renderLanes&&(workInProgress.flags|=2048),current!==null&&pop(resumedCache),null;case 24:return renderLanes=null,current!==null&&(renderLanes=current.memoizedState.cache),workInProgress.memoizedState.cache!==renderLanes&&(workInProgress.flags|=2048),popProvider(CacheContext),bubbleProperties(workInProgress),null;case 25:return null;case 30:return workInProgress.flags|=33554432,bubbleProperties(workInProgress),null}throw Error(formatProdErrorMessage(156,workInProgress.tag))}function unwindWork(current,workInProgress){switch(popTreeContext(workInProgress),workInProgress.tag){case 1:return current=workInProgress.flags,current&65536?(workInProgress.flags=current&-65537|128,workInProgress):null;case 3:return popProvider(CacheContext),popHostContainer(),current=workInProgress.flags,(current&65536)!==0&&(current&128)===0?(workInProgress.flags=current&-65537|128,workInProgress):null;case 26:case 27:case 5:return popHostContext(workInProgress),null;case 31:if(workInProgress.memoizedState!==null){if(popSuspenseHandler(workInProgress),workInProgress.alternate===null)throw Error(formatProdErrorMessage(340));resetHydrationState()}return current=workInProgress.flags,current&65536?(workInProgress.flags=current&-65537|128,workInProgress):null;case 13:if(popSuspenseHandler(workInProgress),current=workInProgress.memoizedState,current!==null&&current.dehydrated!==null){if(workInProgress.alternate===null)throw Error(formatProdErrorMessage(340));resetHydrationState()}return current=workInProgress.flags,current&65536?(workInProgress.flags=current&-65537|128,workInProgress):null;case 19:return popSuspenseListContext(workInProgress),current=workInProgress.flags,current&65536?(workInProgress.flags=current&-65537|128,current=workInProgress.memoizedState,current!==null&&(current.rendering=null,current.tail=null),workInProgress.flags|=4,workInProgress):null;case 4:return popHostContainer(),null;case 10:return popProvider(workInProgress.type),null;case 22:case 23:return popSuspenseHandler(workInProgress),popHiddenContext(),current!==null&&pop(resumedCache),current=workInProgress.flags,current&65536?(workInProgress.flags=current&-65537|128,workInProgress):null;case 24:return popProvider(CacheContext),null;case 25:return null;default:return null}}function unwindInterruptedWork(current,interruptedWork){switch(popTreeContext(interruptedWork),interruptedWork.tag){case 3:popProvider(CacheContext),popHostContainer();break;case 26:case 27:case 5:popHostContext(interruptedWork);break;case 4:popHostContainer();break;case 31:interruptedWork.memoizedState!==null&&popSuspenseHandler(interruptedWork);break;case 13:popSuspenseHandler(interruptedWork);break;case 19:popSuspenseListContext(interruptedWork);break;case 10:popProvider(interruptedWork.type);break;case 22:case 23:popSuspenseHandler(interruptedWork),popHiddenContext(),current!==null&&pop(resumedCache);break;case 24:popProvider(CacheContext)}}function commitHookEffectListMount(flags,finishedWork){try{var updateQueue=finishedWork.updateQueue,lastEffect=updateQueue!==null?updateQueue.lastEffect:null;if(lastEffect!==null){var firstEffect=lastEffect.next;updateQueue=firstEffect;do{if((updateQueue.tag&flags)===flags){lastEffect=void 0;var create=updateQueue.create,inst=updateQueue.inst;lastEffect=create(),inst.destroy=lastEffect}updateQueue=updateQueue.next}while(updateQueue!==firstEffect)}}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}function commitHookEffectListUnmount(flags,finishedWork,nearestMountedAncestor$jscomp$0){try{var updateQueue=finishedWork.updateQueue,lastEffect=updateQueue!==null?updateQueue.lastEffect:null;if(lastEffect!==null){var firstEffect=lastEffect.next;updateQueue=firstEffect;do{if((updateQueue.tag&flags)===flags){var inst=updateQueue.inst,destroy=inst.destroy;if(destroy!==void 0){inst.destroy=void 0,lastEffect=finishedWork;var nearestMountedAncestor=nearestMountedAncestor$jscomp$0,destroy_=destroy;try{destroy_()}catch(error){captureCommitPhaseError(lastEffect,nearestMountedAncestor,error)}}}updateQueue=updateQueue.next}while(updateQueue!==firstEffect)}}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}function commitClassCallbacks(finishedWork){var updateQueue=finishedWork.updateQueue;if(updateQueue!==null){var instance=finishedWork.stateNode;try{commitCallbacks(updateQueue,instance)}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}}function safelyCallComponentWillUnmount(current,nearestMountedAncestor,instance){instance.props=resolveClassComponentProps(current.type,current.memoizedProps),instance.state=current.memoizedState;try{instance.componentWillUnmount()}catch(error){captureCommitPhaseError(current,nearestMountedAncestor,error)}}function safelyAttachRef(current,nearestMountedAncestor){try{var ref=current.ref;if(ref!==null){switch(current.tag){case 26:case 27:case 5:var instanceToUse=getPublicInstance(current.stateNode);break;case 30:var instance=current.stateNode,name=getViewTransitionName(current.memoizedProps,instance);if(instance.ref===null||instance.ref.name!==name)instance.ref=createViewTransitionInstance(name);instanceToUse=instance.ref;break;case 7:current.stateNode===null&&(current.stateNode=createFragmentInstance(current)),instanceToUse=current.stateNode;break;default:instanceToUse=current.stateNode}typeof ref==="function"?current.refCleanup=ref(instanceToUse):ref.current=instanceToUse}}catch(error){captureCommitPhaseError(current,nearestMountedAncestor,error)}}function safelyDetachRef(current,nearestMountedAncestor){var ref=current.ref,refCleanup=current.refCleanup;if(ref!==null)if(typeof refCleanup==="function")try{refCleanup()}catch(error){captureCommitPhaseError(current,nearestMountedAncestor,error)}finally{current.refCleanup=null,current=current.alternate,current!=null&&(current.refCleanup=null)}else if(typeof ref==="function")try{ref(null)}catch(error$130){captureCommitPhaseError(current,nearestMountedAncestor,error$130)}else ref.current=null}function pushMutationContext(){var prev=viewTransitionMutationContext;return viewTransitionMutationContext=!1,prev}function commitNewChildToFragmentInstances(fiber,parentFragmentInstances){if((fiber.tag===5||fiber.tag===27||fiber.tag===6)&&fiber.alternate===null&&parentFragmentInstances!==null)for(var i=0;i<parentFragmentInstances.length;i++)commitNewChildToFragmentInstance(fiber.stateNode,parentFragmentInstances[i])}function commitFragmentInstanceInsertionEffects(fiber){for(var parent=fiber.return;parent!==null;){if(isFragmentInstanceParent(parent)&&commitNewChildToFragmentInstance(fiber.stateNode,parent.stateNode),isFragmentInstanceHostBoundary(parent))break;parent=parent.return}}function commitFragmentInstanceDeletionEffects(fiber){for(var parent=fiber.return;parent!==null;){if(isFragmentInstanceParent(parent)&&deleteChildFromFragmentInstance(fiber.stateNode,parent.stateNode),isFragmentInstanceHostBoundary(parent))break;parent=parent.return}}function isFragmentInstanceHostBoundary(fiber){return fiber.tag===5||fiber.tag===3||(supportsSingletons?fiber.tag===27:!1)}function isFragmentInstanceParent(fiber){return fiber&&fiber.tag===7&&fiber.stateNode!==null}function commitHostMount(finishedWork){var{type,memoizedProps:props,stateNode:instance}=finishedWork;try{commitMount(instance,type,props,finishedWork)}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}function commitHostUpdate(finishedWork,newProps,oldProps){try{commitUpdate(finishedWork.stateNode,finishedWork.type,oldProps,newProps,finishedWork)}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}function isHostParent(fiber){return fiber.tag===5||fiber.tag===3||(supportsResources?fiber.tag===26:!1)||(supportsSingletons?fiber.tag===27&&isSingletonScope(fiber.type):!1)||fiber.tag===4}function getHostSibling(fiber){a:for(;;){for(;fiber.sibling===null;){if(fiber.return===null||isHostParent(fiber.return))return null;fiber=fiber.return}fiber.sibling.return=fiber.return;for(fiber=fiber.sibling;fiber.tag!==5&&fiber.tag!==6&&fiber.tag!==18;){if(supportsSingletons&&fiber.tag===27&&isSingletonScope(fiber.type))continue a;if(fiber.flags&2)continue a;if(fiber.child===null||fiber.tag===4)continue a;else fiber.child.return=fiber,fiber=fiber.child}if(!(fiber.flags&2))return fiber.stateNode}}function insertOrAppendPlacementNodeIntoContainer(node,before,parent,parentFragmentInstances){var tag=node.tag;if(tag===5||tag===6)tag=node.stateNode,before?insertInContainerBefore(parent,tag,before):appendChildToContainer(parent,tag),commitNewChildToFragmentInstances(node,parentFragmentInstances),viewTransitionMutationContext=!0;else if(tag!==4&&(supportsSingletons&&tag===27&&(commitNewChildToFragmentInstances(node,parentFragmentInstances),parentFragmentInstances=null,isSingletonScope(node.type)&&(parent=node.stateNode,before=null)),node=node.child,node!==null))for(insertOrAppendPlacementNodeIntoContainer(node,before,parent,parentFragmentInstances),node=node.sibling;node!==null;)insertOrAppendPlacementNodeIntoContainer(node,before,parent,parentFragmentInstances),node=node.sibling}function insertOrAppendPlacementNode(node,before,parent,parentFragmentInstances){var tag=node.tag;if(tag===5||tag===6)tag=node.stateNode,before?insertBefore(parent,tag,before):appendChild(parent,tag),commitNewChildToFragmentInstances(node,parentFragmentInstances),viewTransitionMutationContext=!0;else if(tag!==4&&(supportsSingletons&&tag===27&&(commitNewChildToFragmentInstances(node,parentFragmentInstances),parentFragmentInstances=null,isSingletonScope(node.type)&&(parent=node.stateNode)),node=node.child,node!==null))for(insertOrAppendPlacementNode(node,before,parent,parentFragmentInstances),node=node.sibling;node!==null;)insertOrAppendPlacementNode(node,before,parent,parentFragmentInstances),node=node.sibling}function commitImmutablePlacementNodeToFragmentInstances(finishedWork,parentFragmentInstances){if(finishedWork.tag===5||supportsSingletons&&finishedWork.tag===27)commitNewChildToFragmentInstances(finishedWork,parentFragmentInstances);else if(finishedWork.tag!==4&&(finishedWork=finishedWork.child,finishedWork!==null))for(commitImmutablePlacementNodeToFragmentInstances(finishedWork,parentFragmentInstances),finishedWork=finishedWork.sibling;finishedWork!==null;)commitImmutablePlacementNodeToFragmentInstances(finishedWork,parentFragmentInstances),finishedWork=finishedWork.sibling}function commitHostPortalContainerChildren(portal,finishedWork,pendingChildren){portal=portal.containerInfo;try{replaceContainerChildren(portal,pendingChildren)}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}function commitHostSingletonAcquisition(finishedWork){var{stateNode:singleton,memoizedProps:props}=finishedWork;try{acquireSingletonInstance(finishedWork.type,props,singleton,finishedWork)}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}function trackEnterViewTransitions(placement){if(placement.tag===30||(placement.subtreeFlags&33554432)!==0)shouldStartViewTransition=!0}function pushViewTransitionCancelableScope(){var prevChildren=viewTransitionCancelableChildren;return viewTransitionCancelableChildren=null,prevChildren}function applyViewTransitionToHostInstances(fiber,name,className,collectMeasurements,stopAtNestedViewTransitions){return viewTransitionHostInstanceIdx=0,applyViewTransitionToHostInstancesRecursive(fiber.child,name,className,collectMeasurements,stopAtNestedViewTransitions)}function applyViewTransitionToHostInstancesRecursive(child,name,className,collectMeasurements,stopAtNestedViewTransitions){if(!supportsMutation)return!1;for(var inViewport=!1;child!==null;){if(child.tag===5){var instance=child.stateNode;if(collectMeasurements!==null){var measurement=measureInstance(instance);collectMeasurements.push(measurement),wasInstanceInViewport(measurement)&&(inViewport=!0)}else inViewport||wasInstanceInViewport(measureInstance(instance))&&(inViewport=!0);shouldStartViewTransition=!0,applyViewTransitionName(instance,viewTransitionHostInstanceIdx===0?name:name+"_"+viewTransitionHostInstanceIdx,className),viewTransitionHostInstanceIdx++}else if(child.tag!==22||child.memoizedState===null)child.tag===30&&stopAtNestedViewTransitions||applyViewTransitionToHostInstancesRecursive(child.child,name,className,collectMeasurements,stopAtNestedViewTransitions)&&(inViewport=!0);child=child.sibling}return inViewport}function restoreViewTransitionOnHostInstances(child,stopAtNestedViewTransitions){if(supportsMutation)for(;child!==null;){if(child.tag===5)restoreViewTransitionName(child.stateNode,child.memoizedProps);else if(child.tag!==22||child.memoizedState===null)child.tag===30&&stopAtNestedViewTransitions||restoreViewTransitionOnHostInstances(child.child,stopAtNestedViewTransitions);child=child.sibling}}function commitAppearingPairViewTransitions(placement){if((placement.subtreeFlags&18874368)!==0)for(placement=placement.child;placement!==null;){if(placement.tag!==22||placement.memoizedState===null){if(commitAppearingPairViewTransitions(placement),placement.tag===30&&(placement.flags&18874368)!==0&&placement.stateNode.paired){var props=placement.memoizedProps;if(props.name==null||props.name==="auto")throw Error(formatProdErrorMessage(544));var name=props.name;props=getViewTransitionClassName(props.default,props.share),props!=="none"&&(applyViewTransitionToHostInstances(placement,name,props,null,!1)||restoreViewTransitionOnHostInstances(placement.child,!1))}}placement=placement.sibling}}function commitEnterViewTransitions(placement,gesture){if(placement.tag===30){var state=placement.stateNode,props=placement.memoizedProps,name=getViewTransitionName(props,state),className=getViewTransitionClassName(props.default,state.paired?props.share:props.enter);className!=="none"?applyViewTransitionToHostInstances(placement,name,className,null,!1)?(commitAppearingPairViewTransitions(placement),state.paired||gesture||scheduleViewTransitionEvent(placement,props.onEnter)):restoreViewTransitionOnHostInstances(placement.child,!1):commitAppearingPairViewTransitions(placement)}else if((placement.subtreeFlags&33554432)!==0)for(placement=placement.child;placement!==null;)commitEnterViewTransitions(placement,gesture),placement=placement.sibling;else commitAppearingPairViewTransitions(placement)}function commitDeletedPairViewTransitions(deletion){if(appearingViewTransitions!==null&&appearingViewTransitions.size!==0){var pairs=appearingViewTransitions;if((deletion.subtreeFlags&18874368)!==0)for(deletion=deletion.child;deletion!==null;){if(deletion.tag!==22||deletion.memoizedState===null){if(deletion.tag===30&&(deletion.flags&18874368)!==0){var props=deletion.memoizedProps,name=props.name;if(name!=null&&name!=="auto"){var pair=pairs.get(name);if(pair!==void 0){var className=getViewTransitionClassName(props.default,props.share);if(className!=="none"&&(applyViewTransitionToHostInstances(deletion,name,className,null,!1)?(className=deletion.stateNode,pair.paired=className,className.paired=pair,scheduleViewTransitionEvent(deletion,props.onShare)):restoreViewTransitionOnHostInstances(deletion.child,!1)),pairs.delete(name),pairs.size===0)break}}}commitDeletedPairViewTransitions(deletion)}deletion=deletion.sibling}}}function commitExitViewTransitions(deletion){if(deletion.tag===30){var props=deletion.memoizedProps,name=getViewTransitionName(props,deletion.stateNode),pair=appearingViewTransitions!==null?appearingViewTransitions.get(name):void 0,className=getViewTransitionClassName(props.default,pair!==void 0?props.share:props.exit);className!=="none"&&(applyViewTransitionToHostInstances(deletion,name,className,null,!1)?pair!==void 0?(className=deletion.stateNode,pair.paired=className,className.paired=pair,appearingViewTransitions.delete(name),scheduleViewTransitionEvent(deletion,props.onShare)):scheduleViewTransitionEvent(deletion,props.onExit):restoreViewTransitionOnHostInstances(deletion.child,!1)),appearingViewTransitions!==null&&commitDeletedPairViewTransitions(deletion)}else if((deletion.subtreeFlags&33554432)!==0)for(deletion=deletion.child;deletion!==null;)commitExitViewTransitions(deletion),deletion=deletion.sibling;else appearingViewTransitions!==null&&commitDeletedPairViewTransitions(deletion)}function commitNestedViewTransitions(changedParent){for(changedParent=changedParent.child;changedParent!==null;){if(changedParent.tag===30){var props=changedParent.memoizedProps,name=getViewTransitionName(props,changedParent.stateNode);props=getViewTransitionClassName(props.default,props.update),changedParent.flags&=-5,props!=="none"&&applyViewTransitionToHostInstances(changedParent,name,props,changedParent.memoizedState=[],!1)}else(changedParent.subtreeFlags&33554432)!==0&&commitNestedViewTransitions(changedParent);changedParent=changedParent.sibling}}function restorePairedViewTransitions(parent){if((parent.subtreeFlags&18874368)!==0)for(parent=parent.child;parent!==null;){if(parent.tag!==22||parent.memoizedState===null){if(parent.tag===30&&(parent.flags&18874368)!==0){var instance=parent.stateNode;instance.paired!==null&&(instance.paired=null,restoreViewTransitionOnHostInstances(parent.child,!1))}restorePairedViewTransitions(parent)}parent=parent.sibling}}function restoreEnterOrExitViewTransitions(fiber){if(fiber.tag===30)fiber.stateNode.paired=null,restoreViewTransitionOnHostInstances(fiber.child,!1),restorePairedViewTransitions(fiber);else if((fiber.subtreeFlags&33554432)!==0)for(fiber=fiber.child;fiber!==null;)restoreEnterOrExitViewTransitions(fiber),fiber=fiber.sibling;else restorePairedViewTransitions(fiber)}function restoreNestedViewTransitions(changedParent){for(changedParent=changedParent.child;changedParent!==null;)changedParent.tag===30?restoreViewTransitionOnHostInstances(changedParent.child,!1):(changedParent.subtreeFlags&33554432)!==0&&restoreNestedViewTransitions(changedParent),changedParent=changedParent.sibling}function measureViewTransitionHostInstancesRecursive(parentViewTransition,child,newName,oldName,className,previousMeasurements,stopAtNestedViewTransitions){if(!supportsMutation)return!1;for(var inViewport=!1;child!==null;){if(child.tag===5){var instance=child.stateNode;if(previousMeasurements!==null&&viewTransitionHostInstanceIdx<previousMeasurements.length){var previousMeasurement=previousMeasurements[viewTransitionHostInstanceIdx],nextMeasurement=measureInstance(instance);if(wasInstanceInViewport(previousMeasurement)||wasInstanceInViewport(nextMeasurement))inViewport=!0;(parentViewTransition.flags&4)===0&&hasInstanceChanged(previousMeasurement,nextMeasurement)&&(parentViewTransition.flags|=4),hasInstanceAffectedParent(previousMeasurement,nextMeasurement)&&(parentViewTransition.flags|=32)}else parentViewTransition.flags|=32;(parentViewTransition.flags&4)!==0&&applyViewTransitionName(instance,viewTransitionHostInstanceIdx===0?newName:newName+"_"+viewTransitionHostInstanceIdx,className),inViewport&&(parentViewTransition.flags&4)!==0||(viewTransitionCancelableChildren===null&&(viewTransitionCancelableChildren=[]),viewTransitionCancelableChildren.push(instance,viewTransitionHostInstanceIdx===0?oldName:oldName+"_"+viewTransitionHostInstanceIdx,child.memoizedProps)),viewTransitionHostInstanceIdx++}else if(child.tag!==22||child.memoizedState===null)child.tag===30&&stopAtNestedViewTransitions?parentViewTransition.flags|=child.flags&32:measureViewTransitionHostInstancesRecursive(parentViewTransition,child.child,newName,oldName,className,previousMeasurements,stopAtNestedViewTransitions)&&(inViewport=!0);child=child.sibling}return inViewport}function measureNestedViewTransitions(changedParent,gesture){for(changedParent=changedParent.child;changedParent!==null;){if(changedParent.tag===30){var props=changedParent.memoizedProps,state=changedParent.stateNode,name=getViewTransitionName(props,state),className=getViewTransitionClassName(props.default,props.update);if(gesture){state=state.clones;var previousMeasurements=state===null?null:state.map(measureClonedInstance)}else previousMeasurements=changedParent.memoizedState,changedParent.memoizedState=null;state=changedParent;var child=changedParent.child;viewTransitionHostInstanceIdx=0,name=measureViewTransitionHostInstancesRecursive(state,child,name,name,className,previousMeasurements,!1),(changedParent.flags&4)!==0&&name&&(gesture||scheduleViewTransitionEvent(changedParent,props.onUpdate))}else(changedParent.subtreeFlags&33554432)!==0&&measureNestedViewTransitions(changedParent,gesture);changedParent=changedParent.sibling}}function commitBeforeMutationEffects(root,firstChild,committedLanes){prepareForCommit(root.containerInfo),root=(committedLanes&335544064)===committedLanes,nextEffect=firstChild;for(firstChild=root?9270:1024;nextEffect!==null;){if(committedLanes=nextEffect,root){var deletions=committedLanes.deletions;if(deletions!==null)for(var i=0;i<deletions.length;i++)root&&commitExitViewTransitions(deletions[i])}if(committedLanes.alternate===null&&(committedLanes.flags&2)!==0)root&&trackEnterViewTransitions(committedLanes),commitBeforeMutationEffects_complete(root);else{if(committedLanes.tag===22){if(deletions=committedLanes.alternate,committedLanes.memoizedState!==null){deletions!==null&&deletions.memoizedState===null&&root&&commitExitViewTransitions(deletions),commitBeforeMutationEffects_complete(root);continue}else if(deletions!==null&&deletions.memoizedState!==null){root&&trackEnterViewTransitions(committedLanes),commitBeforeMutationEffects_complete(root);continue}}deletions=committedLanes.child,(committedLanes.subtreeFlags&firstChild)!==0&&deletions!==null?(deletions.return=committedLanes,nextEffect=deletions):(root&&commitNestedViewTransitions(committedLanes),commitBeforeMutationEffects_complete(root))}}appearingViewTransitions=null}function commitBeforeMutationEffects_complete(isViewTransitionEligible$jscomp$0){for(;nextEffect!==null;){var fiber=nextEffect,isViewTransitionEligible=isViewTransitionEligible$jscomp$0,{alternate:current,flags}=fiber;switch(fiber.tag){case 0:case 11:case 15:break;case 1:if((flags&1024)!==0&&current!==null){isViewTransitionEligible=void 0,flags=current.memoizedProps,current=current.memoizedState;var instance=fiber.stateNode;try{var resolvedPrevProps=resolveClassComponentProps(fiber.type,flags);isViewTransitionEligible=instance.getSnapshotBeforeUpdate(resolvedPrevProps,current),instance.__reactInternalSnapshotBeforeUpdate=isViewTransitionEligible}catch(error){captureCommitPhaseError(fiber,fiber.return,error)}}break;case 3:(flags&1024)!==0&&supportsMutation&&clearContainer(fiber.stateNode.containerInfo);break;case 5:case 26:case 27:case 6:case 4:case 17:break;case 30:isViewTransitionEligible&&current!==null&&(isViewTransitionEligible=getViewTransitionName(current.memoizedProps,current.stateNode),flags=fiber.memoizedProps,flags=getViewTransitionClassName(flags.default,flags.update),flags!=="none"&&applyViewTransitionToHostInstances(current,isViewTransitionEligible,flags,current.memoizedState=[],!0));break;default:if((flags&1024)!==0)throw Error(formatProdErrorMessage(163))}if(current=fiber.sibling,current!==null){current.return=fiber.return,nextEffect=current;break}nextEffect=fiber.return}}function commitLayoutEffectOnFiber(finishedRoot,current,finishedWork){var flags=finishedWork.flags;switch(finishedWork.tag){case 0:case 11:case 15:recursivelyTraverseLayoutEffects(finishedRoot,finishedWork),flags&4&&commitHookEffectListMount(5,finishedWork);break;case 1:if(recursivelyTraverseLayoutEffects(finishedRoot,finishedWork),flags&4)if(finishedRoot=finishedWork.stateNode,current===null)try{finishedRoot.componentDidMount()}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}else{var prevProps=resolveClassComponentProps(finishedWork.type,current.memoizedProps);current=current.memoizedState;try{finishedRoot.componentDidUpdate(prevProps,current,finishedRoot.__reactInternalSnapshotBeforeUpdate)}catch(error$128){captureCommitPhaseError(finishedWork,finishedWork.return,error$128)}}flags&64&&commitClassCallbacks(finishedWork),flags&512&&safelyAttachRef(finishedWork,finishedWork.return);break;case 3:if(recursivelyTraverseLayoutEffects(finishedRoot,finishedWork),flags&64&&(flags=finishedWork.updateQueue,flags!==null)){if(finishedRoot=null,finishedWork.child!==null)switch(finishedWork.child.tag){case 27:case 5:finishedRoot=getPublicInstance(finishedWork.child.stateNode);break;case 1:finishedRoot=finishedWork.child.stateNode}try{commitCallbacks(flags,finishedRoot)}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}break;case 27:supportsSingletons&&current===null&&flags&4&&commitHostSingletonAcquisition(finishedWork);case 26:case 5:if(recursivelyTraverseLayoutEffects(finishedRoot,finishedWork),current===null){if(flags&4)commitHostMount(finishedWork);else if(flags&64){finishedRoot=finishedWork.type,current=finishedWork.memoizedProps,prevProps=finishedWork.stateNode;try{commitHydratedInstance(prevProps,finishedRoot,current,finishedWork)}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}}flags&512&&safelyAttachRef(finishedWork,finishedWork.return);break;case 12:recursivelyTraverseLayoutEffects(finishedRoot,finishedWork);break;case 31:recursivelyTraverseLayoutEffects(finishedRoot,finishedWork),flags&4&&commitActivityHydrationCallbacks(finishedRoot,finishedWork);break;case 13:recursivelyTraverseLayoutEffects(finishedRoot,finishedWork),flags&4&&commitSuspenseHydrationCallbacks(finishedRoot,finishedWork),flags&64&&(flags=finishedWork.memoizedState,flags!==null&&(flags=flags.dehydrated,flags!==null&&(finishedWork=retryDehydratedSuspenseBoundary.bind(null,finishedWork),registerSuspenseInstanceRetry(flags,finishedWork))));break;case 22:if(flags=finishedWork.memoizedState!==null||offscreenSubtreeIsHidden,!flags){var newOffscreenSubtreeWasHidden=current!==null&&current.memoizedState!==null||offscreenSubtreeWasHidden;current=offscreenSubtreeIsHidden,prevProps=offscreenSubtreeWasHidden,offscreenSubtreeIsHidden=flags,(offscreenSubtreeWasHidden=newOffscreenSubtreeWasHidden)&&!prevProps?(flags=supportsSingletons?2:0,(finishedWork.subtreeFlags&8772)!==0&&(flags|=1),recursivelyTraverseReappearLayoutEffects(finishedRoot,finishedWork,flags)):recursivelyTraverseLayoutEffects(finishedRoot,finishedWork),offscreenSubtreeIsHidden=current,offscreenSubtreeWasHidden=prevProps}break;case 30:recursivelyTraverseLayoutEffects(finishedRoot,finishedWork),flags&512&&safelyAttachRef(finishedWork,finishedWork.return);break;case 7:flags&512&&safelyAttachRef(finishedWork,finishedWork.return);default:recursivelyTraverseLayoutEffects(finishedRoot,finishedWork)}}function hideOrUnhideAllChildren(parentFiber,isHidden){if(supportsMutation)for(parentFiber=parentFiber.child;parentFiber!==null;)hideOrUnhideAllChildrenOnFiber(parentFiber,isHidden),parentFiber=parentFiber.sibling}function hideOrUnhideAllChildrenOnFiber(fiber,isHidden){if(supportsMutation)switch(fiber.tag){case 5:case 26:try{var instance=fiber.stateNode;isHidden?hideInstance(instance):unhideInstance(fiber.stateNode,fiber.memoizedProps)}catch(error){captureCommitPhaseError(fiber,fiber.return,error)}hideOrUnhideNearestPortals(fiber,isHidden);break;case 6:try{var instance$jscomp$0=fiber.stateNode;isHidden?hideTextInstance(instance$jscomp$0):unhideTextInstance(instance$jscomp$0,fiber.memoizedProps),viewTransitionMutationContext=!0}catch(error){captureCommitPhaseError(fiber,fiber.return,error)}break;case 18:try{var instance$jscomp$1=fiber.stateNode;isHidden?hideDehydratedBoundary(instance$jscomp$1):unhideDehydratedBoundary(fiber.stateNode)}catch(error){captureCommitPhaseError(fiber,fiber.return,error)}break;case 22:case 23:fiber.memoizedState===null&&hideOrUnhideAllChildren(fiber,isHidden);break;default:hideOrUnhideAllChildren(fiber,isHidden)}}function hideOrUnhideNearestPortals(parentFiber,isHidden$jscomp$0){if(supportsMutation&&parentFiber.subtreeFlags&67108864)for(parentFiber=parentFiber.child;parentFiber!==null;){var fiber=parentFiber,isHidden=isHidden$jscomp$0;if(supportsMutation)switch(fiber.tag){case 4:hideOrUnhideAllChildrenOnFiber(fiber,isHidden);break;case 22:fiber.memoizedState===null&&hideOrUnhideNearestPortals(fiber,isHidden);break;default:hideOrUnhideNearestPortals(fiber,isHidden)}parentFiber=parentFiber.sibling}}function detachFiberAfterEffects(fiber){var alternate=fiber.alternate;alternate!==null&&(fiber.alternate=null,detachFiberAfterEffects(alternate)),fiber.child=null,fiber.deletions=null,fiber.sibling=null,fiber.tag===5&&(alternate=fiber.stateNode,alternate!==null&&detachDeletedInstance(alternate)),fiber.stateNode=null,fiber.return=null,fiber.dependencies=null,fiber.memoizedProps=null,fiber.memoizedState=null,fiber.pendingProps=null,fiber.stateNode=null,fiber.updateQueue=null}function recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,parent){for(parent=parent.child;parent!==null;)commitDeletionEffectsOnFiber(finishedRoot,nearestMountedAncestor,parent),parent=parent.sibling}function commitDeletionEffectsOnFiber(finishedRoot,nearestMountedAncestor,deletedFiber){if(injectedHook&&typeof injectedHook.onCommitFiberUnmount==="function")try{injectedHook.onCommitFiberUnmount(rendererID,deletedFiber)}catch(err){}switch(deletedFiber.tag){case 26:if(supportsResources){offscreenSubtreeWasHidden||safelyDetachRef(deletedFiber,nearestMountedAncestor),recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber),deletedFiber.memoizedState?releaseResource(deletedFiber.memoizedState):deletedFiber.stateNode&&(offscreenSubtreeWasHidden||unmountHoistable(deletedFiber.stateNode));break}case 27:if(supportsSingletons){offscreenSubtreeWasHidden||safelyDetachRef(deletedFiber,nearestMountedAncestor),commitFragmentInstanceDeletionEffects(deletedFiber);var prevHostParent=hostParent,prevHostParentIsContainer=hostParentIsContainer;isSingletonScope(deletedFiber.type)&&(hostParent=deletedFiber.stateNode,hostParentIsContainer=!1),recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber),releaseSingletonInstance(deletedFiber.stateNode,deletedFiber.type,deletedFiber.memoizedProps),hostParent=prevHostParent,hostParentIsContainer=prevHostParentIsContainer;break}case 5:offscreenSubtreeWasHidden||safelyDetachRef(deletedFiber,nearestMountedAncestor),commitFragmentInstanceDeletionEffects(deletedFiber);case 6:if(deletedFiber.tag===6&&commitFragmentInstanceDeletionEffects(deletedFiber),supportsMutation){if(prevHostParent=hostParent,prevHostParentIsContainer=hostParentIsContainer,hostParent=null,recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber),hostParent=prevHostParent,hostParentIsContainer=prevHostParentIsContainer,hostParent!==null)if(hostParentIsContainer)try{removeChildFromContainer(hostParent,deletedFiber.stateNode),viewTransitionMutationContext=!0}catch(error){captureCommitPhaseError(deletedFiber,nearestMountedAncestor,error)}else try{removeChild(hostParent,deletedFiber.stateNode),viewTransitionMutationContext=!0}catch(error){captureCommitPhaseError(deletedFiber,nearestMountedAncestor,error)}}else recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber);break;case 18:supportsMutation&&hostParent!==null&&(hostParentIsContainer?clearSuspenseBoundaryFromContainer(hostParent,deletedFiber.stateNode):clearSuspenseBoundary(hostParent,deletedFiber.stateNode));break;case 4:supportsMutation?(prevHostParent=hostParent,prevHostParentIsContainer=hostParentIsContainer,hostParent=deletedFiber.stateNode.containerInfo,hostParentIsContainer=!0,recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber),hostParent=prevHostParent,hostParentIsContainer=prevHostParentIsContainer):(supportsPersistence&&commitHostPortalContainerChildren(deletedFiber.stateNode,deletedFiber,createContainerChildSet()),recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber));break;case 0:case 11:case 14:case 15:commitHookEffectListUnmount(2,deletedFiber,nearestMountedAncestor),offscreenSubtreeWasHidden||commitHookEffectListUnmount(4,deletedFiber,nearestMountedAncestor),recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber);break;case 1:offscreenSubtreeWasHidden||(safelyDetachRef(deletedFiber,nearestMountedAncestor),prevHostParent=deletedFiber.stateNode,typeof prevHostParent.componentWillUnmount==="function"&&safelyCallComponentWillUnmount(deletedFiber,nearestMountedAncestor,prevHostParent)),recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber);break;case 21:recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber);break;case 22:offscreenSubtreeWasHidden=(prevHostParent=offscreenSubtreeWasHidden)||deletedFiber.memoizedState!==null,recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber),offscreenSubtreeWasHidden=prevHostParent;break;case 30:safelyDetachRef(deletedFiber,nearestMountedAncestor),recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber);break;case 7:offscreenSubtreeWasHidden||safelyDetachRef(deletedFiber,nearestMountedAncestor),recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber);break;default:recursivelyTraverseDeletionEffects(finishedRoot,nearestMountedAncestor,deletedFiber)}}function commitActivityHydrationCallbacks(finishedRoot,finishedWork){if(supportsHydration&&finishedWork.memoizedState===null&&(finishedRoot=finishedWork.alternate,finishedRoot!==null&&(finishedRoot=finishedRoot.memoizedState,finishedRoot!==null))){finishedRoot=finishedRoot.dehydrated;try{commitHydratedActivityInstance(finishedRoot)}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}}function commitSuspenseHydrationCallbacks(finishedRoot,finishedWork){if(supportsHydration&&finishedWork.memoizedState===null&&(finishedRoot=finishedWork.alternate,finishedRoot!==null&&(finishedRoot=finishedRoot.memoizedState,finishedRoot!==null&&(finishedRoot=finishedRoot.dehydrated,finishedRoot!==null))))try{commitHydratedSuspenseInstance(finishedRoot)}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}function getRetryCache(finishedWork){switch(finishedWork.tag){case 31:case 13:case 19:var retryCache=finishedWork.stateNode;return retryCache===null&&(retryCache=finishedWork.stateNode=new PossiblyWeakSet),retryCache;case 22:return finishedWork=finishedWork.stateNode,retryCache=finishedWork._retryCache,retryCache===null&&(retryCache=finishedWork._retryCache=new PossiblyWeakSet),retryCache;default:throw Error(formatProdErrorMessage(435,finishedWork.tag))}}function attachSuspenseRetryListeners(finishedWork,wakeables){var retryCache=getRetryCache(finishedWork);wakeables.forEach(function(wakeable){if(!retryCache.has(wakeable)){retryCache.add(wakeable);var retry=resolveRetryWakeable.bind(null,finishedWork,wakeable);wakeable.then(retry,retry)}})}function recursivelyTraverseMutationEffects(root$jscomp$0,parentFiber,lanes){var deletions=parentFiber.deletions;if(deletions!==null)for(var i=0;i<deletions.length;i++){var childToDelete=deletions[i],root=root$jscomp$0,returnFiber=parentFiber;if(supportsMutation){var parent=returnFiber;a:for(;parent!==null;){switch(parent.tag){case 27:if(supportsSingletons){if(isSingletonScope(parent.type)){hostParent=parent.stateNode,hostParentIsContainer=!1;break a}break}case 5:hostParent=parent.stateNode,hostParentIsContainer=!1;break a;case 3:case 4:hostParent=parent.stateNode.containerInfo,hostParentIsContainer=!0;break a}parent=parent.return}if(hostParent===null)throw Error(formatProdErrorMessage(160));commitDeletionEffectsOnFiber(root,returnFiber,childToDelete),hostParent=null,hostParentIsContainer=!1}else commitDeletionEffectsOnFiber(root,returnFiber,childToDelete);root=childToDelete.alternate,root!==null&&(root.return=null),childToDelete.return=null}if(parentFiber.subtreeFlags&13886)for(parentFiber=parentFiber.child;parentFiber!==null;)commitMutationEffectsOnFiber(parentFiber,root$jscomp$0,lanes),parentFiber=parentFiber.sibling}function commitMutationEffectsOnFiber(finishedWork,root,lanes){var current=finishedWork.alternate,flags=finishedWork.flags;switch(finishedWork.tag){case 0:case 11:case 14:case 15:if(flags&4&&(current=finishedWork.updateQueue,current=current!==null?current.events:null,current!==null))for(var ii=0;ii<current.length;ii++){var _eventPayloads$ii2=current[ii];_eventPayloads$ii2.ref.impl=_eventPayloads$ii2.nextImpl}recursivelyTraverseMutationEffects(root,finishedWork,lanes),commitReconciliationEffects(finishedWork),flags&4&&(commitHookEffectListUnmount(3,finishedWork,finishedWork.return),commitHookEffectListMount(3,finishedWork),commitHookEffectListUnmount(5,finishedWork,finishedWork.return));break;case 1:recursivelyTraverseMutationEffects(root,finishedWork,lanes),commitReconciliationEffects(finishedWork),flags&512&&(offscreenSubtreeWasHidden||current===null||safelyDetachRef(current,current.return)),flags&64&&offscreenSubtreeIsHidden&&(finishedWork=finishedWork.updateQueue,finishedWork!==null&&(root=finishedWork.callbacks,root!==null&&(flags=finishedWork.shared.hiddenCallbacks,finishedWork.shared.hiddenCallbacks=flags===null?root:flags.concat(root))));break;case 26:if(supportsResources){ii=currentHoistableRoot,recursivelyTraverseMutationEffects(root,finishedWork,lanes),commitReconciliationEffects(finishedWork),flags&512&&(offscreenSubtreeWasHidden||current===null||safelyDetachRef(current,current.return)),flags&4&&(lanes=current!==null?current.memoizedState:null,flags=finishedWork.memoizedState,current===null?flags===null?finishedWork.stateNode===null?finishedWork.stateNode=offscreenSubtreeIsHidden?createHoistableInstance(finishedWork.type,finishedWork.memoizedProps,root.containerInfo,finishedWork):hydrateHoistable(ii,finishedWork.type,finishedWork.memoizedProps,finishedWork):offscreenSubtreeIsHidden||mountHoistable(ii,finishedWork.type,finishedWork.stateNode):finishedWork.stateNode=acquireResource(ii,flags,finishedWork.memoizedProps):lanes!==flags?(lanes===null?(root=current.stateNode,root===null||offscreenSubtreeWasHidden||unmountHoistable(root)):releaseResource(lanes),flags===null?offscreenSubtreeIsHidden||mountHoistable(ii,finishedWork.type,finishedWork.stateNode):acquireResource(ii,flags,finishedWork.memoizedProps)):flags===null&&finishedWork.stateNode!==null&&commitHostUpdate(finishedWork,finishedWork.memoizedProps,current.memoizedProps));break}case 27:if(supportsSingletons){recursivelyTraverseMutationEffects(root,finishedWork,lanes),commitReconciliationEffects(finishedWork),flags&512&&(offscreenSubtreeWasHidden||current===null||safelyDetachRef(current,current.return)),current!==null&&flags&4&&commitHostUpdate(finishedWork,finishedWork.memoizedProps,current.memoizedProps);break}case 5:if(ii=offscreenDirectParentIsHidden,offscreenDirectParentIsHidden=!1,recursivelyTraverseMutationEffects(root,finishedWork,lanes),offscreenDirectParentIsHidden=ii,commitReconciliationEffects(finishedWork),flags&512&&(offscreenSubtreeWasHidden||current===null||safelyDetachRef(current,current.return)),supportsMutation){if(finishedWork.flags&32){root=finishedWork.stateNode;try{resetTextContent(root),viewTransitionMutationContext=!0}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}flags&4&&finishedWork.stateNode!=null&&(root=finishedWork.memoizedProps,commitHostUpdate(finishedWork,root,current!==null?current.memoizedProps:root)),flags&1024&&(needsFormReset=!0)}else supportsPersistence&&finishedWork.alternate!==null&&(finishedWork.alternate.stateNode=finishedWork.stateNode);break;case 6:if(recursivelyTraverseMutationEffects(root,finishedWork,lanes),commitReconciliationEffects(finishedWork),flags&4&&supportsMutation){if(finishedWork.stateNode===null)throw Error(formatProdErrorMessage(162));root=finishedWork.memoizedProps,flags=current!==null?current.memoizedProps:root,lanes=finishedWork.stateNode;try{commitTextUpdate(lanes,flags,root),viewTransitionMutationContext=!0}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}break;case 3:if(viewTransitionMutationContext=!1,supportsResources?(prepareToCommitHoistables(),ii=currentHoistableRoot,currentHoistableRoot=getHoistableRoot(root.containerInfo),recursivelyTraverseMutationEffects(root,finishedWork,lanes),currentHoistableRoot=ii):recursivelyTraverseMutationEffects(root,finishedWork,lanes),commitReconciliationEffects(finishedWork),flags&4){if(supportsMutation&&supportsHydration&&current!==null&&current.memoizedState.isDehydrated)try{commitHydratedContainer(root.containerInfo)}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}if(supportsPersistence){flags=root.containerInfo,root=root.pendingChildren;try{replaceContainerChildren(flags,root),viewTransitionMutationContext=!0}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}}needsFormReset&&(needsFormReset=!1,recursivelyResetForms(finishedWork)),viewTransitionMutationContext=!1;break;case 4:current=offscreenDirectParentIsHidden,offscreenDirectParentIsHidden=offscreenSubtreeIsHidden,ii=pushMutationContext(),supportsResources?(_eventPayloads$ii2=currentHoistableRoot,currentHoistableRoot=getHoistableRoot(finishedWork.stateNode.containerInfo),recursivelyTraverseMutationEffects(root,finishedWork,lanes),commitReconciliationEffects(finishedWork),currentHoistableRoot=_eventPayloads$ii2):(recursivelyTraverseMutationEffects(root,finishedWork,lanes),commitReconciliationEffects(finishedWork)),viewTransitionMutationContext&&inUpdateViewTransition&&(rootViewTransitionAffected=!0),viewTransitionMutationContext=ii,offscreenDirectParentIsHidden=current,flags&4&&supportsPersistence&&commitHostPortalContainerChildren(finishedWork.stateNode,finishedWork,finishedWork.stateNode.pendingChildren);break;case 12:recursivelyTraverseMutationEffects(root,finishedWork,lanes),commitReconciliationEffects(finishedWork);break;case 31:recursivelyTraverseMutationEffects(root,finishedWork,lanes),commitReconciliationEffects(finishedWork),flags&4&&(root=finishedWork.updateQueue,root!==null&&(finishedWork.updateQueue=null,attachSuspenseRetryListeners(finishedWork,root)));break;case 13:recursivelyTraverseMutationEffects(root,finishedWork,lanes),commitReconciliationEffects(finishedWork),finishedWork.child.flags&8192&&finishedWork.memoizedState!==null!==(current!==null&&current.memoizedState!==null)&&(globalMostRecentFallbackTime=now()),flags&4&&(root=finishedWork.updateQueue,root!==null&&(finishedWork.updateQueue=null,attachSuspenseRetryListeners(finishedWork,root)));break;case 22:ii=finishedWork.memoizedState!==null,_eventPayloads$ii2=current!==null&&current.memoizedState!==null;var prevOffscreenSubtreeIsHidden=offscreenSubtreeIsHidden,prevOffscreenSubtreeWasHidden=offscreenSubtreeWasHidden,prevOffscreenDirectParentIsHidden$147=offscreenDirectParentIsHidden;offscreenSubtreeIsHidden=prevOffscreenSubtreeIsHidden||ii,offscreenDirectParentIsHidden=prevOffscreenDirectParentIsHidden$147||ii,offscreenSubtreeWasHidden=prevOffscreenSubtreeWasHidden||_eventPayloads$ii2,recursivelyTraverseMutationEffects(root,finishedWork,lanes),offscreenSubtreeWasHidden=prevOffscreenSubtreeWasHidden,offscreenDirectParentIsHidden=prevOffscreenDirectParentIsHidden$147,offscreenSubtreeIsHidden=prevOffscreenSubtreeIsHidden,commitReconciliationEffects(finishedWork),flags&8192&&(root=finishedWork.stateNode,root._visibility=ii?root._visibility&-2:root._visibility|1,!ii||current===null||_eventPayloads$ii2||offscreenSubtreeIsHidden||offscreenSubtreeWasHidden||(root=supportsSingletons?2:0,lanes=_eventPayloads$ii2||offscreenSubtreeWasHidden,current=offscreenSubtreeIsHidden,_eventPayloads$ii2=offscreenSubtreeWasHidden,offscreenSubtreeIsHidden=ii||offscreenSubtreeIsHidden,offscreenSubtreeWasHidden=lanes,recursivelyTraverseDisappearLayoutEffects(finishedWork,root),offscreenSubtreeIsHidden=current,offscreenSubtreeWasHidden=_eventPayloads$ii2),supportsMutation&&(ii||!offscreenDirectParentIsHidden)&&hideOrUnhideAllChildren(finishedWork,ii)),flags&4&&(root=finishedWork.updateQueue,root!==null&&(flags=root.retryQueue,flags!==null&&(root.retryQueue=null,attachSuspenseRetryListeners(finishedWork,flags))));break;case 19:recursivelyTraverseMutationEffects(root,finishedWork,lanes),commitReconciliationEffects(finishedWork),flags&4&&(root=finishedWork.updateQueue,root!==null&&(finishedWork.updateQueue=null,attachSuspenseRetryListeners(finishedWork,root)));break;case 30:flags&512&&(offscreenSubtreeWasHidden||current===null||safelyDetachRef(current,current.return)),flags=pushMutationContext(),ii=inUpdateViewTransition,_eventPayloads$ii2=(lanes&335544064)===lanes,prevOffscreenSubtreeIsHidden=finishedWork.memoizedProps,inUpdateViewTransition=_eventPayloads$ii2&&getViewTransitionClassName(prevOffscreenSubtreeIsHidden.default,prevOffscreenSubtreeIsHidden.update)!=="none",recursivelyTraverseMutationEffects(root,finishedWork,lanes),commitReconciliationEffects(finishedWork),_eventPayloads$ii2&&current!==null&&viewTransitionMutationContext&&(finishedWork.flags|=4),inUpdateViewTransition=ii,viewTransitionMutationContext=flags;break;case 21:break;case 7:flags&512&&(offscreenSubtreeWasHidden||current===null||safelyDetachRef(current,current.return)),current&&current.stateNode!==null&&updateFragmentInstanceFiber(finishedWork,current.stateNode);default:recursivelyTraverseMutationEffects(root,finishedWork,lanes),commitReconciliationEffects(finishedWork)}}function commitReconciliationEffects(finishedWork){var flags=finishedWork.flags;if(flags&2){try{for(var hostParentFiber,parentFiber=finishedWork.return;parentFiber!==null;){if(isHostParent(parentFiber)){hostParentFiber=parentFiber;break}parentFiber=parentFiber.return}parentFiber=null;for(var parent=finishedWork.return;parent!==null;){if(isFragmentInstanceParent(parent)){var fragmentInstance=parent.stateNode;parentFiber===null?parentFiber=[fragmentInstance]:parentFiber.push(fragmentInstance)}if(isFragmentInstanceHostBoundary(parent))break;parent=parent.return}var JSCompiler_inline_result=parentFiber;if(supportsMutation){if(hostParentFiber==null)throw Error(formatProdErrorMessage(160));switch(hostParentFiber.tag){case 27:if(supportsSingletons){var parent$jscomp$0=hostParentFiber.stateNode,before=getHostSibling(finishedWork);insertOrAppendPlacementNode(finishedWork,before,parent$jscomp$0,JSCompiler_inline_result);break}case 5:var parent$131=hostParentFiber.stateNode;hostParentFiber.flags&32&&(resetTextContent(parent$131),hostParentFiber.flags&=-33);var before$132=getHostSibling(finishedWork);insertOrAppendPlacementNode(finishedWork,before$132,parent$131,JSCompiler_inline_result);break;case 3:case 4:var parent$133=hostParentFiber.stateNode.containerInfo,before$134=getHostSibling(finishedWork);insertOrAppendPlacementNodeIntoContainer(finishedWork,before$134,parent$133,JSCompiler_inline_result);break;default:throw Error(formatProdErrorMessage(161))}}else commitImmutablePlacementNodeToFragmentInstances(finishedWork,JSCompiler_inline_result)}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}finishedWork.flags&=-3}flags&4096&&(finishedWork.flags&=-4097)}function recursivelyResetForms(parentFiber){if(parentFiber.subtreeFlags&1024)for(parentFiber=parentFiber.child;parentFiber!==null;){var fiber=parentFiber;recursivelyResetForms(fiber),fiber.tag===5&&fiber.flags&1024&&resetFormInstance(fiber.stateNode),parentFiber=parentFiber.sibling}}function recursivelyTraverseAfterMutationEffects(root,parentFiber){if(parentFiber.subtreeFlags&9270)for(parentFiber=parentFiber.child;parentFiber!==null;)commitAfterMutationEffectsOnFiber(parentFiber,root),parentFiber=parentFiber.sibling;else measureNestedViewTransitions(parentFiber,!1)}function commitAfterMutationEffectsOnFiber(finishedWork,root){var current=finishedWork.alternate;if(current===null)commitEnterViewTransitions(finishedWork,!1);else switch(finishedWork.tag){case 3:if(rootViewTransitionNameCanceled=viewTransitionContextChanged=!1,pushViewTransitionCancelableScope(),recursivelyTraverseAfterMutationEffects(root,finishedWork),!viewTransitionContextChanged&&!rootViewTransitionAffected){if(finishedWork=viewTransitionCancelableChildren,finishedWork!==null)for(var i=0;i<finishedWork.length;i+=3)cancelViewTransitionName(finishedWork[i],finishedWork[i+1],finishedWork[i+2]);cancelRootViewTransitionName(root.containerInfo),rootViewTransitionNameCanceled=!0}viewTransitionCancelableChildren=null;break;case 5:recursivelyTraverseAfterMutationEffects(root,finishedWork);break;case 4:i=viewTransitionContextChanged,viewTransitionContextChanged=!1,recursivelyTraverseAfterMutationEffects(root,finishedWork),viewTransitionContextChanged&&(rootViewTransitionAffected=!0),viewTransitionContextChanged=i;break;case 22:finishedWork.memoizedState===null&&(current.memoizedState!==null?commitEnterViewTransitions(finishedWork,!1):recursivelyTraverseAfterMutationEffects(root,finishedWork));break;case 30:i=viewTransitionContextChanged;var prevCancelableChildren=pushViewTransitionCancelableScope();viewTransitionContextChanged=!1,recursivelyTraverseAfterMutationEffects(root,finishedWork),viewTransitionContextChanged&&(finishedWork.flags|=4);var props=finishedWork.memoizedProps,state=finishedWork.stateNode;root=getViewTransitionName(props,state),state=getViewTransitionName(current.memoizedProps,state);var className=getViewTransitionClassName(props.default,props.update);className==="none"?current=!1:(props=current.memoizedState,current.memoizedState=null,current=finishedWork.child,viewTransitionHostInstanceIdx=0,current=measureViewTransitionHostInstancesRecursive(finishedWork,current,root,state,className,props,!0),viewTransitionHostInstanceIdx!==(props===null?0:props.length)&&(finishedWork.flags|=32)),(finishedWork.flags&4)!==0&&current?(scheduleViewTransitionEvent(finishedWork,finishedWork.memoizedProps.onUpdate),viewTransitionCancelableChildren=prevCancelableChildren):prevCancelableChildren!==null&&(prevCancelableChildren.push.apply(prevCancelableChildren,viewTransitionCancelableChildren),viewTransitionCancelableChildren=prevCancelableChildren),viewTransitionContextChanged=(finishedWork.flags&32)!==0?!0:i;break;default:recursivelyTraverseAfterMutationEffects(root,finishedWork)}}function recursivelyTraverseLayoutEffects(root,parentFiber){if(parentFiber.subtreeFlags&8772)for(parentFiber=parentFiber.child;parentFiber!==null;)commitLayoutEffectOnFiber(root,parentFiber.alternate,parentFiber),parentFiber=parentFiber.sibling}function recursivelyTraverseDisappearLayoutEffects(parentFiber,layoutEffectTraversalFlags$jscomp$0){for(parentFiber=parentFiber.child;parentFiber!==null;){var finishedWork=parentFiber,layoutEffectTraversalFlags=layoutEffectTraversalFlags$jscomp$0;switch(finishedWork.tag){case 0:case 11:case 14:case 15:commitHookEffectListUnmount(4,finishedWork,finishedWork.return),recursivelyTraverseDisappearLayoutEffects(finishedWork,layoutEffectTraversalFlags);break;case 1:safelyDetachRef(finishedWork,finishedWork.return);var instance=finishedWork.stateNode;typeof instance.componentWillUnmount==="function"&&safelyCallComponentWillUnmount(finishedWork,finishedWork.return,instance),recursivelyTraverseDisappearLayoutEffects(finishedWork,layoutEffectTraversalFlags);break;case 27:supportsSingletons&&(layoutEffectTraversalFlags&2)!==0&&releaseSingletonInstance(finishedWork.stateNode,finishedWork.type,finishedWork.memoizedProps);case 5:safelyDetachRef(finishedWork,finishedWork.return),finishedWork.tag!==5&&finishedWork.tag!==27||commitFragmentInstanceDeletionEffects(finishedWork),recursivelyTraverseDisappearLayoutEffects(finishedWork,layoutEffectTraversalFlags);break;case 6:commitFragmentInstanceDeletionEffects(finishedWork);break;case 26:safelyDetachRef(finishedWork,finishedWork.return),supportsResources&&(instance=finishedWork.stateNode,finishedWork.memoizedState!==null||instance===null||offscreenSubtreeWasHidden||unmountHoistable(instance)),recursivelyTraverseDisappearLayoutEffects(finishedWork,layoutEffectTraversalFlags);break;case 22:finishedWork.memoizedState===null&&recursivelyTraverseDisappearLayoutEffects(finishedWork,layoutEffectTraversalFlags);break;case 30:safelyDetachRef(finishedWork,finishedWork.return),recursivelyTraverseDisappearLayoutEffects(finishedWork,layoutEffectTraversalFlags);break;case 7:safelyDetachRef(finishedWork,finishedWork.return);default:recursivelyTraverseDisappearLayoutEffects(finishedWork,layoutEffectTraversalFlags)}parentFiber=parentFiber.sibling}}function recursivelyTraverseReappearLayoutEffects(finishedRoot$jscomp$0,parentFiber,layoutEffectTraversalFlags){layoutEffectTraversalFlags=(parentFiber.subtreeFlags&8772)!==0?layoutEffectTraversalFlags:layoutEffectTraversalFlags&-2;for(parentFiber=parentFiber.child;parentFiber!==null;){var current=parentFiber.alternate,finishedRoot=finishedRoot$jscomp$0,finishedWork=parentFiber,flags=finishedWork.flags,includeWorkInProgressEffects=(layoutEffectTraversalFlags&1)!==0;switch(finishedWork.tag){case 0:case 11:case 15:recursivelyTraverseReappearLayoutEffects(finishedRoot,finishedWork,layoutEffectTraversalFlags),commitHookEffectListMount(4,finishedWork);break;case 1:if(recursivelyTraverseReappearLayoutEffects(finishedRoot,finishedWork,layoutEffectTraversalFlags),current=finishedWork,finishedRoot=current.stateNode,typeof finishedRoot.componentDidMount==="function")try{finishedRoot.componentDidMount()}catch(error){captureCommitPhaseError(current,current.return,error)}if(current=finishedWork,finishedRoot=current.updateQueue,finishedRoot!==null){var instance=current.stateNode;try{var hiddenCallbacks=finishedRoot.shared.hiddenCallbacks;if(hiddenCallbacks!==null)for(finishedRoot.shared.hiddenCallbacks=null,finishedRoot=0;finishedRoot<hiddenCallbacks.length;finishedRoot++)callCallback(hiddenCallbacks[finishedRoot],instance)}catch(error){captureCommitPhaseError(current,current.return,error)}}includeWorkInProgressEffects&&flags&64&&commitClassCallbacks(finishedWork),safelyAttachRef(finishedWork,finishedWork.return);break;case 27:supportsSingletons&&(layoutEffectTraversalFlags&2)!==0&&commitHostSingletonAcquisition(finishedWork);case 5:finishedWork.tag!==5&&finishedWork.tag!==27||commitFragmentInstanceInsertionEffects(finishedWork),recursivelyTraverseReappearLayoutEffects(finishedRoot,finishedWork,layoutEffectTraversalFlags),includeWorkInProgressEffects&&current===null&&flags&4&&commitHostMount(finishedWork),safelyAttachRef(finishedWork,finishedWork.return);break;case 6:commitFragmentInstanceInsertionEffects(finishedWork);break;case 26:supportsResources&&(instance=finishedWork.stateNode,finishedWork.memoizedState!==null||instance===null||offscreenSubtreeIsHidden||mountHoistable(getHoistableRoot(instance.ownerDocument),finishedWork.type,instance)),recursivelyTraverseReappearLayoutEffects(finishedRoot,finishedWork,layoutEffectTraversalFlags),includeWorkInProgressEffects&&current===null&&flags&4&&commitHostMount(finishedWork),safelyAttachRef(finishedWork,finishedWork.return);break;case 12:recursivelyTraverseReappearLayoutEffects(finishedRoot,finishedWork,layoutEffectTraversalFlags);break;case 31:recursivelyTraverseReappearLayoutEffects(finishedRoot,finishedWork,layoutEffectTraversalFlags),includeWorkInProgressEffects&&flags&4&&commitActivityHydrationCallbacks(finishedRoot,finishedWork);break;case 13:recursivelyTraverseReappearLayoutEffects(finishedRoot,finishedWork,layoutEffectTraversalFlags),includeWorkInProgressEffects&&flags&4&&commitSuspenseHydrationCallbacks(finishedRoot,finishedWork);break;case 22:finishedWork.memoizedState===null&&recursivelyTraverseReappearLayoutEffects(finishedRoot,finishedWork,layoutEffectTraversalFlags),safelyAttachRef(finishedWork,finishedWork.return);break;case 30:recursivelyTraverseReappearLayoutEffects(finishedRoot,finishedWork,layoutEffectTraversalFlags),safelyAttachRef(finishedWork,finishedWork.return);break;case 7:safelyAttachRef(finishedWork,finishedWork.return);default:recursivelyTraverseReappearLayoutEffects(finishedRoot,finishedWork,layoutEffectTraversalFlags)}parentFiber=parentFiber.sibling}}function commitOffscreenPassiveMountEffects(current,finishedWork){var previousCache=null;current!==null&&current.memoizedState!==null&&current.memoizedState.cachePool!==null&&(previousCache=current.memoizedState.cachePool.pool),current=null,finishedWork.memoizedState!==null&&finishedWork.memoizedState.cachePool!==null&&(current=finishedWork.memoizedState.cachePool.pool),current!==previousCache&&(current!=null&&current.refCount++,previousCache!=null&&releaseCache(previousCache))}function commitCachePassiveMountEffect(current,finishedWork){current=null,finishedWork.alternate!==null&&(current=finishedWork.alternate.memoizedState.cache),finishedWork=finishedWork.memoizedState.cache,finishedWork!==current&&(finishedWork.refCount++,current!=null&&releaseCache(current))}function recursivelyTraversePassiveMountEffects(root,parentFiber,committedLanes,committedTransitions){var isViewTransitionEligible=(committedLanes&335544064)===committedLanes;if(parentFiber.subtreeFlags&(isViewTransitionEligible?10262:10256))for(parentFiber=parentFiber.child;parentFiber!==null;)commitPassiveMountOnFiber(root,parentFiber,committedLanes,committedTransitions),parentFiber=parentFiber.sibling;else isViewTransitionEligible&&restoreNestedViewTransitions(parentFiber)}function commitPassiveMountOnFiber(finishedRoot,finishedWork,committedLanes,committedTransitions){var isViewTransitionEligible=(committedLanes&335544064)===committedLanes;isViewTransitionEligible&&finishedWork.alternate===null&&finishedWork.return!==null&&finishedWork.return.alternate!==null&&restoreEnterOrExitViewTransitions(finishedWork);var flags=finishedWork.flags;switch(finishedWork.tag){case 0:case 11:case 15:recursivelyTraversePassiveMountEffects(finishedRoot,finishedWork,committedLanes,committedTransitions),flags&2048&&commitHookEffectListMount(9,finishedWork);break;case 1:recursivelyTraversePassiveMountEffects(finishedRoot,finishedWork,committedLanes,committedTransitions);break;case 3:recursivelyTraversePassiveMountEffects(finishedRoot,finishedWork,committedLanes,committedTransitions),isViewTransitionEligible&&supportsMutation&&rootViewTransitionNameCanceled&&restoreRootViewTransitionName(finishedRoot.containerInfo),flags&2048&&(finishedRoot=null,finishedWork.alternate!==null&&(finishedRoot=finishedWork.alternate.memoizedState.cache),finishedWork=finishedWork.memoizedState.cache,finishedWork!==finishedRoot&&(finishedWork.refCount++,finishedRoot!=null&&releaseCache(finishedRoot)));break;case 12:if(flags&2048){recursivelyTraversePassiveMountEffects(finishedRoot,finishedWork,committedLanes,committedTransitions),finishedRoot=finishedWork.stateNode;try{var _finishedWork$memoize2=finishedWork.memoizedProps,id=_finishedWork$memoize2.id,onPostCommit=_finishedWork$memoize2.onPostCommit;typeof onPostCommit==="function"&&onPostCommit(id,finishedWork.alternate===null?"mount":"update",finishedRoot.passiveEffectDuration,-0)}catch(error){captureCommitPhaseError(finishedWork,finishedWork.return,error)}}else recursivelyTraversePassiveMountEffects(finishedRoot,finishedWork,committedLanes,committedTransitions);break;case 31:recursivelyTraversePassiveMountEffects(finishedRoot,finishedWork,committedLanes,committedTransitions);break;case 13:recursivelyTraversePassiveMountEffects(finishedRoot,finishedWork,committedLanes,committedTransitions);break;case 23:break;case 22:_finishedWork$memoize2=finishedWork.stateNode,id=finishedWork.alternate,finishedWork.memoizedState!==null?(isViewTransitionEligible&&id!==null&&id.memoizedState===null&&restoreEnterOrExitViewTransitions(id),_finishedWork$memoize2._visibility&2?recursivelyTraversePassiveMountEffects(finishedRoot,finishedWork,committedLanes,committedTransitions):recursivelyTraverseAtomicPassiveEffects(finishedRoot,finishedWork)):(isViewTransitionEligible&&id!==null&&id.memoizedState!==null&&restoreEnterOrExitViewTransitions(finishedWork),_finishedWork$memoize2._visibility&2?recursivelyTraversePassiveMountEffects(finishedRoot,finishedWork,committedLanes,committedTransitions):(_finishedWork$memoize2._visibility|=2,recursivelyTraverseReconnectPassiveEffects(finishedRoot,finishedWork,committedLanes,committedTransitions,(finishedWork.subtreeFlags&10256)!==0||!1))),flags&2048&&commitOffscreenPassiveMountEffects(id,finishedWork);break;case 24:recursivelyTraversePassiveMountEffects(finishedRoot,finishedWork,committedLanes,committedTransitions),flags&2048&&commitCachePassiveMountEffect(finishedWork.alternate,finishedWork);break;case 30:isViewTransitionEligible&&(isViewTransitionEligible=finishedWork.alternate,isViewTransitionEligible!==null&&(restoreViewTransitionOnHostInstances(isViewTransitionEligible.child,!0),restoreViewTransitionOnHostInstances(finishedWork.child,!0))),recursivelyTraversePassiveMountEffects(finishedRoot,finishedWork,committedLanes,committedTransitions);break;default:recursivelyTraversePassiveMountEffects(finishedRoot,finishedWork,committedLanes,committedTransitions)}}function recursivelyTraverseReconnectPassiveEffects(finishedRoot$jscomp$0,parentFiber,committedLanes$jscomp$0,committedTransitions$jscomp$0,includeWorkInProgressEffects){includeWorkInProgressEffects=includeWorkInProgressEffects&&((parentFiber.subtreeFlags&10256)!==0||!1);for(parentFiber=parentFiber.child;parentFiber!==null;){var finishedRoot=finishedRoot$jscomp$0,finishedWork=parentFiber,committedLanes=committedLanes$jscomp$0,committedTransitions=committedTransitions$jscomp$0,flags=finishedWork.flags;switch(finishedWork.tag){case 0:case 11:case 15:recursivelyTraverseReconnectPassiveEffects(finishedRoot,finishedWork,committedLanes,committedTransitions,includeWorkInProgressEffects),commitHookEffectListMount(8,finishedWork);break;case 23:break;case 22:var instance=finishedWork.stateNode;finishedWork.memoizedState!==null?instance._visibility&2?recursivelyTraverseReconnectPassiveEffects(finishedRoot,finishedWork,committedLanes,committedTransitions,includeWorkInProgressEffects):recursivelyTraverseAtomicPassiveEffects(finishedRoot,finishedWork):(instance._visibility|=2,recursivelyTraverseReconnectPassiveEffects(finishedRoot,finishedWork,committedLanes,committedTransitions,includeWorkInProgressEffects)),includeWorkInProgressEffects&&flags&2048&&commitOffscreenPassiveMountEffects(finishedWork.alternate,finishedWork);break;case 24:recursivelyTraverseReconnectPassiveEffects(finishedRoot,finishedWork,committedLanes,committedTransitions,includeWorkInProgressEffects),includeWorkInProgressEffects&&flags&2048&&commitCachePassiveMountEffect(finishedWork.alternate,finishedWork);break;default:recursivelyTraverseReconnectPassiveEffects(finishedRoot,finishedWork,committedLanes,committedTransitions,includeWorkInProgressEffects)}parentFiber=parentFiber.sibling}}function recursivelyTraverseAtomicPassiveEffects(finishedRoot$jscomp$0,parentFiber){if(parentFiber.subtreeFlags&10256)for(parentFiber=parentFiber.child;parentFiber!==null;){var finishedRoot=finishedRoot$jscomp$0,finishedWork=parentFiber,flags=finishedWork.flags;switch(finishedWork.tag){case 22:recursivelyTraverseAtomicPassiveEffects(finishedRoot,finishedWork),flags&2048&&commitOffscreenPassiveMountEffects(finishedWork.alternate,finishedWork);break;case 24:recursivelyTraverseAtomicPassiveEffects(finishedRoot,finishedWork),flags&2048&&commitCachePassiveMountEffect(finishedWork.alternate,finishedWork);break;default:recursivelyTraverseAtomicPassiveEffects(finishedRoot,finishedWork)}parentFiber=parentFiber.sibling}}function recursivelyAccumulateSuspenseyCommit(parentFiber,committedLanes,suspendedState){if(parentFiber.subtreeFlags&suspenseyCommitFlag)for(parentFiber=parentFiber.child;parentFiber!==null;)accumulateSuspenseyCommitOnFiber(parentFiber,committedLanes,suspendedState),parentFiber=parentFiber.sibling}function accumulateSuspenseyCommitOnFiber(fiber,committedLanes,suspendedState){switch(fiber.tag){case 26:if(recursivelyAccumulateSuspenseyCommit(fiber,committedLanes,suspendedState),fiber.flags&suspenseyCommitFlag)if(fiber.memoizedState!==null)suspendResource(suspendedState,currentHoistableRoot,fiber.memoizedState,fiber.memoizedProps);else{var instance=fiber.stateNode,type=fiber.type;fiber=fiber.memoizedProps,((committedLanes&335544128)===committedLanes||maySuspendCommitInSyncRender(type,fiber))&&suspendInstance(suspendedState,instance,type,fiber)}break;case 5:recursivelyAccumulateSuspenseyCommit(fiber,committedLanes,suspendedState),fiber.flags&suspenseyCommitFlag&&(instance=fiber.stateNode,type=fiber.type,fiber=fiber.memoizedProps,((committedLanes&335544128)===committedLanes||maySuspendCommitInSyncRender(type,fiber))&&suspendInstance(suspendedState,instance,type,fiber));break;case 3:case 4:supportsResources?(instance=currentHoistableRoot,currentHoistableRoot=getHoistableRoot(fiber.stateNode.containerInfo),recursivelyAccumulateSuspenseyCommit(fiber,committedLanes,suspendedState),currentHoistableRoot=instance):recursivelyAccumulateSuspenseyCommit(fiber,committedLanes,suspendedState);break;case 22:fiber.memoizedState===null&&(instance=fiber.alternate,instance!==null&&instance.memoizedState!==null?(instance=suspenseyCommitFlag,suspenseyCommitFlag=16777216,recursivelyAccumulateSuspenseyCommit(fiber,committedLanes,suspendedState),suspenseyCommitFlag=instance):recursivelyAccumulateSuspenseyCommit(fiber,committedLanes,suspendedState));break;case 30:(fiber.flags&suspenseyCommitFlag)!==0&&(instance=fiber.memoizedProps.name,instance!=null&&instance!=="auto"&&(type=fiber.stateNode,type.paired=null,appearingViewTransitions===null&&(appearingViewTransitions=new Map),appearingViewTransitions.set(instance,type))),recursivelyAccumulateSuspenseyCommit(fiber,committedLanes,suspendedState);break;default:recursivelyAccumulateSuspenseyCommit(fiber,committedLanes,suspendedState)}}function detachAlternateSiblings(parentFiber){var previousFiber=parentFiber.alternate;if(previousFiber!==null&&(parentFiber=previousFiber.child,parentFiber!==null)){previousFiber.child=null;do previousFiber=parentFiber.sibling,parentFiber.sibling=null,parentFiber=previousFiber;while(parentFiber!==null)}}function recursivelyTraversePassiveUnmountEffects(parentFiber){var deletions=parentFiber.deletions;if((parentFiber.flags&16)!==0){if(deletions!==null)for(var i=0;i<deletions.length;i++){var childToDelete=deletions[i];nextEffect=childToDelete,commitPassiveUnmountEffectsInsideOfDeletedTree_begin(childToDelete,parentFiber)}detachAlternateSiblings(parentFiber)}if(parentFiber.subtreeFlags&10256)for(parentFiber=parentFiber.child;parentFiber!==null;)commitPassiveUnmountOnFiber(parentFiber),parentFiber=parentFiber.sibling}function commitPassiveUnmountOnFiber(finishedWork){switch(finishedWork.tag){case 0:case 11:case 15:recursivelyTraversePassiveUnmountEffects(finishedWork),finishedWork.flags&2048&&commitHookEffectListUnmount(9,finishedWork,finishedWork.return);break;case 3:recursivelyTraversePassiveUnmountEffects(finishedWork);break;case 12:recursivelyTraversePassiveUnmountEffects(finishedWork);break;case 22:var instance=finishedWork.stateNode;finishedWork.memoizedState!==null&&instance._visibility&2&&(finishedWork.return===null||finishedWork.return.tag!==13)?(instance._visibility&=-3,recursivelyTraverseDisconnectPassiveEffects(finishedWork)):recursivelyTraversePassiveUnmountEffects(finishedWork);break;default:recursivelyTraversePassiveUnmountEffects(finishedWork)}}function recursivelyTraverseDisconnectPassiveEffects(parentFiber){var deletions=parentFiber.deletions;if((parentFiber.flags&16)!==0){if(deletions!==null)for(var i=0;i<deletions.length;i++){var childToDelete=deletions[i];nextEffect=childToDelete,commitPassiveUnmountEffectsInsideOfDeletedTree_begin(childToDelete,parentFiber)}detachAlternateSiblings(parentFiber)}for(parentFiber=parentFiber.child;parentFiber!==null;){switch(deletions=parentFiber,deletions.tag){case 0:case 11:case 15:commitHookEffectListUnmount(8,deletions,deletions.return),recursivelyTraverseDisconnectPassiveEffects(deletions);break;case 22:i=deletions.stateNode,i._visibility&2&&(i._visibility&=-3,recursivelyTraverseDisconnectPassiveEffects(deletions));break;default:recursivelyTraverseDisconnectPassiveEffects(deletions)}parentFiber=parentFiber.sibling}}function commitPassiveUnmountEffectsInsideOfDeletedTree_begin(deletedSubtreeRoot,nearestMountedAncestor){for(;nextEffect!==null;){var fiber=nextEffect;switch(fiber.tag){case 0:case 11:case 15:commitHookEffectListUnmount(8,fiber,nearestMountedAncestor);break;case 23:case 22:if(fiber.memoizedState!==null&&fiber.memoizedState.cachePool!==null){var cache=fiber.memoizedState.cachePool.pool;cache!=null&&cache.refCount++}break;case 24:releaseCache(fiber.memoizedState.cache)}if(cache=fiber.child,cache!==null)cache.return=fiber,nextEffect=cache;else a:for(fiber=deletedSubtreeRoot;nextEffect!==null;){cache=nextEffect;var sibling=cache.sibling,returnFiber=cache.return;if(detachFiberAfterEffects(cache),cache===fiber){nextEffect=null;break a}if(sibling!==null){sibling.return=returnFiber,nextEffect=sibling;break a}nextEffect=returnFiber}}}function findFiberRootForHostRoot(hostRoot){var maybeFiber=getInstanceFromNode(hostRoot);if(maybeFiber!=null){if(typeof maybeFiber.memoizedProps["data-testname"]!=="string")throw Error(formatProdErrorMessage(364));return maybeFiber}if(hostRoot=findFiberRoot(hostRoot),hostRoot===null)throw Error(formatProdErrorMessage(362));return hostRoot.stateNode.current}function matchSelector(fiber$jscomp$0,selector){var tag=fiber$jscomp$0.tag;switch(selector.$$typeof){case COMPONENT_TYPE:if(fiber$jscomp$0.type===selector.value)return!0;break;case HAS_PSEUDO_CLASS_TYPE:a:{selector=selector.value,fiber$jscomp$0=[fiber$jscomp$0,0];for(tag=0;tag<fiber$jscomp$0.length;){var fiber=fiber$jscomp$0[tag++],tag$jscomp$0=fiber.tag,selectorIndex=fiber$jscomp$0[tag++],selector$jscomp$0=selector[selectorIndex];if(tag$jscomp$0!==5&&tag$jscomp$0!==26&&tag$jscomp$0!==27||!isHiddenSubtree(fiber)){for(;selector$jscomp$0!=null&&matchSelector(fiber,selector$jscomp$0);)selectorIndex++,selector$jscomp$0=selector[selectorIndex];if(selectorIndex===selector.length){selector=!0;break a}else for(fiber=fiber.child;fiber!==null;)fiber$jscomp$0.push(fiber,selectorIndex),fiber=fiber.sibling}}selector=!1}return selector;case ROLE_TYPE:if((tag===5||tag===26||tag===27)&&matchAccessibilityRole(fiber$jscomp$0.stateNode,selector.value))return!0;break;case TEXT_TYPE:if(tag===5||tag===6||tag===26||tag===27){if(fiber$jscomp$0=getTextContent(fiber$jscomp$0),fiber$jscomp$0!==null&&0<=fiber$jscomp$0.indexOf(selector.value))return!0}break;case TEST_NAME_TYPE:if(tag===5||tag===26||tag===27){if(fiber$jscomp$0=fiber$jscomp$0.memoizedProps["data-testname"],typeof fiber$jscomp$0==="string"&&fiber$jscomp$0.toLowerCase()===selector.value.toLowerCase())return!0}break;default:throw Error(formatProdErrorMessage(365))}return!1}function selectorToString(selector){switch(selector.$$typeof){case COMPONENT_TYPE:return"<"+(getComponentNameFromType(selector.value)||"Unknown")+">";case HAS_PSEUDO_CLASS_TYPE:return":has("+(selectorToString(selector)||"")+")";case ROLE_TYPE:return'[role="'+selector.value+'"]';case TEXT_TYPE:return'"'+selector.value+'"';case TEST_NAME_TYPE:return'[data-testname="'+selector.value+'"]';default:throw Error(formatProdErrorMessage(365))}}function findPaths(root,selectors){var matchingFibers=[];root=[root,0];for(var index=0;index<root.length;){var fiber=root[index++],tag=fiber.tag,selectorIndex=root[index++],selector=selectors[selectorIndex];if(tag!==5&&tag!==26&&tag!==27||!isHiddenSubtree(fiber)){for(;selector!=null&&matchSelector(fiber,selector);)selectorIndex++,selector=selectors[selectorIndex];if(selectorIndex===selectors.length)matchingFibers.push(fiber);else for(fiber=fiber.child;fiber!==null;)root.push(fiber,selectorIndex),fiber=fiber.sibling}}return matchingFibers}function findAllNodes(hostRoot,selectors){if(!supportsTestSelectors)throw Error(formatProdErrorMessage(363));hostRoot=findFiberRootForHostRoot(hostRoot),hostRoot=findPaths(hostRoot,selectors),selectors=[],hostRoot=Array.from(hostRoot);for(var index=0;index<hostRoot.length;){var node=hostRoot[index++],tag=node.tag;if(tag===5||tag===26||tag===27)isHiddenSubtree(node)||selectors.push(node.stateNode);else for(node=node.child;node!==null;)hostRoot.push(node),node=node.sibling}return selectors}function requestUpdateLane(){return(executionContext&2)!==0&&workInProgressRootRenderLanes!==0?workInProgressRootRenderLanes&-workInProgressRootRenderLanes:ReactSharedInternals.T!==null?requestTransitionLane():resolveUpdatePriority()}function requestDeferredLane(){if(workInProgressDeferredLane===0)if((workInProgressRootRenderLanes&536870912)===0||isHydrating){var lane=nextTransitionDeferredLane;nextTransitionDeferredLane<<=1,(nextTransitionDeferredLane&3932160)===0&&(nextTransitionDeferredLane=262144),workInProgressDeferredLane=lane}else workInProgressDeferredLane=536870912;return lane=suspenseHandlerStackCursor.current,lane!==null&&(lane.flags|=32),workInProgressDeferredLane}function scheduleViewTransitionEvent(fiber,callback){if(callback!=null){var state=fiber.stateNode,instance=state.ref;instance===null&&(instance=state.ref=createViewTransitionInstance(getViewTransitionName(fiber.memoizedProps,state))),pendingViewTransitionEvents===null&&(pendingViewTransitionEvents=[]),pendingViewTransitionEvents.push(callback.bind(null,instance))}}function scheduleUpdateOnFiber(root,fiber,lane){if(root===workInProgressRoot&&(workInProgressSuspendedReason===2||workInProgressSuspendedReason===9)||root.cancelPendingCommit!==null)prepareFreshStack(root,0),markRootSuspended(root,workInProgressRootRenderLanes,workInProgressDeferredLane,!1);if(markRootUpdated$1(root,lane),(executionContext&2)===0||root!==workInProgressRoot)root===workInProgressRoot&&((executionContext&2)===0&&(workInProgressRootInterleavedUpdatedLanes|=lane),workInProgressRootExitStatus===4&&markRootSuspended(root,workInProgressRootRenderLanes,workInProgressDeferredLane,!1)),ensureRootIsScheduled(root)}function performWorkOnRoot(root$jscomp$0,lanes,forceSync){if((executionContext&6)!==0)throw Error(formatProdErrorMessage(327));var shouldTimeSlice=!forceSync&&(lanes&127)===0&&(lanes&root$jscomp$0.expiredLanes)===0||checkIfRootIsPrerendering(root$jscomp$0,lanes),exitStatus=shouldTimeSlice?renderRootConcurrent(root$jscomp$0,lanes):renderRootSync(root$jscomp$0,lanes,!0),renderWasConcurrent=shouldTimeSlice;do{if(exitStatus===0){workInProgressRootIsPrerendering&&!shouldTimeSlice&&markRootSuspended(root$jscomp$0,lanes,0,!1);break}else{if(forceSync=root$jscomp$0.current.alternate,renderWasConcurrent&&!isRenderConsistentWithExternalStores(forceSync)){exitStatus=renderRootSync(root$jscomp$0,lanes,!1),renderWasConcurrent=!1;continue}if(exitStatus===2){if(renderWasConcurrent=lanes,root$jscomp$0.errorRecoveryDisabledLanes&renderWasConcurrent)var JSCompiler_inline_result=0;else JSCompiler_inline_result=root$jscomp$0.pendingLanes&-536870913,JSCompiler_inline_result=JSCompiler_inline_result!==0?JSCompiler_inline_result:JSCompiler_inline_result&536870912?536870912:0;if(JSCompiler_inline_result!==0){lanes=JSCompiler_inline_result;a:{var root=root$jscomp$0;exitStatus=workInProgressRootConcurrentErrors;var wasRootDehydrated=supportsHydration&&root.current.memoizedState.isDehydrated;if(wasRootDehydrated&&(prepareFreshStack(root,JSCompiler_inline_result).flags|=256),JSCompiler_inline_result=renderRootSync(root,JSCompiler_inline_result,!1),JSCompiler_inline_result!==2&&JSCompiler_inline_result!==6){if(workInProgressRootDidAttachPingListener&&!wasRootDehydrated){root.errorRecoveryDisabledLanes|=renderWasConcurrent,workInProgressRootInterleavedUpdatedLanes|=renderWasConcurrent,exitStatus=4;break a}renderWasConcurrent=workInProgressRootRecoverableErrors,workInProgressRootRecoverableErrors=exitStatus,renderWasConcurrent!==null&&(workInProgressRootRecoverableErrors===null?workInProgressRootRecoverableErrors=renderWasConcurrent:workInProgressRootRecoverableErrors.push.apply(workInProgressRootRecoverableErrors,renderWasConcurrent))}exitStatus=JSCompiler_inline_result}if(renderWasConcurrent=!1,exitStatus!==2)continue}}if(exitStatus===1){prepareFreshStack(root$jscomp$0,0),markRootSuspended(root$jscomp$0,lanes,0,!0);break}a:{switch(shouldTimeSlice=root$jscomp$0,renderWasConcurrent=exitStatus,renderWasConcurrent){case 0:case 1:throw Error(formatProdErrorMessage(345));case 4:if((lanes&4194048)!==lanes&&(lanes&62914560)!==lanes)break;case 6:markRootSuspended(shouldTimeSlice,lanes,workInProgressDeferredLane,!workInProgressRootDidSkipSuspendedSiblings);break a;case 2:workInProgressRootRecoverableErrors=null;break;case 3:case 5:break;default:throw Error(formatProdErrorMessage(329))}if((lanes&62914560)===lanes&&(exitStatus=globalMostRecentFallbackTime+300-now(),10<exitStatus)){if(markRootSuspended(shouldTimeSlice,lanes,workInProgressDeferredLane,!workInProgressRootDidSkipSuspendedSiblings),getNextLanes(shouldTimeSlice,0,!0)!==0)break a;pendingEffectsLanes=lanes,shouldTimeSlice.timeoutHandle=scheduleTimeout(completeRootWhenReady.bind(null,shouldTimeSlice,forceSync,workInProgressRootRecoverableErrors,workInProgressTransitions,workInProgressRootDidIncludeRecursiveRenderUpdate,lanes,workInProgressDeferredLane,workInProgressRootInterleavedUpdatedLanes,workInProgressSuspendedRetryLanes,workInProgressRootDidSkipSuspendedSiblings,renderWasConcurrent,"Throttled",-0,0),exitStatus);break a}completeRootWhenReady(shouldTimeSlice,forceSync,workInProgressRootRecoverableErrors,workInProgressTransitions,workInProgressRootDidIncludeRecursiveRenderUpdate,lanes,workInProgressDeferredLane,workInProgressRootInterleavedUpdatedLanes,workInProgressSuspendedRetryLanes,workInProgressRootDidSkipSuspendedSiblings,renderWasConcurrent,null,-0,0)}}break}while(1);ensureRootIsScheduled(root$jscomp$0)}function completeRootWhenReady(root,finishedWork,recoverableErrors,transitions,didIncludeRenderPhaseUpdate,lanes,spawnedLane,updatedLanes,suspendedRetryLanes,didSkipSuspendedSiblings,exitStatus,suspendedCommitReason,completedRenderStartTime,completedRenderEndTime){root.timeoutHandle=noTimeout;var subtreeFlags=finishedWork.subtreeFlags,isViewTransitionEligible=(lanes&335544064)===lanes;if(suspendedCommitReason=null,isViewTransitionEligible||subtreeFlags&8192||(subtreeFlags&16785408)===16785408){if(suspendedCommitReason=startSuspendingCommit(),appearingViewTransitions=null,accumulateSuspenseyCommitOnFiber(finishedWork,lanes,suspendedCommitReason),isViewTransitionEligible&&suspendOnActiveViewTransition(suspendedCommitReason,root.containerInfo),subtreeFlags=(lanes&62914560)===lanes?globalMostRecentFallbackTime-now():(lanes&4194048)===lanes?globalMostRecentTransitionTime-now():0,subtreeFlags=waitForCommitToBeReady(suspendedCommitReason,subtreeFlags),subtreeFlags!==null){pendingEffectsLanes=lanes,root.cancelPendingCommit=subtreeFlags(completeRoot.bind(null,root,finishedWork,lanes,recoverableErrors,transitions,didIncludeRenderPhaseUpdate,spawnedLane,updatedLanes,suspendedRetryLanes,didSkipSuspendedSiblings,exitStatus,suspendedCommitReason,null,completedRenderStartTime,completedRenderEndTime)),markRootSuspended(root,lanes,spawnedLane,!didSkipSuspendedSiblings);return}}completeRoot(root,finishedWork,lanes,recoverableErrors,transitions,didIncludeRenderPhaseUpdate,spawnedLane,updatedLanes,suspendedRetryLanes,didSkipSuspendedSiblings,exitStatus,suspendedCommitReason)}function isRenderConsistentWithExternalStores(finishedWork){for(var node=finishedWork;;){var tag=node.tag;if((tag===0||tag===11||tag===15)&&node.flags&16384&&(tag=node.updateQueue,tag!==null&&(tag=tag.stores,tag!==null)))for(var i=0;i<tag.length;i++){var check=tag[i],getSnapshot=check.getSnapshot;check=check.value;try{if(!objectIs(getSnapshot(),check))return!1}catch(error){return!1}}if(tag=node.child,node.subtreeFlags&16384&&tag!==null)tag.return=node,node=tag;else{if(node===finishedWork)break;for(;node.sibling===null;){if(node.return===null||node.return===finishedWork)return!0;node=node.return}node.sibling.return=node.return,node=node.sibling}}return!0}function markRootSuspended(root,suspendedLanes,spawnedLane,didAttemptEntireTree){suspendedLanes=getEntangledLanes(root,suspendedLanes),suspendedLanes&=~workInProgressRootPingedLanes,suspendedLanes&=~workInProgressRootInterleavedUpdatedLanes,root.suspendedLanes|=suspendedLanes,root.pingedLanes&=~suspendedLanes,didAttemptEntireTree&&(root.warmLanes|=suspendedLanes),didAttemptEntireTree=root.expirationTimes;for(var lanes=suspendedLanes;0<lanes;){var index$4=31-clz32(lanes),lane=1<<index$4;didAttemptEntireTree[index$4]=-1,lanes&=~lane}spawnedLane!==0&&markSpawnedDeferredLane(root,spawnedLane,suspendedLanes)}function flushSyncWork(){return(executionContext&6)===0?(flushSyncWorkAcrossRoots_impl(0,!1),!1):!0}function resetWorkInProgressStack(){if(workInProgress!==null){if(workInProgressSuspendedReason===0)var interruptedWork=workInProgress.return;else interruptedWork=workInProgress,lastContextDependency=currentlyRenderingFiber$1=null,resetHooksOnUnwind(interruptedWork),thenableState$1=null,thenableIndexCounter$1=0,interruptedWork=workInProgress;for(;interruptedWork!==null;)unwindInterruptedWork(interruptedWork.alternate,interruptedWork),interruptedWork=interruptedWork.return;workInProgress=null}}function prepareFreshStack(root,lanes){var timeoutHandle=root.timeoutHandle;return timeoutHandle!==noTimeout&&(root.timeoutHandle=noTimeout,cancelTimeout(timeoutHandle)),timeoutHandle=root.cancelPendingCommit,timeoutHandle!==null&&(root.cancelPendingCommit=null,timeoutHandle()),pendingEffectsLanes=0,resetWorkInProgressStack(),workInProgressRoot=root,workInProgress=timeoutHandle=createWorkInProgress(root.current,null),workInProgressRootRenderLanes=lanes,workInProgressSuspendedReason=0,workInProgressThrownValue=null,workInProgressRootDidSkipSuspendedSiblings=!1,workInProgressRootIsPrerendering=checkIfRootIsPrerendering(root,lanes),workInProgressRootDidAttachPingListener=!1,workInProgressSuspendedRetryLanes=workInProgressDeferredLane=workInProgressRootPingedLanes=workInProgressRootInterleavedUpdatedLanes=workInProgressRootSkippedLanes=workInProgressRootExitStatus=0,workInProgressRootRecoverableErrors=workInProgressRootConcurrentErrors=null,workInProgressRootDidIncludeRecursiveRenderUpdate=!1,entangledRenderLanes=getEntangledLanes(root,lanes),finishQueueingConcurrentUpdates(),timeoutHandle}function handleThrow(root,thrownValue){currentlyRenderingFiber=null,ReactSharedInternals.H=ContextOnlyDispatcher,thrownValue===SuspenseException||thrownValue===SuspenseActionException?(thrownValue=getSuspendedThenable(),workInProgressSuspendedReason=3):thrownValue===SuspenseyCommitException?(thrownValue=getSuspendedThenable(),workInProgressSuspendedReason=4):workInProgressSuspendedReason=thrownValue===SelectiveHydrationException?8:thrownValue!==null&&typeof thrownValue==="object"&&typeof thrownValue.then==="function"?6:1,workInProgressThrownValue=thrownValue,workInProgress===null&&(workInProgressRootExitStatus=1,logUncaughtError(root,createCapturedValueAtFiber(thrownValue,root.current)))}function shouldRemainOnPreviousScreen(){var handler=suspenseHandlerStackCursor.current;return handler===null?!0:(workInProgressRootRenderLanes&4194048)===workInProgressRootRenderLanes?shellBoundary===null?!0:!1:(workInProgressRootRenderLanes&62914560)===workInProgressRootRenderLanes||(workInProgressRootRenderLanes&536870912)!==0?handler===shellBoundary:!1}function pushDispatcher(){var prevDispatcher=ReactSharedInternals.H;return ReactSharedInternals.H=ContextOnlyDispatcher,prevDispatcher===null?ContextOnlyDispatcher:prevDispatcher}function pushAsyncDispatcher(){var prevAsyncDispatcher=ReactSharedInternals.A;return ReactSharedInternals.A=DefaultAsyncDispatcher,prevAsyncDispatcher}function renderDidSuspendDelayIfPossible(){workInProgressRootExitStatus=4,workInProgressRootDidSkipSuspendedSiblings||(workInProgressRootRenderLanes&4194048)!==workInProgressRootRenderLanes&&suspenseHandlerStackCursor.current!==null||(workInProgressRootIsPrerendering=!0),(workInProgressRootSkippedLanes&134217727)===0&&(workInProgressRootInterleavedUpdatedLanes&134217727)===0||workInProgressRoot===null||markRootSuspended(workInProgressRoot,workInProgressRootRenderLanes,workInProgressDeferredLane,!1)}function renderRootSync(root,lanes,shouldYieldForPrerendering){var prevExecutionContext=executionContext;executionContext|=2;var prevDispatcher=pushDispatcher(),prevAsyncDispatcher=pushAsyncDispatcher();if(workInProgressRoot!==root||workInProgressRootRenderLanes!==lanes)workInProgressTransitions=null,prepareFreshStack(root,lanes);lanes=!1;var exitStatus=workInProgressRootExitStatus;a:do try{if(workInProgressSuspendedReason!==0&&workInProgress!==null){var unitOfWork=workInProgress,thrownValue=workInProgressThrownValue;switch(workInProgressSuspendedReason){case 8:resetWorkInProgressStack(),exitStatus=6;break a;case 3:case 2:case 9:case 6:suspenseHandlerStackCursor.current===null&&(lanes=!0);var reason=workInProgressSuspendedReason;if(workInProgressSuspendedReason=0,workInProgressThrownValue=null,throwAndUnwindWorkLoop(root,unitOfWork,thrownValue,reason),shouldYieldForPrerendering&&workInProgressRootIsPrerendering){exitStatus=0;break a}break;default:reason=workInProgressSuspendedReason,workInProgressSuspendedReason=0,workInProgressThrownValue=null,throwAndUnwindWorkLoop(root,unitOfWork,thrownValue,reason)}}workLoopSync(),exitStatus=workInProgressRootExitStatus;break}catch(thrownValue$169){handleThrow(root,thrownValue$169)}while(1);return lanes&&root.shellSuspendCounter++,lastContextDependency=currentlyRenderingFiber$1=null,executionContext=prevExecutionContext,ReactSharedInternals.H=prevDispatcher,ReactSharedInternals.A=prevAsyncDispatcher,workInProgress===null&&(workInProgressRoot=null,workInProgressRootRenderLanes=0,finishQueueingConcurrentUpdates()),exitStatus}function workLoopSync(){for(;workInProgress!==null;)performUnitOfWork(workInProgress)}function renderRootConcurrent(root,lanes){var prevExecutionContext=executionContext;executionContext|=2;var prevDispatcher=pushDispatcher(),prevAsyncDispatcher=pushAsyncDispatcher();workInProgressRoot!==root||workInProgressRootRenderLanes!==lanes?(workInProgressTransitions=null,workInProgressRootRenderTargetTime=now()+500,prepareFreshStack(root,lanes)):workInProgressRootIsPrerendering=checkIfRootIsPrerendering(root,lanes);a:do try{if(workInProgressSuspendedReason!==0&&workInProgress!==null){lanes=workInProgress;var thrownValue=workInProgressThrownValue;b:switch(workInProgressSuspendedReason){case 1:workInProgressSuspendedReason=0,workInProgressThrownValue=null,throwAndUnwindWorkLoop(root,lanes,thrownValue,1);break;case 2:case 9:if(isThenableResolved(thrownValue)){workInProgressSuspendedReason=0,workInProgressThrownValue=null,replaySuspendedUnitOfWork(lanes);break}lanes=function(){workInProgressSuspendedReason!==2&&workInProgressSuspendedReason!==9||workInProgressRoot!==root||(workInProgressSuspendedReason=7),ensureRootIsScheduled(root)},thrownValue.then(lanes,lanes);break a;case 3:workInProgressSuspendedReason=7;break a;case 4:workInProgressSuspendedReason=5;break a;case 7:isThenableResolved(thrownValue)?(workInProgressSuspendedReason=0,workInProgressThrownValue=null,replaySuspendedUnitOfWork(lanes)):(workInProgressSuspendedReason=0,workInProgressThrownValue=null,throwAndUnwindWorkLoop(root,lanes,thrownValue,7));break;case 5:var resource=null;switch(workInProgress.tag){case 26:resource=workInProgress.memoizedState;case 5:case 27:var hostFiber=workInProgress,{type,pendingProps:props}=hostFiber;if(resource?preloadResource(resource):preloadInstance(hostFiber.stateNode,type,props)){workInProgressSuspendedReason=0,workInProgressThrownValue=null;var sibling=hostFiber.sibling;if(sibling!==null)workInProgress=sibling;else{var returnFiber=hostFiber.return;returnFiber!==null?(workInProgress=returnFiber,completeUnitOfWork(returnFiber)):workInProgress=null}break b}}workInProgressSuspendedReason=0,workInProgressThrownValue=null,throwAndUnwindWorkLoop(root,lanes,thrownValue,5);break;case 6:workInProgressSuspendedReason=0,workInProgressThrownValue=null,throwAndUnwindWorkLoop(root,lanes,thrownValue,6);break;case 8:resetWorkInProgressStack(),workInProgressRootExitStatus=6;break a;default:throw Error(formatProdErrorMessage(462))}}workLoopConcurrentByScheduler();break}catch(thrownValue$171){handleThrow(root,thrownValue$171)}while(1);if(lastContextDependency=currentlyRenderingFiber$1=null,ReactSharedInternals.H=prevDispatcher,ReactSharedInternals.A=prevAsyncDispatcher,executionContext=prevExecutionContext,workInProgress!==null)return 0;return workInProgressRoot=null,workInProgressRootRenderLanes=0,finishQueueingConcurrentUpdates(),workInProgressRootExitStatus}function workLoopConcurrentByScheduler(){for(;workInProgress!==null&&!shouldYield();)performUnitOfWork(workInProgress)}function performUnitOfWork(unitOfWork){var next=beginWork(unitOfWork.alternate,unitOfWork,entangledRenderLanes);unitOfWork.memoizedProps=unitOfWork.pendingProps,next===null?completeUnitOfWork(unitOfWork):workInProgress=next}function replaySuspendedUnitOfWork(unitOfWork){var next=unitOfWork,current=next.alternate;switch(next.tag){case 15:case 0:next=replayFunctionComponent(current,next,next.pendingProps,next.type,void 0,workInProgressRootRenderLanes);break;case 11:next=replayFunctionComponent(current,next,next.pendingProps,next.type.render,next.ref,workInProgressRootRenderLanes);break;case 5:resetHooksOnUnwind(next);var fiber=next;supportsHydration&&fiber===hydrationParentFiber&&(isHydrating?(popToNextHostParent(fiber),fiber.tag===5&&fiber.stateNode!=null&&(nextHydratableInstance=fiber.stateNode)):(popToNextHostParent(fiber),isHydrating=!0));default:unwindInterruptedWork(current,next),next=workInProgress=resetWorkInProgress(next,entangledRenderLanes),next=beginWork(current,next,entangledRenderLanes)}unitOfWork.memoizedProps=unitOfWork.pendingProps,next===null?completeUnitOfWork(unitOfWork):workInProgress=next}function throwAndUnwindWorkLoop(root,unitOfWork,thrownValue,suspendedReason){lastContextDependency=currentlyRenderingFiber$1=null,resetHooksOnUnwind(unitOfWork),thenableState$1=null,thenableIndexCounter$1=0;var returnFiber=unitOfWork.return;try{if(throwException(root,returnFiber,unitOfWork,thrownValue,workInProgressRootRenderLanes)){workInProgressRootExitStatus=1,logUncaughtError(root,createCapturedValueAtFiber(thrownValue,root.current)),workInProgress=null;return}}catch(error){if(returnFiber!==null)throw workInProgress=returnFiber,error;workInProgressRootExitStatus=1,logUncaughtError(root,createCapturedValueAtFiber(thrownValue,root.current)),workInProgress=null;return}if(unitOfWork.flags&32768){if(isHydrating||suspendedReason===1)root=!0;else if(workInProgressRootIsPrerendering||(workInProgressRootRenderLanes&536870912)!==0)root=!1;else if(workInProgressRootDidSkipSuspendedSiblings=root=!0,suspendedReason===2||suspendedReason===9||suspendedReason===3||suspendedReason===6)suspendedReason=suspenseHandlerStackCursor.current,suspendedReason!==null&&suspendedReason.tag===13&&(suspendedReason.flags|=16384);unwindUnitOfWork(unitOfWork,root)}else completeUnitOfWork(unitOfWork)}function completeUnitOfWork(unitOfWork){var completedWork=unitOfWork;do{if((completedWork.flags&32768)!==0){unwindUnitOfWork(completedWork,workInProgressRootDidSkipSuspendedSiblings);return}unitOfWork=completedWork.return;var next=completeWork(completedWork.alternate,completedWork,entangledRenderLanes);if(next!==null){workInProgress=next;return}if(completedWork=completedWork.sibling,completedWork!==null){workInProgress=completedWork;return}workInProgress=completedWork=unitOfWork}while(completedWork!==null);workInProgressRootExitStatus===0&&(workInProgressRootExitStatus=5)}function unwindUnitOfWork(unitOfWork,skipSiblings){do{var next=unwindWork(unitOfWork.alternate,unitOfWork);if(next!==null){next.flags&=32767,workInProgress=next;return}if(next=unitOfWork.return,next!==null&&(next.flags|=32768,next.subtreeFlags=0,next.deletions=null),!skipSiblings&&(unitOfWork=unitOfWork.sibling,unitOfWork!==null)){workInProgress=unitOfWork;return}workInProgress=unitOfWork=next}while(unitOfWork!==null);workInProgressRootExitStatus=6,workInProgress=null}function completeRoot(root,finishedWork,lanes,recoverableErrors,transitions,didIncludeRenderPhaseUpdate,spawnedLane,updatedLanes,suspendedRetryLanes,didSkipSuspendedSiblings,exitStatus,suspendedState){root.cancelPendingCommit=null;do flushPendingEffects();while(pendingEffectsStatus!==0);if((executionContext&6)!==0)throw Error(formatProdErrorMessage(327));if(finishedWork!==null){if(finishedWork===root.current)throw Error(formatProdErrorMessage(177));root===workInProgressRoot&&(workInProgress=workInProgressRoot=null,workInProgressRootRenderLanes=0),pendingFinishedWork=finishedWork,pendingEffectsRoot=root,pendingEffectsLanes=lanes,pendingPassiveTransitions=transitions,pendingRecoverableErrors=recoverableErrors,commitRoot(root,finishedWork,lanes,spawnedLane,updatedLanes,suspendedRetryLanes,suspendedState)}}function commitRoot(root,finishedWork,lanes,spawnedLane,updatedLanes,suspendedRetryLanes,suspendedState){var remainingLanes=finishedWork.lanes|finishedWork.childLanes;if(pendingEffectsRemainingLanes=remainingLanes,remainingLanes|=concurrentlyUpdatedLanes,markRootFinished(root,lanes,remainingLanes,spawnedLane,updatedLanes,suspendedRetryLanes),pendingViewTransitionEvents=null,(lanes&335544064)===lanes?(pendingTransitionTypes=claimQueuedTransitionTypes(root),spawnedLane=10262):(pendingTransitionTypes=null,spawnedLane=10256),(finishedWork.subtreeFlags&spawnedLane)!==0||(finishedWork.flags&spawnedLane)!==0?(root.callbackNode=null,root.callbackPriority=0,scheduleCallback(NormalPriority$1,function(){return flushPassiveEffects(),null})):(root.callbackNode=null,root.callbackPriority=0),shouldStartViewTransition=!1,spawnedLane=(finishedWork.flags&13878)!==0,(finishedWork.subtreeFlags&13878)!==0||spawnedLane){spawnedLane=ReactSharedInternals.T,ReactSharedInternals.T=null,updatedLanes=getCurrentUpdatePriority(),setCurrentUpdatePriority(2),suspendedRetryLanes=executionContext,executionContext|=4;try{commitBeforeMutationEffects(root,finishedWork,lanes)}finally{executionContext=suspendedRetryLanes,setCurrentUpdatePriority(updatedLanes),ReactSharedInternals.T=spawnedLane}}pendingEffectsStatus=1,shouldStartViewTransition?pendingViewTransition=startViewTransition(suspendedState,root.containerInfo,pendingTransitionTypes,flushMutationEffects,flushLayoutEffects,flushAfterMutationEffects,flushSpawnedWork,flushPassiveEffects,reportViewTransitionError,null,null):(flushMutationEffects(),flushLayoutEffects(),flushSpawnedWork())}function reportViewTransitionError(error){if(pendingEffectsStatus!==0){var onRecoverableError=pendingEffectsRoot.onRecoverableError;onRecoverableError(error,{componentStack:null})}}function flushAfterMutationEffects(){pendingEffectsStatus===3&&(pendingEffectsStatus=0,commitAfterMutationEffectsOnFiber(pendingFinishedWork,pendingEffectsRoot),pendingEffectsStatus=4)}function flushMutationEffects(){if(pendingEffectsStatus===1){pendingEffectsStatus=0;var root=pendingEffectsRoot,finishedWork=pendingFinishedWork,lanes=pendingEffectsLanes,rootMutationHasEffect=(finishedWork.flags&13878)!==0;if((finishedWork.subtreeFlags&13878)!==0||rootMutationHasEffect){rootMutationHasEffect=ReactSharedInternals.T,ReactSharedInternals.T=null;var previousPriority=getCurrentUpdatePriority();setCurrentUpdatePriority(2);var prevExecutionContext=executionContext;executionContext|=4;try{inUpdateViewTransition=rootViewTransitionAffected=!1,commitMutationEffectsOnFiber(finishedWork,root,lanes),resetAfterCommit(root.containerInfo)}finally{executionContext=prevExecutionContext,setCurrentUpdatePriority(previousPriority),ReactSharedInternals.T=rootMutationHasEffect}}root.current=finishedWork,pendingEffectsStatus=2}}function flushLayoutEffects(){if(pendingEffectsStatus===2){pendingEffectsStatus=0;var root=pendingEffectsRoot,finishedWork=pendingFinishedWork,rootHasLayoutEffect=(finishedWork.flags&8772)!==0;if((finishedWork.subtreeFlags&8772)!==0||rootHasLayoutEffect){rootHasLayoutEffect=ReactSharedInternals.T,ReactSharedInternals.T=null;var previousPriority=getCurrentUpdatePriority();setCurrentUpdatePriority(2);var prevExecutionContext=executionContext;executionContext|=4;try{commitLayoutEffectOnFiber(root,finishedWork.alternate,finishedWork)}finally{executionContext=prevExecutionContext,setCurrentUpdatePriority(previousPriority),ReactSharedInternals.T=rootHasLayoutEffect}}pendingEffectsStatus=3}}function flushSpawnedWork(){if(pendingEffectsStatus===4||pendingEffectsStatus===3){pendingEffectsStatus=0;var committedViewTransition=pendingViewTransition;pendingViewTransition=null,requestPaint();var root=pendingEffectsRoot,finishedWork=pendingFinishedWork,lanes=pendingEffectsLanes,recoverableErrors=pendingRecoverableErrors,passiveSubtreeMask=(lanes&335544064)===lanes?10262:10256;if((finishedWork.subtreeFlags&passiveSubtreeMask)!==0||(finishedWork.flags&passiveSubtreeMask)!==0?pendingEffectsStatus=5:(pendingEffectsStatus=0,pendingFinishedWork=pendingEffectsRoot=null,releaseRootPooledCache(root,root.pendingLanes)),passiveSubtreeMask=root.pendingLanes,passiveSubtreeMask===0&&(legacyErrorBoundariesThatAlreadyFailed=null),lanesToEventPriority(lanes),finishedWork=finishedWork.stateNode,injectedHook&&typeof injectedHook.onCommitFiberRoot==="function")try{injectedHook.onCommitFiberRoot(rendererID,finishedWork,void 0,(finishedWork.current.flags&128)===128)}catch(err){}if(recoverableErrors!==null){finishedWork=ReactSharedInternals.T,passiveSubtreeMask=getCurrentUpdatePriority(),setCurrentUpdatePriority(2),ReactSharedInternals.T=null;try{for(var onRecoverableError=root.onRecoverableError,i=0;i<recoverableErrors.length;i++){var recoverableError=recoverableErrors[i];onRecoverableError(recoverableError.value,{componentStack:recoverableError.stack})}}finally{ReactSharedInternals.T=finishedWork,setCurrentUpdatePriority(passiveSubtreeMask)}}if(recoverableErrors=pendingViewTransitionEvents,onRecoverableError=pendingTransitionTypes,pendingTransitionTypes=null,recoverableErrors!==null&&(pendingViewTransitionEvents=null,onRecoverableError===null&&(onRecoverableError=[]),committedViewTransition!==null))for(recoverableError=0;recoverableError<recoverableErrors.length;recoverableError++)finishedWork=(0,recoverableErrors[recoverableError])(onRecoverableError),finishedWork!==void 0&&addViewTransitionFinishedListener(committedViewTransition,finishedWork);(pendingEffectsLanes&3)!==0&&flushPendingEffects(),ensureRootIsScheduled(root),passiveSubtreeMask=root.pendingLanes,(lanes&261930)!==0&&(passiveSubtreeMask&42)!==0?root===rootWithNestedUpdates?nestedUpdateCount++:(nestedUpdateCount=0,rootWithNestedUpdates=root):(nestedUpdateCount=0,rootWithNestedUpdates=null),supportsHydration&&flushHydrationEvents(),flushSyncWorkAcrossRoots_impl(0,!1)}}function releaseRootPooledCache(root,remainingLanes){(root.pooledCacheLanes&=remainingLanes)===0&&(remainingLanes=root.pooledCache,remainingLanes!=null&&(root.pooledCache=null,releaseCache(remainingLanes)))}function flushPendingEffects(){return pendingViewTransition!==null&&(stopViewTransition(pendingViewTransition),pendingViewTransition=null),flushMutationEffects(),flushLayoutEffects(),flushSpawnedWork(),flushPassiveEffects()}function flushPassiveEffects(){if(pendingEffectsStatus!==5)return!1;var root=pendingEffectsRoot,remainingLanes=pendingEffectsRemainingLanes;pendingEffectsRemainingLanes=0;var renderPriority=lanesToEventPriority(pendingEffectsLanes),priority=32>renderPriority?32:renderPriority;renderPriority=ReactSharedInternals.T;var previousPriority=getCurrentUpdatePriority();try{setCurrentUpdatePriority(priority),ReactSharedInternals.T=null,priority=pendingPassiveTransitions,pendingPassiveTransitions=null;var root$jscomp$0=pendingEffectsRoot,lanes=pendingEffectsLanes;if(pendingEffectsStatus=0,pendingFinishedWork=pendingEffectsRoot=null,pendingEffectsLanes=0,(executionContext&6)!==0)throw Error(formatProdErrorMessage(331));var prevExecutionContext=executionContext;if(executionContext|=4,commitPassiveUnmountOnFiber(root$jscomp$0.current),commitPassiveMountOnFiber(root$jscomp$0,root$jscomp$0.current,lanes,priority),executionContext=prevExecutionContext,flushSyncWorkAcrossRoots_impl(0,!1),injectedHook&&typeof injectedHook.onPostCommitFiberRoot==="function")try{injectedHook.onPostCommitFiberRoot(rendererID,root$jscomp$0)}catch(err){}return!0}finally{setCurrentUpdatePriority(previousPriority),ReactSharedInternals.T=renderPriority,releaseRootPooledCache(root,remainingLanes)}}function captureCommitPhaseErrorOnRoot(rootFiber,sourceFiber,error){sourceFiber=createCapturedValueAtFiber(error,sourceFiber),sourceFiber=createRootErrorUpdate(rootFiber.stateNode,sourceFiber,2),rootFiber=enqueueUpdate(rootFiber,sourceFiber,2),rootFiber!==null&&(markRootUpdated$1(rootFiber,2),ensureRootIsScheduled(rootFiber))}function captureCommitPhaseError(sourceFiber,nearestMountedAncestor,error){if(sourceFiber.tag===3)captureCommitPhaseErrorOnRoot(sourceFiber,sourceFiber,error);else for(;nearestMountedAncestor!==null;){if(nearestMountedAncestor.tag===3){captureCommitPhaseErrorOnRoot(nearestMountedAncestor,sourceFiber,error);break}else if(nearestMountedAncestor.tag===1){var instance=nearestMountedAncestor.stateNode;if(typeof nearestMountedAncestor.type.getDerivedStateFromError==="function"||typeof instance.componentDidCatch==="function"&&(legacyErrorBoundariesThatAlreadyFailed===null||!legacyErrorBoundariesThatAlreadyFailed.has(instance))){sourceFiber=createCapturedValueAtFiber(error,sourceFiber),error=createClassErrorUpdate(2),instance=enqueueUpdate(nearestMountedAncestor,error,2),instance!==null&&(initializeClassErrorUpdate(error,instance,nearestMountedAncestor,sourceFiber),markRootUpdated$1(instance,2),ensureRootIsScheduled(instance));break}}nearestMountedAncestor=nearestMountedAncestor.return}}function attachPingListener(root,wakeable,lanes){var pingCache=root.pingCache;if(pingCache===null){pingCache=root.pingCache=new PossiblyWeakMap;var threadIDs=new Set;pingCache.set(wakeable,threadIDs)}else threadIDs=pingCache.get(wakeable),threadIDs===void 0&&(threadIDs=new Set,pingCache.set(wakeable,threadIDs));threadIDs.has(lanes)||(workInProgressRootDidAttachPingListener=!0,threadIDs.add(lanes),root=pingSuspendedRoot.bind(null,root,wakeable,lanes),wakeable.then(root,root))}function pingSuspendedRoot(root,wakeable,pingedLanes){var pingCache=root.pingCache;pingCache!==null&&pingCache.delete(wakeable),root.pingedLanes|=root.suspendedLanes&pingedLanes,root.warmLanes&=~pingedLanes,workInProgressRoot===root&&(workInProgressRootRenderLanes&pingedLanes)===pingedLanes&&(workInProgressRootExitStatus===4||workInProgressRootExitStatus===3&&(workInProgressRootRenderLanes&62914560)===workInProgressRootRenderLanes&&300>now()-globalMostRecentFallbackTime?(executionContext&2)===0?prepareFreshStack(root,0):workInProgressRootPingedLanes|=pingedLanes:workInProgressRootPingedLanes|=pingedLanes,workInProgressSuspendedRetryLanes===workInProgressRootRenderLanes&&(workInProgressSuspendedRetryLanes=0)),ensureRootIsScheduled(root)}function retryTimedOutBoundary(boundaryFiber,retryLane){retryLane===0&&(retryLane=claimNextRetryLane()),boundaryFiber=enqueueConcurrentRenderForLane(boundaryFiber,retryLane),boundaryFiber!==null&&(markRootUpdated$1(boundaryFiber,retryLane),ensureRootIsScheduled(boundaryFiber))}function retryDehydratedSuspenseBoundary(boundaryFiber){var suspenseState=boundaryFiber.memoizedState,retryLane=0;suspenseState!==null&&(retryLane=suspenseState.retryLane),retryTimedOutBoundary(boundaryFiber,retryLane)}function resolveRetryWakeable(boundaryFiber,wakeable){var retryLane=0;switch(boundaryFiber.tag){case 31:case 13:var{stateNode:retryCache,memoizedState:suspenseState}=boundaryFiber;suspenseState!==null&&(retryLane=suspenseState.retryLane);break;case 19:retryCache=boundaryFiber.stateNode;break;case 22:retryCache=boundaryFiber.stateNode._retryCache;break;default:throw Error(formatProdErrorMessage(314))}retryCache!==null&&retryCache.delete(wakeable),retryTimedOutBoundary(boundaryFiber,retryLane)}function scheduleCallback(priorityLevel,callback){return scheduleCallback$3(priorityLevel,callback)}function FiberNode(tag,pendingProps,key,mode){this.tag=tag,this.key=key,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=pendingProps,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=mode,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function shouldConstruct(Component){return Component=Component.prototype,!(!Component||!Component.isReactComponent)}function createWorkInProgress(current,pendingProps){var workInProgress=current.alternate;return workInProgress===null?(workInProgress=createFiber(current.tag,pendingProps,current.key,current.mode),workInProgress.elementType=current.elementType,workInProgress.type=current.type,workInProgress.stateNode=current.stateNode,workInProgress.alternate=current,current.alternate=workInProgress):(workInProgress.pendingProps=pendingProps,workInProgress.type=current.type,workInProgress.flags=0,workInProgress.subtreeFlags=0,workInProgress.deletions=null),workInProgress.flags=current.flags&1206910976,workInProgress.childLanes=current.childLanes,workInProgress.lanes=current.lanes,workInProgress.child=current.child,workInProgress.memoizedProps=current.memoizedProps,workInProgress.memoizedState=current.memoizedState,workInProgress.updateQueue=current.updateQueue,pendingProps=current.dependencies,workInProgress.dependencies=pendingProps===null?null:{lanes:pendingProps.lanes,firstContext:pendingProps.firstContext},workInProgress.sibling=current.sibling,workInProgress.index=current.index,workInProgress.ref=current.ref,workInProgress.refCleanup=current.refCleanup,workInProgress}function resetWorkInProgress(workInProgress,renderLanes){workInProgress.flags&=1206910978;var current=workInProgress.alternate;return current===null?(workInProgress.childLanes=0,workInProgress.lanes=renderLanes,workInProgress.child=null,workInProgress.subtreeFlags=0,workInProgress.memoizedProps=null,workInProgress.memoizedState=null,workInProgress.updateQueue=null,workInProgress.dependencies=null,workInProgress.stateNode=null):(workInProgress.childLanes=current.childLanes,workInProgress.lanes=current.lanes,workInProgress.child=current.child,workInProgress.subtreeFlags=0,workInProgress.deletions=null,workInProgress.memoizedProps=current.memoizedProps,workInProgress.memoizedState=current.memoizedState,workInProgress.updateQueue=current.updateQueue,workInProgress.type=current.type,renderLanes=current.dependencies,workInProgress.dependencies=renderLanes===null?null:{lanes:renderLanes.lanes,firstContext:renderLanes.firstContext}),workInProgress}function createFiberFromTypeAndProps(type,key,pendingProps,owner,mode,lanes){var fiberTag=0;if(owner=type,typeof owner==="function")shouldConstruct(owner)&&(fiberTag=1);else if(typeof owner==="string")fiberTag=supportsResources&&supportsSingletons?isHostHoistableType(type,pendingProps,contextStackCursor.current)?26:isHostSingletonType(type)?27:5:supportsResources?isHostHoistableType(type,pendingProps,contextStackCursor.current)?26:5:supportsSingletons?isHostSingletonType(type)?27:5:5;else a:switch(owner){case REACT_ACTIVITY_TYPE:return type=createFiber(31,pendingProps,key,mode),type.elementType=REACT_ACTIVITY_TYPE,type.lanes=lanes,type;case REACT_FRAGMENT_TYPE:return createFiberFromFragment(pendingProps.children,mode,lanes,key);case REACT_STRICT_MODE_TYPE:fiberTag=8,mode|=24;break;case REACT_PROFILER_TYPE:return type=createFiber(12,pendingProps,key,mode|2),type.elementType=REACT_PROFILER_TYPE,type.lanes=lanes,type;case REACT_SUSPENSE_TYPE:return type=createFiber(13,pendingProps,key,mode),type.elementType=REACT_SUSPENSE_TYPE,type.lanes=lanes,type;case REACT_SUSPENSE_LIST_TYPE:return type=createFiber(19,pendingProps,key,mode),type.elementType=REACT_SUSPENSE_LIST_TYPE,type.lanes=lanes,type;case REACT_LEGACY_HIDDEN_TYPE:case REACT_VIEW_TRANSITION_TYPE:return type=mode|32,type=createFiber(30,pendingProps,key,type),type.elementType=REACT_VIEW_TRANSITION_TYPE,type.lanes=lanes,type.stateNode={autoName:null,paired:null,clones:null,ref:null},type;default:if(typeof owner==="object"&&owner!==null)switch(owner.$$typeof){case REACT_CONTEXT_TYPE:fiberTag=10;break a;case REACT_CONSUMER_TYPE:fiberTag=9;break a;case REACT_FORWARD_REF_TYPE:fiberTag=11;break a;case REACT_MEMO_TYPE:fiberTag=14;break a;case REACT_LAZY_TYPE:fiberTag=16,owner=null;break a}fiberTag=29,pendingProps=Error(formatProdErrorMessage(130,type===null?"null":typeof type,"")),owner=null}return key=createFiber(fiberTag,pendingProps,key,mode),key.elementType=type,key.type=owner,key.lanes=lanes,key}function createFiberFromFragment(elements,mode,lanes,key){return elements=createFiber(7,elements,key,mode),elements.lanes=lanes,elements}function createFiberFromText(content,mode,lanes){return content=createFiber(6,content,null,mode),content.lanes=lanes,content}function createFiberFromDehydratedFragment(dehydratedNode){var fiber=createFiber(18,null,null,0);return fiber.stateNode=dehydratedNode,fiber}function createFiberFromPortal(portal,mode,lanes){return mode=createFiber(4,portal.children!==null?portal.children:[],portal.key,mode),mode.lanes=lanes,mode.stateNode={containerInfo:portal.containerInfo,pendingChildren:null,implementation:portal.implementation},mode}function FiberRootNode(containerInfo,tag,hydrate,identifierPrefix,onUncaughtError,onCaughtError,onRecoverableError,onDefaultTransitionIndicator,formState){this.tag=1,this.containerInfo=containerInfo,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=noTimeout,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=createLaneMap(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=createLaneMap(0),this.hiddenUpdates=createLaneMap(null),this.identifierPrefix=identifierPrefix,this.onUncaughtError=onUncaughtError,this.onCaughtError=onCaughtError,this.onRecoverableError=onRecoverableError,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=formState,this.transitionTypes=null,this.incompleteTransitions=new Map}function createFiberRoot(containerInfo,tag,hydrate,initialChildren,hydrationCallbacks,isStrictMode,identifierPrefix,formState,onUncaughtError,onCaughtError,onRecoverableError,onDefaultTransitionIndicator){return containerInfo=new FiberRootNode(containerInfo,tag,hydrate,identifierPrefix,onUncaughtError,onCaughtError,onRecoverableError,onDefaultTransitionIndicator,formState),tag=1,isStrictMode===!0&&(tag|=24),isStrictMode=createFiber(3,null,null,tag),containerInfo.current=isStrictMode,isStrictMode.stateNode=containerInfo,tag=createCache(),tag.refCount++,containerInfo.pooledCache=tag,tag.refCount++,isStrictMode.memoizedState={element:initialChildren,isDehydrated:hydrate,cache:tag},initializeUpdateQueue(isStrictMode),containerInfo}function getContextForSubtree(parentComponent){if(!parentComponent)return emptyContextObject;return parentComponent=emptyContextObject,parentComponent}function findHostInstance(component){var fiber=component._reactInternals;if(fiber===void 0){if(typeof component.render==="function")throw Error(formatProdErrorMessage(188));throw component=Object.keys(component).join(","),Error(formatProdErrorMessage(268,component))}return component=findCurrentFiberUsingSlowPath(fiber),component=component!==null?findCurrentHostFiberImpl(component):null,component===null?null:getPublicInstance(component.stateNode)}function updateContainerImpl(rootFiber,lane,element,container,parentComponent,callback){parentComponent=getContextForSubtree(parentComponent),container.context===null?container.context=parentComponent:container.pendingContext=parentComponent,container=createUpdate(lane),container.payload={element},callback=callback===void 0?null:callback,callback!==null&&(container.callback=callback),element=enqueueUpdate(rootFiber,container,lane),element!==null&&(scheduleUpdateOnFiber(element,rootFiber,lane),entangleTransitions(element,rootFiber,lane))}function markRetryLaneImpl(fiber,retryLane){if(fiber=fiber.memoizedState,fiber!==null&&fiber.dehydrated!==null){var a=fiber.retryLane;fiber.retryLane=a!==0&&a<retryLane?a:retryLane}}function markRetryLaneIfNotHydrated(fiber,retryLane){markRetryLaneImpl(fiber,retryLane),(fiber=fiber.alternate)&&markRetryLaneImpl(fiber,retryLane)}var exports2={},assign=Object.assign,REACT_LEGACY_ELEMENT_TYPE=Symbol.for("react.element"),REACT_ELEMENT_TYPE=Symbol.for("react.transitional.element"),REACT_PORTAL_TYPE=Symbol.for("react.portal"),REACT_FRAGMENT_TYPE=Symbol.for("react.fragment"),REACT_STRICT_MODE_TYPE=Symbol.for("react.strict_mode"),REACT_PROFILER_TYPE=Symbol.for("react.profiler"),REACT_CONSUMER_TYPE=Symbol.for("react.consumer"),REACT_CONTEXT_TYPE=Symbol.for("react.context"),REACT_FORWARD_REF_TYPE=Symbol.for("react.forward_ref"),REACT_SUSPENSE_TYPE=Symbol.for("react.suspense"),REACT_SUSPENSE_LIST_TYPE=Symbol.for("react.suspense_list"),REACT_MEMO_TYPE=Symbol.for("react.memo"),REACT_LAZY_TYPE=Symbol.for("react.lazy"),REACT_ACTIVITY_TYPE=Symbol.for("react.activity"),REACT_LEGACY_HIDDEN_TYPE=Symbol.for("react.legacy_hidden"),REACT_MEMO_CACHE_SENTINEL=Symbol.for("react.memo_cache_sentinel"),REACT_VIEW_TRANSITION_TYPE=Symbol.for("react.view_transition"),REACT_RECOVERABLE_TYPE=Symbol.for("react.recoverable"),MAYBE_ITERATOR_SYMBOL=Symbol.iterator,REACT_OPTIMISTIC_KEY=Symbol.for("react.optimistic_key"),REACT_CLIENT_REFERENCE=Symbol.for("react.client.reference"),isArrayImpl=Array.isArray,ReactSharedInternals=$__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,{rendererVersion,rendererPackageName,extraDevToolsConfig,getPublicInstance,getRootHostContext,getChildHostContext,prepareForCommit,resetAfterCommit,createInstance}=$$$config;$$$config.cloneMutableInstance;var{appendInitialChild,finalizeInitialChildren,shouldSetTextContent,createTextInstance}=$$$config;$$$config.cloneMutableTextInstance;var{scheduleTimeout,cancelTimeout,noTimeout,isPrimaryRenderer}=$$$config;$$$config.warnsIfNotActing;var{supportsMutation,supportsPersistence,supportsHydration,getInstanceFromNode}=$$$config;$$$config.beforeActiveInstanceBlur;var preparePortalMount=$$$config.preparePortalMount;$$$config.prepareScopeUpdate,$$$config.getInstanceFromScope;var{setCurrentUpdatePriority,getCurrentUpdatePriority,resolveUpdatePriority}=$$$config;$$$config.trackSchedulerEvent,$$$config.resolveEventType,$$$config.resolveEventTimeStamp;var{shouldAttemptEagerTransition,detachDeletedInstance}=$$$config;$$$config.requestPostPaintCallback;var{maySuspendCommit,maySuspendCommitOnUpdate,maySuspendCommitInSyncRender,preloadInstance,startSuspendingCommit,suspendInstance,suspendOnActiveViewTransition,waitForCommitToBeReady}=$$$config;$$$config.getSuspendedCommitReason;var{NotPendingTransition,HostTransitionContext,resetFormInstance}=$$$config;$$$config.bindToConsole;var{supportsMicrotasks,scheduleMicrotask,supportsTestSelectors,findFiberRoot,getBoundingRect,getTextContent,isHiddenSubtree,matchAccessibilityRole,setFocusIfFocusable,setupIntersectionObserver,appendChild,appendChildToContainer,commitTextUpdate,commitMount,commitUpdate,insertBefore,insertInContainerBefore,removeChild,removeChildFromContainer,resetTextContent,hideInstance,hideTextInstance,unhideInstance,unhideTextInstance,applyViewTransitionName,restoreViewTransitionName,cancelViewTransitionName,cancelRootViewTransitionName,restoreRootViewTransitionName}=$$$config;$$$config.cloneRootViewTransitionContainer,$$$config.removeRootViewTransitionClone;var{measureInstance,measureClonedInstance,wasInstanceInViewport,hasInstanceChanged,hasInstanceAffectedParent,startViewTransition}=$$$config;$$$config.startGestureTransition;var{stopViewTransition,addViewTransitionFinishedListener}=$$$config;$$$config.getCurrentGestureOffset;var{createViewTransitionInstance,clearContainer,createFragmentInstance,updateFragmentInstanceFiber,commitNewChildToFragmentInstance,deleteChildFromFragmentInstance,cloneInstance,createContainerChildSet,appendChildToContainerChildSet,finalizeContainerChildren,replaceContainerChildren,cloneHiddenInstance,cloneHiddenTextInstance,isSuspenseInstancePending,isSuspenseInstanceFallback,getSuspenseInstanceFallbackErrorDetails,registerSuspenseInstanceRetry,canHydrateFormStateMarker,isFormStateMarkerMatching,getNextHydratableSibling,getNextHydratableSiblingAfterSingleton,getFirstHydratableChild,getFirstHydratableChildWithinContainer,getFirstHydratableChildWithinActivityInstance,getFirstHydratableChildWithinSuspenseInstance,getFirstHydratableChildWithinSingleton,canHydrateInstance,canHydrateTextInstance,canHydrateActivityInstance,canHydrateSuspenseInstance,hydrateInstance,hydrateTextInstance,hydrateActivityInstance,hydrateSuspenseInstance,getNextHydratableInstanceAfterActivityInstance,getNextHydratableInstanceAfterSuspenseInstance,commitHydratedInstance,commitHydratedContainer,commitHydratedActivityInstance,commitHydratedSuspenseInstance,finalizeHydratedChildren,flushHydrationEvents}=$$$config;$$$config.clearActivityBoundary;var clearSuspenseBoundary=$$$config.clearSuspenseBoundary;$$$config.clearActivityBoundaryFromContainer;var{clearSuspenseBoundaryFromContainer,hideDehydratedBoundary,unhideDehydratedBoundary,shouldDeleteUnhydratedTailInstances}=$$$config;$$$config.diffHydratedPropsForDevWarnings,$$$config.diffHydratedTextForDevWarnings,$$$config.describeHydratableInstanceForDevWarnings;var{validateHydratableInstance,validateHydratableTextInstance,supportsResources,isHostHoistableType,getHoistableRoot,getResource,acquireResource,releaseResource,hydrateHoistable,mountHoistable,unmountHoistable,createHoistableInstance,prepareToCommitHoistables,mayResourceSuspendCommit,preloadResource,suspendResource,supportsSingletons,resolveSingletonInstance,acquireSingletonInstance,releaseSingletonInstance,isHostSingletonType,isSingletonScope}=$$$config,valueStack=[],index$jscomp$0=-1,emptyContextObject={},clz32=Math.clz32?Math.clz32:clz32Fallback,{log:log$1,LN2}=Math,nextTransitionUpdateLane=256,nextTransitionDeferredLane=262144,nextRetryLane=4194304,scheduleCallback$3=$unstable_scheduleCallback,cancelCallback$1=$unstable_cancelCallback,shouldYield=$unstable_shouldYield,requestPaint=$unstable_requestPaint,now=$unstable_now,ImmediatePriority=$unstable_ImmediatePriority,UserBlockingPriority=$unstable_UserBlockingPriority,NormalPriority$1=$unstable_NormalPriority,IdlePriority=$unstable_IdlePriority,log2=void 0,unstable_setDisableYieldValue2=void 0,rendererID=null,injectedHook=null,globalClientIdCounter$1=0,objectIs=typeof Object.is==="function"?Object.is:is,reportGlobalError=typeof reportError==="function"?reportError:function(error){if(typeof window==="object"&&typeof window.ErrorEvent==="function"){var event=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof error==="object"&&error!==null&&typeof error.message==="string"?String(error.message):String(error),error});if(!window.dispatchEvent(event))return}else if(typeof process==="object"&&typeof process.emit==="function"){process.emit("uncaughtException",error);return}console.error(error)},hasOwnProperty=Object.prototype.hasOwnProperty,prefix,suffix,reentry=!1,CapturedStacks=new WeakMap,forkStack=[],forkStackIndex=0,treeForkProvider=null,treeForkCount=0,idStack=[],idStackIndex=0,treeContextProvider=null,treeContextId=1,treeContextOverflow="",contextStackCursor=createCursor(null),contextFiberStackCursor=createCursor(null),rootInstanceStackCursor=createCursor(null),hostTransitionProviderCursor=createCursor(null),hydrationParentFiber=null,nextHydratableInstance=null,isHydrating=!1,hydrationErrors=null,rootOrSingletonContext=!1,HydrationMismatchException=Error(formatProdErrorMessage(519)),valueCursor=createCursor(null),currentlyRenderingFiber$1=null,lastContextDependency=null,AbortControllerLocal=typeof AbortController<"u"?AbortController:function(){var listeners=[],signal=this.signal={aborted:!1,addEventListener:function(type,listener){listeners.push(listener)}};this.abort=function(){signal.aborted=!0,listeners.forEach(function(listener){return listener()})}},scheduleCallback$2=$unstable_scheduleCallback,NormalPriority=$unstable_NormalPriority,CacheContext={$$typeof:REACT_CONTEXT_TYPE,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0},entangledTransitionTypes=null,firstScheduledRoot=null,lastScheduledRoot=null,didScheduleMicrotask=!1,mightHavePendingSyncWork=!1,isFlushingWork=!1,currentEventTransitionLane=0,currentEntangledListeners=null,currentEntangledPendingCount=0,currentEntangledLane=0,currentEntangledActionThenable=null,prevOnStartTransitionFinish=ReactSharedInternals.S;ReactSharedInternals.S=function(transition,returnValue){if(globalMostRecentTransitionTime=now(),typeof returnValue==="object"&&returnValue!==null&&typeof returnValue.then==="function"&&entangleAsyncAction(transition,returnValue),entangledTransitionTypes!==null)for(var root=firstScheduledRoot;root!==null;)queueTransitionTypes(root,entangledTransitionTypes),root=root.next;if(root=transition.types,root!==null){for(var root$19=firstScheduledRoot;root$19!==null;)queueTransitionTypes(root$19,root),root$19=root$19.next;if(currentEntangledLane!==0){root$19=entangledTransitionTypes,root$19===null&&(root$19=entangledTransitionTypes=[]);for(var i=0;i<root.length;i++){var transitionType=root[i];root$19.indexOf(transitionType)===-1&&root$19.push(transitionType)}}}prevOnStartTransitionFinish!==null&&prevOnStartTransitionFinish(transition,returnValue)};var resumedCache=createCursor(null),SuspenseException=Error(formatProdErrorMessage(460)),SuspenseyCommitException=Error(formatProdErrorMessage(474)),SuspenseActionException=Error(formatProdErrorMessage(542)),noopSuspenseyCommitThenable={then:function(){}},suspendedThenable=null,thenableState$1=null,thenableIndexCounter$1=0,reconcileChildFibers=createChildReconciler(!0),mountChildFibers=createChildReconciler(!1),concurrentQueues=[],concurrentQueuesIndex=0,concurrentlyUpdatedLanes=0,hasForceUpdate=!1,didReadFromEntangledAsyncAction=!1,currentTreeHiddenStackCursor=createCursor(null),prevEntangledRenderLanesCursor=createCursor(0),suspenseHandlerStackCursor=createCursor(null),shellBoundary=null,suspenseStackCursor=createCursor(0),renderLanes=0,currentlyRenderingFiber=null,currentHook=null,workInProgressHook=null,didScheduleRenderPhaseUpdate=!1,didScheduleRenderPhaseUpdateDuringThisPass=!1,shouldDoubleInvokeUserFnsInHooksDEV=!1,localIdCounter=0,thenableIndexCounter=0,thenableState=null,globalClientIdCounter=0,ContextOnlyDispatcher={readContext,use,useCallback:throwInvalidHookError,useContext:throwInvalidHookError,useEffect:throwInvalidHookError,useImperativeHandle:throwInvalidHookError,useLayoutEffect:throwInvalidHookError,useInsertionEffect:throwInvalidHookError,useMemo:throwInvalidHookError,useReducer:throwInvalidHookError,useRef:throwInvalidHookError,useState:throwInvalidHookError,useDebugValue:throwInvalidHookError,useDeferredValue:throwInvalidHookError,useTransition:throwInvalidHookError,useSyncExternalStore:throwInvalidHookError,useId:throwInvalidHookError,useHostTransitionStatus:throwInvalidHookError,useFormState:throwInvalidHookError,useActionState:throwInvalidHookError,useOptimistic:throwInvalidHookError,useMemoCache:throwInvalidHookError,useCacheRefresh:throwInvalidHookError,useEffectEvent:throwInvalidHookError},HooksDispatcherOnMount={readContext,use,useCallback:function(callback,deps){return mountWorkInProgressHook().memoizedState=[callback,deps===void 0?null:deps],callback},useContext:readContext,useEffect:mountEffect,useImperativeHandle:function(ref,create,deps){deps=deps!==null&&deps!==void 0?deps.concat([ref]):null,mountEffectImpl(4194308,4,imperativeHandleEffect.bind(null,create,ref),deps)},useLayoutEffect:function(create,deps){return mountEffectImpl(4194308,4,create,deps)},useInsertionEffect:function(create,deps){mountEffectImpl(4,2,create,deps)},useMemo:function(nextCreate,deps){var hook=mountWorkInProgressHook();deps=deps===void 0?null:deps;var nextValue=nextCreate();if(shouldDoubleInvokeUserFnsInHooksDEV){setIsStrictModeForDevtools(!0);try{nextCreate()}finally{setIsStrictModeForDevtools(!1)}}return hook.memoizedState=[nextValue,deps],nextValue},useReducer:function(reducer,initialArg,init){var hook=mountWorkInProgressHook();if(init!==void 0){var initialState=init(initialArg);if(shouldDoubleInvokeUserFnsInHooksDEV){setIsStrictModeForDevtools(!0);try{init(initialArg)}finally{setIsStrictModeForDevtools(!1)}}}else initialState=initialArg;return hook.memoizedState=hook.baseState=initialState,reducer={pending:null,lanes:0,dispatch:null,lastRenderedReducer:reducer,lastRenderedState:initialState},hook.queue=reducer,reducer=reducer.dispatch=dispatchReducerAction.bind(null,currentlyRenderingFiber,reducer),[hook.memoizedState,reducer]},useRef:function(initialValue){var hook=mountWorkInProgressHook();return initialValue={current:initialValue},hook.memoizedState=initialValue},useState:function(initialState){initialState=mountStateImpl(initialState);var queue=initialState.queue,dispatch=dispatchSetState.bind(null,currentlyRenderingFiber,queue);return queue.dispatch=dispatch,[initialState.memoizedState,dispatch]},useDebugValue:mountDebugValue,useDeferredValue:function(value,initialValue){var hook=mountWorkInProgressHook();return mountDeferredValueImpl(hook,value,initialValue)},useTransition:function(){var stateHook=mountStateImpl(!1);return stateHook=startTransition.bind(null,currentlyRenderingFiber,stateHook.queue,!0,!1),mountWorkInProgressHook().memoizedState=stateHook,[!1,stateHook]},useSyncExternalStore:function(subscribe,getSnapshot,getServerSnapshot){var fiber=currentlyRenderingFiber,hook=mountWorkInProgressHook();if(isHydrating){if(getServerSnapshot===void 0)throw Error(formatProdErrorMessage(407));getServerSnapshot=getServerSnapshot()}else{if(getServerSnapshot=getSnapshot(),workInProgressRoot===null)throw Error(formatProdErrorMessage(349));(workInProgressRootRenderLanes&127)!==0||pushStoreConsistencyCheck(fiber,getSnapshot,getServerSnapshot)}hook.memoizedState=getServerSnapshot;var inst={value:getServerSnapshot,getSnapshot};return hook.queue=inst,mountEffect(subscribeToStore.bind(null,fiber,inst,subscribe),[subscribe]),fiber.flags|=2048,pushSimpleEffect(9,{destroy:void 0},updateStoreInstance.bind(null,fiber,inst,getServerSnapshot,getSnapshot),null),getServerSnapshot},useId:function(){var hook=mountWorkInProgressHook(),identifierPrefix=workInProgressRoot.identifierPrefix;if(isHydrating){var JSCompiler_inline_result=treeContextOverflow,idWithLeadingBit=treeContextId;JSCompiler_inline_result=(idWithLeadingBit&~(1<<32-clz32(idWithLeadingBit)-1)).toString(32)+JSCompiler_inline_result,identifierPrefix="_"+identifierPrefix+"R_"+JSCompiler_inline_result,JSCompiler_inline_result=localIdCounter++,0<JSCompiler_inline_result&&(identifierPrefix+="H"+JSCompiler_inline_result.toString(32)),identifierPrefix+="_"}else JSCompiler_inline_result=globalClientIdCounter++,identifierPrefix="_"+identifierPrefix+"r_"+JSCompiler_inline_result.toString(32)+"_";return hook.memoizedState=identifierPrefix},useHostTransitionStatus,useFormState:mountActionState,useActionState:mountActionState,useOptimistic:function(passthrough){var hook=mountWorkInProgressHook();hook.memoizedState=hook.baseState=passthrough;var queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return hook.queue=queue,hook=dispatchOptimisticSetState.bind(null,currentlyRenderingFiber,!0,queue),queue.dispatch=hook,[passthrough,hook]},useMemoCache,useCacheRefresh:function(){return mountWorkInProgressHook().memoizedState=refreshCache.bind(null,currentlyRenderingFiber)},useEffectEvent:function(callback){var hook=mountWorkInProgressHook(),ref={impl:callback};return hook.memoizedState=ref,function(){if((executionContext&2)!==0)throw Error(formatProdErrorMessage(440));return ref.impl.apply(void 0,arguments)}}},HooksDispatcherOnUpdate={readContext,use,useCallback:updateCallback,useContext:readContext,useEffect:updateEffect,useImperativeHandle:updateImperativeHandle,useInsertionEffect:updateInsertionEffect,useLayoutEffect:updateLayoutEffect,useMemo:updateMemo,useReducer:updateReducer,useRef:updateRef,useState:function(){return updateReducer(basicStateReducer)},useDebugValue:mountDebugValue,useDeferredValue:function(value,initialValue){var hook=updateWorkInProgressHook();return updateDeferredValueImpl(hook,currentHook.memoizedState,value,initialValue)},useTransition:function(){var booleanOrThenable=updateReducer(basicStateReducer)[0],start=updateWorkInProgressHook().memoizedState;return[typeof booleanOrThenable==="boolean"?booleanOrThenable:useThenable(booleanOrThenable),start]},useSyncExternalStore:updateSyncExternalStore,useId:updateId,useHostTransitionStatus,useFormState:updateActionState,useActionState:updateActionState,useOptimistic:function(passthrough,reducer){var hook=updateWorkInProgressHook();return updateOptimisticImpl(hook,currentHook,passthrough,reducer)},useMemoCache,useCacheRefresh:updateRefresh,useEffectEvent:updateEvent},HooksDispatcherOnRerender={readContext,use,useCallback:updateCallback,useContext:readContext,useEffect:updateEffect,useImperativeHandle:updateImperativeHandle,useInsertionEffect:updateInsertionEffect,useLayoutEffect:updateLayoutEffect,useMemo:updateMemo,useReducer:rerenderReducer,useRef:updateRef,useState:function(){return rerenderReducer(basicStateReducer)},useDebugValue:mountDebugValue,useDeferredValue:function(value,initialValue){var hook=updateWorkInProgressHook();return currentHook===null?mountDeferredValueImpl(hook,value,initialValue):updateDeferredValueImpl(hook,currentHook.memoizedState,value,initialValue)},useTransition:function(){var booleanOrThenable=rerenderReducer(basicStateReducer)[0],start=updateWorkInProgressHook().memoizedState;return[typeof booleanOrThenable==="boolean"?booleanOrThenable:useThenable(booleanOrThenable),start]},useSyncExternalStore:updateSyncExternalStore,useId:updateId,useHostTransitionStatus,useFormState:rerenderActionState,useActionState:rerenderActionState,useOptimistic:function(passthrough,reducer){var hook=updateWorkInProgressHook();if(currentHook!==null)return updateOptimisticImpl(hook,currentHook,passthrough,reducer);return hook.baseState=passthrough,[passthrough,hook.queue.dispatch]},useMemoCache,useCacheRefresh:updateRefresh,useEffectEvent:updateEvent},classComponentUpdater={enqueueSetState:function(inst,payload,callback){inst=inst._reactInternals;var lane=requestUpdateLane(),update=createUpdate(lane);update.payload=payload,callback!==void 0&&callback!==null&&(update.callback=callback),payload=enqueueUpdate(inst,update,lane),payload!==null&&(scheduleUpdateOnFiber(payload,inst,lane),entangleTransitions(payload,inst,lane))},enqueueReplaceState:function(inst,payload,callback){inst=inst._reactInternals;var lane=requestUpdateLane(),update=createUpdate(lane);update.tag=1,update.payload=payload,callback!==void 0&&callback!==null&&(update.callback=callback),payload=enqueueUpdate(inst,update,lane),payload!==null&&(scheduleUpdateOnFiber(payload,inst,lane),entangleTransitions(payload,inst,lane))},enqueueForceUpdate:function(inst,callback){inst=inst._reactInternals;var lane=requestUpdateLane(),update=createUpdate(lane);update.tag=2,callback!==void 0&&callback!==null&&(update.callback=callback),callback=enqueueUpdate(inst,update,lane),callback!==null&&(scheduleUpdateOnFiber(callback,inst,lane),entangleTransitions(callback,inst,lane))}},SelectiveHydrationException=Error(formatProdErrorMessage(461)),didReceiveUpdate=!1,SUSPENDED_MARKER={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null},viewTransitionMutationContext=!1,shouldStartViewTransition=!1,appearingViewTransitions=null,viewTransitionCancelableChildren=null,viewTransitionHostInstanceIdx=0,offscreenSubtreeIsHidden=!1,offscreenSubtreeWasHidden=!1,offscreenDirectParentIsHidden=!1,needsFormReset=!1,PossiblyWeakSet=typeof WeakSet==="function"?WeakSet:Set,nextEffect=null,viewTransitionContextChanged=!1,inUpdateViewTransition=!1,rootViewTransitionAffected=!1,rootViewTransitionNameCanceled=!1,hostParent=null,hostParentIsContainer=!1,currentHoistableRoot=null,suspenseyCommitFlag=8192,DefaultAsyncDispatcher={getCacheForType:function(resourceType){var cache=readContext(CacheContext),cacheForType=cache.data.get(resourceType);return cacheForType===void 0&&(cacheForType=resourceType(),cache.data.set(resourceType,cacheForType)),cacheForType},cacheSignal:function(){return readContext(CacheContext).controller.signal}},COMPONENT_TYPE=0,HAS_PSEUDO_CLASS_TYPE=1,ROLE_TYPE=2,TEST_NAME_TYPE=3,TEXT_TYPE=4;if(typeof Symbol==="function"&&Symbol.for){var symbolFor=Symbol.for;COMPONENT_TYPE=symbolFor("selector.component"),HAS_PSEUDO_CLASS_TYPE=symbolFor("selector.has_pseudo_class"),ROLE_TYPE=symbolFor("selector.role"),TEST_NAME_TYPE=symbolFor("selector.test_id"),TEXT_TYPE=symbolFor("selector.text")}var PossiblyWeakMap=typeof WeakMap==="function"?WeakMap:Map,executionContext=0,workInProgressRoot=null,workInProgress=null,workInProgressRootRenderLanes=0,workInProgressSuspendedReason=0,workInProgressThrownValue=null,workInProgressRootDidSkipSuspendedSiblings=!1,workInProgressRootIsPrerendering=!1,workInProgressRootDidAttachPingListener=!1,entangledRenderLanes=0,workInProgressRootExitStatus=0,workInProgressRootSkippedLanes=0,workInProgressRootInterleavedUpdatedLanes=0,workInProgressRootPingedLanes=0,workInProgressDeferredLane=0,workInProgressSuspendedRetryLanes=0,workInProgressRootConcurrentErrors=null,workInProgressRootRecoverableErrors=null,workInProgressRootDidIncludeRecursiveRenderUpdate=!1,globalMostRecentFallbackTime=0,globalMostRecentTransitionTime=0,workInProgressRootRenderTargetTime=1/0,workInProgressTransitions=null,legacyErrorBoundariesThatAlreadyFailed=null,pendingEffectsStatus=0,pendingEffectsRoot=null,pendingFinishedWork=null,pendingEffectsLanes=0,pendingEffectsRemainingLanes=0,pendingPassiveTransitions=null,pendingRecoverableErrors=null,pendingViewTransition=null,pendingViewTransitionEvents=null,pendingTransitionTypes=null,nestedUpdateCount=0,rootWithNestedUpdates=null;return exports2.attemptContinuousHydration=function(fiber){if(fiber.tag===13||fiber.tag===31){var root=enqueueConcurrentRenderForLane(fiber,67108864);root!==null&&scheduleUpdateOnFiber(root,fiber,67108864),markRetryLaneIfNotHydrated(fiber,67108864)}},exports2.attemptHydrationAtCurrentPriority=function(fiber){if(fiber.tag===13||fiber.tag===31){var lane=requestUpdateLane();lane=getBumpedLaneForHydrationByLane(lane);var root=enqueueConcurrentRenderForLane(fiber,lane);root!==null&&scheduleUpdateOnFiber(root,fiber,lane),markRetryLaneIfNotHydrated(fiber,lane)}},exports2.attemptSynchronousHydration=function(fiber){switch(fiber.tag){case 3:if(fiber=fiber.stateNode,fiber.current.memoizedState.isDehydrated){var lanes=getHighestPriorityLanes(fiber.pendingLanes);if(lanes!==0){fiber.pendingLanes|=2;for(fiber.entangledLanes|=2;lanes;){var lane=1<<31-clz32(lanes);fiber.entanglements[1]|=lane,lanes&=~lane}ensureRootIsScheduled(fiber),(executionContext&6)===0&&(workInProgressRootRenderTargetTime=now()+500,flushSyncWorkAcrossRoots_impl(0,!1))}}break;case 31:case 13:lanes=enqueueConcurrentRenderForLane(fiber,2),lanes!==null&&scheduleUpdateOnFiber(lanes,fiber,2),flushSyncWork(),markRetryLaneIfNotHydrated(fiber,2)}},exports2.batchedUpdates=function(fn,a){return fn(a)},exports2.createComponentSelector=function(component){return{$$typeof:COMPONENT_TYPE,value:component}},exports2.createContainer=function(containerInfo,tag,hydrationCallbacks,isStrictMode,concurrentUpdatesByDefaultOverride,identifierPrefix,onUncaughtError,onCaughtError,onRecoverableError,onDefaultTransitionIndicator){return createFiberRoot(containerInfo,tag,!1,null,hydrationCallbacks,isStrictMode,identifierPrefix,null,onUncaughtError,onCaughtError,onRecoverableError,onDefaultTransitionIndicator)},exports2.createHasPseudoClassSelector=function(selectors){return{$$typeof:HAS_PSEUDO_CLASS_TYPE,value:selectors}},exports2.createHydrationContainer=function(initialChildren,callback,containerInfo,tag,hydrationCallbacks,isStrictMode,concurrentUpdatesByDefaultOverride,identifierPrefix,onUncaughtError,onCaughtError,onRecoverableError,onDefaultTransitionIndicator,transitionCallbacks,formState){return initialChildren=createFiberRoot(containerInfo,tag,!0,initialChildren,hydrationCallbacks,isStrictMode,identifierPrefix,formState,onUncaughtError,onCaughtError,onRecoverableError,onDefaultTransitionIndicator),initialChildren.context=getContextForSubtree(null),containerInfo=initialChildren.current,tag=requestUpdateLane(),tag=getBumpedLaneForHydrationByLane(tag),hydrationCallbacks=createUpdate(tag),hydrationCallbacks.callback=callback!==void 0&&callback!==null?callback:null,enqueueUpdate(containerInfo,hydrationCallbacks,tag),callback=tag,initialChildren.current.lanes=callback,markRootUpdated$1(initialChildren,callback),ensureRootIsScheduled(initialChildren),initialChildren},exports2.createPortal=function(children,containerInfo,implementation){var key=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:REACT_PORTAL_TYPE,key:key==null?null:key===REACT_OPTIMISTIC_KEY?REACT_OPTIMISTIC_KEY:""+key,children,containerInfo,implementation}},exports2.createRoleSelector=function(role){return{$$typeof:ROLE_TYPE,value:role}},exports2.createTestNameSelector=function(id){return{$$typeof:TEST_NAME_TYPE,value:id}},exports2.createTextSelector=function(text){return{$$typeof:TEXT_TYPE,value:text}},exports2.defaultOnCaughtError=function(error){console.error(error)},exports2.defaultOnRecoverableError=function(error){reportGlobalError(error)},exports2.defaultOnUncaughtError=function(error){reportGlobalError(error)},exports2.deferredUpdates=function(fn){var prevTransition=ReactSharedInternals.T,previousPriority=getCurrentUpdatePriority();try{return setCurrentUpdatePriority(32),ReactSharedInternals.T=null,fn()}finally{setCurrentUpdatePriority(previousPriority),ReactSharedInternals.T=prevTransition}},exports2.discreteUpdates=function(fn,a,b,c,d){var prevTransition=ReactSharedInternals.T,previousPriority=getCurrentUpdatePriority();try{return setCurrentUpdatePriority(2),ReactSharedInternals.T=null,fn(a,b,c,d)}finally{setCurrentUpdatePriority(previousPriority),ReactSharedInternals.T=prevTransition,executionContext===0&&(workInProgressRootRenderTargetTime=now()+500)}},exports2.findAllNodes=findAllNodes,exports2.findBoundingRects=function(hostRoot,selectors){if(!supportsTestSelectors)throw Error(formatProdErrorMessage(363));selectors=findAllNodes(hostRoot,selectors),hostRoot=[];for(var i=0;i<selectors.length;i++)hostRoot.push(getBoundingRect(selectors[i]));for(selectors=hostRoot.length-1;0<selectors;selectors--){i=hostRoot[selectors];for(var targetLeft=i.x,targetRight=targetLeft+i.width,targetTop=i.y,targetBottom=targetTop+i.height,j=selectors-1;0<=j;j--)if(selectors!==j){var otherRect=hostRoot[j],otherLeft=otherRect.x,otherRight=otherLeft+otherRect.width,otherTop=otherRect.y,otherBottom=otherTop+otherRect.height;if(targetLeft>=otherLeft&&targetTop>=otherTop&&targetRight<=otherRight&&targetBottom<=otherBottom){hostRoot.splice(selectors,1);break}else if(!(targetLeft!==otherLeft||i.width!==otherRect.width||otherBottom<targetTop||otherTop>targetBottom)){otherTop>targetTop&&(otherRect.height+=otherTop-targetTop,otherRect.y=targetTop),otherBottom<targetBottom&&(otherRect.height=targetBottom-otherTop),hostRoot.splice(selectors,1);break}else if(!(targetTop!==otherTop||i.height!==otherRect.height||otherRight<targetLeft||otherLeft>targetRight)){otherLeft>targetLeft&&(otherRect.width+=otherLeft-targetLeft,otherRect.x=targetLeft),otherRight<targetRight&&(otherRect.width=targetRight-otherLeft),hostRoot.splice(selectors,1);break}}}return hostRoot},exports2.findHostInstance=findHostInstance,exports2.findHostInstanceWithNoPortals=function(fiber){return fiber=findCurrentFiberUsingSlowPath(fiber),fiber=fiber!==null?findCurrentHostFiberWithNoPortalsImpl(fiber):null,fiber===null?null:getPublicInstance(fiber.stateNode)},exports2.findHostInstanceWithWarning=function(component){return findHostInstance(component)},exports2.flushPassiveEffects=flushPendingEffects,exports2.flushSyncFromReconciler=function(fn){var prevExecutionContext=executionContext;executionContext|=1;var prevTransition=ReactSharedInternals.T,previousPriority=getCurrentUpdatePriority();try{if(setCurrentUpdatePriority(2),ReactSharedInternals.T=null,fn)return fn()}finally{setCurrentUpdatePriority(previousPriority),ReactSharedInternals.T=prevTransition,executionContext=prevExecutionContext,(executionContext&6)===0&&flushSyncWorkAcrossRoots_impl(0,!1)}},exports2.flushSyncWork=flushSyncWork,exports2.focusWithin=function(hostRoot,selectors){if(!supportsTestSelectors)throw Error(formatProdErrorMessage(363));hostRoot=findFiberRootForHostRoot(hostRoot),selectors=findPaths(hostRoot,selectors),selectors=Array.from(selectors);for(hostRoot=0;hostRoot<selectors.length;){var fiber=selectors[hostRoot++],tag=fiber.tag;if(!isHiddenSubtree(fiber)){if((tag===5||tag===26||tag===27)&&setFocusIfFocusable(fiber.stateNode))return!0;for(fiber=fiber.child;fiber!==null;)selectors.push(fiber),fiber=fiber.sibling}}return!1},exports2.getFindAllNodesFailureDescription=function(hostRoot,selectors){if(!supportsTestSelectors)throw Error(formatProdErrorMessage(363));var maxSelectorIndex=0,matchedNames=[];hostRoot=[findFiberRootForHostRoot(hostRoot),0];for(var index=0;index<hostRoot.length;){var fiber=hostRoot[index++],tag=fiber.tag,selectorIndex=hostRoot[index++],selector=selectors[selectorIndex];if(tag!==5&&tag!==26&&tag!==27||!isHiddenSubtree(fiber)){if(matchSelector(fiber,selector)&&(matchedNames.push(selectorToString(selector)),selectorIndex++,selectorIndex>maxSelectorIndex&&(maxSelectorIndex=selectorIndex)),selectorIndex<selectors.length)for(fiber=fiber.child;fiber!==null;)hostRoot.push(fiber,selectorIndex),fiber=fiber.sibling}}if(maxSelectorIndex<selectors.length){for(hostRoot=[];maxSelectorIndex<selectors.length;maxSelectorIndex++)hostRoot.push(selectorToString(selectors[maxSelectorIndex]));return`findAllNodes was able to match part of the selector:
1285
- `+(matchedNames.join(" > ")+`
1286
-
1287
- No matching component was found for:
1288
- `)+hostRoot.join(" > ")}return null},exports2.getPublicRootInstance=function(container){if(container=container.current,!container.child)return null;switch(container.child.tag){case 27:case 5:return getPublicInstance(container.child.stateNode);default:return container.child.stateNode}},exports2.injectIntoDevTools=function(){var internals={bundleType:0,version:rendererVersion,rendererPackageName,currentDispatcherRef:ReactSharedInternals,reconcilerVersion:"19.3.0"};if(extraDevToolsConfig!==null&&(internals.rendererConfig=extraDevToolsConfig),typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")internals=!1;else{var hook=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(hook.isDisabled||!hook.supportsFiber)internals=!0;else{try{rendererID=hook.inject(internals),injectedHook=hook}catch(err){}internals=hook.checkDCE?!0:!1}}return internals},exports2.isAlreadyRendering=function(){return(executionContext&6)!==0},exports2.observeVisibleRects=function(hostRoot,selectors,callback,options){if(!supportsTestSelectors)throw Error(formatProdErrorMessage(363));hostRoot=findAllNodes(hostRoot,selectors);var disconnect=setupIntersectionObserver(hostRoot,callback,options).disconnect;return{disconnect:function(){disconnect()}}},exports2.shouldError=function(){return null},exports2.shouldSuspend=function(){return!1},exports2.startHostTransition=function(formFiber,pendingState,action,formData){if(formFiber.tag!==5)throw Error(formatProdErrorMessage(476));var queue=ensureFormComponentIsStateful(formFiber).queue;startTransition(formFiber,queue,pendingState,NotPendingTransition,action===null?noop:function(){var stateHook=ensureFormComponentIsStateful(formFiber);return stateHook.next===null&&(stateHook=formFiber.alternate.memoizedState),dispatchSetStateInternal(formFiber,stateHook.next.queue,{},requestUpdateLane()),action(formData)})},exports2.updateContainer=function(element,container,parentComponent,callback){var current=container.current,lane=requestUpdateLane();return updateContainerImpl(current,lane,element,container,parentComponent,callback),lane},exports2.updateContainerSync=function(element,container,parentComponent,callback){return updateContainerImpl(container.current,2,element,container,parentComponent,callback),2},exports2};module.exports.default=module.exports;Object.defineProperty(module.exports,"__esModule",{value:!0})});function widestLine(string){let lineWidth=0;for(let line of string.split(`
1289
- `))lineWidth=Math.max(lineWidth,stringWidth(line));return lineWidth}var init_widest_line=__esm(()=>{init_string_width()});var QuickLRU;var init_quick_lru=__esm(()=>{QuickLRU=class QuickLRU extends Map{#size=0;#cache=new Map;#oldCache=new Map;#maxSize;#maxAge;#onEviction;constructor(options={}){super();if(!(options.maxSize&&options.maxSize>0))throw TypeError("`maxSize` must be a number greater than 0");if(typeof options.maxAge==="number"&&options.maxAge===0)throw TypeError("`maxAge` must be a number greater than 0");this.#maxSize=options.maxSize,this.#maxAge=options.maxAge||Number.POSITIVE_INFINITY,this.#onEviction=options.onEviction}get __oldCache(){return this.#oldCache}#emitEvictions(cache){if(typeof this.#onEviction!=="function")return;for(let[key,item]of cache)this.#onEviction(key,item.value)}#deleteIfExpired(key,item){if(typeof item.expiry==="number"&&item.expiry<=Date.now()){if(typeof this.#onEviction==="function")this.#onEviction(key,item.value);return this.delete(key)}return!1}#getOrDeleteIfExpired(key,item){if(this.#deleteIfExpired(key,item)===!1)return item.value}#getItemValue(key,item){return item.expiry?this.#getOrDeleteIfExpired(key,item):item.value}#peek(key,cache){let item=cache.get(key);return this.#getItemValue(key,item)}#set(key,value){if(this.#cache.set(key,value),this.#size++,this.#size>=this.#maxSize)this.#size=0,this.#emitEvictions(this.#oldCache),this.#oldCache=this.#cache,this.#cache=new Map}#moveToRecent(key,item){this.#oldCache.delete(key),this.#set(key,item)}*#entriesAscending(){for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield item}}for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield item}}get(key){if(this.#cache.has(key)){let item=this.#cache.get(key);return this.#getItemValue(key,item)}if(this.#oldCache.has(key)){let item=this.#oldCache.get(key);if(this.#deleteIfExpired(key,item)===!1)return this.#moveToRecent(key,item),item.value}}set(key,value,{maxAge=this.#maxAge}={}){let expiry=typeof maxAge==="number"&&maxAge!==Number.POSITIVE_INFINITY?Date.now()+maxAge:void 0;if(this.#cache.has(key))this.#cache.set(key,{value,expiry});else this.#set(key,{value,expiry});return this}has(key){if(this.#cache.has(key))return!this.#deleteIfExpired(key,this.#cache.get(key));if(this.#oldCache.has(key))return!this.#deleteIfExpired(key,this.#oldCache.get(key));return!1}peek(key){if(this.#cache.has(key))return this.#peek(key,this.#cache);if(this.#oldCache.has(key))return this.#peek(key,this.#oldCache)}expiresIn(key){let item=this.#cache.get(key)??this.#oldCache.get(key);if(item)return item.expiry?item.expiry-Date.now():Number.POSITIVE_INFINITY}delete(key){let deleted=this.#cache.delete(key);if(deleted)this.#size--;return this.#oldCache.delete(key)||deleted}clear(){this.#cache.clear(),this.#oldCache.clear(),this.#size=0}resize(newSize){if(!(newSize&&newSize>0))throw TypeError("`maxSize` must be a number greater than 0");let items=[...this.#entriesAscending()],removeCount=items.length-newSize;if(removeCount<0)this.#cache=new Map(items),this.#oldCache=new Map,this.#size=items.length;else{if(removeCount>0)this.#emitEvictions(items.slice(0,removeCount));this.#oldCache=new Map(items.slice(removeCount)),this.#cache=new Map,this.#size=0}this.#maxSize=newSize}evict(count=1){let requested=Number(count);if(!requested||requested<=0)return;let items=[...this.#entriesAscending()],evictCount=Math.trunc(Math.min(requested,Math.max(items.length-1,0)));if(evictCount<=0)return;this.#emitEvictions(items.slice(0,evictCount)),this.#oldCache=new Map(items.slice(evictCount)),this.#cache=new Map,this.#size=0}*keys(){for(let[key]of this)yield key}*values(){for(let[,value]of this)yield value}*[Symbol.iterator](){for(let item of this.#cache){let[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}for(let item of this.#oldCache){let[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesDescending(){let items=[...this.#cache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}items=[...this.#oldCache];for(let i=items.length-1;i>=0;--i){let item=items[i],[key,value]=item;if(!this.#cache.has(key)){if(this.#deleteIfExpired(key,value)===!1)yield[key,value.value]}}}*entriesAscending(){for(let[key,value]of this.#entriesAscending())yield[key,value.value]}get size(){if(!this.#size)return this.#oldCache.size;let oldCacheSize=0;for(let key of this.#oldCache.keys())if(!this.#cache.has(key))oldCacheSize++;return Math.min(this.#size+oldCacheSize,this.#maxSize)}get maxSize(){return this.#maxSize}get maxAge(){return this.#maxAge}entries(){return this.entriesAscending()}forEach(callbackFunction,thisArgument=this){for(let[key,value]of this.entriesAscending())callbackFunction.call(thisArgument,value,key,this)}get[Symbol.toStringTag](){return"QuickLRU"}toString(){return`QuickLRU(${this.size}/${this.maxSize})`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}});var cache,measureText=(text)=>{if(text.length===0)return{width:0,height:0};let cachedDimensions=cache.get(text);if(cachedDimensions)return cachedDimensions;let width=widestLine(text),height=text.split(`
1290
- `).length,dimensions={width,height};return cache.set(text,dimensions),dimensions},measure_text_default;var init_measure_text=__esm(()=>{init_widest_line();init_quick_lru();cache=new QuickLRU({maxSize:4096}),measure_text_default=measureText});function assembleStyles3(){let codes=new Map;for(let[groupName,group]of Object.entries(styles4)){for(let[styleName,style]of Object.entries(group))styles4[styleName]={open:`\x1B[${style[0]}m`,close:`\x1B[${style[1]}m`},group[styleName]=styles4[styleName],codes.set(style[0],style[1]);Object.defineProperty(styles4,groupName,{value:group,enumerable:!1})}return Object.defineProperty(styles4,"codes",{value:codes,enumerable:!1}),styles4.color.close="\x1B[39m",styles4.bgColor.close="\x1B[49m",styles4.color.ansi=wrapAnsi163(),styles4.color.ansi256=wrapAnsi2563(),styles4.color.ansi16m=wrapAnsi16m3(),styles4.bgColor.ansi=wrapAnsi163(10),styles4.bgColor.ansi256=wrapAnsi2563(10),styles4.bgColor.ansi16m=wrapAnsi16m3(10),Object.defineProperties(styles4,{rgbToAnsi256:{value(red,green,blue){if(red===green&&green===blue){if(red<8)return 16;if(red>248)return 231;return Math.round((red-8)/247*24)+232}return 16+36*Math.round(red/255*5)+6*Math.round(green/255*5)+Math.round(blue/255*5)},enumerable:!1},hexToRgb:{value(hex){let matches=/[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));if(!matches)return[0,0,0];let[colorString]=matches;if(colorString.length===3)colorString=[...colorString].map((character)=>character+character).join("");let integer=Number.parseInt(colorString,16);return[integer>>16&255,integer>>8&255,integer&255]},enumerable:!1},hexToAnsi256:{value:(hex)=>styles4.rgbToAnsi256(...styles4.hexToRgb(hex)),enumerable:!1},ansi256ToAnsi:{value(code){if(code<8)return 30+code;if(code<16)return 90+(code-8);let red,green,blue;if(code>=232)red=((code-232)*10+8)/255,green=red,blue=red;else{code-=16;let remainder=code%36;red=Math.floor(code/36)/5,green=Math.floor(remainder/6)/5,blue=remainder%6/5}let value=Math.max(red,green,blue)*2;if(value===0)return 30;let result=30+(Math.round(blue)<<2|Math.round(green)<<1|Math.round(red));if(value===2)result+=60;return result},enumerable:!1},rgbToAnsi:{value:(red,green,blue)=>styles4.ansi256ToAnsi(styles4.rgbToAnsi256(red,green,blue)),enumerable:!1},hexToAnsi:{value:(hex)=>styles4.ansi256ToAnsi(styles4.hexToAnsi256(hex)),enumerable:!1}}),styles4}var wrapAnsi163=(offset=0)=>(code)=>`\x1B[${code+offset}m`,wrapAnsi2563=(offset=0)=>(code)=>`\x1B[${38+offset};5;${code}m`,wrapAnsi16m3=(offset=0)=>(red,green,blue)=>`\x1B[${38+offset};2;${red};${green};${blue}m`,styles4,modifierNames3,foregroundColorNames3,backgroundColorNames3,colorNames3,ansiStyles3,ansi_styles_default3;var init_ansi_styles3=__esm(()=>{styles4={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},modifierNames3=Object.keys(styles4.modifier),foregroundColorNames3=Object.keys(styles4.color),backgroundColorNames3=Object.keys(styles4.bgColor),colorNames3=[...foregroundColorNames3,...backgroundColorNames3];ansiStyles3=assembleStyles3(),ansi_styles_default3=ansiStyles3});function isFullwidthCodePoint(codePoint){if(!Number.isInteger(codePoint))return!1;return isFullwidth(codePoint)||isWide(codePoint)}var init_is_fullwidth_code_point=__esm(()=>{init_get_east_asian_width()});function isSgrParameterCharacter(codePoint){return codePoint>=CODE_POINT_0&&codePoint<=CODE_POINT_9||codePoint===CODE_POINT_SEMICOLON||codePoint===CODE_POINT_COLON}function isCsiParameterCharacter(codePoint){return codePoint>=CODE_POINT_CSI_PARAMETER_START&&codePoint<=CODE_POINT_CSI_PARAMETER_END}function isCsiIntermediateCharacter(codePoint){return codePoint>=CODE_POINT_CSI_INTERMEDIATE_START&&codePoint<=CODE_POINT_CSI_INTERMEDIATE_END}function isCsiFinalCharacter(codePoint){return codePoint>=CODE_POINT_CSI_FINAL_START&&codePoint<=CODE_POINT_CSI_FINAL_END}function isRegionalIndicatorCodePoint(codePoint){return codePoint>=REGIONAL_INDICATOR_SYMBOL_LETTER_A&&codePoint<=REGIONAL_INDICATOR_SYMBOL_LETTER_Z}function createControlParseResult(code,endIndex){return{token:{type:"control",code},endIndex}}function isEmojiStyleGrapheme(grapheme){if(EMOJI_PRESENTATION_GRAPHEME_REGEX.test(grapheme))return!0;for(let character of grapheme){let codePoint=character.codePointAt(0);if(codePoint===VARIATION_SELECTOR_16_CODE_POINT||codePoint===COMBINING_ENCLOSING_KEYCAP_CODE_POINT)return!0}return!1}function getGraphemeWidth(grapheme){let regionalIndicatorCount=0;for(let character of grapheme){let codePoint=character.codePointAt(0);if(isFullwidthCodePoint(codePoint))return 2;if(isRegionalIndicatorCodePoint(codePoint))regionalIndicatorCount++}if(regionalIndicatorCount>=1)return 2;if(isEmojiStyleGrapheme(grapheme))return 2;return 1}function getSgrPrefix(code){if(code.startsWith("›"))return"›";return`${ESCAPE}${ANSI_CSI2}`}function createSgrCode(prefix,values){return`${prefix}${values.join(";")}${ANSI_SGR_TERMINATOR2}`}function getSgrFragments(code){let fragments=[],sgrPrefix=getSgrPrefix(code),parameterString;if(code.startsWith(`${ESCAPE}${ANSI_CSI2}`))parameterString=code.slice(2,-1);else if(code.startsWith("›"))parameterString=code.slice(1,-1);else return fragments;let rawCodes=parameterString.length===0?[String(SGR_RESET_CODE)]:parameterString.split(";"),index=0;while(index<rawCodes.length){let codeNumber=Number.parseInt(rawCodes[index],10);if(Number.isNaN(codeNumber)){index++;continue}if(codeNumber===SGR_RESET_CODE){fragments.push({type:"reset"}),index++;continue}if(codeNumber===SGR_EXTENDED_FOREGROUND_CODE||codeNumber===SGR_EXTENDED_BACKGROUND_CODE){let colorType=Number.parseInt(rawCodes[index+1],10);if(colorType===SGR_COLOR_TYPE_ANSI_256&&index+SGR_ANSI_256_LAST_PARAMETER_OFFSET<rawCodes.length){let openCode=createSgrCode(sgrPrefix,rawCodes.slice(index,index+SGR_ANSI_256_FRAGMENT_LENGTH));fragments.push({type:"start",code:openCode,endCode:ansi_styles_default3.color.ansi(codeNumber===SGR_EXTENDED_FOREGROUND_CODE?SGR_DEFAULT_FOREGROUND_CODE:SGR_DEFAULT_BACKGROUND_CODE)}),index+=SGR_ANSI_256_FRAGMENT_LENGTH;continue}if(colorType===SGR_COLOR_TYPE_TRUECOLOR&&index+SGR_TRUECOLOR_LAST_PARAMETER_OFFSET<rawCodes.length){let openCode=createSgrCode(sgrPrefix,rawCodes.slice(index,index+SGR_TRUECOLOR_FRAGMENT_LENGTH));fragments.push({type:"start",code:openCode,endCode:ansi_styles_default3.color.ansi(codeNumber===SGR_EXTENDED_FOREGROUND_CODE?SGR_DEFAULT_FOREGROUND_CODE:SGR_DEFAULT_BACKGROUND_CODE)}),index+=SGR_TRUECOLOR_FRAGMENT_LENGTH;continue}let openCode=createSgrCode(sgrPrefix,[rawCodes[index]]);fragments.push({type:"start",code:openCode,endCode:ansi_styles_default3.color.ansi(codeNumber===SGR_EXTENDED_FOREGROUND_CODE?SGR_DEFAULT_FOREGROUND_CODE:SGR_DEFAULT_BACKGROUND_CODE)}),index++;continue}if(endCodeNumbers.has(codeNumber)){fragments.push({type:"end",endCode:ansi_styles_default3.color.ansi(codeNumber)}),index++;continue}let mappedEndCode=ansi_styles_default3.codes.get(codeNumber);if(mappedEndCode!==void 0){let openCode=createSgrCode(sgrPrefix,[rawCodes[index]]);fragments.push({type:"start",code:openCode,endCode:ansi_styles_default3.color.ansi(mappedEndCode)}),index++;continue}let openCode=createSgrCode(sgrPrefix,[rawCodes[index]]);fragments.push({type:"start",code:openCode,endCode:ansi_styles_default3.reset.open}),index++}if(fragments.length===0)fragments.push({type:"reset"});return fragments}function parseCsiCode(string,index){let escapeCodePoint=string.codePointAt(index),sequenceStartIndex;if(escapeCodePoint===ESCAPE_CODE_POINT){if(string[index+1]!==ANSI_CSI2)return;sequenceStartIndex=index+2}else if(escapeCodePoint===C1_CSI_CODE_POINT)sequenceStartIndex=index+1;else return;let hasCanonicalSgrParameters=!0;for(let sequenceIndex=sequenceStartIndex;sequenceIndex<string.length;sequenceIndex++){let codePoint=string.codePointAt(sequenceIndex);if(isCsiFinalCharacter(codePoint)){let code=string.slice(index,sequenceIndex+1);if(string[sequenceIndex]!==ANSI_SGR_TERMINATOR2||!hasCanonicalSgrParameters)return createControlParseResult(code,sequenceIndex+1);return{token:{type:"sgr",code,fragments:getSgrFragments(code)},endIndex:sequenceIndex+1}}if(isCsiParameterCharacter(codePoint)){if(!isSgrParameterCharacter(codePoint))hasCanonicalSgrParameters=!1;continue}if(isCsiIntermediateCharacter(codePoint)){hasCanonicalSgrParameters=!1;continue}let endIndex=sequenceIndex;return createControlParseResult(string.slice(index,endIndex),endIndex)}return createControlParseResult(string.slice(index),string.length)}function parseHyperlinkCode(string,index){let hyperlinkPrefix,hyperlinkClose,codePoint=string.codePointAt(index);if(codePoint===ESCAPE_CODE_POINT&&string.startsWith(ANSI_HYPERLINK_ESC_PREFIX,index))hyperlinkPrefix=ANSI_HYPERLINK_ESC_PREFIX,hyperlinkClose=ANSI_HYPERLINK_ESC_CLOSE;else if(codePoint===C1_OSC_CODE_POINT&&string.startsWith(ANSI_HYPERLINK_C1_PREFIX,index))hyperlinkPrefix=ANSI_HYPERLINK_C1_PREFIX,hyperlinkClose=ANSI_HYPERLINK_C1_CLOSE;else return;let uriStart=string.indexOf(";",index+hyperlinkPrefix.length);if(uriStart===-1)return createControlParseResult(string.slice(index),string.length);for(let sequenceIndex=uriStart+1;sequenceIndex<string.length;sequenceIndex++){let character=string[sequenceIndex];if(character===ANSI_BELL){let code=string.slice(index,sequenceIndex+1),action=sequenceIndex===uriStart+1?"close":"open";return{token:{type:"hyperlink",code,action,closePrefix:hyperlinkClose,terminator:ANSI_BELL},endIndex:sequenceIndex+1}}if(character===ESCAPE&&string[sequenceIndex+1]===ANSI_OSC_TERMINATOR){let code=string.slice(index,sequenceIndex+2),action=sequenceIndex===uriStart+1?"close":"open";return{token:{type:"hyperlink",code,action,closePrefix:hyperlinkClose,terminator:ANSI_STRING_TERMINATOR},endIndex:sequenceIndex+2}}if(character===C1_STRING_TERMINATOR){let code=string.slice(index,sequenceIndex+1),action=sequenceIndex===uriStart+1?"close":"open";return{token:{type:"hyperlink",code,action,closePrefix:hyperlinkClose,terminator:C1_STRING_TERMINATOR},endIndex:sequenceIndex+1}}}return createControlParseResult(string.slice(index),string.length)}function parseControlStringCode(string,index){let codePoint=string.codePointAt(index),sequenceStartIndex,supportsBellTerminator=!1;switch(codePoint){case ESCAPE_CODE_POINT:{switch(string[index+1]){case ANSI_OSC2:{sequenceStartIndex=index+2,supportsBellTerminator=!0;break}case ANSI_DCS:case ANSI_SOS:case ANSI_PM:case ANSI_APC:{sequenceStartIndex=index+2;break}case ANSI_OSC_TERMINATOR:return createControlParseResult(ANSI_STRING_TERMINATOR,index+2);default:return}break}case C1_OSC_CODE_POINT:{sequenceStartIndex=index+1,supportsBellTerminator=!0;break}case C1_DCS_CODE_POINT:case C1_SOS_CODE_POINT:case C1_PM_CODE_POINT:case C1_APC_CODE_POINT:{sequenceStartIndex=index+1;break}case C1_ST_CODE_POINT:return createControlParseResult(C1_STRING_TERMINATOR,index+1);default:return}for(let sequenceIndex=sequenceStartIndex;sequenceIndex<string.length;sequenceIndex++){if(supportsBellTerminator&&string[sequenceIndex]===ANSI_BELL)return createControlParseResult(string.slice(index,sequenceIndex+1),sequenceIndex+1);if(string[sequenceIndex]===ESCAPE&&string[sequenceIndex+1]===ANSI_OSC_TERMINATOR)return createControlParseResult(string.slice(index,sequenceIndex+2),sequenceIndex+2);if(string[sequenceIndex]===C1_STRING_TERMINATOR)return createControlParseResult(string.slice(index,sequenceIndex+1),sequenceIndex+1)}return createControlParseResult(string.slice(index),string.length)}function parseAnsiCode(string,index){let codePoint=string.codePointAt(index);if(codePoint===ESCAPE_CODE_POINT||codePoint===C1_OSC_CODE_POINT){let hyperlinkCode=parseHyperlinkCode(string,index);if(hyperlinkCode)return hyperlinkCode}let controlStringCode=parseControlStringCode(string,index);if(controlStringCode)return controlStringCode;return parseCsiCode(string,index)}function appendTrailingAnsiTokens(string,index,tokens){while(index<string.length){let nextCodePoint=string.codePointAt(index);if(!ESCAPES2.has(nextCodePoint))break;let escapeCode=parseAnsiCode(string,index);if(!escapeCode)break;tokens.push(escapeCode.token),index=escapeCode.endIndex}return index}function parseCharacterTokenWithRawSegmentation(string,index,graphemeSegments){let segment=graphemeSegments.containing(index);if(!segment||segment.index!==index)return;return{token:{type:"character",value:segment.segment,visibleWidth:getGraphemeWidth(segment.segment),isGraphemeContinuation:!1},endIndex:index+segment.segment.length}}function collectVisibleCharacters(string){let visibleCharacters=[],index=0;while(index<string.length){let codePoint=string.codePointAt(index);if(ESCAPES2.has(codePoint)){let code=parseAnsiCode(string,index);if(code){index=code.endIndex;continue}}let value=String.fromCodePoint(codePoint);visibleCharacters.push({value,visibleWidth:1,isGraphemeContinuation:!1}),index+=value.length}return visibleCharacters}function applyGraphemeMetadata(visibleCharacters){if(visibleCharacters.length===0)return;let visibleString=visibleCharacters.map(({value})=>value).join(""),scalarOffsets=[],scalarOffset=0;for(let visibleCharacter of visibleCharacters)scalarOffsets.push(scalarOffset),scalarOffset+=visibleCharacter.value.length;let scalarIndex=0;for(let segment of GRAPHEME_SEGMENTER2.segment(visibleString)){while(scalarIndex<visibleCharacters.length&&scalarOffsets[scalarIndex]<segment.index)scalarIndex++;let graphemeIndex=scalarIndex,isFirstInGrapheme=!0;while(graphemeIndex<visibleCharacters.length&&scalarOffsets[graphemeIndex]<segment.index+segment.segment.length)visibleCharacters[graphemeIndex].visibleWidth=isFirstInGrapheme?getGraphemeWidth(segment.segment):0,visibleCharacters[graphemeIndex].isGraphemeContinuation=!isFirstInGrapheme,isFirstInGrapheme=!1,graphemeIndex++;scalarIndex=graphemeIndex}}function tokenizeAnsiWithVisibleSegmentation(string,{endCharacter=Number.POSITIVE_INFINITY}={}){let tokens=[],visibleCharacters=collectVisibleCharacters(string);applyGraphemeMetadata(visibleCharacters);let index=0,visibleCharacterIndex=0,visibleCount=0;while(index<string.length){let codePoint=string.codePointAt(index);if(ESCAPES2.has(codePoint)){let code=parseAnsiCode(string,index);if(code){tokens.push(code.token),index=code.endIndex;continue}}let value=String.fromCodePoint(codePoint),visibleCharacter=visibleCharacters[visibleCharacterIndex],visibleWidth=isFullwidthCodePoint(codePoint)?2:value.length;if(visibleCharacter)visibleWidth=visibleCharacter.visibleWidth;let token={type:"character",value,visibleWidth,isGraphemeContinuation:visibleCharacter?visibleCharacter.isGraphemeContinuation:!1};if(tokens.push(token),index+=value.length,visibleCharacterIndex++,visibleCount+=token.visibleWidth,visibleCount>=endCharacter){let nextVisibleCharacter=visibleCharacters[visibleCharacterIndex];if(!nextVisibleCharacter||!nextVisibleCharacter.isGraphemeContinuation){index=appendTrailingAnsiTokens(string,index,tokens);break}}}return tokens}function areValuesInSameGrapheme(leftValue,rightValue){let pair=`${leftValue}${rightValue}`,splitIndex=leftValue.length;for(let segment of GRAPHEME_SEGMENTER2.segment(pair)){if(segment.index===splitIndex)return!1;if(segment.index>splitIndex)return!0}return!0}function hasAnsiSplitContinuationAhead(string,startIndex,previousVisibleValue,graphemeSegments){if(!previousVisibleValue)return!1;let index=startIndex,hasAnsiCode=!1;while(index<string.length){let codePoint=string.codePointAt(index);if(ESCAPES2.has(codePoint)){let code=parseAnsiCode(string,index);if(code){hasAnsiCode=!0,index=code.endIndex;continue}}if(!hasAnsiCode)return!1;let characterToken=parseCharacterTokenWithRawSegmentation(string,index,graphemeSegments);if(!characterToken)return!0;return areValuesInSameGrapheme(previousVisibleValue,characterToken.token.value)}return!1}function tokenizeAnsi(string,{endCharacter=Number.POSITIVE_INFINITY}={}){let tokens=[],graphemeSegments=GRAPHEME_SEGMENTER2.segment(string),index=0,visibleCount=0,previousVisibleValue,hasAnsiSinceLastVisible=!1;while(index<string.length){let codePoint=string.codePointAt(index);if(ESCAPES2.has(codePoint)){let code=parseAnsiCode(string,index);if(code){tokens.push(code.token),index=code.endIndex,hasAnsiSinceLastVisible=!0;continue}}let characterToken=parseCharacterTokenWithRawSegmentation(string,index,graphemeSegments);if(!characterToken)return tokenizeAnsiWithVisibleSegmentation(string,{endCharacter});if(hasAnsiSinceLastVisible&&previousVisibleValue&&areValuesInSameGrapheme(previousVisibleValue,characterToken.token.value))return tokenizeAnsiWithVisibleSegmentation(string,{endCharacter});if(tokens.push(characterToken.token),index=characterToken.endIndex,visibleCount+=characterToken.token.visibleWidth,hasAnsiSinceLastVisible=!1,previousVisibleValue=characterToken.token.value,visibleCount>=endCharacter){if(hasAnsiSplitContinuationAhead(string,index,previousVisibleValue,graphemeSegments))return tokenizeAnsiWithVisibleSegmentation(string,{endCharacter});index=appendTrailingAnsiTokens(string,index,tokens);break}}return tokens}var ESCAPE_CODE_POINT=27,C1_DCS_CODE_POINT=144,C1_SOS_CODE_POINT=152,C1_CSI_CODE_POINT=155,C1_ST_CODE_POINT=156,C1_OSC_CODE_POINT=157,C1_PM_CODE_POINT=158,C1_APC_CODE_POINT=159,ESCAPES2,ESCAPE="\x1B",ANSI_BELL="\x07",ANSI_CSI2="[",ANSI_OSC2="]",ANSI_DCS="P",ANSI_SOS="X",ANSI_PM="^",ANSI_APC="_",ANSI_SGR_TERMINATOR2="m",ANSI_OSC_TERMINATOR="\\",ANSI_STRING_TERMINATOR,C1_OSC="",C1_STRING_TERMINATOR="œ",ANSI_HYPERLINK_ESC_PREFIX,ANSI_HYPERLINK_C1_PREFIX,ANSI_HYPERLINK_ESC_CLOSE,ANSI_HYPERLINK_C1_CLOSE,CODE_POINT_0,CODE_POINT_9,CODE_POINT_SEMICOLON,CODE_POINT_COLON,CODE_POINT_CSI_PARAMETER_START,CODE_POINT_CSI_PARAMETER_END,CODE_POINT_CSI_INTERMEDIATE_START,CODE_POINT_CSI_INTERMEDIATE_END,CODE_POINT_CSI_FINAL_START,CODE_POINT_CSI_FINAL_END,REGIONAL_INDICATOR_SYMBOL_LETTER_A=127462,REGIONAL_INDICATOR_SYMBOL_LETTER_Z=127487,SGR_RESET_CODE=0,SGR_EXTENDED_FOREGROUND_CODE=38,SGR_DEFAULT_FOREGROUND_CODE=39,SGR_EXTENDED_BACKGROUND_CODE=48,SGR_DEFAULT_BACKGROUND_CODE=49,SGR_COLOR_TYPE_ANSI_256=5,SGR_COLOR_TYPE_TRUECOLOR=2,SGR_ANSI_256_FRAGMENT_LENGTH=3,SGR_TRUECOLOR_FRAGMENT_LENGTH=5,SGR_ANSI_256_LAST_PARAMETER_OFFSET=2,SGR_TRUECOLOR_LAST_PARAMETER_OFFSET=4,VARIATION_SELECTOR_16_CODE_POINT=65039,COMBINING_ENCLOSING_KEYCAP_CODE_POINT=8419,EMOJI_PRESENTATION_GRAPHEME_REGEX,GRAPHEME_SEGMENTER2,endCodeNumbers;var init_tokenize_ansi=__esm(()=>{init_ansi_styles3();init_is_fullwidth_code_point();ESCAPES2=new Set([ESCAPE_CODE_POINT,C1_DCS_CODE_POINT,C1_SOS_CODE_POINT,C1_CSI_CODE_POINT,C1_ST_CODE_POINT,C1_OSC_CODE_POINT,C1_PM_CODE_POINT,C1_APC_CODE_POINT]),ANSI_STRING_TERMINATOR=`${ESCAPE}${ANSI_OSC_TERMINATOR}`,ANSI_HYPERLINK_ESC_PREFIX=`${ESCAPE}${ANSI_OSC2}8;`,ANSI_HYPERLINK_C1_PREFIX=`${C1_OSC}8;`,ANSI_HYPERLINK_ESC_CLOSE=`${ANSI_HYPERLINK_ESC_PREFIX};`,ANSI_HYPERLINK_C1_CLOSE=`${ANSI_HYPERLINK_C1_PREFIX};`,CODE_POINT_0="0".codePointAt(0),CODE_POINT_9="9".codePointAt(0),CODE_POINT_SEMICOLON=";".codePointAt(0),CODE_POINT_COLON=":".codePointAt(0),CODE_POINT_CSI_PARAMETER_START="0".codePointAt(0),CODE_POINT_CSI_PARAMETER_END="?".codePointAt(0),CODE_POINT_CSI_INTERMEDIATE_START=" ".codePointAt(0),CODE_POINT_CSI_INTERMEDIATE_END="/".codePointAt(0),CODE_POINT_CSI_FINAL_START="@".codePointAt(0),CODE_POINT_CSI_FINAL_END="~".codePointAt(0),EMOJI_PRESENTATION_GRAPHEME_REGEX=/\p{Emoji_Presentation}/v,GRAPHEME_SEGMENTER2=new Intl.Segmenter(void 0,{granularity:"grapheme"}),endCodeNumbers=new Set;for(let[,end]of ansi_styles_default3.codes)endCodeNumbers.add(end)});function applySgrFragments(activeStyles,fragments){for(let fragment of fragments)switch(fragment.type){case"reset":{activeStyles.clear();break}case"end":{activeStyles.delete(fragment.endCode);break}case"start":{activeStyles.delete(fragment.endCode),activeStyles.set(fragment.endCode,fragment.code);break}default:break}return activeStyles}function undoAnsiCodes(activeStyles){return[...activeStyles.keys()].toReversed().join("")}function closeHyperlink(hyperlinkToken){return`${hyperlinkToken.closePrefix}${hyperlinkToken.terminator}`}function shouldIncludeSgrAfterEnd(token,activeStyles){let hasStartFragment=!1,hasClosingEffect=!1;for(let fragment of token.fragments){if(fragment.type==="start"){hasStartFragment=!0;continue}if(fragment.type==="reset"&&activeStyles.size>0){hasClosingEffect=!0;continue}if(fragment.type==="end"&&activeStyles.has(fragment.endCode))hasClosingEffect=!0}return hasClosingEffect&&!hasStartFragment}function hasSgrStartFragment(token){return token.fragments.some((fragment)=>fragment.type==="start")}function discardPendingHyperlink(state){if(state.activeHyperlink&&!state.activeHyperlinkHasVisibleText&&state.activeHyperlinkOutputIndex!==void 0){let openCodeLength=state.activeHyperlink.code.length;if(state.returnValue=state.returnValue.slice(0,state.activeHyperlinkOutputIndex)+state.returnValue.slice(state.activeHyperlinkOutputIndex+openCodeLength),state.pendingSgrOutputIndex!==void 0&&state.pendingSgrOutputIndex>state.activeHyperlinkOutputIndex)state.pendingSgrOutputIndex-=openCodeLength}state.activeHyperlink=void 0,state.activeHyperlinkHasVisibleText=!1,state.activeHyperlinkOutputIndex=void 0}function settleActiveHyperlink(state){if(state.activeHyperlinkHasVisibleText)state.returnValue+=closeHyperlink(state.activeHyperlink);else discardPendingHyperlink(state)}function applySgrToken2(state){if(state.isPastEnd&&!shouldIncludeSgrAfterEnd(state.token,state.activeStyles))return;if(state.include&&hasSgrStartFragment(state.token)&&state.pendingSgrOutputIndex===void 0)state.pendingSgrOutputIndex=state.returnValue.length,state.pendingSgrActiveStyles=new Map(state.activeStyles);if(state.activeStyles=applySgrFragments(state.activeStyles,state.token.fragments),state.include)state.returnValue+=state.token.code}function applyHyperlinkToken(state){if(state.isPastEnd&&(state.token.action!=="close"||!state.activeHyperlink))return;if(state.token.action==="open"){if(state.activeHyperlink)settleActiveHyperlink(state);if(state.activeHyperlink=state.token,state.activeHyperlinkHasVisibleText=!1,state.activeHyperlinkOutputIndex=void 0,state.include)state.activeHyperlinkOutputIndex=state.returnValue.length}else if(state.token.action==="close"){if(state.include&&state.activeHyperlink&&!state.activeHyperlinkHasVisibleText){discardPendingHyperlink(state);return}state.activeHyperlink=void 0,state.activeHyperlinkHasVisibleText=!1,state.activeHyperlinkOutputIndex=void 0}if(state.include)state.returnValue+=state.token.code}function applyControlToken(state){if(!state.isPastEnd&&state.include)state.returnValue+=state.token.code}function applyCharacterToken(state){if(!state.include&&state.position>=state.start&&!state.token.isGraphemeContinuation){if(state.include=!0,state.returnValue=[...state.activeStyles.values()].join(""),state.activeHyperlink)state.activeHyperlinkOutputIndex=state.returnValue.length,state.returnValue+=state.activeHyperlink.code}if(state.include){if(state.returnValue+=state.token.value,state.pendingSgrOutputIndex=void 0,state.pendingSgrActiveStyles=void 0,state.activeHyperlink)state.activeHyperlinkHasVisibleText=!0}state.position+=state.token.visibleWidth}function applyToken(state){tokenHandlers[state.token.type]?.(state)}function createHasContinuationAheadMap(tokens){let hasContinuationAhead=Array.from({length:tokens.length},()=>!1),nextCharacterIsContinuation=!1;for(let tokenIndex=tokens.length-1;tokenIndex>=0;tokenIndex--){let token=tokens[tokenIndex];if(hasContinuationAhead[tokenIndex]=nextCharacterIsContinuation,token.type==="character")nextCharacterIsContinuation=Boolean(token.isGraphemeContinuation)}return hasContinuationAhead}function isPastEndBoundary(token,position,end){if(end===void 0)return!1;if(position>=end)return!0;return token.type==="character"&&!token.isGraphemeContinuation&&position+token.visibleWidth>end}function sliceAnsi(string,start,end){let tokens=tokenizeAnsi(string,{endCharacter:end}),hasContinuationAhead=createHasContinuationAheadMap(tokens),state={start,token:void 0,isPastEnd:!1,activeStyles:new Map,activeHyperlink:void 0,activeHyperlinkHasVisibleText:!1,activeHyperlinkOutputIndex:void 0,pendingSgrOutputIndex:void 0,pendingSgrActiveStyles:void 0,position:0,returnValue:"",include:!1};for(let[tokenIndex,token]of tokens.entries()){let isPastEnd=isPastEndBoundary(token,state.position,end);if(isPastEnd&&token.type!=="character"&&hasContinuationAhead[tokenIndex])isPastEnd=!1;if(isPastEnd&&token.type==="character"&&!token.isGraphemeContinuation){if(state.activeHyperlink&&!state.activeHyperlinkHasVisibleText)discardPendingHyperlink(state);if(state.pendingSgrOutputIndex!==void 0)state.returnValue=state.returnValue.slice(0,state.pendingSgrOutputIndex),state.activeStyles=state.pendingSgrActiveStyles,state.pendingSgrOutputIndex=void 0,state.pendingSgrActiveStyles=void 0;break}state.token=token,state.isPastEnd=isPastEnd,applyToken(state)}if(!state.include)return"";if(state.activeHyperlink)settleActiveHyperlink(state);return state.returnValue+=undoAnsiCodes(state.activeStyles),state.returnValue}var tokenHandlers;var init_slice_ansi=__esm(()=>{init_tokenize_ansi();tokenHandlers={sgr:applySgrToken2,hyperlink:applyHyperlinkToken,control:applyControlToken,character:applyCharacterToken}});function getIndexOfNearestSpace(string,wantedIndex,shouldSearchRight){if(string.charAt(wantedIndex)===" ")return wantedIndex;let direction=shouldSearchRight?1:-1;for(let index=0;index<=3;index++){let finalIndex=wantedIndex+index*direction;if(string.charAt(finalIndex)===" ")return finalIndex}return wantedIndex}function validateInput(text,columns,position,truncationCharacter){if(typeof text!=="string")throw TypeError(`Expected \`input\` to be a string, got ${typeof text}`);if(typeof columns!=="number")throw TypeError(`Expected \`columns\` to be a number, got ${typeof columns}`);if(!Number.isFinite(columns))throw TypeError(`Expected \`columns\` to be a finite number, got ${columns}`);if(!validPositions.has(position))throw TypeError(`Expected \`options.position\` to be either \`start\`, \`middle\` or \`end\`, got ${position}`);if(typeof truncationCharacter!=="string")throw TypeError(`Expected \`options.truncationCharacter\` to be a string, got ${typeof truncationCharacter}`)}function cliTruncate(text,columns,options={}){let{position="end",space=!1,preferTruncationOnSpace=!1}=options,{truncationCharacter="…"}=options;if(validateInput(text,columns,position,truncationCharacter),columns<1)return"";let length=stringWidth(text);if(length<=columns)return text;if(columns===1)return truncationCharacter;let ANSI={ESC:27,LEFT_BRACKET:91,LETTER_M:109},isSgrParameter=(code)=>code>=48&&code<=57||code===59;function leadingSgrSpanEndIndex(string){let index=0;while(index+2<string.length&&string.codePointAt(index)===ANSI.ESC&&string.codePointAt(index+1)===ANSI.LEFT_BRACKET){let j=index+2;while(j<string.length&&isSgrParameter(string.codePointAt(j)))j++;if(j<string.length&&string.codePointAt(j)===ANSI.LETTER_M){index=j+1;continue}break}return index}function trailingSgrSpanStartIndex(string){let start=string.length;while(start>1&&string.codePointAt(start-1)===ANSI.LETTER_M){let j=start-2;while(j>=0&&isSgrParameter(string.codePointAt(j)))j--;if(j>=1&&string.codePointAt(j-1)===ANSI.ESC&&string.codePointAt(j)===ANSI.LEFT_BRACKET){start=j-1;continue}break}return start}function appendWithInheritedStyleFromEnd(visible,suffix){let start=trailingSgrSpanStartIndex(visible);if(start===visible.length)return visible+suffix;return visible.slice(0,start)+suffix+visible.slice(start)}function prependWithInheritedStyleFromStart(prefix,visible){let end=leadingSgrSpanEndIndex(visible);if(end===0)return prefix+visible;return visible.slice(0,end)+prefix+visible.slice(end)}if(position==="start"){if(preferTruncationOnSpace){let nearestSpace=getIndexOfNearestSpace(text,length-columns+stringWidth(truncationCharacter),!0),right=sliceAnsi(text,nearestSpace,length).trim();return prependWithInheritedStyleFromStart(truncationCharacter,right)}if(space)truncationCharacter+=" ";let right=sliceAnsi(text,length-columns+stringWidth(truncationCharacter),length);return prependWithInheritedStyleFromStart(truncationCharacter,right)}if(position==="middle"){if(space){if(truncationCharacter=` ${truncationCharacter} `,stringWidth(truncationCharacter)>=columns)truncationCharacter=truncationCharacter.trim()}let truncationWidth=stringWidth(truncationCharacter),half=Math.min(Math.floor(columns/2),Math.max(0,columns-truncationWidth));if(preferTruncationOnSpace){let spaceNearFirstBreakPoint=getIndexOfNearestSpace(text,half),spaceNearSecondBreakPoint=getIndexOfNearestSpace(text,length-(columns-half)+truncationWidth,!0);return sliceAnsi(text,0,spaceNearFirstBreakPoint)+truncationCharacter+sliceAnsi(text,spaceNearSecondBreakPoint,length).trim()}return sliceAnsi(text,0,half)+truncationCharacter+sliceAnsi(text,length-(columns-half)+truncationWidth,length)}if(position==="end"){if(preferTruncationOnSpace){let nearestSpace=getIndexOfNearestSpace(text,columns-stringWidth(truncationCharacter)),left=sliceAnsi(text,0,nearestSpace);return appendWithInheritedStyleFromEnd(left,truncationCharacter)}if(space)truncationCharacter=` ${truncationCharacter}`;let left=sliceAnsi(text,0,columns-stringWidth(truncationCharacter));return appendWithInheritedStyleFromEnd(left,truncationCharacter)}}var validPositions;var init_cli_truncate=__esm(()=>{init_slice_ansi();init_string_width();validPositions=new Set(["start","middle","end"])});function assembleStyles4(){let codes=new Map;for(let[groupName,group]of Object.entries(styles5)){for(let[styleName,style]of Object.entries(group))styles5[styleName]={open:`\x1B[${style[0]}m`,close:`\x1B[${style[1]}m`},group[styleName]=styles5[styleName],codes.set(style[0],style[1]);Object.defineProperty(styles5,groupName,{value:group,enumerable:!1})}return Object.defineProperty(styles5,"codes",{value:codes,enumerable:!1}),styles5.color.close="\x1B[39m",styles5.bgColor.close="\x1B[49m",styles5.color.ansi=wrapAnsi164(),styles5.color.ansi256=wrapAnsi2564(),styles5.color.ansi16m=wrapAnsi16m4(),styles5.bgColor.ansi=wrapAnsi164(10),styles5.bgColor.ansi256=wrapAnsi2564(10),styles5.bgColor.ansi16m=wrapAnsi16m4(10),Object.defineProperties(styles5,{rgbToAnsi256:{value(red,green,blue){if(red===green&&green===blue){if(red<8)return 16;if(red>248)return 231;return Math.round((red-8)/247*24)+232}return 16+36*Math.round(red/255*5)+6*Math.round(green/255*5)+Math.round(blue/255*5)},enumerable:!1},hexToRgb:{value(hex){let matches=/[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));if(!matches)return[0,0,0];let[colorString]=matches;if(colorString.length===3)colorString=[...colorString].map((character)=>character+character).join("");let integer=Number.parseInt(colorString,16);return[integer>>16&255,integer>>8&255,integer&255]},enumerable:!1},hexToAnsi256:{value:(hex)=>styles5.rgbToAnsi256(...styles5.hexToRgb(hex)),enumerable:!1},ansi256ToAnsi:{value(code){if(code<8)return 30+code;if(code<16)return 90+(code-8);let red,green,blue;if(code>=232)red=((code-232)*10+8)/255,green=red,blue=red;else{code-=16;let remainder=code%36;red=Math.floor(code/36)/5,green=Math.floor(remainder/6)/5,blue=remainder%6/5}let value=Math.max(red,green,blue)*2;if(value===0)return 30;let result=30+(Math.round(blue)<<2|Math.round(green)<<1|Math.round(red));if(value===2)result+=60;return result},enumerable:!1},rgbToAnsi:{value:(red,green,blue)=>styles5.ansi256ToAnsi(styles5.rgbToAnsi256(red,green,blue)),enumerable:!1},hexToAnsi:{value:(hex)=>styles5.ansi256ToAnsi(styles5.hexToAnsi256(hex)),enumerable:!1}}),styles5}var wrapAnsi164=(offset=0)=>(code)=>`\x1B[${code+offset}m`,wrapAnsi2564=(offset=0)=>(code)=>`\x1B[${38+offset};5;${code}m`,wrapAnsi16m4=(offset=0)=>(red,green,blue)=>`\x1B[${38+offset};2;${red};${green};${blue}m`,styles5,modifierNames4,foregroundColorNames4,backgroundColorNames4,colorNames4,ansiStyles4,ansi_styles_default4;var init_ansi_styles4=__esm(()=>{styles5={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},modifierNames4=Object.keys(styles5.modifier),foregroundColorNames4=Object.keys(styles5.color),backgroundColorNames4=Object.keys(styles5.bgColor),colorNames4=[...foregroundColorNames4,...backgroundColorNames4];ansiStyles4=assembleStyles4(),ansi_styles_default4=ansiStyles4});var CC_BEL=7,CC_ESC=27,CC_BACKSLASH=92,CC_CSI=91,CC_OSC=93,CC_C1_ST,CC_0=48,CC_9=57,CC_SEMI=59,CC_M=109,ESCAPES3,linkCodePrefix="\x1B]8;",linkCodePrefixCharCodes,linkEndCode="\x1B]8;;\x07",linkEndCodeST="\x1B]8;;\x1B\\",linkEndCodeC1ST;var init_consts=__esm(()=>{CC_C1_ST="œ".charCodeAt(0),ESCAPES3=new Set([27,155]),linkCodePrefixCharCodes="\x1B]8;".split("").map((char)=>char.charCodeAt(0)),linkEndCodeC1ST=`\x1B]8;;${"œ"}`});function getEndCode(code){if(endCodesSet.has(code))return code;if(endCodesMap.has(code))return endCodesMap.get(code);if(code.startsWith(linkCodePrefix)){if(code.endsWith("\x1B\\"))return linkEndCodeST;if(code.endsWith("œ"))return linkEndCodeC1ST;return linkEndCode}if(code=code.slice(2),code.startsWith("38"))return ansi_styles_default4.color.close;else if(code.startsWith("48"))return ansi_styles_default4.bgColor.close;let ret=ansi_styles_default4.codes.get(parseInt(code,10));if(ret)return ansi_styles_default4.color.ansi(ret);else return ansi_styles_default4.reset.open}function ansiCodesToString(codes){return[...new Set(codes.map((code)=>code.code))].join("")}function isIntensityCode(code){return code.code===ansi_styles_default4.bold.open||code.code===ansi_styles_default4.dim.open}var endCodesSet,endCodesMap;var init_ansiCodes=__esm(()=>{init_ansi_styles4();init_consts();endCodesSet=new Set,endCodesMap=new Map;for(let[start,end]of ansi_styles_default4.codes)endCodesSet.add(ansi_styles_default4.color.ansi(end)),endCodesMap.set(ansi_styles_default4.color.ansi(start),ansi_styles_default4.color.ansi(end));endCodesSet.add(linkEndCode);endCodesSet.add(linkEndCodeST);endCodesSet.add(linkEndCodeC1ST)});function reduceAnsiCodes(codes){return reduceAnsiCodesIncremental([],codes)}function reduceAnsiCodesIncremental(codes,newCodes){let ret=[...codes];for(let code of newCodes)if(code.code===ansi_styles_default4.reset.open)ret=[];else if(endCodesSet.has(code.code))ret=ret.filter((retCode)=>retCode.endCode!==code.code);else if(isIntensityCode(code)){if(!ret.find((retCode)=>retCode.code===code.code&&retCode.endCode===code.endCode))ret.push(code)}else ret=ret.filter((retCode)=>retCode.endCode!==code.endCode),ret.push(code);return ret}var init_reduce=__esm(()=>{init_ansi_styles4();init_ansiCodes()});function undoAnsiCodes2(codes){return reduceAnsiCodes(codes).reverse().map((code)=>({...code,code:code.endCode}))}var init_undo=__esm(()=>{init_reduce()});function diffAnsiCodes(from,to){let endCodesInTo=new Set(to.map((code)=>code.endCode)),startCodesInTo=new Set(to.map((code)=>code.code)),startCodesInFrom=new Set(from.map((code)=>code.code));return[...undoAnsiCodes2(from.filter((code)=>{if(isIntensityCode(code))return!startCodesInTo.has(code.code);return!endCodesInTo.has(code.endCode)})),...to.filter((code)=>!startCodesInFrom.has(code.code))]}var init_diff2=__esm(()=>{init_ansiCodes();init_undo()});function styledCharsFromTokens(tokens){let codes=[],ret=[];for(let token of tokens)if(token.type==="ansi")codes=reduceAnsiCodesIncremental(codes,[token]);else if(token.type==="char")ret.push({...token,styles:[...codes]});return ret}function styledCharsToString(chars){let ret="";for(let i=0;i<chars.length;i++){let char=chars[i];if(i===0)ret+=ansiCodesToString(char.styles);else ret+=ansiCodesToString(diffAnsiCodes(chars[i-1].styles,char.styles));if(ret+=char.value,i===chars.length-1)ret+=ansiCodesToString(diffAnsiCodes(char.styles,[]))}return ret}var init_styledChars=__esm(()=>{init_ansiCodes();init_diff2();init_reduce()});function isFullwidthGrapheme(grapheme,baseCodePoint){if(isFullwidthCodePoint(baseCodePoint))return!0;if(grapheme.includes("️"))return!0;if(baseCodePoint>=127462&&baseCodePoint<=127487)return!0;return!1}function parseLinkCode(string,offset){string=string.slice(offset);for(let index=1;index<linkCodePrefixCharCodes.length;index++)if(string.charCodeAt(index)!==linkCodePrefixCharCodes[index])return;let paramsEndIndex=string.indexOf(";",linkCodePrefix.length);if(paramsEndIndex===-1)return;let endIndex=findOSCTerminatorIndex(string,paramsEndIndex+1);if(endIndex===-1)return;return string.slice(0,endIndex+1)}function parseOSCSequence(string,offset){string=string.slice(offset);let endIndex=findOSCTerminatorIndex(string,2);if(endIndex===-1)return;return string.slice(0,endIndex+1)}function findOSCTerminatorIndex(string,startIndex){for(let i=startIndex;i<string.length;i++){let ch=string.charCodeAt(i);if(ch===CC_BEL)return i;if(ch===CC_C1_ST)return i;if(ch===CC_ESC&&i+1<string.length&&string.charCodeAt(i+1)===CC_BACKSLASH)return i+1}return-1}function findSGRSequenceEndIndex(str){for(let index=2;index<str.length;index++){let charCode=str.charCodeAt(index);if(charCode===CC_M)return index;if(charCode===CC_SEMI)continue;if(charCode>=CC_0&&charCode<=CC_9)continue;break}return-1}function parseSGRSequence(string,offset){string=string.slice(offset);let endIndex=findSGRSequenceEndIndex(string);if(endIndex===-1)return;return string.slice(0,endIndex+1)}function splitCompoundSGRSequences(code){if(!code.includes(";"))return[code];let codeParts=code.slice(2,-1).split(";"),ret=[];for(let i=0;i<codeParts.length;i++){let rawCode=codeParts[i];if(rawCode==="38"||rawCode==="48"){if(i+2<codeParts.length&&codeParts[i+1]==="5"){ret.push(codeParts.slice(i,i+3).join(";")),i+=2;continue}else if(i+4<codeParts.length&&codeParts[i+1]==="2"){ret.push(codeParts.slice(i,i+5).join(";")),i+=4;continue}}ret.push(rawCode)}return ret.map((part)=>`\x1B[${part}m`)}function tokenize2(str,endChar=Number.POSITIVE_INFINITY){let ret=[],visible=0,codeEndIndex=0;for(let{segment,index}of segmenter3.segment(str)){if(index<codeEndIndex)continue;let codePoint=segment.codePointAt(0);if(ESCAPES3.has(codePoint)){let code,nextCodePoint=str.codePointAt(index+1);if(nextCodePoint===CC_OSC){if(code=parseLinkCode(str,index),code)ret.push({type:"ansi",code,endCode:getEndCode(code)});else if(code=parseOSCSequence(str,index),code)ret.push({type:"control",code})}else if(nextCodePoint===CC_CSI){if(code=parseSGRSequence(str,index),code){let codes=splitCompoundSGRSequences(code);for(let individualCode of codes)ret.push({type:"ansi",code:individualCode,endCode:getEndCode(individualCode)})}}if(code){codeEndIndex=index+code.length;continue}}let fullWidth=isFullwidthGrapheme(segment,codePoint);if(ret.push({type:"char",value:segment,fullWidth}),visible+=fullWidth?2:1,visible>=endChar)break}return ret}var segmenter3;var init_tokenize=__esm(()=>{init_is_fullwidth_code_point();init_ansiCodes();init_consts();segmenter3=new Intl.Segmenter(void 0,{granularity:"grapheme"})});var init_build3=__esm(()=>{init_ansiCodes();init_diff2();init_reduce();init_undo();init_styledChars();init_tokenize()});var wrapTextCache,wrapText=(text,maxWidth,wrapType)=>{if(maxWidth<=0&&(wrapType==="wrap"||wrapType==="hard"))return text;if(maxWidth>0&&maxWidth<1)maxWidth=1;let cacheKey=`${maxWidth}\x00${String(wrapType)}\x00${text}`,cachedText=wrapTextCache.get(cacheKey);if(cachedText!==void 0)return cachedText;let wrappedText=text;if(wrapType==="wrap")wrappedText=wrapAnsi(text,maxWidth,{trim:!1,hard:!0});else if(wrapType==="hard")wrappedText=wrapAnsi(text,maxWidth,{trim:!1,hard:!0,wordWrap:!1});else if(wrapType.startsWith("truncate")){let position="end";if(wrapType==="truncate-middle")position="middle";else if(wrapType==="truncate-start")position="start";let lines=[text];if(text.includes(`
1291
- `)){let styledLines=[[]];for(let character of styledCharsFromTokens(tokenize2(text)))if(character.value===`
1292
- `)styledLines.push([]);else styledLines.at(-1).push(character);lines=styledLines.map((line)=>styledCharsToString(line))}wrappedText=lines.map((line)=>cliTruncate(line,maxWidth,{position})).join(`
1293
- `)}return wrapTextCache.set(cacheKey,wrappedText),wrappedText},wrap_text_default;var init_wrap_text=__esm(()=>{init_wrap_ansi();init_cli_truncate();init_build3();init_quick_lru();wrapTextCache=new QuickLRU({maxSize:4096}),wrap_text_default=wrapText});var isCsiParameterCharacter2=(character)=>{let codePoint=character.codePointAt(0);return codePoint!==void 0&&codePoint>=48&&codePoint<=63},isCsiIntermediateCharacter2=(character)=>{let codePoint=character.codePointAt(0);return codePoint!==void 0&&codePoint>=32&&codePoint<=47},isCsiFinalCharacter2=(character)=>{let codePoint=character.codePointAt(0);return codePoint!==void 0&&codePoint>=64&&codePoint<=126},isEscapeIntermediateCharacter=(character)=>{let codePoint=character.codePointAt(0);return codePoint!==void 0&&codePoint>=32&&codePoint<=47},isEscapeFinalCharacter=(character)=>{let codePoint=character.codePointAt(0);return codePoint!==void 0&&codePoint>=48&&codePoint<=126},isC1ControlCharacter=(character)=>{let codePoint=character.codePointAt(0);return codePoint!==void 0&&codePoint>=128&&codePoint<=159},readCsiSequence=(text,fromIndex)=>{let index=fromIndex;while(index<text.length){let character=text[index];if(!isCsiParameterCharacter2(character))break;index++}let parameterString=text.slice(fromIndex,index),intermediateStartIndex=index;while(index<text.length){let character=text[index];if(!isCsiIntermediateCharacter2(character))break;index++}let intermediateString=text.slice(intermediateStartIndex,index),finalCharacter=text[index];if(finalCharacter===void 0||!isCsiFinalCharacter2(finalCharacter))return;return{endIndex:index+1,parameterString,intermediateString,finalCharacter}},findControlStringTerminatorIndex=(text,fromIndex,isBellTerminatorAllowed)=>{for(let index=fromIndex;index<text.length;index++){let character=text[index];if(isBellTerminatorAllowed&&character==="\x07")return index+1;if(character==="œ")return index+1;if(character!=="\x1B")continue;let followingCharacter=text[index+1];if(followingCharacter==="\x1B"){index++;continue}if(followingCharacter==="\\")return index+2}return},readEscapeSequence=(text,fromIndex)=>{let index=fromIndex;while(index<text.length){let character=text[index];if(!isEscapeIntermediateCharacter(character))break;index++}let intermediateString=text.slice(fromIndex,index),finalCharacter=text[index];if(finalCharacter===void 0||!isEscapeFinalCharacter(finalCharacter))return;return{endIndex:index+1,intermediateString,finalCharacter}},getControlStringFromEscapeIntroducer=(character)=>{switch(character){case"]":return{type:"osc",allowBellTerminator:!0};case"P":return{type:"dcs",allowBellTerminator:!1};case"^":return{type:"pm",allowBellTerminator:!1};case"_":return{type:"apc",allowBellTerminator:!1};case"X":return{type:"sos",allowBellTerminator:!1};default:return}},getControlStringFromC1Introducer=(character)=>{switch(character){case"":return{type:"osc",allowBellTerminator:!0};case"":return{type:"dcs",allowBellTerminator:!1};case"ž":return{type:"pm",allowBellTerminator:!1};case"Ÿ":return{type:"apc",allowBellTerminator:!1};case"˜":return{type:"sos",allowBellTerminator:!1};default:return}},hasAnsiControlCharacters=(text)=>{if(text.includes("\x1B"))return!0;for(let character of text)if(isC1ControlCharacter(character))return!0;return!1},malformedFromIndex=(tokens,text,textStartIndex,fromIndex)=>{if(fromIndex>textStartIndex)tokens.push({type:"text",value:text.slice(textStartIndex,fromIndex)});return tokens.push({type:"invalid",value:text.slice(fromIndex)}),tokens},tokenizeAnsi2=(text)=>{if(!hasAnsiControlCharacters(text))return[{type:"text",value:text}];let tokens=[],textStartIndex=0;for(let index=0;index<text.length;){let character=text[index];if(character===void 0)break;if(character==="\x1B"){let followingCharacter=text[index+1];if(followingCharacter===void 0)return malformedFromIndex(tokens,text,textStartIndex,index);if(followingCharacter==="["){let csiSequence=readCsiSequence(text,index+2);if(csiSequence===void 0)return malformedFromIndex(tokens,text,textStartIndex,index);if(index>textStartIndex)tokens.push({type:"text",value:text.slice(textStartIndex,index)});tokens.push({type:"csi",value:text.slice(index,csiSequence.endIndex),parameterString:csiSequence.parameterString,intermediateString:csiSequence.intermediateString,finalCharacter:csiSequence.finalCharacter}),index=csiSequence.endIndex,textStartIndex=index;continue}let escapeControlString=getControlStringFromEscapeIntroducer(followingCharacter);if(escapeControlString!==void 0){let controlStringTerminatorIndex=findControlStringTerminatorIndex(text,index+2,escapeControlString.allowBellTerminator);if(controlStringTerminatorIndex===void 0)return malformedFromIndex(tokens,text,textStartIndex,index);if(index>textStartIndex)tokens.push({type:"text",value:text.slice(textStartIndex,index)});tokens.push({type:escapeControlString.type,value:text.slice(index,controlStringTerminatorIndex)}),index=controlStringTerminatorIndex,textStartIndex=index;continue}let escapeSequence=readEscapeSequence(text,index+1);if(escapeSequence===void 0){if(isEscapeIntermediateCharacter(followingCharacter))return malformedFromIndex(tokens,text,textStartIndex,index);if(index>textStartIndex)tokens.push({type:"text",value:text.slice(textStartIndex,index)});index++,textStartIndex=index;continue}if(index>textStartIndex)tokens.push({type:"text",value:text.slice(textStartIndex,index)});tokens.push({type:"esc",value:text.slice(index,escapeSequence.endIndex),intermediateString:escapeSequence.intermediateString,finalCharacter:escapeSequence.finalCharacter}),index=escapeSequence.endIndex,textStartIndex=index;continue}if(character==="›"){let csiSequence=readCsiSequence(text,index+1);if(csiSequence===void 0)return malformedFromIndex(tokens,text,textStartIndex,index);if(index>textStartIndex)tokens.push({type:"text",value:text.slice(textStartIndex,index)});tokens.push({type:"csi",value:text.slice(index,csiSequence.endIndex),parameterString:csiSequence.parameterString,intermediateString:csiSequence.intermediateString,finalCharacter:csiSequence.finalCharacter}),index=csiSequence.endIndex,textStartIndex=index;continue}let c1ControlString=getControlStringFromC1Introducer(character);if(c1ControlString!==void 0){let controlStringTerminatorIndex=findControlStringTerminatorIndex(text,index+1,c1ControlString.allowBellTerminator);if(controlStringTerminatorIndex===void 0)return malformedFromIndex(tokens,text,textStartIndex,index);if(index>textStartIndex)tokens.push({type:"text",value:text.slice(textStartIndex,index)});tokens.push({type:c1ControlString.type,value:text.slice(index,controlStringTerminatorIndex)}),index=controlStringTerminatorIndex,textStartIndex=index;continue}if(character==="œ"){if(index>textStartIndex)tokens.push({type:"text",value:text.slice(textStartIndex,index)});tokens.push({type:"st",value:character}),index++,textStartIndex=index;continue}if(isC1ControlCharacter(character)){if(index>textStartIndex)tokens.push({type:"text",value:text.slice(textStartIndex,index)});tokens.push({type:"c1",value:character}),index++,textStartIndex=index;continue}index++}if(textStartIndex<text.length)tokens.push({type:"text",value:text.slice(textStartIndex)});return tokens};var sgrParametersRegex,controlCharactersRegex,leadingMarksRegex,normalizeParameter=(parameter)=>{let parts=parameter.split(":");if(parts.length===1)return parameter;if(parts[0]==="4")return parts[1]==="0"||parts[1]===""?"24":"4";if(parts[0]!=="38"&&parts[0]!=="48")return;if(parts[1]==="5"&&parts.length===3)return parts.join(";");if(parts[1]==="2"){if(parts.length===6&&(parts[2]===""||parts[2]==="0"))parts.splice(2,1);if(parts.length===5)return parts.join(";")}return},sanitizeAnsi=(text)=>{if(!hasAnsiControlCharacters(text))return text.replaceAll(controlCharactersRegex,"");let output="",pendingStyles="";for(let token of tokenizeAnsi2(text)){if(token.type==="text"){let value=token.value.replaceAll(controlCharactersRegex,""),marks=leadingMarksRegex.exec(value)?.[0]??"";if(output+=marks,value.length>marks.length)output+=pendingStyles+value.slice(marks.length),pendingStyles="";continue}if(token.type==="osc"){output+=pendingStyles+token.value,pendingStyles="";continue}if(token.type!=="csi"||token.finalCharacter!=="m"||token.intermediateString!==""||!sgrParametersRegex.test(token.parameterString))continue;let parameters=token.parameterString.split(";").map((parameter)=>normalizeParameter(parameter)).filter((parameter)=>parameter!==void 0);if(parameters.length>0)pendingStyles+=`\x1B[${parameters.join(";")}m`}return output+pendingStyles},sanitize_ansi_default;var init_sanitize_ansi=__esm(()=>{sgrParametersRegex=/^[\d:;]*$/,controlCharactersRegex=/(?![\t\n])\p{Control}/gu,leadingMarksRegex=/^\p{Mark}+/u,sanitize_ansi_default=sanitizeAnsi});var squashTextNodes=(node)=>{let text="";for(let childNode of node.childNodes){let nodeText="";if(childNode.nodeName==="#text")nodeText=childNode.nodeValue;else{if(childNode.isHidden)continue;if(childNode.nodeName==="ink-text"||childNode.nodeName==="ink-virtual-text")nodeText=squashTextNodes(childNode);if(nodeText.length>0&&typeof childNode.internal_transform==="function"){let transform=childNode.internal_transform;nodeText=nodeText.split(`
1294
- `).map((line,lineIndex)=>transform(line,lineIndex)).join(`
1295
- `)}}text+=nodeText}if(text=sanitize_ansi_default(text.replaceAll(`\r
1296
- `,`
1297
- `)),text=text.replaceAll("›","\x1B[").replaceAll("","\x1B]").replaceAll("œ","\x1B\\"),node.nodeName==="ink-text"&&text.includes("\t"))text=wrapAnsi(text,1/0,{trim:!1});return text},squash_text_nodes_default;var init_squash_text_nodes=__esm(()=>{init_wrap_ansi();init_sanitize_ansi();squash_text_nodes_default=squashTextNodes});var createNode=(nodeName)=>{let node={nodeName,style:{},attributes:{},childNodes:[],parentNode:void 0,yogaNode:nodeName==="ink-virtual-text"?void 0:src_default.Node.create(),internal_accessibility:{}};if(nodeName==="ink-text")node.yogaNode?.setMeasureFunc(measureTextNode.bind(null,node));return node},appendChildNode=(node,childNode)=>{if(childNode.parentNode)removeChildNode(childNode.parentNode,childNode);if(childNode.parentNode=node,node.childNodes.push(childNode),childNode.yogaNode)node.yogaNode?.insertChild(childNode.yogaNode,node.yogaNode.getChildCount());if(node.nodeName==="ink-text"||node.nodeName==="ink-virtual-text")markNodeAsDirty(node)},insertBeforeNode=(node,newChildNode,beforeChildNode)=>{if(newChildNode.parentNode)removeChildNode(newChildNode.parentNode,newChildNode);newChildNode.parentNode=node;let index=node.childNodes.indexOf(beforeChildNode);if(index>=0){if(node.childNodes.splice(index,0,newChildNode),newChildNode.yogaNode)node.yogaNode?.insertChild(newChildNode.yogaNode,index)}else if(node.childNodes.push(newChildNode),newChildNode.yogaNode)node.yogaNode?.insertChild(newChildNode.yogaNode,node.yogaNode.getChildCount());if(node.nodeName==="ink-text"||node.nodeName==="ink-virtual-text")markNodeAsDirty(node)},removeChildNode=(node,removedNode)=>{if(removedNode.yogaNode)removedNode.parentNode?.yogaNode?.removeChild(removedNode.yogaNode);removedNode.parentNode=void 0;let index=node.childNodes.indexOf(removedNode);if(index>=0)node.childNodes.splice(index,1);if(node.nodeName==="ink-text"||node.nodeName==="ink-virtual-text")markNodeAsDirty(node)},nullifyYogaNodes=(node)=>{if(node.yogaNode=void 0,node.nodeName!=="#text")for(let childNode of node.childNodes)nullifyYogaNodes(childNode)},freeYogaSubtree=(removedNode)=>{removedNode.yogaNode?.unsetMeasureFunc(),removedNode.yogaNode?.freeRecursive(),nullifyYogaNodes(removedNode)},setAttribute=(node,key,value)=>{if(key==="internal_accessibility"){node.internal_accessibility=value;return}node.attributes[key]=value},setTransform=(node,transform)=>{if(node.internal_transform=transform,node.nodeName==="ink-virtual-text")markNodeAsDirty(node)},setStyle=(node,style)=>{if(node.nodeName==="ink-text"&&node.style.textWrap!==style?.textWrap)node.yogaNode?.markDirty();node.style=style??{}},createTextNode=(text)=>{let node={nodeName:"#text",nodeValue:text,yogaNode:void 0,parentNode:void 0,style:{}};return setTextNodeValue(node,text),node},measureTextNode=function(node,width,widthMode){let text=node.nodeName==="#text"?node.nodeValue:squash_text_nodes_default(node),dimensions=measure_text_default(text);if(widthMode===src_default.MEASURE_MODE_UNDEFINED||dimensions.width<=width)return dimensions;let textWrap=node.style?.textWrap??"wrap",wrappedText=wrap_text_default(text,width,textWrap),wrappedDimensions=measure_text_default(wrappedText);return textWrap.startsWith("truncate")?{width,height:wrappedDimensions.height}:wrappedDimensions},findClosestYogaNode=(node)=>node?.parentNode?node.yogaNode??findClosestYogaNode(node.parentNode):void 0,markNodeAsDirty=(node)=>{findClosestYogaNode(node)?.markDirty()},setNodeHidden=(node,isHidden)=>{if(node.isHidden=isHidden,node.yogaNode?.setDisplay(isHidden||node.style.display==="none"?src_default.DISPLAY_NONE:src_default.DISPLAY_FLEX),node.nodeName==="ink-virtual-text")markNodeAsDirty(node)},setTextNodeValue=(node,text)=>{if(typeof text!=="string")text=String(text);node.nodeValue=text,markNodeAsDirty(node)},addLayoutListener=(rootNode,listener)=>{if(rootNode.nodeName!=="ink-root")return()=>{};return rootNode.internal_layoutListeners??=new Set,rootNode.internal_layoutListeners.add(listener),()=>{rootNode.internal_layoutListeners?.delete(listener)}},emitLayoutListeners=(rootNode)=>{if(rootNode.nodeName!=="ink-root"||!rootNode.internal_layoutListeners)return;for(let listener of rootNode.internal_layoutListeners)listener()};var init_dom=__esm(async()=>{init_measure_text();init_wrap_text();init_squash_text_nodes();await init_src()});var positionEdges,applyPositionStyles=(node,style)=>{if("position"in style){let positionType=src_default.POSITION_TYPE_RELATIVE;if(style.position==="absolute")positionType=src_default.POSITION_TYPE_ABSOLUTE;else if(style.position==="static")positionType=src_default.POSITION_TYPE_STATIC;node.setPositionType(positionType)}for(let[property,edge]of positionEdges){if(!Object.hasOwn(style,property))continue;let value=style[property];if(typeof value==="string"){node.setPositionPercent(edge,Number.parseFloat(value));continue}node.setPosition(edge,value)}},applyMarginStyles=(node,style)=>{if("margin"in style)node.setMargin(src_default.EDGE_ALL,style.margin??0);if("marginX"in style)node.setMargin(src_default.EDGE_HORIZONTAL,style.marginX);if("marginY"in style)node.setMargin(src_default.EDGE_VERTICAL,style.marginY);if("marginLeft"in style)node.setMargin(src_default.EDGE_START,style.marginLeft);if("marginRight"in style)node.setMargin(src_default.EDGE_END,style.marginRight);if("marginTop"in style)node.setMargin(src_default.EDGE_TOP,style.marginTop);if("marginBottom"in style)node.setMargin(src_default.EDGE_BOTTOM,style.marginBottom)},applyPaddingStyles=(node,style)=>{if("padding"in style)node.setPadding(src_default.EDGE_ALL,style.padding??0);if("paddingX"in style)node.setPadding(src_default.EDGE_HORIZONTAL,style.paddingX);if("paddingY"in style)node.setPadding(src_default.EDGE_VERTICAL,style.paddingY);if("paddingLeft"in style)node.setPadding(src_default.EDGE_LEFT,style.paddingLeft);if("paddingRight"in style)node.setPadding(src_default.EDGE_RIGHT,style.paddingRight);if("paddingTop"in style)node.setPadding(src_default.EDGE_TOP,style.paddingTop);if("paddingBottom"in style)node.setPadding(src_default.EDGE_BOTTOM,style.paddingBottom)},flexWrapValues,flexDirectionValues,alignItemsValues,alignSelfValues,alignContentValues,justifyContentValues,applyFlexStyles=(node,style)=>{if("flexGrow"in style)node.setFlexGrow(style.flexGrow??0);if("flexShrink"in style)node.setFlexShrink(typeof style.flexShrink==="number"?style.flexShrink:1);if("flexWrap"in style){let flexWrap=flexWrapValues.get(style.flexWrap);if(flexWrap!==void 0)node.setFlexWrap(flexWrap)}if("flexDirection"in style){let flexDirection=flexDirectionValues.get(style.flexDirection);if(flexDirection!==void 0)node.setFlexDirection(flexDirection)}if("flexBasis"in style)if(typeof style.flexBasis==="number")node.setFlexBasis(style.flexBasis);else if(typeof style.flexBasis==="string")node.setFlexBasisPercent(Number.parseFloat(style.flexBasis));else node.setFlexBasisAuto();if("alignItems"in style){let alignItems=style.alignItems?alignItemsValues.get(style.alignItems):src_default.ALIGN_STRETCH;if(alignItems!==void 0)node.setAlignItems(alignItems)}if("alignSelf"in style){let alignSelf=style.alignSelf?alignSelfValues.get(style.alignSelf):src_default.ALIGN_AUTO;if(alignSelf!==void 0)node.setAlignSelf(alignSelf)}if("alignContent"in style){let alignContent=style.alignContent?alignContentValues.get(style.alignContent):src_default.ALIGN_FLEX_START;if(alignContent!==void 0)node.setAlignContent(alignContent)}if(!("justifyContent"in style))return;let justifyContent=style.justifyContent?justifyContentValues.get(style.justifyContent):src_default.JUSTIFY_FLEX_START;if(justifyContent!==void 0)node.setJustifyContent(justifyContent)},applyDimensionStyles=(node,style)=>{if("width"in style)if(typeof style.width==="number")node.setWidth(style.width);else if(typeof style.width==="string")node.setWidthPercent(Number.parseFloat(style.width));else node.setWidthAuto();if("height"in style)if(typeof style.height==="number")node.setHeight(style.height);else if(typeof style.height==="string")node.setHeightPercent(Number.parseFloat(style.height));else node.setHeightAuto();if("minWidth"in style)node.setMinWidth(style.minWidth??0);if("minHeight"in style)if(typeof style.minHeight==="string")node.setMinHeightPercent(Number.parseFloat(style.minHeight));else node.setMinHeight(style.minHeight??0);if("maxWidth"in style)node.setMaxWidth(style.maxWidth);if("maxHeight"in style)if(typeof style.maxHeight==="string")node.setMaxHeightPercent(Number.parseFloat(style.maxHeight));else node.setMaxHeight(style.maxHeight);if("aspectRatio"in style)node.setAspectRatio(style.aspectRatio)},applyDisplayStyles=(node,style)=>{if("display"in style)node.setDisplay(style.display==="none"?src_default.DISPLAY_NONE:src_default.DISPLAY_FLEX)},applyBorderStyles=(node,style,currentStyle)=>{if(!(("borderStyle"in style)||("borderTop"in style)||("borderBottom"in style)||("borderLeft"in style)||("borderRight"in style)))return;let borderWidth=Boolean(currentStyle.borderStyle)?1:0;node.setBorder(src_default.EDGE_TOP,currentStyle.borderTop===!1?0:borderWidth),node.setBorder(src_default.EDGE_BOTTOM,currentStyle.borderBottom===!1?0:borderWidth),node.setBorder(src_default.EDGE_LEFT,currentStyle.borderLeft===!1?0:borderWidth),node.setBorder(src_default.EDGE_RIGHT,currentStyle.borderRight===!1?0:borderWidth)},applyGapStyles=(node,style)=>{if("gap"in style)node.setGap(src_default.GUTTER_ALL,style.gap??0);if("columnGap"in style)node.setGap(src_default.GUTTER_COLUMN,style.columnGap);if("rowGap"in style)node.setGap(src_default.GUTTER_ROW,style.rowGap)},styles6=(node,style={},currentStyle=style)=>{applyPositionStyles(node,style),applyMarginStyles(node,style),applyPaddingStyles(node,style),applyFlexStyles(node,style),applyDimensionStyles(node,style),applyDisplayStyles(node,style),applyBorderStyles(node,style,currentStyle),applyGapStyles(node,style)},styles_default;var init_styles=__esm(async()=>{await init_src();positionEdges=[["top",src_default.EDGE_TOP],["right",src_default.EDGE_RIGHT],["bottom",src_default.EDGE_BOTTOM],["left",src_default.EDGE_LEFT]],flexWrapValues=new Map([["nowrap",src_default.WRAP_NO_WRAP],["wrap",src_default.WRAP_WRAP],["wrap-reverse",src_default.WRAP_WRAP_REVERSE]]),flexDirectionValues=new Map([["row",src_default.FLEX_DIRECTION_ROW],["row-reverse",src_default.FLEX_DIRECTION_ROW_REVERSE],["column",src_default.FLEX_DIRECTION_COLUMN],["column-reverse",src_default.FLEX_DIRECTION_COLUMN_REVERSE]]),alignItemsValues=new Map([["stretch",src_default.ALIGN_STRETCH],["flex-start",src_default.ALIGN_FLEX_START],["center",src_default.ALIGN_CENTER],["flex-end",src_default.ALIGN_FLEX_END],["baseline",src_default.ALIGN_BASELINE]]),alignSelfValues=new Map([["auto",src_default.ALIGN_AUTO],["flex-start",src_default.ALIGN_FLEX_START],["center",src_default.ALIGN_CENTER],["flex-end",src_default.ALIGN_FLEX_END],["stretch",src_default.ALIGN_STRETCH],["baseline",src_default.ALIGN_BASELINE]]),alignContentValues=new Map([["flex-start",src_default.ALIGN_FLEX_START],["center",src_default.ALIGN_CENTER],["flex-end",src_default.ALIGN_FLEX_END],["space-between",src_default.ALIGN_SPACE_BETWEEN],["space-around",src_default.ALIGN_SPACE_AROUND],["space-evenly",src_default.ALIGN_SPACE_EVENLY],["stretch",src_default.ALIGN_STRETCH]]),justifyContentValues=new Map([["flex-start",src_default.JUSTIFY_FLEX_START],["center",src_default.JUSTIFY_CENTER],["flex-end",src_default.JUSTIFY_FLEX_END],["space-between",src_default.JUSTIFY_SPACE_BETWEEN],["space-around",src_default.JUSTIFY_SPACE_AROUND],["space-evenly",src_default.JUSTIFY_SPACE_EVENLY]]),styles_default=styles6});var customGlobal;var init_devtools_window_polyfill=__esm(()=>{customGlobal=globalThis;customGlobal.window||=globalThis;customGlobal.self||=globalThis;customGlobal.window.__REACT_DEVTOOLS_COMPONENT_FILTERS__=[{type:1,value:7,isEnabled:!0},{type:2,value:"InternalApp",isEnabled:!0,isValid:!0},{type:2,value:"InternalAppContext",isEnabled:!0,isValid:!0},{type:2,value:"InternalStdoutContext",isEnabled:!0,isValid:!0},{type:2,value:"InternalStderrContext",isEnabled:!0,isValid:!0},{type:2,value:"InternalStdinContext",isEnabled:!0,isValid:!0},{type:2,value:"InternalFocusContext",isEnabled:!0,isValid:!0}]});var devtools,stub_react_devtools_core_default,connectToDevTools;var init_stub_react_devtools_core=__esm(()=>{devtools={connectToDevTools(){}},stub_react_devtools_core_default=devtools,connectToDevTools=devtools.connectToDevTools});var isDevToolsReachable=async(url="ws://localhost:8097",timeoutMs=2000)=>new Promise((resolve)=>{let socket=new WebSocket(url),timeout=setTimeout(()=>{resolve(!1),socket.close()},timeoutMs);timeout.unref(),socket.addEventListener("open",()=>{clearTimeout(timeout),socket.close(),resolve(!0)}),socket.addEventListener("error",()=>{clearTimeout(timeout),resolve(!1)})}),is_devtools_reachable_default;var init_is_devtools_reachable=__esm(()=>{is_devtools_reachable_default=isDevToolsReachable});var init_devtools=__esm(async()=>{init_devtools_window_polyfill();init_stub_react_devtools_core();init_is_devtools_reachable();if(await is_devtools_reachable_default())stub_react_devtools_core_default.initialize(),stub_react_devtools_core_default.connectToDevTools();else console.warn(`DEV is set to true, but the React DevTools server is not running. Start it with:
1298
-
1299
- $ npx react-devtools
1300
- `)});import process17 from"node:process";async function loadPackageJson(){let fs=await import("node:fs"),content=fs.readFileSync(new URL("../package.json",import.meta.url),"utf8"),parsedContent=JSON.parse(content);return{name:parsedContent?.name,version:parsedContent?.version}}var import_react_reconciler,diff2=(before,after)=>{if(before===after)return;if(!before)return after;let changed={},hasChanges=!1;for(let key of Object.keys(before)){if(!(after?!Object.hasOwn(after,key):!0))continue;changed[key]=void 0,hasChanges=!0}if(after)for(let[key,value]of Object.entries(after)){if(value===before[key])continue;changed[key]=value,hasChanges=!0}return hasChanges?changed:void 0},findRootNode=(node)=>{let current=node;while(current){if(current.nodeName==="ink-root")return current;current=current.parentNode}return},clearStaticNodeIfContained=(rootNode,removedNode)=>{if(!rootNode?.staticNode)return;let current=rootNode.staticNode;while(current){if(current===removedNode){rootNode.staticNode=void 0;return}current=current.parentNode}},findStaticNode=(node)=>{if(node.internal_static)return node;for(let child of node.childNodes){if(child.nodeName==="#text")continue;let staticNode=findStaticNode(child);if(staticNode)return staticNode}return},currentUpdatePriority,packageInfo,hostConfig,reconciler_default;var init_reconciler=__esm(async()=>{init_react_reconciler_constants_production();init_react_production();await __promiseAll([init_dom(),init_styles()]);import_react_reconciler=__toESM(require_react_reconciler_production(),1);if(process17.env.DEV==="true"){let isDevtoolsInstalled=!1;try{import.meta.resolve("react-devtools-core"),isDevtoolsInstalled=!0}catch{}if(isDevtoolsInstalled)await init_devtools().then(() => ({}))}currentUpdatePriority=$NoEventPriority;packageInfo={name:"ink",version:$version};if(process17.env.DEV==="true")try{let loaded=await loadPackageJson();packageInfo={name:loaded.name===void 0||loaded.name===""?packageInfo.name:loaded.name,version:loaded.version===void 0||loaded.version===""?packageInfo.version:loaded.version}}catch(error){console.warn("Failed to load package.json in development mode. Falling back to default renderer metadata.",error)}hostConfig={getRootHostContext:()=>({isInsideText:!1}),prepareForCommit:()=>null,preparePortalMount:()=>null,clearContainer:()=>!1,resetAfterCommit(rootNode){let staticNode=findStaticNode(rootNode);if(rootNode.staticNode=staticNode,staticNode!==rootNode.previousStaticNode)rootNode.isStaticDirty=!0;if(typeof rootNode.onComputeLayout==="function")rootNode.onComputeLayout();if(emitLayoutListeners(rootNode),rootNode.staticNode!==rootNode.previousStaticNode){if(rootNode.previousStaticNode=rootNode.staticNode,typeof rootNode.onStaticChange==="function")rootNode.onStaticChange()}if(rootNode.isStaticDirty){if(rootNode.isStaticDirty=!1,typeof rootNode.onImmediateRender==="function")rootNode.onImmediateRender();return}if(typeof rootNode.onRender==="function")rootNode.onRender()},getChildHostContext(parentHostContext,type){let wasInsideText=parentHostContext.isInsideText,isInsideText=type==="ink-text"||type==="ink-virtual-text";return wasInsideText===isInsideText?parentHostContext:{isInsideText}},shouldSetTextContent:()=>!1,createInstance(originalType,newProps,_rootNode,hostContext){if(originalType==="ink-box"&&hostContext.isInsideText)throw Error("<Box> can’t be nested inside <Text> component");let type=originalType==="ink-text"&&hostContext.isInsideText?"ink-virtual-text":originalType,node=createNode(type);for(let[key,value]of Object.entries(newProps)){if(key==="children")continue;if(key==="style"){if(setStyle(node,value),node.yogaNode)styles_default(node.yogaNode,value);continue}if(key==="internal_transform"){node.internal_transform=value;continue}if(key==="internal_static"){node.internal_static=!0;continue}setAttribute(node,key,value)}return node},createTextInstance(text,_root,hostContext){if(!hostContext.isInsideText)throw Error(`Text string "${text}" must be rendered inside <Text> component`);return createTextNode(text)},resetTextContent(){},hideTextInstance(node){setTextNodeValue(node,"")},unhideTextInstance(node,text){setTextNodeValue(node,text)},getPublicInstance:(instance)=>instance,hideInstance(node){setNodeHidden(node,!0)},unhideInstance(node){setNodeHidden(node,!1)},appendInitialChild:appendChildNode,appendChild:appendChildNode,insertBefore:insertBeforeNode,finalizeInitialChildren(){return!1},isPrimaryRenderer:!0,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,supportsMicrotasks:!0,scheduleMicrotask:queueMicrotask,scheduleTimeout:setTimeout,cancelTimeout:clearTimeout,noTimeout:-1,beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},detachDeletedInstance(){},getInstanceFromNode:()=>null,createFragmentInstance:()=>null,prepareScopeUpdate(){},getInstanceFromScope:()=>null,appendChildToContainer:appendChildNode,insertInContainerBefore:insertBeforeNode,removeChildFromContainer(node,removedNode){clearStaticNodeIfContained(findRootNode(node),removedNode),removeChildNode(node,removedNode),freeYogaSubtree(removedNode)},commitUpdate(node,_type,oldProps,newProps){if(node.internal_static){let rootNode=findRootNode(node);if(rootNode)rootNode.isStaticDirty=!0}let props=diff2(oldProps,newProps),style=diff2(oldProps.style,newProps.style);if(!props&&!style)return;if(props)for(let[key,value]of Object.entries(props)){if(key==="style"){setStyle(node,value);continue}if(key==="internal_transform"){setTransform(node,value);continue}if(key==="internal_static"){node.internal_static=!0;continue}setAttribute(node,key,value)}if(style&&node.yogaNode)styles_default(node.yogaNode,style,newProps.style??{})},commitTextUpdate(node,_oldText,newText){setTextNodeValue(node,newText)},removeChild(node,removedNode){clearStaticNodeIfContained(findRootNode(node),removedNode),removeChildNode(node,removedNode),freeYogaSubtree(removedNode)},setCurrentUpdatePriority(newPriority){currentUpdatePriority=newPriority},getCurrentUpdatePriority:()=>currentUpdatePriority,resolveUpdatePriority(){return currentUpdatePriority===$NoEventPriority?$DefaultEventPriority:currentUpdatePriority},maySuspendCommit(){return!0},maySuspendCommitOnUpdate:()=>!1,maySuspendCommitInSyncRender:()=>!1,NotPendingTransition:void 0,HostTransitionContext:$createContext(null),resetFormInstance(){},requestPostPaintCallback(){},shouldAttemptEagerTransition(){return!1},trackSchedulerEvent(){},resolveEventType(){return null},resolveEventTimeStamp(){return-1.1},preloadInstance(){return!0},startSuspendingCommit(){},suspendInstance(){},suspendOnActiveViewTransition(){},waitForCommitToBeReady(){return null},getSuspendedCommitReason:()=>null,extraDevToolsConfig:null,bindToConsole(methodName,args){let method=Reflect.get(console,methodName);return()=>{if(typeof method==="function")Reflect.apply(method,console,args)}},rendererPackageName:packageInfo.name,rendererVersion:packageInfo.version},reconciler_default=import_react_reconciler.default(hostConfig)});function indentString(string,count=1,options={}){let{indent=" ",includeEmptyLines=!1}=options;if(typeof string!=="string")throw TypeError(`Expected \`input\` to be a \`string\`, got \`${typeof string}\``);if(typeof count!=="number")throw TypeError(`Expected \`count\` to be a \`number\`, got \`${typeof count}\``);if(count<0)throw RangeError(`Expected \`count\` to be at least 0, got \`${count}\``);if(typeof indent!=="string")throw TypeError(`Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``);if(count===0)return string;let regex=includeEmptyLines?/^/gm:/^(?!\s*$)/gm;return string.replace(regex,indent.repeat(count))}var getMaxWidth=(yogaNode)=>yogaNode.getComputedWidth()-yogaNode.getComputedPadding(src_default.EDGE_LEFT)-yogaNode.getComputedPadding(src_default.EDGE_RIGHT)-yogaNode.getComputedBorder(src_default.EDGE_LEFT)-yogaNode.getComputedBorder(src_default.EDGE_RIGHT),get_max_width_default;var init_get_max_width=__esm(async()=>{await init_src();get_max_width_default=getMaxWidth});var boxes_default;var init_boxes=__esm(()=>{boxes_default={single:{topLeft:"┌",top:"─",topRight:"┐",right:"│",bottomRight:"┘",bottom:"─",bottomLeft:"└",left:"│"},double:{topLeft:"╔",top:"═",topRight:"╗",right:"║",bottomRight:"╝",bottom:"═",bottomLeft:"╚",left:"║"},round:{topLeft:"╭",top:"─",topRight:"╮",right:"│",bottomRight:"╯",bottom:"─",bottomLeft:"╰",left:"│"},bold:{topLeft:"┏",top:"━",topRight:"┓",right:"┃",bottomRight:"┛",bottom:"━",bottomLeft:"┗",left:"┃"},singleDouble:{topLeft:"╓",top:"─",topRight:"╖",right:"║",bottomRight:"╜",bottom:"─",bottomLeft:"╙",left:"║"},doubleSingle:{topLeft:"╒",top:"═",topRight:"╕",right:"│",bottomRight:"╛",bottom:"═",bottomLeft:"╘",left:"│"},classic:{topLeft:"+",top:"-",topRight:"+",right:"|",bottomRight:"+",bottom:"-",bottomLeft:"+",left:"|"},arrow:{topLeft:"↘",top:"↓",topRight:"↙",right:"←",bottomRight:"↖",bottom:"↑",bottomLeft:"↗",left:"→"}}});var cli_boxes_default;var init_cli_boxes=__esm(()=>{init_boxes();cli_boxes_default=boxes_default});var rgbRegex,ansiRegex2,isNamedColor=(color)=>foregroundColorNames2.includes(color),colorize=(text,color,type)=>{if(!color)return text;if(isNamedColor(color)){if(type==="foreground")return source_default[color](text);let methodName=`bg${color[0].toUpperCase()+color.slice(1)}`;return source_default[methodName](text)}if(color.startsWith("#"))return type==="foreground"?source_default.hex(color)(text):source_default.bgHex(color)(text);if(color.startsWith("ansi256")){let matches=ansiRegex2.exec(color);if(!matches)return text;let value=Number(matches.groups.value);return type==="foreground"?source_default.ansi256(value)(text):source_default.bgAnsi256(value)(text)}if(color.startsWith("rgb")){let matches=rgbRegex.exec(color);if(!matches)return text;let{red,green,blue}=matches.groups,firstValue=Number(red),secondValue=Number(green),thirdValue=Number(blue);return type==="foreground"?source_default.rgb(firstValue,secondValue,thirdValue)(text):source_default.bgRgb(firstValue,secondValue,thirdValue)(text)}return text},colorize_default;var init_colorize=__esm(()=>{init_source2();rgbRegex=/^rgb\(\s*(?<red>\d+)\s*,\s*(?<green>\d+)\s*,\s*(?<blue>\d+)\s*\)$/,ansiRegex2=/^ansi256\(\s?(?<value>\d+)\s?\)$/,colorize_default=colorize});var stylePiece=(segment,fg,bg,isDim)=>{let styled=colorize_default(segment,fg,"foreground");if(styled=colorize_default(styled,bg,"background"),isDim)styled=source_default.dim(styled);return styled},renderBorder=(x,y,node,output)=>{if(!node.style.borderStyle)return;let width=node.yogaNode.getComputedWidth(),height=node.yogaNode.getComputedHeight(),box=typeof node.style.borderStyle==="string"?cli_boxes_default[node.style.borderStyle]:node.style.borderStyle,topBorderColor=node.style.borderTopColor??node.style.borderColor,bottomBorderColor=node.style.borderBottomColor??node.style.borderColor,leftBorderColor=node.style.borderLeftColor??node.style.borderColor,rightBorderColor=node.style.borderRightColor??node.style.borderColor,topBorderBackgroundColor=node.style.borderTopBackgroundColor??node.style.borderBackgroundColor,bottomBorderBackgroundColor=node.style.borderBottomBackgroundColor??node.style.borderBackgroundColor,leftBorderBackgroundColor=node.style.borderLeftBackgroundColor??node.style.borderBackgroundColor,rightBorderBackgroundColor=node.style.borderRightBackgroundColor??node.style.borderBackgroundColor,dimTopBorderColor=node.style.borderTopDimColor??node.style.borderDimColor,dimBottomBorderColor=node.style.borderBottomDimColor??node.style.borderDimColor,dimLeftBorderColor=node.style.borderLeftDimColor??node.style.borderDimColor,dimRightBorderColor=node.style.borderRightDimColor??node.style.borderDimColor,shouldShowTopBorder=node.style.borderTop!==!1,shouldShowBottomBorder=node.style.borderBottom!==!1,shouldShowLeftBorder=node.style.borderLeft!==!1,shouldShowRightBorder=node.style.borderRight!==!1,contentWidth=width-(shouldShowLeftBorder?1:0)-(shouldShowRightBorder?1:0),topBorder=shouldShowTopBorder?(shouldShowLeftBorder?box.topLeft:"")+box.top.repeat(contentWidth)+(shouldShowRightBorder?box.topRight:""):void 0;topBorder&&=stylePiece(topBorder,topBorderColor,topBorderBackgroundColor,dimTopBorderColor);let verticalBorderHeight=height;if(shouldShowTopBorder)verticalBorderHeight-=1;if(shouldShowBottomBorder)verticalBorderHeight-=1;let leftBorder="";if(shouldShowLeftBorder)leftBorder=(stylePiece(box.left,leftBorderColor,leftBorderBackgroundColor,dimLeftBorderColor)+`
1301
- `).repeat(verticalBorderHeight);let rightBorder="";if(shouldShowRightBorder)rightBorder=(stylePiece(box.right,rightBorderColor,rightBorderBackgroundColor,dimRightBorderColor)+`
1302
- `).repeat(verticalBorderHeight);let bottomBorder=shouldShowBottomBorder?(shouldShowLeftBorder?box.bottomLeft:"")+box.bottom.repeat(contentWidth)+(shouldShowRightBorder?box.bottomRight:""):void 0;bottomBorder&&=stylePiece(bottomBorder,bottomBorderColor,bottomBorderBackgroundColor,dimBottomBorderColor);let offsetY=shouldShowTopBorder?1:0;if(topBorder!==void 0&&topBorder!=="")output.write(x,y,topBorder,{transformers:[]});if(leftBorder!=="")output.write(x,y+offsetY,leftBorder,{transformers:[]});if(rightBorder!=="")output.write(x+width-1,y+offsetY,rightBorder,{transformers:[]});if(bottomBorder!==void 0&&bottomBorder!=="")output.write(x,y+height-1,bottomBorder,{transformers:[]})},render_border_default;var init_render_border=__esm(()=>{init_cli_boxes();init_source2();init_colorize();render_border_default=renderBorder});var renderBackground=(x,y,node,output)=>{if(!node.style.backgroundColor)return;let width=node.yogaNode.getComputedWidth(),height=node.yogaNode.getComputedHeight(),hasBorder=Boolean(node.style.borderStyle),leftBorderWidth=hasBorder&&node.style.borderLeft!==!1?1:0,rightBorderWidth=hasBorder&&node.style.borderRight!==!1?1:0,topBorderHeight=hasBorder&&node.style.borderTop!==!1?1:0,bottomBorderHeight=hasBorder&&node.style.borderBottom!==!1?1:0,contentWidth=width-leftBorderWidth-rightBorderWidth,contentHeight=height-topBorderHeight-bottomBorderHeight;if(!(contentWidth>0&&contentHeight>0))return;let backgroundLine=colorize_default(" ".repeat(contentWidth),node.style.backgroundColor,"background");for(let row=0;row<contentHeight;row++)output.write(x+leftBorderWidth,y+topBorderHeight+row,backgroundLine,{transformers:[]})},render_background_default;var init_render_background=__esm(()=>{init_colorize();render_background_default=renderBackground});var applyPaddingToText=(node,text)=>{let yogaNode=node.childNodes.at(0)?.yogaNode;if(yogaNode){let offsetX=yogaNode.getComputedLeft(),offsetY=yogaNode.getComputedTop();text=`
1303
- `.repeat(offsetY)+indentString(text,offsetX)}return text},normalizeContentOffset=(value)=>typeof value==="number"&&Number.isFinite(value)?Math.trunc(value):0,renderNodeToScreenReaderOutput=(node,options={})=>{if(Boolean(options.skipStaticElements&&node.internal_static)||node.yogaNode?.getDisplay()===src_default.DISPLAY_NONE)return"";let output="";if(node.nodeName==="ink-text")output=squash_text_nodes_default(node);else if(node.nodeName==="ink-box"||node.nodeName==="ink-root"){let separator=node.style.flexDirection==="row"||node.style.flexDirection==="row-reverse"?" ":`
1304
- `;output=(node.style.flexDirection==="row-reverse"||node.style.flexDirection==="column-reverse"?[...node.childNodes].reverse():[...node.childNodes]).map((childNode)=>renderNodeToScreenReaderOutput(childNode,{parentRole:node.internal_accessibility?.role,skipStaticElements:options.skipStaticElements})).filter(Boolean).join(separator)}if(node.internal_accessibility){let{role,state}=node.internal_accessibility;if(state){let stateDescription=Object.keys(state).filter((key)=>state[key]).join(", ");if(stateDescription!=="")output=`(${stateDescription}) ${output}`}if(Boolean(role)&&role!==options.parentRole)output=`${role}: ${output}`}return output},renderNodeToOutput=(node,output,options)=>{let{offsetX=0,offsetY=0,transformers=[],skipStaticElements}=options;if(skipStaticElements&&node.internal_static)return;let{yogaNode}=node;if(!yogaNode||yogaNode.getDisplay()===src_default.DISPLAY_NONE)return;let x=offsetX+yogaNode.getComputedLeft(),y=offsetY+yogaNode.getComputedTop(),newTransformers=typeof node.internal_transform==="function"?[node.internal_transform,...transformers]:transformers;if(node.nodeName==="ink-text"){let text=squash_text_nodes_default(node);if(text.length>0){let currentWidth=widestLine(text),maxWidth=get_max_width_default(yogaNode);if(currentWidth>maxWidth){let textWrap=node.style.textWrap??"wrap";text=wrap_text_default(text,maxWidth,textWrap)}text=applyPaddingToText(node,text),output.write(x,y,text,{transformers:newTransformers})}return}let isClipped=!1;if(node.nodeName==="ink-box"){render_background_default(x,y,node,output),render_border_default(x,y,node,output);let shouldClipHorizontally=(node.style.overflowX??node.style.overflow)==="hidden",shouldClipVertically=(node.style.overflowY??node.style.overflow)==="hidden";if(shouldClipHorizontally||shouldClipVertically){let x1=shouldClipHorizontally?x+yogaNode.getComputedBorder(src_default.EDGE_LEFT):void 0,x2=shouldClipHorizontally?x+yogaNode.getComputedWidth()-yogaNode.getComputedBorder(src_default.EDGE_RIGHT):void 0,y1=shouldClipVertically?y+yogaNode.getComputedBorder(src_default.EDGE_TOP):void 0,y2=shouldClipVertically?y+yogaNode.getComputedHeight()-yogaNode.getComputedBorder(src_default.EDGE_BOTTOM):void 0;output.clip({x1,x2,y1,y2}),isClipped=!0}}if(!(node.nodeName==="ink-root"||node.nodeName==="ink-box"))return;for(let childNode of node.childNodes)renderNodeToOutput(childNode,output,{offsetX:x-normalizeContentOffset(node.style.contentOffsetX),offsetY:y-normalizeContentOffset(node.style.contentOffsetY),transformers:newTransformers,skipStaticElements});if(isClipped)output.unclip()},render_node_to_output_default;var init_render_node_to_output=__esm(async()=>{init_widest_line();init_wrap_text();init_squash_text_nodes();init_render_border();init_render_background();await __promiseAll([init_src(),init_get_max_width()]);render_node_to_output_default=renderNodeToOutput});class OutputCaches{widths=new Map;blockWidths=new Map;styledChars=new Map;getStyledChars(line){let cached=this.styledChars.get(line);if(cached===void 0)cached=styledCharsFromTokens(tokenize2(line)).filter((character)=>!/^\p{Default_Ignorable_Code_Point}+$/u.test(character.value)),this.styledChars.set(line,cached);return cached}getStringWidth(text){let cached=this.widths.get(text);if(cached===void 0)cached=stringWidth(text),this.widths.set(text,cached);return cached}getWidestLine(text){let cached=this.blockWidths.get(text);if(cached===void 0){let lineWidth=0;for(let line of text.split(`
1305
- `))lineWidth=Math.max(lineWidth,this.getStringWidth(line));cached=lineWidth,this.blockWidths.set(text,cached)}return cached}}class Output{operations=[];caches=new OutputCaches;width;height;constructor(options){let{width,height}=options;this.width=width,this.height=height}applyWriteOperation(output,operation,clip){let{text,transformers}=operation,{x,y}=operation,characterLines=[[]];for(let character of this.caches.getStyledChars(text))if(character.value===`
1306
- `)characterLines.push([]);else characterLines.at(-1).push(character);let lines=characterLines.map((line)=>styledCharsToString(line));if(clip){if(isClipEmpty(clip))return;let shouldClipHorizontally=typeof clip?.x1==="number"&&typeof clip?.x2==="number",shouldClipVertically=typeof clip?.y1==="number"&&typeof clip?.y2==="number";if(shouldClipHorizontally){let width=this.caches.getWidestLine(text);if(x+width<clip.x1||x>clip.x2)return}if(shouldClipVertically){let height=lines.length;if(y+height<clip.y1||y>clip.y2)return}if(shouldClipHorizontally){if(lines=lines.map((line)=>{let from=x<clip.x1?clip.x1-x:0,width=this.caches.getStringWidth(line),to=x+width>clip.x2?clip.x2-x:width;return this.sliceLineToColumns(line,from,to)}),x<clip.x1)x=clip.x1}if(shouldClipVertically){let from=y<clip.y1?clip.y1-y:0,height=lines.length,to=y+height>clip.y2?clip.y2-y:height;if(lines=lines.slice(from,to),y<clip.y1)y=clip.y1}}for(let[index,line]of lines.entries()){let currentLine=output[y+index];if(!currentLine)continue;for(let transformer of transformers)line=transformer(line,index+y-operation.y);let characters=this.caches.getStyledChars(line);if(characters.length===0)continue;let offsetX=x;if(currentLine[offsetX]?.value===""&&offsetX>0&&this.caches.getStringWidth(currentLine[offsetX-1]?.value??"")>1)currentLine[offsetX-1]=blankCell(currentLine[offsetX-1]);for(let character of characters){currentLine[offsetX]=character;let characterWidth=Math.max(1,this.caches.getStringWidth(character.value));if(characterWidth>1)for(let offset=1;offset<characterWidth;offset++)currentLine[offsetX+offset]={type:"char",value:offsetX<0?" ":"",fullWidth:!1,styles:character.styles};offsetX+=characterWidth}if(currentLine[offsetX]?.value==="")currentLine[offsetX]=blankCell(currentLine[offsetX])}}write(x,y,text,options){let{transformers}=options;if(text==="")return;this.operations.push({type:"write",x,y,text,transformers})}clip(clip){this.operations.push({type:"clip",clip})}unclip(){this.operations.push({type:"unclip"})}sliceLineToColumns(line,from,to){if(from>=to)return"";let result=[],column=0;for(let character of this.caches.getStyledChars(line)){let width=this.caches.getStringWidth(character.value),start=column;if(column+=width,column<=from)continue;if(start>=to)break;if(width>1&&(start<from||column>to))result.push(blankCell(character));else result.push(character)}return styledCharsToString(result)}get(){let output=[];for(let y=0;y<this.height;y++){let row=[];for(let x=0;x<this.width;x++)row.push({type:"char",value:" ",fullWidth:!1,styles:[]});output.push(row)}let clips=[];for(let operation of this.operations)if(operation.type==="clip")clips.push(intersectClips(clips.at(-1),operation.clip));else if(operation.type==="unclip")clips.pop();else this.applyWriteOperation(output,operation,clips.at(-1));return{output:output.map((line)=>{let lineWithoutEmptyItems=line.filter((item)=>item!==void 0);return styledCharsToString(lineWithoutEmptyItems).trimEnd()}).join(`
1307
- `),height:output.length}}}var blankCell=(cell)=>({...cell,value:" ",fullWidth:!1}),intersectBound=(a,b,tighter)=>{if(a===void 0)return b;return b===void 0?a:tighter(a,b)},isClipEmpty=(clip)=>clip.x1!==void 0&&clip.x2!==void 0&&clip.x1>=clip.x2||clip.y1!==void 0&&clip.y2!==void 0&&clip.y1>=clip.y2,intersectClips=(outer,inner)=>{if(!outer)return inner;return{x1:intersectBound(outer.x1,inner.x1,Math.max),x2:intersectBound(outer.x2,inner.x2,Math.min),y1:intersectBound(outer.y1,inner.y1,Math.max),y2:intersectBound(outer.y2,inner.y2,Math.min)}};var init_output=__esm(()=>{init_string_width();init_build3()});var getVisibleStaticNode=(node)=>{for(let ancestor=node;ancestor;ancestor=ancestor.parentNode)if(ancestor.yogaNode?.getDisplay()===src_default.DISPLAY_NONE)return;return node},renderer=(node,isScreenReaderEnabled)=>{if(node.yogaNode){let staticNode=getVisibleStaticNode(node.staticNode);if(isScreenReaderEnabled){let output=renderNodeToScreenReaderOutput(node,{skipStaticElements:!0}),outputHeight=output===""?0:output.split(`
1308
- `).length,staticOutput="";if(staticNode)staticOutput=renderNodeToScreenReaderOutput(staticNode,{skipStaticElements:!1});return{output,outputHeight,staticOutput:staticOutput===""?"":`${staticOutput}
1309
- `}}let output=new Output({width:node.yogaNode.getComputedWidth(),height:node.yogaNode.getComputedHeight()});render_node_to_output_default(node,output,{skipStaticElements:!0});let staticOutput;if(staticNode?.yogaNode){let{yogaNode}=staticNode;staticOutput=new Output({width:yogaNode.getComputedLeft()+yogaNode.getComputedWidth()+yogaNode.getComputedMargin(src_default.EDGE_RIGHT),height:yogaNode.getComputedTop()+yogaNode.getComputedHeight()+yogaNode.getComputedMargin(src_default.EDGE_BOTTOM)}),render_node_to_output_default(staticNode,staticOutput,{skipStaticElements:!1})}let{output:generatedOutput,height:outputHeight}=output.get();return{output:generatedOutput,outputHeight,staticOutput:staticOutput&&staticOutput.height>0?`${staticOutput.get().output}
1310
- `:""}}return{output:"",outputHeight:0,staticOutput:""}},renderer_default;var init_renderer=__esm(async()=>{init_output();await __promiseAll([init_src(),init_render_node_to_output()]);renderer_default=renderer});var showCursorEscape="\x1B[?25h",hideCursorEscape="\x1B[?25l",cursorPositionChanged=(a,b)=>a?.x!==b?.x||a?.y!==b?.y,buildCursorSuffix=(bottomLine,cursorPosition)=>{if(!cursorPosition)return"";let moveUp=bottomLine-cursorPosition.y;return(moveUp>0?cursorUp(moveUp):"")+cursorTo(cursorPosition.x)+showCursorEscape},buildReturnToBottom=(previousLineCount,previousCursorPosition)=>{if(!previousCursorPosition)return"";let down=previousLineCount-1-previousCursorPosition.y;return(down>0?cursorDown(down):"")+cursorTo(0)},buildCursorOnlySequence=(input)=>{let hidePrefix=input.cursorWasShown?hideCursorEscape:"",returnToBottom=buildReturnToBottom(input.previousLineCount,input.previousCursorPosition),cursorSuffix=buildCursorSuffix(input.previousLineCount-1,input.cursorPosition);return hidePrefix+returnToBottom+cursorSuffix},buildReturnToBottomPrefix=(wasCursorShown,previousLineCount,previousCursorPosition)=>{if(!wasCursorShown)return"";return hideCursorEscape+buildReturnToBottom(previousLineCount,previousCursorPosition)},buildEraseFrame=(previousLineCount,previousCursorPosition)=>{if(!previousCursorPosition)return eraseLines(previousLineCount);let rowsBelowTop=Math.min(previousCursorPosition.y,previousLineCount-1);return hideCursorEscape+cursorMove(0,-rowsBelowTop)+cursorTo(0)+eraseDown};var init_cursor_helpers=__esm(()=>{init_ansi_escapes()});var require_mimic_fn=__commonJS(function(exports,module){var mimicFn=(to,from)=>{for(let prop of Reflect.ownKeys(from))Object.defineProperty(to,prop,Object.getOwnPropertyDescriptor(from,prop));return to};module.exports=mimicFn;module.exports.default=mimicFn});var require_onetime=__commonJS(function(exports,module){var mimicFn=require_mimic_fn(),calledFunctions=new WeakMap,onetime=(function_,options={})=>{if(typeof function_!=="function")throw TypeError("Expected a function");let returnValue,callCount=0,functionName=function_.displayName||function_.name||"<anonymous>",onetime=function(...arguments_){if(calledFunctions.set(onetime,++callCount),callCount===1)returnValue=function_.apply(this,arguments_),function_=null;else if(options.throw===!0)throw Error(`Function \`${functionName}\` can only be called once`);return returnValue};return mimicFn(onetime,function_),calledFunctions.set(onetime,callCount),onetime};module.exports=onetime;module.exports.default=onetime;module.exports.callCount=(function_)=>{if(!calledFunctions.has(function_))throw Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);return calledFunctions.get(function_)}});import process18 from"node:process";var import_onetime,import_signal_exit,restoreCursor,restore_cursor_default;var init_restore_cursor=__esm(()=>{import_onetime=__toESM(require_onetime(),1),import_signal_exit=__toESM(require_signal_exit(),1),restoreCursor=import_onetime.default(()=>{import_signal_exit.default(()=>{process18.stderr.write("\x1B[?25h")},{alwaysLast:!0})}),restore_cursor_default=restoreCursor});import process19 from"node:process";var isHidden=!1,cliCursor,cli_cursor_default;var init_cli_cursor=__esm(()=>{init_restore_cursor();cliCursor={};cliCursor.show=(writableStream=process19.stderr)=>{if(!writableStream.isTTY)return;isHidden=!1,writableStream.write("\x1B[?25h")};cliCursor.hide=(writableStream=process19.stderr)=>{if(!writableStream.isTTY)return;restore_cursor_default(),isHidden=!0,writableStream.write("\x1B[?25l")};cliCursor.toggle=(force,writableStream)=>{if(force!==void 0)isHidden=force;if(isHidden)cliCursor.show(writableStream);else cliCursor.hide(writableStream)};cli_cursor_default=cliCursor});function lineUpdate(previous,next,columns){let full=cursorTo(0)+eraseEndLine+next;if(columns===void 0||Number.isNaN(columns)||columns<1)return full;let commonLength=0;while(commonLength<previous.length&&commonLength<next.length&&previous[commonLength]===next[commonLength])commonLength++;if(commonLength===0)return full;let previousText=previous.replaceAll(sgr,""),nextText=next.replaceAll(sgr,"");if(control.test(previousText)||control.test(nextText))return full;let codes=[...next.matchAll(sgr)],textLimit=commonLength;for(let match of codes){if(match.index>=commonLength)break;textLimit-=Math.min(match[0].length,commonLength-match.index)}let textLength=0,column=0;if(printableAscii.test(previousText)&&printableAscii.test(nextText))textLength=textLimit,column=textLimit;else{let previousSegments=segmenter4.segment(previousText)[Symbol.iterator]();for(let{segment,index}of segmenter4.segment(nextText)){if(index+segment.length>textLimit||previousSegments.next().value?.segment!==segment)break;textLength=index+segment.length}column=stringWidth(nextText.slice(0,textLength))}if(column===0||column>=columns||column+stringWidth(previousText.slice(textLength))>columns||column+stringWidth(nextText.slice(textLength))>columns)return full;let offset=textLength,styles="";for(let match of codes){if(match.index>offset||match.index+match[0].length>commonLength)break;offset+=match[0].length,styles+=match[0]}let partial=cursorTo(column)+eraseEndLine+styles+next.slice(offset);return partial.length<full.length?partial:full}var segmenter4,sgr,control,printableAscii;var init_line_update=__esm(()=>{init_ansi_escapes();init_string_width();segmenter4=new Intl.Segmenter(void 0,{granularity:"grapheme"}),sgr=/\u{1B}\[[\d;]*m/gu,control=/\p{Control}/u,printableAscii=/^[ -~]*$/u});var visibleLineCount=(lines,text)=>text.endsWith(`
1311
- `)?lines.length-1:lines.length,createStandard=(stream,{showCursor=!1}={})=>{let previousLineCount=0,previousOutput="",hasHiddenCursor=!1,cursorPosition,isCursorDirty=!1,previousCursorPosition,wasCursorShown=!1,getActiveCursor=()=>isCursorDirty?cursorPosition:void 0,hasChanges=(text,activeCursor)=>{let hasCursorChanged=cursorPositionChanged(activeCursor,previousCursorPosition);return text!==previousOutput||hasCursorChanged},render=(text)=>{if(!showCursor&&!hasHiddenCursor)cli_cursor_default.hide(stream),hasHiddenCursor=!0;let activeCursor=getActiveCursor();isCursorDirty=!1;let hasCursorChanged=cursorPositionChanged(activeCursor,previousCursorPosition);if(!hasChanges(text,activeCursor))return!1;let lines=text.split(`
1312
- `),cursorSuffix=buildCursorSuffix(lines.length-1,activeCursor);if(text===previousOutput&&hasCursorChanged)stream.write(buildCursorOnlySequence({cursorWasShown:wasCursorShown,previousLineCount,previousCursorPosition,cursorPosition:activeCursor}));else{previousOutput=text;let returnPrefix=buildReturnToBottomPrefix(wasCursorShown,previousLineCount,previousCursorPosition);stream.write(returnPrefix+eraseLines(previousLineCount)+text+cursorSuffix),previousLineCount=lines.length}return previousCursorPosition=activeCursor?{...activeCursor}:void 0,wasCursorShown=activeCursor!==void 0,!0};return render.clear=()=>{stream.write(buildEraseFrame(previousLineCount,previousCursorPosition)),previousOutput="",previousLineCount=0,previousCursorPosition=void 0,wasCursorShown=!1},render.done=()=>{if(previousCursorPosition)stream.write(buildReturnToBottom(previousLineCount,previousCursorPosition));if(previousOutput="",previousLineCount=0,previousCursorPosition=void 0,wasCursorShown=!1,showCursor)return;cli_cursor_default.show(stream),hasHiddenCursor=!1},render.reset=()=>{previousOutput="",previousLineCount=0,previousCursorPosition=void 0,wasCursorShown=!1},render.sync=(text)=>{let activeCursor=isCursorDirty?cursorPosition:void 0;isCursorDirty=!1;let lines=text.split(`
1313
- `);if(previousOutput=text,previousLineCount=lines.length,!activeCursor&&wasCursorShown)stream.write(hideCursorEscape);if(activeCursor)stream.write(buildCursorSuffix(lines.length-1,activeCursor));previousCursorPosition=activeCursor?{...activeCursor}:void 0,wasCursorShown=activeCursor!==void 0},render.setCursorPosition=(position)=>{cursorPosition=position,isCursorDirty=!0},render.isCursorDirty=()=>isCursorDirty,render.willRender=(text)=>hasChanges(text,getActiveCursor()),render.getCursorPosition=()=>previousCursorPosition,render},createIncremental=(stream,{showCursor=!1}={})=>{let previousLines=[],previousOutput="",previousColumns=stream.columns,hasHiddenCursor=!1,cursorPosition,isCursorDirty=!1,previousCursorPosition,wasCursorShown=!1,getActiveCursor=()=>isCursorDirty?cursorPosition:void 0,hasChanges=(text,activeCursor)=>{let hasCursorChanged=cursorPositionChanged(activeCursor,previousCursorPosition);return text!==previousOutput||hasCursorChanged},render=(text)=>{if(!showCursor&&!hasHiddenCursor)cli_cursor_default.hide(stream),hasHiddenCursor=!0;let activeCursor=getActiveCursor();isCursorDirty=!1;let hasCursorChanged=cursorPositionChanged(activeCursor,previousCursorPosition);if(!hasChanges(text,activeCursor))return!1;let areColumnsUnchanged=previousColumns===stream.columns;previousColumns=stream.columns;let nextLines=text.split(`
1314
- `),visibleCount=visibleLineCount(nextLines,text),previousVisible=visibleLineCount(previousLines,previousOutput);if(text===previousOutput&&hasCursorChanged)return stream.write(buildCursorOnlySequence({cursorWasShown:wasCursorShown,previousLineCount:previousLines.length,previousCursorPosition,cursorPosition:activeCursor})),previousCursorPosition=activeCursor?{...activeCursor}:void 0,wasCursorShown=activeCursor!==void 0,!0;let returnPrefix=buildReturnToBottomPrefix(wasCursorShown,previousLines.length,previousCursorPosition);if(text===`
1315
- `||previousOutput.length===0){let cursorSuffix=buildCursorSuffix(nextLines.length-1,activeCursor);return stream.write(returnPrefix+eraseLines(previousLines.length)+text+cursorSuffix),wasCursorShown=activeCursor!==void 0,previousCursorPosition=activeCursor?{...activeCursor}:void 0,previousOutput=text,previousLines=nextLines,!0}let hasTrailingNewline=text.endsWith(`
1316
- `),buffer=[];if(buffer.push(returnPrefix),visibleCount<previousVisible){let extraSlot=previousOutput.endsWith(`
1317
- `)?1:0;buffer.push(eraseLines(previousVisible-visibleCount+extraSlot),cursorUp(visibleCount))}else if(previousLines.length>1)buffer.push(cursorUp(previousLines.length-1));for(let i=0;i<visibleCount;i++){let isLastLine=i===visibleCount-1;if(i<previousVisible&&nextLines[i]===previousLines[i]){if(!isLastLine||hasTrailingNewline)buffer.push(cursorNextLine);continue}let nextLine=nextLines[i],changedLine=areColumnsUnchanged&&nextLines.length===previousLines.length?lineUpdate(previousLines[i],nextLine,stream.columns):cursorTo(0)+eraseEndLine+nextLine;buffer.push(changedLine+(isLastLine&&!hasTrailingNewline?"":`
1318
- `))}let cursorSuffix=buildCursorSuffix(nextLines.length-1,activeCursor);return buffer.push(cursorSuffix),stream.write(buffer.join("")),wasCursorShown=activeCursor!==void 0,previousCursorPosition=activeCursor?{...activeCursor}:void 0,previousOutput=text,previousLines=nextLines,!0};return render.clear=()=>{stream.write(buildEraseFrame(previousLines.length,previousCursorPosition)),previousOutput="",previousLines=[],previousCursorPosition=void 0,wasCursorShown=!1},render.done=()=>{if(previousCursorPosition)stream.write(buildReturnToBottom(previousLines.length,previousCursorPosition));if(previousOutput="",previousLines=[],previousCursorPosition=void 0,wasCursorShown=!1,showCursor)return;cli_cursor_default.show(stream),hasHiddenCursor=!1},render.reset=()=>{previousOutput="",previousLines=[],previousCursorPosition=void 0,wasCursorShown=!1},render.sync=(text)=>{let activeCursor=isCursorDirty?cursorPosition:void 0;isCursorDirty=!1,previousColumns=stream.columns;let lines=text.split(`
1319
- `);if(previousOutput=text,previousLines=lines,!activeCursor&&wasCursorShown)stream.write(hideCursorEscape);if(activeCursor)stream.write(buildCursorSuffix(lines.length-1,activeCursor));previousCursorPosition=activeCursor?{...activeCursor}:void 0,wasCursorShown=activeCursor!==void 0},render.setCursorPosition=(position)=>{cursorPosition=position,isCursorDirty=!0},render.isCursorDirty=()=>isCursorDirty,render.willRender=(text)=>hasChanges(text,getActiveCursor()),render.getCursorPosition=()=>previousCursorPosition,render},create7=(stream,{showCursor=!1,incremental=!1}={})=>incremental?createIncremental(stream,{showCursor}):createStandard(stream,{showCursor}),logUpdate,log_update_default;var init_log_update=__esm(()=>{init_ansi_escapes();init_cli_cursor();init_line_update();init_cursor_helpers();logUpdate={create:create7},log_update_default=logUpdate});function shouldSynchronize(stream,isInteractive){return"isTTY"in stream&&stream.isTTY&&(isInteractive??!is_in_ci_default)}var bsu="\x1B[?2026h",esu="\x1B[?2026l";var init_write_synchronized=__esm(()=>{init_is_in_ci()});var instances,instances_default;var init_instances=__esm(()=>{instances=new WeakMap,instances_default=instances});var isCsiParameterByte=(byte)=>byte>=48&&byte<=63,isCsiIntermediateByte=(byte)=>byte>=32&&byte<=47,isCsiFinalByte=(byte)=>byte>=64&&byte<=126,parseCsiSequence=(input,startIndex,prefixLength)=>{let csiPayloadStart=startIndex+prefixLength+1,index=csiPayloadStart;for(;index<input.length;index++){let byte=input.codePointAt(index);if(byte===void 0)return"pending";if(byte===91&&index===csiPayloadStart)continue;if(byte===36&&index===csiPayloadStart+1&&"235678".includes(input[csiPayloadStart])||isCsiFinalByte(byte))return{sequence:input.slice(startIndex,index+1),nextIndex:index+1};if(isCsiParameterByte(byte)||isCsiIntermediateByte(byte))continue;return}return"pending"},parseSs3Sequence=(input,startIndex,prefixLength)=>{let index=startIndex+prefixLength+1;for(;index<input.length;index++){let byte=input.codePointAt(index);if(isCsiFinalByte(byte))return{sequence:input.slice(startIndex,index+1),nextIndex:index+1};if(byte!==59&&(byte<48||byte>57))return}return"pending"},parseControlSequence=(input,startIndex,prefixLength)=>{let sequenceType=input[startIndex+prefixLength];if(sequenceType===void 0)return"pending";if(sequenceType==="[")return parseCsiSequence(input,startIndex,prefixLength);return sequenceType==="O"?parseSs3Sequence(input,startIndex,prefixLength):void 0},isCompleteControlSequence=(input)=>{if(!input.startsWith("\x1B"))return!1;let prefixLength=input[1]==="\x1B"?2:1,parsed=parseControlSequence(input,0,prefixLength);return typeof parsed==="object"&&parsed.nextIndex===input.length},parseEscapedCodePoint=(input,escapeIndex)=>{let nextCodePoint=input.codePointAt(escapeIndex+1),nextCodePointLength=nextCodePoint!==void 0&&nextCodePoint>65535?2:1,nextIndex=escapeIndex+1+nextCodePointLength;return{sequence:input.slice(escapeIndex,nextIndex),nextIndex}},parseEscapeSequence=(input,escapeIndex)=>{if(escapeIndex===input.length-1)return"pending";if(input[escapeIndex+1]==="\x1B"){if(escapeIndex+2>=input.length)return"pending";let doubleEscapeSequence=parseControlSequence(input,escapeIndex,2);if(doubleEscapeSequence==="pending")return"pending";if(doubleEscapeSequence)return doubleEscapeSequence;return{sequence:input.slice(escapeIndex,escapeIndex+2),nextIndex:escapeIndex+2}}let controlSequence=parseControlSequence(input,escapeIndex,1);return controlSequence==="pending"?"pending":controlSequence??parseEscapedCodePoint(input,escapeIndex)},splitControlBytes=(text,events)=>{let textSegmentStart=0;for(let index=0;index<text.length;index++){let character=text[index];if(!["","\b","\x03"].includes(character))continue;if(index>textSegmentStart)events.push(text.slice(textSegmentStart,index));events.push(character),textSegmentStart=index+1}if(textSegmentStart<text.length)events.push(text.slice(textSegmentStart))},parseKeypresses=(input)=>{let events=[],index=0,pendingFrom=(pendingStartIndex)=>({events,pending:input.slice(pendingStartIndex)});while(index<input.length){let escapeIndex=input.indexOf("\x1B",index);if(escapeIndex===-1)return splitControlBytes(input.slice(index),events),{events,pending:""};if(escapeIndex>index)splitControlBytes(input.slice(index,escapeIndex),events);let parsedEscapeSequence=parseEscapeSequence(input,escapeIndex);if(parsedEscapeSequence==="pending")return pendingFrom(escapeIndex);if(parsedEscapeSequence.sequence==="\x1B[200~"){let afterStart=parsedEscapeSequence.nextIndex,endIndex=input.indexOf("\x1B[201~",afterStart);if(endIndex===-1)return pendingFrom(escapeIndex);events.push({paste:input.slice(afterStart,endIndex)}),index=endIndex+6;continue}events.push(parsedEscapeSequence.sequence),index=parsedEscapeSequence.nextIndex}return{events,pending:""}},createInputParser=()=>{let pending="";return{push(chunk){let parsedInput=parseKeypresses(pending+chunk);return pending=parsedInput.pending,parsedInput.events},hasPendingEscape(){return pending.startsWith("\x1B")&&!pending.startsWith("\x1B[200~")&&pending!=="\x1B[200"},flushPendingEscape(){if(!pending.startsWith("\x1B"))return;let pendingEscape=pending;return pending="",pendingEscape},reset(){pending=""}}};function resolveFlags(flags){let result=0;for(let flag of flags)result|=kittyFlags[flag];if(flags.includes("reportAssociatedText"))result|=kittyFlags.reportAllKeysAsEscapeCodes;return result}var kittyFlags,kittyModifiers;var init_kitty_keyboard=__esm(()=>{kittyFlags={disambiguateEscapeCodes:1,reportEventTypes:2,reportAlternateKeys:4,reportAllKeysAsEscapeCodes:8,reportAssociatedText:16};kittyModifiers={shift:1,alt:2,ctrl:4,super:8,hyper:16,meta:32,capsLock:64,numLock:128}});function resolveEventType(value){if(value===3)return"release";if(value===2)return"repeat";return"press"}function parseKittyModifiers(modifiers){return{ctrl:!!(modifiers&kittyModifiers.ctrl),shift:!!(modifiers&kittyModifiers.shift),meta:!!(modifiers&(kittyModifiers.meta|kittyModifiers.alt)),super:!!(modifiers&kittyModifiers.super),hyper:!!(modifiers&kittyModifiers.hyper),capsLock:!!(modifiers&kittyModifiers.capsLock),numLock:!!(modifiers&kittyModifiers.numLock)}}var textDecoder,metaKeyCodeRe,fnKeyRe,keyName,nonAlphanumericKeys,isShiftKey=(code)=>["[a","[b","[c","[d","[e","[2$","[3$","[5$","[6$","[7$","[8$","[Z"].includes(code),isCtrlKey=(code)=>["Oa","Ob","Oc","Od","Oe","[2^","[3^","[5^","[6^","[7^","[8^"].includes(code),kittyKeyRe,kittySpecialKeyRe,kittySpecialLetterKeys,kittySpecialNumberKeys,kittyCodepointNames,isValidCodepoint=(cp)=>cp>=0&&cp<=1114111&&!(cp>=55296&&cp<=57343),safeFromCodePoint=(cp)=>isValidCodepoint(cp)?String.fromCodePoint(cp):"?",parseKittyKeypress=(s)=>{let match=kittyKeyRe.exec(s);if(!match)return null;let codepoint=parseInt(match[1],10);if(codepoint===57414)codepoint=13;let modifiers=match[2]?Math.max(0,parseInt(match[2],10)-1):0,eventType=match[3]?parseInt(match[3],10):1,textField=match[4];if(!isValidCodepoint(codepoint))return null;let text;if(textField)text=textField.split(":").map((cp)=>safeFromCodePoint(parseInt(cp,10))).join("");let name,isPrintable;if(codepoint===32)name="space",isPrintable=!0;else if(codepoint===13)name="return",isPrintable=!0;else if(kittyCodepointNames[codepoint])name=kittyCodepointNames[codepoint],isPrintable=!1;else if(codepoint<32||codepoint>=127&&codepoint<=159||codepoint>=57344&&codepoint<=63743)name="",isPrintable=!1;else name=safeFromCodePoint(codepoint).toLowerCase(),isPrintable=!0;if(isPrintable&&!text)text=safeFromCodePoint(codepoint);return{name,...parseKittyModifiers(modifiers),eventType:resolveEventType(eventType),sequence:s,raw:s,isKittyProtocol:!0,isPrintable:isPrintable||text!==void 0,text}},parseKittySpecialKey=(s)=>{let match=kittySpecialKeyRe.exec(s);if(!match)return null;let number=parseInt(match[1],10),modifiers=match[2]?Math.max(0,parseInt(match[2],10)-1):0,eventType=match[3]?parseInt(match[3],10):1,terminator=match[4];if(terminator!=="~"&&number!==1)return null;let name=terminator==="~"?kittySpecialNumberKeys[number]:kittySpecialLetterKeys[terminator];if(!name)return null;return{name,...parseKittyModifiers(modifiers),eventType:resolveEventType(eventType),sequence:s,raw:s,isKittyProtocol:!0,isPrintable:!1}},parseKeypress=(s="")=>{let parts;if(s instanceof Uint8Array)if(s[0]>127&&s[1]===void 0)s="\x1B"+String.fromCharCode(s[0]-128);else s=textDecoder.decode(s);else if(s!==void 0&&typeof s!=="string")s=String(s);else if(!s)s="";let kittyResult=parseKittyKeypress(s);if(kittyResult)return kittyResult;let kittySpecialResult=parseKittySpecialKey(s);if(kittySpecialResult)return kittySpecialResult;if(kittyKeyRe.test(s))return{name:"",ctrl:!1,meta:!1,shift:!1,sequence:s,raw:s,isKittyProtocol:!0,isPrintable:!1};let key={name:"",ctrl:!1,meta:!1,shift:!1,sequence:s,raw:s};if(key.sequence=key.sequence||s||key.name,s==="\r"||s==="\x1B\r")key.raw=void 0,key.name="return",key.meta=s.length===2;else if(s==="\x1BOM"||s==="\x1B\x1BOM")key.raw=void 0,key.name="return",key.sequence="\r",key.meta=s.length===4;else if(s===`
1320
- `)key.name="enter";else if(s==="\t"||s==="\x1B\t")key.name="tab",key.meta=s.length===2;else if(s==="\b"||s==="\x1B\b")key.name="backspace",key.meta=s.charAt(0)==="\x1B";else if(s===""||s==="\x1B")key.name="backspace",key.meta=s.charAt(0)==="\x1B";else if(s==="\x1B"||s==="\x1B\x1B")key.name="escape",key.meta=s.length===2;else if(/^\x1b?[ \x00]$/.test(s))key.name="space",key.ctrl=s.endsWith("\x00"),key.meta=s.length===2;else if(/^\x1b?[\x00-\x1f]$/.test(s)){let codepoint=s.charCodeAt(s.length-1);key.name=String.fromCharCode(codepoint+(codepoint<=26?96:64)),key.ctrl=!0,key.meta=s.length===2}else if(s.length===1&&s>="0"&&s<="9")key.name="number";else if(s.length===1&&s>="a"&&s<="z")key.name=s;else if(s.length===1&&s>="A"&&s<="Z")key.name=s.toLowerCase(),key.shift=!0;else if(parts=metaKeyCodeRe.exec(s))key.name=parts[1].toLowerCase(),key.meta=!0,key.shift=/^[A-Z]$/.test(parts[1]);else if(parts=fnKeyRe.exec(s)){let segs=[...s];if(segs[0]==="\x1B"&&segs[1]==="\x1B")key.meta=!0;let code=[parts[1],parts[2],parts[4],parts[6]].filter(Boolean).join(""),modifier=(parts[3]||parts[5]||1)-1;key.ctrl=!!(modifier&4),key.meta=key.meta||!!(modifier&10),key.shift=!!(modifier&1),key.code=code,key.name=keyName[code]??"",key.shift=isShiftKey(code)||key.shift,key.ctrl=isCtrlKey(code)||key.ctrl}return key},parse_keypress_default;var init_parse_keypress=__esm(()=>{init_kitty_keyboard();textDecoder=new TextDecoder,metaKeyCodeRe=/^(?:\x1b)([^\p{C}\[])$/u,fnKeyRe=/^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/,keyName={OP:"f1",OQ:"f2",OR:"f3",OS:"f4","[P":"f1","[Q":"f2","[R":"f3","[S":"f4","[11~":"f1","[12~":"f2","[13~":"f3","[14~":"f4","[[A":"f1","[[B":"f2","[[C":"f3","[[D":"f4","[[E":"f5","[15~":"f5","[17~":"f6","[18~":"f7","[19~":"f8","[20~":"f9","[21~":"f10","[23~":"f11","[24~":"f12","[A":"up","[B":"down","[C":"right","[D":"left","[E":"clear","[F":"end","[H":"home",OA:"up",OB:"down",OC:"right",OD:"left",OE:"clear",OF:"end",OH:"home","[1~":"home","[2~":"insert","[3~":"delete","[4~":"end","[5~":"pageup","[6~":"pagedown","[[5~":"pageup","[[6~":"pagedown","[7~":"home","[8~":"end","[a":"up","[b":"down","[c":"right","[d":"left","[e":"clear","[2$":"insert","[3$":"delete","[5$":"pageup","[6$":"pagedown","[7$":"home","[8$":"end",Oa:"up",Ob:"down",Oc:"right",Od:"left",Oe:"clear","[2^":"insert","[3^":"delete","[5^":"pageup","[6^":"pagedown","[7^":"home","[8^":"end","[Z":"tab"},nonAlphanumericKeys=[...Object.values(keyName),"backspace"],kittyKeyRe=/^\x1b\[(\d+)(?::\d*(?::\d+)?)?(?:;(\d*)(?::(\d+))?(?:;([\d:]+))?)?u$/,kittySpecialKeyRe=/^\x1b\[(\d+)(?:;(\d+)(?::(\d+))?)?([A-Za-z~])$/,kittySpecialLetterKeys={A:"up",B:"down",C:"right",D:"left",E:"clear",F:"end",H:"home",P:"f1",Q:"f2",S:"f4"},kittySpecialNumberKeys={2:"insert",3:"delete",5:"pageup",6:"pagedown",7:"home",8:"end",11:"f1",12:"f2",13:"f3",14:"f4",15:"f5",17:"f6",18:"f7",19:"f8",20:"f9",21:"f10",23:"f11",24:"f12",57427:"clear"},kittyCodepointNames={27:"escape",9:"tab",127:"backspace",57358:"capslock",57359:"scrolllock",57360:"numlock",57361:"printscreen",57362:"pause",57363:"menu",57376:"f13",57377:"f14",57378:"f15",57379:"f16",57380:"f17",57381:"f18",57382:"f19",57383:"f20",57384:"f21",57385:"f22",57386:"f23",57387:"f24",57388:"f25",57389:"f26",57390:"f27",57391:"f28",57392:"f29",57393:"f30",57394:"f31",57395:"f32",57396:"f33",57397:"f34",57398:"f35",57399:"kp0",57400:"kp1",57401:"kp2",57402:"kp3",57403:"kp4",57404:"kp5",57405:"kp6",57406:"kp7",57407:"kp8",57408:"kp9",57409:"kpdecimal",57410:"kpdivide",57411:"kpmultiply",57412:"kpsubtract",57413:"kpadd",57415:"kpequal",57416:"kpseparator",57417:"left",57418:"right",57419:"up",57420:"down",57421:"pageup",57422:"pagedown",57423:"home",57424:"end",57425:"insert",57426:"delete",57428:"mediaplay",57429:"mediapause",57430:"mediaplaypause",57431:"mediareverse",57432:"mediastop",57433:"mediafastforward",57434:"mediarewind",57435:"mediatracknext",57436:"mediatrackprevious",57437:"mediarecord",57438:"lowervolume",57439:"raisevolume",57440:"mutevolume",57441:"leftshift",57442:"leftcontrol",57443:"leftalt",57444:"leftsuper",57445:"lefthyper",57446:"leftmeta",57447:"rightshift",57448:"rightcontrol",57449:"rightalt",57450:"rightsuper",57451:"righthyper",57452:"rightmeta",57453:"isoLevel3Shift",57454:"isoLevel5Shift"};parse_keypress_default=parseKeypress});var isTty=(stream)=>("isTTY"in stream)&&stream.isTTY===!0,isRawModeStream=(stdin)=>isTty(stdin)&&("setRawMode"in stdin)&&typeof stdin.setRawMode==="function",getRawModeStream=(stdin)=>isRawModeStream(stdin)?stdin:void 0;var noopSuspension,defaultValue,AppContext,AppContext_default;var init_AppContext=__esm(()=>{init_react_production();noopSuspension={async resume(){},async[Symbol.asyncDispose](){}},defaultValue={exit(_errorOrResult){},async waitUntilRenderFlush(){},suspendTerminal:async(callback)=>{if(callback){await callback();return}return noopSuspension}},AppContext=$createContext(defaultValue);AppContext.displayName="InternalAppContext";AppContext_default=AppContext});import{EventEmitter as EventEmitter3}from"node:events";import process20 from"node:process";var StdinContext,StdinContext_default;var init_StdinContext=__esm(()=>{init_react_production();StdinContext=$createContext({stdin:process20.stdin,internal_eventEmitter:new EventEmitter3,setRawMode(){},setBracketedPasteMode(){},isRawModeSupported:!1,internal_exitOnCtrlC:!0});StdinContext.displayName="InternalStdinContext";StdinContext_default=StdinContext});import process21 from"node:process";var StdoutContext,StdoutContext_default;var init_StdoutContext=__esm(()=>{init_react_production();StdoutContext=$createContext({stdout:process21.stdout,write(){}});StdoutContext.displayName="InternalStdoutContext";StdoutContext_default=StdoutContext});import process22 from"node:process";var StderrContext,StderrContext_default;var init_StderrContext=__esm(()=>{init_react_production();StderrContext=$createContext({stderr:process22.stderr,write(){}});StderrContext.displayName="InternalStderrContext";StderrContext_default=StderrContext});var FocusContext,FocusContext_default;var init_FocusContext=__esm(()=>{init_react_production();FocusContext=$createContext({activeId:void 0,add(){},remove(){},activate(){},deactivate(){},enableFocus(){},disableFocus(){},focusNext(){},focusPrevious(){},focus(){}});FocusContext.displayName="InternalFocusContext";FocusContext_default=FocusContext});var AnimationContext,AnimationContext_default;var init_AnimationContext=__esm(()=>{init_react_production();AnimationContext=$createContext({renderThrottleMs:0,subscribe(){return{startTime:0,unsubscribe(){}}}});AnimationContext.displayName="InternalAnimationContext";AnimationContext_default=AnimationContext});var CursorContext,CursorContext_default;var init_CursorContext=__esm(()=>{init_react_production();CursorContext=$createContext({setCursorPosition(){}});CursorContext.displayName="InternalCursorContext";CursorContext_default=CursorContext});var require_escape_string_regexp=__commonJS(function(exports,module){var matchOperatorsRegex=/[|\\{}()[\]^$+*?.-]/g;module.exports=(string)=>{if(typeof string!=="string")throw TypeError("Expected a string");return string.replace(matchOperatorsRegex,"\\$&")}});var require_stack_utils=__commonJS(function(exports,module){var escapeStringRegexp=require_escape_string_regexp(),cwd=typeof process==="object"&&process&&typeof process.cwd==="function"?process.cwd():".",natives=[].concat(__require("module").builtinModules,"bootstrap_node","node").map((n)=>new RegExp(`(?:\\((?:node:)?${n}(?:\\.js)?:\\d+:\\d+\\)$|^\\s*at (?:node:)?${n}(?:\\.js)?:\\d+:\\d+$)`));natives.push(/\((?:node:)?internal\/[^:]+:\d+:\d+\)$/,/\s*at (?:node:)?internal\/[^:]+:\d+:\d+$/,/\/\.node-spawn-wrap-\w+-\w+\/node:\d+:\d+\)?$/);class StackUtils{constructor(opts){if(opts={ignoredPackages:[],...opts},"internals"in opts===!1)opts.internals=StackUtils.nodeInternals();if("cwd"in opts===!1)opts.cwd=cwd;this._cwd=opts.cwd.replace(/\\/g,"/"),this._internals=[].concat(opts.internals,ignoredPackagesRegExp(opts.ignoredPackages)),this._wrapCallSite=opts.wrapCallSite||!1}static nodeInternals(){return[...natives]}clean(stack,indent=0){if(indent=" ".repeat(indent),!Array.isArray(stack))stack=stack.split(`
1321
- `);if(!/^\s*at /.test(stack[0])&&/^\s*at /.test(stack[1]))stack=stack.slice(1);let outdent=!1,lastNonAtLine=null,result=[];return stack.forEach((st)=>{if(st=st.replace(/\\/g,"/"),this._internals.some((internal)=>internal.test(st)))return;let isAtLine=/^\s*at /.test(st);if(outdent)st=st.trimEnd().replace(/^(\s+)at /,"$1");else if(st=st.trim(),isAtLine)st=st.slice(3);if(st=st.replace(`${this._cwd}/`,""),st)if(isAtLine){if(lastNonAtLine)result.push(lastNonAtLine),lastNonAtLine=null;result.push(st)}else outdent=!0,lastNonAtLine=st}),result.map((line)=>`${indent}${line}
1322
- `).join("")}captureString(limit,fn=this.captureString){if(typeof limit==="function")fn=limit,limit=1/0;let{stackTraceLimit}=Error;if(limit)Error.stackTraceLimit=limit;let obj={};Error.captureStackTrace(obj,fn);let{stack}=obj;return Error.stackTraceLimit=stackTraceLimit,this.clean(stack)}capture(limit,fn=this.capture){if(typeof limit==="function")fn=limit,limit=1/0;let{prepareStackTrace,stackTraceLimit}=Error;if(Error.prepareStackTrace=(obj,site)=>{if(this._wrapCallSite)return site.map(this._wrapCallSite);return site},limit)Error.stackTraceLimit=limit;let obj={};Error.captureStackTrace(obj,fn);let{stack}=obj;return Object.assign(Error,{prepareStackTrace,stackTraceLimit}),stack}at(fn=this.at){let[site]=this.capture(1,fn);if(!site)return{};let res={line:site.getLineNumber(),column:site.getColumnNumber()};if(setFile(res,site.getFileName(),this._cwd),site.isConstructor())Object.defineProperty(res,"constructor",{value:!0,configurable:!0});if(site.isEval())res.evalOrigin=site.getEvalOrigin();if(site.isNative())res.native=!0;let typename;try{typename=site.getTypeName()}catch(_){}if(typename&&typename!=="Object"&&typename!=="[object Object]")res.type=typename;let fname=site.getFunctionName();if(fname)res.function=fname;let meth=site.getMethodName();if(meth&&fname!==meth)res.method=meth;return res}parseLine(line){let match=line&&line.match(re);if(!match)return null;let ctor=match[1]==="new",fname=match[2],evalOrigin=match[3],evalFile=match[4],evalLine=Number(match[5]),evalCol=Number(match[6]),file=match[7],lnum=match[8],col=match[9],native=match[10]==="native",closeParen=match[11]===")",method,res={};if(lnum)res.line=Number(lnum);if(col)res.column=Number(col);if(closeParen&&file){let closes=0;for(let i=file.length-1;i>0;i--)if(file.charAt(i)===")")closes++;else if(file.charAt(i)==="("&&file.charAt(i-1)===" "){if(closes--,closes===-1&&file.charAt(i-1)===" "){let before=file.slice(0,i-1);file=file.slice(i+1),fname+=` (${before}`;break}}}if(fname){let methodMatch=fname.match(methodRe);if(methodMatch)fname=methodMatch[1],method=methodMatch[2]}if(setFile(res,file,this._cwd),ctor)Object.defineProperty(res,"constructor",{value:!0,configurable:!0});if(evalOrigin)res.evalOrigin=evalOrigin,res.evalLine=evalLine,res.evalColumn=evalCol,res.evalFile=evalFile&&evalFile.replace(/\\/g,"/");if(native)res.native=!0;if(fname)res.function=fname;if(method&&fname!==method)res.method=method;return res}}function setFile(result,filename,cwd){if(filename){if(filename=filename.replace(/\\/g,"/"),filename.startsWith(`${cwd}/`))filename=filename.slice(cwd.length+1);result.file=filename}}function ignoredPackagesRegExp(ignoredPackages){if(ignoredPackages.length===0)return[];let packages=ignoredPackages.map((mod)=>escapeStringRegexp(mod));return new RegExp(`[/\\\\]node_modules[/\\\\](?:${packages.join("|")})[/\\\\][^:]+:\\d+:\\d+`)}var re=new RegExp("^(?:\\s*at )?(?:(new) )?(?:(.*?) \\()?(?:eval at ([^ ]+) \\((.+?):(\\d+):(\\d+)\\), )?(?:(.+?):(\\d+):(\\d+)|(native))(\\)?)$"),methodRe=/^(.*?) \[as (.*?)\]$/;module.exports=StackUtils});var convertToSpaces=(input,spaces=2)=>input.replace(/^\t+/gm,($1)=>" ".repeat($1.length*spaces)),dist_default2;var init_dist8=__esm(()=>{dist_default2=convertToSpaces});var generateLineNumbers=(line,around)=>{let lineNumbers=[],min=line-around,max=line+around;for(let lineNumber=min;lineNumber<=max;lineNumber++)lineNumbers.push(lineNumber);return lineNumbers},codeExcerpt=(source,line,options={})=>{var _a;if(typeof source!=="string")throw TypeError("Source code is missing.");if(!line||line<1)throw TypeError("Line number must start from `1`.");let lines=dist_default2(source).split(/\r?\n/);if(line>lines.length)return;return generateLineNumbers(line,(_a=options.around)!==null&&_a!==void 0?_a:3).filter((line)=>lines[line-1]!==void 0).map((line)=>({line,value:lines[line-1]}))},dist_default3;var init_dist9=__esm(()=>{init_dist8();dist_default3=codeExcerpt});var AccessibilityContext;var init_AccessibilityContext=__esm(()=>{init_react_production();AccessibilityContext=$createContext({isScreenReaderEnabled:!1})});var BackgroundContext;var init_BackgroundContext=__esm(()=>{init_react_production();BackgroundContext=$createContext(void 0)});var Box,Box_default;var init_Box=__esm(()=>{init_react_production();init_AccessibilityContext();init_BackgroundContext();Box=$forwardRef(({children,backgroundColor,flexWrap="nowrap",flexDirection="row","aria-label":ariaLabel,"aria-hidden":ariaHidden,"aria-role":role,"aria-state":ariaState,...style},ref)=>{let{isScreenReaderEnabled}=$use(AccessibilityContext),inheritedBackgroundColor=$use(BackgroundContext);if(isScreenReaderEnabled&&ariaHidden)return null;let effectiveBackgroundColor=backgroundColor||inheritedBackgroundColor,boxElement=$createElement("ink-box",{ref,style:{flexWrap,flexDirection,flexGrow:0,flexShrink:1,...style,backgroundColor,overflowX:style.overflowX??style.overflow??"visible",overflowY:style.overflowY??style.overflow??"visible"},internal_accessibility:{role,state:ariaState}},isScreenReaderEnabled&&Boolean(ariaLabel)?$createElement("ink-text",null,ariaLabel):children);return $createElement(BackgroundContext,{value:effectiveBackgroundColor},boxElement)});Box.displayName="Box";Box_default=Box});function Text({color,backgroundColor,dimColor=!1,bold=!1,italic=!1,underline=!1,strikethrough=!1,inverse=!1,wrap="wrap",children,"aria-label":ariaLabel,"aria-hidden":ariaHidden=!1}){let{isScreenReaderEnabled}=$use(AccessibilityContext),inheritedBackgroundColor=$use(BackgroundContext),effectiveBackgroundColor=backgroundColor??inheritedBackgroundColor,childrenOrAriaLabel=isScreenReaderEnabled&&Boolean(ariaLabel)?ariaLabel:children;if(childrenOrAriaLabel===void 0||childrenOrAriaLabel===null||isScreenReaderEnabled&&ariaHidden)return null;let transform=(text)=>{if(dimColor)text=source_default.dim(text);if(text=colorize_default(text,color,"foreground"),text=colorize_default(text,effectiveBackgroundColor,"background"),bold)text=source_default.bold(text);if(italic)text=source_default.italic(text);if(underline)text=source_default.underline(text);if(strikethrough)text=source_default.strikethrough(text);if(inverse)text=source_default.inverse(text);return text};return $createElement(BackgroundContext,{value:effectiveBackgroundColor},$createElement("ink-text",{style:{flexGrow:0,flexShrink:1,flexDirection:"row",textWrap:wrap},internal_transform:isScreenReaderEnabled?void 0:transform},childrenOrAriaLabel))}var init_Text=__esm(()=>{init_react_production();init_source2();init_colorize();init_AccessibilityContext();init_BackgroundContext()});import*as fs16 from"node:fs";import{relative}from"node:path";import{cwd}from"node:process";import{fileURLToPath as fileURLToPath6}from"node:url";function ErrorOverview({error}){let stack=error.stack?.split(`
1323
- `).slice(error.message.split(`
1324
- `).length),origin=stack?stackUtils.parseLine(stack[0]):void 0,filePath=cleanupPath(origin?.file),excerpt,lineWidth=0,stackLineCounts=new Map;if(filePath!==void 0&&filePath!==""&&origin?.line!==void 0&&origin.line!==0){try{let sourceCode=fs16.readFileSync(filePath,"utf8");excerpt=dist_default3(sourceCode,origin.line)}catch{}if(excerpt)for(let{line}of excerpt)lineWidth=Math.max(lineWidth,String(line).length)}return $createElement(Box_default,{flexDirection:"column",padding:1},$createElement(Box_default,null,$createElement(Text,{backgroundColor:"red",color:"white"}," ","ERROR"," "),$createElement(Text,null," ",error.message)),origin&&filePath!==void 0&&filePath!==""?$createElement(Box_default,{marginTop:1},$createElement(Text,{dimColor:!0},filePath,":",origin.line,":",origin.column)):null,origin&&excerpt?$createElement(Box_default,{marginTop:1,flexDirection:"column"},excerpt.map(({line,value})=>$createElement(Box_default,{key:line},$createElement(Box_default,{width:lineWidth+1},$createElement(Text,{dimColor:line!==origin.line,backgroundColor:line===origin.line?"red":void 0,color:line===origin.line?"white":void 0,"aria-label":line===origin.line?`Line ${line}, error`:`Line ${line}`},String(line).padStart(lineWidth," "),":")),$createElement(Text,{key:line,backgroundColor:line===origin.line?"red":void 0,color:line===origin.line?"white":void 0}," "+value)))):null,stack?$createElement(Box_default,{marginTop:1,flexDirection:"column"},stack.map((line)=>{let parsedLine=stackUtils.parseLine(line),lineCount=stackLineCounts.get(line)??0;stackLineCounts.set(line,lineCount+1);let key=`${line}-${lineCount}`;if(parsedLine?.file===void 0||parsedLine.file===""||parsedLine.line===void 0||parsedLine.line===0||parsedLine.column===void 0||parsedLine.column===0)return $createElement(Box_default,{key},$createElement(Text,{dimColor:!0},"- "),$createElement(Text,{dimColor:!0,bold:!0},line,"\\t"," "));return $createElement(Box_default,{key},$createElement(Text,{dimColor:!0},"- "),$createElement(Text,{dimColor:!0,bold:!0},parsedLine.function),$createElement(Text,{dimColor:!0,color:"gray","aria-label":`at ${cleanupPath(parsedLine.file)??""} line ${parsedLine.line} column ${parsedLine.column}`}," ","(",cleanupPath(parsedLine.file)??"",":",parsedLine.line,":",parsedLine.column,")"))})):null)}var import_stack_utils,cleanupPath=(path)=>path?.startsWith("file://")?relative(cwd(),fileURLToPath6(path)):path,stackUtils;var init_ErrorOverview=__esm(()=>{init_react_production();init_dist9();init_Box();init_Text();import_stack_utils=__toESM(require_stack_utils(),1),stackUtils=new import_stack_utils.default({cwd:cwd(),internals:import_stack_utils.default.nodeInternals()})});import{types as types8}from"node:util";var ErrorBoundary;var init_ErrorBoundary=__esm(()=>{init_react_production();init_ErrorOverview();ErrorBoundary=class ErrorBoundary extends $PureComponent{static displayName="InternalErrorBoundary";static getDerivedStateFromError(error){return{error:types8.isNativeError(error)?error:Error(String(error))}}state={error:void 0};componentDidCatch(){this.props.onError(this.state.error)}render(){return this.state.error?$createElement(ErrorOverview,{error:this.state.error}):this.props.children}}});import{EventEmitter as EventEmitter4}from"node:events";import process23 from"node:process";function App({children,stdin,stdout,stderr,writeToStdout,writeToStderr,exitOnCtrlC,onExit,onWaitUntilRenderFlush,onSuspendTerminal,onKittyQueryResponse,onRegisterInputControl,setCursorPosition,interactive,renderThrottleMs}){let isFocusEnabledRef=$useRef(!0),[activeFocusId,setActiveFocusId]=$useState(void 0),focusablesRef=$useRef([]),animationSubscribersRef=$useRef(new Map),animationTimerRef=$useRef(void 0),rawModeEnabledCountRef=$useRef(0),pendingDisableRawModeRef=$useRef(!1),isInputPausedRef=$useRef(!1),bracketedPasteModeEnabledCountRef=$useRef(0),eventEmitterRef=$useRef(new EventEmitter4);eventEmitterRef.current.setMaxListeners(1/0);let readableListenerRef=$useRef(void 0),inputParserRef=$useRef(createInputParser()),pendingInputFlushRef=$useRef(void 0),pendingInputFlushDelayMilliseconds=20,clearPendingInputFlush=$useCallback(()=>{if(!pendingInputFlushRef.current)return;clearTimeout(pendingInputFlushRef.current),pendingInputFlushRef.current=void 0},[]),clearAnimationTimer=$useCallback(()=>{if(!animationTimerRef.current)return;clearTimeout(animationTimerRef.current),animationTimerRef.current=void 0},[]),scheduleAnimationTick=$useCallback(()=>{if(clearAnimationTimer(),animationSubscribersRef.current.size===0)return;let nextDueTime=1/0;for(let subscriber of animationSubscribersRef.current.values())nextDueTime=Math.min(nextDueTime,subscriber.nextDueTime);let delay=Math.max(0,nextDueTime-performance.now());animationTimerRef.current=setTimeout(()=>{animationTimerRef.current=void 0;let currentTime=performance.now();for(let subscriber of animationSubscribersRef.current.values()){if(currentTime<subscriber.nextDueTime)continue;subscriber.callback(currentTime);let elapsedTime=currentTime-subscriber.startTime,elapsedFrames=Math.floor(elapsedTime/subscriber.interval)+1;subscriber.nextDueTime=subscriber.startTime+elapsedFrames*subscriber.interval}scheduleAnimationTick()},delay)},[clearAnimationTimer]),animationSubscribe=$useCallback((callback,interval)=>{let startTime=performance.now();return animationSubscribersRef.current.set(callback,{callback,interval,startTime,nextDueTime:startTime+interval}),scheduleAnimationTick(),{startTime,unsubscribe(){if(animationSubscribersRef.current.delete(callback),animationSubscribersRef.current.size===0){clearAnimationTimer();return}scheduleAnimationTick()}}},[clearAnimationTimer,scheduleAnimationTick]);$useEffect(()=>()=>{clearAnimationTimer()},[clearAnimationTimer]);let rawModeStdin=getRawModeStream(stdin),isRawModeSupported=rawModeStdin!==void 0,detachReadableListener=$useCallback(()=>{if(!readableListenerRef.current)return;stdin.removeListener("readable",readableListenerRef.current),readableListenerRef.current=void 0},[stdin]),clearInputState=$useCallback(()=>{inputParserRef.current.reset(),clearPendingInputFlush(),detachReadableListener()},[clearPendingInputFlush,detachReadableListener]),disableRawMode=$useCallback(()=>{if(!rawModeStdin)return;pendingDisableRawModeRef.current=!1,rawModeStdin.setRawMode(!1),rawModeStdin.unref?.(),rawModeEnabledCountRef.current=0,clearInputState()},[rawModeStdin,clearInputState]),handleExit=$useCallback((errorOrResult)=>{if(isRawModeSupported&&(rawModeEnabledCountRef.current>0||pendingDisableRawModeRef.current))disableRawMode();onExit(errorOrResult)},[isRawModeSupported,disableRawMode,onExit]),handleInput=$useCallback((input)=>{let key=parse_keypress_default(input);if(exitOnCtrlC&&key.ctrl&&key.name==="c"&&key.eventType!=="release"){handleExit();return}if(isFocusEnabledRef.current&&key.name==="escape"&&key.eventType!=="release"&&!key.shift&&!key.ctrl&&!key.meta&&key.super!==!0&&key.hyper!==!0)setActiveFocusId(void 0)},[exitOnCtrlC,handleExit]),emitInput=$useCallback((input)=>{handleInput(input),eventEmitterRef.current.emit("input",input)},[handleInput]),schedulePendingInputFlush=$useCallback(()=>{clearPendingInputFlush(),pendingInputFlushRef.current=setTimeout(()=>{pendingInputFlushRef.current=void 0;let pendingEscape=inputParserRef.current.flushPendingEscape();if(pendingEscape===void 0||pendingEscape==="")return;emitInput(pendingEscape)},pendingInputFlushDelayMilliseconds)},[clearPendingInputFlush,emitInput]),handleReadable=$useCallback(()=>{let handleInputEvent=(event)=>{if(typeof event==="string"){if(/^\u{1B}\[\?\d+u$/u.test(event)){onKittyQueryResponse();return}if(isCompleteControlSequence(event)){let key=parse_keypress_default(event);if(!key.isKittyProtocol&&key.name==="")return}emitInput(event)}else{if(eventEmitterRef.current.listenerCount("paste")===0){emitInput(event.paste);return}eventEmitterRef.current.emit("paste",event.paste)}};clearPendingInputFlush();let chunk;while((chunk=stdin.read())!==null)for(let event of inputParserRef.current.push(chunk))handleInputEvent(event);if(inputParserRef.current.hasPendingEscape())schedulePendingInputFlush()},[stdin,emitInput,clearPendingInputFlush,schedulePendingInputFlush,onKittyQueryResponse]),attachReadableListener=$useCallback(()=>{if(readableListenerRef.current)return;readableListenerRef.current=handleReadable,stdin.addListener("readable",handleReadable)},[stdin,handleReadable]),handleSetRawMode=$useCallback((isEnabled)=>{if(!rawModeStdin){if(stdin===process23.stdin)throw Error(`Raw mode is not supported on the current process.stdin, which Ink uses as input stream by default.
1325
- Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`);throw Error(`Raw mode is not supported on the stdin provided to Ink.
1326
- Read about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`)}if(rawModeStdin.setEncoding("utf8"),isEnabled){if(rawModeEnabledCountRef.current===0){let isRawModeAlreadyEnabled=pendingDisableRawModeRef.current;if(pendingDisableRawModeRef.current=!1,!isInputPausedRef.current){if(!isRawModeAlreadyEnabled)rawModeStdin.ref?.(),rawModeStdin.setRawMode(!0);attachReadableListener()}}rawModeEnabledCountRef.current++;return}if(rawModeEnabledCountRef.current===0||--rawModeEnabledCountRef.current!==0||isInputPausedRef.current)return;clearInputState(),pendingDisableRawModeRef.current=!0,queueMicrotask(()=>{if(!pendingDisableRawModeRef.current)return;disableRawMode()})},[rawModeStdin,stdin,attachReadableListener,clearInputState,disableRawMode]),handleSetBracketedPasteMode=$useCallback((isEnabled)=>{if(!stdout.isTTY)return;if(isEnabled){if(bracketedPasteModeEnabledCountRef.current===0&&!isInputPausedRef.current)stdout.write("\x1B[?2004h");bracketedPasteModeEnabledCountRef.current++;return}if(bracketedPasteModeEnabledCountRef.current===0)return;if(--bracketedPasteModeEnabledCountRef.current===0&&!isInputPausedRef.current)stdout.write("\x1B[?2004l")},[stdout]),pauseInput=$useCallback(()=>{if(isInputPausedRef.current=!0,bracketedPasteModeEnabledCountRef.current>0&&stdout.isTTY)try{stdout.write("\x1B[?2004l")}catch{}if(!(isRawModeSupported&&(rawModeEnabledCountRef.current>0||pendingDisableRawModeRef.current)))return;pendingDisableRawModeRef.current=!1,rawModeStdin?.setRawMode(!1),rawModeStdin?.unref?.(),clearInputState()},[isRawModeSupported,rawModeStdin,stdout,clearInputState]),resumeInput=$useCallback(()=>{if(isInputPausedRef.current=!1,isRawModeSupported&&rawModeEnabledCountRef.current>0)rawModeStdin?.setEncoding("utf8"),rawModeStdin?.ref?.(),rawModeStdin?.setRawMode(!0),attachReadableListener();if(bracketedPasteModeEnabledCountRef.current>0&&stdout.isTTY)try{stdout.write("\x1B[?2004h")}catch{}},[isRawModeSupported,rawModeStdin,stdout,attachReadableListener]);$useInsertionEffect(()=>{onRegisterInputControl(pauseInput,resumeInput)},[onRegisterInputControl,pauseInput,resumeInput]);let findNextFocusable=$useCallback((currentFocusables,currentActiveFocusId)=>{let activeIndex=currentFocusables.findIndex((focusable)=>focusable.id===currentActiveFocusId);for(let index=activeIndex+1;index<currentFocusables.length;index++){let focusable=currentFocusables[index];if(focusable?.isActive)return focusable.id}return},[]),findPreviousFocusable=$useCallback((currentFocusables,currentActiveFocusId)=>{let activeIndex=currentFocusables.findIndex((focusable)=>focusable.id===currentActiveFocusId);for(let index=activeIndex-1;index>=0;index--){let focusable=currentFocusables[index];if(focusable?.isActive)return focusable.id}return},[]),focusNext=$useCallback(()=>{let currentFocusables=uniqueFocusables(focusablesRef.current);setActiveFocusId((currentActiveFocusId)=>{let firstFocusableId=currentFocusables.find((focusable)=>focusable.isActive)?.id;return findNextFocusable(currentFocusables,currentActiveFocusId)??firstFocusableId})},[findNextFocusable]),focusPrevious=$useCallback(()=>{let currentFocusables=uniqueFocusables(focusablesRef.current);setActiveFocusId((currentActiveFocusId)=>{let lastFocusableId=currentFocusables.findLast((focusable)=>focusable.isActive)?.id;return findPreviousFocusable(currentFocusables,currentActiveFocusId)??lastFocusableId})},[findPreviousFocusable]);$useEffect(()=>{let handleTabNavigation=(input)=>{if(!isFocusEnabledRef.current||focusablesRef.current.length===0)return;let key=parse_keypress_default(input);if(key.name!=="tab"||key.eventType==="release"||key.ctrl||key.meta||key.super===!0||key.hyper===!0)return;if(key.shift)focusPrevious();else focusNext()};eventEmitterRef.current.on("input",handleTabNavigation);let emitter=eventEmitterRef.current;return()=>{emitter.off("input",handleTabNavigation)}},[focusNext,focusPrevious]);let enableFocus=$useCallback(()=>{isFocusEnabledRef.current=!0},[]),disableFocus=$useCallback(()=>{isFocusEnabledRef.current=!1,setActiveFocusId(void 0)},[]),focus=$useCallback((id)=>{if(focusablesRef.current.some((focusable)=>focusable.id===id&&focusable.isActive))setActiveFocusId(id)},[]),addFocusable=$useCallback((id,{autoFocus})=>{if(focusablesRef.current=[...focusablesRef.current,{id,isActive:!0}],autoFocus&&isFocusEnabledRef.current)setActiveFocusId((currentActiveFocusId)=>currentActiveFocusId??id)},[]),removeFocusable=$useCallback((id)=>{setActiveFocusId((currentActiveFocusId)=>currentActiveFocusId===id?void 0:currentActiveFocusId),focusablesRef.current=focusablesRef.current.filter((focusable)=>focusable.id!==id)},[]),activateFocusable=$useCallback((id)=>{focusablesRef.current=focusablesRef.current.map((focusable)=>focusable.id===id?{id,isActive:!0}:focusable)},[]),deactivateFocusable=$useCallback((id)=>{setActiveFocusId((currentActiveFocusId)=>currentActiveFocusId===id?void 0:currentActiveFocusId),focusablesRef.current=focusablesRef.current.map((focusable)=>focusable.id===id?{id,isActive:!1}:focusable)},[]);$useEffect(()=>()=>{let canWriteToStdout=!stdout.destroyed&&!stdout.writableEnded;if(interactive&&canWriteToStdout)cli_cursor_default.show(stdout);if(isRawModeSupported&&(rawModeEnabledCountRef.current>0||pendingDisableRawModeRef.current))disableRawMode();if(!(bracketedPasteModeEnabledCountRef.current>0))return;if(canWriteToStdout&&stdout.isTTY)stdout.write("\x1B[?2004l");bracketedPasteModeEnabledCountRef.current=0},[stdout,isRawModeSupported,disableRawMode,interactive]);let appContextValue=$useMemo(()=>({exit:handleExit,waitUntilRenderFlush:onWaitUntilRenderFlush,suspendTerminal:onSuspendTerminal}),[handleExit,onWaitUntilRenderFlush,onSuspendTerminal]),stdinContextValue=$useMemo(()=>({stdin,setRawMode:handleSetRawMode,setBracketedPasteMode:handleSetBracketedPasteMode,isRawModeSupported,internal_exitOnCtrlC:exitOnCtrlC,internal_eventEmitter:eventEmitterRef.current}),[stdin,handleSetRawMode,handleSetBracketedPasteMode,isRawModeSupported,exitOnCtrlC]),stdoutContextValue=$useMemo(()=>({stdout,write:writeToStdout}),[stdout,writeToStdout]),stderrContextValue=$useMemo(()=>({stderr,write:writeToStderr}),[stderr,writeToStderr]),cursorContextValue=$useMemo(()=>({setCursorPosition}),[setCursorPosition]),focusContextValue=$useMemo(()=>({activeId:activeFocusId,add:addFocusable,remove:removeFocusable,activate:activateFocusable,deactivate:deactivateFocusable,enableFocus,disableFocus,focusNext,focusPrevious,focus}),[activeFocusId,addFocusable,removeFocusable,activateFocusable,deactivateFocusable,enableFocus,disableFocus,focusNext,focusPrevious,focus]),animationContextValue=$useMemo(()=>({renderThrottleMs,subscribe:animationSubscribe}),[animationSubscribe,renderThrottleMs]);return $createElement(AppContext_default,{value:appContextValue},$createElement(StdinContext_default,{value:stdinContextValue},$createElement(StdoutContext_default,{value:stdoutContextValue},$createElement(StderrContext_default,{value:stderrContextValue},$createElement(FocusContext_default,{value:focusContextValue},$createElement(AnimationContext_default,{value:animationContextValue},$createElement(CursorContext_default,{value:cursorContextValue},$createElement(ErrorBoundary,{onError:handleExit},children))))))))}var uniqueFocusables=(focusables)=>{let seenIds=new Set;return focusables.filter((focusable)=>{if(seenIds.has(focusable.id))return!1;return seenIds.add(focusable.id),!0})},App_default;var init_App=__esm(()=>{init_react_production();init_cli_cursor();init_parse_keypress();init_AppContext();init_StdinContext();init_StdoutContext();init_StderrContext();init_FocusContext();init_AnimationContext();init_CursorContext();init_ErrorBoundary();App.displayName="InternalApp";App_default=App});var RootNodeContext,RootNodeContext_default;var init_RootNodeContext=__esm(()=>{init_react_production();RootNodeContext=$createContext(void 0),RootNodeContext_default=RootNodeContext});import process24 from"node:process";class Ink{options;log;cursorPosition;throttledLog;isScreenReaderEnabled;interactive;renderThrottleMs;alternateScreen;isUnmounted;isUnmounting;lastOutput;lastOutputToRender;lastOutputHeight;lastTerminalWidth;lastTerminalHeight;container;rootNode;fullStaticOutput;hasRenderedStaticOutput;exitPromise;exitResult;beforeExitHandler;restoreConsole;unsubscribeResize;throttledOnRender;hasPendingThrottledRender=!1;kittyProtocolEnabled=!1;kittyFlags;finishKittyDetection;nextRenderCommit;isSuspended=!1;pauseInput;resumeInput;isConcurrent;resized=()=>{let{columns:currentWidth,rows:currentHeight}=getWindowSize(this.options.stdout);if(currentWidth<this.lastTerminalWidth||currentHeight<this.lastTerminalHeight&&this.log.getCursorPosition()!==void 0)this.log.clear(),this.lastOutput="",this.lastOutputToRender="",this.lastOutputHeight=0;this.calculateLayout(),emitLayoutListeners(this.rootNode),this.onRender(),this.lastTerminalWidth=currentWidth,this.lastTerminalHeight=currentHeight};resolveExitPromise=()=>{};rejectExitPromise=()=>{};unsubscribeExit=()=>{};handleAppExit=(errorOrResult)=>{if(this.isUnmounted||this.isUnmounting)return;if(isErrorInput(errorOrResult)){this.unmount(errorOrResult);return}this.exitResult=errorOrResult,this.unmount()};setCursorPosition=(position)=>{this.cursorPosition=position,this.log.setCursorPosition(position)};handleKittyQueryResponse=()=>{this.finishKittyDetection?.(!0)};restoreLastOutput=()=>{if(!this.interactive)return;if(this.isScreenReaderEnabled){this.options.stdout.write(this.lastOutputToRender),this.log.setCursorPosition(void 0),this.log.sync(this.lastOutputToRender);return}this.log.setCursorPosition(this.cursorPosition),this.log(this.lastOutputToRender===""?this.lastOutput+`
1327
- `:this.lastOutputToRender)};calculateLayout=()=>{let{yogaNode}=this.rootNode;if(!yogaNode)return;let terminalWidth=getWindowSize(this.options.stdout).columns;yogaNode.setWidth(terminalWidth),yogaNode.calculateLayout(void 0,void 0,src_default.DIRECTION_LTR)};handleStaticChange=()=>{this.fullStaticOutput="",this.hasRenderedStaticOutput=!1};onRender=()=>{if(this.hasPendingThrottledRender=!1,this.isUnmounted)return;if(this.isSuspended){if(this.nextRenderCommit)this.nextRenderCommit.resolve(),this.nextRenderCommit=void 0;return}if(this.nextRenderCommit)this.nextRenderCommit.resolve(),this.nextRenderCommit=void 0;if(this.lastOutputHeight===0&&this.lastOutput!==""&&!this.isUnmounting)this.lastOutputToRender="";let startTime=performance.now(),{output,outputHeight,staticOutput}=renderer_default(this.rootNode,this.isScreenReaderEnabled),renderTime=performance.now()-startTime;this.renderFrame(output,outputHeight,staticOutput),this.options.onRender?.({renderTime})};constructor(options){autoBind(this),this.options=options,this.rootNode=createNode("ink-root"),this.rootNode.onComputeLayout=this.calculateLayout,this.isScreenReaderEnabled=options.isScreenReaderEnabled??process24.env.INK_SCREEN_READER==="true",this.interactive=this.resolveInteractiveOption(options.interactive),this.alternateScreen=!1;let isUnthrottled=options.debug||this.isScreenReaderEnabled,maxFps=options.maxFps??30,renderThrottleMs=maxFps>0?Math.max(1,Math.ceil(1000/maxFps)):0;if(this.renderThrottleMs=isUnthrottled?0:renderThrottleMs,isUnthrottled)this.rootNode.onRender=this.onRender,this.throttledOnRender=void 0;else{let throttled=throttle(this.onRender,renderThrottleMs,{leading:!0,trailing:!0});this.rootNode.onRender=()=>{this.hasPendingThrottledRender=!0,throttled()},this.throttledOnRender=throttled}this.rootNode.onImmediateRender=this.onRender,this.rootNode.onStaticChange=this.handleStaticChange,this.log=log_update_default.create(options.stdout,{incremental:options.incrementalRendering}),this.cursorPosition=void 0,this.throttledLog=isUnthrottled?this.log:throttle((output)=>{let shouldWrite=this.log.willRender(output),shouldSync=this.shouldSync();if(shouldSync&&shouldWrite)this.options.stdout.write(bsu);if(this.log(output),shouldSync&&shouldWrite)this.options.stdout.write(esu)},void 0,{leading:!0,trailing:!0}),this.isUnmounted=!1,this.isUnmounting=!1,this.isConcurrent=options.concurrent??!1,this.lastOutput="",this.lastOutputToRender="",this.lastOutputHeight=0;let{columns,rows}=getWindowSize(this.options.stdout);this.lastTerminalWidth=columns,this.lastTerminalHeight=rows,this.fullStaticOutput="",this.hasRenderedStaticOutput=!1;let rootTag=options.concurrent?$ConcurrentRoot:$LegacyRoot;if(this.container=reconciler_default.createContainer(this.rootNode,rootTag,null,!1,null,"id",()=>{},()=>{},()=>{},()=>{},null),this.unsubscribeExit=import_signal_exit2.default(this.unmount,{alwaysLast:!1}),this.setAlternateScreen(Boolean(options.alternateScreen)),process24.env.DEV==="true")reconciler_default.injectIntoDevTools();if(options.patchConsole)this.patchConsole();if(this.interactive)options.stdout.on("resize",this.resized),this.unsubscribeResize=()=>{options.stdout.off("resize",this.resized)};this.initKittyKeyboard(),this.exitPromise=new Promise((resolve,reject)=>{this.resolveExitPromise=resolve,this.rejectExitPromise=reject}),this.exitPromise.catch(noop4)}renderFrame(output,outputHeight,staticOutput){let hasStaticOutput=staticOutput!=="";if(this.options.debug){if(hasStaticOutput)this.fullStaticOutput+=staticOutput,this.hasRenderedStaticOutput=!0;this.lastOutput=output,this.lastOutputToRender=output,this.lastOutputHeight=outputHeight,this.options.stdout.write(this.fullStaticOutput+output);return}if(!this.interactive){if(hasStaticOutput)this.options.stdout.write(staticOutput);this.lastOutput=output,this.lastOutputToRender=output+`
1328
- `,this.lastOutputHeight=outputHeight;return}if(this.isScreenReaderEnabled){let shouldSync=this.shouldSync();if(shouldSync)this.options.stdout.write(bsu);let terminalWidth=getWindowSize(this.options.stdout).columns,wrappedOutput=wrapAnsi(output,terminalWidth,{trim:!1,hard:!0});if(!hasStaticOutput&&wrappedOutput===this.lastOutputToRender){if(shouldSync)this.options.stdout.write(esu);return}if(this.log.clear(),this.lastOutputHeight=0,hasStaticOutput){if(this.options.stdout.write(staticOutput),this.alternateScreen)this.fullStaticOutput+=staticOutput}if(this.options.stdout.write(wrappedOutput),this.lastOutput=output,this.lastOutputToRender=wrappedOutput,this.lastOutputHeight=wrappedOutput===""?0:wrappedOutput.split(`
1329
- `).length,this.log.setCursorPosition(void 0),this.log.sync(wrappedOutput),shouldSync)this.options.stdout.write(esu);return}if(hasStaticOutput){if(this.hasRenderedStaticOutput=!0,this.alternateScreen)this.fullStaticOutput+=staticOutput}this.renderInteractiveFrame(output,outputHeight,hasStaticOutput?staticOutput:"")}setAlternateScreen(isEnabled){if(this.alternateScreen=this.resolveAlternateScreenOption(isEnabled,this.interactive),!this.alternateScreen)return;this.writeBestEffort(this.options.stdout,enterAlternativeScreen),this.writeBestEffort(this.options.stdout,hideCursorEscape)}resolveInteractiveOption(interactive){return interactive??(!is_in_ci_default&&Boolean(this.options.stdout.isTTY))}resolveAlternateScreenOption(alternateScreen,isInteractive){return Boolean(alternateScreen)&&isInteractive&&Boolean(this.options.stdout.isTTY)}shouldSync(){return shouldSynchronize(this.options.stdout,this.interactive)}writeBestEffort(stream,data){try{stream.write(data)}catch{}}async awaitExit(){try{await this.exitPromise}catch{}}hasPendingConcurrentWork(){let concurrentContainer=this.container;return(concurrentContainer.pendingLanes??0)!==0&&concurrentContainer.callbackNode!==void 0&&concurrentContainer.callbackNode!==null}async awaitNextRender(){return this.nextRenderCommit??=Promise.withResolvers(),this.nextRenderCommit.promise}renderInteractiveFrame(output,outputHeight,staticOutput){let hasStaticOutput=staticOutput!=="",isStdoutTty=Boolean(this.options.stdout.isTTY),viewportRows=isStdoutTty?getWindowSize(this.options.stdout).rows:24,outputToRender=isStdoutTty&&outputHeight>=viewportRows?output:output+`
1330
- `,previousViewportRows=this.lastTerminalHeight,shouldClearTerminal=shouldClearTerminalForFrame({isStdoutTty,viewportRows,previousViewportRows,previousOutputHeight:this.lastOutputHeight,nextOutputHeight:outputHeight,isUnmounting:this.isUnmounting});if(this.lastTerminalHeight=viewportRows,!shouldClearTerminal&&!hasStaticOutput&&outputToRender===this.lastOutputToRender&&!this.log.isCursorDirty())return;if(this.log.setCursorPosition(this.cursorPosition),shouldClearTerminal){let shouldSync=this.shouldSync();if(shouldSync)this.options.stdout.write(bsu);if(this.alternateScreen)this.options.stdout.write(homeAndEraseDown+this.fullStaticOutput+outputToRender);else if(this.lastOutputHeight>=viewportRows){let erasePrefix=homeAndEraseDown,previousCursor=this.log.getCursorPosition();if(!isWindowsConsole&&previousCursor&&viewportRows<previousViewportRows)erasePrefix=(previousCursor.y>0?cursorUp(previousCursor.y):"")+cursorTo(0)+eraseDown;this.options.stdout.write(erasePrefix+staticOutput+outputToRender)}else this.log.clear(),this.options.stdout.write(staticOutput+outputToRender);if(this.lastOutput=output,this.lastOutputToRender=outputToRender,this.lastOutputHeight=outputHeight,this.log.sync(outputToRender),shouldSync)this.options.stdout.write(esu);return}if(hasStaticOutput){let shouldSync=this.shouldSync();if(shouldSync)this.options.stdout.write(bsu);if(this.log.clear(),this.options.stdout.write(staticOutput),this.log(outputToRender),shouldSync)this.options.stdout.write(esu)}else this.throttledLog(outputToRender);this.lastOutput=output,this.lastOutputToRender=outputToRender,this.lastOutputHeight=outputHeight}initKittyKeyboard(){if(!this.options.kittyKeyboard)return;let options=this.options.kittyKeyboard,mode=options.mode??"auto";if(mode==="disabled")return;let flags=options.flags??["disambiguateEscapeCodes"];if(mode==="enabled"){if(isTty(this.options.stdin)&&this.options.stdout.isTTY)this.enableKittyProtocol(flags);return}if(!this.interactive||!isTty(this.options.stdin)||!this.options.stdout.isTTY)return;this.confirmKittySupport(flags)}confirmKittySupport(flags){let finish=(isSupported)=>{if(this.finishKittyDetection=void 0,clearTimeout(timer),isSupported&&!this.isUnmounted)this.enableKittyProtocol(flags)},timer=setTimeout(()=>{finish(!1)},200);this.finishKittyDetection=finish,this.options.stdout.write("\x1B[?u")}enableKittyProtocol(flags){this.options.stdout.write(`\x1B[>${resolveFlags(flags)}u`),this.kittyProtocolEnabled=!0,this.kittyFlags=flags}beginSuspend(){if(!this.interactive)return;if(this.isSuspended)throw Error("The terminal is already suspended. Resume the current suspension before suspending again.");if(this.finishKittyDetection?.(!1),this.isSuspended=!0,!this.interactive||this.isUnmounted||this.isUnmounting)return;try{let{stdout}=this.options,{canWriteToStdout}=getWritableStreamState(stdout);if(settleThrottle(this.throttledOnRender,canWriteToStdout),settleThrottle(this.throttledLog,canWriteToStdout),canWriteToStdout){if(this.log.clear(),this.log.done(),this.kittyProtocolEnabled)this.writeBestEffort(this.options.stdout,"\x1B[<u"),this.kittyProtocolEnabled=!1;if(this.alternateScreen)this.writeBestEffort(this.options.stdout,exitAlternativeScreen)}this.pauseInput?.()}catch(error){this.isSuspended=!1;try{this.resumeInput?.()}catch{}throw error}}async endSuspend(){if(!this.isSuspended)return;if(this.isSuspended=!1,!this.interactive||this.isUnmounted||this.isUnmounting)return;this.resumeInput?.();let{stdout}=this.options,{canWriteToStdout}=getWritableStreamState(stdout);if(canWriteToStdout){if(this.alternateScreen)this.writeBestEffort(this.options.stdout,enterAlternativeScreen+(this.options.debug?"":this.fullStaticOutput));if(this.kittyFlags)this.writeBestEffort(this.options.stdout,`\x1B[>${resolveFlags(this.kittyFlags)}u`),this.kittyProtocolEnabled=!0}this.lastOutput="",this.lastOutputToRender="",this.lastOutputHeight=0,this.log.reset();try{this.calculateLayout(),this.onRender(),await this.waitUntilRenderFlush()}catch{}}render(node){let tree=$createElement(AccessibilityContext,{value:{isScreenReaderEnabled:this.isScreenReaderEnabled}},$createElement(App_default,{stdin:this.options.stdin,stdout:this.options.stdout,stderr:this.options.stderr,exitOnCtrlC:this.options.exitOnCtrlC,interactive:this.interactive,renderThrottleMs:this.renderThrottleMs,writeToStdout:this.writeToStdout,writeToStderr:this.writeToStderr,setCursorPosition:this.setCursorPosition,onExit:this.handleAppExit,onWaitUntilRenderFlush:this.waitUntilRenderFlush,onSuspendTerminal:this.suspendTerminal,onRegisterInputControl:this.registerInputControl,onKittyQueryResponse:this.handleKittyQueryResponse},$createElement(RootNodeContext_default,{value:this.rootNode},node)));if(this.options.concurrent)reconciler_default.updateContainer(tree,this.container,null,noop4);else reconciler_default.updateContainerSync(tree,this.container,null,noop4),reconciler_default.flushSyncWork()}writeToStdout(data){if(this.isUnmounted||this.isSuspended)return;if(this.options.debug){this.options.stdout.write(data+this.fullStaticOutput+this.lastOutput);return}if(!this.interactive){this.options.stdout.write(data);return}let shouldSync=this.shouldSync();if(shouldSync)this.options.stdout.write(bsu);if(this.log.clear(),this.options.stdout.write(data),this.restoreLastOutput(),shouldSync)this.options.stdout.write(esu)}writeToStderr(data){if(this.isUnmounted||this.isSuspended)return;if(this.options.debug){this.options.stderr.write(data),this.options.stdout.write(this.fullStaticOutput+this.lastOutput);return}if(!this.interactive){this.options.stderr.write(data);return}let shouldSync=this.shouldSync();if(shouldSync)this.options.stdout.write(bsu);if(this.log.clear(),this.options.stderr.write(data),this.restoreLastOutput(),shouldSync)this.options.stdout.write(esu)}unmount(error){if(this.isUnmounted||this.isUnmounting)return;if(this.isUnmounting=!0,this.beforeExitHandler)process24.off("beforeExit",this.beforeExitHandler),this.beforeExitHandler=void 0;let{stdout}=this.options,{canWriteToStdout}=getWritableStreamState(stdout);if(settleThrottle(this.throttledOnRender,canWriteToStdout),canWriteToStdout){if(!this.throttledOnRender||!this.hasPendingThrottledRender&&!this.hasRenderedStaticOutput)this.calculateLayout(),this.onRender()}if(this.isUnmounted=!0,this.unsubscribeExit(),settleThrottle(this.throttledLog,canWriteToStdout),typeof this.restoreConsole==="function")this.restoreConsole();let finishUnmount=()=>{if(typeof this.unsubscribeResize==="function")this.unsubscribeResize();if(this.finishKittyDetection?.(!1),canWriteToStdout){if(this.kittyProtocolEnabled)this.writeBestEffort(this.options.stdout,"\x1B[<u"),this.kittyProtocolEnabled=!1;if(this.interactive&&!this.options.debug)this.log.done();if(this.alternateScreen)this.writeBestEffort(this.options.stdout,exitAlternativeScreen),this.writeBestEffort(this.options.stdout,showCursorEscape),this.alternateScreen=!1;if(!this.interactive)this.options.stdout.write(this.options.debug?`
1331
- `:this.lastOutput+`
1332
- `)}this.kittyProtocolEnabled=!1,instances_default.delete(this.options.stdout),this.rootNode.yogaNode?.free(),this.rootNode.yogaNode=void 0;let{exitResult}=this,resolveOrReject=()=>{if(isErrorInput(error))this.rejectExitPromise(error);else this.resolveExitPromise(exitResult)};if(error!==void 0&&!isErrorInput(error))resolveOrReject();else if(canWriteToStdout)this.options.stdout.write("",resolveOrReject);else setImmediate(resolveOrReject)},concurrentReconciler=reconciler_default;if(this.options.concurrent)reconciler_default.updateContainerSync(null,this.container,null,noop4),reconciler_default.flushSyncWork(),concurrentReconciler.flushPassiveEffects?.(),finishUnmount();else reconciler_default.updateContainerSync(null,this.container,null,noop4),reconciler_default.flushSyncWork(),finishUnmount()}async waitUntilExit(){if(!this.isUnmounting&&!this.beforeExitHandler)this.beforeExitHandler=()=>{this.unmount()},process24.once("beforeExit",this.beforeExitHandler);return this.exitPromise}async waitUntilRenderFlush(){if(this.isUnmounted||this.isUnmounting){await this.awaitExit();return}if(await yieldImmediate(),this.isUnmounted||this.isUnmounting){await this.awaitExit();return}if(this.isConcurrent&&this.hasPendingConcurrentWork()){if(await Promise.race([this.awaitNextRender(),this.awaitExit()]),this.isUnmounted||this.isUnmounting){this.nextRenderCommit=void 0,await this.awaitExit();return}}reconciler_default.flushSyncWork();let{stdout}=this.options,{canWriteToStdout}=getWritableStreamState(stdout);if(settleThrottle(this.throttledOnRender,canWriteToStdout),settleThrottle(this.throttledLog,canWriteToStdout),canWriteToStdout){await new Promise((resolve)=>{this.options.stdout.write("",()=>{resolve()})});return}await yieldImmediate()}clear(){if(!this.interactive||this.options.debug)return;this.log.clear(),this.lastOutputHeight=0}patchConsole(){if(this.options.debug)return;this.restoreConsole=dist_default((stream,data)=>{if(stream==="stdout")this.writeToStdout(data);else if(stream==="stderr"){if(!data.startsWith("The above error occurred"))this.writeToStderr(data)}})}registerInputControl(pauseInput,resumeInput){this.pauseInput=pauseInput,this.resumeInput=resumeInput}async suspendTerminal(callback){if(this.beginSuspend(),callback){try{await callback()}finally{await this.endSuspend()}return}let isResumed=!1,resume=async()=>{if(isResumed)return;isResumed=!0,await this.endSuspend()};return{resume,[Symbol.asyncDispose]:resume}}}var import_signal_exit2,noop4=()=>{},yieldImmediate=async()=>new Promise((resolve)=>{setImmediate(resolve)}),isWindowsConsole,homeAndEraseDown,shouldClearTerminalForFrame=({isStdoutTty,viewportRows,previousViewportRows,previousOutputHeight,nextOutputHeight,isUnmounting})=>{if(!isStdoutTty)return!1;let wasFullscreen=previousOutputHeight>=viewportRows,isFullscreen=nextOutputHeight>=viewportRows;if(isWindowsConsole&&(wasFullscreen||isFullscreen))return!0;let hadPreviousFrame=previousOutputHeight>0,wasOverflowing=previousOutputHeight>viewportRows,isOverflowing=nextOutputHeight>viewportRows,isLeavingFullscreen=wasFullscreen&&nextOutputHeight<viewportRows,isViewportShrinking=viewportRows<previousViewportRows;return wasOverflowing||isOverflowing&&hadPreviousFrame||isLeavingFullscreen||isViewportShrinking&&wasFullscreen||isUnmounting&&wasFullscreen},isErrorInput=(value)=>value instanceof Error||Object.prototype.toString.call(value)==="[object Error]",getWritableStreamState=(stdout)=>({canWriteToStdout:!stdout.destroyed&&!stdout.writableEnded&&(stdout.writable??!0)}),settleThrottle=(throttled,canWriteToStdout)=>{if(throttled===void 0||throttled===null||typeof throttled.flush!=="function")return;let throttledValue=throttled;if(canWriteToStdout)throttledValue.flush();else if(typeof throttledValue.cancel==="function")throttledValue.cancel()};var init_ink=__esm(async()=>{init_react_production();init_compat2();init_ansi_escapes();init_is_in_ci();init_dist7();init_react_reconciler_constants_production();init_wrap_ansi();init_utils5();init_cursor_helpers();init_log_update();init_write_synchronized();init_instances();init_App();init_RootNodeContext();init_AccessibilityContext();init_kitty_keyboard();await __promiseAll([init_src(),init_reconciler(),init_renderer(),init_dom()]);import_signal_exit2=__toESM(require_signal_exit(),1),isWindowsConsole=process24.platform==="win32",homeAndEraseDown=cursorTo(0,0)+eraseDown});import{Stream as Stream3}from"node:stream";import process25 from"node:process";var render=(node,options)=>{let{stdout=process25.stdout,stdin=process25.stdin,stderr=process25.stderr,exitOnCtrlC=!0,patchConsole=!0,...renderOptions}=getOptions(options),inkOptions={stdout,stdin,stderr,debug:!1,exitOnCtrlC,patchConsole,maxFps:30,incrementalRendering:!1,concurrent:!1,alternateScreen:!1,...renderOptions},instance=getInstance(inkOptions.stdout,()=>new Ink(inkOptions));return instance.render(node),{rerender:instance.render,unmount(){instance.unmount()},waitUntilExit:instance.waitUntilExit,waitUntilRenderFlush:instance.waitUntilRenderFlush,cleanup(){instance.unmount()},clear:instance.clear}},render_default,getOptions=(stdout={})=>{if(stdout instanceof Stream3)return{stdout,stdin:process25.stdin};return stdout},getInstance=(stdout,createInstance)=>{let instance=instances_default.get(stdout);if(instance===void 0){let newInstance=createInstance();return instances_default.set(stdout,newInstance),newInstance}return process25.stderr.write(`Warning: render() was called again for the same stdout before the previous Ink instance was unmounted. Reusing stdout across multiple render() calls is unsupported. Call unmount() first.
1333
- `),instance};var init_render=__esm(async()=>{init_instances();await init_ink();render_default=render});var init_render_to_string=__esm(async()=>{init_react_production();init_react_reconciler_constants_production();init_RootNodeContext();await __promiseAll([init_src(),init_reconciler(),init_renderer(),init_dom()])});function Static(props){let{items,children:render,style:customStyle}=props,[index,setIndex]=$useState(0),inheritedBackgroundColor=$use(BackgroundContext),effectiveBackgroundColor=customStyle?.backgroundColor||inheritedBackgroundColor,itemsToRender=$useMemo(()=>items.slice(index),[items,index]);$useLayoutEffect(()=>{setIndex(items.length)},[items.length]);let children=itemsToRender.map((item,itemIndex)=>render(item,index+itemIndex)),style=$useMemo(()=>({position:"absolute",flexDirection:"column",...customStyle,display:itemsToRender.length>0?customStyle?.display:"none"}),[customStyle,itemsToRender.length]);return $createElement(BackgroundContext,{value:effectiveBackgroundColor},$createElement("ink-box",{internal_static:!0,style},children))}var init_Static=__esm(()=>{init_react_production();init_BackgroundContext()});var init_Transform=__esm(()=>{init_react_production();init_AccessibilityContext()});var init_Newline=__esm(()=>{init_react_production()});var init_Spacer=__esm(()=>{init_react_production();init_Box()});var useStdinContext=()=>$use(StdinContext_default);var init_use_stdin=__esm(()=>{init_react_production();init_StdinContext()});var useInput=(inputHandler,options={})=>{let{setRawMode,internal_exitOnCtrlC,internal_eventEmitter}=useStdinContext();$useEffect(()=>{if(options.isActive===!1)return;return setRawMode(!0),()=>{setRawMode(!1)}},[options.isActive,setRawMode]);let handleData=$useEffectEvent((data)=>{let keypress=parse_keypress_default(data),key={upArrow:keypress.name==="up",downArrow:keypress.name==="down",leftArrow:keypress.name==="left",rightArrow:keypress.name==="right",pageDown:keypress.name==="pagedown",pageUp:keypress.name==="pageup",home:keypress.name==="home",end:keypress.name==="end",return:keypress.name==="return",escape:keypress.name==="escape",ctrl:keypress.ctrl,shift:keypress.shift,tab:keypress.name==="tab",backspace:keypress.name==="backspace",delete:keypress.name==="delete",meta:keypress.meta,super:keypress.super??!1,hyper:keypress.hyper??!1,capsLock:keypress.capsLock??!1,numLock:keypress.numLock??!1,eventType:keypress.eventType},input;if(keypress.isKittyProtocol)input=keypress.isPrintable?keypress.text??keypress.name:"";else if(keypress.ctrl)input=keypress.name==="space"?" ":keypress.name??"";else input=keypress.sequence;if(!keypress.isKittyProtocol&&nonAlphanumericKeys.includes(keypress.name))input="";if(input.startsWith("\x1B"))input=input.slice(1);if(!keypress.isKittyProtocol&&input.length===1&&/[A-Z]/.test(input))key.shift=!0;if(internal_exitOnCtrlC&&keypress.name==="c"&&key.ctrl&&keypress.eventType!=="release")return;reconciler_default.discreteUpdates(()=>{inputHandler(input,key)})});$useEffect(()=>{if(options.isActive===!1)return;return internal_eventEmitter.on("input",handleData),()=>{internal_eventEmitter.removeListener("input",handleData)}},[options.isActive,internal_eventEmitter])},use_input_default;var init_use_input=__esm(async()=>{init_react_production();init_parse_keypress();init_use_stdin();await init_reconciler();use_input_default=useInput});var usePaste=(handler,options={})=>{let{setRawMode,setBracketedPasteMode,internal_eventEmitter}=useStdinContext();$useEffect(()=>{if(options.isActive===!1)return;return setRawMode(!0),setBracketedPasteMode(!0),()=>{setRawMode(!1),setBracketedPasteMode(!1)}},[options.isActive,setRawMode,setBracketedPasteMode]);let handlePaste=$useEffectEvent((text)=>{reconciler_default.discreteUpdates(()=>{handler(text)})});$useEffect(()=>{if(options.isActive===!1)return;return internal_eventEmitter.on("paste",handlePaste),()=>{internal_eventEmitter.removeListener("paste",handlePaste)}},[options.isActive,internal_eventEmitter])},use_paste_default;var init_use_paste=__esm(async()=>{init_react_production();init_use_stdin();await init_reconciler();use_paste_default=usePaste});function useApp(){return $use(AppContext_default)}var init_use_app=__esm(()=>{init_react_production();init_AppContext()});function useStdout(){return $use(StdoutContext_default)}var init_use_stdout=__esm(()=>{init_react_production();init_StdoutContext()});var init_use_stderr=__esm(()=>{init_react_production();init_StderrContext()});var init_use_focus=__esm(()=>{init_react_production();init_FocusContext();init_use_stdin()});var init_use_focus_manager=__esm(()=>{init_react_production();init_FocusContext()});var init_use_is_screen_reader_enabled=__esm(()=>{init_react_production();init_AccessibilityContext()});var useCursor=()=>{let context=$use(CursorContext_default),positionRef=$useRef(void 0),setCursorPosition=$useCallback((position)=>{positionRef.current=position},[]);return $useInsertionEffect(()=>(context.setCursorPosition(positionRef.current),()=>{context.setCursorPosition(void 0)})),{setCursorPosition}},use_cursor_default;var init_use_cursor=__esm(()=>{init_react_production();init_CursorContext();use_cursor_default=useCursor});var init_use_animation=__esm(()=>{init_react_production();init_AnimationContext()});var useWindowSize=()=>{let{stdout}=useStdout(),[size,setSize]=$useState(()=>getWindowSize(stdout));return $useEffect(()=>{let onResize=()=>{setSize(getWindowSize(stdout))};return stdout.on("resize",onResize),onResize(),()=>{stdout.off("resize",onResize)}},[stdout]),size},use_window_size_default;var init_use_window_size=__esm(()=>{init_react_production();init_utils5();init_use_stdout();use_window_size_default=useWindowSize});var emptyOutput,measureElement=(node)=>{let{yogaNode}=node;if(!yogaNode)return emptyOutput;let x=yogaNode.getComputedLeft(),y=yogaNode.getComputedTop(),current=node.parentNode;while(current){if(current.yogaNode)x+=current.yogaNode.getComputedLeft(),y+=current.yogaNode.getComputedTop();current=current.parentNode}let width=yogaNode.getComputedWidth(),height=yogaNode.getComputedHeight(),borderLeft=yogaNode.getComputedBorder(src_default.EDGE_LEFT),borderTop=yogaNode.getComputedBorder(src_default.EDGE_TOP),clientWidth=width-borderLeft-yogaNode.getComputedBorder(src_default.EDGE_RIGHT),clientHeight=height-borderTop-yogaNode.getComputedBorder(src_default.EDGE_BOTTOM);return{x,y,width,height,clientWidth,clientHeight}},measure_element_default;var init_measure_element=__esm(async()=>{await init_src();emptyOutput={x:0,y:0,width:0,height:0,clientWidth:0,clientHeight:0},measure_element_default=measureElement});var emptyMetrics,useBoxMetrics=(ref)=>{let rootNode=$use(RootNodeContext_default),[metrics,setMetrics]=$useState(emptyMetrics),[hasMeasured,setHasMeasured]=$useState(!1),updateMetrics=$useCallback(()=>{let node=ref.current,layout=node?.yogaNode?.getComputedLayout(),nextMetrics=emptyMetrics;if(node&&layout){let{width,height,clientWidth,clientHeight}=measure_element_default(node);nextMetrics={width,height,left:layout.left,top:layout.top,clientWidth,clientHeight}}setMetrics((previousMetrics)=>Object.keys(nextMetrics).some((key)=>previousMetrics[key]!==nextMetrics[key])?nextMetrics:previousMetrics),setHasMeasured(Boolean(node))},[ref]);return $useEffect(updateMetrics),$useEffect(()=>{if(!rootNode)return;return addLayoutListener(rootNode,()=>{queueMicrotask(updateMetrics)})},[rootNode,updateMetrics]),$useMemo(()=>({...metrics,hasMeasured}),[metrics,hasMeasured])},use_box_metrics_default;var init_use_box_metrics=__esm(async()=>{init_react_production();init_RootNodeContext();await __promiseAll([init_dom(),init_measure_element()]);emptyMetrics={width:0,height:0,left:0,top:0,clientWidth:0,clientHeight:0},use_box_metrics_default=useBoxMetrics});var init_build4=__esm(async()=>{init_Box();init_Text();init_Static();init_Transform();init_Newline();init_Spacer();init_use_app();init_use_stdin();init_use_stdout();init_use_stderr();init_use_focus();init_use_focus_manager();init_use_is_screen_reader_enabled();init_use_cursor();init_use_animation();init_use_window_size();init_kitty_keyboard();await __promiseAll([init_render(),init_render_to_string(),init_use_input(),init_use_paste(),init_use_box_metrics(),init_measure_element()])});var MIRO_LOGO_ROWS,MIRO_LOGO,BLACK_CIRCLE,BLACK_CIRCLE_PLAIN="●",TREE_LAST_PLAIN="└",TREE_LAST="└",TREE_LAST_PREFIX,TREE_MID_PREFIX,TREE_VERTICAL_PREFIX,TREE_BLANK_PREFIX=" ";var init_figures=__esm(()=>{MIRO_LOGO_ROWS=[[[" ▗█","#77818d"],["▀","yellow"],["▙","#77818d"],["▸","yellow"]],[[" ▟","#77818d"],["▌","yellow"],["██▐","#f5f2e9"],["▙","#77818d"]],[[" ▝","#77818d"],["▟","yellow"],["██","#f5f2e9"],["▙","yellow"],["▘","#77818d"]]],MIRO_LOGO=MIRO_LOGO_ROWS.map((row)=>row.map(([glyphs])=>glyphs).join("")).join(`
1276
+ `);if(lfIndex!==-1)string=stringEncaseCRLFWithFirstIndex(string,closeAll,openAll,lfIndex);return openAll+string+closeAll},chalk,chalkStderr,source_default;var init_source2=__esm(()=>{init_ansi_styles2();init_supports_color();({stdout:stdoutColor,stderr:stderrColor}=supports_color_default),GENERATOR=Symbol("GENERATOR"),STYLER=Symbol("STYLER"),IS_EMPTY=Symbol("IS_EMPTY"),LEVEL=Symbol("LEVEL"),styles3=Object.create(null),levelDescriptor={enumerable:!0,get(){return this[LEVEL]},set(level){assertValidLevel(level),this[LEVEL]=level}};Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(let[styleName,style]of Object.entries(ansi_styles_default2))styles3[styleName]={get(){let builder=createBuilder(this,createStyler(style.open,style.close,this[STYLER]),this[IS_EMPTY]);return Object.defineProperty(this,styleName,{value:builder}),builder}};styles3.visible={get(){let builder=createBuilder(this,this[STYLER],!0);return Object.defineProperty(this,"visible",{value:builder}),builder}};usedModels=["rgb","hex","ansi256"];for(let model of usedModels){let capitalizedModel=model[0].toUpperCase()+model.slice(1);for(let[styleName,type]of[[model,"color"],["bg"+capitalizedModel,"bgColor"],["underline"+capitalizedModel,"underlineColor"]]){let{close}=ansi_styles_default2[type],converters=createModelConverters(model,type);styles3[styleName]={get(){let styleFunction=function(first,second,third){let open=converters[this.level](first,second,third);return createBuilder(this,createStyler(open,close,this[STYLER]),this[IS_EMPTY])};return Object.defineProperty(this,styleName,{value:styleFunction}),styleFunction}}}}proto=Object.defineProperties(()=>{},{...styles3,level:{enumerable:!0,get(){return this[GENERATOR].level},set(level){this[GENERATOR].level=level}}});Object.defineProperties(createChalk.prototype,{...styles3,level:levelDescriptor});chalk=createChalk(),chalkStderr=createChalk({level:stderrColor?stderrColor.level:0}),source_default=chalk});function createStore(init){let state,listeners=new Set,setState=(partial,replace=!1)=>{let next=typeof partial==="function"?partial(state):partial;if(Object.is(next,state))return;let previous=state;state=replace?next:Object.assign({},state,next);for(let listener of listeners)listener(state,previous)},getState=()=>state,subscribe=(listener)=>(listeners.add(listener),()=>listeners.delete(listener));return state=init(setState,getState),{getState,setState,subscribe}}import os10 from"node:os";import path26 from"node:path";import process15 from"node:process";function extractToolPreview(content){if(!Array.isArray(content))return null;let texts=[];for(let block of content)if(block?.type==="content"&&block.content?.type==="text"&&typeof block.content.text==="string")texts.push(block.content.text);if(texts.length===0)return null;let joined=texts.join(`
1277
+ `).replace(/\n+$/,"");if(joined.trim().length===0)return null;let lines=joined.split(`
1278
+ `),shown=lines.slice(0,TOOL_PREVIEW_MAX_LINES).map((line)=>line.length>PREVIEW_LINE_MAX_CHARS?`${line.slice(0,PREVIEW_LINE_MAX_CHARS-1)}…`:line);return{lines:shown,more:Math.max(0,lines.length-shown.length)}}function extractToolOutputPreview(rawOutput){if(rawOutput==null||typeof rawOutput!=="object")return null;let texts=[rawOutput.stdout,rawOutput.stderr].filter((text)=>typeof text==="string"&&text.trim().length>0);if(texts.length===0)return null;return extractToolPreview([{type:"content",content:{type:"text",text:texts.join(`
1279
+ `)}}])}function extractOutputText(rawOutput){if(rawOutput==null||typeof rawOutput!=="object")return"";return[rawOutput.stdout,rawOutput.stderr].filter((text)=>typeof text==="string"&&text.trim().length>0).join(`
1280
+ `)}function firstNonEmptyLine(text){if(typeof text!=="string")return"";for(let line of text.replace(/\r\n?/g,`
1281
+ `).split(`
1282
+ `)){let flat=line.trim();if(flat.length>0)return flat}return""}function truncatePreviewLine(text){return text.length>PREVIEW_LINE_MAX_CHARS?`${text.slice(0,PREVIEW_LINE_MAX_CHARS-1)}…`:text}function commandText(rawInput){let command=rawInput?.command;if(typeof command!=="string")return null;let normalized=command.replace(/\r\n?/g,`
1283
+ `).replace(/\n+$/,"");if(normalized.trim().length===0)return null;return normalized.length>COMMAND_TEXT_MAX_CHARS?`${normalized.slice(0,COMMAND_TEXT_MAX_CHARS)}…`:normalized}function textContent4(content){if(!Array.isArray(content))return"";return content.filter((block)=>block?.type==="content"&&block.content?.type==="text"&&typeof block.content.text==="string").map((block)=>block.content.text).join(`
1284
+ `)}function clippedDetail(text){let value=String(text??"").replace(/\r\n?/g,`
1285
+ `).replace(/\n+$/,"");if(value.length<=TOOL_DETAIL_MAX_CHARS)return value;return`${value.slice(0,TOOL_DETAIL_MAX_CHARS)}
1286
+ … detail truncated`}function safeJson2(value){if(value==null)return"";if(typeof value==="string")return clippedDetail(value);try{return clippedDetail(JSON.stringify(value,(key,item)=>{if(key==="data"&&typeof item==="string"&&item.length>120)return`[binary data: ${item.length} chars]`;return item},2))}catch{return clippedDetail(String(value))}}function buildToolDetail(info={}){let output=extractOutputText(info.rawOutput)||textContent4(info.content);return{kind:info.kind??null,title:typeof info.title==="string"?info.title:null,input:safeJson2(info.rawInput),output:clippedDetail(output),locations:safeJson2(info.locations)}}function imageContent(content){if(!Array.isArray(content))return null;return content.find((block)=>block?.type==="content"&&block.content?.type==="image")?.content??null}function imageBytes(image){for(let key of["bytes","byteLength","size","fileSize"])if(typeof image?.[key]==="number"&&Number.isFinite(image[key])&&image[key]>=0)return image[key];if(typeof image?.data!=="string"||image.data.length===0)return null;let padding=image.data.endsWith("==")?2:image.data.endsWith("=")?1:0;return Math.max(0,Math.floor(image.data.length*3/4)-padding)}function formatImageBytes(bytes){if(bytes==null)return"";if(bytes<1024)return`${bytes}B`;if(bytes<1048576)return`${Math.round(bytes/1024)}KB`;return`${Math.round(bytes/1048576)}MB`}function summarizeReadResult(info={}){let outputText=extractOutputText(info.rawOutput),contentText=textContent4(info.content),text=outputText||contentText;if(info.status==="failed"){let error=firstNonEmptyLine(text);return error?{lines:[truncatePreviewLine(error)],more:0}:null}if(text.trim().length>0){let lines=text.replace(/\r\n?/g,`
1287
+ `).replace(/\n+$/,"").split(`
1288
+ `);return{lines:[`Read ${lines.length} ${lines.length===1?"line":"lines"}`],more:0}}let image=imageContent(info.content);if(!image)return null;let size=formatImageBytes(imageBytes(image));return{lines:[`Read image${size?` (${size})`:""}`],more:0}}function summarizeEditResult(info={}){if(info.status==="failed"){let error=firstNonEmptyLine(extractOutputText(info.rawOutput)||textContent4(info.content));return error?{lines:[truncatePreviewLine(error)],more:0}:null}let applyContent=info.rawInput?.apply_content,text=typeof applyContent==="string"&&applyContent.length>0?applyContent:textContent4(info.content);if(text.trim().length===0)return null;let lines=text.replace(/\r\n?/g,`
1289
+ `).replace(/\n+$/,"").split(`
1290
+ `);return{lines:[`Wrote ${lines.length} ${lines.length===1?"line":"lines"}`],more:0}}function summarizeQuestionResult(info){let output=extractOutputText(info.rawOutput)||textContent4(info.content),result;try{result=JSON.parse(output)}catch{return null}if(!result?.answers||typeof result.answers!=="object"||Array.isArray(result.answers))return null;let questions=Array.isArray(info.rawInput?.questions)?info.rawInput.questions:[],lines=[];for(let[id,answer]of Object.entries(result.answers)){if(typeof answer!=="string"||!answer.trim())continue;let question=questions.find((item)=>item?.id===id),title=question?.header||question?.question||id,notes=result.annotations?.[id]?.notes,summary=`${title}: ${answer}${typeof notes==="string"&&notes.trim()?` (${notes})`:""}`.replace(/\s+/g," ").trim();lines.push(truncatePreviewLine(summary))}return lines.length>0?{lines,more:0}:null}function restoreQuestionPreview(tool){if(tool?.label?.name!=="Question"||tool.preview?.lines?.length!==1||tool.preview.lines[0]!=="{"||typeof tool.detail?.output!=="string")return null;let rawInput;try{rawInput=JSON.parse(tool.detail.input)}catch{return null}return summarizeQuestionResult({rawInput,content:[{type:"content",content:{type:"text",text:tool.detail.output}}]})}function summarizeToolResult(info={}){if(info.kind==="read"||info.kind==null&&info.name==="Read")return summarizeReadResult(info);if(info.kind==="execute")return extractToolOutputPreview(info.rawOutput)??extractToolPreview(info.content);if(info.kind==="edit"||info.kind==null&&info.name==="Edit")return summarizeEditResult(info);if(info.name==="request_user_input"||info.title==="Question"){let summary=summarizeQuestionResult(info);if(summary)return summary}let text=firstNonEmptyLine(extractOutputText(info.rawOutput)||textContent4(info.content));return text?{lines:[truncatePreviewLine(text)],more:0}:null}function preferredDisplayName(name,kind,title){let wire=typeof name==="string"?name.trim():"",byKind=KIND_NAMES[kind]??"",byTitle=typeof title==="string"?title.trim():"";if(wire&&WIRE_TOOL_NAME.test(wire))return byKind||byTitle||wire;if(wire&&byTitle&&wire.toLowerCase()===byTitle.toLowerCase())return byTitle;return wire||byKind||byTitle||"Tool"}function displayPath(filePath){if(typeof filePath!=="string"||filePath.length===0)return"";try{let relativePath=path26.relative(process15.cwd(),filePath);if(relativePath&&!relativePath.startsWith("..")&&!path26.isAbsolute(relativePath))return relativePath;let home=os10.homedir();if(home&&filePath.startsWith(home+path26.sep))return`~${filePath.slice(home.length)}`}catch{}return filePath}function truncate3(text){let flat=text.replace(/\s*\n\s*/g," ").trim();if(flat.length<=MAX_ARGS_DISPLAY_CHARS)return flat;return`${flat.slice(0,MAX_ARGS_DISPLAY_CHARS-1)}…`}function pickString(input,keys){if(input==null||typeof input!=="object")return null;for(let key of keys){let value=input[key];if(typeof value==="string"&&value.trim().length>0)return value}return null}function formatToolLabel(info){let{name,kind,title,rawInput,locations}=info??{};if(name==="mcp_call"||name==="mcp_list_tools"){let target=[rawInput?.server,name==="mcp_call"?rawInput?.name:rawInput?.query].filter((value)=>typeof value==="string"&&value.length>0).join(" / ");return{name:name==="mcp_call"?"MCP":"MCP tools",args:truncate3(target)}}if(rawInput?.tool_call_name==="spawn_agent"){let agentName=typeof rawInput.sub_content==="string"&&rawInput.sub_content.trim()||typeof title==="string"&&title.trim()||"子智能体",summary=(typeof rawInput.message==="string"?rawInput.message:"").split(`
1291
+ `).map((line)=>line.trim()).find((line)=>line.length>0)??"";return{name:truncate3(agentName),args:truncate3(summary)}}let displayName=preferredDisplayName(name,kind,title),args="";if((name==="request_user_input"||title==="Question")&&Array.isArray(rawInput?.questions))args=rawInput.questions.map((question)=>question?.question).filter((question)=>typeof question==="string"&&question.trim()).join(" | ");let location2=Array.isArray(locations)?locations[0]:null,pathArg=pickString(rawInput,PATH_KEYS),commandArg=pickString(rawInput,COMMAND_KEYS);if(!args&&(kind==="search"&&commandArg))args=commandArg;else if(!args&&location2&&typeof location2.path==="string"&&location2.path.length>0){if(args=displayPath(location2.path),typeof location2.line==="number")args+=`:${location2.line}`}else if(!args&&pathArg)args=displayPath(pathArg);else if(!args&&commandArg)args=commandArg;else if(!args&&typeof title==="string"&&title.trim()&&title.trim()!==displayName)args=title.trim();return{name:truncate3(displayName),args:truncate3(args)}}var TERMINAL_STATUSES,TOOL_PREVIEW_MAX_LINES=5,COMMAND_TEXT_MAX_CHARS=1e4,PREVIEW_LINE_MAX_CHARS=200,TOOL_DETAIL_MAX_CHARS=200000,KIND_NAMES,WIRE_TOOL_NAME,PATH_KEYS,COMMAND_KEYS,MAX_ARGS_DISPLAY_CHARS=160;var init_tool_title=__esm(()=>{TERMINAL_STATUSES=new Set(["completed","failed","cancelled"]);KIND_NAMES={read:"Read",edit:"Edit",execute:"Bash",search:"Search",fetch:"Fetch",think:"Think",delete:"Delete",move:"Move"},WIRE_TOOL_NAME=/^[a-z0-9]+(?:_[a-z0-9]+)+$/;PATH_KEYS=["path","file_path","filePath","abs_path","filename","url","uri","sub_content_event_value"],COMMAND_KEYS=["command","query","pattern","search_term","sub_content"]});function parsePatch(uniDiff){let diffstr=uniDiff.split(/\n/),list=[],i=0;function isGitDiffHeader(line){return/^diff --git /.test(line)}function isDiffHeader(line){return isGitDiffHeader(line)||/^Index:\s/.test(line)||/^diff(?: -r \w+)+\s/.test(line)}function isFileHeader(line){return/^(---|\+\+\+)\s/.test(line)}function isHunkHeader(line){return/^@@\s/.test(line)}function parseIndex(){var _a;let index={};index.hunks=[],list.push(index);let seenDiffHeader=!1;while(i<diffstr.length){let line=diffstr[i];if(isFileHeader(line)||isHunkHeader(line))break;if(isGitDiffHeader(line)){if(seenDiffHeader)return;seenDiffHeader=!0,index.isGit=!0;let paths=parseGitDiffHeader(line);if(paths)index.oldFileName=paths.oldFileName,index.newFileName=paths.newFileName;i++;while(i<diffstr.length){let extLine=diffstr[i];if(isFileHeader(extLine)||isHunkHeader(extLine)||isDiffHeader(extLine))break;let renameFromMatch=/^rename from (.*)/.exec(extLine);if(renameFromMatch)index.oldFileName="a/"+unquoteIfQuoted(renameFromMatch[1]),index.isRename=!0;let renameToMatch=/^rename to (.*)/.exec(extLine);if(renameToMatch)index.newFileName="b/"+unquoteIfQuoted(renameToMatch[1]),index.isRename=!0;let copyFromMatch=/^copy from (.*)/.exec(extLine);if(copyFromMatch)index.oldFileName="a/"+unquoteIfQuoted(copyFromMatch[1]),index.isCopy=!0;let copyToMatch=/^copy to (.*)/.exec(extLine);if(copyToMatch)index.newFileName="b/"+unquoteIfQuoted(copyToMatch[1]),index.isCopy=!0;let newFileModeMatch=/^new file mode (\d+)/.exec(extLine);if(newFileModeMatch)index.isCreate=!0,index.newMode=newFileModeMatch[1];let deletedFileModeMatch=/^deleted file mode (\d+)/.exec(extLine);if(deletedFileModeMatch)index.isDelete=!0,index.oldMode=deletedFileModeMatch[1];let oldModeMatch=/^old mode (\d+)/.exec(extLine);if(oldModeMatch)index.oldMode=oldModeMatch[1];let newModeMatch=/^new mode (\d+)/.exec(extLine);if(newModeMatch)index.newMode=newModeMatch[1];if(/^Binary files /.test(extLine))index.isBinary=!0;i++}continue}else if(isDiffHeader(line)){if(seenDiffHeader)return;seenDiffHeader=!0;let headerMatch=/^(?:Index:|diff(?: -r \w+)+)\s+/.exec(line);if(headerMatch)index.index=line.substring(headerMatch[0].length).trim()}i++}if(parseFileHeader(index),parseFileHeader(index),index.oldFileName===void 0!==(index.newFileName===void 0))throw Error("Missing "+(index.oldFileName!==void 0?'"+++ ..."':'"--- ..."')+" file header for "+((_a=index.oldFileName)!==null&&_a!==void 0?_a:index.newFileName));while(i<diffstr.length){let line=diffstr[i];if(isDiffHeader(line)||isFileHeader(line)||/^===================================================================/.test(line))break;else if(isHunkHeader(line))index.hunks.push(parseHunk());else i++}}function parseGitDiffHeader(line){let rest=line.substring(11);if(rest.startsWith('"')){let oldPath=parseQuotedFileName(rest);if(oldPath===null)return null;let afterOld=rest.substring(oldPath.rawLength+1),newFileName;if(afterOld.startsWith('"')){let newPath=parseQuotedFileName(afterOld);if(newPath===null)return null;newFileName=newPath.fileName}else newFileName=afterOld;return{oldFileName:oldPath.fileName,newFileName}}let quoteIdx=rest.indexOf('"');if(quoteIdx>0){let oldFileName=rest.substring(0,quoteIdx-1),newPath=parseQuotedFileName(rest.substring(quoteIdx));if(newPath===null)return null;return{oldFileName,newFileName:newPath.fileName}}if(rest.startsWith("a/")){let splits=[],idx=0;while(!0){if(idx=rest.indexOf(" b/",idx+1),idx===-1)break;splits.push(idx)}if(splits.length>0){let mid=splits[Math.floor(splits.length/2)];return{oldFileName:rest.substring(0,mid),newFileName:rest.substring(mid+1)}}}return null}function unquoteIfQuoted(s){if(s.startsWith('"')){let parsed=parseQuotedFileName(s);if(parsed)return parsed.fileName}return s}function parseQuotedFileName(s){if(!s.startsWith('"'))return null;let result="",j=1;while(j<s.length){if(s[j]==='"')return{fileName:result,rawLength:j+1};if(s[j]==="\\"&&j+1<s.length)switch(j++,s[j]){case"a":result+="\x07";break;case"b":result+="\b";break;case"f":result+="\f";break;case"n":result+=`
1292
+ `;break;case"r":result+="\r";break;case"t":result+="\t";break;case"v":result+="\v";break;case"\\":result+="\\";break;case'"':result+='"';break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{if(j+2>=s.length||s[j+1]<"0"||s[j+1]>"7"||s[j+2]<"0"||s[j+2]>"7")return null;let bytes=[parseInt(s.substring(j,j+3),8)];j+=3;while(s[j]==="\\"&&s[j+1]>="0"&&s[j+1]<="7"){if(j+3>=s.length||s[j+2]<"0"||s[j+2]>"7"||s[j+3]<"0"||s[j+3]>"7")return null;bytes.push(parseInt(s.substring(j+1,j+4),8)),j+=4}result+=new TextDecoder("utf-8").decode(new Uint8Array(bytes));continue}default:return null}else result+=s[j];j++}return null}function parseFileHeader(index){let fileHeaderMatch=/^(---|\+\+\+)\s+/.exec(diffstr[i]);if(fileHeaderMatch){let prefix=fileHeaderMatch[1],data=diffstr[i].substring(3).trim().split("\t",2),header=(data[1]||"").trim(),fileName=data[0];if(fileName.startsWith('"'))fileName=unquoteIfQuoted(fileName);else fileName=fileName.replace(/\\\\/g,"\\");if(prefix==="---")index.oldFileName=fileName,index.oldHeader=header;else index.newFileName=fileName,index.newHeader=header;i++}}function parseHunk(){var _a;let chunkHeaderIndex=i,chunkHeaderLine=diffstr[i++],chunkHeader=chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/),hunk={oldStart:+chunkHeader[1],oldLines:typeof chunkHeader[2]>"u"?1:+chunkHeader[2],newStart:+chunkHeader[3],newLines:typeof chunkHeader[4]>"u"?1:+chunkHeader[4],lines:[]};if(hunk.oldLines===0)hunk.oldStart+=1;if(hunk.newLines===0)hunk.newStart+=1;let addCount=0,removeCount=0;for(;i<diffstr.length&&(removeCount<hunk.oldLines||addCount<hunk.newLines||((_a=diffstr[i])===null||_a===void 0?void 0:_a.startsWith("\\")));i++){let operation=diffstr[i].length==0&&i!=diffstr.length-1?" ":diffstr[i][0];if(operation==="+"||operation==="-"||operation===" "||operation==="\\"){if(hunk.lines.push(diffstr[i]),operation==="+")addCount++;else if(operation==="-")removeCount++;else if(operation===" ")addCount++,removeCount++}else throw Error(`Hunk at line ${chunkHeaderIndex+1} contained invalid line ${diffstr[i]}`)}if(!addCount&&hunk.newLines===1)hunk.newLines=0;if(!removeCount&&hunk.oldLines===1)hunk.oldLines=0;if(addCount!==hunk.newLines)throw Error("Added line count did not match for hunk at line "+(chunkHeaderIndex+1));if(removeCount!==hunk.oldLines)throw Error("Removed line count did not match for hunk at line "+(chunkHeaderIndex+1));if(i<diffstr.length&&diffstr[i]&&/^[+ -]/.test(diffstr[i])&&!isFileHeader(diffstr[i]))throw Error("Hunk at line "+(chunkHeaderIndex+1)+" has more lines than expected (expected "+hunk.oldLines+" old lines and "+hunk.newLines+" new lines)");return hunk}while(i<diffstr.length)parseIndex();return list}class Diff2{diff(oldStr,newStr,options={}){let callback;if(typeof options==="function")callback=options,options={};else if("callback"in options)callback=options.callback;let oldString=this.castInput(oldStr,options),newString=this.castInput(newStr,options),oldTokens=this.removeEmpty(this.tokenize(oldString,options)),newTokens=this.removeEmpty(this.tokenize(newString,options));return this.diffWithOptionsObj(oldTokens,newTokens,options,callback)}diffWithOptionsObj(oldTokens,newTokens,options,callback){var _a;let done=(value)=>{if(value=this.postProcess(value,options),callback){setTimeout(function(){callback(value)},0);return}else return value},newLen=newTokens.length,oldLen=oldTokens.length,editLength=1,maxEditLength=newLen+oldLen;if(options.maxEditLength!=null)maxEditLength=Math.min(maxEditLength,options.maxEditLength);let maxExecutionTime=(_a=options.timeout)!==null&&_a!==void 0?_a:1/0,abortAfterTimestamp=Date.now()+maxExecutionTime,bestPath=[{oldPos:-1,lastComponent:void 0}],newPos=this.extractCommon(bestPath[0],newTokens,oldTokens,0,options);if(bestPath[0].oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(bestPath[0].lastComponent,newTokens,oldTokens));let minDiagonalToConsider=-1/0,maxDiagonalToConsider=1/0,execEditLength=()=>{for(let diagonalPath=Math.max(minDiagonalToConsider,-editLength);diagonalPath<=Math.min(maxDiagonalToConsider,editLength);diagonalPath+=2){let basePath,removePath=bestPath[diagonalPath-1],addPath=bestPath[diagonalPath+1];if(removePath)bestPath[diagonalPath-1]=void 0;let canAdd=!1;if(addPath){let addPathNewPos=addPath.oldPos-diagonalPath;canAdd=addPath&&0<=addPathNewPos&&addPathNewPos<newLen}let canRemove=removePath&&removePath.oldPos+1<oldLen;if(!canAdd&&!canRemove){bestPath[diagonalPath]=void 0;continue}if(!canRemove||canAdd&&removePath.oldPos<addPath.oldPos)basePath=this.addToPath(addPath,!0,!1,0,options);else basePath=this.addToPath(removePath,!1,!0,1,options);if(newPos=this.extractCommon(basePath,newTokens,oldTokens,diagonalPath,options),basePath.oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(basePath.lastComponent,newTokens,oldTokens))||!0;else{if(bestPath[diagonalPath]=basePath,basePath.oldPos+1>=oldLen)maxDiagonalToConsider=Math.min(maxDiagonalToConsider,diagonalPath-1);if(newPos+1>=newLen)minDiagonalToConsider=Math.max(minDiagonalToConsider,diagonalPath+1)}}editLength++};if(callback)(function exec(){setTimeout(function(){if(editLength>maxEditLength||Date.now()>abortAfterTimestamp)return callback(void 0);if(!execEditLength())exec()},0)})();else while(editLength<=maxEditLength&&Date.now()<=abortAfterTimestamp){let ret=execEditLength();if(ret)return ret}}addToPath(path,added,removed,oldPosInc,options){let last=path.lastComponent;if(last&&!options.oneChangePerToken&&last.added===added&&last.removed===removed)return{oldPos:path.oldPos+oldPosInc,lastComponent:{count:last.count+1,added,removed,previousComponent:last.previousComponent}};else return{oldPos:path.oldPos+oldPosInc,lastComponent:{count:1,added,removed,previousComponent:last}}}extractCommon(basePath,newTokens,oldTokens,diagonalPath,options){let newLen=newTokens.length,oldLen=oldTokens.length,oldPos=basePath.oldPos,newPos=oldPos-diagonalPath,commonCount=0;while(newPos+1<newLen&&oldPos+1<oldLen&&this.equals(oldTokens[oldPos+1],newTokens[newPos+1],options))if(newPos++,oldPos++,commonCount++,options.oneChangePerToken)basePath.lastComponent={count:1,previousComponent:basePath.lastComponent,added:!1,removed:!1};if(commonCount&&!options.oneChangePerToken)basePath.lastComponent={count:commonCount,previousComponent:basePath.lastComponent,added:!1,removed:!1};return basePath.oldPos=oldPos,newPos}equals(left,right,options){if(options.comparator)return options.comparator(left,right);else return left===right||!!options.ignoreCase&&left.toLowerCase()===right.toLowerCase()}removeEmpty(array){let ret=[];for(let i=0;i<array.length;i++)if(array[i])ret.push(array[i]);return ret}castInput(value,options){return value}tokenize(value,options){return Array.from(value)}join(chars){return chars.join("")}postProcess(changeObjects,options){return changeObjects}get useLongestToken(){return!1}buildValues(lastComponent,newTokens,oldTokens){let components=[],nextComponent;while(lastComponent)components.push(lastComponent),nextComponent=lastComponent.previousComponent,delete lastComponent.previousComponent,lastComponent=nextComponent;components.reverse();let componentLen=components.length,componentPos=0,newPos=0,oldPos=0;for(;componentPos<componentLen;componentPos++){let component=components[componentPos];if(!component.removed){if(!component.added&&this.useLongestToken){let value=newTokens.slice(newPos,newPos+component.count);value=value.map(function(value,i){let oldValue=oldTokens[oldPos+i];return oldValue.length>value.length?oldValue:value}),component.value=this.join(value)}else component.value=this.join(newTokens.slice(newPos,newPos+component.count));if(newPos+=component.count,!component.added)oldPos+=component.count}else component.value=this.join(oldTokens.slice(oldPos,oldPos+component.count)),oldPos+=component.count}return components}}function diffLines(oldStr,newStr,options){return lineDiff.diff(oldStr,newStr,options)}function tokenize2(value,options){if(options.stripTrailingCr)value=value.replace(/\r\n/g,`
1293
+ `);let retLines=[],linesAndNewlines=value.split(/(\n|\r\n)/);if(!linesAndNewlines[linesAndNewlines.length-1])linesAndNewlines.pop();for(let i=0;i<linesAndNewlines.length;i++){let line=linesAndNewlines[i];if(i%2&&!options.newlineIsToken)retLines[retLines.length-1]+=line;else retLines.push(line)}return retLines}var LineDiff,lineDiff;var init_line3=__esm(()=>{LineDiff=class LineDiff extends Diff2{constructor(){super(...arguments);this.tokenize=tokenize2}equals(left,right,options){if(options.ignoreWhitespace){if(!options.newlineIsToken||!left.includes(`
1294
+ `))left=left.trim();if(!options.newlineIsToken||!right.includes(`
1295
+ `))right=right.trim()}else if(options.ignoreNewlineAtEof&&!options.newlineIsToken){if(left.endsWith(`
1296
+ `))left=left.slice(0,-1);if(right.endsWith(`
1297
+ `))right=right.slice(0,-1)}return super.equals(left,right,options)}};lineDiff=new LineDiff});function structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options){let optionsObj;if(!options)optionsObj={};else if(typeof options==="function")optionsObj={callback:options};else optionsObj=options;if(typeof optionsObj.context>"u")optionsObj.context=4;let context=optionsObj.context;if(optionsObj.newlineIsToken)throw Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(!optionsObj.callback)return diffLinesResultToPatch(diffLines(oldStr,newStr,optionsObj));else{let{callback}=optionsObj;diffLines(oldStr,newStr,Object.assign(Object.assign({},optionsObj),{callback:(diff)=>{let patch=diffLinesResultToPatch(diff);callback(patch)}}))}function diffLinesResultToPatch(diff){if(!diff)return;diff.push({value:"",lines:[]});function contextLines(lines){return lines.map(function(entry){return" "+entry})}let hunks=[],oldRangeStart=0,newRangeStart=0,curRange=[],oldLine=1,newLine=1;for(let i=0;i<diff.length;i++){let current=diff[i],lines=current.lines||splitLines(current.value);if(current.lines=lines,current.added||current.removed){if(!oldRangeStart){let prev=diff[i-1];if(oldRangeStart=oldLine,newRangeStart=newLine,prev)curRange=context>0?contextLines(prev.lines.slice(-context)):[],oldRangeStart-=curRange.length,newRangeStart-=curRange.length}for(let line of lines)curRange.push((current.added?"+":"-")+line);if(current.added)newLine+=lines.length;else oldLine+=lines.length}else{if(oldRangeStart)if(lines.length<=context*2&&i<diff.length-2)for(let line of contextLines(lines))curRange.push(line);else{let contextSize=Math.min(lines.length,context);for(let line of contextLines(lines.slice(0,contextSize)))curRange.push(line);let hunk={oldStart:oldRangeStart,oldLines:oldLine-oldRangeStart+contextSize,newStart:newRangeStart,newLines:newLine-newRangeStart+contextSize,lines:curRange};hunks.push(hunk),oldRangeStart=0,newRangeStart=0,curRange=[]}oldLine+=lines.length,newLine+=lines.length}}for(let hunk of hunks)for(let i=0;i<hunk.lines.length;i++)if(hunk.lines[i].endsWith(`
1298
+ `))hunk.lines[i]=hunk.lines[i].slice(0,-1);else hunk.lines.splice(i+1,0,"\"),i++;return{oldFileName,newFileName,oldHeader,newHeader,hunks}}}function splitLines(text){let hasTrailingNl=text.endsWith(`
1299
+ `),result=text.split(`
1300
+ `).map((line)=>line+`
1301
+ `);if(hasTrailingNl)result.pop();else result.push(result.pop().slice(0,-1));return result}var init_create5=__esm(()=>{init_line3()});var init_libesm=__esm(()=>{init_create5()});function own2(object,key){return object!=null&&Object.prototype.hasOwnProperty.call(object,key)}function normalizedText(value){return typeof value==="string"?value.replace(/\r\n?/g,`
1302
+ `):value}function splitLines2(text){if(text==="")return[];let lines=normalizedText(text).split(`
1303
+ `);if(lines.at(-1)==="")lines.pop();return lines}function pathFromInput(input){if(input==null||typeof input!=="object")return null;for(let key of["path","file_path","filePath","filename"])if(typeof input[key]==="string"&&input[key].length>0)return input[key];return null}function operationFor(oldText,newText,{oldMissing=!1}={}){if(oldMissing||oldText==null)return"create";if(newText===""&&oldText!=="")return"delete";if(oldText===""&&newText!=="")return"create";return"update"}function displayHunks(hunks){return hunks.map(({oldStart,oldLines,newStart,newLines,lines})=>({oldStart:oldLines===0?Math.max(0,oldStart-1):oldStart,oldLines,newStart:newLines===0?Math.max(0,newStart-1):newStart,newLines,lines:lines.filter((line)=>!line.startsWith("\\"))}))}function countChanges(hunks){let additions=0,deletions=0;for(let hunk of hunks)for(let line of hunk.lines){if(line.startsWith("+"))additions+=1;if(line.startsWith("-"))deletions+=1}return{additions,deletions}}function textHunks(oldText,newText){let oldLines=splitLines2(oldText),newLines=splitLines2(newText),terminated=(lines)=>lines.length?`${lines.join(`
1304
+ `)}
1305
+ `:"",patch=structuredPatch("","",terminated(oldLines),terminated(newLines),"","",{context:DIFF_CONTEXT_LINES,maxEditLength:MAX_EDIT_LENGTH,timeout:DIFF_TIMEOUT_MS});if(patch)return displayHunks(patch.hunks);return[{oldStart:oldLines.length?1:0,oldLines:oldLines.length,newStart:newLines.length?1:0,newLines:newLines.length,lines:[...oldLines.map((line)=>`-${line}`),...newLines.map((line)=>`+${line}`)]}]}function fromTexts({path,oldText,newText,source,complete,oldMissing=!1}){if(typeof newText!=="string"||!oldMissing&&typeof oldText!=="string")return null;let normalizedOld=normalizedText(oldMissing?"":oldText),normalizedNew=normalizedText(newText),hunks=textHunks(normalizedOld,normalizedNew);return{path:typeof path==="string"&&path.length>0?path:null,oldText:oldMissing?null:normalizedOld,newText:normalizedNew,hunks,...countChanges(hunks),operation:operationFor(normalizedOld,normalizedNew,{oldMissing}),source,complete,hasLineNumbers:complete}}function contentDiff(content){if(!Array.isArray(content))return null;for(let item of content){let block=item?.type==="content"?item.content:item;if(block?.type!=="diff"||typeof block.newText!=="string")continue;let oldMissing=block.oldText==null;return fromTexts({path:block.path,oldText:block.oldText,newText:block.newText,source:"acp",complete:!0,oldMissing})}return null}function cleanPatchPath(value){if(typeof value!=="string"||!value||value==="/dev/null")return null;return value.startsWith("a/")||value.startsWith("b/")?value.slice(2):value}function parseUnifiedPatch(patch,fallbackPath){if(typeof patch!=="string"||patch.trim().length===0)return null;try{let patches=parsePatch(normalizedText(patch)).filter((entry)=>entry.hunks.length>0),entry=patches.find((item)=>fallbackPath!=null&&[cleanPatchPath(item.newFileName),cleanPatchPath(item.oldFileName)].includes(fallbackPath))??patches[0];if(!entry||!entry.hunks.every((hunk)=>[hunk.oldStart,hunk.oldLines,hunk.newStart,hunk.newLines].every((value)=>Number.isSafeInteger(value)&&value>=0)))return null;let hunks=displayHunks(entry.hunks);return{path:cleanPatchPath(entry.newFileName)??fallbackPath??cleanPatchPath(entry.oldFileName),oldText:null,newText:null,hunks,...countChanges(hunks),operation:entry.oldFileName==="/dev/null"?"create":entry.newFileName==="/dev/null"?"delete":"update",source:"patch",complete:!1,hasLineNumbers:!0}}catch{return null}}function rawInputDiff(rawInput){if(rawInput==null||typeof rawInput!=="object")return null;let path=pathFromInput(rawInput);for(let key of["patch","diff"]){if(!own2(rawInput,key))continue;let value=rawInput[key];if(typeof value==="string"){let parsed=parseUnifiedPatch(value,path);if(parsed)return parsed}else if(value!=null&&typeof value==="object"){let nestedPath=pathFromInput(value)??path;if(typeof value.newText==="string")return fromTexts({path:nestedPath,oldText:value.oldText,newText:value.newText,source:"raw-input",complete:!0,oldMissing:value.oldText==null})}}if(own2(rawInput,"newText")&&typeof rawInput.newText==="string")return fromTexts({path,oldText:rawInput.oldText,newText:rawInput.newText,source:"raw-input",complete:!0,oldMissing:rawInput.oldText==null});if(own2(rawInput,"edits")&&Array.isArray(rawInput.edits)){let edits=rawInput.edits.filter((edit)=>edit!=null&&typeof edit==="object"&&typeof edit.oldText==="string"&&typeof edit.newText==="string");if(edits.length>0)return fromTexts({path,oldText:edits.map((edit)=>edit.oldText).join(`
1306
+ `),newText:edits.map((edit)=>edit.newText).join(`
1307
+ `),source:"raw-input",complete:!1,oldMissing:!1})}if(own2(rawInput,"new_string")&&typeof rawInput.new_string==="string")return fromTexts({path,oldText:rawInput.old_string,newText:rawInput.new_string,source:"raw-input",complete:!1,oldMissing:rawInput.old_string==null});if(own2(rawInput,"content")&&typeof rawInput.content==="string")return fromTexts({path,oldText:null,newText:rawInput.content,source:"raw-input",complete:!1,oldMissing:!0});return null}function extractToolDiff(info={}){return contentDiff(info.content)??rawInputDiff(info.rawInput)}var DIFF_CONTEXT_LINES=3,MAX_EDIT_LENGTH=1000,DIFF_TIMEOUT_MS=100;var init_tool_diff=__esm(()=>{init_libesm()});function isVisibleTool(tool){return tool?.raw?.name!=="codemode"&&tool?.name!=="codemode"&&tool?.raw?.kind!=="codemode"&&tool?.kind!=="codemode"&&tool?.label?.name!=="Codemode"}function summarizeToolCategories(items){let counts=new Map;for(let item of items){let name=String(item.label?.name??"Tool").toLowerCase(),category=name==="bash"?"commands":`${name}${name.endsWith("s")?"":name.endsWith("ch")?"es":"s"}`;counts.set(category,(counts.get(category)??0)+1)}return[...counts.entries()].sort((a,b)=>b[1]-a[1]).map(([name,count])=>`${count} ${name}`).join(" · ")}function toolForDisplay(tool){if(!tool?.group)return isVisibleTool(tool)?tool:null;let items=tool.group.items.filter(isVisibleTool);if(items.length===0)return null;if(items.length===tool.group.items.length)return tool;return{...tool,group:{...tool.group,name:`${items.length} tool calls`,summary:summarizeToolCategories(items),count:items.length,items}}}function setRecorder(next){recorder=next}function appendBlock(state,block,record=!0){let entry={id:nextId(),...block},diffLength=entry.tool?.diff==null?0:JSON.stringify(entry.tool.diff).length,entryLength=(entry.text?.length??0)+(entry.thought?.text?.length??0)+(entry.tool?.hint?.length??0)+diffLength,length=state.length+entryLength;if(record&&recorder)recorder.recordBlock(entry);if(length>MAX_TRANSCRIPT_LENGTH)return{...state,blocks:[entry],length:entryLength,epoch:state.epoch+1};return{...state,blocks:[...state.blocks,entry],length}}function commitPending(state){let{pending}=state;if(!pending||pending.text.length===0)return{...state,pending:null};let text=pending.text.replace(/\n+$/,"");if(text.length===0)return{...state,pending:null};return{...appendBlock(flushToolGroup(state),{...pending,text}),pending:null}}function openFenceStart(text,upTo){let region=text.slice(0,upTo);FENCE_PATTERN.lastIndex=0;let open=-1,match;while(match=FENCE_PATTERN.exec(region))open=open<0?match.index+match[1].length:-1;return open}function isBlockStructureLine(line,partial=!1){if(partial?TABLE_ROW_PARTIAL.test(line):TABLE_ROW.test(line))return!0;return LIST_ITEM.test(line)||BLOCKQUOTE.test(line)}function splitsBlockStructure(text,cut){let before=text.lastIndexOf(`
1308
+ `,cut-1),prevLine=text.slice(before+1,cut);if(!isBlockStructureLine(prevLine))return!1;let rest=text.slice(cut+1),nextEnd=rest.indexOf(`
1309
+ `);if(nextEnd<0)return rest.length===0||isBlockStructureLine(rest,!0);return isBlockStructureLine(rest.slice(0,nextEnd))}function safeCut(text,separator){let cut=text.lastIndexOf(separator);while(cut>=0){let fence=openFenceStart(text,cut);if(fence<0){if(separator!==`
1310
+ `||!splitsBlockStructure(text,cut))return cut;cut=text.lastIndexOf(separator,cut-1);continue}let before=fence-separator.length;cut=before>=0?text.lastIndexOf(separator,before):-1}return-1}function streamChunk(state,chunk,role="assistant",messageId=null){let current=state.pending,messageChanged=messageId!=null&&current?.messageId!=null&&messageId!==current.messageId,base=current&&(current.role!==role||messageChanged)?commitPending(state):flushToolGroup(state),pending=base.pending?{...base.pending,messageId:base.pending.messageId??messageId}:{role,text:"",head:!0,messageId},text=pending.text+chunk,cut=safeCut(text,`
1311
+
1312
+ `),separatorLength=2,nextGap=!0;if(cut<0&&text.length>STREAM_BLOCK_MAX_CHARS)cut=safeCut(text,`
1313
+ `),separatorLength=1,nextGap=!1;if(cut<0)return{...base,pending:{...pending,text}};return{...appendBlock(flushToolGroup(base),{role:pending.role,head:pending.head,gap:pending.gap,text:text.slice(0,cut)}),pending:{role:pending.role,head:!1,gap:nextGap,text:text.slice(cut+separatorLength),messageId:pending.messageId}}}function hasPayloadDetail(value){if(value==null)return!1;if(Array.isArray(value))return value.length>0;if(typeof value==="object")return Object.keys(value).length>0;return!0}function isPlanningPlaceholder(payload){if(payload?.toolKind!=="other")return!1;if(payload?.name)return!1;if(hasPayloadDetail(payload?.rawInput)||hasPayloadDetail(payload?.locations))return!1;let title=typeof payload?.title==="string"?payload.title.trim():"";return HIDDEN_TOOL_TITLES.some((pattern)=>pattern.test(title))}function beginThought(state){if(state.thought)return state;return{...flushToolGroup(state),thought:{startedAt:Date.now(),activeAt:null,activeMs:0,pausedAt:null,pausedMs:0,text:"",title:null,expanded:state.thinkingDisplay==="full"}}}function isRedundantPreview(preview,label,title){if(!preview||preview.more>0)return!1;let text=preview.lines.join(`
1314
+ `).trim();if(text.length===0)return!0;return[label.name,label.args,title].filter((value)=>typeof value==="string"&&value.trim().length>0).map((value)=>value.trim()).includes(text)}function flushThought(state){let thought=state.thought;if(!thought)return state;let elapsed=thinkingElapsed(thought),text=thought.text??"",displayMode=normalizeThinkingDisplayMode(state.thinkingDisplay);return appendBlock({...state,thought:null},{role:"thought",head:!0,text:thoughtSummaryText(thought,formatDuration(elapsed)),thought:{durationMs:elapsed,hasContent:text.trim().length>0,title:thought.title??splitThinkingText(text).title,displayMode,text}})}function toolFromGroup(group,{live=!1,now=Date.now()}={}){let failed=group.items.some((item)=>item.status==="failed"||item.status==="cancelled"),liveStatus=failed?"failed":"pending",liveElapsed=group.startedAt!=null?Math.max(0,now-group.startedAt):null;if(group.items.length===1){let{label,status,elapsed,preview,command,subagent,detail,diff,autoReview}=group.items[0];return{label,status:live?liveStatus:status,elapsed:live?liveElapsed:elapsed,hint:group.hint??null,preview:preview??null,command:command??null,subagent:subagent??null,detail:detail??null,diff:diff??null,autoReview:autoReview??null,...group.items[0].toolCallId?{toolCallId:group.items[0].toolCallId}:{},...group.items[0].parentToolCallId?{parentToolCallId:group.items[0].parentToolCallId}:{},reviewItems:group.items}}let status="pending";if(failed)status="failed";else if(!live&&group.items.every((item)=>item.status==="completed"))status="completed";return{group:{name:`${group.items.length} tool calls`,summary:summarizeToolCategories(group.items),count:group.items.length,items:group.items},status,hint:group.hint??null,elapsed:live?liveElapsed:group.startedAt!=null&&group.finishedAt!=null?group.finishedAt-group.startedAt:null,reviewItems:group.items}}function flushToolGroup(state){let group=state.pendingToolGroup;if(!group)return state;let tool=toolFromGroup(group),text=tool.group?`${tool.group.name}${tool.group.summary?` · ${tool.group.summary}`:""}`:tool.label.args?`${tool.label.name}(${tool.label.args})`:tool.label.name;return appendBlock({...state,pendingToolGroup:null},{role:"tool",head:!0,text,tool})}function isRichTool(kind,name){return kind==="execute"||kind==="edit"||name==="Bash"||name==="Edit"}function finalizeTool(state,tool){let now=Date.now(),startedAt=tool.startedAt??now,finalDiff=tool.diff?{...tool.diff,complete:!0}:null,item={label:tool.label,kind:tool.kind??tool.raw?.kind??null,status:tool.status,elapsed:tool.startedAt!=null?now-tool.startedAt:null,preview:tool.preview??null,command:tool.command??null,subagent:tool.subagent??null,detail:tool.detail??null,diff:finalDiff,autoReview:tool.autoReview??null,...tool.toolCallId?{toolCallId:tool.toolCallId}:{},...tool.raw?.parentToolCallId?{parentToolCallId:tool.raw.parentToolCallId}:{}},next=commitPending(state);if(isRichTool(item.kind,item.label?.name))return next=flushToolGroup(next),flushToolGroup({...next,pendingToolGroup:{name:item.label.name,items:[item],hint:tool.hint??null,startedAt,finishedAt:now}});let current=next.pendingToolGroup;if(current&&!item.subagent&&!current.items.some((entry)=>entry.subagent))return{...next,pendingToolGroup:{...current,items:[...current.items,item],finishedAt:now}};return next=flushToolGroup(next),{...next,pendingToolGroup:{name:tool.label.name,items:[item],hint:tool.hint??null,startedAt,finishedAt:now}}}function mergeDiff(candidate,previous){if(candidate?.complete)return candidate;if(previous?.complete)return previous;return candidate??previous??null}function bumpToolRound(state){if(state.activeTools.length>0)return state;return{...state,toolRound:state.toolRound+1}}function mergeTool(state,payload){let{toolCallId,status}=payload;if(toolCallId&&state.finalizedToolIds.has(toolCallId))return state;if(toolCallId!=null&&state.planningToolIds.has(toolCallId)||isPlanningPlaceholder(payload)){let planningToolIds=new Set(state.planningToolIds);if(toolCallId)planningToolIds.add(toolCallId);if(TERMINAL_STATUSES.has(status)){if(toolCallId)planningToolIds.delete(toolCallId);let next=flushThought(state);return{...next,planningToolIds,finalizedToolIds:toolCallId?new Set(next.finalizedToolIds).add(toolCallId):next.finalizedToolIds}}return{...beginThought(state),planningToolIds}}let raw={name:payload.name,kind:payload.toolKind,title:payload.title,rawInput:payload.rawInput,rawOutput:payload.rawOutput,locations:payload.locations,parentToolCallId:payload.parentToolCallId};if(!toolCallId){let next=bumpToolRound(commitPending(flushThought(state))),label=formatToolLabel(raw),preview=summarizeToolResult({...raw,name:label.name,content:payload.content,status});return finalizeTool(next,{label,kind:raw.kind,status,preview:isRedundantPreview(preview,label,payload.title)?null:preview,command:commandText(raw.rawInput),detail:buildToolDetail({...raw,content:payload.content}),diff:extractToolDiff({...raw,content:payload.content})})}let existing=state.activeTools.find((tool)=>tool.toolCallId===toolCallId),isSubagent=payload.isSubagent===!0||existing?.subagent!=null,next=state;if(!existing)next=commitPending(flushThought(next)),next=bumpToolRound(next);let subagent=isSubagent?updateSubagentState(existing?.subagent??createSubagentState(),payload.rawInput,extractRawText(payload.content)):null,mergedRaw=existing?{...existing.raw}:{};for(let[key,value]of Object.entries(raw))if(value!=null)mergedRaw[key]=value;let nextLabel=formatToolLabel(mergedRaw),nextStatus=status??existing?.status??"pending",previewCandidate=isSubagent?null:mergedRaw.kind==="execute"?extractToolOutputPreview(payload.rawOutput)??extractToolPreview(payload.content)??existing?.preview??null:summarizeToolResult({...mergedRaw,name:nextLabel.name,content:payload.content,status:nextStatus}),preview=isRedundantPreview(previewCandidate,nextLabel,payload.title??mergedRaw.title)?null:previewCandidate,merged={toolCallId,raw:mergedRaw,label:nextLabel,status:nextStatus,startedAt:existing?.startedAt??Date.now(),hint:existing?.hint??null,preview,command:commandText(mergedRaw.rawInput),subagent,content:payload.content??existing?.content,detail:buildToolDetail({...mergedRaw,content:payload.content??existing?.content}),diff:mergeDiff(extractToolDiff({...mergedRaw,content:payload.content??existing?.content}),existing?.diff??null),autoReview:payload.autoReview??existing?.autoReview??null};if(merged.subagent&&merged.status!=="failed"&&merged.status!=="cancelled")merged.status=merged.subagent.runFinished?"completed":"in_progress";if(TERMINAL_STATUSES.has(merged.status))return{...finalizeTool(next,merged),activeTools:next.activeTools.filter((tool)=>tool.toolCallId!==toolCallId),finalizedToolIds:new Set(next.finalizedToolIds).add(toolCallId)};if(!existing&&isRichTool(merged.raw?.kind,merged.label.name)&&next.pendingToolGroup)next=flushToolGroup(next);return{...next,activeTools:existing?next.activeTools.map((tool)=>tool.toolCallId===toolCallId?merged:tool):[...next.activeTools,merged]}}function flushActiveTools(state,cancelled=!1){let next=state,finalized=new Set(state.finalizedToolIds);for(let tool of state.activeTools){let finalTool=cancelled&&(tool.status==="pending"||tool.status==="in_progress")?{...tool,status:"cancelled"}:tool;next=finalizeTool(next,finalTool),finalized.add(tool.toolCallId)}return{...next,activeTools:[],finalizedToolIds:finalized}}function normalizePlanEntries(entries){if(!Array.isArray(entries))return[];return entries.map((entry)=>({status:entry?.status==="completed"||entry?.status==="in_progress"?entry.status:"pending",content:typeof entry?.content==="string"?entry.content:""})).filter((entry)=>entry.content.length>0)}function planSignatureOf(rows){return rows.map((row)=>`${row.status}\x00${row.content}`).join(`
1315
+ `)}function planBlockText(rows){return["Update Todos",...rows.map((row)=>`${row.status==="completed"?"☒":"☐"} ${row.content}`)].join(`
1316
+ `)}function flushBashCard(state){let card=state.bashCard;if(!card)return state;let{visible,hidden}=previewBashLines(card.lines,!1,BASH_PREVIEW_LINES),snapshot={...card,lines:visible,hidden},text=visible.map((line)=>line.text).join(`
1317
+ `);return{...appendBlock(state,{role:"bashCard",head:!0,text,card:snapshot}),bashCard:null}}function flushBeforeStandaloneBlock(state){return flushBashCard(commitPending(flushThought(flushToolGroup(state))))}function reportedTokenCounts(usage){let pick=(keys)=>{for(let key of keys){let value=usage[key];if(typeof value==="number"&&Number.isFinite(value)&&value>=0)return value}return null},counts={};for(let field of TOKEN_FIELDS)counts[field]=pick(TOKEN_FIELD_SOURCES[field]);return counts}function sameTokenCounts(a,b){if(a===b)return!0;return TOKEN_FIELDS.every((field)=>(a?.[field]??null)===(b?.[field]??null))}function reportedCost(cost){let amount=cost?.amount;if(typeof amount!=="number"||!Number.isFinite(amount)||amount<=0)return null;let currency=typeof cost?.currency==="string"&&cost.currency?cost.currency:"USD";return{amount,currency}}var recorder=null,bannerBlock=()=>({id:nextId(),role:"banner",text:"",head:!0}),STREAM_BLOCK_MAX_CHARS=300,MAX_THOUGHT_TEXT=50000,TURN_STOP_NOTICES,FENCE_PATTERN,TABLE_ROW,TABLE_ROW_PARTIAL,LIST_ITEM,BLOCKQUOTE,HIDDEN_TOOL_TITLES,TOKEN_FIELDS,TOKEN_FIELD_SOURCES,useStore;var init_store=__esm(()=>{init_subagent();init_tool_title();init_bash();init_config();init_thinking();init_tool_diff();TURN_STOP_NOTICES={max_turns:"Stopped after reaching the tool-call round limit — the task may be unfinished.",max_tokens:"The reply was cut off by the model's output token limit.",content_filter:"The provider stopped the reply with a content filter.",empty_response:"The model kept returning an empty reply — the turn ended without an answer."},FENCE_PATTERN=/(^|\n)( {0,3})(```|~~~)/g;TABLE_ROW=/^ {0,3}\|.*\|\s*$/,TABLE_ROW_PARTIAL=/^ {0,3}\|/,LIST_ITEM=/^ {0,3}(?:[-*+]|\d{1,9}[.)])\s/,BLOCKQUOTE=/^ {0,3}>/;HIDDEN_TOOL_TITLES=[/^(?:任务)?规划中$/,/^(?:planning|planning task)$/i];TOKEN_FIELDS=["total","input","output","cacheRead","cacheWrite","thought"],TOKEN_FIELD_SOURCES={total:["totalTokens"],input:["inputTokens"],output:["outputTokens"],cacheRead:["cachedReadTokens","cacheReadTokens"],cacheWrite:["cachedWriteTokens","cacheWriteTokens"],thought:["thoughtTokens"]};useStore=createStore((set,get)=>({blocks:[],pending:null,epoch:0,length:0,activeTools:[],finalizedToolIds:new Set,planningToolIds:new Set,toolRound:0,pendingToolGroup:null,thought:null,thinkingDisplay:DEFAULT_THINKING_DISPLAY_MODE,planSignature:null,queuedInputs:[],pendingInputs:[],queuePaused:!1,providerCommands:[],pendingBashContext:[],bashCard:null,status:"connecting",connectionStage:"Starting ACP…",providerName:null,providerId:null,sessionId:null,sessionMeta:null,sessionTitle:null,providerCapabilities:null,modelConfig:null,effortConfig:null,configOptions:[],modes:null,busy:!1,cancelling:!1,compacting:!1,switching:null,overlay:null,fatalError:null,usage:null,tokens:null,sessionTokens:null,sessionCost:null,planProgress:null,gitBranch:null,goal:null,turnStartedAt:null,turnKind:null,turnBlocksAt:0,animationTick:0,retryNotice:null,push:(role,text)=>set((state)=>appendBlock(flushBeforeStandaloneBlock(state),{role,text,head:!0})),pushProposedPlan:(text,planPath=null)=>set((state)=>appendBlock(flushBeforeStandaloneBlock(state),{role:"proposedPlan",text,planPath,head:!0})),appendChunk:(chunk,messageId)=>set((state)=>streamChunk(flushBashCard(flushThought(flushToolGroup(state))),chunk,"assistant",messageId)),appendUserChunk:(chunk,messageId)=>set((state)=>streamChunk(flushBashCard(flushToolGroup(state)),chunk,"user",messageId)),upsertTool:(payload)=>set((state)=>mergeTool(flushBashCard(state),payload)),startBashCard:(command)=>set((state)=>({...flushBashCard(state),bashCard:{command,lines:[],status:"running",outcome:null}})),finishBashCard:({stdout,stderr,outcome})=>set((state)=>state.bashCard?{bashCard:{...state.bashCard,lines:buildBashCardLines(stdout,stderr),status:"done",outcome}}:state),noteThought:(text="",now=Date.now())=>set((state)=>{let chunk=text??"";if(!state.thought)return{...flushToolGroup(state),thought:{startedAt:now,activeAt:chunk?now:null,activeMs:0,pausedAt:null,pausedMs:0,text:chunk,title:splitThinkingText(chunk).title,expanded:state.thinkingDisplay==="full"}};let combined=(state.thought.text??"")+chunk,truncated=combined.length>MAX_THOUGHT_TEXT?combined.slice(combined.length-MAX_THOUGHT_TEXT):combined,activity=chunk?advanceThinking(state.thought,now):null;return{thought:{...state.thought,...activity??{},text:truncated,title:state.thought.title??splitThinkingText(combined).title}}}),setThinkingDisplay:(value)=>set((state)=>{let thinkingDisplay=normalizeThinkingDisplayMode(value);if(thinkingDisplay===state.thinkingDisplay)return state;return{thinkingDisplay,thought:state.thought?{...state.thought,expanded:thinkingDisplay==="full"}:state.thought}}),setThoughtPaused:(paused,now=Date.now())=>set((state)=>{let thought=state.thought;if(!thought)return state;if(paused){if(thought.pausedAt!=null)return state;return{thought:{...thought,pausedAt:now}}}if(thought.pausedAt==null)return state;return{thought:{...thought,pausedAt:null,pausedMs:(thought.pausedMs??0)+Math.max(0,now-thought.pausedAt)}}}),setPlan:(entries)=>set((state)=>{let rows=normalizePlanEntries(entries);if(rows.length===0)return state.planSignature==null?state:{planSignature:null};let signature=planSignatureOf(rows),planProgress={total:rows.length,completed:rows.filter((row)=>row.status==="completed").length};if(signature===state.planSignature){let current=state.planProgress;return current!=null&&current.total===planProgress.total&&current.completed===planProgress.completed?state:{planProgress}}let next=flushBeforeStandaloneBlock(state);return{...appendBlock(next,{role:"plan",head:!0,text:planBlockText(rows),plan:{entries:rows}}),planSignature:signature,planProgress}}),setGoal:(snapshot)=>set((state)=>{if(snapshot==null)return state.goal==null?state:{goal:null};let current=state.goal;return current!=null&&current.goalId===snapshot.goalId&&current.status===snapshot.status&&current.objective===snapshot.objective&&current.turnsUsed===snapshot.turnsUsed&&current.wallClockMs===snapshot.wallClockMs&&current.terminalReason===snapshot.terminalReason&&current.budget?.turnBudget===snapshot.budget?.turnBudget?state:{goal:snapshot}}),queueInput:(text,display=null,id=null)=>set((state)=>({queuedInputs:[...state.queuedInputs,{text,display,...id?{id}:{}}]})),addPendingInput:(input)=>set((state)=>({pendingInputs:[...state.pendingInputs,normalizeInput(input)]})),applyInput:(input)=>set((state)=>{let next={...state,pendingInputs:state.pendingInputs.filter((item)=>item.id!==input.id)};if(state.blocks.some((block)=>block.inputId===input.id))return next;return appendBlock(flushBeforeStandaloneBlock(next),{role:"user",text:input.display??input.text,inputId:input.id,head:!0})}),returnInputs:(inputs,paused)=>set((state)=>{let ids=new Set(inputs.map((input)=>input.id)),queuedIds=new Set(state.queuedInputs.map((input)=>input.id).filter(Boolean));return{pendingInputs:state.pendingInputs.filter((input)=>!ids.has(input.id)),queuedInputs:[...inputs.filter((input)=>!queuedIds.has(input.id)).map(normalizeInput),...state.queuedInputs],queuePaused:state.queuePaused||paused}}),resumeInputQueue:()=>set({queuePaused:!1}),replaceQueuedInputs:(items)=>set({queuedInputs:Array.isArray(items)?items.map(normalizeInput):[]}),updateQueuedInput:(index,text)=>set((state)=>({queuedInputs:state.queuedInputs.map((item,itemIndex)=>itemIndex===index?{...item,text,display:null}:item)})),removeQueuedInput:(index)=>set((state)=>({queuedInputs:state.queuedInputs.filter((_,itemIndex)=>itemIndex!==index),...state.queuedInputs.length===1?{queuePaused:!1}:{}})),moveQueuedInput:(index,direction)=>set((state)=>{let target=index+direction;if(index<0||index>=state.queuedInputs.length||target<0||target>=state.queuedInputs.length)return state;let queuedInputs=[...state.queuedInputs];return[queuedInputs[index],queuedInputs[target]]=[queuedInputs[target],queuedInputs[index]],{queuedInputs}}),clearQueuedInputs:()=>set({queuedInputs:[],queuePaused:!1}),takeQueuedInput:()=>{if(get().queuePaused)return null;let queue=get().queuedInputs;if(queue.length===0)return null;return set({queuedInputs:queue.slice(1)}),queue[0]},setProviderCommands:(providerCommands)=>set({providerCommands:providerCommands??[]}),pushBashContext:(text)=>set((state)=>({pendingBashContext:[...state.pendingBashContext,text]})),takeBashContext:()=>{let items=get().pendingBashContext;if(items.length>0)set({pendingBashContext:[]});return items},restoreBashContext:(items)=>set((state)=>({pendingBashContext:[...items,...state.pendingBashContext]})),clearTranscript:()=>set((state)=>({blocks:state.status==="ready"?[bannerBlock()]:[],pending:null,activeTools:[],finalizedToolIds:new Set,planningToolIds:new Set,toolRound:0,pendingToolGroup:null,thought:null,planSignature:null,planProgress:null,goal:null,bashCard:null,epoch:state.epoch+1,length:0})),connected:({providerName,sessionId,providerCapabilities,modelConfig,effortConfig,configOptions,modes})=>set((state)=>{let hasBanner=state.blocks.some((block)=>block.role==="banner"),nextSessionId=sessionId??null,sessionChanged=state.sessionId!==nextSessionId;return{...hasBanner?state:appendBlock(state,bannerBlock(),!1),status:"ready",connectionStage:null,providerName,sessionId:nextSessionId,providerCapabilities:providerCapabilities??state.providerCapabilities,modelConfig,effortConfig,configOptions:Array.isArray(configOptions)?configOptions:state.configOptions,modes:modes??null,...sessionChanged?{usage:null,tokens:null,sessionTokens:null,sessionCost:null,sessionTitle:null,planProgress:null,goal:null}:{}}}),hydrate:(historyBlocks)=>set((state)=>{let next=state;for(let block of historyBlocks){if(!block||block.role==="banner")continue;let preview=block.role==="tool"?restoreQuestionPreview(block.tool):null,restored=preview?{...block,tool:{...block.tool,preview,reviewItems:block.tool.reviewItems?.map((item)=>item.label?.name==="Question"?{...item,preview}:item)}}:block;next=appendBlock(next,restored,!1)}return next}),setSessionMeta:(sessionMeta)=>set({sessionMeta}),setSessionTitle:(sessionTitle)=>set((state)=>state.sessionTitle===(sessionTitle??null)?state:{sessionTitle:sessionTitle??null}),setUsage:({used,size,cost,costCumulative}={})=>set((state)=>{let next={used:typeof used==="number"?used:state.usage?.used??null,size:typeof size==="number"?size:state.usage?.size??null,cost:cost??state.usage?.cost??null},reading=reportedCost(cost),sessionCost=state.sessionCost;if(reading)sessionCost=costCumulative===!0?reading:{amount:(sessionCost?.amount??0)+reading.amount,currency:reading.currency};let current=state.usage;if(current&&current.used===next.used&&current.size===next.size&&current.cost===next.cost&&sessionCost===state.sessionCost)return state;return{usage:next,sessionCost}}),setTokens:(usage)=>set((state)=>{if(!usage||typeof usage!=="object")return state;let reported=reportedTokenCounts(usage),previous=state.tokens,cumulative=usage.sessionCumulative===!0,reading={},totals={};for(let field of TOKEN_FIELDS){let value=reported[field],last=previous?.[field],lastValue=typeof last==="number"?last:null;reading[field]=value??lastValue;let step=cumulative?Math.max(0,value-(lastValue??0)):value,accumulated=state.sessionTokens?.[field],base=typeof accumulated==="number"?accumulated:null;totals[field]=value==null?base:(base??0)+step}if(sameTokenCounts(previous,reading)&&sameTokenCounts(state.sessionTokens,totals))return state;return{tokens:reading,sessionTokens:totals}}),setGitBranch:(gitBranch)=>set((state)=>state.gitBranch===(gitBranch??null)?state:{gitBranch:gitBranch??null}),setConfigs:({modelConfig,effortConfig,configOptions})=>set({modelConfig,effortConfig,...configOptions!==void 0?{configOptions:configOptions??[]}:{}}),setModes:(modes)=>set({modes}),setCompacting:(compacting)=>set({compacting}),recordContextState:(state)=>recorder?.recordContextState?.(state),setConnectionStage:(connectionStage)=>set({connectionStage}),setProviderId:(providerId)=>set({providerId}),reconnecting:()=>set({status:"connecting",connectionStage:"Starting ACP…",modes:null,providerCommands:[],planSignature:null,planningToolIds:new Set,planProgress:null,goal:null,usage:null,tokens:null,sessionTokens:null,sessionCost:null,sessionTitle:null,fatalError:null}),connectionFailed:()=>set({status:"failed",switching:null,busy:!1,cancelling:!1,compacting:!1,turnStartedAt:null,retryNotice:null}),setSwitching:(switching)=>set({switching}),bumpAnimationTick:()=>set((state)=>({animationTick:state.animationTick+1})),setOverlay:(overlay)=>set({overlay}),setCancelling:(cancelling)=>set({cancelling}),setFatalError:(fatalError)=>set({fatalError}),setRetryNotice:(retryNotice)=>set({retryNotice:retryNotice??null}),startTurn:(kind="prompt")=>set((state)=>({busy:!0,cancelling:!1,turnStartedAt:Date.now(),turnKind:kind,turnBlocksAt:state.blocks.length,toolRound:0,retryNotice:null})),endTurn:(result)=>set((state)=>{let wasCancelled=state.cancelling||result===!0||result==="cancelled"||result?.cancelled===!0||result?.stopReason==="cancelled",next=commitPending(flushToolGroup(flushActiveTools(flushThought(state),wasCancelled)));if(wasCancelled)next=appendBlock(next,{role:"error",head:!0,text:"Interrupted by user"});else{let notice=TURN_STOP_NOTICES[result?.stopReason];if(notice)next=appendBlock(next,{role:"error",head:!0,text:notice});if(state.turnKind==="prompt"&&state.turnStartedAt!=null&&next.blocks.length>state.turnBlocksAt){let elapsed=formatDuration(Date.now()-state.turnStartedAt);next=appendBlock(next,{role:"system",head:!0,text:elapsed?`Done in ${elapsed}`:"Done"})}}return{...next,finalizedToolIds:new Set,planningToolIds:new Set,planSignature:null,busy:!1,cancelling:!1,compacting:!1,turnStartedAt:null,turnKind:null,retryNotice:null}})}))});function isSynchronizedOutputSupported(environment=process.env){if(environment.TMUX!==void 0)return!1;let{TERM_PROGRAM:termProgram,TERM:term}=environment;if(SYNC_OUTPUT_TERM_PROGRAMS.has(termProgram))return!0;if(term?.includes("kitty"))return!0;if(term==="xterm-ghostty")return!0;if(term?.startsWith("foot"))return!0;if(term?.includes("alacritty"))return!0;if(environment.KITTY_WINDOW_ID)return!0;if(environment.ZED_TERM)return!0;if(environment.WT_SESSION)return!0;let vteVersion=Number.parseInt(environment.VTE_VERSION,10);return Number.isFinite(vteVersion)&&vteVersion>=6800}function shouldWrapSyncOutput(environment=process.env){return isSynchronizedOutputSupported(environment)}var SYNC_OUTPUT_TERM_PROGRAMS;var init_term_caps=__esm(()=>{SYNC_OUTPUT_TERM_PROGRAMS=new Set(["iTerm.app","WezTerm","WarpTerminal","ghostty","contour","vscode","alacritty"])});var STEADY_BAR_CURSOR="\x1B[6 q",DEFAULT_CURSOR="\x1B[0 q";import os11 from"node:os";import path27 from"node:path";function shortenHome(dir){let home=os11.homedir();if(!dir)return null;if(dir===home)return"~";return dir.startsWith(`${home}${path27.sep}`)?`~${dir.slice(home.length)}`:dir}function formatTokens2(value){if(typeof value!=="number"||!Number.isFinite(value)||value<=0)return null;if(value<1000)return String(Math.round(value));if(value<1e6)return`${(value/1000).toFixed(1).replace(/\.0$/,"")}k`;return`${(value/1e6).toFixed(1).replace(/\.0$/,"")}M`}function positiveOrZero(count){return typeof count==="number"&&Number.isFinite(count)&&count>0?count:0}function formatSessionCost(cost){let amount=cost?.amount;if(typeof amount!=="number"||!Number.isFinite(amount)||amount<=0)return null;let digits=amount<0.001?4:amount<1?3:2,currency=typeof cost?.currency==="string"&&cost.currency?cost.currency:"USD",value=amount.toFixed(digits);if(currency!=="USD")return`${value} ${currency}`;return`$${value}`}function formatSessionTokenUsage(tokens,cost){let value=(count)=>{if(typeof count!=="number"||!Number.isFinite(count)||count<0)return null;return formatTokens2(count)??"0"},parts=[],fields=[["↑",tokens?.input],["↓",tokens?.output]].flatMap(([arrow,count])=>{let formatted=value(count);return formatted==null?[]:[`${arrow}${formatted}`]}).join(" ");if(fields)parts.push(fields);let cacheRead=positiveOrZero(tokens?.cacheRead),cacheWrite=positiveOrZero(tokens?.cacheWrite);if(cacheRead>0||cacheWrite>0){let cacheParts=[`R${value(cacheRead)} W${value(cacheWrite)}`],prompt=positiveOrZero(tokens?.input)+cacheRead+cacheWrite;if(prompt>0)cacheParts.push(`CH${(cacheRead/prompt*100).toFixed(1)}%`);parts.push(cacheParts.join(" "))}let spent=formatSessionCost(cost);if(spent)parts.push(spent);return parts.length>0?`Stat ${parts.join(" ")}`:null}function usedPercent(usage){let used=usage?.used,size=usage?.size;if(typeof used!=="number"||typeof size!=="number"||size<=0)return null;return Math.min(100,Math.max(0,Math.round(used/size*100)))}function runStateText(snapshot){if(snapshot.cancelling)return"Interrupting";if(!snapshot.busy)return"Ready";return snapshot.thinking?"Thinking":"Working"}function resolveStatusLineItem(id){if(typeof id!=="string")return null;return ALIAS_TO_ID.get(id.trim().toLowerCase())??null}function parseStatusLineItems(ids){let items=[],invalid=[],seen=new Set;for(let raw of Array.isArray(ids)?ids:[]){let id=resolveStatusLineItem(raw);if(id==null){if(typeof raw==="string"&&raw.trim())invalid.push(raw.trim());continue}if(seen.has(id))continue;seen.add(id),items.push(id)}return{items,invalid}}var ITEM_DEFINITIONS,STATUS_LINE_ITEMS,ALIAS_TO_ID;var init_items7=__esm(()=>{ITEM_DEFINITIONS=[{id:"model",aliases:["model-name"],label:"Current model name",placeholder:"gpt-5",tone:"model",description:"当前模型名",value:(s)=>s.modelName??null},{id:"model-with-reasoning",label:"Current model name with reasoning level",placeholder:"gpt-5 medium",tone:"model",description:"模型名 + 思考强度",value:(s)=>s.modelName==null?null:s.effortName?`${s.modelName} ${s.effortName}`:s.modelName},{id:"reasoning",label:"Current reasoning level",placeholder:"medium",tone:"model",description:"当前思考强度",value:(s)=>s.effortName??null},{id:"mode",label:"Current session mode",placeholder:"default",tone:"accent",description:"当前会话模式",value:(s)=>s.modeName??null},{id:"permission-mode",aliases:["permissions"],label:"Current permission mode",placeholder:"AUTO",tone:"accent",description:"当前权限模式",value:(s)=>{if(s.permissionMode==="auto")return"AUTO";if(s.permissionMode==="manual")return"MANUAL";return null}},{id:"current-dir",label:"Current working directory",placeholder:"~/workspace/miro",tone:"dir",description:"当前工作目录",value:(s)=>shortenHome(s.cwd)??null},{id:"project-name",aliases:["project","project-root"],label:"Current project name",placeholder:"miro",tone:"dir",description:"项目名",value:(s)=>s.projectName??null},{id:"hostname",label:"Current hostname",placeholder:"localhost",tone:"dim",description:"主机名",value:(s)=>s.hostname??null},{id:"git-branch",label:"Current Git branch",placeholder:"feat/branch-name",tone:"accent",description:"当前 Git 分支",value:(s)=>s.gitBranch??null},{id:"run-state",aliases:["status"],label:"Current run state",placeholder:"Ready",tone:"state",description:"运行状态",value:(s)=>runStateText(s)},{id:"provider",label:"Current ACP provider",placeholder:"Codex",tone:"accent",description:"当前 ACP provider",value:(s)=>s.providerName??null},{id:"session-id",aliases:["thread-id"],label:"Current session ID",placeholder:"1094dbe3",tone:"dim",description:"会话 id(短格式)",value:(s)=>typeof s.sessionId==="string"&&s.sessionId?s.sessionId.slice(0,8):null},{id:"session-title",aliases:["thread-title"],label:"Current session title",placeholder:"Status line setup",tone:"dim",description:"会话标题",value:(s)=>typeof s.sessionTitle==="string"&&s.sessionTitle.trim()?s.sessionTitle.trim():null},{id:"miro-version",aliases:["version"],label:"Miro version",placeholder:"v0.1.0",tone:"dim",description:"miro 版本号",value:(s)=>s.version?`v${s.version}`:null},{id:"context-used",aliases:["context-usage"],label:"Context window used percentage",placeholder:"28% used",tone:"state",description:"上下文已用百分比",value:(s)=>{let percent=usedPercent(s.usage);return percent==null?null:`${percent}% used`}},{id:"context-remaining",label:"Context window remaining percentage",placeholder:"72% left",tone:"state",description:"上下文剩余百分比",value:(s)=>{let percent=usedPercent(s.usage);return percent==null?null:`${100-percent}% left`}},{id:"context-window-size",label:"Context window size",placeholder:"200k ctx",tone:"dim",description:"上下文窗口总量",value:(s)=>{let size=formatTokens2(s.usage?.size);return size==null?null:`${size} ctx`}},{id:"task-progress",label:"Current task progress",placeholder:"3/7",tone:"accent",description:"最新 checklist 进度",value:(s)=>{let total=s.plan?.total??0;if(!total)return null;return`${s.plan.completed??0}/${total}`}},{id:"goal",aliases:["goal-status"],label:"Active goal status and progress",placeholder:"goal active 3t",tone:"accent",description:"目标状态与进度",value:(s)=>{let goal=s.goal;if(goal==null||typeof goal.status!=="string")return null;let limit=goal.budget?.turnBudget,turns=typeof goal.turnsUsed==="number"?goal.turnsUsed:0,progress=limit!=null?`${turns}/${limit}t`:`${turns}t`;return`goal ${goal.status} ${progress}`}},{id:"used-tokens",label:"Total session tokens",placeholder:"12.3k tokens",tone:"dim",description:"会话累计 token",value:(s)=>{let total=formatTokens2(s.sessionTokens?.total);return total==null?null:`${total} tokens`}},{id:"input-tokens",label:"Total input tokens",placeholder:"10k in",tone:"dim",description:"累计输入 token",value:(s)=>{let value=formatTokens2(s.sessionTokens?.input);return value==null?null:`${value} in`}},{id:"output-tokens",label:"Total output tokens",placeholder:"2k out",tone:"dim",description:"累计输出 token",value:(s)=>{let value=formatTokens2(s.sessionTokens?.output);return value==null?null:`${value} out`}},{id:"thought-tokens",label:"Total reasoning tokens",placeholder:"345 think",tone:"dim",description:"累计思考 token",value:(s)=>{let value=formatTokens2(s.sessionTokens?.thought);return value==null?null:`${value} think`}},{id:"session-cost",label:"Estimated session cost",placeholder:"$1.50",tone:"dim",description:"会话累计成本",value:(s)=>{let amount=s.sessionCost?.amount;if(typeof amount!=="number"||!Number.isFinite(amount)||amount<=0)return null;let currency=s.sessionCost.currency??"USD";return currency==="USD"?`$${amount.toFixed(2)}`:`${amount.toFixed(2)} ${currency}`}}],STATUS_LINE_ITEMS=new Map(ITEM_DEFINITIONS.map((item)=>[item.id,item])),ALIAS_TO_ID=new Map;for(let item of ITEM_DEFINITIONS){ALIAS_TO_ID.set(item.id,item.id);for(let alias of item.aliases??[])ALIAS_TO_ID.set(alias,item.id)}});var MIRO_LOGO_ROWS,MIRO_LOGO,BLACK_CIRCLE,BLACK_CIRCLE_PLAIN="●",TREE_LAST_PLAIN="└",TREE_LAST="└",TREE_LAST_PREFIX,TREE_MID_PREFIX,TREE_VERTICAL_PREFIX,TREE_BLANK_PREFIX=" ";var init_figures=__esm(()=>{MIRO_LOGO_ROWS=[[[" ▗█","#77818d"],["▀","yellow"],["▙","#77818d"],["▸","yellow"]],[[" ▟","#77818d"],["▌","yellow"],["██▐","#f5f2e9"],["▙","#77818d"]],[[" ▝","#77818d"],["▟","yellow"],["██","#f5f2e9"],["▙","yellow"],["▘","#77818d"]]],MIRO_LOGO=MIRO_LOGO_ROWS.map((row)=>row.map(([glyphs])=>glyphs).join("")).join(`
1334
1318
  `),BLACK_CIRCLE=process.platform==="darwin"?"⏺":"●",TREE_LAST_PREFIX=` ${"└"} `,TREE_MID_PREFIX=` ${"├"} `,TREE_VERTICAL_PREFIX=` ${"│"} `});function renderMarkedBlock(block){if(!block||block.role==="banner")return[];if(block.role==="thought"){if(block.thought?.displayMode==="hidden")return[];let detailsMissing=block.thought?.hasContent&&!block.thought?.text,summary=`${String(block.text??"")}${detailsMissing?" · details not retained":""}`,lines=[`${ROLE_MARKERS.thought} ${summary}`];if(block.thought?.displayMode==="full"&&block.thought.text){let body=splitThinkingText(block.thought.text).body;if(body)lines.push(...body.split(`
1335
1319
  `).map((line)=>` ${line}`))}return lines}if(block.role==="plan"||block.role==="proposedPlan"||block.role==="bashCard")return String(block.text??"").split(`
1336
1320
  `);if(block.role==="tool"){let lines=[`${BLACK_CIRCLE_PLAIN} ${String(block.text??"")}`];if(block.tool?.hint)lines.push(` ${TREE_LAST_PLAIN} ${block.tool.hint}`);let diff=block.tool?.diff;if(diff){let path=diff.path?` ${diff.path}`:"";lines.push(` diff${path} (+${diff.additions??0} -${diff.deletions??0})`);for(let hunk of diff.hunks??[]){lines.push(` @@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`);for(let line of hunk.lines??[])lines.push(` ${line}`)}}for(let line of block.tool?.preview?.lines??[])lines.push(` ${line}`);return lines}let marker=ROLE_MARKERS[block.role],text=String(block.text??"");if(!marker)return text.split(`
@@ -2155,48 +2139,7 @@ EOF
2155
2139
  成功時提供分支、短提交 SHA 同標題,以及拉取請求 URL。部分完成時講明 commit、push 同 PR 建立分別完成到邊一步,以及下一步要做乜。有意留下嘅未提交檔案放喺 \`## Left uncommitted\` 下面。唔好輸出 JSON,亦唔好將成個回覆包喺代碼塊入面。`;var init_commit3=__esm(()=>{DEFAULT_PROMPT3="為當前改動建立一個 git 提交。"+"自己將相關檔案加入暫存區,然後用你根據上面上下文起草嘅提交訊息提交佢哋。";STAGED_ONLY_PROMPT3="用已經暫存嘅改動建立一個 git 提交。"+"唔好再用 `git add` 暫存任何其他嘢——就按暫存區現時嘅樣子提交,"+"並且根據上面嘅暫存 diff 起草提交訊息。",AMEND_PROMPT3="用 `git commit --amend` 修補最近嘅一次提交。"+"這係用戶明確要求嘅,所以只有本次請求准許修補。"+"先暫存相關改動,然後判斷現有嘅提交訊息係唔係仍然貼切:"+"貼切就保留,如果修補後嘅內容改變咗佢嘅含義就更新佢。"+"除非用戶講明咁做係安全嘅,唔好修補已經推送過嘅提交。";DIFF_TRUNCATED_NOTE3="上面嘅 diff 因為太大被截斷咗。"+"如果寫提交訊息之前需要睇完剩落嘅部分,自己跑一次 `git diff HEAD`。",FORGE_LABELS3={github:"GitHub",gitlab:"GitLab",gitea:"Gitea/Forgejo",bitbucket:"Bitbucket"}});function promptBundle(language){let id=normalizeLanguage(language);return BUNDLES[id]??BUNDLES[DEFAULT_LANGUAGE]}function initPrompts(language){return promptBundle(language).init}function reviewPrompts(language){return promptBundle(language).review}function simplifyPrompts(language){return promptBundle(language).simplify}function commitPrompts(language){return promptBundle(language).commit}var BUNDLES;var init_prompts=__esm(()=>{init_commit();init_commit2();init_commit3();init_language();BUNDLES={english:{init:exports_init,review:exports_review,simplify:exports_simplify,commit:exports_commit},chinese:{init:exports_init2,review:exports_review2,simplify:exports_simplify2,commit:exports_commit2},cantonese:{init:exports_init3,review:exports_review3,simplify:exports_simplify3,commit:exports_commit3}}});function buildInitPrompt(args="",language=readLanguageSetting()){let{INIT_PROMPT:base,INIT_EXTRA_HEADING}=initPrompts(language),extra=String(args??"").trim();if(extra.length===0)return base;return`${base}
2156
2140
 
2157
2141
  ${INIT_EXTRA_HEADING}
2158
- ${extra}`}var INIT_PROMPT4;var init_init=__esm(()=>{init_prompts();init_language();init_settings_file();INIT_PROMPT4=initPrompts(DEFAULT_LANGUAGE).INIT_PROMPT});function languageConfigOption(language){return{id:LANGUAGE_OPTION_ID,name:"Language",type:"select",category:"miro",description:"Language of miro's built-in workflow prompts",currentValue:normalizeLanguage(language),options:LANGUAGES.map((item)=>({value:item.value,name:item.name})),local:!0}}function isLanguageOption(option){return option?.id===LANGUAGE_OPTION_ID}function withLanguageOption(options,language){let listed=Array.isArray(options)?options:[];if(listed.some((option)=>option?.id===LANGUAGE_OPTION_ID))return listed;return[...listed,languageConfigOption(language)]}var LANGUAGE_OPTION_ID="language";var init_language_config=__esm(()=>{init_language()});import os11 from"node:os";import path26 from"node:path";function shortenHome(dir){let home=os11.homedir();if(!dir)return null;if(dir===home)return"~";return dir.startsWith(`${home}${path26.sep}`)?`~${dir.slice(home.length)}`:dir}function formatTokens2(value){if(typeof value!=="number"||!Number.isFinite(value)||value<=0)return null;if(value<1000)return String(Math.round(value));if(value<1e6)return`${(value/1000).toFixed(1).replace(/\.0$/,"")}k`;return`${(value/1e6).toFixed(1).replace(/\.0$/,"")}M`}function positiveOrZero(count){return typeof count==="number"&&Number.isFinite(count)&&count>0?count:0}function formatSessionCost(cost){let amount=cost?.amount;if(typeof amount!=="number"||!Number.isFinite(amount)||amount<=0)return null;let digits=amount<0.001?4:amount<1?3:2,currency=typeof cost?.currency==="string"&&cost.currency?cost.currency:"USD",value=amount.toFixed(digits);if(currency!=="USD")return`${value} ${currency}`;return`$${value}`}function formatSessionTokenUsage(tokens,cost){let value=(count)=>{if(typeof count!=="number"||!Number.isFinite(count)||count<0)return null;return formatTokens2(count)??"0"},parts=[],fields=[["↑",tokens?.input],["↓",tokens?.output]].flatMap(([arrow,count])=>{let formatted=value(count);return formatted==null?[]:[`${arrow}${formatted}`]}).join(" ");if(fields)parts.push(fields);let cacheRead=positiveOrZero(tokens?.cacheRead),cacheWrite=positiveOrZero(tokens?.cacheWrite);if(cacheRead>0||cacheWrite>0){let cacheParts=[`R${value(cacheRead)} W${value(cacheWrite)}`],prompt=positiveOrZero(tokens?.input)+cacheRead+cacheWrite;if(prompt>0)cacheParts.push(`CH${(cacheRead/prompt*100).toFixed(1)}%`);parts.push(cacheParts.join(" "))}let spent=formatSessionCost(cost);if(spent)parts.push(spent);return parts.length>0?`Stat ${parts.join(" ")}`:null}function usedPercent(usage){let used=usage?.used,size=usage?.size;if(typeof used!=="number"||typeof size!=="number"||size<=0)return null;return Math.min(100,Math.max(0,Math.round(used/size*100)))}function runStateText(snapshot){if(snapshot.cancelling)return"Interrupting";if(!snapshot.busy)return"Ready";return snapshot.thinking?"Thinking":"Working"}function resolveStatusLineItem(id){if(typeof id!=="string")return null;return ALIAS_TO_ID.get(id.trim().toLowerCase())??null}function parseStatusLineItems(ids){let items=[],invalid=[],seen=new Set;for(let raw of Array.isArray(ids)?ids:[]){let id=resolveStatusLineItem(raw);if(id==null){if(typeof raw==="string"&&raw.trim())invalid.push(raw.trim());continue}if(seen.has(id))continue;seen.add(id),items.push(id)}return{items,invalid}}var ITEM_DEFINITIONS,STATUS_LINE_ITEMS,ALIAS_TO_ID;var init_items7=__esm(()=>{ITEM_DEFINITIONS=[{id:"model",aliases:["model-name"],label:"Current model name",placeholder:"gpt-5",tone:"model",description:"当前模型名",value:(s)=>s.modelName??null},{id:"model-with-reasoning",label:"Current model name with reasoning level",placeholder:"gpt-5 medium",tone:"model",description:"模型名 + 思考强度",value:(s)=>s.modelName==null?null:s.effortName?`${s.modelName} ${s.effortName}`:s.modelName},{id:"reasoning",label:"Current reasoning level",placeholder:"medium",tone:"model",description:"当前思考强度",value:(s)=>s.effortName??null},{id:"mode",label:"Current session mode",placeholder:"default",tone:"accent",description:"当前会话模式",value:(s)=>s.modeName??null},{id:"permission-mode",aliases:["permissions"],label:"Current permission mode",placeholder:"AUTO",tone:"accent",description:"当前权限模式",value:(s)=>{if(s.permissionMode==="auto")return"AUTO";if(s.permissionMode==="manual")return"MANUAL";return null}},{id:"current-dir",label:"Current working directory",placeholder:"~/workspace/miro",tone:"dir",description:"当前工作目录",value:(s)=>shortenHome(s.cwd)??null},{id:"project-name",aliases:["project","project-root"],label:"Current project name",placeholder:"miro",tone:"dir",description:"项目名",value:(s)=>s.projectName??null},{id:"hostname",label:"Current hostname",placeholder:"localhost",tone:"dim",description:"主机名",value:(s)=>s.hostname??null},{id:"git-branch",label:"Current Git branch",placeholder:"feat/branch-name",tone:"accent",description:"当前 Git 分支",value:(s)=>s.gitBranch??null},{id:"run-state",aliases:["status"],label:"Current run state",placeholder:"Ready",tone:"state",description:"运行状态",value:(s)=>runStateText(s)},{id:"provider",label:"Current ACP provider",placeholder:"Codex",tone:"accent",description:"当前 ACP provider",value:(s)=>s.providerName??null},{id:"session-id",aliases:["thread-id"],label:"Current session ID",placeholder:"1094dbe3",tone:"dim",description:"会话 id(短格式)",value:(s)=>typeof s.sessionId==="string"&&s.sessionId?s.sessionId.slice(0,8):null},{id:"session-title",aliases:["thread-title"],label:"Current session title",placeholder:"Status line setup",tone:"dim",description:"会话标题",value:(s)=>typeof s.sessionTitle==="string"&&s.sessionTitle.trim()?s.sessionTitle.trim():null},{id:"miro-version",aliases:["version"],label:"Miro version",placeholder:"v0.1.0",tone:"dim",description:"miro 版本号",value:(s)=>s.version?`v${s.version}`:null},{id:"context-used",aliases:["context-usage"],label:"Context window used percentage",placeholder:"28% used",tone:"state",description:"上下文已用百分比",value:(s)=>{let percent=usedPercent(s.usage);return percent==null?null:`${percent}% used`}},{id:"context-remaining",label:"Context window remaining percentage",placeholder:"72% left",tone:"state",description:"上下文剩余百分比",value:(s)=>{let percent=usedPercent(s.usage);return percent==null?null:`${100-percent}% left`}},{id:"context-window-size",label:"Context window size",placeholder:"200k ctx",tone:"dim",description:"上下文窗口总量",value:(s)=>{let size=formatTokens2(s.usage?.size);return size==null?null:`${size} ctx`}},{id:"task-progress",label:"Current task progress",placeholder:"3/7",tone:"accent",description:"最新 checklist 进度",value:(s)=>{let total=s.plan?.total??0;if(!total)return null;return`${s.plan.completed??0}/${total}`}},{id:"goal",aliases:["goal-status"],label:"Active goal status and progress",placeholder:"goal active 3t",tone:"accent",description:"目标状态与进度",value:(s)=>{let goal=s.goal;if(goal==null||typeof goal.status!=="string")return null;let limit=goal.budget?.turnBudget,turns=typeof goal.turnsUsed==="number"?goal.turnsUsed:0,progress=limit!=null?`${turns}/${limit}t`:`${turns}t`;return`goal ${goal.status} ${progress}`}},{id:"used-tokens",label:"Total session tokens",placeholder:"12.3k tokens",tone:"dim",description:"会话累计 token",value:(s)=>{let total=formatTokens2(s.sessionTokens?.total);return total==null?null:`${total} tokens`}},{id:"input-tokens",label:"Total input tokens",placeholder:"10k in",tone:"dim",description:"累计输入 token",value:(s)=>{let value=formatTokens2(s.sessionTokens?.input);return value==null?null:`${value} in`}},{id:"output-tokens",label:"Total output tokens",placeholder:"2k out",tone:"dim",description:"累计输出 token",value:(s)=>{let value=formatTokens2(s.sessionTokens?.output);return value==null?null:`${value} out`}},{id:"thought-tokens",label:"Total reasoning tokens",placeholder:"345 think",tone:"dim",description:"累计思考 token",value:(s)=>{let value=formatTokens2(s.sessionTokens?.thought);return value==null?null:`${value} think`}},{id:"session-cost",label:"Estimated session cost",placeholder:"$1.50",tone:"dim",description:"会话累计成本",value:(s)=>{let amount=s.sessionCost?.amount;if(typeof amount!=="number"||!Number.isFinite(amount)||amount<=0)return null;let currency=s.sessionCost.currency??"USD";return currency==="USD"?`$${amount.toFixed(2)}`:`${amount.toFixed(2)} ${currency}`}}],STATUS_LINE_ITEMS=new Map(ITEM_DEFINITIONS.map((item)=>[item.id,item])),ALIAS_TO_ID=new Map;for(let item of ITEM_DEFINITIONS){ALIAS_TO_ID.set(item.id,item.id);for(let alias of item.aliases??[])ALIAS_TO_ID.set(alias,item.id)}});function composerHasDraft(snapshot){return Boolean(snapshot?.value)||(snapshot?.pastes?.size??0)>0}function inputHint({busy,hasDraft,canSteer,queuedCount=0,queuePaused=!1}){if(!busy||!hasDraft)return null;let action=canSteer?"Enter to steer · Tab to queue":"Enter/Tab to queue · steering unavailable",queue=queuedCount>0?` · ${queuedCount} message${queuedCount>1?"s":""} queued${queuePaused?" · paused":""}`:"";return`${action} · Ctrl+Q to review queue${queue}`}import{execFile}from"node:child_process";import{existsSync as existsSync10}from"node:fs";import path27 from"node:path";function projectNameFor(cwd){if(typeof cwd!=="string"||cwd.length===0)return null;if(projectNameCache.has(cwd))return projectNameCache.get(cwd);let dir=cwd,found=null;while(!0){if(PROJECT_MARKERS.some((marker)=>existsSync10(path27.join(dir,marker)))){found=path27.basename(dir);break}let parent=path27.dirname(dir);if(parent===dir)break;dir=parent}let name=found??(path27.basename(cwd)||null);return projectNameCache.set(cwd,name),name}function loadGitBranch(cwd){if(typeof cwd!=="string"||cwd.length===0)return Promise.resolve(null);if(branchCache.has(cwd))return Promise.resolve(branchCache.get(cwd));let pending=inFlight.get(cwd);if(pending)return pending;let task=new Promise((resolve)=>{execFile("git",["rev-parse","--abbrev-ref","HEAD"],{cwd,timeout:2000},(error,stdout)=>{let branch=error?null:String(stdout).trim();resolve(branch&&branch!=="HEAD"?branch:null)})}).then((branch)=>(branchCache.set(cwd,branch),inFlight.delete(cwd),branch));return inFlight.set(cwd,task),task}var projectNameCache,branchCache,inFlight,PROJECT_MARKERS;var init_workspace_info=__esm(()=>{projectNameCache=new Map,branchCache=new Map,inFlight=new Map,PROJECT_MARKERS=[".git","package.json","Cargo.toml","go.mod","pyproject.toml"]});function getNextModeId(modes){if(!modes||!Array.isArray(modes.availableModes))return null;let list=modes.availableModes;if(list.length<=1)return null;let current=modes.currentModeId,nextIndex=(list.findIndex((mode)=>mode.id===current)+1)%list.length;return list[nextIndex]?.id??null}var createStoreImpl=(createState)=>{let state,listeners=new Set,setState=(partial,replace)=>{let nextState=typeof partial==="function"?partial(state):partial;if(!Object.is(nextState,state)){let previousState=state;state=(replace!=null?replace:typeof nextState!=="object"||nextState===null)?nextState:Object.assign({},state,nextState),listeners.forEach((listener)=>listener(state,previousState))}},getState=()=>state,api={setState,getState,getInitialState:()=>initialState,subscribe:(listener)=>(listeners.add(listener),()=>listeners.delete(listener))},initialState=state=createState(setState,getState,api);return api},createStore=(createState)=>createState?createStoreImpl(createState):createStoreImpl;var init_vanilla=()=>{};function useStore(api,selector=identity3){let slice=$useSyncExternalStore(api.subscribe,$useCallback(()=>selector(api.getState()),[api,selector]),$useCallback(()=>selector(api.getInitialState()),[api,selector]));return $useDebugValue(slice),slice}var identity3=(arg)=>arg,createImpl=(createState)=>{let api=createStore(createState),useBoundStore=(selector)=>useStore(api,selector);return Object.assign(useBoundStore,api),useBoundStore},create8=(createState)=>createState?createImpl(createState):createImpl;var init_react=__esm(()=>{init_react_production();init_vanilla()});var init_esm2=__esm(()=>{init_vanilla();init_react()});import os12 from"node:os";import path28 from"node:path";import process26 from"node:process";function extractToolPreview(content){if(!Array.isArray(content))return null;let texts=[];for(let block of content)if(block?.type==="content"&&block.content?.type==="text"&&typeof block.content.text==="string")texts.push(block.content.text);if(texts.length===0)return null;let joined=texts.join(`
2159
- `).replace(/\n+$/,"");if(joined.trim().length===0)return null;let lines=joined.split(`
2160
- `),shown=lines.slice(0,TOOL_PREVIEW_MAX_LINES).map((line)=>line.length>PREVIEW_LINE_MAX_CHARS?`${line.slice(0,PREVIEW_LINE_MAX_CHARS-1)}…`:line);return{lines:shown,more:Math.max(0,lines.length-shown.length)}}function extractToolOutputPreview(rawOutput){if(rawOutput==null||typeof rawOutput!=="object")return null;let texts=[rawOutput.stdout,rawOutput.stderr].filter((text)=>typeof text==="string"&&text.trim().length>0);if(texts.length===0)return null;return extractToolPreview([{type:"content",content:{type:"text",text:texts.join(`
2161
- `)}}])}function extractOutputText(rawOutput){if(rawOutput==null||typeof rawOutput!=="object")return"";return[rawOutput.stdout,rawOutput.stderr].filter((text)=>typeof text==="string"&&text.trim().length>0).join(`
2162
- `)}function firstNonEmptyLine(text){if(typeof text!=="string")return"";for(let line of text.replace(/\r\n?/g,`
2163
- `).split(`
2164
- `)){let flat=line.trim();if(flat.length>0)return flat}return""}function truncatePreviewLine(text){return text.length>PREVIEW_LINE_MAX_CHARS?`${text.slice(0,PREVIEW_LINE_MAX_CHARS-1)}…`:text}function commandText(rawInput){let command=rawInput?.command;if(typeof command!=="string")return null;let normalized=command.replace(/\r\n?/g,`
2165
- `).replace(/\n+$/,"");if(normalized.trim().length===0)return null;return normalized.length>COMMAND_TEXT_MAX_CHARS?`${normalized.slice(0,COMMAND_TEXT_MAX_CHARS)}…`:normalized}function textContent4(content){if(!Array.isArray(content))return"";return content.filter((block)=>block?.type==="content"&&block.content?.type==="text"&&typeof block.content.text==="string").map((block)=>block.content.text).join(`
2166
- `)}function clippedDetail(text){let value=String(text??"").replace(/\r\n?/g,`
2167
- `).replace(/\n+$/,"");if(value.length<=TOOL_DETAIL_MAX_CHARS)return value;return`${value.slice(0,TOOL_DETAIL_MAX_CHARS)}
2168
- … detail truncated`}function safeJson2(value){if(value==null)return"";if(typeof value==="string")return clippedDetail(value);try{return clippedDetail(JSON.stringify(value,(key,item)=>{if(key==="data"&&typeof item==="string"&&item.length>120)return`[binary data: ${item.length} chars]`;return item},2))}catch{return clippedDetail(String(value))}}function buildToolDetail(info={}){let output=extractOutputText(info.rawOutput)||textContent4(info.content);return{kind:info.kind??null,title:typeof info.title==="string"?info.title:null,input:safeJson2(info.rawInput),output:clippedDetail(output),locations:safeJson2(info.locations)}}function imageContent(content){if(!Array.isArray(content))return null;return content.find((block)=>block?.type==="content"&&block.content?.type==="image")?.content??null}function imageBytes(image){for(let key of["bytes","byteLength","size","fileSize"])if(typeof image?.[key]==="number"&&Number.isFinite(image[key])&&image[key]>=0)return image[key];if(typeof image?.data!=="string"||image.data.length===0)return null;let padding=image.data.endsWith("==")?2:image.data.endsWith("=")?1:0;return Math.max(0,Math.floor(image.data.length*3/4)-padding)}function formatImageBytes(bytes){if(bytes==null)return"";if(bytes<1024)return`${bytes}B`;if(bytes<1048576)return`${Math.round(bytes/1024)}KB`;return`${Math.round(bytes/1048576)}MB`}function summarizeReadResult(info={}){let outputText=extractOutputText(info.rawOutput),contentText=textContent4(info.content),text=outputText||contentText;if(info.status==="failed"){let error=firstNonEmptyLine(text);return error?{lines:[truncatePreviewLine(error)],more:0}:null}if(text.trim().length>0){let lines=text.replace(/\r\n?/g,`
2169
- `).replace(/\n+$/,"").split(`
2170
- `);return{lines:[`Read ${lines.length} ${lines.length===1?"line":"lines"}`],more:0}}let image=imageContent(info.content);if(!image)return null;let size=formatImageBytes(imageBytes(image));return{lines:[`Read image${size?` (${size})`:""}`],more:0}}function summarizeEditResult(info={}){if(info.status==="failed"){let error=firstNonEmptyLine(extractOutputText(info.rawOutput)||textContent4(info.content));return error?{lines:[truncatePreviewLine(error)],more:0}:null}let applyContent=info.rawInput?.apply_content,text=typeof applyContent==="string"&&applyContent.length>0?applyContent:textContent4(info.content);if(text.trim().length===0)return null;let lines=text.replace(/\r\n?/g,`
2171
- `).replace(/\n+$/,"").split(`
2172
- `);return{lines:[`Wrote ${lines.length} ${lines.length===1?"line":"lines"}`],more:0}}function summarizeQuestionResult(info){let output=extractOutputText(info.rawOutput)||textContent4(info.content),result;try{result=JSON.parse(output)}catch{return null}if(!result?.answers||typeof result.answers!=="object"||Array.isArray(result.answers))return null;let questions=Array.isArray(info.rawInput?.questions)?info.rawInput.questions:[],lines=[];for(let[id,answer]of Object.entries(result.answers)){if(typeof answer!=="string"||!answer.trim())continue;let question=questions.find((item)=>item?.id===id),title=question?.header||question?.question||id,notes=result.annotations?.[id]?.notes,summary=`${title}: ${answer}${typeof notes==="string"&&notes.trim()?` (${notes})`:""}`.replace(/\s+/g," ").trim();lines.push(truncatePreviewLine(summary))}return lines.length>0?{lines,more:0}:null}function restoreQuestionPreview(tool){if(tool?.label?.name!=="Question"||tool.preview?.lines?.length!==1||tool.preview.lines[0]!=="{"||typeof tool.detail?.output!=="string")return null;let rawInput;try{rawInput=JSON.parse(tool.detail.input)}catch{return null}return summarizeQuestionResult({rawInput,content:[{type:"content",content:{type:"text",text:tool.detail.output}}]})}function summarizeToolResult(info={}){if(info.kind==="read"||info.kind==null&&info.name==="Read")return summarizeReadResult(info);if(info.kind==="execute")return extractToolOutputPreview(info.rawOutput)??extractToolPreview(info.content);if(info.kind==="edit"||info.kind==null&&info.name==="Edit")return summarizeEditResult(info);if(info.name==="request_user_input"||info.title==="Question"){let summary=summarizeQuestionResult(info);if(summary)return summary}let text=firstNonEmptyLine(extractOutputText(info.rawOutput)||textContent4(info.content));return text?{lines:[truncatePreviewLine(text)],more:0}:null}function preferredDisplayName(name,kind,title){let wire=typeof name==="string"?name.trim():"",byKind=KIND_NAMES[kind]??"",byTitle=typeof title==="string"?title.trim():"";if(wire&&WIRE_TOOL_NAME.test(wire))return byKind||byTitle||wire;if(wire&&byTitle&&wire.toLowerCase()===byTitle.toLowerCase())return byTitle;return wire||byKind||byTitle||"Tool"}function displayPath(filePath){if(typeof filePath!=="string"||filePath.length===0)return"";try{let relativePath=path28.relative(process26.cwd(),filePath);if(relativePath&&!relativePath.startsWith("..")&&!path28.isAbsolute(relativePath))return relativePath;let home=os12.homedir();if(home&&filePath.startsWith(home+path28.sep))return`~${filePath.slice(home.length)}`}catch{}return filePath}function truncate4(text){let flat=text.replace(/\s*\n\s*/g," ").trim();if(flat.length<=MAX_ARGS_DISPLAY_CHARS)return flat;return`${flat.slice(0,MAX_ARGS_DISPLAY_CHARS-1)}…`}function pickString(input,keys){if(input==null||typeof input!=="object")return null;for(let key of keys){let value=input[key];if(typeof value==="string"&&value.trim().length>0)return value}return null}function formatToolLabel(info){let{name,kind,title,rawInput,locations}=info??{};if(name==="mcp_call"||name==="mcp_list_tools"){let target=[rawInput?.server,name==="mcp_call"?rawInput?.name:rawInput?.query].filter((value)=>typeof value==="string"&&value.length>0).join(" / ");return{name:name==="mcp_call"?"MCP":"MCP tools",args:truncate4(target)}}if(rawInput?.tool_call_name==="spawn_agent"){let agentName=typeof rawInput.sub_content==="string"&&rawInput.sub_content.trim()||typeof title==="string"&&title.trim()||"子智能体",summary=(typeof rawInput.message==="string"?rawInput.message:"").split(`
2173
- `).map((line)=>line.trim()).find((line)=>line.length>0)??"";return{name:truncate4(agentName),args:truncate4(summary)}}let displayName=preferredDisplayName(name,kind,title),args="";if((name==="request_user_input"||title==="Question")&&Array.isArray(rawInput?.questions))args=rawInput.questions.map((question)=>question?.question).filter((question)=>typeof question==="string"&&question.trim()).join(" | ");let location2=Array.isArray(locations)?locations[0]:null,pathArg=pickString(rawInput,PATH_KEYS),commandArg=pickString(rawInput,COMMAND_KEYS);if(!args&&(kind==="search"&&commandArg))args=commandArg;else if(!args&&location2&&typeof location2.path==="string"&&location2.path.length>0){if(args=displayPath(location2.path),typeof location2.line==="number")args+=`:${location2.line}`}else if(!args&&pathArg)args=displayPath(pathArg);else if(!args&&commandArg)args=commandArg;else if(!args&&typeof title==="string"&&title.trim()&&title.trim()!==displayName)args=title.trim();return{name:truncate4(displayName),args:truncate4(args)}}var TERMINAL_STATUSES,TOOL_PREVIEW_MAX_LINES=5,COMMAND_TEXT_MAX_CHARS=1e4,PREVIEW_LINE_MAX_CHARS=200,TOOL_DETAIL_MAX_CHARS=200000,KIND_NAMES,WIRE_TOOL_NAME,PATH_KEYS,COMMAND_KEYS,MAX_ARGS_DISPLAY_CHARS=160;var init_tool_title=__esm(()=>{TERMINAL_STATUSES=new Set(["completed","failed","cancelled"]);KIND_NAMES={read:"Read",edit:"Edit",execute:"Bash",search:"Search",fetch:"Fetch",think:"Think",delete:"Delete",move:"Move"},WIRE_TOOL_NAME=/^[a-z0-9]+(?:_[a-z0-9]+)+$/;PATH_KEYS=["path","file_path","filePath","abs_path","filename","url","uri","sub_content_event_value"],COMMAND_KEYS=["command","query","pattern","search_term","sub_content"]});function parsePatch(uniDiff){let diffstr=uniDiff.split(/\n/),list=[],i=0;function isGitDiffHeader(line){return/^diff --git /.test(line)}function isDiffHeader(line){return isGitDiffHeader(line)||/^Index:\s/.test(line)||/^diff(?: -r \w+)+\s/.test(line)}function isFileHeader(line){return/^(---|\+\+\+)\s/.test(line)}function isHunkHeader(line){return/^@@\s/.test(line)}function parseIndex(){var _a;let index={};index.hunks=[],list.push(index);let seenDiffHeader=!1;while(i<diffstr.length){let line=diffstr[i];if(isFileHeader(line)||isHunkHeader(line))break;if(isGitDiffHeader(line)){if(seenDiffHeader)return;seenDiffHeader=!0,index.isGit=!0;let paths=parseGitDiffHeader(line);if(paths)index.oldFileName=paths.oldFileName,index.newFileName=paths.newFileName;i++;while(i<diffstr.length){let extLine=diffstr[i];if(isFileHeader(extLine)||isHunkHeader(extLine)||isDiffHeader(extLine))break;let renameFromMatch=/^rename from (.*)/.exec(extLine);if(renameFromMatch)index.oldFileName="a/"+unquoteIfQuoted(renameFromMatch[1]),index.isRename=!0;let renameToMatch=/^rename to (.*)/.exec(extLine);if(renameToMatch)index.newFileName="b/"+unquoteIfQuoted(renameToMatch[1]),index.isRename=!0;let copyFromMatch=/^copy from (.*)/.exec(extLine);if(copyFromMatch)index.oldFileName="a/"+unquoteIfQuoted(copyFromMatch[1]),index.isCopy=!0;let copyToMatch=/^copy to (.*)/.exec(extLine);if(copyToMatch)index.newFileName="b/"+unquoteIfQuoted(copyToMatch[1]),index.isCopy=!0;let newFileModeMatch=/^new file mode (\d+)/.exec(extLine);if(newFileModeMatch)index.isCreate=!0,index.newMode=newFileModeMatch[1];let deletedFileModeMatch=/^deleted file mode (\d+)/.exec(extLine);if(deletedFileModeMatch)index.isDelete=!0,index.oldMode=deletedFileModeMatch[1];let oldModeMatch=/^old mode (\d+)/.exec(extLine);if(oldModeMatch)index.oldMode=oldModeMatch[1];let newModeMatch=/^new mode (\d+)/.exec(extLine);if(newModeMatch)index.newMode=newModeMatch[1];if(/^Binary files /.test(extLine))index.isBinary=!0;i++}continue}else if(isDiffHeader(line)){if(seenDiffHeader)return;seenDiffHeader=!0;let headerMatch=/^(?:Index:|diff(?: -r \w+)+)\s+/.exec(line);if(headerMatch)index.index=line.substring(headerMatch[0].length).trim()}i++}if(parseFileHeader(index),parseFileHeader(index),index.oldFileName===void 0!==(index.newFileName===void 0))throw Error("Missing "+(index.oldFileName!==void 0?'"+++ ..."':'"--- ..."')+" file header for "+((_a=index.oldFileName)!==null&&_a!==void 0?_a:index.newFileName));while(i<diffstr.length){let line=diffstr[i];if(isDiffHeader(line)||isFileHeader(line)||/^===================================================================/.test(line))break;else if(isHunkHeader(line))index.hunks.push(parseHunk());else i++}}function parseGitDiffHeader(line){let rest=line.substring(11);if(rest.startsWith('"')){let oldPath=parseQuotedFileName(rest);if(oldPath===null)return null;let afterOld=rest.substring(oldPath.rawLength+1),newFileName;if(afterOld.startsWith('"')){let newPath=parseQuotedFileName(afterOld);if(newPath===null)return null;newFileName=newPath.fileName}else newFileName=afterOld;return{oldFileName:oldPath.fileName,newFileName}}let quoteIdx=rest.indexOf('"');if(quoteIdx>0){let oldFileName=rest.substring(0,quoteIdx-1),newPath=parseQuotedFileName(rest.substring(quoteIdx));if(newPath===null)return null;return{oldFileName,newFileName:newPath.fileName}}if(rest.startsWith("a/")){let splits=[],idx=0;while(!0){if(idx=rest.indexOf(" b/",idx+1),idx===-1)break;splits.push(idx)}if(splits.length>0){let mid=splits[Math.floor(splits.length/2)];return{oldFileName:rest.substring(0,mid),newFileName:rest.substring(mid+1)}}}return null}function unquoteIfQuoted(s){if(s.startsWith('"')){let parsed=parseQuotedFileName(s);if(parsed)return parsed.fileName}return s}function parseQuotedFileName(s){if(!s.startsWith('"'))return null;let result="",j=1;while(j<s.length){if(s[j]==='"')return{fileName:result,rawLength:j+1};if(s[j]==="\\"&&j+1<s.length)switch(j++,s[j]){case"a":result+="\x07";break;case"b":result+="\b";break;case"f":result+="\f";break;case"n":result+=`
2174
- `;break;case"r":result+="\r";break;case"t":result+="\t";break;case"v":result+="\v";break;case"\\":result+="\\";break;case'"':result+='"';break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{if(j+2>=s.length||s[j+1]<"0"||s[j+1]>"7"||s[j+2]<"0"||s[j+2]>"7")return null;let bytes=[parseInt(s.substring(j,j+3),8)];j+=3;while(s[j]==="\\"&&s[j+1]>="0"&&s[j+1]<="7"){if(j+3>=s.length||s[j+2]<"0"||s[j+2]>"7"||s[j+3]<"0"||s[j+3]>"7")return null;bytes.push(parseInt(s.substring(j+1,j+4),8)),j+=4}result+=new TextDecoder("utf-8").decode(new Uint8Array(bytes));continue}default:return null}else result+=s[j];j++}return null}function parseFileHeader(index){let fileHeaderMatch=/^(---|\+\+\+)\s+/.exec(diffstr[i]);if(fileHeaderMatch){let prefix=fileHeaderMatch[1],data=diffstr[i].substring(3).trim().split("\t",2),header=(data[1]||"").trim(),fileName=data[0];if(fileName.startsWith('"'))fileName=unquoteIfQuoted(fileName);else fileName=fileName.replace(/\\\\/g,"\\");if(prefix==="---")index.oldFileName=fileName,index.oldHeader=header;else index.newFileName=fileName,index.newHeader=header;i++}}function parseHunk(){var _a;let chunkHeaderIndex=i,chunkHeaderLine=diffstr[i++],chunkHeader=chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/),hunk={oldStart:+chunkHeader[1],oldLines:typeof chunkHeader[2]>"u"?1:+chunkHeader[2],newStart:+chunkHeader[3],newLines:typeof chunkHeader[4]>"u"?1:+chunkHeader[4],lines:[]};if(hunk.oldLines===0)hunk.oldStart+=1;if(hunk.newLines===0)hunk.newStart+=1;let addCount=0,removeCount=0;for(;i<diffstr.length&&(removeCount<hunk.oldLines||addCount<hunk.newLines||((_a=diffstr[i])===null||_a===void 0?void 0:_a.startsWith("\\")));i++){let operation=diffstr[i].length==0&&i!=diffstr.length-1?" ":diffstr[i][0];if(operation==="+"||operation==="-"||operation===" "||operation==="\\"){if(hunk.lines.push(diffstr[i]),operation==="+")addCount++;else if(operation==="-")removeCount++;else if(operation===" ")addCount++,removeCount++}else throw Error(`Hunk at line ${chunkHeaderIndex+1} contained invalid line ${diffstr[i]}`)}if(!addCount&&hunk.newLines===1)hunk.newLines=0;if(!removeCount&&hunk.oldLines===1)hunk.oldLines=0;if(addCount!==hunk.newLines)throw Error("Added line count did not match for hunk at line "+(chunkHeaderIndex+1));if(removeCount!==hunk.oldLines)throw Error("Removed line count did not match for hunk at line "+(chunkHeaderIndex+1));if(i<diffstr.length&&diffstr[i]&&/^[+ -]/.test(diffstr[i])&&!isFileHeader(diffstr[i]))throw Error("Hunk at line "+(chunkHeaderIndex+1)+" has more lines than expected (expected "+hunk.oldLines+" old lines and "+hunk.newLines+" new lines)");return hunk}while(i<diffstr.length)parseIndex();return list}class Diff2{diff(oldStr,newStr,options={}){let callback;if(typeof options==="function")callback=options,options={};else if("callback"in options)callback=options.callback;let oldString=this.castInput(oldStr,options),newString=this.castInput(newStr,options),oldTokens=this.removeEmpty(this.tokenize(oldString,options)),newTokens=this.removeEmpty(this.tokenize(newString,options));return this.diffWithOptionsObj(oldTokens,newTokens,options,callback)}diffWithOptionsObj(oldTokens,newTokens,options,callback){var _a;let done=(value)=>{if(value=this.postProcess(value,options),callback){setTimeout(function(){callback(value)},0);return}else return value},newLen=newTokens.length,oldLen=oldTokens.length,editLength=1,maxEditLength=newLen+oldLen;if(options.maxEditLength!=null)maxEditLength=Math.min(maxEditLength,options.maxEditLength);let maxExecutionTime=(_a=options.timeout)!==null&&_a!==void 0?_a:1/0,abortAfterTimestamp=Date.now()+maxExecutionTime,bestPath=[{oldPos:-1,lastComponent:void 0}],newPos=this.extractCommon(bestPath[0],newTokens,oldTokens,0,options);if(bestPath[0].oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(bestPath[0].lastComponent,newTokens,oldTokens));let minDiagonalToConsider=-1/0,maxDiagonalToConsider=1/0,execEditLength=()=>{for(let diagonalPath=Math.max(minDiagonalToConsider,-editLength);diagonalPath<=Math.min(maxDiagonalToConsider,editLength);diagonalPath+=2){let basePath,removePath=bestPath[diagonalPath-1],addPath=bestPath[diagonalPath+1];if(removePath)bestPath[diagonalPath-1]=void 0;let canAdd=!1;if(addPath){let addPathNewPos=addPath.oldPos-diagonalPath;canAdd=addPath&&0<=addPathNewPos&&addPathNewPos<newLen}let canRemove=removePath&&removePath.oldPos+1<oldLen;if(!canAdd&&!canRemove){bestPath[diagonalPath]=void 0;continue}if(!canRemove||canAdd&&removePath.oldPos<addPath.oldPos)basePath=this.addToPath(addPath,!0,!1,0,options);else basePath=this.addToPath(removePath,!1,!0,1,options);if(newPos=this.extractCommon(basePath,newTokens,oldTokens,diagonalPath,options),basePath.oldPos+1>=oldLen&&newPos+1>=newLen)return done(this.buildValues(basePath.lastComponent,newTokens,oldTokens))||!0;else{if(bestPath[diagonalPath]=basePath,basePath.oldPos+1>=oldLen)maxDiagonalToConsider=Math.min(maxDiagonalToConsider,diagonalPath-1);if(newPos+1>=newLen)minDiagonalToConsider=Math.max(minDiagonalToConsider,diagonalPath+1)}}editLength++};if(callback)(function exec(){setTimeout(function(){if(editLength>maxEditLength||Date.now()>abortAfterTimestamp)return callback(void 0);if(!execEditLength())exec()},0)})();else while(editLength<=maxEditLength&&Date.now()<=abortAfterTimestamp){let ret=execEditLength();if(ret)return ret}}addToPath(path,added,removed,oldPosInc,options){let last=path.lastComponent;if(last&&!options.oneChangePerToken&&last.added===added&&last.removed===removed)return{oldPos:path.oldPos+oldPosInc,lastComponent:{count:last.count+1,added,removed,previousComponent:last.previousComponent}};else return{oldPos:path.oldPos+oldPosInc,lastComponent:{count:1,added,removed,previousComponent:last}}}extractCommon(basePath,newTokens,oldTokens,diagonalPath,options){let newLen=newTokens.length,oldLen=oldTokens.length,oldPos=basePath.oldPos,newPos=oldPos-diagonalPath,commonCount=0;while(newPos+1<newLen&&oldPos+1<oldLen&&this.equals(oldTokens[oldPos+1],newTokens[newPos+1],options))if(newPos++,oldPos++,commonCount++,options.oneChangePerToken)basePath.lastComponent={count:1,previousComponent:basePath.lastComponent,added:!1,removed:!1};if(commonCount&&!options.oneChangePerToken)basePath.lastComponent={count:commonCount,previousComponent:basePath.lastComponent,added:!1,removed:!1};return basePath.oldPos=oldPos,newPos}equals(left,right,options){if(options.comparator)return options.comparator(left,right);else return left===right||!!options.ignoreCase&&left.toLowerCase()===right.toLowerCase()}removeEmpty(array){let ret=[];for(let i=0;i<array.length;i++)if(array[i])ret.push(array[i]);return ret}castInput(value,options){return value}tokenize(value,options){return Array.from(value)}join(chars){return chars.join("")}postProcess(changeObjects,options){return changeObjects}get useLongestToken(){return!1}buildValues(lastComponent,newTokens,oldTokens){let components=[],nextComponent;while(lastComponent)components.push(lastComponent),nextComponent=lastComponent.previousComponent,delete lastComponent.previousComponent,lastComponent=nextComponent;components.reverse();let componentLen=components.length,componentPos=0,newPos=0,oldPos=0;for(;componentPos<componentLen;componentPos++){let component=components[componentPos];if(!component.removed){if(!component.added&&this.useLongestToken){let value=newTokens.slice(newPos,newPos+component.count);value=value.map(function(value,i){let oldValue=oldTokens[oldPos+i];return oldValue.length>value.length?oldValue:value}),component.value=this.join(value)}else component.value=this.join(newTokens.slice(newPos,newPos+component.count));if(newPos+=component.count,!component.added)oldPos+=component.count}else component.value=this.join(oldTokens.slice(oldPos,oldPos+component.count)),oldPos+=component.count}return components}}function diffLines(oldStr,newStr,options){return lineDiff.diff(oldStr,newStr,options)}function tokenize4(value,options){if(options.stripTrailingCr)value=value.replace(/\r\n/g,`
2175
- `);let retLines=[],linesAndNewlines=value.split(/(\n|\r\n)/);if(!linesAndNewlines[linesAndNewlines.length-1])linesAndNewlines.pop();for(let i=0;i<linesAndNewlines.length;i++){let line=linesAndNewlines[i];if(i%2&&!options.newlineIsToken)retLines[retLines.length-1]+=line;else retLines.push(line)}return retLines}var LineDiff,lineDiff;var init_line3=__esm(()=>{LineDiff=class LineDiff extends Diff2{constructor(){super(...arguments);this.tokenize=tokenize4}equals(left,right,options){if(options.ignoreWhitespace){if(!options.newlineIsToken||!left.includes(`
2176
- `))left=left.trim();if(!options.newlineIsToken||!right.includes(`
2177
- `))right=right.trim()}else if(options.ignoreNewlineAtEof&&!options.newlineIsToken){if(left.endsWith(`
2178
- `))left=left.slice(0,-1);if(right.endsWith(`
2179
- `))right=right.slice(0,-1)}return super.equals(left,right,options)}};lineDiff=new LineDiff});function structuredPatch(oldFileName,newFileName,oldStr,newStr,oldHeader,newHeader,options){let optionsObj;if(!options)optionsObj={};else if(typeof options==="function")optionsObj={callback:options};else optionsObj=options;if(typeof optionsObj.context>"u")optionsObj.context=4;let context=optionsObj.context;if(optionsObj.newlineIsToken)throw Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(!optionsObj.callback)return diffLinesResultToPatch(diffLines(oldStr,newStr,optionsObj));else{let{callback}=optionsObj;diffLines(oldStr,newStr,Object.assign(Object.assign({},optionsObj),{callback:(diff)=>{let patch=diffLinesResultToPatch(diff);callback(patch)}}))}function diffLinesResultToPatch(diff){if(!diff)return;diff.push({value:"",lines:[]});function contextLines(lines){return lines.map(function(entry){return" "+entry})}let hunks=[],oldRangeStart=0,newRangeStart=0,curRange=[],oldLine=1,newLine=1;for(let i=0;i<diff.length;i++){let current=diff[i],lines=current.lines||splitLines(current.value);if(current.lines=lines,current.added||current.removed){if(!oldRangeStart){let prev=diff[i-1];if(oldRangeStart=oldLine,newRangeStart=newLine,prev)curRange=context>0?contextLines(prev.lines.slice(-context)):[],oldRangeStart-=curRange.length,newRangeStart-=curRange.length}for(let line of lines)curRange.push((current.added?"+":"-")+line);if(current.added)newLine+=lines.length;else oldLine+=lines.length}else{if(oldRangeStart)if(lines.length<=context*2&&i<diff.length-2)for(let line of contextLines(lines))curRange.push(line);else{let contextSize=Math.min(lines.length,context);for(let line of contextLines(lines.slice(0,contextSize)))curRange.push(line);let hunk={oldStart:oldRangeStart,oldLines:oldLine-oldRangeStart+contextSize,newStart:newRangeStart,newLines:newLine-newRangeStart+contextSize,lines:curRange};hunks.push(hunk),oldRangeStart=0,newRangeStart=0,curRange=[]}oldLine+=lines.length,newLine+=lines.length}}for(let hunk of hunks)for(let i=0;i<hunk.lines.length;i++)if(hunk.lines[i].endsWith(`
2180
- `))hunk.lines[i]=hunk.lines[i].slice(0,-1);else hunk.lines.splice(i+1,0,"\"),i++;return{oldFileName,newFileName,oldHeader,newHeader,hunks}}}function splitLines(text){let hasTrailingNl=text.endsWith(`
2181
- `),result=text.split(`
2182
- `).map((line)=>line+`
2183
- `);if(hasTrailingNl)result.pop();else result.push(result.pop().slice(0,-1));return result}var init_create5=__esm(()=>{init_line3()});var init_libesm=__esm(()=>{init_create5()});function own2(object,key){return object!=null&&Object.prototype.hasOwnProperty.call(object,key)}function normalizedText(value){return typeof value==="string"?value.replace(/\r\n?/g,`
2184
- `):value}function splitLines2(text){if(text==="")return[];let lines=normalizedText(text).split(`
2185
- `);if(lines.at(-1)==="")lines.pop();return lines}function pathFromInput(input){if(input==null||typeof input!=="object")return null;for(let key of["path","file_path","filePath","filename"])if(typeof input[key]==="string"&&input[key].length>0)return input[key];return null}function operationFor(oldText,newText,{oldMissing=!1}={}){if(oldMissing||oldText==null)return"create";if(newText===""&&oldText!=="")return"delete";if(oldText===""&&newText!=="")return"create";return"update"}function displayHunks(hunks){return hunks.map(({oldStart,oldLines,newStart,newLines,lines})=>({oldStart:oldLines===0?Math.max(0,oldStart-1):oldStart,oldLines,newStart:newLines===0?Math.max(0,newStart-1):newStart,newLines,lines:lines.filter((line)=>!line.startsWith("\\"))}))}function countChanges(hunks){let additions=0,deletions=0;for(let hunk of hunks)for(let line of hunk.lines){if(line.startsWith("+"))additions+=1;if(line.startsWith("-"))deletions+=1}return{additions,deletions}}function textHunks(oldText,newText){let oldLines=splitLines2(oldText),newLines=splitLines2(newText),terminated=(lines)=>lines.length?`${lines.join(`
2186
- `)}
2187
- `:"",patch=structuredPatch("","",terminated(oldLines),terminated(newLines),"","",{context:DIFF_CONTEXT_LINES,maxEditLength:MAX_EDIT_LENGTH,timeout:DIFF_TIMEOUT_MS});if(patch)return displayHunks(patch.hunks);return[{oldStart:oldLines.length?1:0,oldLines:oldLines.length,newStart:newLines.length?1:0,newLines:newLines.length,lines:[...oldLines.map((line)=>`-${line}`),...newLines.map((line)=>`+${line}`)]}]}function fromTexts({path,oldText,newText,source,complete,oldMissing=!1}){if(typeof newText!=="string"||!oldMissing&&typeof oldText!=="string")return null;let normalizedOld=normalizedText(oldMissing?"":oldText),normalizedNew=normalizedText(newText),hunks=textHunks(normalizedOld,normalizedNew);return{path:typeof path==="string"&&path.length>0?path:null,oldText:oldMissing?null:normalizedOld,newText:normalizedNew,hunks,...countChanges(hunks),operation:operationFor(normalizedOld,normalizedNew,{oldMissing}),source,complete,hasLineNumbers:complete}}function contentDiff(content){if(!Array.isArray(content))return null;for(let item of content){let block=item?.type==="content"?item.content:item;if(block?.type!=="diff"||typeof block.newText!=="string")continue;let oldMissing=block.oldText==null;return fromTexts({path:block.path,oldText:block.oldText,newText:block.newText,source:"acp",complete:!0,oldMissing})}return null}function cleanPatchPath(value){if(typeof value!=="string"||!value||value==="/dev/null")return null;return value.startsWith("a/")||value.startsWith("b/")?value.slice(2):value}function parseUnifiedPatch(patch,fallbackPath){if(typeof patch!=="string"||patch.trim().length===0)return null;try{let patches=parsePatch(normalizedText(patch)).filter((entry)=>entry.hunks.length>0),entry=patches.find((item)=>fallbackPath!=null&&[cleanPatchPath(item.newFileName),cleanPatchPath(item.oldFileName)].includes(fallbackPath))??patches[0];if(!entry||!entry.hunks.every((hunk)=>[hunk.oldStart,hunk.oldLines,hunk.newStart,hunk.newLines].every((value)=>Number.isSafeInteger(value)&&value>=0)))return null;let hunks=displayHunks(entry.hunks);return{path:cleanPatchPath(entry.newFileName)??fallbackPath??cleanPatchPath(entry.oldFileName),oldText:null,newText:null,hunks,...countChanges(hunks),operation:entry.oldFileName==="/dev/null"?"create":entry.newFileName==="/dev/null"?"delete":"update",source:"patch",complete:!1,hasLineNumbers:!0}}catch{return null}}function rawInputDiff(rawInput){if(rawInput==null||typeof rawInput!=="object")return null;let path=pathFromInput(rawInput);for(let key of["patch","diff"]){if(!own2(rawInput,key))continue;let value=rawInput[key];if(typeof value==="string"){let parsed=parseUnifiedPatch(value,path);if(parsed)return parsed}else if(value!=null&&typeof value==="object"){let nestedPath=pathFromInput(value)??path;if(typeof value.newText==="string")return fromTexts({path:nestedPath,oldText:value.oldText,newText:value.newText,source:"raw-input",complete:!0,oldMissing:value.oldText==null})}}if(own2(rawInput,"newText")&&typeof rawInput.newText==="string")return fromTexts({path,oldText:rawInput.oldText,newText:rawInput.newText,source:"raw-input",complete:!0,oldMissing:rawInput.oldText==null});if(own2(rawInput,"edits")&&Array.isArray(rawInput.edits)){let edits=rawInput.edits.filter((edit)=>edit!=null&&typeof edit==="object"&&typeof edit.oldText==="string"&&typeof edit.newText==="string");if(edits.length>0)return fromTexts({path,oldText:edits.map((edit)=>edit.oldText).join(`
2188
- `),newText:edits.map((edit)=>edit.newText).join(`
2189
- `),source:"raw-input",complete:!1,oldMissing:!1})}if(own2(rawInput,"new_string")&&typeof rawInput.new_string==="string")return fromTexts({path,oldText:rawInput.old_string,newText:rawInput.new_string,source:"raw-input",complete:!1,oldMissing:rawInput.old_string==null});if(own2(rawInput,"content")&&typeof rawInput.content==="string")return fromTexts({path,oldText:null,newText:rawInput.content,source:"raw-input",complete:!1,oldMissing:!0});return null}function extractToolDiff(info={}){return contentDiff(info.content)??rawInputDiff(info.rawInput)}var DIFF_CONTEXT_LINES=3,MAX_EDIT_LENGTH=1000,DIFF_TIMEOUT_MS=100;var init_tool_diff=__esm(()=>{init_libesm()});function isVisibleTool(tool){return tool?.raw?.name!=="codemode"&&tool?.name!=="codemode"&&tool?.raw?.kind!=="codemode"&&tool?.kind!=="codemode"&&tool?.label?.name!=="Codemode"}function summarizeToolCategories(items){let counts=new Map;for(let item of items){let name=String(item.label?.name??"Tool").toLowerCase(),category=name==="bash"?"commands":`${name}${name.endsWith("s")?"":name.endsWith("ch")?"es":"s"}`;counts.set(category,(counts.get(category)??0)+1)}return[...counts.entries()].sort((a,b)=>b[1]-a[1]).map(([name,count])=>`${count} ${name}`).join(" · ")}function toolForDisplay(tool){if(!tool?.group)return isVisibleTool(tool)?tool:null;let items=tool.group.items.filter(isVisibleTool);if(items.length===0)return null;if(items.length===tool.group.items.length)return tool;return{...tool,group:{...tool.group,name:`${items.length} tool calls`,summary:summarizeToolCategories(items),count:items.length,items}}}function setRecorder(next){recorder=next}function appendBlock(state,block,record=!0){let entry={id:nextId(),...block},diffLength=entry.tool?.diff==null?0:JSON.stringify(entry.tool.diff).length,entryLength=(entry.text?.length??0)+(entry.thought?.text?.length??0)+(entry.tool?.hint?.length??0)+diffLength,length=state.length+entryLength;if(record&&recorder)recorder.recordBlock(entry);if(length>MAX_TRANSCRIPT_LENGTH)return{...state,blocks:[entry],length:entryLength,epoch:state.epoch+1};return{...state,blocks:[...state.blocks,entry],length}}function commitPending(state){let{pending}=state;if(!pending||pending.text.length===0)return{...state,pending:null};let text=pending.text.replace(/\n+$/,"");if(text.length===0)return{...state,pending:null};return{...appendBlock(flushToolGroup(state),{...pending,text}),pending:null}}function openFenceStart(text,upTo){let region=text.slice(0,upTo);FENCE_PATTERN.lastIndex=0;let open=-1,match;while(match=FENCE_PATTERN.exec(region))open=open<0?match.index+match[1].length:-1;return open}function isBlockStructureLine(line,partial=!1){if(partial?TABLE_ROW_PARTIAL.test(line):TABLE_ROW.test(line))return!0;return LIST_ITEM.test(line)||BLOCKQUOTE.test(line)}function splitsBlockStructure(text,cut){let before=text.lastIndexOf(`
2190
- `,cut-1),prevLine=text.slice(before+1,cut);if(!isBlockStructureLine(prevLine))return!1;let rest=text.slice(cut+1),nextEnd=rest.indexOf(`
2191
- `);if(nextEnd<0)return rest.length===0||isBlockStructureLine(rest,!0);return isBlockStructureLine(rest.slice(0,nextEnd))}function safeCut(text,separator){let cut=text.lastIndexOf(separator);while(cut>=0){let fence=openFenceStart(text,cut);if(fence<0){if(separator!==`
2192
- `||!splitsBlockStructure(text,cut))return cut;cut=text.lastIndexOf(separator,cut-1);continue}let before=fence-separator.length;cut=before>=0?text.lastIndexOf(separator,before):-1}return-1}function streamChunk(state,chunk,role="assistant",messageId=null){let current=state.pending,messageChanged=messageId!=null&&current?.messageId!=null&&messageId!==current.messageId,base=current&&(current.role!==role||messageChanged)?commitPending(state):flushToolGroup(state),pending=base.pending?{...base.pending,messageId:base.pending.messageId??messageId}:{role,text:"",head:!0,messageId},text=pending.text+chunk,cut=safeCut(text,`
2193
-
2194
- `),separatorLength=2,nextGap=!0;if(cut<0&&text.length>STREAM_BLOCK_MAX_CHARS)cut=safeCut(text,`
2195
- `),separatorLength=1,nextGap=!1;if(cut<0)return{...base,pending:{...pending,text}};return{...appendBlock(flushToolGroup(base),{role:pending.role,head:pending.head,gap:pending.gap,text:text.slice(0,cut)}),pending:{role:pending.role,head:!1,gap:nextGap,text:text.slice(cut+separatorLength),messageId:pending.messageId}}}function hasPayloadDetail(value){if(value==null)return!1;if(Array.isArray(value))return value.length>0;if(typeof value==="object")return Object.keys(value).length>0;return!0}function isPlanningPlaceholder(payload){if(payload?.toolKind!=="other")return!1;if(payload?.name)return!1;if(hasPayloadDetail(payload?.rawInput)||hasPayloadDetail(payload?.locations))return!1;let title=typeof payload?.title==="string"?payload.title.trim():"";return HIDDEN_TOOL_TITLES.some((pattern)=>pattern.test(title))}function beginThought(state){if(state.thought)return state;return{...flushToolGroup(state),thought:{startedAt:Date.now(),activeAt:null,activeMs:0,pausedAt:null,pausedMs:0,text:"",title:null,expanded:state.thinkingDisplay==="full"}}}function isRedundantPreview(preview,label,title){if(!preview||preview.more>0)return!1;let text=preview.lines.join(`
2196
- `).trim();if(text.length===0)return!0;return[label.name,label.args,title].filter((value)=>typeof value==="string"&&value.trim().length>0).map((value)=>value.trim()).includes(text)}function flushThought(state){let thought=state.thought;if(!thought)return state;let elapsed=thinkingElapsed(thought),text=thought.text??"",displayMode=normalizeThinkingDisplayMode(state.thinkingDisplay);return appendBlock({...state,thought:null},{role:"thought",head:!0,text:thoughtSummaryText(thought,formatDuration(elapsed)),thought:{durationMs:elapsed,hasContent:text.trim().length>0,title:thought.title??splitThinkingText(text).title,displayMode,text}})}function toolFromGroup(group,{live=!1,now=Date.now()}={}){let failed=group.items.some((item)=>item.status==="failed"||item.status==="cancelled"),liveStatus=failed?"failed":"pending",liveElapsed=group.startedAt!=null?Math.max(0,now-group.startedAt):null;if(group.items.length===1){let{label,status,elapsed,preview,command,subagent,detail,diff,autoReview}=group.items[0];return{label,status:live?liveStatus:status,elapsed:live?liveElapsed:elapsed,hint:group.hint??null,preview:preview??null,command:command??null,subagent:subagent??null,detail:detail??null,diff:diff??null,autoReview:autoReview??null,...group.items[0].toolCallId?{toolCallId:group.items[0].toolCallId}:{},...group.items[0].parentToolCallId?{parentToolCallId:group.items[0].parentToolCallId}:{},reviewItems:group.items}}let status="pending";if(failed)status="failed";else if(!live&&group.items.every((item)=>item.status==="completed"))status="completed";return{group:{name:`${group.items.length} tool calls`,summary:summarizeToolCategories(group.items),count:group.items.length,items:group.items},status,hint:group.hint??null,elapsed:live?liveElapsed:group.startedAt!=null&&group.finishedAt!=null?group.finishedAt-group.startedAt:null,reviewItems:group.items}}function flushToolGroup(state){let group=state.pendingToolGroup;if(!group)return state;let tool=toolFromGroup(group),text=tool.group?`${tool.group.name}${tool.group.summary?` · ${tool.group.summary}`:""}`:tool.label.args?`${tool.label.name}(${tool.label.args})`:tool.label.name;return appendBlock({...state,pendingToolGroup:null},{role:"tool",head:!0,text,tool})}function isRichTool(kind,name){return kind==="execute"||kind==="edit"||name==="Bash"||name==="Edit"}function finalizeTool(state,tool){let now=Date.now(),startedAt=tool.startedAt??now,finalDiff=tool.diff?{...tool.diff,complete:!0}:null,item={label:tool.label,kind:tool.kind??tool.raw?.kind??null,status:tool.status,elapsed:tool.startedAt!=null?now-tool.startedAt:null,preview:tool.preview??null,command:tool.command??null,subagent:tool.subagent??null,detail:tool.detail??null,diff:finalDiff,autoReview:tool.autoReview??null,...tool.toolCallId?{toolCallId:tool.toolCallId}:{},...tool.raw?.parentToolCallId?{parentToolCallId:tool.raw.parentToolCallId}:{}},next=commitPending(state);if(isRichTool(item.kind,item.label?.name))return next=flushToolGroup(next),flushToolGroup({...next,pendingToolGroup:{name:item.label.name,items:[item],hint:tool.hint??null,startedAt,finishedAt:now}});let current=next.pendingToolGroup;if(current&&!item.subagent&&!current.items.some((entry)=>entry.subagent))return{...next,pendingToolGroup:{...current,items:[...current.items,item],finishedAt:now}};return next=flushToolGroup(next),{...next,pendingToolGroup:{name:tool.label.name,items:[item],hint:tool.hint??null,startedAt,finishedAt:now}}}function mergeDiff(candidate,previous){if(candidate?.complete)return candidate;if(previous?.complete)return previous;return candidate??previous??null}function bumpToolRound(state){if(state.activeTools.length>0)return state;return{...state,toolRound:state.toolRound+1}}function mergeTool(state,payload){let{toolCallId,status}=payload;if(toolCallId&&state.finalizedToolIds.has(toolCallId))return state;if(toolCallId!=null&&state.planningToolIds.has(toolCallId)||isPlanningPlaceholder(payload)){let planningToolIds=new Set(state.planningToolIds);if(toolCallId)planningToolIds.add(toolCallId);if(TERMINAL_STATUSES.has(status)){if(toolCallId)planningToolIds.delete(toolCallId);let next=flushThought(state);return{...next,planningToolIds,finalizedToolIds:toolCallId?new Set(next.finalizedToolIds).add(toolCallId):next.finalizedToolIds}}return{...beginThought(state),planningToolIds}}let raw={name:payload.name,kind:payload.toolKind,title:payload.title,rawInput:payload.rawInput,rawOutput:payload.rawOutput,locations:payload.locations,parentToolCallId:payload.parentToolCallId};if(!toolCallId){let next=bumpToolRound(commitPending(flushThought(state))),label=formatToolLabel(raw),preview=summarizeToolResult({...raw,name:label.name,content:payload.content,status});return finalizeTool(next,{label,kind:raw.kind,status,preview:isRedundantPreview(preview,label,payload.title)?null:preview,command:commandText(raw.rawInput),detail:buildToolDetail({...raw,content:payload.content}),diff:extractToolDiff({...raw,content:payload.content})})}let existing=state.activeTools.find((tool)=>tool.toolCallId===toolCallId),isSubagent=payload.isSubagent===!0||existing?.subagent!=null,next=state;if(!existing)next=commitPending(flushThought(next)),next=bumpToolRound(next);let subagent=isSubagent?updateSubagentState(existing?.subagent??createSubagentState(),payload.rawInput,extractRawText(payload.content)):null,mergedRaw=existing?{...existing.raw}:{};for(let[key,value]of Object.entries(raw))if(value!=null)mergedRaw[key]=value;let nextLabel=formatToolLabel(mergedRaw),nextStatus=status??existing?.status??"pending",previewCandidate=isSubagent?null:mergedRaw.kind==="execute"?extractToolOutputPreview(payload.rawOutput)??extractToolPreview(payload.content)??existing?.preview??null:summarizeToolResult({...mergedRaw,name:nextLabel.name,content:payload.content,status:nextStatus}),preview=isRedundantPreview(previewCandidate,nextLabel,payload.title??mergedRaw.title)?null:previewCandidate,merged={toolCallId,raw:mergedRaw,label:nextLabel,status:nextStatus,startedAt:existing?.startedAt??Date.now(),hint:existing?.hint??null,preview,command:commandText(mergedRaw.rawInput),subagent,content:payload.content??existing?.content,detail:buildToolDetail({...mergedRaw,content:payload.content??existing?.content}),diff:mergeDiff(extractToolDiff({...mergedRaw,content:payload.content??existing?.content}),existing?.diff??null),autoReview:payload.autoReview??existing?.autoReview??null};if(merged.subagent&&merged.status!=="failed"&&merged.status!=="cancelled")merged.status=merged.subagent.runFinished?"completed":"in_progress";if(TERMINAL_STATUSES.has(merged.status))return{...finalizeTool(next,merged),activeTools:next.activeTools.filter((tool)=>tool.toolCallId!==toolCallId),finalizedToolIds:new Set(next.finalizedToolIds).add(toolCallId)};if(!existing&&isRichTool(merged.raw?.kind,merged.label.name)&&next.pendingToolGroup)next=flushToolGroup(next);return{...next,activeTools:existing?next.activeTools.map((tool)=>tool.toolCallId===toolCallId?merged:tool):[...next.activeTools,merged]}}function flushActiveTools(state,cancelled=!1){let next=state,finalized=new Set(state.finalizedToolIds);for(let tool of state.activeTools){let finalTool=cancelled&&(tool.status==="pending"||tool.status==="in_progress")?{...tool,status:"cancelled"}:tool;next=finalizeTool(next,finalTool),finalized.add(tool.toolCallId)}return{...next,activeTools:[],finalizedToolIds:finalized}}function normalizePlanEntries(entries){if(!Array.isArray(entries))return[];return entries.map((entry)=>({status:entry?.status==="completed"||entry?.status==="in_progress"?entry.status:"pending",content:typeof entry?.content==="string"?entry.content:""})).filter((entry)=>entry.content.length>0)}function planSignatureOf(rows){return rows.map((row)=>`${row.status}\x00${row.content}`).join(`
2197
- `)}function planBlockText(rows){return["Update Todos",...rows.map((row)=>`${row.status==="completed"?"☒":"☐"} ${row.content}`)].join(`
2198
- `)}function flushBashCard(state){let card=state.bashCard;if(!card)return state;let{visible,hidden}=previewBashLines(card.lines,!1,BASH_PREVIEW_LINES),snapshot={...card,lines:visible,hidden},text=visible.map((line)=>line.text).join(`
2199
- `);return{...appendBlock(state,{role:"bashCard",head:!0,text,card:snapshot}),bashCard:null}}function flushBeforeStandaloneBlock(state){return flushBashCard(commitPending(flushThought(flushToolGroup(state))))}function reportedTokenCounts(usage){let pick=(keys)=>{for(let key of keys){let value=usage[key];if(typeof value==="number"&&Number.isFinite(value)&&value>=0)return value}return null},counts={};for(let field of TOKEN_FIELDS)counts[field]=pick(TOKEN_FIELD_SOURCES[field]);return counts}function sameTokenCounts(a,b){if(a===b)return!0;return TOKEN_FIELDS.every((field)=>(a?.[field]??null)===(b?.[field]??null))}function reportedCost(cost){let amount=cost?.amount;if(typeof amount!=="number"||!Number.isFinite(amount)||amount<=0)return null;let currency=typeof cost?.currency==="string"&&cost.currency?cost.currency:"USD";return{amount,currency}}var recorder=null,bannerBlock=()=>({id:nextId(),role:"banner",text:"",head:!0}),STREAM_BLOCK_MAX_CHARS=300,MAX_THOUGHT_TEXT=50000,TURN_STOP_NOTICES,FENCE_PATTERN,TABLE_ROW,TABLE_ROW_PARTIAL,LIST_ITEM,BLOCKQUOTE,HIDDEN_TOOL_TITLES,TOKEN_FIELDS,TOKEN_FIELD_SOURCES,useStore2;var init_store=__esm(()=>{init_esm2();init_subagent();init_tool_title();init_bash();init_config();init_thinking();init_tool_diff();TURN_STOP_NOTICES={max_turns:"Stopped after reaching the tool-call round limit — the task may be unfinished.",max_tokens:"The reply was cut off by the model's output token limit.",content_filter:"The provider stopped the reply with a content filter.",empty_response:"The model kept returning an empty reply — the turn ended without an answer."},FENCE_PATTERN=/(^|\n)( {0,3})(```|~~~)/g;TABLE_ROW=/^ {0,3}\|.*\|\s*$/,TABLE_ROW_PARTIAL=/^ {0,3}\|/,LIST_ITEM=/^ {0,3}(?:[-*+]|\d{1,9}[.)])\s/,BLOCKQUOTE=/^ {0,3}>/;HIDDEN_TOOL_TITLES=[/^(?:任务)?规划中$/,/^(?:planning|planning task)$/i];TOKEN_FIELDS=["total","input","output","cacheRead","cacheWrite","thought"],TOKEN_FIELD_SOURCES={total:["totalTokens"],input:["inputTokens"],output:["outputTokens"],cacheRead:["cachedReadTokens","cacheReadTokens"],cacheWrite:["cachedWriteTokens","cacheWriteTokens"],thought:["thoughtTokens"]};useStore2=create8((set,get)=>({blocks:[],pending:null,epoch:0,length:0,activeTools:[],finalizedToolIds:new Set,planningToolIds:new Set,toolRound:0,pendingToolGroup:null,thought:null,thinkingDisplay:DEFAULT_THINKING_DISPLAY_MODE,planSignature:null,queuedInputs:[],pendingInputs:[],queuePaused:!1,providerCommands:[],pendingBashContext:[],bashCard:null,status:"connecting",connectionStage:"Starting ACP…",providerName:null,providerId:null,sessionId:null,sessionMeta:null,sessionTitle:null,providerCapabilities:null,modelConfig:null,effortConfig:null,configOptions:[],modes:null,busy:!1,cancelling:!1,compacting:!1,switching:null,overlay:null,fatalError:null,usage:null,tokens:null,sessionTokens:null,sessionCost:null,planProgress:null,gitBranch:null,goal:null,turnStartedAt:null,turnKind:null,turnBlocksAt:0,animationTick:0,retryNotice:null,push:(role,text)=>set((state)=>appendBlock(flushBeforeStandaloneBlock(state),{role,text,head:!0})),pushProposedPlan:(text,planPath=null)=>set((state)=>appendBlock(flushBeforeStandaloneBlock(state),{role:"proposedPlan",text,planPath,head:!0})),appendChunk:(chunk,messageId)=>set((state)=>streamChunk(flushBashCard(flushThought(flushToolGroup(state))),chunk,"assistant",messageId)),appendUserChunk:(chunk,messageId)=>set((state)=>streamChunk(flushBashCard(flushToolGroup(state)),chunk,"user",messageId)),upsertTool:(payload)=>set((state)=>mergeTool(flushBashCard(state),payload)),startBashCard:(command)=>set((state)=>({...flushBashCard(state),bashCard:{command,lines:[],status:"running",outcome:null}})),finishBashCard:({stdout,stderr,outcome})=>set((state)=>state.bashCard?{bashCard:{...state.bashCard,lines:buildBashCardLines(stdout,stderr),status:"done",outcome}}:state),noteThought:(text="",now=Date.now())=>set((state)=>{let chunk=text??"";if(!state.thought)return{...flushToolGroup(state),thought:{startedAt:now,activeAt:chunk?now:null,activeMs:0,pausedAt:null,pausedMs:0,text:chunk,title:splitThinkingText(chunk).title,expanded:state.thinkingDisplay==="full"}};let combined=(state.thought.text??"")+chunk,truncated=combined.length>MAX_THOUGHT_TEXT?combined.slice(combined.length-MAX_THOUGHT_TEXT):combined,activity=chunk?advanceThinking(state.thought,now):null;return{thought:{...state.thought,...activity??{},text:truncated,title:state.thought.title??splitThinkingText(combined).title}}}),setThinkingDisplay:(value)=>set((state)=>{let thinkingDisplay=normalizeThinkingDisplayMode(value);if(thinkingDisplay===state.thinkingDisplay)return state;return{thinkingDisplay,thought:state.thought?{...state.thought,expanded:thinkingDisplay==="full"}:state.thought}}),setThoughtPaused:(paused,now=Date.now())=>set((state)=>{let thought=state.thought;if(!thought)return state;if(paused){if(thought.pausedAt!=null)return state;return{thought:{...thought,pausedAt:now}}}if(thought.pausedAt==null)return state;return{thought:{...thought,pausedAt:null,pausedMs:(thought.pausedMs??0)+Math.max(0,now-thought.pausedAt)}}}),setPlan:(entries)=>set((state)=>{let rows=normalizePlanEntries(entries);if(rows.length===0)return state.planSignature==null?state:{planSignature:null};let signature=planSignatureOf(rows),planProgress={total:rows.length,completed:rows.filter((row)=>row.status==="completed").length};if(signature===state.planSignature){let current=state.planProgress;return current!=null&&current.total===planProgress.total&&current.completed===planProgress.completed?state:{planProgress}}let next=flushBeforeStandaloneBlock(state);return{...appendBlock(next,{role:"plan",head:!0,text:planBlockText(rows),plan:{entries:rows}}),planSignature:signature,planProgress}}),setGoal:(snapshot)=>set((state)=>{if(snapshot==null)return state.goal==null?state:{goal:null};let current=state.goal;return current!=null&&current.goalId===snapshot.goalId&&current.status===snapshot.status&&current.objective===snapshot.objective&&current.turnsUsed===snapshot.turnsUsed&&current.wallClockMs===snapshot.wallClockMs&&current.terminalReason===snapshot.terminalReason&&current.budget?.turnBudget===snapshot.budget?.turnBudget?state:{goal:snapshot}}),queueInput:(text,display=null,id=null)=>set((state)=>({queuedInputs:[...state.queuedInputs,{text,display,...id?{id}:{}}]})),addPendingInput:(input)=>set((state)=>({pendingInputs:[...state.pendingInputs,normalizeInput(input)]})),applyInput:(input)=>set((state)=>{let next={...state,pendingInputs:state.pendingInputs.filter((item)=>item.id!==input.id)};if(state.blocks.some((block)=>block.inputId===input.id))return next;return appendBlock(flushBeforeStandaloneBlock(next),{role:"user",text:input.display??input.text,inputId:input.id,head:!0})}),returnInputs:(inputs,paused)=>set((state)=>{let ids=new Set(inputs.map((input)=>input.id)),queuedIds=new Set(state.queuedInputs.map((input)=>input.id).filter(Boolean));return{pendingInputs:state.pendingInputs.filter((input)=>!ids.has(input.id)),queuedInputs:[...inputs.filter((input)=>!queuedIds.has(input.id)).map(normalizeInput),...state.queuedInputs],queuePaused:state.queuePaused||paused}}),resumeInputQueue:()=>set({queuePaused:!1}),replaceQueuedInputs:(items)=>set({queuedInputs:Array.isArray(items)?items.map(normalizeInput):[]}),updateQueuedInput:(index,text)=>set((state)=>({queuedInputs:state.queuedInputs.map((item,itemIndex)=>itemIndex===index?{...item,text,display:null}:item)})),removeQueuedInput:(index)=>set((state)=>({queuedInputs:state.queuedInputs.filter((_,itemIndex)=>itemIndex!==index),...state.queuedInputs.length===1?{queuePaused:!1}:{}})),moveQueuedInput:(index,direction)=>set((state)=>{let target=index+direction;if(index<0||index>=state.queuedInputs.length||target<0||target>=state.queuedInputs.length)return state;let queuedInputs=[...state.queuedInputs];return[queuedInputs[index],queuedInputs[target]]=[queuedInputs[target],queuedInputs[index]],{queuedInputs}}),clearQueuedInputs:()=>set({queuedInputs:[],queuePaused:!1}),takeQueuedInput:()=>{if(get().queuePaused)return null;let queue=get().queuedInputs;if(queue.length===0)return null;return set({queuedInputs:queue.slice(1)}),queue[0]},setProviderCommands:(providerCommands)=>set({providerCommands:providerCommands??[]}),pushBashContext:(text)=>set((state)=>({pendingBashContext:[...state.pendingBashContext,text]})),takeBashContext:()=>{let items=get().pendingBashContext;if(items.length>0)set({pendingBashContext:[]});return items},restoreBashContext:(items)=>set((state)=>({pendingBashContext:[...items,...state.pendingBashContext]})),clearTranscript:()=>set((state)=>({blocks:state.status==="ready"?[bannerBlock()]:[],pending:null,activeTools:[],finalizedToolIds:new Set,planningToolIds:new Set,toolRound:0,pendingToolGroup:null,thought:null,planSignature:null,planProgress:null,goal:null,bashCard:null,epoch:state.epoch+1,length:0})),connected:({providerName,sessionId,providerCapabilities,modelConfig,effortConfig,configOptions,modes})=>set((state)=>{let hasBanner=state.blocks.some((block)=>block.role==="banner"),nextSessionId=sessionId??null,sessionChanged=state.sessionId!==nextSessionId;return{...hasBanner?state:appendBlock(state,bannerBlock(),!1),status:"ready",connectionStage:null,providerName,sessionId:nextSessionId,providerCapabilities:providerCapabilities??state.providerCapabilities,modelConfig,effortConfig,configOptions:Array.isArray(configOptions)?configOptions:state.configOptions,modes:modes??null,...sessionChanged?{usage:null,tokens:null,sessionTokens:null,sessionCost:null,sessionTitle:null,planProgress:null,goal:null}:{}}}),hydrate:(historyBlocks)=>set((state)=>{let next=state;for(let block of historyBlocks){if(!block||block.role==="banner")continue;let preview=block.role==="tool"?restoreQuestionPreview(block.tool):null,restored=preview?{...block,tool:{...block.tool,preview,reviewItems:block.tool.reviewItems?.map((item)=>item.label?.name==="Question"?{...item,preview}:item)}}:block;next=appendBlock(next,restored,!1)}return next}),setSessionMeta:(sessionMeta)=>set({sessionMeta}),setSessionTitle:(sessionTitle)=>set((state)=>state.sessionTitle===(sessionTitle??null)?state:{sessionTitle:sessionTitle??null}),setUsage:({used,size,cost,costCumulative}={})=>set((state)=>{let next={used:typeof used==="number"?used:state.usage?.used??null,size:typeof size==="number"?size:state.usage?.size??null,cost:cost??state.usage?.cost??null},reading=reportedCost(cost),sessionCost=state.sessionCost;if(reading)sessionCost=costCumulative===!0?reading:{amount:(sessionCost?.amount??0)+reading.amount,currency:reading.currency};let current=state.usage;if(current&&current.used===next.used&&current.size===next.size&&current.cost===next.cost&&sessionCost===state.sessionCost)return state;return{usage:next,sessionCost}}),setTokens:(usage)=>set((state)=>{if(!usage||typeof usage!=="object")return state;let reported=reportedTokenCounts(usage),previous=state.tokens,cumulative=usage.sessionCumulative===!0,reading={},totals={};for(let field of TOKEN_FIELDS){let value=reported[field],last=previous?.[field],lastValue=typeof last==="number"?last:null;reading[field]=value??lastValue;let step=cumulative?Math.max(0,value-(lastValue??0)):value,accumulated=state.sessionTokens?.[field],base=typeof accumulated==="number"?accumulated:null;totals[field]=value==null?base:(base??0)+step}if(sameTokenCounts(previous,reading)&&sameTokenCounts(state.sessionTokens,totals))return state;return{tokens:reading,sessionTokens:totals}}),setGitBranch:(gitBranch)=>set((state)=>state.gitBranch===(gitBranch??null)?state:{gitBranch:gitBranch??null}),setConfigs:({modelConfig,effortConfig,configOptions})=>set({modelConfig,effortConfig,...configOptions!==void 0?{configOptions:configOptions??[]}:{}}),setModes:(modes)=>set({modes}),setCompacting:(compacting)=>set({compacting}),recordContextState:(state)=>recorder?.recordContextState?.(state),setConnectionStage:(connectionStage)=>set({connectionStage}),setProviderId:(providerId)=>set({providerId}),reconnecting:()=>set({status:"connecting",connectionStage:"Starting ACP…",modes:null,providerCommands:[],planSignature:null,planningToolIds:new Set,planProgress:null,goal:null,usage:null,tokens:null,sessionTokens:null,sessionCost:null,sessionTitle:null,fatalError:null}),connectionFailed:()=>set({status:"failed",switching:null,busy:!1,cancelling:!1,compacting:!1,turnStartedAt:null,retryNotice:null}),setSwitching:(switching)=>set({switching}),bumpAnimationTick:()=>set((state)=>({animationTick:state.animationTick+1})),setOverlay:(overlay)=>set({overlay}),setCancelling:(cancelling)=>set({cancelling}),setFatalError:(fatalError)=>set({fatalError}),setRetryNotice:(retryNotice)=>set({retryNotice:retryNotice??null}),startTurn:(kind="prompt")=>set((state)=>({busy:!0,cancelling:!1,turnStartedAt:Date.now(),turnKind:kind,turnBlocksAt:state.blocks.length,toolRound:0,retryNotice:null})),endTurn:(result)=>set((state)=>{let wasCancelled=state.cancelling||result===!0||result==="cancelled"||result?.cancelled===!0||result?.stopReason==="cancelled",next=commitPending(flushToolGroup(flushActiveTools(flushThought(state),wasCancelled)));if(wasCancelled)next=appendBlock(next,{role:"error",head:!0,text:"Interrupted by user"});else{let notice=TURN_STOP_NOTICES[result?.stopReason];if(notice)next=appendBlock(next,{role:"error",head:!0,text:notice});if(state.turnKind==="prompt"&&state.turnStartedAt!=null&&next.blocks.length>state.turnBlocksAt){let elapsed=formatDuration(Date.now()-state.turnStartedAt);next=appendBlock(next,{role:"system",head:!0,text:elapsed?`Done in ${elapsed}`:"Done"})}}return{...next,finalizedToolIds:new Set,planningToolIds:new Set,planSignature:null,busy:!1,cancelling:!1,compacting:!1,turnStartedAt:null,turnKind:null,retryNotice:null}})}))});function toolEntries(tool,prefix){return((tool?.reviewItems?.length)?tool.reviewItems:[]).map((item,index)=>({id:`${prefix}:tool:${index}`,kind:item?.subagent?"subagent":"tool",item}))}function bashEntry(card,id){return{id:`${id}:bash`,kind:"bash",card}}function reviewEntries(state){let entries=[];for(let[index,block]of(state.blocks??[]).entries())if(block.role==="thought"&&block.thought?.text?.trim())entries.push({id:`${block.id??index}:thought`,kind:"thought",thought:block.thought});else if(block.role==="tool")entries.push(...toolEntries(block.tool,block.id??index));else if(block.role==="bashCard"&&block.card)entries.push(bashEntry(block.card,block.id??index));if(state.pendingToolGroup)entries.push(...toolEntries(toolFromGroup(state.pendingToolGroup),"pending"));if(state.thought&&state.thought.text&&state.thought.text.trim().length>0)entries.push({id:"live:thought",kind:"thought",thought:state.thought,live:!0});if(state.bashCard&&state.bashCard.status==="done")entries.push({...bashEntry(state.bashCard,"live"),live:!0});return entries}function findReviewTarget(state){let{overlay,pendingToolGroup,blocks=[]}=state;if(overlay?.kind==="review-browser")return{kind:"close"};if(overlay)return null;let entries=reviewEntries({...state,blocks,pendingToolGroup});if(entries.length===0)return null;return{kind:"review",entries,index:entries.length-1,live:Boolean(pendingToolGroup)||entries.some((entry)=>entry.live)}}var init_review_target=__esm(()=>{init_store()});import{execFile as execFile2}from"node:child_process";function git(args,cwd){return new Promise((resolve)=>{execFile2("git",args,{cwd,timeout:GIT_TIMEOUT_MS,maxBuffer:8388608},(error,stdout)=>{resolve(error?null:String(stdout))})})}async function isGitRepo(cwd){return(await git(["rev-parse","--is-inside-work-tree"],cwd))?.trim()==="true"}async function currentBranch(cwd){let branch=(await git(["rev-parse","--abbrev-ref","HEAD"],cwd))?.trim();return branch&&branch!=="HEAD"?branch:null}async function localBranches(cwd){let out=await git(["for-each-ref","--sort=-committerdate","--format=%(refname:short)","refs/heads"],cwd);if(out==null)return[];let current=await currentBranch(cwd);return out.split(`
2142
+ ${extra}`}var INIT_PROMPT4;var init_init=__esm(()=>{init_prompts();init_language();init_settings_file();INIT_PROMPT4=initPrompts(DEFAULT_LANGUAGE).INIT_PROMPT});function languageConfigOption(language){return{id:LANGUAGE_OPTION_ID,name:"Language",type:"select",category:"miro",description:"Language of miro's built-in workflow prompts",currentValue:normalizeLanguage(language),options:LANGUAGES.map((item)=>({value:item.value,name:item.name})),local:!0}}function isLanguageOption(option){return option?.id===LANGUAGE_OPTION_ID}function withLanguageOption(options,language){let listed=Array.isArray(options)?options:[];if(listed.some((option)=>option?.id===LANGUAGE_OPTION_ID))return listed;return[...listed,languageConfigOption(language)]}var LANGUAGE_OPTION_ID="language";var init_language_config=__esm(()=>{init_language()});function composerHasDraft(snapshot){return Boolean(snapshot?.value)||(snapshot?.pastes?.size??0)>0}function inputHint({busy,hasDraft,canSteer,queuedCount=0,queuePaused=!1}){if(!busy||!hasDraft)return null;let action=canSteer?"Enter to steer · Tab to queue":"Enter/Tab to queue · steering unavailable",queue=queuedCount>0?` · ${queuedCount} message${queuedCount>1?"s":""} queued${queuePaused?" · paused":""}`:"";return`${action} · Ctrl+Q to review queue${queue}`}import{execFile}from"node:child_process";import{existsSync as existsSync10}from"node:fs";import path28 from"node:path";function projectNameFor(cwd){if(typeof cwd!=="string"||cwd.length===0)return null;if(projectNameCache.has(cwd))return projectNameCache.get(cwd);let dir=cwd,found=null;while(!0){if(PROJECT_MARKERS.some((marker)=>existsSync10(path28.join(dir,marker)))){found=path28.basename(dir);break}let parent=path28.dirname(dir);if(parent===dir)break;dir=parent}let name=found??(path28.basename(cwd)||null);return projectNameCache.set(cwd,name),name}function loadGitBranch(cwd){if(typeof cwd!=="string"||cwd.length===0)return Promise.resolve(null);if(branchCache.has(cwd))return Promise.resolve(branchCache.get(cwd));let pending=inFlight.get(cwd);if(pending)return pending;let task=new Promise((resolve)=>{execFile("git",["rev-parse","--abbrev-ref","HEAD"],{cwd,timeout:2000},(error,stdout)=>{let branch=error?null:String(stdout).trim();resolve(branch&&branch!=="HEAD"?branch:null)})}).then((branch)=>(branchCache.set(cwd,branch),inFlight.delete(cwd),branch));return inFlight.set(cwd,task),task}var projectNameCache,branchCache,inFlight,PROJECT_MARKERS;var init_workspace_info=__esm(()=>{projectNameCache=new Map,branchCache=new Map,inFlight=new Map,PROJECT_MARKERS=[".git","package.json","Cargo.toml","go.mod","pyproject.toml"]});function getNextModeId(modes){if(!modes||!Array.isArray(modes.availableModes))return null;let list=modes.availableModes;if(list.length<=1)return null;let current=modes.currentModeId,nextIndex=(list.findIndex((mode)=>mode.id===current)+1)%list.length;return list[nextIndex]?.id??null}function toolEntries(tool,prefix){return((tool?.reviewItems?.length)?tool.reviewItems:[]).map((item,index)=>({id:`${prefix}:tool:${index}`,kind:item?.subagent?"subagent":"tool",item}))}function bashEntry(card,id){return{id:`${id}:bash`,kind:"bash",card}}function reviewEntries(state){let entries=[];for(let[index,block]of(state.blocks??[]).entries())if(block.role==="thought"&&block.thought?.text?.trim())entries.push({id:`${block.id??index}:thought`,kind:"thought",thought:block.thought});else if(block.role==="tool")entries.push(...toolEntries(block.tool,block.id??index));else if(block.role==="bashCard"&&block.card)entries.push(bashEntry(block.card,block.id??index));if(state.pendingToolGroup)entries.push(...toolEntries(toolFromGroup(state.pendingToolGroup),"pending"));if(state.thought&&state.thought.text&&state.thought.text.trim().length>0)entries.push({id:"live:thought",kind:"thought",thought:state.thought,live:!0});if(state.bashCard&&state.bashCard.status==="done")entries.push({...bashEntry(state.bashCard,"live"),live:!0});return entries}function findReviewTarget(state){let{overlay,pendingToolGroup,blocks=[]}=state;if(overlay?.kind==="review-browser")return{kind:"close"};if(overlay)return null;let entries=reviewEntries({...state,blocks,pendingToolGroup});if(entries.length===0)return null;return{kind:"review",entries,index:entries.length-1,live:Boolean(pendingToolGroup)||entries.some((entry)=>entry.live)}}var init_review_target=__esm(()=>{init_store()});import{execFile as execFile2}from"node:child_process";function git(args,cwd){return new Promise((resolve)=>{execFile2("git",args,{cwd,timeout:GIT_TIMEOUT_MS,maxBuffer:8388608},(error,stdout)=>{resolve(error?null:String(stdout))})})}async function isGitRepo(cwd){return(await git(["rev-parse","--is-inside-work-tree"],cwd))?.trim()==="true"}async function currentBranch(cwd){let branch=(await git(["rev-parse","--abbrev-ref","HEAD"],cwd))?.trim();return branch&&branch!=="HEAD"?branch:null}async function localBranches(cwd){let out=await git(["for-each-ref","--sort=-committerdate","--format=%(refname:short)","refs/heads"],cwd);if(out==null)return[];let current=await currentBranch(cwd);return out.split(`
2200
2143
  `).map((line)=>line.trim()).filter((line)=>line.length>0&&line!==current)}async function recentCommits(cwd,limit=COMMIT_LIMIT){let out=await git(["log",`-n${limit}`,"--format=%H%x00%s"],cwd);if(out==null)return[];let commits=[];for(let line of out.split(`
2201
2144
  `)){if(line.trim().length===0)continue;let[sha,subject]=line.split("\x00");if(!sha)continue;commits.push({sha:sha.trim(),subject:(subject??"").trim()||sha.slice(0,7)})}return commits}async function mergeBaseWithHead(cwd,branch){let candidates=[(await git(["rev-parse","--abbrev-ref",`${branch}@{upstream}`],cwd))?.trim(),branch].filter((value)=>typeof value==="string"&&value.length>0);for(let candidate of candidates){let sha=(await git(["merge-base","HEAD",candidate],cwd))?.trim();if(sha)return sha}return null}async function hasUncommittedChanges(cwd){let out=await git(["status","--porcelain"],cwd);return out!=null&&out.trim().length>0}async function reviewPrompt(target,cwd,language=readLanguageSetting()){let prompts=reviewPrompts(language);switch(target?.kind){case"uncommitted":return prompts.UNCOMMITTED_PROMPT;case"base-branch":{let sha=await mergeBaseWithHead(cwd,target.branch);return prompts.baseBranchPrompt(target.branch,sha)}case"commit":return prompts.commitPrompt(target.sha,target.title);case"custom":{let instructions=(target.instructions??"").trim();if(instructions.length===0)throw Error("Review instructions cannot be empty.");return instructions}default:throw Error(`Unknown review target: ${target?.kind}`)}}function userFacingHint(target){switch(target?.kind){case"uncommitted":return"current changes";case"base-branch":return`changes against '${target.branch}'`;case"commit":{let shortSha=String(target.sha??"").slice(0,7);return target.title?`commit ${shortSha}: ${target.title}`:`commit ${shortSha}`}case"custom":return(target.instructions??"").trim();default:return"changes"}}function reviewRubricFor(language){return reviewPrompts(language).REVIEW_RUBRIC}function buildReviewRequest(prompt,language=readLanguageSetting()){return`${reviewRubricFor(language)}
2202
2145
 
@@ -2206,8 +2149,8 @@ ${prompt}`}var GIT_TIMEOUT_MS=3000,COMMIT_LIMIT=100,REVIEW_RUBRIC4;var init_revi
2206
2149
 
2207
2150
  ---
2208
2151
 
2209
- ${prompt}`}function looksLikePaths(args){let text=String(args??"").trim();if(text.length===0)return!1;return text.split(/\s+/).every((token)=>/^[\w./@~-]+$/.test(token)&&/[./]/.test(token))}var SIMPLIFY_RUBRIC4;var init_simplify=__esm(()=>{init_prompts();init_language();init_review();init_settings_file();SIMPLIFY_RUBRIC4=simplifyPrompts(DEFAULT_LANGUAGE).SIMPLIFY_RUBRIC});import{execFile as execFile3}from"node:child_process";import{accessSync as accessSync3,constants as constants4,statSync as statSync10}from"node:fs";import path29 from"node:path";function git2(args,cwd){return new Promise((resolve)=>{execFile3("git",args,{cwd,timeout:GIT_TIMEOUT_MS2,maxBuffer:8388608},(error,stdout)=>{resolve(error?null:String(stdout))})})}function trimmedOrNull(text){let value=text?.trim();return value&&value.length>0?value:null}function truncateDiff(diff,limit=DIFF_LIMIT){let text=diff??"";if(text.length<=limit)return{text,truncated:!1};let cut=text.slice(0,limit),lastNewline=cut.lastIndexOf(`
2210
- `);return{text:lastNewline>0?cut.slice(0,lastNewline):cut,truncated:!0}}async function readCommitContext(cwd,{staged=!1}={}){let diffArgs=staged?["diff","--cached"]:["diff","HEAD"],[status,diff,branch,log,remote]=await Promise.all([git2(["status","--porcelain=v1"],cwd),git2(diffArgs,cwd),git2(["rev-parse","--abbrev-ref","HEAD"],cwd),git2(["log","--oneline",`-${LOG_LIMIT}`],cwd),git2(["remote","get-url","origin"],cwd)]);return{status:trimmedOrNull(status),diff:trimmedOrNull(diff),branch:trimmedOrNull(branch),log:trimmedOrNull(log),remote:trimmedOrNull(remote)}}async function hasStagedChanges(cwd){let out=await git2(["diff","--cached","--name-only"],cwd);return out!=null&&out.trim().length>0}async function hasCommits(cwd){let out=await git2(["rev-parse","--verify","HEAD"],cwd);return out!=null&&out.trim().length>0}function parseRemoteHost(url){let text=typeof url==="string"?url.trim():"";if(text.length===0)return null;if(/^[a-z][a-z0-9+.-]*:\/\//i.test(text))try{let host=new URL(text).hostname;return host?host.toLowerCase():null}catch{return null}let scp=/^(?:[^@/]+@)?([^:/]+):(.+)$/.exec(text);return scp?scp[1].toLowerCase():null}function detectForge(remoteUrl){let host=parseRemoteHost(remoteUrl);if(!host)return null;return FORGE_RULES.find((rule)=>rule.pattern.test(host))?.id??"unknown"}function isExecutableFile2(candidate){try{return accessSync3(candidate,constants4.X_OK),statSync10(candidate).isFile()}catch{return!1}}function availableForgeClis({pathEnv=process.env.PATH}={}){let dirs=String(pathEnv??"").split(path29.delimiter).filter((dir)=>dir.length>0);return FORGE_CLI_CANDIDATES.filter((name)=>dirs.some((dir)=>CLI_SUFFIXES.some((suffix)=>isExecutableFile2(path29.join(dir,`${name}${suffix}`)))))}function publishTarget(context,clis=availableForgeClis()){let remote=context?.remote??null,host=parseRemoteHost(remote),forge=host?detectForge(remote):null;return{remote,host,forge,cli:forge&&FORGE_CLIS[forge]||null,clis}}function commitTaskPrompt(target,language=readLanguageSetting()){let prompts=commitPrompts(language);switch(target?.kind){case"default":return prompts.DEFAULT_PROMPT;case"message":{let message=(target.message??"").trim();if(message.length===0)throw Error("Commit message cannot be empty.");return prompts.messagePrompt(message)}case"paths":{let paths=(target.paths??"").trim();if(paths.length===0)throw Error("Commit paths cannot be empty.");return prompts.pathsPrompt(paths)}case"staged":return prompts.STAGED_ONLY_PROMPT;case"amend":return prompts.AMEND_PROMPT;default:throw Error(`Unknown commit target: ${target?.kind}`)}}async function commitPrompt7(target,cwd,language=readLanguageSetting()){let prompts=commitPrompts(language),task=commitTaskPrompt(target,language),context=await readCommitContext(cwd,{staged:target?.kind==="staged"}),{text,truncated}=truncateDiff(context.diff);return[prompts.contextSection({...context,diff:text}),truncated?prompts.DIFF_TRUNCATED_NOTE:null,task].filter((block)=>typeof block==="string"&&block.length>0).join(`
2152
+ ${prompt}`}function looksLikePaths(args){let text=String(args??"").trim();if(text.length===0)return!1;return text.split(/\s+/).every((token)=>/^[\w./@~-]+$/.test(token)&&/[./]/.test(token))}var SIMPLIFY_RUBRIC4;var init_simplify=__esm(()=>{init_prompts();init_language();init_review();init_settings_file();SIMPLIFY_RUBRIC4=simplifyPrompts(DEFAULT_LANGUAGE).SIMPLIFY_RUBRIC});import{execFile as execFile3}from"node:child_process";import{accessSync as accessSync3,constants as constants3,statSync as statSync10}from"node:fs";import path29 from"node:path";function git2(args,cwd){return new Promise((resolve)=>{execFile3("git",args,{cwd,timeout:GIT_TIMEOUT_MS2,maxBuffer:8388608},(error,stdout)=>{resolve(error?null:String(stdout))})})}function trimmedOrNull(text){let value=text?.trim();return value&&value.length>0?value:null}function truncateDiff(diff,limit=DIFF_LIMIT){let text=diff??"";if(text.length<=limit)return{text,truncated:!1};let cut=text.slice(0,limit),lastNewline=cut.lastIndexOf(`
2153
+ `);return{text:lastNewline>0?cut.slice(0,lastNewline):cut,truncated:!0}}async function readCommitContext(cwd,{staged=!1}={}){let diffArgs=staged?["diff","--cached"]:["diff","HEAD"],[status,diff,branch,log,remote]=await Promise.all([git2(["status","--porcelain=v1"],cwd),git2(diffArgs,cwd),git2(["rev-parse","--abbrev-ref","HEAD"],cwd),git2(["log","--oneline",`-${LOG_LIMIT}`],cwd),git2(["remote","get-url","origin"],cwd)]);return{status:trimmedOrNull(status),diff:trimmedOrNull(diff),branch:trimmedOrNull(branch),log:trimmedOrNull(log),remote:trimmedOrNull(remote)}}async function hasStagedChanges(cwd){let out=await git2(["diff","--cached","--name-only"],cwd);return out!=null&&out.trim().length>0}async function hasCommits(cwd){let out=await git2(["rev-parse","--verify","HEAD"],cwd);return out!=null&&out.trim().length>0}function parseRemoteHost(url){let text=typeof url==="string"?url.trim():"";if(text.length===0)return null;if(/^[a-z][a-z0-9+.-]*:\/\//i.test(text))try{let host=new URL(text).hostname;return host?host.toLowerCase():null}catch{return null}let scp=/^(?:[^@/]+@)?([^:/]+):(.+)$/.exec(text);return scp?scp[1].toLowerCase():null}function detectForge(remoteUrl){let host=parseRemoteHost(remoteUrl);if(!host)return null;return FORGE_RULES.find((rule)=>rule.pattern.test(host))?.id??"unknown"}function isExecutableFile2(candidate){try{return accessSync3(candidate,constants3.X_OK),statSync10(candidate).isFile()}catch{return!1}}function availableForgeClis({pathEnv=process.env.PATH}={}){let dirs=String(pathEnv??"").split(path29.delimiter).filter((dir)=>dir.length>0);return FORGE_CLI_CANDIDATES.filter((name)=>dirs.some((dir)=>CLI_SUFFIXES.some((suffix)=>isExecutableFile2(path29.join(dir,`${name}${suffix}`)))))}function publishTarget(context,clis=availableForgeClis()){let remote=context?.remote??null,host=parseRemoteHost(remote),forge=host?detectForge(remote):null;return{remote,host,forge,cli:forge&&FORGE_CLIS[forge]||null,clis}}function commitTaskPrompt(target,language=readLanguageSetting()){let prompts=commitPrompts(language);switch(target?.kind){case"default":return prompts.DEFAULT_PROMPT;case"message":{let message=(target.message??"").trim();if(message.length===0)throw Error("Commit message cannot be empty.");return prompts.messagePrompt(message)}case"paths":{let paths=(target.paths??"").trim();if(paths.length===0)throw Error("Commit paths cannot be empty.");return prompts.pathsPrompt(paths)}case"staged":return prompts.STAGED_ONLY_PROMPT;case"amend":return prompts.AMEND_PROMPT;default:throw Error(`Unknown commit target: ${target?.kind}`)}}async function commitPrompt7(target,cwd,language=readLanguageSetting()){let prompts=commitPrompts(language),task=commitTaskPrompt(target,language),context=await readCommitContext(cwd,{staged:target?.kind==="staged"}),{text,truncated}=truncateDiff(context.diff);return[prompts.contextSection({...context,diff:text}),truncated?prompts.DIFF_TRUNCATED_NOTE:null,task].filter((block)=>typeof block==="string"&&block.length>0).join(`
2211
2154
 
2212
2155
  `)}async function commitPushPrPrompt(cwd,language=readLanguageSetting()){let prompts=commitPrompts(language),context=await readCommitContext(cwd),{text,truncated}=truncateDiff(context.diff),section=prompts.contextSection({...context,diff:text}),target=prompts.publishTargetSection(publishTarget(context));return[section,truncated?prompts.DIFF_TRUNCATED_NOTE:null,target,prompts.COMMIT_PUSH_PR_PROMPT].filter((block)=>typeof block==="string"&&block.length>0).join(`
2213
2156
 
@@ -2219,11 +2162,14 @@ ${prompt}`}function buildCommitPushPrRequest(prompt,language=readLanguageSetting
2219
2162
 
2220
2163
  ---
2221
2164
 
2222
- ${prompt}`}function parseCommitArgs(args){let text=String(args??"").trim();if(text.length===0)return{kind:"default"};let lower=text.toLowerCase();if(lower==="staged"||lower==="--staged")return{kind:"staged"};if(lower==="amend"||lower==="--amend")return{kind:"amend"};if(looksLikePaths(text))return{kind:"paths",paths:text};return{kind:"message",message:text}}var GIT_TIMEOUT_MS2=3000,LOG_LIMIT=10,DIFF_LIMIT=24000,FORGE_RULES,FORGE_CLIS,FORGE_CLI_CANDIDATES,CLI_SUFFIXES,COMMIT_RUBRIC4,COMMIT_PUSH_PR_RUBRIC4;var init_commit4=__esm(()=>{init_prompts();init_language();init_simplify();init_settings_file();FORGE_RULES=[{id:"github",pattern:/github/i},{id:"gitlab",pattern:/gitlab/i},{id:"gitea",pattern:/(gitea|forgejo|codeberg)/i},{id:"bitbucket",pattern:/bitbucket/i}],FORGE_CLIS={github:"gh",gitlab:"glab",gitea:"tea"},FORGE_CLI_CANDIDATES=["gh","glab","tea"],CLI_SUFFIXES=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];COMMIT_RUBRIC4=commitPrompts(DEFAULT_LANGUAGE).COMMIT_RUBRIC;COMMIT_PUSH_PR_RUBRIC4=commitPrompts(DEFAULT_LANGUAGE).COMMIT_PUSH_PR_RUBRIC});function jsxProd(type,config,maybeKey){var key=null;if(maybeKey!==void 0&&(key=""+maybeKey),config.key!==void 0&&(key=""+config.key),"key"in config){maybeKey={};for(var propName in config)propName!=="key"&&(maybeKey[propName]=config[propName])}else maybeKey=config;return config=maybeKey.ref,{$$typeof:REACT_ELEMENT_TYPE2,type,key,ref:config!==void 0?config:null,props:maybeKey}}var REACT_ELEMENT_TYPE2,REACT_FRAGMENT_TYPE,$Fragment,$jsx,$jsxs;var init_react_jsx_runtime_production=__esm(()=>{REACT_ELEMENT_TYPE2=Symbol.for("react.transitional.element"),REACT_FRAGMENT_TYPE=Symbol.for("react.fragment");$Fragment=REACT_FRAGMENT_TYPE,$jsx=jsxProd,$jsxs=jsxProd});function BashCard({card}){let{command,lines,status}=card,outcome=card.outcome??(card.timedOut?{type:"timed_out"}:card.interrupted?{type:"cancelled"}:card.exitCode!=null?{type:"exited",code:card.exitCode}:Object.hasOwn(card,"exitCode")?{type:"spawn_failed"}:null),running=status==="running",finalized=card.hidden!=null,{visible,hidden}=finalized?{visible:lines,hidden:card.hidden}:previewBashLines(lines,!1,DYNAMIC_BASH_PREVIEW_LINES),statusParts=[];if(!running){if(hidden>0)statusParts.push({text:finalized?`... ${hidden} more lines`:`... ${hidden} more lines (ctrl+o to review)`});if(outcome?.type==="timed_out")statusParts.push({color:"red",text:"(timed out)"});else if(outcome?.type==="cancelled")statusParts.push({color:"yellow",text:"(cancelled)"});else if(outcome?.type==="signaled")statusParts.push({color:"red",text:`(signal ${outcome.signal})`});else if(outcome?.type==="exited"&&outcome.code!==0)statusParts.push({color:"red",text:`(exit ${outcome.code})`});else if(outcome?.type==="spawn_failed")statusParts.push({color:"red",text:"(failed to start)"})}return $jsxs(Box_default,{flexDirection:"column",marginTop:1,paddingX:1,borderStyle:"single",borderColor:"magenta",borderLeft:!1,borderRight:!1,children:[$jsxs(Text,{bold:!0,color:"magenta",children:["$ ",command]}),running?$jsx(Text,{dimColor:!0,children:"Running… (esc to cancel)"}):visible.map((line,index)=>$jsx(Text,{dimColor:!0,color:line.err?"yellow":void 0,children:line.text.length>0?line.text:" "},index)),statusParts.length>0?$jsx(Box_default,{marginTop:1,children:$jsx(Text,{dimColor:!0,children:statusParts.map((part,index)=>$jsxs(Text,{color:part.color,children:[index>0?" ":"",part.text]},index))})}):null]})}var init_BashCard=__esm(async()=>{init_bash();init_config();init_react_jsx_runtime_production();await init_build4()});function autoReviewNote(payload){if(!payload||typeof payload!=="object")return null;if(payload.status==="checking")return"Auto safety review: checking…";if(payload.status==="allowed")return"Auto safety review: approved";if(payload.status==="blocked")return`Auto safety review: blocked · ${(typeof payload.reason==="string"?payload.reason.trim():"")||"no reason given"}`;return"Auto safety review: no decision"}function B(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function V(a){y=a}function D(a){let e=[];return(t)=>{let n=Math.max(0,Math.min(3,t-1)),i=e[n];return i||(i=a(n),e[n]=i),i}}function h(a,e=""){let t=typeof a=="string"?a:a.source,n={replace:(i,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(x.caret,"$1"),t=t.replace(i,o),n},getRegex:()=>new RegExp(t,e)};return n}function w(a,e){if(e){if(x.escapeTest.test(a))return a.replace(x.escapeReplace,Pe)}else if(x.escapeTestNoEncode.test(a))return a.replace(x.escapeReplaceNoEncode,Pe);return a}function ye(a){return x.numericCharacterReference.test(a)?a.replace(x.numericCharacterReferenceOrAmpersand,(e,t,n)=>{if(t===void 0&&n===void 0)return"&amp;";let i=t===void 0?Number.parseInt(n,16):Number.parseInt(t,10);return i===0||i>1114111||i>=55296&&i<=57343?"�":i===38?"&amp;":String.fromCodePoint(i)}):a}function ie(a){try{a=encodeURI(a).replace(x.percentDecode,"%")}catch{return null}return a}function oe(a,e){let t=a.replace(x.findPipe,(r,o,s)=>{let l=!1,u=o;for(;--u>=0&&s[u]==="\\";)l=!l;return l?"|":" |"}),n=t.split(x.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(x.slashPipe,"|");return n}function A(a,e,t){let n=a.length;if(n===0)return"";let i=0;for(;i<n;){let r=a.charAt(n-i-1);if(r===e&&!t)i++;else if(r!==e&&t)i++;else break}return a.slice(0,n-i)}function ae(a){let e=a.split(`
2165
+ ${prompt}`}function parseCommitArgs(args){let text=String(args??"").trim();if(text.length===0)return{kind:"default"};let lower=text.toLowerCase();if(lower==="staged"||lower==="--staged")return{kind:"staged"};if(lower==="amend"||lower==="--amend")return{kind:"amend"};if(looksLikePaths(text))return{kind:"paths",paths:text};return{kind:"message",message:text}}var GIT_TIMEOUT_MS2=3000,LOG_LIMIT=10,DIFF_LIMIT=24000,FORGE_RULES,FORGE_CLIS,FORGE_CLI_CANDIDATES,CLI_SUFFIXES,COMMIT_RUBRIC4,COMMIT_PUSH_PR_RUBRIC4;var init_commit4=__esm(()=>{init_prompts();init_language();init_simplify();init_settings_file();FORGE_RULES=[{id:"github",pattern:/github/i},{id:"gitlab",pattern:/gitlab/i},{id:"gitea",pattern:/(gitea|forgejo|codeberg)/i},{id:"bitbucket",pattern:/bitbucket/i}],FORGE_CLIS={github:"gh",gitlab:"glab",gitea:"tea"},FORGE_CLI_CANDIDATES=["gh","glab","tea"],CLI_SUFFIXES=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];COMMIT_RUBRIC4=commitPrompts(DEFAULT_LANGUAGE).COMMIT_RUBRIC;COMMIT_PUSH_PR_RUBRIC4=commitPrompts(DEFAULT_LANGUAGE).COMMIT_PUSH_PR_RUBRIC});function acquireAnimationClock(){if(subscribers+=1,timer==null){if(timer=setInterval(()=>useStore.getState().bumpAnimationTick(),ANIMATION_FRAME_MS),typeof timer.unref==="function")timer.unref()}let released=!1;return()=>{if(released)return;if(released=!0,subscribers-=1,subscribers>0||timer==null)return;clearInterval(timer),timer=null,subscribers=0}}var ANIMATION_FRAME_MS=100,subscribers=0,timer=null;var init_animation_clock=__esm(()=>{init_store()});function charWidth(ch){return stringWidth2(ch)}function tokens(text){let out=[],i=0;while(i<text.length){if(text.charCodeAt(i)===27){ANSI_TOKEN.lastIndex=i;let match=ANSI_TOKEN.exec(text);if(match){out.push({ansi:!0,value:match[0],width:0}),i+=match[0].length;continue}}let cp=text.codePointAt(i)??0,ch=String.fromCodePoint(cp),w=charWidth(ch),last=out.at(-1);if(w===0&&last&&!last.ansi)last.value+=ch;else out.push({ansi:!1,value:ch,width:w});i+=ch.length}return out}function truncate4(text,maxWidth,ellipsis="…"){if(maxWidth<=0)return"";if(stringWidth2(text)<=maxWidth)return text;let room=maxWidth-stringWidth2(ellipsis),used=0,out="",hasAnsi=!1;for(let token of tokens(text)){if(token.ansi){out+=token.value,hasAnsi=!0;continue}if(used+token.width>room)break;out+=token.value,used+=token.width}return`${out}${ellipsis}${hasAnsi?RESET:""}`}function truncateStart(text,maxWidth,ellipsis="…"){if(maxWidth<=0)return"";if(stringWidth2(text)<=maxWidth)return text;let room=maxWidth-stringWidth2(ellipsis),parts=tokens(text).filter((token)=>!token.ansi),used=0,out="";for(let index=parts.length-1;index>=0;index-=1){if(used+parts[index].width>room)break;out=parts[index].value+out,used+=parts[index].width}return`${ellipsis}${out}`}function padEnd(text,targetWidth){let gap=targetWidth-stringWidth2(text);return gap>0?text+" ".repeat(gap):text}function wrap(text,maxWidth){let w=Math.max(1,maxWidth),out=[];for(let logical of String(text).split(`
2166
+ `)){if(stringWidth2(logical)<=w){out.push(logical);continue}let wrapped=typeof Bun<"u"&&typeof Bun.wrapAnsi==="function"?Bun.wrapAnsi(logical,w,{hard:!0,trim:!1,wordWrap:!0}):hardWrap(logical,w);out.push(...wrapped.split(`
2167
+ `))}return out}function hardWrap(text,w){let rows=[],row="",used=0;for(let token of tokens(text)){if(!token.ansi&&used+token.width>w)rows.push(row),row="",used=0;row+=token.value,used+=token.width}return rows.push(row),rows.join(`
2168
+ `)}function hang(marker,markerWidth,body,rest=null){let blank=rest??" ".repeat(markerWidth);return body.map((line,index)=>(index===0?padEnd(marker,markerWidth):padEnd(blank,markerWidth))+line)}function indent(lines,n){let pad=" ".repeat(n);return lines.map((line)=>pad+line)}function spread2(left,right,totalWidth,gap=2){if(!right)return truncate4(left,totalWidth);let rightWidth=stringWidth2(right);if(rightWidth+gap>=totalWidth)return truncate4(right,totalWidth);let leftText=truncate4(left,totalWidth-rightWidth-gap),fill=totalWidth-stringWidth2(leftText)-rightWidth;return leftText+" ".repeat(Math.max(gap,fill))+right}function columns(cols,gap=2){let height=Math.max(0,...cols.map((col)=>col.lines.length)),out=[];for(let row=0;row<height;row+=1){let line="";cols.forEach((col,index)=>{let cell=col.lines[row]??"",isLast=index===cols.length-1;line+=isLast||col.width==null?cell:padEnd(cell,col.width)+" ".repeat(gap)}),out.push(line.replace(/\s+$/,""))}return out}function paint(text,color){if(!color||!text)return text;if(color.startsWith("#"))return source_default.hex(color)(text);let fn=source_default[color];return typeof fn==="function"?fn(text):text}function style(text,s={}){if(!text)return text;let out=paint(text,s.color);if(s.bold)out=source_default.bold(out);if(s.dim)out=source_default.dim(out);if(s.italic)out=source_default.italic(out);if(s.underline)out=source_default.underline(out);if(s.strikethrough)out=source_default.strikethrough(out);if(s.inverse)out=source_default.inverse(out);return out}function border(content,totalWidth,{style="round",color=null,sides={},paddingX=0}={}){let glyphs=style==="single"?SINGLE:ROUND,{top=!0,bottom=!0,left=!0,right=!0}=sides,innerWidth=Math.max(0,totalWidth-(left?1:0)-(right?1:0)),pad=" ".repeat(paddingX),bodyWidth=Math.max(0,innerWidth-paddingX*2),edge=(l,r)=>paint((left?l:"")+glyphs.h.repeat(innerWidth)+(right?r:""),color),out=[];if(top)out.push(edge(glyphs.tl,glyphs.tr));for(let line of content){let body=padEnd(truncate4(line,bodyWidth),bodyWidth);out.push((left?paint(glyphs.v,color):"")+pad+body+pad+(right?paint(glyphs.v,color):""))}if(bottom)out.push(edge(glyphs.bl,glyphs.br));return out}var ANSI_TOKEN,RESET="\x1B[0m",dim=(text)=>style(text,{dim:!0}),ROUND,SINGLE;var init_layout=__esm(()=>{init_source2();init_markdown_width();ANSI_TOKEN=/\u001B\[[0-9;:?]*[ -/]*[@-~]|\u001B\]8;;[^\u0007\u001B]*(?:\u0007|\u001B\\)/y;ROUND={tl:"╭",tr:"╮",bl:"╰",br:"╯",h:"─",v:"│"},SINGLE={tl:"┌",tr:"┐",bl:"└",br:"┘",h:"─",v:"│"}});function goalIndicator(snapshot,{useColors=!0}={}){if(snapshot==null||typeof snapshot.status!=="string")return null;let status=snapshot.status.trim();if(status.length===0)return null;let elapsed=Number.isFinite(snapshot.wallClockMs)?Math.max(0,snapshot.wallClockMs):0,color=GOAL_STATUS_COLORS[status]??null;return{mark:GOAL_INDICATOR_MARK,text:`${GOAL_INDICATOR_MARK} /goal ${status} (${formatElapsed(elapsed)})`,color:useColors?color:null,dim:!useColors}}var GOAL_INDICATOR_MARK="◎",GOAL_STATUS_COLORS;var init_goal_indicator=__esm(()=>{init_goal();GOAL_STATUS_COLORS={pending:"yellow",active:"cyan",pausing:"yellow",paused:"yellow",blocked:"red",complete:"green"}});function buildStatusLineSegments(ids,snapshot={},{useColors=!0}={}){let{items,invalid}=parseStatusLineItems(ids),segments=[];for(let id of items){let item=STATUS_LINE_ITEMS.get(id);if(!item)continue;let text=null;try{text=item.value(snapshot)}catch{text=null}if(text==null)continue;let value=String(text).trim();if(value.length===0)continue;segments.push({id,text:value,color:useColors?TONE_COLORS[item.tone]??null:null,dim:!useColors||TONE_COLORS[item.tone]==null})}return{segments,invalid}}var STATUS_LINE_SEPARATOR=" · ",TONE_COLORS;var init_render=__esm(()=>{init_items7();TONE_COLORS={model:"yellow",dir:"cyan",state:"green",accent:"blue",dim:null}});function normalizeSpinnerVerbsConfig(value){if(!value||typeof value!=="object"||Array.isArray(value))return null;if(!Array.isArray(value.verbs))return null;let verbs=value.verbs.filter((verb)=>typeof verb==="string").map((verb)=>verb.trim()).filter((verb)=>verb.length>0);if(verbs.length===0)return null;return{mode:value.mode==="replace"?"replace":"append",verbs}}function getSpinnerVerbs(settings=readSystemSettings()){let config=normalizeSpinnerVerbsConfig(settings.spinnerVerbs);if(!config)return SPINNER_VERBS;if(config.mode==="replace")return config.verbs;return[...SPINNER_VERBS,...config.verbs]}function sampleSpinnerVerb(verbs=getSpinnerVerbs()){if(!Array.isArray(verbs)||verbs.length===0)return"Working";return verbs[Math.floor(Math.random()*verbs.length)]??"Working"}var SPINNER_VERBS;var init_spinner_verbs=__esm(()=>{init_settings_file();SPINNER_VERBS=["Accomplishing","Actioning","Actualizing","Architecting","Baking","Beaming","Befuddling","Billowing","Blanching","Bloviating","Boogieing","Boondoggling","Booping","Bootstrapping","Brewing","Burrowing","Calculating","Canoodling","Caramelizing","Cascading","Catapulting","Cerebrating","Channeling","Choreographing","Churning","Coalescing","Cogitating","Combobulating","Composing","Computing","Concocting","Considering","Contemplating","Cooking","Crafting","Creating","Crunching","Crystallizing","Cultivating","Deciphering","Deliberating","Determining","Dilly-dallying","Discombobulating","Doing","Doodling","Drizzling","Ebbing","Effecting","Elucidating","Embellishing","Enchanting","Envisioning","Evaporating","Fermenting","Fiddle-faddling","Finagling","Flambéing","Flibbertigibbeting","Flowing","Flummoxing","Fluttering","Forging","Forming","Frolicking","Frosting","Gallivanting","Galloping","Garnishing","Generating","Germinating","Gesticulating","Grooving","Gusting","Harmonizing","Hashing","Hatching","Herding","Honking","Hullaballooing","Hyperspacing","Ideating","Imagining","Improvising","Incubating","Inferring","Infusing","Ionizing","Jitterbugging","Julienning","Kneading","Leavening","Levitating","Lollygagging","Manifesting","Marinating","Meandering","Metamorphosing","Misting","Mooning","Moonwalking","Moseying","Mulling","Musing","Mustering","Nebulizing","Nesting","Noodling","Nucleating","Orbiting","Orchestrating","Osmosing","Perambulating","Percolating","Perusing","Philosophising","Photosynthesizing","Pollinating","Pondering","Pontificating","Pouncing","Precipitating","Prestidigitating","Processing","Proofing","Propagating","Puttering","Puzzling","Quantumizing","Razzle-dazzling","Razzmatazzing","Recombobulating","Reticulating","Roosting","Ruminating","Sautéing","Scampering","Schlepping","Scurrying","Seasoning","Shenaniganing","Shimmying","Simmering","Skedaddling","Sketching","Slithering","Smooshing","Spelunking","Spinning","Sprouting","Stewing","Sublimating","Swirling","Swooping","Symbioting","Synthesizing","Tempering","Thinking","Thundering","Tinkering","Tomfoolering","Topsy-turvying","Transfiguring","Transmuting","Twisting","Undulating","Unfurling","Unravelling","Vibing","Waddling","Wandering","Warping","Whatchamacalliting","Whirlpooling","Whirring","Whisking","Wibbling","Working","Wrangling","Zesting","Zigzagging"]});function B(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function V(a){y=a}function D(a){let e=[];return(t)=>{let n=Math.max(0,Math.min(3,t-1)),i=e[n];return i||(i=a(n),e[n]=i),i}}function h(a,e=""){let t=typeof a=="string"?a:a.source,n={replace:(i,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(x.caret,"$1"),t=t.replace(i,o),n},getRegex:()=>new RegExp(t,e)};return n}function w(a,e){if(e){if(x.escapeTest.test(a))return a.replace(x.escapeReplace,Pe)}else if(x.escapeTestNoEncode.test(a))return a.replace(x.escapeReplaceNoEncode,Pe);return a}function ye(a){return x.numericCharacterReference.test(a)?a.replace(x.numericCharacterReferenceOrAmpersand,(e,t,n)=>{if(t===void 0&&n===void 0)return"&amp;";let i=t===void 0?Number.parseInt(n,16):Number.parseInt(t,10);return i===0||i>1114111||i>=55296&&i<=57343?"�":i===38?"&amp;":String.fromCodePoint(i)}):a}function ie(a){try{a=encodeURI(a).replace(x.percentDecode,"%")}catch{return null}return a}function oe(a,e){let t=a.replace(x.findPipe,(r,o,s)=>{let l=!1,u=o;for(;--u>=0&&s[u]==="\\";)l=!l;return l?"|":" |"}),n=t.split(x.splitPipe),i=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;i<n.length;i++)n[i]=n[i].trim().replace(x.slashPipe,"|");return n}function A(a,e,t){let n=a.length;if(n===0)return"";let i=0;for(;i<n;){let r=a.charAt(n-i-1);if(r===e&&!t)i++;else if(r!==e&&t)i++;else break}return a.slice(0,n-i)}function ae(a){let e=a.split(`
2223
2169
  `),t=e.length-1;for(;t>=0&&x.blankLine.test(e[t]);)t--;return e.length-t<=2?a:e.slice(0,t+1).join(`
2224
2170
  `)}function v(a){return a.trim().toLowerCase().toUpperCase().toLowerCase()}function le(a,e){if(a.indexOf(e[0])===-1&&a.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<a.length;n++)if(a[n]==="\\")n++;else if(a[n]===e[0])t++;else if(a[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}function X(a,e=0){let t=e,n="";for(let i of a)if(i==="\t"){let r=4-t%4;n+=" ".repeat(r),t+=r}else n+=i,t++;return n}function Se(a,e,t,n,i){let r=e.href,o=e.title||null,s=a[1].replace(i.other.outputLinkReplace,"$1"),l=a[0].charAt(0)==="!",u=n.state.inLink,c=n.state.linkEmitted,p=n.state.inRawBlock;n.state.inLink=!0,n.state.linkEmitted=!1;let d=n.inlineTokens(s),g=n.state.linkEmitted;if(n.state.linkEmitted=c,n.state.inLink=u,!l){if(g){n.state.inRawBlock=p;return}n.state.linkEmitted=!0}return{type:l?"image":"link",raw:t,href:r,title:o,text:s,tokens:d}}function Lt(a,e,t){let n=a.match(t.other.indentCodeCompensation);if(n===null)return e;let i=n[1];return e.split(`
2225
2171
  `).map((r)=>{let o=r.match(t.other.beginningSpace);if(o===null)return r;let[s]=o;return r.slice(Math.min(s.length,i.length))}).join(`
2226
- `)}function _e(a,e,t,n){if(!e.includes("<"))return!1;for(let i=0;i<e.length;i++){if(e[i]==="\\"){i++;continue}if(e[i]==="`"){let s=n.inline.code.exec(e.slice(i));if(s){i+=s[0].length-1;continue}}if(e[i]!=="<")continue;let r=a.slice(t+i),o=n.inline.tag.exec(r)||n.inline.autolink.exec(r);if(o){if(o[0].length>e.length-i)return!0;i+=o[0].length-1}}return!1}function C3(a,e){if(Array.isArray(e))for(let t=0;t<e.length;t++)a.push(e[t]);else a.push(e)}function f(a,e){return I.parse(a,e)}function At(...a){return I.use(...a),f.defaults=I.defaults,V(f.defaults),f}var y,M,ze,x,Ee,Me,Ce,N,Ie,Y,fe,me,Be,ee,De,te,qe,Ze,Q="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",ne,ve,xe=(a)=>h(ee).replace("hr",N).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",a).replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",Q).getRegex(),He,Ge,Ne,re,de,Qe,je,Fe,Ue,be,Ke,S,q,j,Xe,We,Re,Ve,Je,Ye,Te,et,tt,nt,rt,Oe="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",st,it,ot="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",at2,lt2,ut="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",pt,ct,ht="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",dt,kt,gt2,ft,mt,xt,we,K,bt,Rt,Tt,ke,Ot,wt,ge,Pt,yt,se,St,J,_t,F,Z,$t,Pe=(a)=>$t[a],_=class{options;rules;lexer;constructor(e){this.options=e||y}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:ae(t[0]),i=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:i}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],i=Lt(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:i}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let i=A(n,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceTabChar.test(i))&&(n=i.trim())}return{type:"heading",raw:A(t[0],`
2172
+ `)}function _e(a,e,t,n){if(!e.includes("<"))return!1;for(let i=0;i<e.length;i++){if(e[i]==="\\"){i++;continue}if(e[i]==="`"){let s=n.inline.code.exec(e.slice(i));if(s){i+=s[0].length-1;continue}}if(e[i]!=="<")continue;let r=a.slice(t+i),o=n.inline.tag.exec(r)||n.inline.autolink.exec(r);if(o){if(o[0].length>e.length-i)return!0;i+=o[0].length-1}}return!1}function C3(a,e){if(Array.isArray(e))for(let t=0;t<e.length;t++)a.push(e[t]);else a.push(e)}function f(a,e){return I.parse(a,e)}function At(...a){return I.use(...a),f.defaults=I.defaults,V(f.defaults),f}var y,M,ze,x,Ee,Me,Ce,N,Ie,Y,fe,me,Be,ee,De,te,qe,Ze,Q="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",ne,ve,xe=(a)=>h(ee).replace("hr",N).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",a).replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",Q).getRegex(),He,Ge,Ne,re,de,Qe,je,Fe,Ue,be,Ke,S,q,j,Xe,We,Re,Ve,Je,Ye,Te,et,tt,nt,rt,Oe="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",st,it,ot="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",at,lt,ut="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",pt,ct,ht="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",dt,kt,gt,ft,mt,xt,we,K,bt,Rt,Tt,ke,Ot,wt,ge,Pt,yt,se,St,J,_t,F,Z,$t,Pe=(a)=>$t[a],_=class{options;rules;lexer;constructor(e){this.options=e||y}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:ae(t[0]),i=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:i}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],i=Lt(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:i}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let i=A(n,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceTabChar.test(i))&&(n=i.trim())}return{type:"heading",raw:A(t[0],`
2227
2173
  `),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:A(t[0],`
2228
2174
  `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=A(t[0],`
2229
2175
  `).split(`
@@ -2283,7 +2229,7 @@ ${e}</tr>
2283
2229
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
2284
2230
  `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${w(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,text:n,tokens:i,autolink:r}){let o=r?w(n,!0):this.parser.parseInline(i),s=ie(e);if(s===null)return o;e=w(s,r);let l='<a href="'+e+'"';return t&&(l+=' title="'+w(t)+'"'),l+=">"+o+"</a>",l}image({href:e,title:t,text:n,tokens:i}){i&&(n=this.parser.parseInline(i,this.parser.textRenderer));let r=ie(e);if(r===null)return w(n);e=r;let o=`<img src="${w(e)}" alt="${w(n)}"`;return t&&(o+=` title="${w(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):("escaped"in e)&&e.escaped?e.text:w(e.text)}},z=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},O=class a{options;renderer;textRenderer;constructor(e){this.options=e||y,this.options.renderer=this.options.renderer||new $,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new z}static parse(e,t){return new a(t).parse(e)}static parseInline(e,t){return new a(t).parseInline(e)}parse(e){this.renderer.parser=this;let t="";for(let n=0;n<e.length;n++){let i=e[n];if(this.options.extensions?.renderers?.[i.type]){let o=i,s=this.options.extensions.renderers[o.type].call({parser:this},o);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){t+=s||"";continue}}let r=i;switch(r.type){case"space":{t+=this.renderer.space(r);break}case"hr":{t+=this.renderer.hr(r);break}case"heading":{t+=this.renderer.heading(r);break}case"code":{t+=this.renderer.code(r);break}case"table":{t+=this.renderer.table(r);break}case"blockquote":{t+=this.renderer.blockquote(r);break}case"list":{t+=this.renderer.list(r);break}case"checkbox":{t+=this.renderer.checkbox(r);break}case"html":{t+=this.renderer.html(r);break}case"def":{t+=this.renderer.def(r);break}case"paragraph":{t+=this.renderer.paragraph(r);break}case"text":{t+=this.renderer.text(r);break}default:{let o='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw Error(o)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n="";for(let i=0;i<e.length;i++){let r=e[i];if(this.options.extensions?.renderers?.[r.type]){let s=this.options.extensions.renderers[r.type].call({parser:this},r);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(r.type)){n+=s||"";continue}}let o=r;switch(o.type){case"escape":{n+=t.text(o);break}case"html":{n+=t.html(o);break}case"link":{n+=t.link(o);break}case"image":{n+=t.image(o);break}case"checkbox":{n+=t.checkbox(o);break}case"strong":{n+=t.strong(o);break}case"em":{n+=t.em(o);break}case"codespan":{n+=t.codespan(o);break}case"br":{n+=t.br(o);break}case"del":{n+=t.del(o);break}case"text":{n+=t.text(o);break}default:{let s='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw Error(s)}}}return n}},L,U=class{defaults=B();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=O;Renderer=$;TextRenderer=z;Lexer=T2;Tokenizer=_;Hooks=L;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let i of e)switch(C3(n,t.call(this,i)),i.type){case"table":{let r=i;for(let o of r.header)C3(n,this.walkTokens(o.tokens,t));for(let o of r.rows)for(let s of o)C3(n,this.walkTokens(s.tokens,t));break}case"list":{let r=i;C3(n,this.walkTokens(r.items,t));break}default:{let r=i;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach((o)=>{let s=r[o].flat(1/0);C3(n,this.walkTokens(s,t))}):r.tokens&&C3(n,this.walkTokens(r.tokens,t))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((n)=>{let i={...n};if(i.async=this.defaults.async||i.async||!1,n.extensions&&(n.extensions.forEach((r)=>{if(!r.name)throw Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...s){let l=r.renderer.apply(this,s);return l===!1&&(l=o.apply(this,s)),l}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),i.extensions=t),n.renderer){let r=this.defaults.renderer||new $(this.defaults);for(let o in n.renderer){if(!(o in r))throw Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let s=o,l=n.renderer[s],u=r[s];r[s]=(...c)=>{let p=l.apply(r,c);return p===!1&&(p=u.apply(r,c)),p||""}}i.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new _(this.defaults);for(let o in n.tokenizer){if(!(o in r))throw Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let s=o,l=n.tokenizer[s],u=r[s];r[s]=(...c)=>{let p=l.apply(r,c);return p===!1&&(p=u.apply(r,c)),p}}i.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new L;for(let o in n.hooks){if(!(o in r))throw Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let s=o,l=n.hooks[s],u=r[s];L.passThroughHooks.has(o)?r[s]=(c)=>{if(this.defaults.async&&L.passThroughHooksRespectAsync.has(o))return(async()=>{let d=await l.call(r,c);return u.call(r,d)})();let p=l.call(r,c);return u.call(r,p)}:r[s]=(...c)=>{if(this.defaults.async)return(async()=>{let d=await l.apply(r,c);return d===!1&&(d=await u.apply(r,c)),d})();let p=l.apply(r,c);return p===!1&&(p=u.apply(r,c)),p}}i.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,o=n.walkTokens;i.walkTokens=function(s){let l=[];return l.push(o.call(this,s)),r&&C3(l,r.call(this,s)),l}}this.defaults={...this.defaults,...i}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return T2.lex(e,t??this.defaults)}parser(e,t){return O.parse(e,t??this.defaults)}parseMarkdown(e){return(n,i)=>{let r={...i},o={...this.defaults,...r},s=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return s(Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return s(Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return s(Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let l=o.hooks?await o.hooks.preprocess(n):n,c=await(o.hooks?await o.hooks.provideLexer(e):e?T2.lex:T2.lexInline)(l,o),p=o.hooks?await o.hooks.processAllTokens(c):c;o.walkTokens&&await Promise.all(this.walkTokens(p,o.walkTokens));let g=await(o.hooks?await o.hooks.provideParser(e):e?O.parse:O.parseInline)(p,o);return o.hooks?await o.hooks.postprocess(g):g})().catch(s);try{o.hooks&&(n=o.hooks.preprocess(n));let u=(o.hooks?o.hooks.provideLexer(e):e?T2.lex:T2.lexInline)(n,o);o.hooks&&(u=o.hooks.processAllTokens(u)),o.walkTokens&&this.walkTokens(u,o.walkTokens);let p=(o.hooks?o.hooks.provideParser(e):e?O.parse:O.parseInline)(u,o);return o.hooks&&(p=o.hooks.postprocess(p)),p}catch(l){return s(l)}}}onError(e,t){return(n)=>{if(n.message+=`
2285
2231
  Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error occurred:</p><pre>"+w(n.message+"",!0)+"</pre>";return t?Promise.resolve(i):i}if(t)return Promise.reject(n);throw n}}},I,Rn,Tn,On,wn,yn,Sn;var init_marked_esm=__esm(()=>{y=B();M={exec:()=>null};ze=((a="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+a)}catch{return!1}})(),x={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:(a)=>new RegExp(`^( {0,3}${a})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:D((a)=>new RegExp(`^ {0,${a}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:D((a)=>new RegExp(`^ {0,${a}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:D((a)=>new RegExp(`^ {0,${a}}(?:\`\`\`|~~~)`)),headingBeginRegex:D((a)=>new RegExp(`^ {0,${a}}#`)),htmlBeginRegex:D((a)=>new RegExp(`^ {0,${a}}(?:</?(?:${Q})(?: +|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`,"i")),blockquoteBeginRegex:D((a)=>new RegExp(`^ {0,${a}}>`))},Ee=/^(?:[ \t]*(?:\n|$))+/,Me=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ce=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,N=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ie=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Y=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,fe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,me=h(fe).replace(/bull/g,Y).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Be=h(fe).replace(/bull/g,Y).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),ee=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,De=/^[^\n]+/,te=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,qe=h(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",te).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ze=h(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Y).getRegex(),ne=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ve=h("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",ne).replace("tag",Q).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),He=xe(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Ge=xe(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ne=h(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ge).getRegex(),re={blockquote:Ne,code:Me,def:qe,fences:Ce,heading:Ie,hr:N,html:ve,lheading:me,list:Ze,newline:Ee,paragraph:He,table:M,text:De},de=h("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",N).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",Q).getRegex(),Qe={...re,lheading:Be,table:de,paragraph:h(ee).replace("hr",N).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",de).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",Q).getRegex()},je={...re,html:h(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ne).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:M,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:h(ee).replace("hr",N).replace("heading",` *#{1,6} *[^
2286
- ]`).replace("lheading",me).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Fe=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ue=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,be=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,Ke=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,S=/[\p{P}\p{S}]/u,q=/[\s\p{P}\p{S}]/u,j=/[^\s\p{P}\p{S}]/u,Xe=h(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,q).getRegex(),We=/[\p{Pi}\p{Ps}"']/u,Re=/(?!~)[\p{P}\p{S}]/u,Ve=/(?!~)[\s\p{P}\p{S}]/u,Je=/(?:[^\s\p{P}\p{S}]|~)/u,Ye=h(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",ze?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Te=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,et=h(Te,"u").replace(/punct/g,S).getRegex(),tt=h(Te,"u").replace(/punct/g,Re).getRegex(),nt=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,rt=h(nt,"u").replace(/openQuote/g,We).replace(/punct/g,S).getRegex(),st=h(Oe,"gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,q).replace(/punct/g,S).getRegex(),it=h(Oe,"gu").replace(/notPunctSpace/g,Je).replace(/punctSpace/g,Ve).replace(/punct/g,Re).getRegex(),at2=h(ot,"gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,q).replace(/punct/g,S).getRegex(),lt2=h("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,q).replace(/punct/g,S).getRegex(),pt=h(ut,"gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,q).replace(/punct/g,S).getRegex(),ct=h(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,S).getRegex(),dt=h(ht,"gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,q).replace(/punct/g,S).getRegex(),kt=h(/\\(punct)/,"gu").replace(/punct/g,S).getRegex(),gt2=h(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,"gu").replace(/punct/g,S).getRegex(),ft=h(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),mt=h(ne).replace("(?:-->|$)","-->").getRegex(),xt=h("^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",mt).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),we=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,K=h(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",we).getRegex(),bt=h(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace("label",K).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Rt=h(/^!?\[(label)\]\[(ref)\]/).replace("label",K).replace("ref",te).getRegex(),Tt=h(/^!?\[(ref)\](?:\[\])?/).replace("ref",te).getRegex(),ke=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,Ot=h(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",we).getRegex(),wt=h("reflink|nolink(?!\\()","g").replace("reflink",h(/^!?\[(label)\]\[(ref)\]/).replace("label",Ot).replace("ref",ke).getRegex()).replace("nolink",h(/^!?\[(ref)\](?:\[\])?/).replace("ref",ke).getRegex()).getRegex(),ge=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Pt=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,yt=h(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,Pt).getRegex(),se={_backpedal:M,anyPunctuation:kt,anyPunctuationOutsideCode:gt2,autolink:ft,blockSkip:Ye,br:be,code:Ue,del:M,delLDelim:M,delRDelim:M,emStrongLDelim:et,emStrongRDelimAst:st,emStrongRDelimUnd:lt2,escape:Fe,link:bt,nolink:Tt,punctuation:Xe,reflink:Rt,reflinkSearch:wt,tag:xt,text:Ke,url:M},St={...se,emStrongLDelim:rt,emStrongRDelimAst:at2,emStrongRDelimUnd:pt,link:h(/^!?\[(label)\]\((.*?)\)/).replace("label",K).getRegex(),reflink:h(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",K).getRegex()},J={...se,emStrongRDelimAst:it,emStrongLDelim:tt,delLDelim:ct,delRDelim:dt,url:h(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol",yt).replace("protocol",ge).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:h(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))))/).replace("protocol",ge).replace(/emailProtocol/g,/(?:mailto|xmpp):/).getRegex()},_t={...J,br:h(be).replace("{2,}","*").getRegex(),text:h(J.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},F={normal:re,gfm:Qe,pedantic:je},Z={normal:se,gfm:J,breaks:_t,pedantic:St},$t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};L=class{options;block;constructor(e){this.options=e||y}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?T2.lex:T2.lexInline}provideParser(e=this.block){return e?O.parse:O.parseInline}};I=new U;f.options=f.setOptions=function(a){return I.setOptions(a),f.defaults=I.defaults,V(f.defaults),f};f.getDefaults=B;f.defaults=y;f.use=At;f.walkTokens=function(a,e){return I.walkTokens(a,e)};f.parseInline=I.parseInline;f.Parser=O;f.parser=O.parse;f.Renderer=$;f.TextRenderer=z;f.Lexer=T2;f.lexer=T2.lex;f.Tokenizer=_;f.Hooks=L;f.parse=f;Rn=f.options,Tn=f.setOptions,On=f.walkTokens,wn=f.parseInline,yn=O.parse,Sn=T2.lex});function replaceCharacters(value,replacements){let result="";for(let character of value){let replacement=replacements[character];if(replacement===void 0)return;result+=replacement}return result}function formatScript(value,kind){value=value.trim();let replacements=kind==="sub"?SUBSCRIPTS:SUPERSCRIPTS,unicode=replaceCharacters(value.replace(/\s*([=+-])\s*/g,"$1"),replacements);if(unicode!==void 0)return unicode;let prefix=kind==="sub"?"_":"^";if(Array.from(value).length===1||kind==="sub"&&/^[A-Za-z]+$/.test(value))return`${prefix}${value}`;return`${prefix}(${value})`}function formatFraction(numerator,denominator){numerator=numerator.trim(),denominator=denominator.trim();let simpleNumerator=/^[\p{L}\p{N}.]+$/u.test(numerator),simpleDenominator=/^[\p{N}.]+$/u.test(denominator)||Array.from(denominator).length===1;return`${simpleNumerator?numerator:`(${numerator})`}/${simpleDenominator?denominator:`(${denominator})`}`}function formatRoot(value,symbol="√"){return value=value.trim(),/^[\p{L}\p{N}.]+$/u.test(value)?`${symbol}${value}`:`${symbol}(${value})`}function normalizeOutput(value){return value.replace(NAMED_OPERATOR_LEFT_SPACING_PATTERN," ").replaceAll(NAMED_OPERATOR_START,"").replace(NAMED_OPERATOR_RIGHT_SPACING_PATTERN," ").replaceAll(NAMED_OPERATOR_END,"").split(`
2232
+ ]`).replace("lheading",me).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Fe=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ue=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,be=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,Ke=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,S=/[\p{P}\p{S}]/u,q=/[\s\p{P}\p{S}]/u,j=/[^\s\p{P}\p{S}]/u,Xe=h(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,q).getRegex(),We=/[\p{Pi}\p{Ps}"']/u,Re=/(?!~)[\p{P}\p{S}]/u,Ve=/(?!~)[\s\p{P}\p{S}]/u,Je=/(?:[^\s\p{P}\p{S}]|~)/u,Ye=h(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",ze?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Te=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,et=h(Te,"u").replace(/punct/g,S).getRegex(),tt=h(Te,"u").replace(/punct/g,Re).getRegex(),nt=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,rt=h(nt,"u").replace(/openQuote/g,We).replace(/punct/g,S).getRegex(),st=h(Oe,"gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,q).replace(/punct/g,S).getRegex(),it=h(Oe,"gu").replace(/notPunctSpace/g,Je).replace(/punctSpace/g,Ve).replace(/punct/g,Re).getRegex(),at=h(ot,"gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,q).replace(/punct/g,S).getRegex(),lt=h("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,q).replace(/punct/g,S).getRegex(),pt=h(ut,"gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,q).replace(/punct/g,S).getRegex(),ct=h(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,S).getRegex(),dt=h(ht,"gu").replace(/notPunctSpace/g,j).replace(/punctSpace/g,q).replace(/punct/g,S).getRegex(),kt=h(/\\(punct)/,"gu").replace(/punct/g,S).getRegex(),gt=h(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,"gu").replace(/punct/g,S).getRegex(),ft=h(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),mt=h(ne).replace("(?:-->|$)","-->").getRegex(),xt=h("^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",mt).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),we=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,K=h(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",we).getRegex(),bt=h(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace("label",K).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Rt=h(/^!?\[(label)\]\[(ref)\]/).replace("label",K).replace("ref",te).getRegex(),Tt=h(/^!?\[(ref)\](?:\[\])?/).replace("ref",te).getRegex(),ke=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,Ot=h(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",we).getRegex(),wt=h("reflink|nolink(?!\\()","g").replace("reflink",h(/^!?\[(label)\]\[(ref)\]/).replace("label",Ot).replace("ref",ke).getRegex()).replace("nolink",h(/^!?\[(ref)\](?:\[\])?/).replace("ref",ke).getRegex()).getRegex(),ge=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Pt=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,yt=h(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,Pt).getRegex(),se={_backpedal:M,anyPunctuation:kt,anyPunctuationOutsideCode:gt,autolink:ft,blockSkip:Ye,br:be,code:Ue,del:M,delLDelim:M,delRDelim:M,emStrongLDelim:et,emStrongRDelimAst:st,emStrongRDelimUnd:lt,escape:Fe,link:bt,nolink:Tt,punctuation:Xe,reflink:Rt,reflinkSearch:wt,tag:xt,text:Ke,url:M},St={...se,emStrongLDelim:rt,emStrongRDelimAst:at,emStrongRDelimUnd:pt,link:h(/^!?\[(label)\]\((.*?)\)/).replace("label",K).getRegex(),reflink:h(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",K).getRegex()},J={...se,emStrongRDelimAst:it,emStrongLDelim:tt,delLDelim:ct,delRDelim:dt,url:h(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol",yt).replace("protocol",ge).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:h(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))))/).replace("protocol",ge).replace(/emailProtocol/g,/(?:mailto|xmpp):/).getRegex()},_t={...J,br:h(be).replace("{2,}","*").getRegex(),text:h(J.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},F={normal:re,gfm:Qe,pedantic:je},Z={normal:se,gfm:J,breaks:_t,pedantic:St},$t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};L=class{options;block;constructor(e){this.options=e||y}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?T2.lex:T2.lexInline}provideParser(e=this.block){return e?O.parse:O.parseInline}};I=new U;f.options=f.setOptions=function(a){return I.setOptions(a),f.defaults=I.defaults,V(f.defaults),f};f.getDefaults=B;f.defaults=y;f.use=At;f.walkTokens=function(a,e){return I.walkTokens(a,e)};f.parseInline=I.parseInline;f.Parser=O;f.parser=O.parse;f.Renderer=$;f.TextRenderer=z;f.Lexer=T2;f.lexer=T2.lex;f.Tokenizer=_;f.Hooks=L;f.parse=f;Rn=f.options,Tn=f.setOptions,On=f.walkTokens,wn=f.parseInline,yn=O.parse,Sn=T2.lex});function replaceCharacters(value,replacements){let result="";for(let character of value){let replacement=replacements[character];if(replacement===void 0)return;result+=replacement}return result}function formatScript(value,kind){value=value.trim();let replacements=kind==="sub"?SUBSCRIPTS:SUPERSCRIPTS,unicode=replaceCharacters(value.replace(/\s*([=+-])\s*/g,"$1"),replacements);if(unicode!==void 0)return unicode;let prefix=kind==="sub"?"_":"^";if(Array.from(value).length===1||kind==="sub"&&/^[A-Za-z]+$/.test(value))return`${prefix}${value}`;return`${prefix}(${value})`}function formatFraction(numerator,denominator){numerator=numerator.trim(),denominator=denominator.trim();let simpleNumerator=/^[\p{L}\p{N}.]+$/u.test(numerator),simpleDenominator=/^[\p{N}.]+$/u.test(denominator)||Array.from(denominator).length===1;return`${simpleNumerator?numerator:`(${numerator})`}/${simpleDenominator?denominator:`(${denominator})`}`}function formatRoot(value,symbol="√"){return value=value.trim(),/^[\p{L}\p{N}.]+$/u.test(value)?`${symbol}${value}`:`${symbol}(${value})`}function normalizeOutput(value){return value.replace(NAMED_OPERATOR_LEFT_SPACING_PATTERN," ").replaceAll(NAMED_OPERATOR_START,"").replace(NAMED_OPERATOR_RIGHT_SPACING_PATTERN," ").replaceAll(NAMED_OPERATOR_END,"").split(`
2287
2233
  `).map((line)=>line.replace(/[ \t]+/g," ").trim()).filter((line,index,lines)=>line.length>0||index>0&&index<lines.length-1).join(`
2288
2234
  `).trim()}function padLayoutLine(line,width,centered=!1){let padding=Math.max(0,width-stringWidth2(line)),left=centered?Math.floor(padding/2):0;return`${" ".repeat(left)}${line}${" ".repeat(padding-left)}`}function joinLayouts(layouts){if(layouts.length===0)return{lines:[""],width:0,baseline:0};let baseline=Math.max(...layouts.map((layout)=>layout.baseline)),below=Math.max(...layouts.map((layout)=>layout.lines.length-layout.baseline-1)),lines=[];for(let row=0;row<=baseline+below;row++){let line="";for(let layout of layouts){let sourceRow=row-baseline+layout.baseline;line+=sourceRow>=0&&sourceRow<layout.lines.length?padLayoutLine(layout.lines[sourceRow]??"",layout.width):" ".repeat(layout.width)}lines.push(line.trimEnd())}return{lines,width:layouts.reduce((width,layout)=>width+layout.width,0),baseline}}function renderLayout(source,nodes){let renderedLines=[],firstBaseline=0;for(let sourceLine of source.split(`
2289
2235
  `)){let layouts=[],position=0,previousNode;for(let match of sourceLine.matchAll(LAYOUT_MARKER_PATTERN)){let index=match.index,node=nodes[Number(match[1])];if(!node)continue;if(index>position){let sliced=sourceLine.slice(position,index),trimmed=(previousNode?sliced.trimStart():sliced).trimEnd(),preserveLeadingSpace=previousNode?.type==="matrix"&&/^\s/.test(sliced),preserveTrailingSpace=node.type==="matrix"&&/\s$/.test(sliced),text=trimmed?`${preserveLeadingSpace?" ":""}${trimmed}${preserveTrailingSpace?" ":""}`:preserveLeadingSpace||preserveTrailingSpace?" ":"";layouts.push({lines:[text],width:stringWidth2(text),baseline:0})}if(node.type==="fraction"){let numerator=renderLayout(node.numerator,nodes),denominator=renderLayout(node.denominator,nodes),contentWidth=Math.max(numerator.width,denominator.width,1),width=contentWidth+2;layouts.push({lines:[...numerator.lines.map((line)=>padLayoutLine(line,width,!0)),` ${"─".repeat(contentWidth)} `,...denominator.lines.map((line)=>padLayoutLine(line,width,!0))],width,baseline:numerator.lines.length})}else if(node.type==="operator"){let contentWidth=Math.max(stringWidth2(node.operator),node.lower===void 0?0:stringWidth2(node.lower),node.upper===void 0?0:stringWidth2(node.upper)),lines=[];if(node.upper!==void 0)lines.push(`${padLayoutLine(node.upper,contentWidth,!0)} `);if(lines.push(`${padLayoutLine(node.operator,contentWidth,!0)} `),node.lower!==void 0)lines.push(`${padLayoutLine(node.lower,contentWidth,!0)} `);layouts.push({lines,width:contentWidth+1,baseline:node.upper===void 0?0:1})}else{let width=Math.max(0,...node.lines.map((line)=>stringWidth2(line)));layouts.push({lines:node.lines.map((line)=>padLayoutLine(line,width)),width,baseline:node.baseline})}position=index+match[0].length,previousNode=node}if(position<sourceLine.length){let sliced=sourceLine.slice(position),trimmed=previousNode?sliced.trimStart():sliced,text=previousNode?.type==="matrix"&&/^\s/.test(sliced)?` ${trimmed}`:trimmed;layouts.push({lines:[text],width:stringWidth2(text),baseline:0})}let lineLayout=joinLayouts(layouts);if(renderedLines.length===0)firstBaseline=lineLayout.baseline;renderedLines.push(...lineLayout.lines)}return{lines:renderedLines,width:Math.max(0,...renderedLines.map((line)=>stringWidth2(line))),baseline:firstBaseline}}class LatexParser{constructor(source,layoutNodes,display){this.source=source,this.layoutNodes=layoutNodes,this.display=display,this.position=0,this.supported=!0,this.stackFractions=!0}render(){let rendered=this.parseSequence();if(!this.supported||this.position!==this.source.length)return;return normalizeOutput(rendered)}parseSequence(endCharacter){let result="";while(this.position<this.source.length){let character=this.source[this.position];if(endCharacter&&character===endCharacter)return this.position++,result;if(character==="}")return this.supported=!1,result;if(character==="{"){this.position++,result+=this.parseSequence("}");continue}if(character==="\\"){let command=this.parseCommand();if(command===NEGATIVE_SPACE){if(result=result.trimEnd(),result.endsWith(NAMED_OPERATOR_END))result=result.slice(0,-NAMED_OPERATOR_END.length)}else result+=command;continue}if(character==="^"||character==="_"){this.position++,result=result.trimEnd();let script=formatScript(this.parseRequiredArgument(!1),character==="_"?"sub":"sup");if(result.endsWith(NAMED_OPERATOR_END))result=`${result.slice(0,-NAMED_OPERATOR_END.length)}${script}${NAMED_OPERATOR_END}`;else result+=script;continue}if(/\s/.test(character)){result+=this.parseWhitespace();continue}if(character==="="||character==="<"||character===">"){result=`${result.trimEnd()} ${character} `,this.position++;continue}if(character==="&"){this.position++;continue}if(character==="~"){this.position++,result+=" ";continue}if(character==="."){let marker=TRAILING_LAYOUT_MARKER_PATTERN.exec(result),node=marker?this.layoutNodes[Number(marker[1])]:void 0;if(node?.type==="matrix"){let lastLine=node.lines.length-1;node.lines[lastLine]=`${node.lines[lastLine]??""}${character}`,this.position++;continue}}result+=character,this.position++}if(endCharacter)this.supported=!1;return result}parseWhitespace(){while(this.position<this.source.length&&/\s/.test(this.source[this.position]??""))this.position++;return" "}parseCommand(){if(this.position++,this.position>=this.source.length)return this.supported=!1,"";let command="",first=this.source[this.position]??"";if(first===`
@@ -2294,50 +2240,48 @@ Please report this to https://github.com/markedjs/marked.`,e){let i="<p>An error
2294
2240
  `)}if(["array","matrix","smallmatrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix"].includes(environment)){let matrixBody=environment==="array"?body.replace(/^\s*\{[^}]*\}/,""):body;return this.renderMatrix(environment,matrixBody)}return this.supported=!1,body}renderMatrix(environment,body){let matrix=this.splitEnvironmentRows(body).map((row)=>row.split("&").map((cell)=>this.renderNested(cell,!1).trim())).filter((row)=>row.some(Boolean)),columnCount=Math.max(0,...matrix.map((row)=>row.length)),columnWidths=Array.from({length:columnCount},(_,column)=>Math.max(0,...matrix.map((row)=>stringWidth2(row[column]??"")))),rows=matrix.map((row)=>Array.from({length:columnCount},(_,column)=>{let cell=row[column]??"";return`${cell}${PROTECTED_SPACE.repeat(Math.max(0,(columnWidths[column]??0)-stringWidth2(cell)))}`}).join(" │ ")),lines;if(environment==="array"||environment==="matrix"||environment==="smallmatrix")lines=rows;else{let delimiter={pmatrix:["⎛","⎞","⎜","⎟","⎝","⎠"],bmatrix:["⎡","⎤","⎢","⎥","⎣","⎦"],Bmatrix:["⎧","⎫","⎨","⎬","⎩","⎭"],vmatrix:["│","│","│","│","│","│"],Vmatrix:["║","║","║","║","║","║"]}[environment];if(!delimiter)return this.supported=!1,rows.join(`
2295
2241
  `);lines=rows.map((row,index)=>{let left=index===0?delimiter[0]:index===rows.length-1?delimiter[4]:delimiter[2],right=index===0?delimiter[1]:index===rows.length-1?delimiter[5]:delimiter[3];return`${left} ${row} ${right}`})}if(lines.length<=1)return lines[0]??"";let index=this.layoutNodes.push({type:"matrix",lines,baseline:0})-1;return`${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`}renderNested(source,stackFractions=!0){let rendered=new LatexParser(source,this.layoutNodes,this.display&&stackFractions).render();if(rendered===void 0)return this.supported=!1,source;return rendered}}function renderLatex(source,options={}){let layoutNodes=[],rendered=new LatexParser(source,layoutNodes,options.display===!0).render();if(rendered===void 0)return;if(layoutNodes.length===0)return rendered.replaceAll(PROTECTED_SPACE," ");let lines=renderLayout(rendered,layoutNodes).lines,indentation=Math.min(...lines.filter((line)=>line.trim()).map((line)=>line.length-line.trimStart().length));return lines.map((line)=>line.slice(indentation).trimEnd()).join(`
2296
2242
  `).trimEnd().replaceAll(PROTECTED_SPACE," ")}var SYMBOLS,NAMED_OPERATORS,LIMIT_OPERATORS,DISPLAY_LIMIT_SYMBOLS,RELATION_COMMANDS,NEGATED_SYMBOLS,BLACKBOARD,SUPERSCRIPTS,SUBSCRIPTS,SPACING_COMMANDS,NEGATIVE_SPACING_COMMANDS,NEGATIVE_SPACE="\x00",IGNORED_COMMANDS,SIZE_COMMANDS,PLAIN_WRAPPERS,ACCENTS,NAMED_OPERATOR_START="\uDB80\uDC04",NAMED_OPERATOR_END="\uDB80\uDC05",NAMED_OPERATOR_LEFT_SPACING_PATTERN,NAMED_OPERATOR_RIGHT_SPACING_PATTERN,LAYOUT_MARKER_START="\uDB80\uDC00",LAYOUT_MARKER_END="\uDB80\uDC01",LAYOUT_MARKER_PATTERN,TRAILING_LAYOUT_MARKER_PATTERN,PROTECTED_SPACE="\uDB80\uDC02";var init_latex=__esm(()=>{init_markdown_width();SYMBOLS={alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ϵ",varepsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",vartheta:"ϑ",iota:"ι",kappa:"κ",varkappa:"ϰ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",pi:"π",varpi:"ϖ",rho:"ρ",varrho:"ϱ",sigma:"σ",varsigma:"ς",tau:"τ",upsilon:"υ",phi:"ϕ",varphi:"φ",chi:"χ",psi:"ψ",omega:"ω",Gamma:"Γ",Delta:"Δ",Theta:"Θ",Lambda:"Λ",Xi:"Ξ",Pi:"Π",Sigma:"Σ",Upsilon:"Υ",Phi:"Φ",Psi:"Ψ",Omega:"Ω",pm:"±",mp:"∓",times:"×",div:"÷",cdot:"·",ast:"∗",star:"⋆",circ:"∘",bullet:"•",oplus:"⊕",ominus:"⊖",otimes:"⊗",oslash:"⊘",odot:"⊙",bigcirc:"○",dagger:"†",ddagger:"‡",amalg:"⨿",uplus:"⊎",sqcap:"⊓",sqcup:"⊔",bowtie:"⋈",Join:"⋈",ltimes:"⋉",rtimes:"⋊",leftouterjoin:"⟕",rightouterjoin:"⟖",fullouterjoin:"⟗",triangleleft:"◁",triangleright:"▷",wr:"≀",cap:"∩",cup:"∪",bigcap:"⋂",bigcup:"⋃",bigwedge:"⋀",bigvee:"⋁",bigsqcup:"⨆",biguplus:"⨄",bigoplus:"⨁",bigotimes:"⨂",bigodot:"⨀",setminus:"∖",in:"∈",notin:"∉",ni:"∋",subset:"⊂",supset:"⊃",subseteq:"⊆",supseteq:"⊇",sqsubset:"⊏",sqsupset:"⊐",sqsubseteq:"⊑",sqsupseteq:"⊒",prec:"≺",preceq:"≼",succ:"≻",succeq:"≽",ll:"≪",gg:"≫",le:"≤",leq:"≤",leqslant:"≤",ge:"≥",geq:"≥",geqslant:"≥",ne:"≠",neq:"≠",equiv:"≡",approx:"≈",sim:"∼",simeq:"≃",cong:"≅",asymp:"≍",doteq:"≐",propto:"∝",parallel:"∥",perp:"⊥",mid:"∣",vdash:"⊢",dashv:"⊣",models:"⊨",Vdash:"⊩",Vvdash:"⊪",nvdash:"⊬",nvDash:"⊭",forall:"∀",exists:"∃",nexists:"∄",neg:"¬",land:"∧",wedge:"∧",lor:"∨",vee:"∨",to:"→",rightarrow:"→",longrightarrow:"→",leftarrow:"←",longleftarrow:"←",gets:"←",leftrightarrow:"↔",longleftrightarrow:"↔",hookleftarrow:"↩",hookrightarrow:"↪",twoheadleftarrow:"↞",twoheadrightarrow:"↠",leftharpoonup:"↼",leftharpoondown:"↽",rightharpoonup:"⇀",rightharpoondown:"⇁",rightleftharpoons:"⇌",leftrightharpoons:"⇋",nearrow:"↗",searrow:"↘",swarrow:"↙",nwarrow:"↖",rightsquigarrow:"⇝",leadsto:"⇝",Rightarrow:"⇒",Longrightarrow:"⇒",Leftarrow:"⇐",Longleftarrow:"⇐",Leftrightarrow:"⇔",Longleftrightarrow:"⇔",implies:"⇒",iff:"⇔",mapsto:"↦",longmapsto:"↦",uparrow:"↑",downarrow:"↓",partial:"∂",nabla:"∇",int:"∫",iint:"∬",iiint:"∭",oint:"∮",sum:"∑",prod:"∏",coprod:"∐",infty:"∞",emptyset:"∅",varnothing:"∅",angle:"∠",therefore:"∴",because:"∵",aleph:"ℵ",beth:"ℶ",gimel:"ℷ",daleth:"ℸ",top:"⊤",bot:"⊥",triangle:"△",square:"□",lozenge:"◊",checkmark:"✓",complement:"∁",wp:"℘",prime:"′",ldots:"…",dots:"…",cdots:"⋯",vdots:"⋮",ddots:"⋱",ell:"ℓ",hbar:"ℏ",Im:"ℑ",Re:"ℜ",langle:"⟨",rangle:"⟩",vert:"|",lvert:"|",rvert:"|",Vert:"‖",lVert:"‖",rVert:"‖",lbrace:"{",rbrace:"}",backslash:"\\",lfloor:"⌊",rfloor:"⌋",lceil:"⌈",rceil:"⌉",colon:":"},NAMED_OPERATORS=new Set(["arccos","arcsin","arctan","arg","cos","cosh","cot","coth","csc","deg","det","dim","exp","gcd","hom","inf","ker","lg","lim","liminf","limsup","ln","log","max","min","Pr","sec","sin","sinh","sup","tan","tanh"]),LIMIT_OPERATORS=new Set(["argmax","argmin","inf","injlim","lim","liminf","limsup","max","min","projlim","sup"]),DISPLAY_LIMIT_SYMBOLS=new Set(["bigcap","bigcup","bigodot","bigoplus","bigotimes","bigsqcup","biguplus","bigvee","bigwedge","coprod","int","iint","iiint","oint","prod","sum"]),RELATION_COMMANDS=new Set(["Leftarrow","Leftrightarrow","Longleftarrow","Longleftrightarrow","Longrightarrow","Rightarrow","Join","Vdash","Vvdash","approx","asymp","bowtie","cong","dashv","fullouterjoin","doteq","downarrow","equiv","ge","geq","geqslant","gets","gg","hookleftarrow","hookrightarrow","iff","implies","in","leadsto","le","leftarrow","leftharpoondown","leftharpoonup","leftouterjoin","leftrightarrow","leftrightharpoons","leq","leqslant","ll","longleftarrow","longleftrightarrow","longmapsto","ltimes","longrightarrow","mapsto","mid","models","ne","nearrow","neq","ni","notin","nvdash","nvDash","nwarrow","parallel","perp","prec","preceq","propto","rightharpoondown","rightharpoonup","rightouterjoin","rightleftharpoons","rightarrow","rightsquigarrow","rtimes","searrow","sim","simeq","sqsubset","sqsubseteq","sqsupset","sqsupseteq","subset","subseteq","succ","succeq","supset","supseteq","swarrow","to","triangleleft","triangleright","twoheadleftarrow","twoheadrightarrow","uparrow","vdash"]),NEGATED_SYMBOLS={"<":"≮",">":"≯","=":"≠","∈":"∉","∋":"∌","∣":"∤","∥":"∦","∼":"≁","≃":"≄","≅":"≇","≈":"≉","≡":"≢","≤":"≰","≥":"≱","≺":"⊀","≻":"⊁","⊂":"⊄","⊃":"⊅","⊆":"⊈","⊇":"⊉","⊢":"⊬","⊨":"⊭","↔":"↮","←":"↚","→":"↛","⇒":"⇏","⇐":"⇍","⇔":"⇎","≼":"⋠","≽":"⋡"},BLACKBOARD={C:"ℂ",H:"ℍ",N:"ℕ",P:"ℙ",Q:"ℚ",R:"ℝ",Z:"ℤ"},SUPERSCRIPTS={"0":"⁰","1":"¹","2":"²","3":"³","4":"⁴","5":"⁵","6":"⁶","7":"⁷","8":"⁸","9":"⁹","+":"⁺","-":"⁻","=":"⁼","(":"⁽",")":"⁾",a:"ᵃ",b:"ᵇ",c:"ᶜ",d:"ᵈ",e:"ᵉ",f:"ᶠ",g:"ᵍ",h:"ʰ",i:"ⁱ",j:"ʲ",k:"ᵏ",l:"ˡ",m:"ᵐ",n:"ⁿ",o:"ᵒ",p:"ᵖ",r:"ʳ",s:"ˢ",t:"ᵗ",u:"ᵘ",v:"ᵛ",w:"ʷ",x:"ˣ",y:"ʸ",z:"ᶻ"},SUBSCRIPTS={"0":"₀","1":"₁","2":"₂","3":"₃","4":"₄","5":"₅","6":"₆","7":"₇","8":"₈","9":"₉","+":"₊","-":"₋","=":"₌","(":"₍",")":"₎",a:"ₐ",e:"ₑ",h:"ₕ",i:"ᵢ",j:"ⱼ",k:"ₖ",l:"ₗ",m:"ₘ",n:"ₙ",o:"ₒ",p:"ₚ",r:"ᵣ",s:"ₛ",t:"ₜ",u:"ᵤ",v:"ᵥ",x:"ₓ"},SPACING_COMMANDS=new Set([",",":",";"," ",">","enspace","enskip","medspace","quad","qquad","thickspace","thinspace"]),NEGATIVE_SPACING_COMMANDS=new Set(["!","negmedspace","negthickspace","negthinspace"]),IGNORED_COMMANDS=new Set(["displaystyle","limits","nolimits","scriptstyle","scriptscriptstyle","textstyle"]),SIZE_COMMANDS=new Set(["big","Big","bigg","Bigg","bigl","Bigl","biggl","Biggl","bigr","Bigr","biggr","Biggr"]),PLAIN_WRAPPERS=new Set(["emph","mathcal","mathbf","mathfrak","mathit","mathrm","mathnormal","mathscr","mathsf","mathtt","mathup","mbox","overbrace","pmb","smash","substack","text","textbf","textit","textmd","textnormal","textrm","textsc","textsf","textsl","texttt","textup","underbrace","bm","boldsymbol"]),ACCENTS={acute:"́",bar:"̅",breve:"̆",check:"̌",ddot:"̈",dot:"̇",grave:"̀",hat:"̂",mathring:"̊",overleftarrow:"⃖",overleftrightarrow:"⃡",overline:"̅",overrightarrow:"⃗",tilde:"̃",underline:"̲",vec:"⃗",widehat:"̂",widetilde:"̃"};NAMED_OPERATOR_LEFT_SPACING_PATTERN=/(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu,NAMED_OPERATOR_RIGHT_SPACING_PATTERN=/\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu;LAYOUT_MARKER_PATTERN=/\u{f0000}(\d+)\u{f0001}/gu,TRAILING_LAYOUT_MARKER_PATTERN=/\u{f0000}(\d+)\u{f0001}$/u});function configureMarked(){if(markedConfigured)return;markedConfigured=!0,f.use({tokenizer:{del(){return}}}),f.use({extensions:[...LATEX_EXTENSIONS]})}function isEscaped(source,index){let backslashes=0;for(let position=index-1;position>=0&&source[position]==="\\";position--)backslashes++;return backslashes%2===1}function findClosingDelimiter(source,closing,start){let index=source.indexOf(closing,start);while(index>=0&&isEscaped(source,index))index=source.indexOf(closing,index+closing.length);return index}function looksLikePendingDollarMath(source){return/\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(source)}function tokenizeInlineLatex(source){let opening="",closing="";if(source.startsWith("$$"))opening="$$",closing="$$";else if(source.startsWith("\\("))opening="\\(",closing="\\)";else if(source.startsWith("\\["))opening="\\[",closing="\\]";else if(source.startsWith("$")&&!/^\$\s/.test(source))opening="$",closing="$";else return;let closingIndex=findClosingDelimiter(source,closing,opening.length);if(closingIndex>=0&&opening==="$"&&(/\s$/.test(source.slice(opening.length,closingIndex))||/^\d/.test(source.slice(closingIndex+1))||/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(source.slice(opening.length,closingIndex))&&/^[A-Za-z_][A-Za-z0-9_]*/.test(source.slice(closingIndex+1))||source.slice(opening.length,closingIndex).includes("`")))return;if(closingIndex<0){let pendingSource=source.slice(opening.length);if(opening.startsWith("\\")||looksLikePendingDollarMath(pendingSource))return{type:"latex",raw:source,text:pendingSource,pending:!0};return}let text=source.slice(opening.length,closingIndex);if(!text||text.includes(EOL2))return;return{type:"latex",raw:source.slice(0,closingIndex+closing.length),text}}function tokenizeBlockLatex(source){let dollarMatch=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(source);if(dollarMatch?.[1])return{type:"latexBlock",raw:dollarMatch[0],text:dollarMatch[1].trim()};let bracketMatch=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(source);if(bracketMatch?.[1])return{type:"latexBlock",raw:bracketMatch[0],text:bracketMatch[1].trim()};let pendingBracket=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(source);if(pendingBracket)return{type:"latexBlock",raw:pendingBracket[0],text:pendingBracket[1],pending:!0};let pendingDollar=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(source);if(pendingDollar?.[1]&&looksLikePendingDollarMath(pendingDollar[1]))return{type:"latexBlock",raw:pendingDollar[0],text:pendingDollar[1],pending:!0};return}function supportsHyperlinks(){let env=process.env;if(env.FORCE_HYPERLINK==="1")return!0;if(!process.stdout.isTTY)return!1;if(env.TERM_PROGRAM==="iTerm.app"||env.TERM_PROGRAM==="WezTerm")return!0;if(env.TERM_PROGRAM==="vscode"||env.WT_SESSION)return!0;if(env.VTE_VERSION&&Number.parseInt(env.VTE_VERSION,10)>=5000)return!0;if(env.KITTY_WINDOW_ID||env.KONSOLE_VERSION||env.GHOSTTY_RESOURCES_DIR)return!0;return!1}function createHyperlink(url,text=url){if(!supportsHyperlinks())return text===url?url:`${text} (${url})`;return`\x1B]8;;${url}\x07${text}\x1B]8;;\x07`}function padAligned(content,displayWidth,targetWidth,align){let padding=Math.max(0,targetWidth-displayWidth);if(align==="center"){let leftPadding=Math.floor(padding/2);return" ".repeat(leftPadding)+content+" ".repeat(padding-leftPadding)}if(align==="right")return" ".repeat(padding)+content;return content+" ".repeat(padding)}function numberToLetter(n){let result="";while(n>0)n--,result=String.fromCharCode(97+n%26)+result,n=Math.floor(n/26);return result}function numberToRoman(n){let result="";for(let[value,numeral]of ROMAN_VALUES)while(n>=value)result+=numeral,n-=value;return result}function getListNumber(listDepth,orderedListNumber){switch(listDepth){case 2:return numberToLetter(orderedListNumber);case 3:return numberToRoman(orderedListNumber);default:return String(orderedListNumber)}}function formatChildren(tokens,parent=null,listDepth=0,orderedListNumber=null){return(tokens??[]).map((child)=>formatToken(child,listDepth,orderedListNumber,parent)).join("")}function formatToken(token,listDepth=0,orderedListNumber=null,parent=null){switch(token.type){case"blockquote":{let inner=formatChildren(token.tokens),bar=source_default.dim("│");return inner.split(EOL2).map((line)=>stripAnsi2(line).trim()?`${bar} ${source_default.italic(line)}`:line).join(EOL2)}case"code":return token.text+EOL2;case"codespan":return source_default.cyan(token.text);case"em":return source_default.italic(formatChildren(token.tokens,parent));case"strong":return source_default.bold(formatChildren(token.tokens,parent));case"heading":{let inner=formatChildren(token.tokens);return(token.depth===1?source_default.bold.underline(inner):source_default.bold(inner))+EOL2+EOL2}case"hr":return"---"+EOL2;case"image":return token.href;case"latex":{if(token.pending)return token.raw;return renderLatex(token.text)??token.raw}case"latexBlock":return(token.pending?token.raw.trim():renderLatex(token.text,{display:!0})??token.raw.trim())+EOL2+EOL2;case"link":{if(token.href.startsWith("mailto:"))return token.href.replace(/^mailto:/,"");let linkText=formatChildren(token.tokens,token),plainLinkText=stripAnsi2(linkText);if(plainLinkText&&plainLinkText!==token.href)return createHyperlink(token.href,linkText);return createHyperlink(token.href)}case"list":return token.items.map((item,index)=>formatToken(item,listDepth,token.ordered?token.start+index:null,token)).join("");case"list_item":return(token.tokens??[]).map((child)=>`${" ".repeat(listDepth)}${formatToken(child,listDepth+1,orderedListNumber,token)}`).join("");case"paragraph":return formatChildren(token.tokens)+EOL2;case"space":return EOL2;case"br":return EOL2;case"text":if(parent?.type==="link")return token.text;if(parent?.type==="list_item"){let marker=orderedListNumber===null?"-":`${getListNumber(listDepth,orderedListNumber)}.`,inner=token.tokens?formatChildren(token.tokens,token,listDepth,orderedListNumber):token.text;return`${marker} ${inner}${EOL2}`}return token.tokens?formatChildren(token.tokens,token):token.text;case"table":return renderTable(token);case"escape":return token.text;case"def":case"del":case"html":return"";default:return token.raw??""}}function getTableTerminalWidth(){let columns=Number(process.stdout?.columns);return Number.isFinite(columns)&&columns>0?Math.max(columns-2,1):1/0}function wrapPlainText(text,width,hard){let lines=[];for(let sourceLine of text.split(EOL2)){if(sourceLine.length===0){lines.push("");continue}let remaining=sourceLine;while(stringWidth2(remaining)>width){let cut=0,currentWidth=0,lastSpace=-1;for(let character of remaining){let characterWidth=stringWidth2(character);if(currentWidth+characterWidth>width)break;if(currentWidth+=characterWidth,cut+=character.length,/\s/.test(character))lastSpace=cut}if(cut===0)cut=Math.max(1,Array.from(remaining)[0].length);else if(!hard&&lastSpace>0)cut=lastSpace;lines.push(remaining.slice(0,cut).trimEnd()),remaining=remaining.slice(cut).trimStart()}lines.push(remaining)}return lines}function wrapTableText(text,width,hard=!1){let trimmedText=text.trimEnd();if(!Number.isFinite(width)||width<=0)return[trimmedText];let wrapped;if(typeof Bun<"u"&&typeof Bun.wrapAnsi==="function")wrapped=Bun.wrapAnsi(trimmedText,width,{hard,trim:!1,wordWrap:!0});else wrapped=wrapPlainText(stripAnsi2(trimmedText),width,hard).join(EOL2);let lines=wrapped.split(EOL2).filter((line)=>line.length>0);return lines.length>0?lines:[""]}function renderTable(tableToken){let headers=tableToken.header??[],rows=tableToken.rows??[],columnCount=Math.max(headers.length,...rows.map((row)=>row.length),0);if(columnCount===0)return"";let formatCell=(cell)=>formatChildren(cell?.tokens),getPlainText=(cell)=>stripAnsi2(formatCell(cell)),getMinWidth=(cell)=>{let words=getPlainText(cell).split(/\s+/).filter((word)=>word.length>0);if(words.length===0)return TABLE_MIN_COLUMN_WIDTH;return Math.max(...words.map((word)=>stringWidth2(word)),TABLE_MIN_COLUMN_WIDTH)},getIdealWidth=(cell)=>Math.max(stringWidth2(getPlainText(cell)),TABLE_MIN_COLUMN_WIDTH),minWidths=Array.from({length:columnCount},(_,columnIndex)=>{let width=getMinWidth(headers[columnIndex]);for(let row of rows)width=Math.max(width,getMinWidth(row[columnIndex]));return width}),idealWidths=Array.from({length:columnCount},(_,columnIndex)=>{let width=getIdealWidth(headers[columnIndex]);for(let row of rows)width=Math.max(width,getIdealWidth(row[columnIndex]));return width}),terminalWidth=getTableTerminalWidth(),borderOverhead=1+columnCount*3,availableWidth=Number.isFinite(terminalWidth)?Math.max(terminalWidth-borderOverhead-TABLE_SAFETY_MARGIN,columnCount*TABLE_MIN_COLUMN_WIDTH):1/0,totalMin=minWidths.reduce((sum,width)=>sum+width,0),totalIdeal=idealWidths.reduce((sum,width)=>sum+width,0),needsHardWrap=!1,columnWidths;if(totalIdeal<=availableWidth)columnWidths=idealWidths;else if(totalMin<=availableWidth){let extraSpace=availableWidth-totalMin,overflows=idealWidths.map((ideal,index)=>ideal-minWidths[index]),totalOverflow=overflows.reduce((sum,overflow)=>sum+overflow,0);columnWidths=minWidths.map((min,index)=>{if(totalOverflow===0)return min;return min+Math.floor(overflows[index]/totalOverflow*extraSpace)})}else{needsHardWrap=!0;let scaleFactor=availableWidth/totalMin;columnWidths=minWidths.map((width)=>Math.max(Math.floor(width*scaleFactor),TABLE_MIN_COLUMN_WIDTH))}let allRows=[headers,...rows],getRowLines=(cells,isHeader)=>{let cellLines=Array.from({length:columnCount},(_,columnIndex)=>wrapTableText(formatCell(cells[columnIndex]),columnWidths[columnIndex],needsHardWrap)),maxLines=Math.max(...cellLines.map((lines)=>lines.length),1),verticalOffsets=cellLines.map((lines)=>Math.floor((maxLines-lines.length)/2)),result=[];for(let lineIndex=0;lineIndex<maxLines;lineIndex++){let line="│";for(let columnIndex=0;columnIndex<columnCount;columnIndex++){let lines=cellLines[columnIndex],contentIndex=lineIndex-verticalOffsets[columnIndex],lineText=contentIndex>=0&&contentIndex<lines.length?lines[contentIndex]:"",align=isHeader?"center":tableToken.align?.[columnIndex]??"left";line+=` ${padAligned(lineText,stringWidth2(lineText),columnWidths[columnIndex],align)} │`}result.push(line)}return result},maxRowLines=Math.max(...allRows.flatMap((cells)=>Array.from({length:columnCount},(_,columnIndex)=>wrapTableText(formatCell(cells[columnIndex]),columnWidths[columnIndex],needsHardWrap).length)),1),renderBorder=(type)=>{let borders={top:["┌","─","┬","┐"],middle:["├","─","┼","┤"],bottom:["└","─","┴","┘"]},[left,horizontal,cross,right]=borders[type],line=left;return columnWidths.forEach((width,index)=>{line+=horizontal.repeat(width+2),line+=index<columnWidths.length-1?cross:right}),line},renderVertical=()=>{let safeWidth=Number.isFinite(terminalWidth)?terminalWidth:80,separator="─".repeat(Math.max(1,Math.min(safeWidth-1,40))),lines=[];for(let[rowIndex,row]of rows.entries()){if(rowIndex>0)lines.push(separator);for(let columnIndex=0;columnIndex<columnCount;columnIndex++){let label=getPlainText(headers[columnIndex])||`Column ${columnIndex+1}`,value=formatCell(row[columnIndex]).replace(/\n+/g," ").replace(/\s+/g," ").trim(),firstWidth=Math.max(safeWidth-stringWidth2(label)-3,10),continuationWidth=Math.max(safeWidth-3,10),firstPass=wrapTableText(value,firstWidth),wrappedValue=firstPass;if(firstPass.length>1&&continuationWidth>firstWidth){let remaining=firstPass.slice(1).map((line)=>line.trim()).join(" ");wrappedValue=[firstPass[0],...wrapTableText(remaining,continuationWidth)]}lines.push(`${ANSI_BOLD_START}${label}:${ANSI_BOLD_END} ${wrappedValue[0]??""}`);for(let line of wrappedValue.slice(1))if(line.trim())lines.push(` ${line}`)}}return lines.join(EOL2)};if(maxRowLines>TABLE_MAX_ROW_LINES)return renderVertical();let tableLines=[renderBorder("top"),...getRowLines(headers,!0),renderBorder("middle")];rows.forEach((row,rowIndex)=>{if(tableLines.push(...getRowLines(row,!1)),rowIndex<rows.length-1)tableLines.push(renderBorder("middle"))}),tableLines.push(renderBorder("bottom"));let maxLineWidth=Math.max(...tableLines.map((line)=>stringWidth2(line)),0);if(Number.isFinite(terminalWidth)&&maxLineWidth>terminalWidth-TABLE_SAFETY_MARGIN)return renderVertical();return tableLines.join(EOL2)+EOL2}function hasMarkdownSyntax(text){return MARKDOWN_SYNTAX_PATTERN.test(text.slice(0,500))}function renderMarkdown(text){if(!text||text.trim().length===0)return text;if(!hasMarkdownSyntax(text))return text;configureMarked();try{let rendered=f.lexer(text).map((token)=>formatToken(token)).join("").trimEnd();return rendered.length>0?rendered:text}catch{return text}}var EOL2=`
2297
- `,markedConfigured=!1,LATEX_EXTENSIONS,ROMAN_VALUES,TABLE_SAFETY_MARGIN=4,TABLE_MIN_COLUMN_WIDTH=3,TABLE_MAX_ROW_LINES=4,ANSI_BOLD_START="\x1B[1m",ANSI_BOLD_END="\x1B[22m",MARKDOWN_SYNTAX_PATTERN;var init_markdown=__esm(()=>{init_source2();init_marked_esm();init_latex();init_markdown_width();LATEX_EXTENSIONS=[{name:"latexBlock",level:"block",start(source){let match=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(source);return match?match.index+(match[0].startsWith(EOL2)?1:0):void 0},tokenizer:tokenizeBlockLatex},{name:"latex",level:"inline",start(source){let indices=[source.indexOf("$"),source.indexOf("\\("),source.indexOf("\\[")].filter((index)=>index>=0);return indices.length>0?Math.min(...indices):void 0},tokenizer:tokenizeInlineLatex}];ROMAN_VALUES=[[1000,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]];MARKDOWN_SYNTAX_PATTERN=/[*_`#>[\]~|\-$\\]/});import process27 from"node:process";function Banner(){let{columns=80}=use_window_size_default(),modelConfig=useStore2((state)=>state.modelConfig),providerName=useStore2((state)=>state.providerName),details=[modelConfig?currentModelName(modelConfig):null,providerName].filter(Boolean).join(" · "),stacked=columns<40;return $jsxs(Box_default,{flexDirection:stacked?"column":"row",paddingX:1,marginY:1,children:[$jsx(Box_default,{width:LOGO_WIDTH,flexDirection:"column",flexShrink:0,marginRight:stacked?0:2,marginBottom:stacked?1:0,children:MIRO_LOGO_ROWS.map((row,rowIndex)=>$jsx(Text,{children:row.map(([glyphs,color],segmentIndex)=>$jsx(Text,{color,children:glyphs},segmentIndex))},rowIndex))}),$jsxs(Box_default,{flexDirection:"column",flexGrow:1,flexShrink:1,minWidth:0,children:[$jsxs(Text,{wrap:"truncate",children:[$jsx(Text,{bold:!0,children:"Miro"})," ",$jsxs(Text,{dimColor:!0,children:["v",APP_VERSION]})]}),details?$jsx(Text,{dimColor:!0,wrap:"truncate",children:details}):null,$jsx(Text,{dimColor:!0,wrap:"truncate-start",children:process27.cwd()})]})]})}var LOGO_WIDTH;var init_Banner=__esm(async()=>{init_config();init_figures();init_markdown_width();init_store();init_react_jsx_runtime_production();await init_build4();LOGO_WIDTH=Math.max(...MIRO_LOGO.split(`
2298
- `).map(stringWidth2))});function graphemes(value){let text=String(value??"");return segmenter5?[...segmenter5.segment(text)].map(({segment})=>segment):Array.from(text)}function graphemeWidth(grapheme){if(!grapheme)return 0;if(/\p{Extended_Pictographic}/u.test(grapheme))return 2;let width=0;for(let character of grapheme){let point=character.codePointAt(0);if(point===8205||/\p{Mark}/u.test(character))continue;if(point<32||point>=127&&point<160)continue;width+=point>=4352&&(point<=4447||point===9001||point===9002||point>=11904&&point<=42191&&point!==12351||point>=44032&&point<=55203||point>=63744&&point<=64255||point>=65040&&point<=65049||point>=65072&&point<=65135||point>=65280&&point<=65376||point>=65504&&point<=65510||point>=131072&&point<=262141)?2:1}return width}function displayWidth(value){return graphemes(value).reduce((total,item)=>total+graphemeWidth(item),0)}function takeWidth(value,columns){if(columns<=0)return["",String(value??"")];let used=0,head="",tail="";for(let item of graphemes(value)){let itemWidth=graphemeWidth(item);if(tail||used>0&&used+itemWidth>columns)tail+=item;else if(used===0&&itemWidth>columns)head+="?",used+=1;else head+=item,used+=itemWidth}return[head,tail]}function fit(value,columns){let text=String(value??"");if(displayWidth(text)<=columns)return text;if(columns<=1)return takeWidth("…",columns)[0];return`${takeWidth(text,columns-1)[0]}…`}function lineKind(type){if(["+","add","added","addition","insert"].includes(type))return"add";if(["-","del","delete","deleted","deletion","remove"].includes(type))return"delete";return"context"}function hunkRows(hunk,{showLineNumbers=!0}={}){let startOld=hunk?.oldStart??hunk?.oldLine,startNew=hunk?.newStart??hunk?.newLine,oldLine=showLineNumbers&&startOld!=null?Number(startOld):null,newLine=showLineNumbers&&startNew!=null?Number(startNew):null,rows=[];for(let input of Array.isArray(hunk?.lines)?hunk.lines:[]){if(typeof input==="string"&&input.startsWith("\\ No newline"))continue;let rawType=typeof input==="string"?input[0]:input?.type??input?.kind,kind=lineKind(rawType),content=typeof input==="string"?["+","-"," "].includes(input[0])?input.slice(1):input:String(input?.content??input?.text??""),explicitOld=showLineNumbers&&typeof input==="object"?input?.oldLine??input?.oldLineNumber:void 0,explicitNew=showLineNumbers&&typeof input==="object"?input?.newLine??input?.newLineNumber:void 0,row={kind,content:content.replace(/\t/g," "),oldLine:kind==="add"?null:explicitOld??oldLine,newLine:kind==="delete"?null:explicitNew??newLine};if(rows.push(row),kind!=="add"&&(explicitOld??oldLine)!=null)oldLine=(explicitOld??oldLine)+1;if(kind!=="delete"&&(explicitNew??newLine)!=null)newLine=(explicitNew??newLine)+1}return rows}function logicalRows(diff){let showLineNumbers=diff?.hasLineNumbers!==!1,rows=[];for(let[index,hunk]of(diff?.hunks??[]).entries()){if(index>0)rows.push({kind:"separator",content:"…"});rows.push(...hunkRows(hunk,{showLineNumbers}))}return rows}function gutterWidth(rows){let highest=rows.reduce((value,row)=>Math.max(value,row.oldLine??0,row.newLine??0),1);return String(highest).length}function rowsHaveLineNumbers(rows){return rows.some((row)=>row.oldLine!=null||row.newLine!=null)}function physicalRows(rows,columns){let numbered=rowsHaveLineNumbers(rows),digits=numbered?gutterWidth(rows):0,normalPrefixWidth=numbered?digits*2+4:2,compact=!numbered||columns<normalPrefixWidth+2,prefixWidth=compact?Math.min(2,columns):normalPrefixWidth,contentWidth=Math.max(1,columns-prefixWidth),output=[];for(let row of rows){if(row.kind==="separator"){output.push({...row,prefix:compact?"":" ".repeat(normalPrefixWidth)});continue}let marker=row.kind==="add"?"+":row.kind==="delete"?"-":" ",firstPrefix=compact?`${marker} `.slice(0,prefixWidth):`${row.oldLine==null?"".padStart(digits):String(row.oldLine).padStart(digits)} ${row.newLine==null?"".padStart(digits):String(row.newLine).padStart(digits)} ${marker} `,continuationPrefix=" ".repeat(prefixWidth),remaining=row.content.length>0?row.content:" ",first=!0;do{let[content,rest]=takeWidth(remaining,contentWidth);output.push({...row,prefix:first?firstPrefix:continuationPrefix,content}),remaining=rest,first=!1}while(remaining.length>0)}return output}function operationLabel(operation){if(operation==="create")return"Create";if(operation==="delete")return"Delete";return"Edit"}function diffLineCount(diff,width=80){let columns=Math.max(1,Math.floor(width));return physicalRows(logicalRows(diff),columns).length}function DiffView({diff,mode="preview",maxLines,offset=0,width,showHeader=!0}){let{stdout}=useStdout(),columns=Math.max(1,Math.floor(width??stdout?.columns??80)),rows=physicalRows(logicalRows(diff),columns),start=Math.max(0,Math.floor(offset)),limit=maxLines==null?mode==="preview"?DEFAULT_PREVIEW_LINES:1/0:Math.max(0,Math.floor(maxLines)),visible=rows.slice(start,Number.isFinite(limit)?start+limit:void 0),hiddenAfter=Math.max(0,rows.length-start-visible.length),hiddenBefore=Math.min(start,rows.length),stats=`+${diff?.additions??0} -${diff?.deletions??0}`,title=`${operationLabel(diff?.operation)} ${diff?.path||"(unknown file)"} · ${stats}`;return $jsxs(Box_default,{flexDirection:"column",width:columns,children:[showHeader?$jsx(Text,{bold:!0,children:fit(title,columns)}):null,hiddenBefore>0?$jsx(Text,{dimColor:!0,children:fit(`… ${hiddenBefore} earlier lines`,columns)}):null,visible.map((row,index)=>{let color=row.kind==="add"?"green":row.kind==="delete"?"red":void 0;return $jsx(Text,{color,dimColor:row.kind==="separator",children:fit(`${row.prefix}${row.content}`,columns)},`${start}-${index}`)}),hiddenAfter>0?$jsx(Text,{dimColor:!0,children:fit(`… +${hiddenAfter} lines`,columns)}):null]})}var DEFAULT_PREVIEW_LINES=10,segmenter5;var init_DiffView=__esm(async()=>{init_react_jsx_runtime_production();await init_build4();segmenter5=typeof Intl.Segmenter==="function"?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null});function rowProps(status){if(status==="completed")return{box:"☒",style:{dimColor:!0,strikethrough:!0}};if(status==="in_progress")return{box:"☐",style:{bold:!0,color:"cyan"}};return{box:"☐",style:{}}}function PlanMessage({block}){let entries=Array.isArray(block.plan?.entries)?block.plan.entries:[],visible=entries.slice(0,PLAN_MAX_ROWS),omitted=entries.length-visible.length;return $jsxs(Box_default,{flexDirection:"column",marginTop:block.head?1:0,children:[$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:2,flexShrink:0,children:$jsx(Text,{color:"green",children:BLACK_CIRCLE})}),$jsx(Text,{bold:!0,children:"Update Todos"})]}),visible.map((entry,index)=>{let props=rowProps(entry?.status);return $jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:5,flexShrink:0,children:$jsx(Text,{dimColor:!0,children:index===0?TREE_LAST_PREFIX:TREE_BLANK_PREFIX})}),$jsx(Box_default,{flexGrow:1,children:$jsx(Text,{wrap:"truncate-end",...props.style,children:`${props.box} ${entry?.content??""}`})})]},index)}),omitted>0?$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:5,flexShrink:0,children:$jsx(Text,{dimColor:!0,children:TREE_BLANK_PREFIX})}),$jsxs(Text,{dimColor:!0,children:["… +",omitted," more"]})]}):null]})}var init_PlanMessage=__esm(async()=>{init_config();init_figures();init_react_jsx_runtime_production();await init_build4()});function ProposedPlanMessage({block}){return $jsxs(Box_default,{flexDirection:"column",marginTop:block.head?1:0,borderStyle:"single",borderColor:"cyan",paddingX:1,children:[$jsxs(Text,{bold:!0,color:"cyan",children:[BLACK_CIRCLE," Approved Plan"]}),$jsx(Text,{children:renderMarkdown(block.text)}),block.planPath?$jsxs(Text,{dimColor:!0,children:["Saved at ",block.planPath]}):null]})}var init_ProposedPlanMessage=__esm(async()=>{init_figures();init_markdown();init_react_jsx_runtime_production();await init_build4()});function toolDotProps(status){if(status==="completed")return{color:"green"};if(status==="failed"||status==="cancelled")return{color:"red"};return{dimColor:!0}}function SubRow({first,children}){return $jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:5,flexShrink:0,children:$jsx(Text,{dimColor:!0,children:first?TREE_LAST_PREFIX:TREE_BLANK_PREFIX})}),$jsx(Box_default,{flexGrow:1,children:$jsx(Text,{dimColor:!0,wrap:"truncate-end",children})})]})}function SubagentMessage({block}){let{label,status,elapsed,subagent}=block.tool,display=subagentDisplay(subagent),running=status!=="completed"&&status!=="failed"&&status!=="cancelled",statsParts=[];if(display.toolCount>0)statsParts.push(`${display.toolCount} tool ${display.toolCount===1?"use":"uses"}`);let tokens=formatTokens(display.tokens);if(tokens)statsParts.push(`${tokens} tokens`);let duration=elapsed==null?null:formatDuration(elapsed);if(duration)statsParts.push(duration);let stats=statsParts.join(" · "),rowIndex=0,nextFirst=()=>rowIndex++===0;return $jsxs(Box_default,{flexDirection:"column",marginTop:block.head?1:0,children:[$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:2,flexShrink:0,children:$jsx(Text,{...toolDotProps(status),children:BLACK_CIRCLE})}),$jsx(Box_default,{flexGrow:1,children:$jsxs(Text,{wrap:"truncate-end",children:[$jsx(Text,{bold:!0,color:"magenta",children:label.name}),label.args?`(${label.args})`:""]})})]}),display.rows.map((row,index)=>$jsx(SubRow,{first:nextFirst(),children:row},index)),display.moreTools>0?$jsxs(SubRow,{first:nextFirst(),children:["+",display.moreTools," more tool uses"]}):null,!running&&display.textLine?$jsx(SubRow,{first:nextFirst(),children:display.textLine}):null,running?$jsxs(SubRow,{first:nextFirst(),children:["Running…",stats?` (${stats})`:""]}):$jsxs(SubRow,{first:nextFirst(),children:[status==="completed"?"Done":status==="cancelled"?"Cancelled":"Failed",stats?` (${stats})`:""]})]})}function wrapCommandRows(command,{firstWidth,width}){let rows=[];for(let logicalLine of String(command).split(`
2299
- `)){let wrapped=wrapVisualRows(logicalLine,width,{firstWidth:rows.length===0?firstWidth:width});rows.push(wrapped[0]??"");for(let row of wrapped.slice(1))rows.push(row.replace(/^ +/,""))}return rows}function ToolMessage({block,reviewHint,width}){let{stdout}=useStdout(),columns=width??stdout?.columns??80,{label,group,status,elapsed,hint,preview,command,diff,autoReview}=block.tool,name=group?group.name:label.name,elapsedText=elapsed!=null?formatDuration(elapsed):null,elapsedReserve=elapsedText?stringWidth2(` (${elapsedText})`):0,hintReserve=reviewHint?stringWidth2(" · ctrl+o to review"):0,commandRows=command&&!group?wrapCommandRows(command,{width:Math.max(1,columns-5-elapsedReserve),firstWidth:Math.max(1,columns-2-stringWidth2(name)-1-elapsedReserve-hintReserve)}):[],showCommand=commandRows.length>1,bodyCommandRows=showCommand?commandRows.slice(1,COMMAND_PREVIEW_ROWS):[],hiddenCommandRows=showCommand?Math.max(0,commandRows.length-COMMAND_PREVIEW_ROWS):0,args=group||showCommand?null:label.args,showDiff=diff!=null&&(diff.complete===!0||TERMINAL_STATUSES.has(status)),allChildItems=group?.items??[],childItems=allChildItems.length>4?[...allChildItems.slice(0,3),allChildItems.at(-1)]:allChildItems,hiddenItems=Math.max(0,(group?.items?.length??0)-childItems.length);return $jsxs(Box_default,{flexDirection:"column",marginTop:block.head?1:0,children:[$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:2,flexShrink:0,children:$jsx(Text,{...toolDotProps(status),children:BLACK_CIRCLE})}),$jsx(Box_default,{flexGrow:1,children:$jsxs(Text,{wrap:"truncate-end",children:[$jsx(Text,{bold:!0,children:name}),args?`(${args})`:"",showCommand?` ${commandRows[0]}`:"",group?.summary?$jsxs(Text,{dimColor:!0,children:[" · ",group.summary]}):null,showDiff?$jsxs($Fragment,{children:[$jsx(Text,{dimColor:!0,children:" · "}),$jsxs(Text,{color:"green",children:["+",diff.additions??0]}),$jsx(Text,{children:" "}),$jsxs(Text,{color:"red",children:["-",diff.deletions??0]})]}):null,!showCommand&&elapsedText?$jsxs(Text,{dimColor:!0,children:[" (",elapsedText,")"]}):null,reviewHint?$jsx(Text,{dimColor:!0,children:" · ctrl+o to review"}):null]})})]}),childItems.map((item,index)=>$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:5,flexShrink:0,children:$jsx(Text,{dimColor:!0,children:index===childItems.length-1&&hiddenItems===0?TREE_LAST_PREFIX:TREE_MID_PREFIX})}),$jsxs(Text,{dimColor:!0,wrap:"truncate-end",children:[item.label?.name??"Tool",item.label?.args?`(${item.label.args})`:""]})]},index)),hiddenItems>0?$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:5,flexShrink:0,children:$jsx(Text,{dimColor:!0,children:TREE_LAST_PREFIX})}),$jsxs(Text,{dimColor:!0,children:["+",hiddenItems," more calls"]})]}):null,showCommand?$jsxs(Box_default,{flexDirection:"column",children:[bodyCommandRows.map((row,index)=>$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:5,flexShrink:0,children:$jsx(Text,{dimColor:!0,children:TREE_VERTICAL_PREFIX})}),$jsx(Box_default,{flexGrow:1,children:$jsxs(Text,{wrap:"truncate-end",children:[row.length>0?row:" ",index===bodyCommandRows.length-1&&hiddenCommandRows===0&&elapsedText?$jsxs(Text,{dimColor:!0,children:[" (",elapsedText,")"]}):null]})})]},index)),hiddenCommandRows>0?$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:5,flexShrink:0,children:$jsx(Text,{dimColor:!0,children:TREE_VERTICAL_PREFIX})}),$jsxs(Text,{dimColor:!0,children:["… +",hiddenCommandRows," lines",elapsedText?` (${elapsedText})`:""]})]}):null]}):null,hint?$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:5,flexShrink:0,children:$jsx(Text,{dimColor:!0,children:TREE_LAST_PREFIX})}),$jsx(Box_default,{flexGrow:1,children:$jsx(Text,{dimColor:!0,wrap:"truncate-end",children:hint})})]}):null,autoReview?$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:5,flexShrink:0,children:$jsx(Text,{dimColor:!0,children:TREE_LAST_PREFIX})}),$jsx(Box_default,{flexGrow:1,children:$jsx(Text,{dimColor:autoReview.status!=="blocked",color:autoReview.status==="blocked"?"red":autoReview.status==="checking"?"yellow":void 0,wrap:autoReview.status==="blocked"?"wrap":"truncate-end",children:autoReviewNote(autoReview)})})]}):null,showDiff?$jsx(Box_default,{paddingLeft:5,children:$jsx(DiffView,{diff,mode:"preview",maxLines:8,width:Math.max(1,columns-5),showHeader:!1})}):null,diff&&!showDiff?$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:5,flexShrink:0,children:$jsx(Text,{dimColor:!0,children:TREE_LAST_PREFIX})}),$jsx(Box_default,{flexGrow:1,children:$jsxs(Text,{dimColor:!0,wrap:"truncate-end",children:["Editing",diff.path?` ${diff.path}`:"","…"]})})]}):null,!diff&&preview?.lines?.length>0?$jsxs(Box_default,{flexDirection:"column",children:[preview.lines.map((line,index)=>$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:5,flexShrink:0,children:$jsx(Text,{dimColor:!0,children:index===0&&!hint?TREE_LAST_PREFIX:TREE_BLANK_PREFIX})}),$jsx(Box_default,{flexGrow:1,children:$jsx(Text,{dimColor:!0,wrap:"truncate-end",children:line.length>0?line:" "})})]},index)),preview.more>0?$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:5,flexShrink:0,children:$jsx(Text,{dimColor:!0,children:TREE_BLANK_PREFIX})}),$jsxs(Text,{dimColor:!0,children:["… +",preview.more," lines"]})]}):null]}):null]})}var ROLE_STYLES,Message;var init_Message=__esm(async()=>{init_react_production();init_subagent();init_tool_title();init_figures();init_config();init_markdown();init_markdown_width();init_thinking();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_Banner(),init_BashCard(),init_DiffView(),init_PlanMessage(),init_ProposedPlanMessage()]);ROLE_STYLES={user:{marker:">",markerColor:"gray",dim:!0},assistant:{marker:BLACK_CIRCLE,markerColor:"green"},system:{marker:"✻",markerColor:"cyan",dim:!0},thought:{marker:"∴",markerColor:"cyan",dim:!0},tool:{marker:BLACK_CIRCLE,markerColor:"yellow",dim:!0},toolUpdate:{marker:TREE_LAST,markerColor:"gray",dim:!0},bashInput:{marker:"!",markerColor:"magenta"},bashOutput:{marker:TREE_LAST,markerColor:"gray",dim:!0},stderr:{marker:"⚠",markerColor:"yellow",dim:!0},error:{marker:"✗",markerColor:"red"}};Message=$memo(function({block,reviewHint=!1,width}){if(block.role==="banner")return $jsx(Banner,{});if(block.role==="bashCard"&&block.card)return $jsx(BashCard,{card:block.card});if(block.role==="tool"&&block.tool){let tool=toolForDisplay(block.tool);if(!tool)return null;let visibleBlock=tool===block.tool?block:{...block,tool};if(tool.subagent)return $jsx(SubagentMessage,{block:visibleBlock});return $jsx(ToolMessage,{block:visibleBlock,reviewHint,width})}if(block.role==="plan"&&block.plan)return $jsx(PlanMessage,{block});if(block.role==="proposedPlan")return $jsx(ProposedPlanMessage,{block});if(block.role==="thought"&&block.thought){if(block.thought.displayMode==="hidden")return null;let body=splitThinkingText(block.thought.text).body,showBody=block.thought.displayMode==="full"&&body.length>0,detailsMissing=block.thought.hasContent&&!block.thought.text;return $jsxs(Box_default,{flexDirection:"column",marginTop:block.head||block.gap?1:0,children:[$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:2,flexShrink:0,children:$jsx(Text,{color:"cyan",children:"∴"})}),$jsx(Box_default,{flexGrow:1,children:$jsxs(Text,{dimColor:!0,wrap:"truncate-end",children:[block.text,detailsMissing?" · details not retained":""]})})]}),showBody?$jsx(Box_default,{paddingLeft:2,marginTop:1,children:$jsx(Text,{dimColor:!0,children:renderMarkdown(body)})}):null]})}if(block.role==="user")return $jsx(Box_default,{marginTop:block.head||block.gap?1:0,borderStyle:"single",borderColor:"gray",borderTop:!1,borderRight:!1,borderBottom:!1,paddingLeft:1,children:$jsx(Text,{bold:!0,children:block.text.length>0?block.text:" "})});let style=ROLE_STYLES[block.role]??ROLE_STYLES.system,text=block.role==="assistant"&&block.text.length>0?renderMarkdown(block.text):block.text;return $jsxs(Box_default,{flexDirection:"row",marginTop:block.head||block.gap?1:0,children:[$jsx(Box_default,{width:2,flexShrink:0,children:$jsx(Text,{color:style.markerColor,children:block.head?style.marker:" "})}),$jsx(Box_default,{flexGrow:1,children:$jsx(Text,{dimColor:style.dim,children:text.length>0?text:" "})})]})})});function tokenHint(tokens){let input=formatTokens2(tokens?.input),output=formatTokens2(tokens?.output),parts=[input==null?null:`↑${input}`,output==null?null:`↓${output}`].filter(Boolean);return parts.length>0?parts.join(" "):null}function activeToolItem(tool,now){return{label:tool.label,kind:tool.raw?.kind??tool.kind??null,status:tool.status,elapsed:tool.startedAt!=null?Math.max(0,now-tool.startedAt):null,preview:tool.preview??null,command:tool.command??null,subagent:tool.subagent??null,detail:tool.detail??null,diff:tool.diff??null,hint:tool.hint??null,autoReview:tool.autoReview??null}}function isBashTool(tool){return tool.raw?.kind==="execute"||tool.kind==="execute"||tool.label?.name==="Bash"}function ActivitySlot({now,busy,cancelling,activeTools,pendingToolGroup,hasBashActivity=!1,awaitingInput=!1}){let thought=useStore2((state)=>state.thought),thinkingDisplay=useStore2((state)=>state.thinkingDisplay),tokens=useStore2((state)=>state.tokens),statBucket=useStore2((state)=>thoughtStatBucket(state.animationTick,THOUGHT_STAT_SAMPLE_TICKS)),thoughtStatRef=$useRef(null),{columns=80}=use_window_size_default();if(hasBashActivity)return null;if(cancelling)return null;if(awaitingInput)return null;if(!busy&&activeTools.length===0&&!pendingToolGroup&&!thought)return null;if(activeTools=activeTools.filter(isVisibleTool),pendingToolGroup){let items=pendingToolGroup.items.filter(isVisibleTool);pendingToolGroup=items.length>0?{...pendingToolGroup,items}:null}let bashTools=activeTools.filter(isBashTool),subagentTools=activeTools.filter((tool)=>!isBashTool(tool)&&tool.subagent),foldableTools=activeTools.filter((tool)=>!isBashTool(tool)&&!tool.subagent),liveExtras=[...subagentTools,...bashTools].map((tool)=>$jsx(Message,{block:{role:"tool",head:!0,tool:activeToolItem(tool,now)},width:columns},tool.toolCallId));if(pendingToolGroup&&(!thought||foldableTools.length>0)||foldableTools.length>1){let groupedItems=[...pendingToolGroup?.items??[],...foldableTools.map((tool)=>activeToolItem(tool,now))],startedAt=pendingToolGroup?.startedAt??foldableTools.reduce((earliest,tool)=>tool.startedAt==null?earliest:Math.min(earliest,tool.startedAt),now),liveGroup={...pendingToolGroup??{},items:groupedItems,hint:pendingToolGroup?.hint??foldableTools.find((tool)=>tool.hint)?.hint??null,startedAt,finishedAt:now};return $jsxs(Box_default,{flexDirection:"column",children:[groupedItems.length>0?$jsx(Message,{block:{role:"tool",head:!0,tool:toolFromGroup(liveGroup,{live:busy,now})},reviewHint:Boolean(pendingToolGroup),width:columns}):null,liveExtras]})}if(subagentTools.length>0){let active=foldableTools.at(-1);return $jsxs(Box_default,{flexDirection:"column",children:[active?$jsx(Message,{block:{role:"tool",head:!0,tool:activeToolItem(active,now)},width:columns}):null,liveExtras]})}let active=activeTools.at(-1);if(active)return $jsx(Message,{block:{role:"tool",head:!0,tool:activeToolItem(active,now)},width:columns});if(!thought)return null;let parsed=splitThinkingText(thought.text),hasText=Boolean(parsed.body.trim()),previewLines=hasText&&thought.expanded?thinkingPreview(thought.text,Math.max(1,columns-2),THOUGHT_PREVIEW_LINES):null,elapsed=formatDuration(thinkingElapsed(thought,now)),thoughtStat=sampleThoughtTokens(thoughtStatRef.current,thought.text,statBucket);thoughtStatRef.current=thoughtStat;let liveOutput=formatTokens2(thoughtStat.tokens),io=liveOutput!=null?`↓${liveOutput}`:tokenHint(tokens),title=thinkingDisplay==="hidden"&&!thought.expanded?null:thought.title??parsed.title,statusParts=[elapsed,io].filter(Boolean);return $jsxs(Box_default,{flexDirection:"column",marginTop:1,children:[$jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:2,flexShrink:0,children:$jsx(Text,{color:"cyan",children:"∴"})}),$jsxs(Text,{dimColor:!0,wrap:"truncate-end",children:[title?`Thinking: ${[title,...statusParts].join(" · ")}`:statusParts.length>0?`Thinking… (${statusParts.join(" · ")})`:"Thinking…",hasText?" · ctrl+o to review":""]})]}),previewLines?$jsx(Box_default,{paddingLeft:2,marginTop:1,height:THOUGHT_PREVIEW_LINES,flexShrink:0,overflow:"hidden",children:$jsx(Text,{dimColor:!0,wrap:"truncate-end",children:previewLines.join(`
2300
- `)})}):null]})}var init_ActivitySlot=__esm(async()=>{init_react_production();init_config();init_items7();init_store();init_thinking();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_Message()])});function acquireAnimationClock(){if(subscribers+=1,timer==null){if(timer=setInterval(()=>useStore2.getState().bumpAnimationTick(),ANIMATION_FRAME_MS),typeof timer.unref==="function")timer.unref()}let released=!1;return()=>{if(released)return;if(released=!0,subscribers-=1,subscribers>0||timer==null)return;clearInterval(timer),timer=null,subscribers=0}}var ANIMATION_FRAME_MS=100,subscribers=0,timer=null;var init_animation_clock=__esm(()=>{init_store()});function normalizeSpinnerVerbsConfig(value){if(!value||typeof value!=="object"||Array.isArray(value))return null;if(!Array.isArray(value.verbs))return null;let verbs=value.verbs.filter((verb)=>typeof verb==="string").map((verb)=>verb.trim()).filter((verb)=>verb.length>0);if(verbs.length===0)return null;return{mode:value.mode==="replace"?"replace":"append",verbs}}function getSpinnerVerbs(settings=readSystemSettings()){let config=normalizeSpinnerVerbsConfig(settings.spinnerVerbs);if(!config)return SPINNER_VERBS;if(config.mode==="replace")return config.verbs;return[...SPINNER_VERBS,...config.verbs]}function sampleSpinnerVerb(verbs=getSpinnerVerbs()){if(!Array.isArray(verbs)||verbs.length===0)return"Working";return verbs[Math.floor(Math.random()*verbs.length)]??"Working"}var SPINNER_VERBS;var init_spinner_verbs=__esm(()=>{init_settings_file();SPINNER_VERBS=["Accomplishing","Actioning","Actualizing","Architecting","Baking","Beaming","Befuddling","Billowing","Blanching","Bloviating","Boogieing","Boondoggling","Booping","Bootstrapping","Brewing","Burrowing","Calculating","Canoodling","Caramelizing","Cascading","Catapulting","Cerebrating","Channeling","Choreographing","Churning","Coalescing","Cogitating","Combobulating","Composing","Computing","Concocting","Considering","Contemplating","Cooking","Crafting","Creating","Crunching","Crystallizing","Cultivating","Deciphering","Deliberating","Determining","Dilly-dallying","Discombobulating","Doing","Doodling","Drizzling","Ebbing","Effecting","Elucidating","Embellishing","Enchanting","Envisioning","Evaporating","Fermenting","Fiddle-faddling","Finagling","Flambéing","Flibbertigibbeting","Flowing","Flummoxing","Fluttering","Forging","Forming","Frolicking","Frosting","Gallivanting","Galloping","Garnishing","Generating","Germinating","Gesticulating","Grooving","Gusting","Harmonizing","Hashing","Hatching","Herding","Honking","Hullaballooing","Hyperspacing","Ideating","Imagining","Improvising","Incubating","Inferring","Infusing","Ionizing","Jitterbugging","Julienning","Kneading","Leavening","Levitating","Lollygagging","Manifesting","Marinating","Meandering","Metamorphosing","Misting","Mooning","Moonwalking","Moseying","Mulling","Musing","Mustering","Nebulizing","Nesting","Noodling","Nucleating","Orbiting","Orchestrating","Osmosing","Perambulating","Percolating","Perusing","Philosophising","Photosynthesizing","Pollinating","Pondering","Pontificating","Pouncing","Precipitating","Prestidigitating","Processing","Proofing","Propagating","Puttering","Puzzling","Quantumizing","Razzle-dazzling","Razzmatazzing","Recombobulating","Reticulating","Roosting","Ruminating","Sautéing","Scampering","Schlepping","Scurrying","Seasoning","Shenaniganing","Shimmying","Simmering","Skedaddling","Sketching","Slithering","Smooshing","Spelunking","Spinning","Sprouting","Stewing","Sublimating","Swirling","Swooping","Symbioting","Synthesizing","Tempering","Thinking","Thundering","Tinkering","Tomfoolering","Topsy-turvying","Transfiguring","Transmuting","Twisting","Undulating","Unfurling","Unravelling","Vibing","Waddling","Wandering","Warping","Whatchamacalliting","Whirlpooling","Whirring","Whisking","Wibbling","Working","Wrangling","Zesting","Zigzagging"]});function useSpinner(active){let tick=useStore2((state)=>state.animationTick);return $useEffect(()=>{if(!active)return;return acquireAnimationClock()},[active]),FRAMES[tick%FRAMES.length]}function useSpinnerVerb(turnKey=null){let[verb,setVerb]=$useState(sampleSpinnerVerb),[seenKey,setSeenKey]=$useState(turnKey);if(turnKey!==seenKey)setSeenKey(turnKey),setVerb(sampleSpinnerVerb());return verb}var FRAMES;var init_use_spinner=__esm(()=>{init_react_production();init_animation_clock();init_spinner_verbs();init_store();FRAMES=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]});function StatusVerb({now,busy,cancelling,compacting=!1,turnStartedAt,toolRound=0,hasBashActivity=!1,awaitingInput=!1,retryNotice=null}){let spinner=useSpinner(busy&&!awaitingInput),verb=useSpinnerVerb(turnStartedAt==null?null:`${turnStartedAt}:${toolRound}`);if(!busy||hasBashActivity||awaitingInput)return null;if(cancelling)return $jsxs(Box_default,{marginTop:1,children:[$jsx(Box_default,{width:2,flexShrink:0,children:$jsx(Text,{color:"yellow",children:spinner})}),$jsx(Text,{color:"yellow",children:"Interrupting…"})]});if(retryNotice){let{attempt,maxRetries,delayMs,status}=retryNotice,seconds=Math.max(1,Math.ceil((delayMs??0)/1000)),reason=status===429?"rate limited":status!=null?`HTTP ${status}`:"connection lost";return $jsxs(Box_default,{marginTop:1,children:[$jsx(Box_default,{width:2,flexShrink:0,children:$jsx(Text,{color:"yellow",children:spinner})}),$jsxs(Text,{color:"yellow",children:["Reconnecting… ",attempt,"/",maxRetries," ",$jsxs(Text,{dimColor:!0,children:["(",reason," · retrying in ",seconds,"s · esc to interrupt)"]})]})]})}let elapsed=turnStartedAt==null?0:Math.max(0,Math.floor((now-turnStartedAt)/1000)),timing=elapsed>0?`${elapsed}s · `:"";return $jsxs(Box_default,{marginTop:1,children:[$jsx(Box_default,{width:2,flexShrink:0,children:$jsx(Text,{color:"cyan",children:spinner})}),$jsxs(Text,{color:"cyan",children:[compacting?"Compacting context":verb,"… ",$jsxs(Text,{dimColor:!0,children:["(",timing,"esc to interrupt)"]})]})]})}var init_StatusVerb=__esm(async()=>{init_use_spinner();init_react_jsx_runtime_production();await init_build4()});function normalizePastedText(text){return[...String(text??"").replace(ANSI_REGEX,"").replace(/\r\n/g,`
2301
- `).replace(/\r/g,`
2302
- `).replace(/\t/g," ")].filter((ch)=>ch===`
2303
- `||ch.codePointAt(0)>=32&&ch!=="").join("")}function countPastedLines(text){return(String(text??"").match(/\n/g)??[]).length}function shouldCollapsePaste(text,{maxLines=PASTE_MAX_LINES,maxChars=PASTE_MAX_CHARS}={}){let value=String(text??"");return countPastedLines(value)>maxLines||value.length>maxChars}function formatPasteMarker(id,text){let lines=countPastedLines(text);if(lines>0)return`[Pasted text #${id} +${lines} lines]`;return`[Pasted text #${id} ${String(text??"").length} chars]`}function toPasteMap(pastes){if(pastes instanceof Map)return pastes;let map=new Map;for(let[id,text]of Object.entries(pastes??{}))map.set(Number(id),text);return map}function findPasteMarkers(text,pastes){let source=String(text??""),registry=toPasteMap(pastes);if(registry.size===0||!source.includes("[Pasted text #"))return[];let raw=[];for(let match of source.matchAll(PASTE_MARKER_REGEX)){let id=Number(match[1]);if(!registry.has(id))continue;raw.push({id,text:match[0],index:match.index,length:match[0].length})}if(raw.length===0)return[];let points=[...source],unitToPoint=new Map,unit=0;return points.forEach((ch,pointIndex)=>{unitToPoint.set(unit,pointIndex),unit+=ch.length}),unitToPoint.set(unit,points.length),raw.map((marker)=>({...marker,start:unitToPoint.get(marker.index),end:unitToPoint.get(marker.index+marker.length)}))}function expandPasteMarkers(text,pastes){let source=String(text??""),registry=toPasteMap(pastes),markers=findPasteMarkers(source,registry),result=source;for(let i=markers.length-1;i>=0;i--){let marker=markers[i];result=result.slice(0,marker.index)+registry.get(marker.id)+result.slice(marker.index+marker.length)}return result}function pruneOrphanPastes(text,pastes){let registry=toPasteMap(pastes);if(registry.size===0)return registry;let alive=new Set(findPasteMarkers(text,registry).map((marker)=>marker.id));if(alive.size===registry.size)return registry;let next=new Map;for(let[id,content]of registry)if(alive.has(id))next.set(id,content);return next}function insertTextAtCursor(chars,cursor,text){let at=Math.max(0,Math.min(chars.length,cursor)),inserted=[...String(text??"")];return{chars:[...chars.slice(0,at),...inserted,...chars.slice(at)],cursor:at+inserted.length}}function insertPastedText({chars,cursor,pastes,nextId,text,options}){let clean=normalizePastedText(text);if(!clean)return null;let registry=toPasteMap(pastes),at=Math.max(0,Math.min(chars.length,cursor)),collapsed=shouldCollapsePaste(clean,options),inserted=collapsed?[...formatPasteMarker(nextId,clean)]:[...clean],nextPastes=collapsed?new Map(registry).set(nextId,clean):registry;return{chars:[...chars.slice(0,at),...inserted,...chars.slice(at)],cursor:at+inserted.length,pastes:nextPastes,id:collapsed?nextId:null}}function stepCursor(chars,cursor,delta,pastes){let target=cursor+delta,clamped=Math.max(0,Math.min(chars.length,target)),marker=findPasteMarkers(chars.join(""),pastes).find((item)=>clamped>item.start&&clamped<item.end);if(!marker)return clamped;return delta<0?marker.start:marker.end}function deleteBeforeCursor(chars,cursor,pastes){if(cursor<=0)return null;let marker=findPasteMarkers(chars.join(""),pastes).find((item)=>item.end===cursor),from=marker?marker.start:cursor-1;return{chars:[...chars.slice(0,from),...chars.slice(cursor)],cursor:from}}function deleteAfterCursor(chars,cursor,pastes){if(cursor>=chars.length)return null;let marker=findPasteMarkers(chars.join(""),pastes).find((item)=>item.start===cursor),to=marker?marker.end:cursor+1;return{chars:[...chars.slice(0,cursor),...chars.slice(to)],cursor}}function segmentInput(chars,cursor,pastes){let clampedCursor=Math.max(0,Math.min(chars.length,cursor)),markers=findPasteMarkers(chars.join(""),pastes),cursorMarker=markers.find((item)=>clampedCursor>=item.start&&clampedCursor<item.end),cursorStart=cursorMarker?cursorMarker.start:clampedCursor,cursorEnd=cursorMarker?cursorMarker.end:clampedCursor+1,bounds=new Set([0,chars.length,cursorStart,Math.min(cursorEnd,chars.length)]);for(let marker of markers)bounds.add(marker.start),bounds.add(marker.end);let points=[...bounds].filter((n)=>n>=0&&n<=chars.length).sort((a,b)=>a-b),segments=[];for(let i=0;i<points.length-1;i++){let from=points[i],to=points[i+1];if(to<=from)continue;segments.push({text:chars.slice(from,to).join(""),marker:markers.some((marker)=>from>=marker.start&&to<=marker.end),cursor:from>=cursorStart&&to<=cursorEnd})}if(cursorStart>=chars.length)segments.push({text:" ",marker:!1,cursor:!0});return segments}function cursorColumn(segments){return stringWidth2(cursorText(segments))}function cursorText(segments){let text="";for(let segment of segments){if(segment.cursor){if(segment.marker)text+=segment.text;break}text+=segment.text}return text}var PASTE_MAX_CHARS=800,PASTE_MAX_LINES=0,MARKER_SOURCE,PASTE_MARKER_REGEX,PASTE_MARKER_SINGLE,ANSI_REGEX;var init_paste_block=__esm(()=>{init_markdown_width();MARKER_SOURCE=String.raw`\[Pasted text #(\d+)(?: \+(\d+) lines| (\d+) chars)?\]`,PASTE_MARKER_REGEX=new RegExp(MARKER_SOURCE,"g"),PASTE_MARKER_SINGLE=new RegExp(`^${MARKER_SOURCE}$`),ANSI_REGEX=/[\u001B\u009B][[\]()#;?]*(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~])/g});function writeCursorShape(stream,sequence){if(!stream?.isTTY||typeof stream.write!=="function")return;stream.write(sequence)}var STEADY_BAR_CURSOR="\x1B[6 q",DEFAULT_CURSOR="\x1B[0 q";function useInputCursor(ref,column,{truncate=!1,text=null,fullText=null}={}){let{setCursorPosition}=use_cursor_default(),{stdout}=useStdout(),[origin,setOrigin]=$useState(null);$useLayoutEffect(()=>{let node=ref.current,measured=node?.yogaNode?measure_element_default(node):null;setOrigin((current)=>{if(!measured)return current===null?current:null;if(current&&current.x===measured.x&&current.y===measured.y&&current.width===measured.width)return current;return{x:measured.x,y:measured.y,width:measured.width}})});let pinned=Boolean(origin&&column!=null);useStore2((state)=>pinned?state.animationTick:0),$useEffect(()=>{if(!pinned)return;return writeCursorShape(stdout,STEADY_BAR_CURSOR),()=>writeCursorShape(stdout,DEFAULT_CURSOR)},[pinned,stdout]),setCursorPosition(pinned?caretPosition(origin,column,{truncate,text,fullText}):void 0)}function caretPosition({x,y,width},column,{truncate=!1,text=null,fullText=null}={}){if(!(width>0))return{x:x+column,y};if(truncate)return{x:x+Math.min(column,width),y};if(typeof text==="string"&&typeof fullText==="string"&&fullText.startsWith(text)){let position=wordWrappedCaretPosition({x,y,width},fullText,text.length);if(position)return position}if(typeof text==="string")return wrappedCaretPosition({x,y,width},text);return{x:x+column%width,y:y+Math.floor(column/width)}}function wordWrappedCaretPosition({x,y,width},fullText,offset){let wrapped=wrapAnsi(fullText,width,{trim:!1,hard:!0}),row=0,column=0,j=0,consumeInsertedBreaks=()=>{while(wrapped[j]===`
2243
+ `,markedConfigured=!1,LATEX_EXTENSIONS,ROMAN_VALUES,TABLE_SAFETY_MARGIN=4,TABLE_MIN_COLUMN_WIDTH=3,TABLE_MAX_ROW_LINES=4,ANSI_BOLD_START="\x1B[1m",ANSI_BOLD_END="\x1B[22m",MARKDOWN_SYNTAX_PATTERN;var init_markdown=__esm(()=>{init_source2();init_marked_esm();init_latex();init_markdown_width();LATEX_EXTENSIONS=[{name:"latexBlock",level:"block",start(source){let match=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(source);return match?match.index+(match[0].startsWith(EOL2)?1:0):void 0},tokenizer:tokenizeBlockLatex},{name:"latex",level:"inline",start(source){let indices=[source.indexOf("$"),source.indexOf("\\("),source.indexOf("\\[")].filter((index)=>index>=0);return indices.length>0?Math.min(...indices):void 0},tokenizer:tokenizeInlineLatex}];ROMAN_VALUES=[[1000,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]];MARKDOWN_SYNTAX_PATTERN=/[*_`#>[\]~|\-$\\]/});function autoReviewNote(payload){if(!payload||typeof payload!=="object")return null;if(payload.status==="checking")return"Auto safety review: checking…";if(payload.status==="allowed")return"Auto safety review: approved";if(payload.status==="blocked")return`Auto safety review: blocked · ${(typeof payload.reason==="string"?payload.reason.trim():"")||"no reason given"}`;return"Auto safety review: no decision"}function graphemes(value){let text=String(value??"");return segmenter3?[...segmenter3.segment(text)].map(({segment})=>segment):Array.from(text)}function graphemeWidth(grapheme){if(!grapheme)return 0;if(/\p{Extended_Pictographic}/u.test(grapheme))return 2;let width=0;for(let character of grapheme){let point=character.codePointAt(0);if(point===8205||/\p{Mark}/u.test(character))continue;if(point<32||point>=127&&point<160)continue;width+=point>=4352&&(point<=4447||point===9001||point===9002||point>=11904&&point<=42191&&point!==12351||point>=44032&&point<=55203||point>=63744&&point<=64255||point>=65040&&point<=65049||point>=65072&&point<=65135||point>=65280&&point<=65376||point>=65504&&point<=65510||point>=131072&&point<=262141)?2:1}return width}function displayWidth(value){return graphemes(value).reduce((total,item)=>total+graphemeWidth(item),0)}function takeWidth(value,columns){if(columns<=0)return["",String(value??"")];let used=0,head="",tail="";for(let item of graphemes(value)){let itemWidth=graphemeWidth(item);if(tail||used>0&&used+itemWidth>columns)tail+=item;else if(used===0&&itemWidth>columns)head+="?",used+=1;else head+=item,used+=itemWidth}return[head,tail]}function fit(value,columns){let text=String(value??"");if(displayWidth(text)<=columns)return text;if(columns<=1)return takeWidth("…",columns)[0];return`${takeWidth(text,columns-1)[0]}…`}function lineKind(type){if(["+","add","added","addition","insert"].includes(type))return"add";if(["-","del","delete","deleted","deletion","remove"].includes(type))return"delete";return"context"}function hunkRows(hunk,{showLineNumbers=!0}={}){let startOld=hunk?.oldStart??hunk?.oldLine,startNew=hunk?.newStart??hunk?.newLine,oldLine=showLineNumbers&&startOld!=null?Number(startOld):null,newLine=showLineNumbers&&startNew!=null?Number(startNew):null,rows=[];for(let input of Array.isArray(hunk?.lines)?hunk.lines:[]){if(typeof input==="string"&&input.startsWith("\\ No newline"))continue;let rawType=typeof input==="string"?input[0]:input?.type??input?.kind,kind=lineKind(rawType),content=typeof input==="string"?["+","-"," "].includes(input[0])?input.slice(1):input:String(input?.content??input?.text??""),explicitOld=showLineNumbers&&typeof input==="object"?input?.oldLine??input?.oldLineNumber:void 0,explicitNew=showLineNumbers&&typeof input==="object"?input?.newLine??input?.newLineNumber:void 0,row={kind,content:content.replace(/\t/g," "),oldLine:kind==="add"?null:explicitOld??oldLine,newLine:kind==="delete"?null:explicitNew??newLine};if(rows.push(row),kind!=="add"&&(explicitOld??oldLine)!=null)oldLine=(explicitOld??oldLine)+1;if(kind!=="delete"&&(explicitNew??newLine)!=null)newLine=(explicitNew??newLine)+1}return rows}function logicalRows(diff){let showLineNumbers=diff?.hasLineNumbers!==!1,rows=[];for(let[index,hunk]of(diff?.hunks??[]).entries()){if(index>0)rows.push({kind:"separator",content:"…"});rows.push(...hunkRows(hunk,{showLineNumbers}))}return rows}function gutterWidth(rows){let highest=rows.reduce((value,row)=>Math.max(value,row.oldLine??0,row.newLine??0),1);return String(highest).length}function rowsHaveLineNumbers(rows){return rows.some((row)=>row.oldLine!=null||row.newLine!=null)}function physicalRows(rows,columns){let numbered=rowsHaveLineNumbers(rows),digits=numbered?gutterWidth(rows):0,normalPrefixWidth=numbered?digits*2+4:2,compact=!numbered||columns<normalPrefixWidth+2,prefixWidth=compact?Math.min(2,columns):normalPrefixWidth,contentWidth=Math.max(1,columns-prefixWidth),output=[];for(let row of rows){if(row.kind==="separator"){output.push({...row,prefix:compact?"":" ".repeat(normalPrefixWidth)});continue}let marker=row.kind==="add"?"+":row.kind==="delete"?"-":" ",firstPrefix=compact?`${marker} `.slice(0,prefixWidth):`${row.oldLine==null?"".padStart(digits):String(row.oldLine).padStart(digits)} ${row.newLine==null?"".padStart(digits):String(row.newLine).padStart(digits)} ${marker} `,continuationPrefix=" ".repeat(prefixWidth),remaining=row.content.length>0?row.content:" ",first=!0;do{let[content,rest]=takeWidth(remaining,contentWidth);output.push({...row,prefix:first?firstPrefix:continuationPrefix,content}),remaining=rest,first=!1}while(remaining.length>0)}return output}function operationLabel(operation){if(operation==="create")return"Create";if(operation==="delete")return"Delete";return"Edit"}function diffLineCount(diff,width=80){let columns=Math.max(1,Math.floor(width));return physicalRows(logicalRows(diff),columns).length}function renderDiff(diff,{mode="preview",maxLines,offset=0,width=80,showHeader=!0}={}){let columns=Math.max(1,Math.floor(width)),rows=physicalRows(logicalRows(diff),columns),start=Math.max(0,Math.floor(offset)),limit=maxLines==null?mode==="preview"?DEFAULT_PREVIEW_LINES:1/0:Math.max(0,Math.floor(maxLines)),visible=rows.slice(start,Number.isFinite(limit)?start+limit:void 0),hiddenAfter=Math.max(0,rows.length-start-visible.length),hiddenBefore=Math.min(start,rows.length),stats=`+${diff?.additions??0} -${diff?.deletions??0}`,title=`${operationLabel(diff?.operation)} ${diff?.path||"(unknown file)"} · ${stats}`,out=[];if(showHeader)out.push(style(fit(title,columns),{bold:!0}));if(hiddenBefore>0)out.push(style(fit(`… ${hiddenBefore} earlier lines`,columns),{dim:!0}));for(let row of visible){let color=row.kind==="add"?"green":row.kind==="delete"?"red":void 0;out.push(style(fit(`${row.prefix}${row.content}`,columns),{color,dim:row.kind==="separator"}))}if(hiddenAfter>0)out.push(style(fit(`… +${hiddenAfter} lines`,columns),{dim:!0}));return out}var DEFAULT_PREVIEW_LINES=10,segmenter3;var init_diff2=__esm(()=>{init_layout();segmenter3=typeof Intl.Segmenter==="function"?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null});import process16 from"node:process";function topGap(block){return block.head||block.gap?[""]:[]}function toolDot(status){if(status==="completed")return style(BLACK_CIRCLE,{color:"green"});if(status==="failed"||status==="cancelled")return style(BLACK_CIRCLE,{color:"red"});return dim(BLACK_CIRCLE)}function subRow(prefix,text,width,textStyle={dim:!0}){return dim(prefix)+style(truncate4(text,Math.max(1,width-5)),textStyle)}function renderSubagent(block,width){let{label,status,elapsed,subagent}=block.tool,display=subagentDisplay(subagent),running=status!=="completed"&&status!=="failed"&&status!=="cancelled",statsParts=[];if(display.toolCount>0)statsParts.push(`${display.toolCount} tool ${display.toolCount===1?"use":"uses"}`);let tokens=formatTokens(display.tokens);if(tokens)statsParts.push(`${tokens} tokens`);let duration=elapsed==null?null:formatDuration(elapsed);if(duration)statsParts.push(duration);let stats=statsParts.join(" · "),out=block.head?[""]:[],title=style(label.name,{bold:!0,color:"magenta"})+(label.args?`(${label.args})`:"");out.push(padEnd(toolDot(status),2)+truncate4(title,Math.max(1,width-2)));let rows=[...display.rows];if(display.moreTools>0)rows.push(`+${display.moreTools} more tool uses`);if(!running&&display.textLine)rows.push(display.textLine);if(running)rows.push(`Running…${stats?` (${stats})`:""}`);else{let verdict=status==="completed"?"Done":status==="cancelled"?"Cancelled":"Failed";rows.push(`${verdict}${stats?` (${stats})`:""}`)}return rows.forEach((row,index)=>out.push(subRow(index===0?TREE_LAST_PREFIX:TREE_BLANK_PREFIX,String(row),width))),out}function wrapCommandRows(command,{firstWidth,width}){let rows=[];for(let logicalLine of String(command).split(`
2244
+ `)){let wrapped=wrapVisualRows(logicalLine,width,{firstWidth:rows.length===0?firstWidth:width});rows.push(wrapped[0]??"");for(let row of wrapped.slice(1))rows.push(row.replace(/^ +/,""))}return rows}function renderTool(block,{width,reviewHint=!1}){let columns=width,{label,group,status,elapsed,hint,preview,command,diff,autoReview}=block.tool,name=group?group.name:label.name,elapsedText=elapsed!=null?formatDuration(elapsed):null,elapsedReserve=elapsedText?stringWidth2(` (${elapsedText})`):0,hintReserve=reviewHint?stringWidth2(" · ctrl+o to review"):0,commandRows=command&&!group?wrapCommandRows(command,{width:Math.max(1,columns-5-elapsedReserve),firstWidth:Math.max(1,columns-2-stringWidth2(name)-1-elapsedReserve-hintReserve)}):[],showCommand=commandRows.length>1,bodyCommandRows=showCommand?commandRows.slice(1,COMMAND_PREVIEW_ROWS):[],hiddenCommandRows=showCommand?Math.max(0,commandRows.length-COMMAND_PREVIEW_ROWS):0,args=group||showCommand?null:label.args,showDiff=diff!=null&&(diff.complete===!0||TERMINAL_STATUSES.has(status)),allChildItems=group?.items??[],childItems=allChildItems.length>4?[...allChildItems.slice(0,3),allChildItems.at(-1)]:allChildItems,hiddenItems=Math.max(0,(group?.items?.length??0)-childItems.length),title=style(name,{bold:!0});if(args)title+=`(${args})`;if(showCommand)title+=` ${commandRows[0]}`;if(group?.summary)title+=dim(` · ${group.summary}`);if(showDiff)title+=dim(" · ")+style(`+${diff.additions??0}`,{color:"green"})+" "+style(`-${diff.deletions??0}`,{color:"red"});if(!showCommand&&elapsedText)title+=dim(` (${elapsedText})`);if(reviewHint)title+=dim(" · ctrl+o to review");let out=block.head?[""]:[];if(out.push(padEnd(toolDot(status),2)+truncate4(title,Math.max(1,columns-2))),childItems.forEach((item,index)=>{let prefix=index===childItems.length-1&&hiddenItems===0?TREE_LAST_PREFIX:TREE_MID_PREFIX;out.push(subRow(prefix,`${item.label?.name??"Tool"}${item.label?.args?`(${item.label.args})`:""}`,columns))}),hiddenItems>0)out.push(dim(TREE_LAST_PREFIX)+dim(`+${hiddenItems} more calls`));if(showCommand){if(bodyCommandRows.forEach((row,index)=>{let last=index===bodyCommandRows.length-1&&hiddenCommandRows===0&&elapsedText,text=(row.length>0?row:" ")+(last?dim(` (${elapsedText})`):"");out.push(dim(TREE_VERTICAL_PREFIX)+truncate4(text,Math.max(1,columns-5)))}),hiddenCommandRows>0)out.push(dim(TREE_VERTICAL_PREFIX)+dim(`… +${hiddenCommandRows} lines${elapsedText?` (${elapsedText})`:""}`))}if(hint)out.push(subRow(TREE_LAST_PREFIX,hint,columns));if(autoReview){let blocked=autoReview.status==="blocked",noteStyle={dim:!blocked,color:blocked?"red":autoReview.status==="checking"?"yellow":void 0},note=autoReviewNote(autoReview);if(blocked)out.push(...hang(dim(TREE_LAST_PREFIX),5,wrap(note,Math.max(1,columns-5)).map((line)=>style(line,noteStyle))));else out.push(subRow(TREE_LAST_PREFIX,note,columns,noteStyle))}if(showDiff)out.push(...indent(renderDiff(diff,{mode:"preview",maxLines:8,width:Math.max(1,columns-5),showHeader:!1}),5));if(diff&&!showDiff)out.push(subRow(TREE_LAST_PREFIX,`Editing${diff.path?` ${diff.path}`:""}…`,columns));if(!diff&&preview?.lines?.length>0){if(preview.lines.forEach((line,index)=>{out.push(subRow(index===0&&!hint?TREE_LAST_PREFIX:TREE_BLANK_PREFIX,line.length>0?line:" ",columns))}),preview.more>0)out.push(dim(TREE_BLANK_PREFIX)+dim(`… +${preview.more} lines`))}return out}function planRowStyle(status){if(status==="completed")return{box:"☒",style:{dim:!0,strikethrough:!0}};if(status==="in_progress")return{box:"☐",style:{bold:!0,color:"cyan"}};return{box:"☐",style:{}}}function renderPlan(block,width){let entries=Array.isArray(block.plan?.entries)?block.plan.entries:[],visible=entries.slice(0,PLAN_MAX_ROWS),omitted=entries.length-visible.length,out=block.head?[""]:[];if(out.push(padEnd(style(BLACK_CIRCLE,{color:"green"}),2)+style("Update Todos",{bold:!0})),visible.forEach((entry,index)=>{let props=planRowStyle(entry?.status),text=truncate4(`${props.box} ${entry?.content??""}`,Math.max(1,width-5));out.push(dim(index===0?TREE_LAST_PREFIX:TREE_BLANK_PREFIX)+style(text,props.style))}),omitted>0)out.push(dim(TREE_BLANK_PREFIX)+dim(`… +${omitted} more`));return out}function renderProposedPlan(block,width){let inner=Math.max(1,width-4),content=[style(`${BLACK_CIRCLE} Approved Plan`,{bold:!0,color:"cyan"}),...wrap(renderMarkdown(block.text),inner)];if(block.planPath)content.push(...wrap(dim(`Saved at ${block.planPath}`),inner));return[...block.head?[""]:[],...border(content,width,{style:"single",color:"cyan",paddingX:1})]}function renderBashCard(card,width){let{command,lines,status}=card,outcome=card.outcome??(card.timedOut?{type:"timed_out"}:card.interrupted?{type:"cancelled"}:card.exitCode!=null?{type:"exited",code:card.exitCode}:Object.hasOwn(card,"exitCode")?{type:"spawn_failed"}:null),running=status==="running",finalized=card.hidden!=null,{visible,hidden}=finalized?{visible:lines,hidden:card.hidden}:previewBashLines(lines,!1,DYNAMIC_BASH_PREVIEW_LINES),statusParts=[];if(!running){if(hidden>0)statusParts.push({text:finalized?`... ${hidden} more lines`:`... ${hidden} more lines (ctrl+o to review)`});if(outcome?.type==="timed_out")statusParts.push({color:"red",text:"(timed out)"});else if(outcome?.type==="cancelled")statusParts.push({color:"yellow",text:"(cancelled)"});else if(outcome?.type==="signaled")statusParts.push({color:"red",text:`(signal ${outcome.signal})`});else if(outcome?.type==="exited"&&outcome.code!==0)statusParts.push({color:"red",text:`(exit ${outcome.code})`});else if(outcome?.type==="spawn_failed")statusParts.push({color:"red",text:"(failed to start)"})}let inner=Math.max(1,width-2),content=[...wrap(style(`$ ${command}`,{bold:!0,color:"magenta"}),inner)];if(running)content.push(dim("Running… (esc to cancel)"));else for(let line of visible)for(let row of wrap(line.text.length>0?line.text:" ",inner))content.push(style(row,{dim:!0,color:line.err?"yellow":void 0}));if(statusParts.length>0)content.push(""),content.push(statusParts.map((part,index)=>style(`${index>0?" ":""}${part.text}`,{dim:!0,color:part.color})).join(""));return["",...border(content,width,{style:"single",color:"magenta",sides:{left:!1,right:!1},paddingX:1})]}function renderBanner(width){let{modelConfig,providerName}=useStore.getState(),details=[modelConfig?currentModelName(modelConfig):null,providerName].filter(Boolean).join(" · "),logo=MIRO_LOGO_ROWS.map((row)=>row.map(([glyphs,color])=>style(glyphs,{color})).join("")),stacked=width<40,infoWidth=Math.max(1,stacked?width-2:width-2-LOGO_WIDTH-2),info=[truncate4(`${style("Miro",{bold:!0})} ${dim(`v${APP_VERSION}`)}`,infoWidth),...details?[dim(truncate4(details,infoWidth))]:[],dim(truncateStart(process16.cwd(),infoWidth))],body=stacked?[...logo,"",...info]:Array.from({length:Math.max(logo.length,info.length)},(_,index)=>padEnd(logo[index]??"",LOGO_WIDTH)+" "+(info[index]??""));return["",...indent(body,1),""]}function renderThought(block,width){if(block.thought.displayMode==="hidden")return[];let body=splitThinkingText(block.thought.text).body,showBody=block.thought.displayMode==="full"&&body.length>0,detailsMissing=block.thought.hasContent&&!block.thought.text,out=topGap(block);if(out.push(padEnd(style("∴",{color:"cyan"}),2)+dim(truncate4(`${block.text}${detailsMissing?" · details not retained":""}`,Math.max(1,width-2)))),showBody)out.push(""),out.push(...indent(wrap(renderMarkdown(body),Math.max(1,width-2)).map(dim),2));return out}function renderUser(block,width){let rows=wrap(block.text.length>0?block.text:" ",Math.max(1,width-2));return[...topGap(block),...rows.map((row)=>style("│",{color:"gray"})+" "+style(row,{bold:!0}))]}function renderBlock(block,options){let{width}=options;if(block.role==="banner")return renderBanner(width);if(block.role==="bashCard"&&block.card)return renderBashCard(block.card,width);if(block.role==="tool"&&block.tool){let tool=toolForDisplay(block.tool);if(!tool)return[];let visibleBlock=tool===block.tool?block:{...block,tool};if(tool.subagent)return renderSubagent(visibleBlock,width);return renderTool(visibleBlock,options)}if(block.role==="plan"&&block.plan)return renderPlan(block,width);if(block.role==="proposedPlan")return renderProposedPlan(block,width);if(block.role==="thought"&&block.thought)return renderThought(block,width);if(block.role==="user")return renderUser(block,width);let roleStyle=ROLE_STYLES[block.role]??ROLE_STYLES.system,text=block.role==="assistant"&&block.text.length>0?renderMarkdown(block.text):block.text,rows=wrap(text.length>0?text:" ",Math.max(1,width-2)).map((row)=>roleStyle.dim?dim(row):row),marker=block.head?style(roleStyle.marker,{color:roleStyle.markerColor}):" ";return[...topGap(block),...hang(marker,2,rows)]}var ROLE_STYLES,LOGO_WIDTH;var init_blocks=__esm(()=>{init_config();init_figures();init_markdown();init_markdown_width();init_bash();init_subagent();init_thinking();init_tool_title();init_store();init_layout();init_diff2();ROLE_STYLES={user:{marker:">",markerColor:"gray",dim:!0},assistant:{marker:BLACK_CIRCLE,markerColor:"green"},system:{marker:"✻",markerColor:"cyan",dim:!0},thought:{marker:"∴",markerColor:"cyan",dim:!0},tool:{marker:BLACK_CIRCLE,markerColor:"yellow",dim:!0},toolUpdate:{marker:TREE_LAST,markerColor:"gray",dim:!0},bashInput:{marker:"!",markerColor:"magenta"},bashOutput:{marker:TREE_LAST,markerColor:"gray",dim:!0},stderr:{marker:"⚠",markerColor:"yellow",dim:!0},error:{marker:"✗",markerColor:"red"}};LOGO_WIDTH=Math.max(...MIRO_LOGO.split(`
2245
+ `).map(stringWidth2))});function spinnerFrame(){return FRAMES[useStore.getState().animationTick%FRAMES.length]}function spinnerVerb(key){if(key!==verbKey||!verb)verbKey=key,verb=sampleSpinnerVerb();return verb}function tokenHint(tokens){let input=formatTokens2(tokens?.input),output=formatTokens2(tokens?.output),parts=[input==null?null:`↑${input}`,output==null?null:`↓${output}`].filter(Boolean);return parts.length>0?parts.join(" "):null}function activeToolItem(tool,now){return{label:tool.label,kind:tool.raw?.kind??tool.kind??null,status:tool.status,elapsed:tool.startedAt!=null?Math.max(0,now-tool.startedAt):null,preview:tool.preview??null,command:tool.command??null,subagent:tool.subagent??null,detail:tool.detail??null,diff:tool.diff??null,hint:tool.hint??null,autoReview:tool.autoReview??null}}function isBashTool(tool){return tool.raw?.kind==="execute"||tool.kind==="execute"||tool.label?.name==="Bash"}function renderActivitySlot({now,width,awaitingInput}){let state=useStore.getState(),{busy,cancelling,thought,thinkingDisplay,tokens,bashCard}=state,{activeTools,pendingToolGroup}=state;if(bashCard||cancelling||awaitingInput)return[];if(!busy&&activeTools.length===0&&!pendingToolGroup&&!thought)return[];if(activeTools=activeTools.filter(isVisibleTool),pendingToolGroup){let items=pendingToolGroup.items.filter(isVisibleTool);pendingToolGroup=items.length>0?{...pendingToolGroup,items}:null}let bashTools=activeTools.filter(isBashTool),subagentTools=activeTools.filter((tool)=>!isBashTool(tool)&&tool.subagent),foldableTools=activeTools.filter((tool)=>!isBashTool(tool)&&!tool.subagent),toolBlock=(tool,extra={})=>renderBlock({role:"tool",head:!0,tool:activeToolItem(tool,now)},{width,...extra}),liveExtras=[...subagentTools,...bashTools].flatMap((tool)=>toolBlock(tool));if(pendingToolGroup&&(!thought||foldableTools.length>0)||foldableTools.length>1){let groupedItems=[...pendingToolGroup?.items??[],...foldableTools.map((tool)=>activeToolItem(tool,now))],startedAt=pendingToolGroup?.startedAt??foldableTools.reduce((earliest,tool)=>tool.startedAt==null?earliest:Math.min(earliest,tool.startedAt),now),liveGroup={...pendingToolGroup??{},items:groupedItems,hint:pendingToolGroup?.hint??foldableTools.find((tool)=>tool.hint)?.hint??null,startedAt,finishedAt:now};return[...groupedItems.length>0?renderBlock({role:"tool",head:!0,tool:toolFromGroup(liveGroup,{live:busy,now})},{width,reviewHint:Boolean(pendingToolGroup)}):[],...liveExtras]}if(subagentTools.length>0){let active=foldableTools.at(-1);return[...active?toolBlock(active):[],...liveExtras]}let active=activeTools.at(-1);if(active)return toolBlock(active);if(!thought)return[];let parsed=splitThinkingText(thought.text),hasText=Boolean(parsed.body.trim()),previewLines=hasText&&thought.expanded?thinkingPreview(thought.text,Math.max(1,width-2),THOUGHT_PREVIEW_LINES):null,elapsed=formatDuration(thinkingElapsed(thought,now)),bucket=thoughtStatBucket(state.animationTick,THOUGHT_STAT_SAMPLE_TICKS);thoughtStat=sampleThoughtTokens(thoughtStat,thought.text,bucket);let liveOutput=formatTokens2(thoughtStat.tokens),io=liveOutput!=null?`↓${liveOutput}`:tokenHint(tokens),title=thinkingDisplay==="hidden"&&!thought.expanded?null:thought.title??parsed.title,statusParts=[elapsed,io].filter(Boolean),label=title?`Thinking: ${[title,...statusParts].join(" · ")}`:statusParts.length>0?`Thinking… (${statusParts.join(" · ")})`:"Thinking…",out=["",padEnd(style("∴",{color:"cyan"}),2)+dim(truncate4(label+(hasText?" · ctrl+o to review":""),Math.max(1,width-2)))];if(previewLines){out.push("");let rows=previewLines.slice(0,THOUGHT_PREVIEW_LINES);while(rows.length<THOUGHT_PREVIEW_LINES)rows.push("");out.push(...indent(rows.map((row)=>dim(truncate4(row,Math.max(1,width-2)))),2))}return out}function renderStatusVerb({now,width,awaitingInput}){let{busy,cancelling,compacting,turnStartedAt,toolRound,bashCard,retryNotice}=useStore.getState();if(!busy||bashCard||awaitingInput)return[];let spinner=spinnerFrame(),currentVerb=spinnerVerb(turnStartedAt==null?null:`${turnStartedAt}:${toolRound}`),row=(spin,text)=>["",padEnd(spin,2)+truncate4(text,Math.max(1,width-2))];if(cancelling)return row(style(spinner,{color:"yellow"}),style("Interrupting…",{color:"yellow"}));if(retryNotice){let{attempt,maxRetries,delayMs,status}=retryNotice,seconds=Math.max(1,Math.ceil((delayMs??0)/1000)),reason=status===429?"rate limited":status!=null?`HTTP ${status}`:"connection lost";return row(style(spinner,{color:"yellow"}),style(`Reconnecting… ${attempt}/${maxRetries} `,{color:"yellow"})+style(`(${reason} · retrying in ${seconds}s · esc to interrupt)`,{color:"yellow",dim:!0}))}let elapsed=turnStartedAt==null?0:Math.max(0,Math.floor((now-turnStartedAt)/1000)),timing=elapsed>0?`${elapsed}s · `:"";return row(style(spinner,{color:"cyan"}),style(`${compacting?"Compacting context":currentVerb}… `,{color:"cyan"})+style(`(${timing}esc to interrupt)`,{color:"cyan",dim:!0}))}function renderStatusBar(input){let{status,connectionStage,busy,cancelling,switching,goal}=useStore.getState(),inner=Math.max(1,input.width-2),line=(text)=>[" "+truncate4(text,inner)],connecting=status==="connecting";if(input.exitConfirming)return line(style("Press Ctrl+C again to exit",{color:"yellow"}));if(switching)return line(style(`${spinnerFrame()} ${switching}`,{color:"cyan"}));if(connecting)return line(style(`${spinnerFrame()} ${connectionStage??`Connecting to ${input.agentBin} ACP…`}`,{color:"cyan"}));if(status==="failed")return line(style("Disconnected · restart miro to retry · Ctrl+C twice to exit",{color:"red"}));if(cancelling)return line(style("Interrupting…",{color:"yellow"}));if(input.hidden)return[];if(input.statusLineItems?.length===0)return[];if(input.inputHint)return line(dim(input.inputHint));let{segments}=buildStatusLineSegments(input.statusLineItems??DEFAULT_STATUS_LINE_ITEMS,input.statusLineSnapshot??{},{useColors:input.statusLineUseColors});if(segments.length===0)return[];let left=segments.map((segment,index)=>(index>0?dim(STATUS_LINE_SEPARATOR):"")+style(segment.text,{color:busy||segment.color==null?void 0:segment.color,dim:busy||segment.dim})).join(""),indicator=goalIndicator(goal,{useColors:input.statusLineUseColors}),right=indicator?style(indicator.text,{color:indicator.color,dim:indicator.dim}):"";return[" "+spread2(left,right,inner)]}function resetActivityCaches(){thoughtStat=null,verbKey=void 0}var FRAMES,verbKey,verb="",thoughtStat=null;var init_activity=__esm(()=>{init_config();init_settings_file();init_goal_indicator();init_items7();init_render();init_spinner_verbs();init_store();init_thinking();init_layout();init_blocks();FRAMES=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"]});function pickerDensity(rows){let height=Number.isFinite(rows)&&rows>0?Math.floor(rows):24;if(height<9)return"minimal";if(height<16)return"compact";return"full"}function pickerViewport({index,total,rows,reservedRows,maxVisible=10,minVisible=1}){let count=Math.max(0,Math.floor(total));if(count===0)return{index:0,size:0,start:0,end:0,above:0,below:0};let height=Number.isFinite(rows)&&rows>0?Math.floor(rows):24,selected=Math.max(0,Math.min(Math.floor(index),count-1)),budget=Math.max(minVisible,height-Math.max(0,reservedRows)),size=Math.min(count,Math.max(1,Math.min(maxVisible,budget))),start=count<=size?0:Math.max(0,Math.min(selected-Math.floor(size/2),count-size)),end=start+size;return{index:selected,size,start,end,above:start,below:Math.max(0,count-end)}}function normalizeItem(item,index){let raw=item??{},value=raw.value,label=raw.label??raw.name??(value==null?"":String(value));return{key:value==null?`row-${index}`:`${index}:${value}`,value,label:String(label),description:raw.description==null?"":String(raw.description),groupName:raw.groupName==null?"":String(raw.groupName),right:raw.right==null?"":String(raw.right),current:Boolean(raw.current),disabled:Boolean(raw.disabled),disabledReason:raw.disabledReason==null?"":String(raw.disabledReason),source:raw}}function normalizeItems(items){return(Array.isArray(items)?items:[]).map(normalizeItem)}function firstSelectableIndex(rows){let index=rows.findIndex((row)=>!row.disabled);return index===-1?0:index}function initialIndex(rows,selected){if(rows.length===0)return 0;if(Number.isInteger(selected)&&selected>=0&&selected<rows.length&&!rows[selected].disabled)return selected;let current=rows.findIndex((row)=>row.current&&!row.disabled);if(current!==-1)return current;return firstSelectableIndex(rows)}function moveIndex(rows,index,delta){let total=rows.length;if(total===0)return 0;if(!rows.some((row)=>!row.disabled))return index;let step=delta<0?-1:1,cursor=index;for(let hop=0;hop<total;hop+=1)if(cursor=(cursor+step+total)%total,!rows[cursor].disabled)return cursor;return index}function truncateToCellWidth(text,width){let source=String(text??""),limit=Math.max(0,Math.floor(width));if(stringWidth2(source)<=limit)return source;if(limit===0)return"";if(limit===1)return"…";let output="";for(let character of source){if(stringWidth2(output+character)>limit-1)break;output+=character}return`${output}…`}function pathCells(text,width,fromEnd=!1){let parts=Array.from(pathGraphemes.segment(text),(part)=>part.segment);if(fromEnd)parts.reverse();let kept=[],used=0;for(let part of parts){let cells=stringWidth2(part);if(used+cells>width)break;kept.push(part),used+=cells}return(fromEnd?kept.reverse():kept).join("")}function truncatePathToCellWidth(text,width){let source=String(text??"").replace(/[\u0000-\u001f\u007f-\u009f]/g,(char)=>({"\n":"\\n","\r":"\\r","\t":"\\t"})[char]??"�"),limit=Math.max(0,Math.floor(width));if(stringWidth2(source)<=limit)return source;if(limit===0)return"";if(limit===1)return"…";let slash=source.lastIndexOf("/",source.endsWith("/")?source.length-2:source.length-1),basename=source.slice(slash+1);if(slash>=0){let suffix=source.slice(slash);if(stringWidth2(suffix)<limit)return`${pathCells(source.slice(0,slash),limit-1-stringWidth2(suffix))}…${suffix}`;if(stringWidth2(basename)<limit)return`…${basename}`}let suffix=pathCells(basename,Math.floor((limit-1)/2),!0);return`${pathCells(basename,limit-1-stringWidth2(suffix))}…${suffix}`}function splitRowWidth(innerWidth,prefixWidth,rightText){let contentWidth=Math.max(0,innerWidth-prefixWidth),value=String(rightText??""),showRight=Boolean(value)&&contentWidth>=8,rightWidth=showRight?Math.min(stringWidth2(value),Math.max(3,Math.floor(contentWidth/2))):0,leftWidth=Math.max(0,contentWidth-rightWidth-(showRight?1:0));return{showRight,leftWidth,rightWidth,contentWidth}}function compactRowWidth(innerWidth,prefixWidth,labelText){let contentWidth=Math.max(0,innerWidth-prefixWidth),leftWidth=Math.min(stringWidth2(labelText),Math.max(0,contentWidth-1)),rightWidth=Math.max(0,contentWidth-leftWidth-1);return{showRight:rightWidth>0,leftWidth,rightWidth,contentWidth}}var pathGraphemes;var init_picker_rows=__esm(()=>{init_markdown_width();pathGraphemes=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function completionViewport({index,total,rows,inputRows=3,surroundingRows=3}){return pickerViewport({index,total,rows,reservedRows:Math.max(3,inputRows)+surroundingRows+2,maxVisible:8})}function completionHint(width,viewport,total){let position=total>viewport.size?`${viewport.index+1}/${total}`:"",budget=width-stringWidth2(position)-(position?2:0),hint=["↑↓ to select · Tab/Enter to complete · Esc to dismiss","↑↓ · Tab/Enter · Esc","Tab · Esc"].find((text)=>stringWidth2(text)<=budget)??"";return truncateToCellWidth([hint,position].filter(Boolean).join(" "),width)}var init_picker_completion=__esm(()=>{init_markdown_width();init_picker_rows()});function pickerQueryState(result,key){if(key==null)return{items:[],pending:!1};if(result?.key===key)return{items:result.items,pending:!1};return{items:[],pending:!0}}function createPickerRequest(key,publish){let cancelled=!1;return{resolve(items){if(!cancelled)publish({key,items})},cancel(){cancelled=!0}}}function wrapString(text,width){if(typeof Bun>"u"||typeof Bun.wrapAnsi!=="function")return null;return Bun.wrapAnsi(text,width,{trim:!1,hard:!0})}function caretPosition({x,y,width},column,{truncate=!1,text=null,fullText=null}={}){if(!(width>0))return{x:x+column,y};if(truncate)return{x:x+Math.min(column,width),y};if(typeof text==="string"&&typeof fullText==="string"&&fullText.startsWith(text)){let position=wordWrappedCaretPosition({x,y,width},fullText,text.length);if(position)return position}if(typeof text==="string")return wrappedCaretPosition({x,y,width},text);return{x:x+column%width,y:y+Math.floor(column/width)}}function wordWrappedCaretPosition({x,y,width},fullText,offset){let wrapped=wrapString(fullText,width);if(wrapped==null)return null;let row=0,column=0,j=0,consumeInsertedBreaks=()=>{while(wrapped[j]===`
2304
2246
  `)row+=1,column=0,j+=1};for(let{segment,index}of graphemeSegmenter.segment(fullText)){if(index>=offset)break;if(segment!==`
2305
2247
  `)consumeInsertedBreaks();if(!wrapped.startsWith(segment,j))return null;if(j+=segment.length,segment===`
2306
2248
  `)row+=1,column=0;else column+=stringWidth2(segment)}if(offset<fullText.length&&fullText[offset]!==`
2307
2249
  `)consumeInsertedBreaks();if(column>=width)row+=Math.floor(column/width),column%=width;return{x:x+column,y:y+row}}function wrappedCaretPosition({x,y,width},text){let column=0,row=0;for(let character of[...text]){if(character===`
2308
- `){row+=1,column=0;continue}let characterWidth=stringWidth2(character);if(characterWidth>0&&column>0&&column+characterWidth>width)row+=1,column=0;if(column+=characterWidth,column>=width)row+=Math.floor(column/width),column%=width}return{x:x+column,y:y+row}}var graphemeSegmenter;var init_use_input_cursor=__esm(async()=>{init_react_production();init_wrap_ansi();init_markdown_width();init_store();await init_build4();graphemeSegmenter=new Intl.Segmenter(void 0,{granularity:"grapheme"})});import{execFile as execFile4}from"node:child_process";import{readdir as readdir2,stat as stat5}from"node:fs/promises";import{homedir as homedir4}from"node:os";import path30 from"node:path";function extractAtToken(text,cursorPos){if(!text)return null;let before=text.substring(0,cursorPos),atIdx=before.lastIndexOf("@");if(atIdx<0)return null;if(atIdx>0&&!/\s/.test(before[atIdx-1]))return null;let fromAt=before.substring(atIdx);if(fromAt.startsWith('@"')){if(!QUOTED_AT_TOKEN_HEAD_RE.test(fromAt))return null;let afterMatch=text.substring(cursorPos).match(QUOTED_PATH_CHAR_HEAD_RE),token=fromAt+(afterMatch?afterMatch[0]:""),quotedPath=token.slice(2,token.endsWith('"')?-1:void 0);return{token,startPos:atIdx,query:quotedPath,quoted:!0}}let headMatch=fromAt.match(AT_TOKEN_HEAD_RE);if(!headMatch||headMatch[0].length!==fromAt.length)return null;let afterMatch=text.substring(cursorPos).match(PATH_CHAR_HEAD_RE),token=headMatch[0]+(afterMatch?afterMatch[0]:"");return{token,startPos:atIdx,query:token.slice(1)}}function fileSuggestionKey(token){return token?`${token.startPos}:${token.token}`:null}function execCommand(command,args,cwd,timeout=SEARCH_TIMEOUT_MS){return new Promise((resolve)=>{execFile4(command,args,{cwd,timeout,maxBuffer:16777216},(error,stdout)=>resolve(error?null:stdout))})}async function listFilesViaGit(cwd){let inRepo=await execCommand("git",["rev-parse","--is-inside-work-tree"],cwd,GIT_TIMEOUT_MS3);if(inRepo===null)return{inRepo:null,files:null};if(inRepo.trim()!=="true")return{inRepo:!1,files:null};let[stdout,ignoredStdout]=await Promise.all([execCommand("git",["-c","core.quotepath=false","ls-files","-z","--cached","--others","--exclude-standard"],cwd,GIT_TIMEOUT_MS3),execCommand("git",["-c","core.quotepath=false","ls-files","-z","--others","--ignored","--directory","--empty-directory","--exclude-standard"],cwd,GIT_TIMEOUT_MS3)]);if(stdout===null)return{inRepo:!0,files:null,dirs:null};let ignoredDirs=new Set((ignoredStdout??"").split("\x00").filter((entry)=>entry.endsWith("/")).map((entry)=>entry.slice(0,-1))),scannedDirs=ignoredStdout===null?null:await listDirectoriesViaScan(cwd,ignoredDirs);return{inRepo:!0,files:stdout.split("\x00").filter(Boolean),dirs:scannedDirs}}async function listFilesViaRipgrep(cwd){let stdout=await execCommand("rg",["--files","--null","--hidden","--glob","!.git","--glob","!.git/**"],cwd);if(stdout===null)return null;return stdout.split("\x00").filter(Boolean)}async function hasGitMetadata(cwd){let current=path30.resolve(cwd);for(;;){try{return await stat5(path30.join(current,".git")),!0}catch{}let parent=path30.dirname(current);if(parent===current)return!1;current=parent}}async function listFilesViaScan(cwd){let files=[],walk=async(dir,depth)=>{if(depth>SCAN_MAX_DEPTH||files.length>=SCAN_MAX_FILES)return;let entries;try{entries=await readdir2(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(files.length>=SCAN_MAX_FILES)return;let full=path30.join(dir,entry.name);if(entry.isDirectory()){if(!SCAN_SKIP_DIRS.has(entry.name))await walk(full,depth+1)}else if(entry.isFile())files.push(path30.relative(cwd,full))}};return await walk(cwd,0),files}function isInsideIgnoredDirectory(candidate,ignoredDirs){let current=candidate;for(;;){if(ignoredDirs.has(current))return!0;let slash=current.lastIndexOf("/");if(slash<0)return!1;current=current.slice(0,slash)}}async function listDirectoriesViaScan(cwd,ignoredDirs=new Set){let dirs=[],walk=async(dir,prefix,depth)=>{if(depth>SCAN_MAX_DEPTH||dirs.length>=SCAN_MAX_DIRS)return;let entries;try{entries=await readdir2(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(dirs.length>=SCAN_MAX_DIRS)return;if(!entry.isDirectory()||SCAN_SKIP_DIRS.has(entry.name))continue;let relative=prefix?`${prefix}/${entry.name}`:entry.name;if(isInsideIgnoredDirectory(relative,ignoredDirs))continue;dirs.push(relative),await walk(path30.join(dir,entry.name),relative,depth+1)}};return await walk(cwd,"",0),dirs}function getDirectoryNames(files){let dirs=new Set;for(let file of files){let dir=path30.dirname(file);while(dir!=="."&&!dirs.has(dir)){let parent=path30.dirname(dir);if(parent===dir)break;dirs.add(dir),dir=parent}}return[...dirs].map((d)=>d+"/")}async function listWorkspacePaths(cwd){let now=Date.now();if(cache2.cwd===cwd&&cache2.promise&&now<cache2.expiresAt)return cache2.promise;let promise=(async()=>{let git=await listFilesViaGit(cwd),files=git.files??await listFilesViaRipgrep(cwd);if(files===null)files=git.inRepo??await hasGitMetadata(cwd)?[]:await listFilesViaScan(cwd);let dirs=new Set(getDirectoryNames(files));for(let dir of git.dirs??[])dirs.add(`${dir}/`);return{files,dirs:[...dirs]}})();return cache2={cwd,expiresAt:now+CACHE_TTL_MS,promise},promise.catch(()=>{if(cache2.promise===promise)cache2={cwd:null,expiresAt:0,promise:null}}),promise}function toSuggestion2(p){let isDirectory=p.endsWith("/");return{path:isDirectory?p.slice(0,-1):p,isDirectory,displayText:p}}function byDirFirst(a,b){let aDir=a.endsWith("/"),bDir=b.endsWith("/");if(aDir!==bDir)return aDir?-1:1;return a.localeCompare(b)}function listIndexedLevel(files,dirs,dirPrefix){return[...dirs,...files].filter((candidate)=>{if(!candidate.startsWith(dirPrefix)||candidate===dirPrefix)return!1;let remainder=candidate.slice(dirPrefix.length),withoutTrailingSlash=remainder.endsWith("/")?remainder.slice(0,-1):remainder;return withoutTrailingSlash!==""&&!withoutTrailingSlash.includes("/")}).sort(byDirFirst)}function matchRank2(candidate,query){let p=candidate.toLowerCase();if(path30.basename(candidate.endsWith("/")?candidate.slice(0,-1):candidate).toLowerCase().startsWith(query))return 0;if(p.startsWith(query))return 1;if(p.includes(query))return 2;return-1}async function generateFileSuggestions(query,opts={}){let cwd=opts.cwd??process.cwd(),limit=opts.limit??1/0;try{let{files,dirs}=await listWorkspacePaths(cwd);if(query===""||query==="."||query==="./")return listIndexedLevel(files,dirs,"").slice(0,limit).map(toSuggestion2);let normalized=query.startsWith("./")?query.slice(2):query;if(normalized.endsWith("/"))return listIndexedLevel(files,dirs,normalized).slice(0,limit).map(toSuggestion2);let q=normalized.toLowerCase();return[...dirs,...files].map((candidate)=>({candidate,rank:matchRank2(candidate,q)})).filter((item)=>item.rank>=0).sort((a,b)=>a.rank-b.rank||a.candidate.length-b.candidate.length||a.candidate.localeCompare(b.candidate)).slice(0,limit).map((item)=>toSuggestion2(item.candidate))}catch{return[]}}function applyFileSuggestion(chars,token,suggestion){let value=chars.join(""),pathText=`${suggestion.path}${suggestion.isDirectory?"/":""}`,quoted=token.quoted||/\s/u.test(pathText),replacement=quoted?`@"${pathText}"${suggestion.isDirectory?"":" "}`:`@${pathText}${suggestion.isDirectory?"":" "}`,before=value.slice(0,token.startPos),after=value.slice(token.startPos+token.token.length),nextChars=[...before+replacement+after],cursorText=quoted&&suggestion.isDirectory?replacement.slice(0,-1):replacement;return{nextChars,nextCursor:[...before+cursorText].length}}function extractPathToken(text,cursorPos){let before=text.substring(0,cursorPos),start=0;for(let i=before.length-1;i>=0;i-=1)if(PATH_DELIMITERS.has(before[i])){start=i+1;break}let token=before.slice(start);if(start===0&&token.startsWith("!"))token=token.slice(1),start+=1;return{token,startPos:start,query:token}}function expandHome(p){if(p==="~")return homedir4();if(p.startsWith("~/"))return path30.join(homedir4(),p.slice(2));return p}async function generatePathSuggestions(prefix,opts={}){let cwd=opts.cwd??process.cwd(),limit=opts.limit??MAX_SUGGESTIONS;try{let expanded=expandHome(prefix),displayDir,searchDir,namePrefix;if(prefix===""||prefix==="~"||prefix.endsWith("/"))displayDir=prefix==="~"?"~/":prefix,searchDir=path30.isAbsolute(expanded)?expanded:path30.join(cwd,expanded),namePrefix="";else{let slashIdx=prefix.lastIndexOf("/");displayDir=slashIdx===-1?"":prefix.slice(0,slashIdx+1),namePrefix=prefix.slice(slashIdx+1).toLowerCase();let dir=expandHome(displayDir===""?".":displayDir);searchDir=path30.isAbsolute(dir)?dir:path30.join(cwd,dir)}let entries=await readdir2(searchDir,{withFileTypes:!0}),matched=[];for(let entry of entries){if(namePrefix&&!entry.name.toLowerCase().startsWith(namePrefix))continue;let isDirectory=entry.isDirectory();if(!isDirectory&&entry.isSymbolicLink())try{isDirectory=(await stat5(path30.join(searchDir,entry.name))).isDirectory()}catch{}matched.push({name:entry.name,isDirectory})}return matched.sort((a,b)=>{if(a.isDirectory!==b.isDirectory)return a.isDirectory?-1:1;return a.name.localeCompare(b.name)}),matched.slice(0,limit).map((entry)=>{let p=displayDir+entry.name;return{path:p,isDirectory:entry.isDirectory,displayText:p+(entry.isDirectory?"/":"")}})}catch{return[]}}function applyPathSuggestion(chars,token,suggestion){let value=chars.join(""),suffix=suggestion.isDirectory?"/":suggestion.isCommand?" ":"",replacement=suggestion.path+suffix,before=value.slice(0,token.startPos),after=value.slice(token.startPos+token.token.length);return{nextChars:[...before+replacement+after],nextCursor:[...before+replacement].length}}function isCommandPosition(text,startPos){let before=text.slice(0,startPos);if(before.startsWith("!"))before=before.slice(1);let trimmed=before.trim();if(trimmed==="")return!0;return/(\|\||&&|[|;&(`])$/.test(trimmed)}function clearCommandNameCache(){commandCache={key:null,expiresAt:0,promise:null}}async function listPathCommands(paths){let key=paths.join(path30.delimiter),now=Date.now();if(commandCache.key===key&&commandCache.promise&&now<commandCache.expiresAt)return commandCache.promise;let promise=(async()=>{let names=new Set;for(let dir of paths){if(!dir)continue;let entries;try{entries=await readdir2(dir,{withFileTypes:!0})}catch{continue}for(let entry of entries)if(entry.isFile()||entry.isSymbolicLink())names.add(entry.name)}return[...names]})();return commandCache={key,expiresAt:now+COMMAND_CACHE_TTL_MS,promise},promise.catch(()=>{if(commandCache.promise===promise)clearCommandNameCache()}),promise}async function generateCommandNameSuggestions(prefix,opts={}){let limit=opts.limit??MAX_SUGGESTIONS,paths=opts.paths??(process.env.PATH??"").split(path30.delimiter);try{let names=await listPathCommands(paths),q=prefix.toLowerCase();return names.filter((name)=>name.toLowerCase().startsWith(q)).sort((a,b)=>a.length-b.length||a.localeCompare(b)).slice(0,limit).map((name)=>({path:name,isDirectory:!1,isCommand:!0,displayText:name}))}catch{return[]}}async function generateBashSuggestions(text,token,opts={}){let{query}=token,looksLikePath=query.includes("/")||query.startsWith(".")||query.startsWith("~");if(query!==""&&!looksLikePath&&isCommandPosition(text,token.startPos)){let commands=await generateCommandNameSuggestions(query,opts);if(commands.length>0)return commands}return generatePathSuggestions(query,opts)}var AT_TOKEN_HEAD_RE,PATH_CHAR_HEAD_RE,QUOTED_AT_TOKEN_HEAD_RE,QUOTED_PATH_CHAR_HEAD_RE,MAX_SUGGESTIONS=15,CACHE_TTL_MS=5000,GIT_TIMEOUT_MS3=2000,SEARCH_TIMEOUT_MS=5000,SCAN_MAX_DEPTH=6,SCAN_MAX_FILES=5000,SCAN_MAX_DIRS=5000,SCAN_SKIP_DIRS,cache2,PATH_DELIMITERS,commandCache,COMMAND_CACHE_TTL_MS=30000;var init_file_suggestions=__esm(()=>{AT_TOKEN_HEAD_RE=/^@[\p{L}\p{N}\p{M}_\-./\\()[\]~:]*/u,PATH_CHAR_HEAD_RE=/^[\p{L}\p{N}\p{M}_\-./\\()[\]~:]+/u,QUOTED_AT_TOKEN_HEAD_RE=/^@"[^"]*$/u,QUOTED_PATH_CHAR_HEAD_RE=/^[^"]*"?/u,SCAN_SKIP_DIRS=new Set([".git","node_modules"]);cache2={cwd:null,expiresAt:0,promise:null};PATH_DELIMITERS=new Set([" ","\t",'"',"'","="]);commandCache={key:null,expiresAt:0,promise:null}});import{appendFileSync as appendFileSync2,chmodSync as chmodSync4,mkdirSync as mkdirSync9,readFileSync as readFileSync14}from"node:fs";import os13 from"node:os";import path31 from"node:path";import process28 from"node:process";function clonePastes(pastes){return new Map(pastes instanceof Map?pastes:pastes??[])}function cloneInputSnapshot(snapshot,cursor=snapshot.cursor){let value=String(snapshot.value??""),chars=[...value],pastes=clonePastes(snapshot.pastes),highestPasteId=Math.max(0,...pastes.keys()),requestedNextPasteId=Number.isSafeInteger(snapshot.nextPasteId)&&snapshot.nextPasteId>0?snapshot.nextPasteId:1;return{value,cursor:Math.max(0,Math.min(chars.length,Number.isInteger(cursor)?cursor:chars.length)),pastes,nextPasteId:Math.max(highestPasteId+1,requestedNextPasteId)}}function snapshotsEqual(left,right){if(left.value!==right.value||left.pastes.size!==right.pastes.size)return!1;for(let[id,text]of left.pastes)if(right.pastes.get(id)!==text)return!1;return!0}class InputHistory{constructor(entries=[],{maxEntries=MAX_INPUT_HISTORY,onRecord=null}={}){this.maxEntries=maxEntries,this.onRecord=onRecord,this.entries=entries.slice(-maxEntries).map((entry)=>cloneInputSnapshot(entry)),this.index=null,this.draft=null,this.lastRecalled=null}record(snapshot){let entry=cloneInputSnapshot(snapshot);if(this.resetNavigation(),!entry.value.trim())return!1;let latest=this.entries[this.entries.length-1];if(latest&&snapshotsEqual(latest,entry))return!1;if(this.entries.push(entry),this.entries.length>this.maxEntries)this.entries.shift();try{this.onRecord?.(cloneInputSnapshot(entry))}catch{}return!0}previous(active){if(this.entries.length===0)return null;if(this.index==null)this.draft=cloneInputSnapshot(active),this.index=this.entries.length-1;else this.index=Math.max(0,this.index-1);let recalled=cloneInputSnapshot(this.entries[this.index],0);return this.lastRecalled=recalled.value,recalled}next(){if(this.index==null)return null;if(this.index<this.entries.length-1){this.index+=1;let entry=this.entries[this.index],recalled=cloneInputSnapshot(entry,[...entry.value].length);return this.lastRecalled=recalled.value,recalled}let draft=this.draft?cloneInputSnapshot(this.draft):cloneInputSnapshot({value:""});return this.resetNavigation(),draft}isBrowsing(value,cursor){if(this.lastRecalled==null||value!==this.lastRecalled)return!1;return cursor===0||cursor===[...value].length}resetNavigation(){this.index=null,this.draft=null,this.lastRecalled=null}}function deserializeEntry(line,cwd){let record;try{record=JSON.parse(line)}catch{return null}if(record?.version!==1||record.cwd!==cwd||typeof record.value!=="string")return null;if(!Array.isArray(record.pastes))return null;let pastes=new Map;for(let item of record.pastes){if(!Array.isArray(item)||!Number.isSafeInteger(item[0])||item[0]<=0||typeof item[1]!=="string")return null;pastes.set(item[0],item[1])}return cloneInputSnapshot({value:record.value,pastes})}function loadInputHistory({cwd=process28.cwd(),file=INPUT_HISTORY_FILE}={}){let content;try{content=readFileSync14(file,"utf8")}catch{return[]}let entries=[];for(let line of content.split(`
2309
- `)){if(!line.trim())continue;let entry=deserializeEntry(line,cwd);if(entry)entries.push(entry)}return entries.slice(-MAX_INPUT_HISTORY)}function appendInputHistory(snapshot,{cwd=process28.cwd(),file=INPUT_HISTORY_FILE}={}){let entry=cloneInputSnapshot(snapshot),line=`${JSON.stringify({version:1,at:Date.now(),cwd,value:entry.value,pastes:[...entry.pastes]})}
2310
- `;if(Buffer.byteLength(line)>MAX_RECORD_BYTES)return!1;try{let dir=path31.dirname(file);return mkdirSync9(dir,{recursive:!0,mode:448}),chmodSync4(dir,448),appendFileSync2(file,line,{encoding:"utf8",mode:384}),chmodSync4(file,384),!0}catch{return!1}}function getInputHistory(cwd=process28.cwd()){if(!histories.has(cwd))histories.set(cwd,new InputHistory(loadInputHistory({cwd}),{onRecord:(entry)=>appendInputHistory(entry,{cwd})}));return histories.get(cwd)}var MAX_INPUT_HISTORY=100,MAX_RECORD_BYTES=262144,INPUT_HISTORY_FILE,histories;var init_input_history=__esm(()=>{INPUT_HISTORY_FILE=path31.join(os13.homedir(),".miro","history.jsonl");histories=new Map});function pickerQueryState(result,key){if(key==null)return{items:[],pending:!1};if(result?.key===key)return{items:result.items,pending:!1};return{items:[],pending:!0}}function createPickerRequest(key,publish){let cancelled=!1;return{resolve(items){if(!cancelled)publish({key,items})},cancel(){cancelled=!0}}}function pickerDensity(rows){let height=Number.isFinite(rows)&&rows>0?Math.floor(rows):24;if(height<9)return"minimal";if(height<16)return"compact";return"full"}function pickerViewport({index,total,rows,reservedRows,maxVisible=10,minVisible=1}){let count=Math.max(0,Math.floor(total));if(count===0)return{index:0,size:0,start:0,end:0,above:0,below:0};let height=Number.isFinite(rows)&&rows>0?Math.floor(rows):24,selected=Math.max(0,Math.min(Math.floor(index),count-1)),budget=Math.max(minVisible,height-Math.max(0,reservedRows)),size=Math.min(count,Math.max(1,Math.min(maxVisible,budget))),start=count<=size?0:Math.max(0,Math.min(selected-Math.floor(size/2),count-size)),end=start+size;return{index:selected,size,start,end,above:start,below:Math.max(0,count-end)}}function normalizeItem(item,index){let raw=item??{},value=raw.value,label=raw.label??raw.name??(value==null?"":String(value));return{key:value==null?`row-${index}`:`${index}:${value}`,value,label:String(label),description:raw.description==null?"":String(raw.description),groupName:raw.groupName==null?"":String(raw.groupName),right:raw.right==null?"":String(raw.right),current:Boolean(raw.current),disabled:Boolean(raw.disabled),disabledReason:raw.disabledReason==null?"":String(raw.disabledReason),source:raw}}function normalizeItems(items){return(Array.isArray(items)?items:[]).map(normalizeItem)}function firstSelectableIndex(rows){let index=rows.findIndex((row)=>!row.disabled);return index===-1?0:index}function initialIndex(rows,selected){if(rows.length===0)return 0;if(Number.isInteger(selected)&&selected>=0&&selected<rows.length&&!rows[selected].disabled)return selected;let current=rows.findIndex((row)=>row.current&&!row.disabled);if(current!==-1)return current;return firstSelectableIndex(rows)}function moveIndex(rows,index,delta){let total=rows.length;if(total===0)return 0;if(!rows.some((row)=>!row.disabled))return index;let step=delta<0?-1:1,cursor=index;for(let hop=0;hop<total;hop+=1)if(cursor=(cursor+step+total)%total,!rows[cursor].disabled)return cursor;return index}function truncateToCellWidth(text,width){let source=String(text??""),limit=Math.max(0,Math.floor(width));if(stringWidth2(source)<=limit)return source;if(limit===0)return"";if(limit===1)return"…";let output="";for(let character of source){if(stringWidth2(output+character)>limit-1)break;output+=character}return`${output}…`}function pathCells(text,width,fromEnd=!1){let parts=Array.from(pathGraphemes.segment(text),(part)=>part.segment);if(fromEnd)parts.reverse();let kept=[],used=0;for(let part of parts){let cells=stringWidth2(part);if(used+cells>width)break;kept.push(part),used+=cells}return(fromEnd?kept.reverse():kept).join("")}function truncatePathToCellWidth(text,width){let source=String(text??"").replace(/[\u0000-\u001f\u007f-\u009f]/g,(char)=>({"\n":"\\n","\r":"\\r","\t":"\\t"})[char]??"�"),limit=Math.max(0,Math.floor(width));if(stringWidth2(source)<=limit)return source;if(limit===0)return"";if(limit===1)return"…";let slash=source.lastIndexOf("/",source.endsWith("/")?source.length-2:source.length-1),basename=source.slice(slash+1);if(slash>=0){let suffix=source.slice(slash);if(stringWidth2(suffix)<limit)return`${pathCells(source.slice(0,slash),limit-1-stringWidth2(suffix))}…${suffix}`;if(stringWidth2(basename)<limit)return`…${basename}`}let suffix=pathCells(basename,Math.floor((limit-1)/2),!0);return`${pathCells(basename,limit-1-stringWidth2(suffix))}…${suffix}`}function splitRowWidth(innerWidth,prefixWidth,rightText){let contentWidth=Math.max(0,innerWidth-prefixWidth),value=String(rightText??""),showRight=Boolean(value)&&contentWidth>=8,rightWidth=showRight?Math.min(stringWidth2(value),Math.max(3,Math.floor(contentWidth/2))):0,leftWidth=Math.max(0,contentWidth-rightWidth-(showRight?1:0));return{showRight,leftWidth,rightWidth,contentWidth}}function compactRowWidth(innerWidth,prefixWidth,labelText){let contentWidth=Math.max(0,innerWidth-prefixWidth),leftWidth=Math.min(stringWidth2(labelText),Math.max(0,contentWidth-1)),rightWidth=Math.max(0,contentWidth-leftWidth-1);return{showRight:rightWidth>0,leftWidth,rightWidth,contentWidth}}var pathGraphemes;var init_picker_rows=__esm(()=>{init_markdown_width();pathGraphemes=new Intl.Segmenter(void 0,{granularity:"grapheme"})});function completionViewport({index,total,rows,inputRows=3,surroundingRows=3}){return pickerViewport({index,total,rows,reservedRows:Math.max(3,inputRows)+surroundingRows+2,maxVisible:8})}function completionHint(width,viewport,total){let position=total>viewport.size?`${viewport.index+1}/${total}`:"",budget=width-stringWidth2(position)-(position?2:0),hint=["↑↓ to select · Tab/Enter to complete · Esc to dismiss","↑↓ · Tab/Enter · Esc","Tab · Esc"].find((text)=>stringWidth2(text)<=budget)??"";return truncateToCellWidth([hint,position].filter(Boolean).join(" "),width)}var init_picker_completion=__esm(()=>{init_markdown_width();init_picker_rows()});function wrapDescription(text,width,maxLines){let source=String(text??"").replace(/\s+/g," ").trim();if(!source||width<=0)return[];let lines=[],line="";for(let word of source.split(" ")){if(!line)line=word;else if(line.length+1+word.length<=width)line=`${line} ${word}`;else lines.push(line),line=word;while(line.length>width)lines.push(line.slice(0,width)),line=line.slice(width);if(lines.length>maxLines)break}if(line)lines.push(line);if(lines.length<=maxLines)return lines;let kept=lines.slice(0,maxLines),last=kept[maxLines-1];return kept[maxLines-1]=last.length<width?`${last}…`:`${last.slice(0,Math.max(0,width-1)).trimEnd()}…`,kept}function packRows(costs,activeIndex,budget){if(costs.length===0)return{start:0,end:-1,used:0};let start=Math.min(Math.max(activeIndex,0),costs.length-1),end=start,used=costs[start],down=!0;for(;;){let canDown=end+1<costs.length&&used+costs[end+1]<=budget,canUp=start>0&&used+costs[start-1]<=budget;if(!canDown&&!canUp)break;if(down?canDown:!canUp)used+=costs[end+=1];else used+=costs[start-=1];down=!down}return{start,end,used}}function ShortcutHelp({busy,canSteer}){return $jsxs(Box_default,{paddingX:1,gap:2,children:[$jsxs(Box_default,{flexDirection:"column",width:22,children:[$jsx(Text,{dimColor:!0,children:"! for shell mode"}),$jsx(Text,{dimColor:!0,children:"/ for commands"}),$jsx(Text,{dimColor:!0,children:"@ for file paths"}),$jsx(Text,{dimColor:!0,children:"shift + enter newline"}),$jsx(Text,{dimColor:!0,children:busy?canSteer?"enter to steer":"enter to queue":"enter to send"}),$jsx(Text,{dimColor:!0,children:"tab to queue while running"})]}),$jsxs(Box_default,{flexDirection:"column",width:32,children:[$jsx(Text,{dimColor:!0,children:"shift + tab to cycle mode"}),$jsx(Text,{dimColor:!0,children:"ctrl + m to switch model"}),$jsx(Text,{dimColor:!0,children:"ctrl + o to review"}),$jsx(Text,{dimColor:!0,children:"ctrl + q to review queue"})]}),$jsxs(Box_default,{flexDirection:"column",children:[$jsx(Text,{dimColor:!0,children:"ctrl + l to clear screen"}),$jsx(Text,{dimColor:!0,children:"ctrl + c to clear input, then to interrupt"}),$jsx(Text,{dimColor:!0,children:"esc to cancel"}),$jsx(Text,{dimColor:!0,children:"↑/↓ for history"})]})]})}function Composer({disabled,locked=!1,busy=!1,canSteer=!1,onSubmit,onCycleMode,providerCommands=[],inputHistory=null,helpOpen=!1,onHelpOpenChange,onCompletionOpenChange,sessionKey=null,initialSnapshot=null,onSnapshotChange,controlsRef=null}){let{columns=80,rows=24}=use_window_size_default(),inputBoxRef=$useRef(null),inputMetrics=use_box_metrics_default(inputBoxRef),[value,setValue]=$useState(""),[cursor,setCursor]=$useState(0),[selectedIndex,setSelectedIndex]=$useState(0),[dismissed,setDismissed]=$useState(!1),[fileSuggestions,setFileSuggestions]=$useState(null),historyRef=$useRef(inputHistory??getInputHistory()),onSnapshotChangeRef=$useRef(onSnapshotChange);onSnapshotChangeRef.current=onSnapshotChange;let restoredSessionKeyRef=$useRef(Symbol("uninitialized-session")),[pastes,setPastes]=$useState(()=>new Map),nextPasteIdRef=$useRef(1),pastesRef=$useRef(pastes);pastesRef.current=pastes;let valueRef=$useRef(value);valueRef.current=value;let cursorRef=$useRef(cursor);cursorRef.current=cursor;let chars=[...value],cursorPos=chars.slice(0,cursor).join("").length,browsingHistory=historyRef.current.isBrowsing(value,cursor),fileToken=disabled||browsingHistory?null:extractAtToken(value,cursorPos),isBashMode=!disabled&&isBashInput(value),[bashPathActive,setBashPathActive]=$useState(!1),[pathSuggestions,setPathSuggestions]=$useState([]),pathToken=isBashMode&&bashPathActive?extractPathToken(value,cursorPos):null;$useEffect(()=>{if(!isBashMode&&bashPathActive)setBashPathActive(!1),setPathSuggestions([])},[isBashMode,bashPathActive]);let pathFetchSeq=$useRef(0),pathTokenKey=pathToken?`${pathToken.startPos}:${pathToken.query}`:null;$useEffect(()=>{if(pathTokenKey==null){setPathSuggestions([]);return}let seq=++pathFetchSeq.current,timer=setTimeout(()=>{generateBashSuggestions(value,pathToken).then((items)=>{if(pathFetchSeq.current===seq)setPathSuggestions(items)})},FILE_SUGGESTION_DEBOUNCE_MS);return()=>clearTimeout(timer)},[pathTokenKey]);let tokenKey=dismissed?null:fileSuggestionKey(fileToken);$useEffect(()=>{if(setFileSuggestions(null),tokenKey==null)return;let request=createPickerRequest(tokenKey,setFileSuggestions),timer=setTimeout(()=>{generateFileSuggestions(fileToken.query).then(request.resolve,()=>request.resolve([]))},FILE_SUGGESTION_DEBOUNCE_MS);return()=>{clearTimeout(timer),request.cancel()}},[tokenKey,sessionKey]);let fileQuery=pickerQueryState(fileSuggestions,tokenKey),isFileMode=Boolean(fileToken),isPathMode=!isFileMode&&Boolean(pathToken),localNames=new Set(SLASH_COMMANDS.map((cmd)=>cmd.name)),allCommands=[...SLASH_COMMANDS,...providerCommands.filter((cmd)=>cmd?.name&&!localNames.has(cmd.name)).map((cmd)=>({name:cmd.name,aliases:[],description:`${cmd.description??""}${cmd.input?.hint?` (${cmd.input.hint})`:""} [provider]`.trim()}))],commandSuggestions=dismissed||disabled||isFileMode||isPathMode||browsingHistory?[]:generateCommandSuggestions(value,allCommands),activeSuggestions=dismissed||disabled?[]:isFileMode?fileQuery.items:isPathMode?pathSuggestions:commandSuggestions,showSuggestions=activeSuggestions.length>0,activeIndex=Math.min(selectedIndex,Math.max(0,activeSuggestions.length-1)),completionOpen=showSuggestions||fileQuery.pending;$useLayoutEffect(()=>(onCompletionOpenChange?.(completionOpen),()=>onCompletionOpenChange?.(!1)),[completionOpen,onCompletionOpenChange]);let currentSnapshot=()=>cloneInputSnapshot({value:valueRef.current,cursor:cursorRef.current,pastes:pastesRef.current,nextPasteId:nextPasteIdRef.current}),notifySnapshotChange=()=>onSnapshotChangeRef.current?.(currentSnapshot()),replace=(nextChars,nextCursor)=>{let nextValue=nextChars.join(""),clampedCursor=Math.max(0,Math.min(nextChars.length,nextCursor));valueRef.current=nextValue,cursorRef.current=clampedCursor,setValue(nextValue),setCursor(clampedCursor),setSelectedIndex(0),setDismissed(!1);let pruned=pruneOrphanPastes(nextValue,pastesRef.current);if(pruned!==pastesRef.current)pastesRef.current=pruned,setPastes(pruned);notifySnapshotChange()},restoreSnapshot=(snapshot,{notify=!0,resetHistory=!1}={})=>{let restored=cloneInputSnapshot(snapshot??{value:""});if(valueRef.current=restored.value,cursorRef.current=restored.cursor,pastesRef.current=restored.pastes,nextPasteIdRef.current=restored.nextPasteId,setValue(restored.value),setCursor(restored.cursor),setPastes(restored.pastes),setSelectedIndex(0),setDismissed(!1),setFileSuggestions(null),setBashPathActive(!1),setPathSuggestions([]),resetHistory)historyRef.current.resetNavigation();if(notify)notifySnapshotChange()};$useEffect(()=>{if(restoredSessionKeyRef.current===sessionKey)return;restoredSessionKeyRef.current=sessionKey,restoreSnapshot(initialSnapshot,{notify:!1,resetHistory:!0})},[sessionKey]);let resetDraft=()=>{valueRef.current="",cursorRef.current=0,setValue(""),setCursor(0),setSelectedIndex(0),setDismissed(!1),setFileSuggestions(null),setBashPathActive(!1),setPathSuggestions([]),pastesRef.current=new Map,setPastes(pastesRef.current),nextPasteIdRef.current=1},hasDraft=()=>valueRef.current!==""||pastesRef.current.size>0,clearDraft=()=>{if(!hasDraft())return!1;return historyRef.current.resetNavigation(),resetDraft(),notifySnapshotChange(),!0};if(controlsRef)controlsRef.current={hasDraft,clearDraft};let submit=(text,intent="submit")=>{let display=String(text??""),submittedPastes=pruneOrphanPastes(display,pastesRef.current);historyRef.current.record({value:display,cursor:[...display].length,pastes:submittedPastes,nextPasteId:nextPasteIdRef.current});let expanded=expandPasteMarkers(display,submittedPastes);resetDraft(),notifySnapshotChange(),onSubmit(expanded,expanded===display?void 0:display,{intent})},applyActiveFileSuggestion=()=>{let currentChars=[...valueRef.current],currentPos=currentChars.slice(0,cursorRef.current).join("").length,token=extractAtToken(valueRef.current,currentPos),suggestion=pickerQueryState(fileSuggestions,fileSuggestionKey(token)).items[activeIndex];if(!suggestion)return;let{nextChars,nextCursor}=applyFileSuggestion(currentChars,token,suggestion);setFileSuggestions(null),replace(nextChars,nextCursor)},applyActivePathSuggestion=()=>{let suggestion=activeSuggestions[activeIndex],{nextChars,nextCursor}=applyPathSuggestion(chars,pathToken,suggestion);if(!suggestion.isDirectory)setBashPathActive(!1),setPathSuggestions([]);replace(nextChars,nextCursor)},triggerBashPathCompletion=()=>{let currentValue=valueRef.current,currentChars=[...currentValue],currentCursor=Math.max(0,Math.min(currentChars.length,cursorRef.current)),currentCursorPos=currentChars.slice(0,currentCursor).join("").length,token=extractPathToken(currentValue,currentCursorPos),seq=++pathFetchSeq.current,snapshot=currentValue;generateBashSuggestions(currentValue,token).then((items)=>{if(pathFetchSeq.current!==seq||valueRef.current!==snapshot)return;if(items.length===0)return;let only=items[0];if(items.length===1&&only.path+(only.isDirectory?"/":"")!==token.token){let{nextChars,nextCursor}=applyPathSuggestion(currentChars,token,only);if(replace(nextChars,nextCursor),only.isDirectory)setBashPathActive(!0);return}setBashPathActive(!0),setPathSuggestions(items)})},insertPaste=(text)=>{let currentChars=[...valueRef.current],result=insertPastedText({chars:currentChars,cursor:Math.max(0,Math.min(currentChars.length,cursorRef.current)),pastes:pastesRef.current,nextId:nextPasteIdRef.current,text});if(!result)return null;if(result.id!=null)nextPasteIdRef.current=result.id+1;pastesRef.current=result.pastes,setPastes(result.pastes);let nextValue=result.chars.join("");return replace(result.chars,result.cursor),nextValue};use_paste_default((text)=>{if(!locked)insertPaste(text)},{isActive:!disabled}),use_input_default((input,key)=>{if(locked)return;let currentValue=valueRef.current,currentChars=[...currentValue],currentCursor=Math.max(0,Math.min(currentChars.length,cursorRef.current)),currentPastes=pastesRef.current;if(key.tab&&key.shift){onCycleMode?.();return}if(onHelpOpenChange&&!key.ctrl&&!key.meta&&!key.tab&&currentValue===""&&input==="?"){onHelpOpenChange(!helpOpen);return}if(helpOpen)onHelpOpenChange?.(!1);if(key.return&&(key.shift||key.meta)){let next=insertTextAtCursor(currentChars,currentCursor,`
2311
- `);replace(next.chars,next.cursor);return}let currentPos=currentChars.slice(0,currentCursor).join("").length,currentFileToken=historyRef.current.isBrowsing(currentValue,currentCursor)?null:extractAtToken(currentValue,currentPos);if(!dismissed&&(isFileMode||currentFileToken)){if(key.escape){setDismissed(!0);return}if((pickerQueryState(fileSuggestions,fileSuggestionKey(currentFileToken)).pending||!currentFileToken)&&(key.tab||key.return||key.upArrow||key.downArrow))return}if(showSuggestions){if(key.upArrow){setSelectedIndex((activeIndex-1+activeSuggestions.length)%activeSuggestions.length);return}if(key.downArrow){setSelectedIndex((activeIndex+1)%activeSuggestions.length);return}if(key.tab||key.return&&(isFileMode||isPathMode)){if(isFileMode)applyActiveFileSuggestion();else if(isPathMode)applyActivePathSuggestion();else{let name=activeSuggestions[activeIndex].name;replace([...`/${name} `],name.length+2)}return}if(key.return){submit(`/${activeSuggestions[activeIndex].name}`);return}if(key.escape){if(isPathMode){setBashPathActive(!1),setPathSuggestions([]);return}setDismissed(!0);return}}if(key.return){if(helpOpen&&currentValue==="")return;submit(currentValue);return}if(key.leftArrow){let nextCursor=stepCursor(currentChars,currentCursor,-1,currentPastes);cursorRef.current=nextCursor,setCursor(nextCursor),notifySnapshotChange();return}if(key.rightArrow){let nextCursor=stepCursor(currentChars,currentCursor,1,currentPastes);cursorRef.current=nextCursor,setCursor(nextCursor),notifySnapshotChange();return}if(key.home){cursorRef.current=0,setCursor(0),notifySnapshotChange();return}if(key.end){cursorRef.current=currentChars.length,setCursor(currentChars.length),notifySnapshotChange();return}if(key.backspace){let result=deleteBeforeCursor(currentChars,currentCursor,currentPastes);if(result)replace(result.chars,result.cursor);return}if(key.delete){let result=deleteAfterCursor(currentChars,currentCursor,currentPastes);if(result)replace(result.chars,result.cursor);return}if(key.ctrl){if(input==="a")cursorRef.current=0,setCursor(0),notifySnapshotChange();if(input==="e")cursorRef.current=currentChars.length,setCursor(currentChars.length),notifySnapshotChange();if(input==="u")replace(currentChars.slice(currentCursor),0);if(input==="k")replace(currentChars.slice(0,currentCursor),currentCursor);return}if(key.upArrow){let snapshot=historyRef.current.previous(currentSnapshot());if(snapshot)restoreSnapshot(snapshot);return}if(key.downArrow){let snapshot=historyRef.current.next();if(snapshot)restoreSnapshot(snapshot);return}if(key.tab){if(isBashInput(currentValue)&&!isFileMode)triggerBashPathCompletion();else if(submissionIntent({tab:!0,busy,bash:isBashInput(currentValue)})&&currentValue.trim())submit(currentValue,"queue");return}if(key.escape||key.meta)return;if(key.pageUp||key.pageDown)return;if(!input)return;let shouldSubmit=/[\r\n]$/.test(input),body=input.replace(/[\r\n]+$/,"");if([...body].length>1&&shouldCollapsePaste(normalizePastedText(body))){let nextValue=insertPaste(body);if(shouldSubmit&&nextValue!=null)submit(nextValue);return}let text=body.replace(/[\r\n]+/g," ").replace(/[\u0000-\u001F\u007F]/g,""),next=[...currentChars.slice(0,currentCursor),...text,...currentChars.slice(currentCursor)];if(shouldSubmit){submit(next.join(""));return}replace(next,currentCursor+[...text].length)},{isActive:!disabled});let accentColor=disabled?"gray":isBashMode?"magenta":"cyan",displayChars=isBashMode?chars.slice(1):chars,displayCursor=isBashMode?Math.max(0,cursor-1):cursor,inputSegments=segmentInput(displayChars,displayCursor,pastes),inputRowRef=$useRef(null),inputCursorText=cursorText(inputSegments);useInputCursor(inputRowRef,disabled||locked?null:cursorColumn(inputSegments),{text:inputCursorText,fullText:inputSegments.map((segment)=>segment.text).join("")});let isPathLikeMode=isFileMode||isPathMode,nameColumnWidth=isPathLikeMode?0:Math.max(0,...activeSuggestions.map((s)=>s.displayText.length))+2,descriptionWidth=Math.max(MIN_DESCRIPTION_WIDTH,columns-2-(nameColumnWidth+2)),commandRows=isPathLikeMode?[]:activeSuggestions.map((item)=>({item,lines:wrapDescription(item.description,descriptionWidth,COMMAND_DESCRIPTION_LINES)})),rowCosts=commandRows.map((row)=>Math.max(1,row.lines.length)),commandBudget=Math.min(COMMAND_SUGGESTION_LINES,rowCosts.reduce((sum,cost)=>sum+cost,0)),packed=packRows(rowCosts,activeIndex,commandBudget),viewport=completionViewport({index:activeIndex,total:activeSuggestions.length,rows,inputRows:inputMetrics.hasMeasured?inputMetrics.height:3}),windowFrom=isPathLikeMode?viewport.start:packed.start,visibleSuggestions=isPathLikeMode?activeSuggestions.slice(viewport.start,viewport.end):commandRows.slice(packed.start,packed.end+1).map((row)=>row.item),fillerLines=isPathLikeMode?0:Math.max(0,commandBudget-packed.used);return $jsxs(Box_default,{flexDirection:"column",children:[$jsxs(Box_default,{ref:inputBoxRef,borderStyle:"round",borderColor:accentColor,borderLeft:!1,borderRight:!1,width:"100%",children:[$jsx(Box_default,{flexShrink:0,children:$jsx(Text,{color:accentColor,children:isBashMode?"! ":"❯ "})}),$jsx(Box_default,{flexGrow:1,ref:inputRowRef,children:disabled?chars.length>0?$jsx(Text,{dimColor:!0,children:value}):null:$jsx(Text,{children:inputSegments.map((segment,index)=>$jsx(Text,{inverse:segment.marker&&segment.cursor,color:segment.marker?"cyan":void 0,bold:segment.marker,children:segment.text},index))})})]}),showSuggestions?$jsxs(Box_default,{flexDirection:"column",paddingX:1,children:[visibleSuggestions.map((item,index)=>{let active=windowFrom+index===activeIndex;if(isPathLikeMode){let detail=item.isCommand?"cmd":"",pathWidth=Math.max(0,columns-4-(detail?detail.length+2:0));return $jsxs(Text,{color:active?"cyan":void 0,bold:active,dimColor:!active,wrap:"truncate",children:[active?"❯ ":" ",truncatePathToCellWidth(item.displayText,pathWidth),detail?$jsxs(Text,{children:[" ",detail]}):null]},item.displayText)}let lines=commandRows[windowFrom+index].lines;return $jsxs(Box_default,{flexDirection:"row",children:[$jsx(Box_default,{width:nameColumnWidth+2,flexShrink:0,children:$jsxs(Text,{color:active?"cyan":void 0,bold:active,wrap:"truncate-end",children:[active?"❯ ":" ",item.displayText]})}),$jsx(Box_default,{flexGrow:1,flexShrink:1,flexDirection:"column",children:lines.map((line,lineIndex)=>$jsx(Text,{color:active?"cyan":void 0,bold:active,dimColor:!active,wrap:"truncate-end",children:line},lineIndex))})]},item.name)}),fillerLines>0?$jsx(Box_default,{height:fillerLines,flexShrink:0}):null,$jsxs(Text,{dimColor:!0,wrap:"truncate",children:[isPathLikeMode?completionHint(Math.max(0,columns-2),viewport,activeSuggestions.length):"Tab to complete · Enter to run · Esc to dismiss",!isPathLikeMode&&activeSuggestions.length>visibleSuggestions.length?` · ${activeIndex+1}/${activeSuggestions.length}`:""]})]}):fileQuery.pending?$jsx(Box_default,{paddingX:1,children:$jsx(Text,{dimColor:!0,wrap:"truncate",children:"Finding files… · Esc to dismiss"})}):helpOpen?$jsx(ShortcutHelp,{busy,canSteer}):null]})}var COMMAND_SUGGESTION_LINES=10,COMMAND_DESCRIPTION_LINES=2,MIN_DESCRIPTION_WIDTH=20,FILE_SUGGESTION_DEBOUNCE_MS=50;var init_Composer=__esm(async()=>{init_react_production();init_commands();init_bash();init_paste_block();init_file_suggestions();init_input_history();init_picker_completion();init_picker_rows();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_use_input_cursor()])});function InputPrompt({title,value="",hint="Enter to save · Esc to go back",secret=!1,onSubmit,onCancel}){let[text,setText]=$useState(value),lineRef=$useRef(null);return useInputCursor(lineRef,stringWidth2(PROMPT+text)),use_input_default((input,key)=>{if(key.escape)return onCancel();if(key.return)return onSubmit(text);if(key.backspace||key.delete)return setText((current)=>[...current].slice(0,-1).join(""));if(input)setText((current)=>current+input)}),$jsxs(Box_default,{flexDirection:"column",borderStyle:"round",borderColor:"cyan",paddingX:1,children:[$jsx(Text,{bold:!0,color:"cyan",children:title}),$jsx(Box_default,{ref:lineRef,children:$jsx(Text,{children:PROMPT+(secret?"•".repeat([...text].length):text)})}),$jsx(Text,{dimColor:!0,children:hint})]})}var PROMPT="> ";var init_InputPrompt=__esm(async()=>{init_react_production();init_markdown_width();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_use_input_cursor()])});function isMcpCall(toolCall){return toolCall?.name==="mcp_call"}function permissionTitle(toolCall){if(isMcpCall(toolCall))return"MCP tool call";switch(toolCall?.kind){case"execute":return"Bash command";case"edit":return"Edit file";case"read":return"Read file";case"delete":return"Delete file";case"fetch":return"Fetch";case"plan":return"Plan";default:return toolCall?.title||"Tool call"}}function inputText(input){if(input==null)return"";try{return JSON.stringify(input,null,2)}catch{return String(input)}}function permissionReview(toolCall){if(isMcpCall(toolCall))return{diff:null,text:inputText(toolCall.rawInput)};let diff=extractToolDiff(toolCall);if(toolCall?.command)return{diff,text:String(toolCall.command)};let input=toolCall?.rawInput;if(input!=null&&typeof input==="object"){if(typeof input.plan==="string")return{diff,text:input.plan};let path=input.path??input.file_path??input.filePath??input.filename,body=input.patch??input.diff??input.content??input.new_content??input.newText;if(typeof body==="string")return{diff,text:`${path?`Path: ${path}
2250
+ `){row+=1,column=0;continue}let characterWidth=stringWidth2(character);if(characterWidth>0&&column>0&&column+characterWidth>width)row+=1,column=0;if(column+=characterWidth,column>=width)row+=Math.floor(column/width),column%=width}return{x:x+column,y:y+row}}var graphemeSegmenter;var init_caret=__esm(()=>{init_markdown_width();graphemeSegmenter=new Intl.Segmenter(void 0,{granularity:"grapheme"})});import{execFile as execFile4}from"node:child_process";import{readdir as readdir2,stat as stat5}from"node:fs/promises";import{homedir as homedir4}from"node:os";import path30 from"node:path";function extractAtToken(text,cursorPos){if(!text)return null;let before=text.substring(0,cursorPos),atIdx=before.lastIndexOf("@");if(atIdx<0)return null;if(atIdx>0&&!/\s/.test(before[atIdx-1]))return null;let fromAt=before.substring(atIdx);if(fromAt.startsWith('@"')){if(!QUOTED_AT_TOKEN_HEAD_RE.test(fromAt))return null;let afterMatch=text.substring(cursorPos).match(QUOTED_PATH_CHAR_HEAD_RE),token=fromAt+(afterMatch?afterMatch[0]:""),quotedPath=token.slice(2,token.endsWith('"')?-1:void 0);return{token,startPos:atIdx,query:quotedPath,quoted:!0}}let headMatch=fromAt.match(AT_TOKEN_HEAD_RE);if(!headMatch||headMatch[0].length!==fromAt.length)return null;let afterMatch=text.substring(cursorPos).match(PATH_CHAR_HEAD_RE),token=headMatch[0]+(afterMatch?afterMatch[0]:"");return{token,startPos:atIdx,query:token.slice(1)}}function fileSuggestionKey(token){return token?`${token.startPos}:${token.token}`:null}function execCommand(command,args,cwd,timeout=SEARCH_TIMEOUT_MS){return new Promise((resolve)=>{execFile4(command,args,{cwd,timeout,maxBuffer:16777216},(error,stdout)=>resolve(error?null:stdout))})}async function listFilesViaGit(cwd){let inRepo=await execCommand("git",["rev-parse","--is-inside-work-tree"],cwd,GIT_TIMEOUT_MS3);if(inRepo===null)return{inRepo:null,files:null};if(inRepo.trim()!=="true")return{inRepo:!1,files:null};let[stdout,ignoredStdout]=await Promise.all([execCommand("git",["-c","core.quotepath=false","ls-files","-z","--cached","--others","--exclude-standard"],cwd,GIT_TIMEOUT_MS3),execCommand("git",["-c","core.quotepath=false","ls-files","-z","--others","--ignored","--directory","--empty-directory","--exclude-standard"],cwd,GIT_TIMEOUT_MS3)]);if(stdout===null)return{inRepo:!0,files:null,dirs:null};let ignoredDirs=new Set((ignoredStdout??"").split("\x00").filter((entry)=>entry.endsWith("/")).map((entry)=>entry.slice(0,-1))),scannedDirs=ignoredStdout===null?null:await listDirectoriesViaScan(cwd,ignoredDirs);return{inRepo:!0,files:stdout.split("\x00").filter(Boolean),dirs:scannedDirs}}async function listFilesViaRipgrep(cwd){let stdout=await execCommand("rg",["--files","--null","--hidden","--glob","!.git","--glob","!.git/**"],cwd);if(stdout===null)return null;return stdout.split("\x00").filter(Boolean)}async function hasGitMetadata(cwd){let current=path30.resolve(cwd);for(;;){try{return await stat5(path30.join(current,".git")),!0}catch{}let parent=path30.dirname(current);if(parent===current)return!1;current=parent}}async function listFilesViaScan(cwd){let files=[],walk=async(dir,depth)=>{if(depth>SCAN_MAX_DEPTH||files.length>=SCAN_MAX_FILES)return;let entries;try{entries=await readdir2(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(files.length>=SCAN_MAX_FILES)return;let full=path30.join(dir,entry.name);if(entry.isDirectory()){if(!SCAN_SKIP_DIRS.has(entry.name))await walk(full,depth+1)}else if(entry.isFile())files.push(path30.relative(cwd,full))}};return await walk(cwd,0),files}function isInsideIgnoredDirectory(candidate,ignoredDirs){let current=candidate;for(;;){if(ignoredDirs.has(current))return!0;let slash=current.lastIndexOf("/");if(slash<0)return!1;current=current.slice(0,slash)}}async function listDirectoriesViaScan(cwd,ignoredDirs=new Set){let dirs=[],walk=async(dir,prefix,depth)=>{if(depth>SCAN_MAX_DEPTH||dirs.length>=SCAN_MAX_DIRS)return;let entries;try{entries=await readdir2(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(dirs.length>=SCAN_MAX_DIRS)return;if(!entry.isDirectory()||SCAN_SKIP_DIRS.has(entry.name))continue;let relative=prefix?`${prefix}/${entry.name}`:entry.name;if(isInsideIgnoredDirectory(relative,ignoredDirs))continue;dirs.push(relative),await walk(path30.join(dir,entry.name),relative,depth+1)}};return await walk(cwd,"",0),dirs}function getDirectoryNames(files){let dirs=new Set;for(let file of files){let dir=path30.dirname(file);while(dir!=="."&&!dirs.has(dir)){let parent=path30.dirname(dir);if(parent===dir)break;dirs.add(dir),dir=parent}}return[...dirs].map((d)=>d+"/")}async function listWorkspacePaths(cwd){let now=Date.now();if(cache.cwd===cwd&&cache.promise&&now<cache.expiresAt)return cache.promise;let promise=(async()=>{let git=await listFilesViaGit(cwd),files=git.files??await listFilesViaRipgrep(cwd);if(files===null)files=git.inRepo??await hasGitMetadata(cwd)?[]:await listFilesViaScan(cwd);let dirs=new Set(getDirectoryNames(files));for(let dir of git.dirs??[])dirs.add(`${dir}/`);return{files,dirs:[...dirs]}})();return cache={cwd,expiresAt:now+CACHE_TTL_MS,promise},promise.catch(()=>{if(cache.promise===promise)cache={cwd:null,expiresAt:0,promise:null}}),promise}function toSuggestion2(p){let isDirectory=p.endsWith("/");return{path:isDirectory?p.slice(0,-1):p,isDirectory,displayText:p}}function byDirFirst(a,b){let aDir=a.endsWith("/"),bDir=b.endsWith("/");if(aDir!==bDir)return aDir?-1:1;return a.localeCompare(b)}function listIndexedLevel(files,dirs,dirPrefix){return[...dirs,...files].filter((candidate)=>{if(!candidate.startsWith(dirPrefix)||candidate===dirPrefix)return!1;let remainder=candidate.slice(dirPrefix.length),withoutTrailingSlash=remainder.endsWith("/")?remainder.slice(0,-1):remainder;return withoutTrailingSlash!==""&&!withoutTrailingSlash.includes("/")}).sort(byDirFirst)}function matchRank2(candidate,query){let p=candidate.toLowerCase();if(path30.basename(candidate.endsWith("/")?candidate.slice(0,-1):candidate).toLowerCase().startsWith(query))return 0;if(p.startsWith(query))return 1;if(p.includes(query))return 2;return-1}async function generateFileSuggestions(query,opts={}){let cwd=opts.cwd??process.cwd(),limit=opts.limit??1/0;try{let{files,dirs}=await listWorkspacePaths(cwd);if(query===""||query==="."||query==="./")return listIndexedLevel(files,dirs,"").slice(0,limit).map(toSuggestion2);let normalized=query.startsWith("./")?query.slice(2):query;if(normalized.endsWith("/"))return listIndexedLevel(files,dirs,normalized).slice(0,limit).map(toSuggestion2);let q=normalized.toLowerCase();return[...dirs,...files].map((candidate)=>({candidate,rank:matchRank2(candidate,q)})).filter((item)=>item.rank>=0).sort((a,b)=>a.rank-b.rank||a.candidate.length-b.candidate.length||a.candidate.localeCompare(b.candidate)).slice(0,limit).map((item)=>toSuggestion2(item.candidate))}catch{return[]}}function applyFileSuggestion(chars,token,suggestion){let value=chars.join(""),pathText=`${suggestion.path}${suggestion.isDirectory?"/":""}`,quoted=token.quoted||/\s/u.test(pathText),replacement=quoted?`@"${pathText}"${suggestion.isDirectory?"":" "}`:`@${pathText}${suggestion.isDirectory?"":" "}`,before=value.slice(0,token.startPos),after=value.slice(token.startPos+token.token.length),nextChars=[...before+replacement+after],cursorText=quoted&&suggestion.isDirectory?replacement.slice(0,-1):replacement;return{nextChars,nextCursor:[...before+cursorText].length}}function extractPathToken(text,cursorPos){let before=text.substring(0,cursorPos),start=0;for(let i=before.length-1;i>=0;i-=1)if(PATH_DELIMITERS.has(before[i])){start=i+1;break}let token=before.slice(start);if(start===0&&token.startsWith("!"))token=token.slice(1),start+=1;return{token,startPos:start,query:token}}function expandHome(p){if(p==="~")return homedir4();if(p.startsWith("~/"))return path30.join(homedir4(),p.slice(2));return p}async function generatePathSuggestions(prefix,opts={}){let cwd=opts.cwd??process.cwd(),limit=opts.limit??MAX_SUGGESTIONS;try{let expanded=expandHome(prefix),displayDir,searchDir,namePrefix;if(prefix===""||prefix==="~"||prefix.endsWith("/"))displayDir=prefix==="~"?"~/":prefix,searchDir=path30.isAbsolute(expanded)?expanded:path30.join(cwd,expanded),namePrefix="";else{let slashIdx=prefix.lastIndexOf("/");displayDir=slashIdx===-1?"":prefix.slice(0,slashIdx+1),namePrefix=prefix.slice(slashIdx+1).toLowerCase();let dir=expandHome(displayDir===""?".":displayDir);searchDir=path30.isAbsolute(dir)?dir:path30.join(cwd,dir)}let entries=await readdir2(searchDir,{withFileTypes:!0}),matched=[];for(let entry of entries){if(namePrefix&&!entry.name.toLowerCase().startsWith(namePrefix))continue;let isDirectory=entry.isDirectory();if(!isDirectory&&entry.isSymbolicLink())try{isDirectory=(await stat5(path30.join(searchDir,entry.name))).isDirectory()}catch{}matched.push({name:entry.name,isDirectory})}return matched.sort((a,b)=>{if(a.isDirectory!==b.isDirectory)return a.isDirectory?-1:1;return a.name.localeCompare(b.name)}),matched.slice(0,limit).map((entry)=>{let p=displayDir+entry.name;return{path:p,isDirectory:entry.isDirectory,displayText:p+(entry.isDirectory?"/":"")}})}catch{return[]}}function applyPathSuggestion(chars,token,suggestion){let value=chars.join(""),suffix=suggestion.isDirectory?"/":suggestion.isCommand?" ":"",replacement=suggestion.path+suffix,before=value.slice(0,token.startPos),after=value.slice(token.startPos+token.token.length);return{nextChars:[...before+replacement+after],nextCursor:[...before+replacement].length}}function isCommandPosition(text,startPos){let before=text.slice(0,startPos);if(before.startsWith("!"))before=before.slice(1);let trimmed=before.trim();if(trimmed==="")return!0;return/(\|\||&&|[|;&(`])$/.test(trimmed)}function clearCommandNameCache(){commandCache={key:null,expiresAt:0,promise:null}}async function listPathCommands(paths){let key=paths.join(path30.delimiter),now=Date.now();if(commandCache.key===key&&commandCache.promise&&now<commandCache.expiresAt)return commandCache.promise;let promise=(async()=>{let names=new Set;for(let dir of paths){if(!dir)continue;let entries;try{entries=await readdir2(dir,{withFileTypes:!0})}catch{continue}for(let entry of entries)if(entry.isFile()||entry.isSymbolicLink())names.add(entry.name)}return[...names]})();return commandCache={key,expiresAt:now+COMMAND_CACHE_TTL_MS,promise},promise.catch(()=>{if(commandCache.promise===promise)clearCommandNameCache()}),promise}async function generateCommandNameSuggestions(prefix,opts={}){let limit=opts.limit??MAX_SUGGESTIONS,paths=opts.paths??(process.env.PATH??"").split(path30.delimiter);try{let names=await listPathCommands(paths),q=prefix.toLowerCase();return names.filter((name)=>name.toLowerCase().startsWith(q)).sort((a,b)=>a.length-b.length||a.localeCompare(b)).slice(0,limit).map((name)=>({path:name,isDirectory:!1,isCommand:!0,displayText:name}))}catch{return[]}}async function generateBashSuggestions(text,token,opts={}){let{query}=token,looksLikePath=query.includes("/")||query.startsWith(".")||query.startsWith("~");if(query!==""&&!looksLikePath&&isCommandPosition(text,token.startPos)){let commands=await generateCommandNameSuggestions(query,opts);if(commands.length>0)return commands}return generatePathSuggestions(query,opts)}var AT_TOKEN_HEAD_RE,PATH_CHAR_HEAD_RE,QUOTED_AT_TOKEN_HEAD_RE,QUOTED_PATH_CHAR_HEAD_RE,MAX_SUGGESTIONS=15,CACHE_TTL_MS=5000,GIT_TIMEOUT_MS3=2000,SEARCH_TIMEOUT_MS=5000,SCAN_MAX_DEPTH=6,SCAN_MAX_FILES=5000,SCAN_MAX_DIRS=5000,SCAN_SKIP_DIRS,cache,PATH_DELIMITERS,commandCache,COMMAND_CACHE_TTL_MS=30000;var init_file_suggestions=__esm(()=>{AT_TOKEN_HEAD_RE=/^@[\p{L}\p{N}\p{M}_\-./\\()[\]~:]*/u,PATH_CHAR_HEAD_RE=/^[\p{L}\p{N}\p{M}_\-./\\()[\]~:]+/u,QUOTED_AT_TOKEN_HEAD_RE=/^@"[^"]*$/u,QUOTED_PATH_CHAR_HEAD_RE=/^[^"]*"?/u,SCAN_SKIP_DIRS=new Set([".git","node_modules"]);cache={cwd:null,expiresAt:0,promise:null};PATH_DELIMITERS=new Set([" ","\t",'"',"'","="]);commandCache={key:null,expiresAt:0,promise:null}});import{appendFileSync as appendFileSync2,chmodSync as chmodSync4,mkdirSync as mkdirSync9,readFileSync as readFileSync13}from"node:fs";import os12 from"node:os";import path31 from"node:path";import process17 from"node:process";function clonePastes(pastes){return new Map(pastes instanceof Map?pastes:pastes??[])}function cloneInputSnapshot(snapshot,cursor=snapshot.cursor){let value=String(snapshot.value??""),chars=[...value],pastes=clonePastes(snapshot.pastes),highestPasteId=Math.max(0,...pastes.keys()),requestedNextPasteId=Number.isSafeInteger(snapshot.nextPasteId)&&snapshot.nextPasteId>0?snapshot.nextPasteId:1;return{value,cursor:Math.max(0,Math.min(chars.length,Number.isInteger(cursor)?cursor:chars.length)),pastes,nextPasteId:Math.max(highestPasteId+1,requestedNextPasteId)}}function snapshotsEqual(left,right){if(left.value!==right.value||left.pastes.size!==right.pastes.size)return!1;for(let[id,text]of left.pastes)if(right.pastes.get(id)!==text)return!1;return!0}class InputHistory{constructor(entries=[],{maxEntries=MAX_INPUT_HISTORY,onRecord=null}={}){this.maxEntries=maxEntries,this.onRecord=onRecord,this.entries=entries.slice(-maxEntries).map((entry)=>cloneInputSnapshot(entry)),this.index=null,this.draft=null,this.lastRecalled=null}record(snapshot){let entry=cloneInputSnapshot(snapshot);if(this.resetNavigation(),!entry.value.trim())return!1;let latest=this.entries[this.entries.length-1];if(latest&&snapshotsEqual(latest,entry))return!1;if(this.entries.push(entry),this.entries.length>this.maxEntries)this.entries.shift();try{this.onRecord?.(cloneInputSnapshot(entry))}catch{}return!0}previous(active){if(this.entries.length===0)return null;if(this.index==null)this.draft=cloneInputSnapshot(active),this.index=this.entries.length-1;else this.index=Math.max(0,this.index-1);let recalled=cloneInputSnapshot(this.entries[this.index],0);return this.lastRecalled=recalled.value,recalled}next(){if(this.index==null)return null;if(this.index<this.entries.length-1){this.index+=1;let entry=this.entries[this.index],recalled=cloneInputSnapshot(entry,[...entry.value].length);return this.lastRecalled=recalled.value,recalled}let draft=this.draft?cloneInputSnapshot(this.draft):cloneInputSnapshot({value:""});return this.resetNavigation(),draft}isBrowsing(value,cursor){if(this.lastRecalled==null||value!==this.lastRecalled)return!1;return cursor===0||cursor===[...value].length}resetNavigation(){this.index=null,this.draft=null,this.lastRecalled=null}}function deserializeEntry(line,cwd){let record;try{record=JSON.parse(line)}catch{return null}if(record?.version!==1||record.cwd!==cwd||typeof record.value!=="string")return null;if(!Array.isArray(record.pastes))return null;let pastes=new Map;for(let item of record.pastes){if(!Array.isArray(item)||!Number.isSafeInteger(item[0])||item[0]<=0||typeof item[1]!=="string")return null;pastes.set(item[0],item[1])}return cloneInputSnapshot({value:record.value,pastes})}function loadInputHistory({cwd=process17.cwd(),file=INPUT_HISTORY_FILE}={}){let content;try{content=readFileSync13(file,"utf8")}catch{return[]}let entries=[];for(let line of content.split(`
2251
+ `)){if(!line.trim())continue;let entry=deserializeEntry(line,cwd);if(entry)entries.push(entry)}return entries.slice(-MAX_INPUT_HISTORY)}function appendInputHistory(snapshot,{cwd=process17.cwd(),file=INPUT_HISTORY_FILE}={}){let entry=cloneInputSnapshot(snapshot),line=`${JSON.stringify({version:1,at:Date.now(),cwd,value:entry.value,pastes:[...entry.pastes]})}
2252
+ `;if(Buffer.byteLength(line)>MAX_RECORD_BYTES)return!1;try{let dir=path31.dirname(file);return mkdirSync9(dir,{recursive:!0,mode:448}),chmodSync4(dir,448),appendFileSync2(file,line,{encoding:"utf8",mode:384}),chmodSync4(file,384),!0}catch{return!1}}function getInputHistory(cwd=process17.cwd()){if(!histories.has(cwd))histories.set(cwd,new InputHistory(loadInputHistory({cwd}),{onRecord:(entry)=>appendInputHistory(entry,{cwd})}));return histories.get(cwd)}var MAX_INPUT_HISTORY=100,MAX_RECORD_BYTES=262144,INPUT_HISTORY_FILE,histories;var init_input_history=__esm(()=>{INPUT_HISTORY_FILE=path31.join(os12.homedir(),".miro","history.jsonl");histories=new Map});function normalizePastedText(text){return[...String(text??"").replace(ANSI_REGEX,"").replace(/\r\n/g,`
2253
+ `).replace(/\r/g,`
2254
+ `).replace(/\t/g," ")].filter((ch)=>ch===`
2255
+ `||ch.codePointAt(0)>=32&&ch!=="").join("")}function countPastedLines(text){return(String(text??"").match(/\n/g)??[]).length}function shouldCollapsePaste(text,{maxLines=PASTE_MAX_LINES,maxChars=PASTE_MAX_CHARS}={}){let value=String(text??"");return countPastedLines(value)>maxLines||value.length>maxChars}function formatPasteMarker(id,text){let lines=countPastedLines(text);if(lines>0)return`[Pasted text #${id} +${lines} lines]`;return`[Pasted text #${id} ${String(text??"").length} chars]`}function toPasteMap(pastes){if(pastes instanceof Map)return pastes;let map=new Map;for(let[id,text]of Object.entries(pastes??{}))map.set(Number(id),text);return map}function findPasteMarkers(text,pastes){let source=String(text??""),registry=toPasteMap(pastes);if(registry.size===0||!source.includes("[Pasted text #"))return[];let raw=[];for(let match of source.matchAll(PASTE_MARKER_REGEX)){let id=Number(match[1]);if(!registry.has(id))continue;raw.push({id,text:match[0],index:match.index,length:match[0].length})}if(raw.length===0)return[];let points=[...source],unitToPoint=new Map,unit=0;return points.forEach((ch,pointIndex)=>{unitToPoint.set(unit,pointIndex),unit+=ch.length}),unitToPoint.set(unit,points.length),raw.map((marker)=>({...marker,start:unitToPoint.get(marker.index),end:unitToPoint.get(marker.index+marker.length)}))}function expandPasteMarkers(text,pastes){let source=String(text??""),registry=toPasteMap(pastes),markers=findPasteMarkers(source,registry),result=source;for(let i=markers.length-1;i>=0;i--){let marker=markers[i];result=result.slice(0,marker.index)+registry.get(marker.id)+result.slice(marker.index+marker.length)}return result}function pruneOrphanPastes(text,pastes){let registry=toPasteMap(pastes);if(registry.size===0)return registry;let alive=new Set(findPasteMarkers(text,registry).map((marker)=>marker.id));if(alive.size===registry.size)return registry;let next=new Map;for(let[id,content]of registry)if(alive.has(id))next.set(id,content);return next}function insertTextAtCursor(chars,cursor,text){let at=Math.max(0,Math.min(chars.length,cursor)),inserted=[...String(text??"")];return{chars:[...chars.slice(0,at),...inserted,...chars.slice(at)],cursor:at+inserted.length}}function insertPastedText({chars,cursor,pastes,nextId,text,options}){let clean=normalizePastedText(text);if(!clean)return null;let registry=toPasteMap(pastes),at=Math.max(0,Math.min(chars.length,cursor)),collapsed=shouldCollapsePaste(clean,options),inserted=collapsed?[...formatPasteMarker(nextId,clean)]:[...clean],nextPastes=collapsed?new Map(registry).set(nextId,clean):registry;return{chars:[...chars.slice(0,at),...inserted,...chars.slice(at)],cursor:at+inserted.length,pastes:nextPastes,id:collapsed?nextId:null}}function stepCursor(chars,cursor,delta,pastes){let target=cursor+delta,clamped=Math.max(0,Math.min(chars.length,target)),marker=findPasteMarkers(chars.join(""),pastes).find((item)=>clamped>item.start&&clamped<item.end);if(!marker)return clamped;return delta<0?marker.start:marker.end}function deleteBeforeCursor(chars,cursor,pastes){if(cursor<=0)return null;let marker=findPasteMarkers(chars.join(""),pastes).find((item)=>item.end===cursor),from=marker?marker.start:cursor-1;return{chars:[...chars.slice(0,from),...chars.slice(cursor)],cursor:from}}function deleteAfterCursor(chars,cursor,pastes){if(cursor>=chars.length)return null;let marker=findPasteMarkers(chars.join(""),pastes).find((item)=>item.start===cursor),to=marker?marker.end:cursor+1;return{chars:[...chars.slice(0,cursor),...chars.slice(to)],cursor}}function segmentInput(chars,cursor,pastes){let clampedCursor=Math.max(0,Math.min(chars.length,cursor)),markers=findPasteMarkers(chars.join(""),pastes),cursorMarker=markers.find((item)=>clampedCursor>=item.start&&clampedCursor<item.end),cursorStart=cursorMarker?cursorMarker.start:clampedCursor,cursorEnd=cursorMarker?cursorMarker.end:clampedCursor+1,bounds=new Set([0,chars.length,cursorStart,Math.min(cursorEnd,chars.length)]);for(let marker of markers)bounds.add(marker.start),bounds.add(marker.end);let points=[...bounds].filter((n)=>n>=0&&n<=chars.length).sort((a,b)=>a-b),segments=[];for(let i=0;i<points.length-1;i++){let from=points[i],to=points[i+1];if(to<=from)continue;segments.push({text:chars.slice(from,to).join(""),marker:markers.some((marker)=>from>=marker.start&&to<=marker.end),cursor:from>=cursorStart&&to<=cursorEnd})}if(cursorStart>=chars.length)segments.push({text:" ",marker:!1,cursor:!0});return segments}function cursorText(segments){let text="";for(let segment of segments){if(segment.cursor){if(segment.marker)text+=segment.text;break}text+=segment.text}return text}var PASTE_MAX_CHARS=800,PASTE_MAX_LINES=0,MARKER_SOURCE,PASTE_MARKER_REGEX,PASTE_MARKER_SINGLE,ANSI_REGEX;var init_paste_block=__esm(()=>{init_markdown_width();MARKER_SOURCE=String.raw`\[Pasted text #(\d+)(?: \+(\d+) lines| (\d+) chars)?\]`,PASTE_MARKER_REGEX=new RegExp(MARKER_SOURCE,"g"),PASTE_MARKER_SINGLE=new RegExp(`^${MARKER_SOURCE}$`),ANSI_REGEX=/[\u001B\u009B][[\]()#;?]*(?:(?:\d{1,4}(?:;\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~])/g});function wrapDescription(text,width,maxLines){let source=String(text??"").replace(/\s+/g," ").trim();if(!source||width<=0)return[];let lines=[],line="";for(let word of source.split(" ")){if(!line)line=word;else if(line.length+1+word.length<=width)line=`${line} ${word}`;else lines.push(line),line=word;while(line.length>width)lines.push(line.slice(0,width)),line=line.slice(width);if(lines.length>maxLines)break}if(line)lines.push(line);if(lines.length<=maxLines)return lines;let kept=lines.slice(0,maxLines),last=kept[maxLines-1];return kept[maxLines-1]=last.length<width?`${last}…`:`${last.slice(0,Math.max(0,width-1)).trimEnd()}…`,kept}function packRows(costs,activeIndex,budget){if(costs.length===0)return{start:0,end:-1,used:0};let start=Math.min(Math.max(activeIndex,0),costs.length-1),end=start,used=costs[start],down=!0;for(;;){let canDown=end+1<costs.length&&used+costs[end+1]<=budget,canUp=start>0&&used+costs[start-1]<=budget;if(!canDown&&!canUp)break;if(down?canDown:!canUp)used+=costs[end+=1];else used+=costs[start-=1];down=!down}return{start,end,used}}function shortcutHelp(busy,canSteer){let col1=["! for shell mode","/ for commands","@ for file paths","shift + enter newline",busy?canSteer?"enter to steer":"enter to queue":"enter to send","tab to queue while running"],col2=["shift + tab to cycle mode","ctrl + m to switch model","ctrl + o to review","ctrl + q to review queue"],col3=["ctrl + l to clear screen","ctrl + c to clear input, then to interrupt","esc to cancel","↑/↓ for history"];return columns([{lines:col1.map(dim),width:22},{lines:col2.map(dim),width:32},{lines:col3.map(dim)}]).map((line)=>` ${line}`)}class Composer{options;value="";cursor=0;pastes=new Map;nextPasteId=1;helpOpen=!1;disabled=!1;locked=!1;busy=!1;canSteer=!1;providerCommands=[];selectedIndex=0;dismissed=!1;fileSuggestions=null;bashPathActive=!1;pathSuggestions=[];history;sessionKey=null;fileTokenKey=null;fileTimer=null;fileRequest=null;pathTokenKey=null;pathTimer=null;pathFetchSeq=0;constructor(options){this.options=options;this.history=options.inputHistory??getInputHistory()}derive(){let{value,cursor,disabled}=this,chars=[...value],cursorPos=chars.slice(0,cursor).join("").length,browsingHistory=this.history.isBrowsing(value,cursor),fileToken=disabled||browsingHistory?null:extractAtToken(value,cursorPos),isBashMode=!disabled&&isBashInput(value),pathToken=isBashMode&&this.bashPathActive?extractPathToken(value,cursorPos):null,tokenKey=this.dismissed?null:fileSuggestionKey(fileToken),fileQuery=pickerQueryState(this.fileSuggestions,tokenKey),isFileMode=Boolean(fileToken),isPathMode=!isFileMode&&Boolean(pathToken),localNames=new Set(SLASH_COMMANDS.map((cmd)=>cmd.name)),allCommands=[...SLASH_COMMANDS,...this.providerCommands.filter((cmd)=>cmd?.name&&!localNames.has(cmd.name)).map((cmd)=>({name:cmd.name,aliases:[],description:`${cmd.description??""}${cmd.input?.hint?` (${cmd.input.hint})`:""} [provider]`.trim()}))],commandSuggestions=this.dismissed||disabled||isFileMode||isPathMode||browsingHistory?[]:generateCommandSuggestions(value,allCommands),activeSuggestions=this.dismissed||disabled?[]:isFileMode?fileQuery.items:isPathMode?this.pathSuggestions:commandSuggestions,showSuggestions=activeSuggestions.length>0,activeIndex=Math.min(this.selectedIndex,Math.max(0,activeSuggestions.length-1));return{chars,cursorPos,fileToken,isBashMode,pathToken,tokenKey,fileQuery,isFileMode,isPathMode,activeSuggestions,showSuggestions,activeIndex,completionOpen:showSuggestions||fileQuery.pending}}get completionOpen(){return!this.disabled&&this.derive().completionOpen}syncEffects(d=this.derive()){if(!d.isBashMode&&this.bashPathActive)this.bashPathActive=!1,this.pathSuggestions=[];let pathKey=d.pathToken?`${d.pathToken.startPos}:${d.pathToken.query}`:null;if(pathKey!==this.pathTokenKey){if(this.pathTokenKey=pathKey,this.pathTimer)clearTimeout(this.pathTimer);if(this.pathTimer=null,pathKey==null)this.pathSuggestions=[];else{let seq=++this.pathFetchSeq,value=this.value,token=d.pathToken;this.pathTimer=setTimeout(()=>{generateBashSuggestions(value,token).then((items)=>{if(this.pathFetchSeq!==seq)return;this.pathSuggestions=items,this.options.onInvalidate()})},FILE_SUGGESTION_DEBOUNCE_MS)}}let fileKey=d.tokenKey==null?null:`${this.sessionKey}\x00${d.tokenKey}`;if(fileKey!==this.fileTokenKey){if(this.fileTokenKey=fileKey,this.fileTimer)clearTimeout(this.fileTimer);if(this.fileTimer=null,this.fileRequest?.cancel(),this.fileRequest=null,this.fileSuggestions=null,d.tokenKey!=null){let request=createPickerRequest(d.tokenKey,(result)=>{this.fileSuggestions=result,this.options.onInvalidate()});this.fileRequest=request;let query=d.fileToken.query;this.fileTimer=setTimeout(()=>{generateFileSuggestions(query).then(request.resolve,()=>request.resolve([]))},FILE_SUGGESTION_DEBOUNCE_MS)}}}snapshot(){return cloneInputSnapshot({value:this.value,cursor:this.cursor,pastes:this.pastes,nextPasteId:this.nextPasteId})}notify(){this.options.onSnapshotChange(this.snapshot())}replace(nextChars,nextCursor){this.value=nextChars.join(""),this.cursor=Math.max(0,Math.min(nextChars.length,nextCursor)),this.selectedIndex=0,this.dismissed=!1,this.pastes=pruneOrphanPastes(this.value,this.pastes),this.notify()}moveCursor(next){this.cursor=next,this.notify()}resetDraft(){this.value="",this.cursor=0,this.selectedIndex=0,this.dismissed=!1,this.fileSuggestions=null,this.bashPathActive=!1,this.pathSuggestions=[],this.pastes=new Map,this.nextPasteId=1}restore(sessionKey,snapshot){if(this.sessionKey===sessionKey)return;this.sessionKey=sessionKey;let restored=cloneInputSnapshot(snapshot??{value:""});this.value=restored.value,this.cursor=restored.cursor,this.pastes=restored.pastes,this.nextPasteId=restored.nextPasteId,this.selectedIndex=0,this.dismissed=!1,this.fileSuggestions=null,this.bashPathActive=!1,this.pathSuggestions=[],this.history.resetNavigation()}restoreSnapshot(snapshot){let restored=cloneInputSnapshot(snapshot??{value:""});this.value=restored.value,this.cursor=restored.cursor,this.pastes=restored.pastes,this.nextPasteId=restored.nextPasteId,this.selectedIndex=0,this.dismissed=!1,this.fileSuggestions=null,this.bashPathActive=!1,this.pathSuggestions=[],this.notify()}hasDraft(){return this.value!==""||this.pastes.size>0}clearDraft(){if(!this.hasDraft())return!1;return this.history.resetNavigation(),this.resetDraft(),this.notify(),!0}submit(text,intent="submit"){let display=String(text??""),submittedPastes=pruneOrphanPastes(display,this.pastes);this.history.record({value:display,cursor:[...display].length,pastes:submittedPastes,nextPasteId:this.nextPasteId});let expanded=expandPasteMarkers(display,submittedPastes);this.resetDraft(),this.notify(),this.options.onSubmit(expanded,expanded===display?void 0:display,{intent})}applyActiveFileSuggestion(activeIndex){let chars=[...this.value],pos=chars.slice(0,this.cursor).join("").length,token=extractAtToken(this.value,pos),suggestion=pickerQueryState(this.fileSuggestions,fileSuggestionKey(token)).items[activeIndex];if(!suggestion)return;let{nextChars,nextCursor}=applyFileSuggestion(chars,token,suggestion);this.fileSuggestions=null,this.replace(nextChars,nextCursor)}applyActivePathSuggestion(d){let suggestion=d.activeSuggestions[d.activeIndex],{nextChars,nextCursor}=applyPathSuggestion(d.chars,d.pathToken,suggestion);if(!suggestion.isDirectory)this.bashPathActive=!1,this.pathSuggestions=[];this.replace(nextChars,nextCursor)}triggerBashPathCompletion(){let value=this.value,chars=[...value],cursor=Math.max(0,Math.min(chars.length,this.cursor)),cursorPos=chars.slice(0,cursor).join("").length,token=extractPathToken(value,cursorPos),seq=++this.pathFetchSeq;generateBashSuggestions(value,token).then((items)=>{if(this.pathFetchSeq!==seq||this.value!==value)return;if(items.length===0)return;let only=items[0];if(items.length===1&&only.path+(only.isDirectory?"/":"")!==token.token){let{nextChars,nextCursor}=applyPathSuggestion(chars,token,only);if(this.replace(nextChars,nextCursor),only.isDirectory)this.bashPathActive=!0}else this.bashPathActive=!0,this.pathSuggestions=items;this.options.onInvalidate()})}insertPaste(text){let chars=[...this.value],result=insertPastedText({chars,cursor:Math.max(0,Math.min(chars.length,this.cursor)),pastes:this.pastes,nextId:this.nextPasteId,text});if(!result)return null;if(result.id!=null)this.nextPasteId=result.id+1;return this.pastes=result.pastes,this.replace(result.chars,result.cursor),this.value}onPaste(text){if(this.disabled||this.locked)return;this.insertPaste(text)}onKey(input,key){if(this.disabled||this.locked)return;let d=this.derive(),currentValue=this.value,chars=[...currentValue],cursor=Math.max(0,Math.min(chars.length,this.cursor));if(key.tab&&key.shift){this.options.onCycleMode();return}if(!key.ctrl&&!key.meta&&!key.tab&&currentValue===""&&input==="?"){this.helpOpen=!this.helpOpen;return}let helpWasOpen=this.helpOpen;if(this.helpOpen=!1,key.return&&(key.shift||key.meta)){let next=insertTextAtCursor(chars,cursor,`
2256
+ `);this.replace(next.chars,next.cursor);return}let currentPos=chars.slice(0,cursor).join("").length,currentFileToken=this.history.isBrowsing(currentValue,cursor)?null:extractAtToken(currentValue,currentPos);if(!this.dismissed&&(d.isFileMode||currentFileToken)){if(key.escape){this.dismissed=!0;return}if((pickerQueryState(this.fileSuggestions,fileSuggestionKey(currentFileToken)).pending||!currentFileToken)&&(key.tab||key.return||key.upArrow||key.downArrow))return}if(d.showSuggestions){let total=d.activeSuggestions.length;if(key.upArrow){this.selectedIndex=(d.activeIndex-1+total)%total;return}if(key.downArrow){this.selectedIndex=(d.activeIndex+1)%total;return}if(key.tab||key.return&&(d.isFileMode||d.isPathMode)){if(d.isFileMode)this.applyActiveFileSuggestion(d.activeIndex);else if(d.isPathMode)this.applyActivePathSuggestion(d);else{let name=d.activeSuggestions[d.activeIndex].name;this.replace([...`/${name} `],name.length+2)}return}if(key.return){this.submit(`/${d.activeSuggestions[d.activeIndex].name}`);return}if(key.escape){if(d.isPathMode){this.bashPathActive=!1,this.pathSuggestions=[];return}this.dismissed=!0;return}}if(key.return){if(helpWasOpen&&currentValue==="")return;this.submit(currentValue);return}if(key.leftArrow)return this.moveCursor(stepCursor(chars,cursor,-1,this.pastes));if(key.rightArrow)return this.moveCursor(stepCursor(chars,cursor,1,this.pastes));if(key.home)return this.moveCursor(0);if(key.end)return this.moveCursor(chars.length);if(key.backspace){let result=deleteBeforeCursor(chars,cursor,this.pastes);if(result)this.replace(result.chars,result.cursor);return}if(key.delete){let result=deleteAfterCursor(chars,cursor,this.pastes);if(result)this.replace(result.chars,result.cursor);return}if(key.ctrl){if(input==="a")this.moveCursor(0);if(input==="e")this.moveCursor(chars.length);if(input==="u")this.replace(chars.slice(cursor),0);if(input==="k")this.replace(chars.slice(0,cursor),cursor);return}if(key.upArrow){let snapshot=this.history.previous(this.snapshot());if(snapshot)this.restoreSnapshot(snapshot);return}if(key.downArrow){let snapshot=this.history.next();if(snapshot)this.restoreSnapshot(snapshot);return}if(key.tab){if(isBashInput(currentValue)&&!d.isFileMode)this.triggerBashPathCompletion();else if(submissionIntent({tab:!0,busy:this.busy,bash:isBashInput(currentValue)})&&currentValue.trim())this.submit(currentValue,"queue");return}if(key.escape||key.meta)return;if(key.pageUp||key.pageDown)return;if(!input)return;let shouldSubmit=/[\r\n]$/.test(input),body=input.replace(/[\r\n]+$/,"");if([...body].length>1&&shouldCollapsePaste(normalizePastedText(body))){let nextValue=this.insertPaste(body);if(shouldSubmit&&nextValue!=null)this.submit(nextValue);return}let text=body.replace(/[\r\n]+/g," ").replace(/[\u0000-\u001F\u007F]/g,""),next=[...chars.slice(0,cursor),...text,...chars.slice(cursor)];if(shouldSubmit){this.submit(next.join(""));return}this.replace(next,cursor+[...text].length)}render(width,rows){let d=this.derive();this.syncEffects(d);let accent=this.disabled?"gray":d.isBashMode?"magenta":"cyan",bodyWidth=Math.max(1,width-2),rule=style("─".repeat(width),{color:accent}),prompt=style(d.isBashMode?"! ":"❯ ",{color:accent}),lines=[rule],cursor=null;if(this.disabled)(this.value?wrap(this.value,bodyWidth).map(dim):[""]).forEach((row,index)=>lines.push((index===0?prompt:" ")+row));else{let displayChars=d.isBashMode?d.chars.slice(1):d.chars,displayCursor=d.isBashMode?Math.max(0,this.cursor-1):this.cursor,segments=segmentInput(displayChars,displayCursor,this.pastes),styled=segments.map((segment)=>segment.marker?style(segment.text,{color:"cyan",bold:!0,inverse:segment.cursor}):segment.text).join(""),fullText=segments.map((segment)=>segment.text).join("");if(wrap(styled,bodyWidth).forEach((row,index)=>lines.push((index===0?prompt:" ")+row)),!this.locked){let caret=caretPosition({x:0,y:0,width:bodyWidth},0,{text:cursorText(segments),fullText});cursor={row:1+caret.y,col:2+caret.x}}}lines.push(rule);let inputRows=lines.length;if(d.showSuggestions){let isPathLikeMode=d.isFileMode||d.isPathMode,nameColumnWidth=isPathLikeMode?0:Math.max(0,...d.activeSuggestions.map((s)=>s.displayText.length))+2,descriptionWidth=Math.max(MIN_DESCRIPTION_WIDTH,width-2-(nameColumnWidth+2)),commandRows=isPathLikeMode?[]:d.activeSuggestions.map((item)=>({item,lines:wrapDescription(item.description,descriptionWidth,COMMAND_DESCRIPTION_LINES)})),rowCosts=commandRows.map((row)=>Math.max(1,row.lines.length)),commandBudget=Math.min(COMMAND_SUGGESTION_LINES,rowCosts.reduce((sum,cost)=>sum+cost,0)),packed=packRows(rowCosts,d.activeIndex,commandBudget),viewport=completionViewport({index:d.activeIndex,total:d.activeSuggestions.length,rows,inputRows}),windowFrom=isPathLikeMode?viewport.start:packed.start,visible=isPathLikeMode?d.activeSuggestions.slice(viewport.start,viewport.end):commandRows.slice(packed.start,packed.end+1).map((row)=>row.item),fillerLines=isPathLikeMode?0:Math.max(0,commandBudget-packed.used),inner=Math.max(1,width-2);visible.forEach((item,index)=>{let active=windowFrom+index===d.activeIndex,rowStyle={color:active?"cyan":void 0,bold:active,dim:!active};if(isPathLikeMode){let detail=item.isCommand?"cmd":"",pathWidth=Math.max(0,width-4-(detail?detail.length+2:0)),text=`${active?"❯ ":" "}${truncatePathToCellWidth(item.displayText,pathWidth)}${detail?` ${detail}`:""}`;lines.push(` ${style(truncate4(text,inner),rowStyle)}`);return}let descLines=commandRows[windowFrom+index].lines,name=style(truncate4(`${active?"❯ ":" "}${item.displayText}`,nameColumnWidth+2),{color:active?"cyan":void 0,bold:active}),height=Math.max(1,descLines.length);for(let row=0;row<height;row+=1){let left=row===0?padEnd(name,nameColumnWidth+2):" ".repeat(nameColumnWidth+2),desc=descLines[row]?style(truncate4(descLines[row],Math.max(1,inner-nameColumnWidth-2)),rowStyle):"";lines.push(` ${left}${desc}`)}});for(let index=0;index<fillerLines;index+=1)lines.push("");let hint=isPathLikeMode?completionHint(Math.max(0,width-2),viewport,d.activeSuggestions.length):"Tab to complete · Enter to run · Esc to dismiss"+(d.activeSuggestions.length>visible.length?` · ${d.activeIndex+1}/${d.activeSuggestions.length}`:"");lines.push(` ${dim(truncate4(hint,inner))}`)}else if(d.fileQuery.pending)lines.push(` ${dim("Finding files… · Esc to dismiss")}`);else if(this.helpOpen)lines.push(...shortcutHelp(this.busy,this.canSteer));return{lines,cursor}}dispose(){if(this.fileTimer)clearTimeout(this.fileTimer);if(this.pathTimer)clearTimeout(this.pathTimer);this.fileRequest?.cancel()}}var COMMAND_SUGGESTION_LINES=10,COMMAND_DESCRIPTION_LINES=2,MIN_DESCRIPTION_WIDTH=20,FILE_SUGGESTION_DEBOUNCE_MS=50;var init_composer=__esm(()=>{init_commands();init_picker_completion();init_picker_rows();init_caret();init_file_suggestions();init_input_history();init_paste_block();init_bash();init_layout()});function isMcpCall(toolCall){return toolCall?.name==="mcp_call"}function permissionTitle(toolCall){if(isMcpCall(toolCall))return"MCP tool call";switch(toolCall?.kind){case"execute":return"Bash command";case"edit":return"Edit file";case"read":return"Read file";case"delete":return"Delete file";case"fetch":return"Fetch";case"plan":return"Plan";default:return toolCall?.title||"Tool call"}}function inputText(input){if(input==null)return"";try{return JSON.stringify(input,null,2)}catch{return String(input)}}function permissionReview(toolCall){if(isMcpCall(toolCall))return{diff:null,text:inputText(toolCall.rawInput)};let diff=extractToolDiff(toolCall);if(toolCall?.command)return{diff,text:String(toolCall.command)};let input=toolCall?.rawInput;if(input!=null&&typeof input==="object"){if(typeof input.plan==="string")return{diff,text:input.plan};let path=input.path??input.file_path??input.filePath??input.filename,body=input.patch??input.diff??input.content??input.new_content??input.newText;if(typeof body==="string")return{diff,text:`${path?`Path: ${path}
2312
2257
 
2313
- `:""}${body}`}}return{diff,text:inputText(input)}}var init_permission_review=__esm(()=>{init_tool_diff()});function windowStart(index,total,size){if(total<=size)return 0;return Math.max(0,Math.min(index-Math.floor(size/2),total-size))}function isPlanReview(toolCall){return toolCall?.kind==="plan"}function PermissionDialog({toolCall,items,escapeValue,onResolve}){let{rows=24,columns=80}=use_window_size_default(),[index,setIndex]=$useState(0),[scroll,setScroll]=$useState(0),{diff,text}=permissionReview(toolCall),rawReview=text.replace(/\r\n?/g,`
2258
+ `:""}${body}`}}return{diff,text:inputText(input)}}var init_permission_review=__esm(()=>{init_tool_diff()});function buildSetupItems(configuredIds,useColors=!0){let{items:configured}=parseStatusLineItems(configuredIds),enabled=new Set(configured),orderedIds=[...configured,...Array.from(STATUS_LINE_ITEMS.keys()).filter((id)=>!enabled.has(id))];return[{id:USE_COLORS_ID,label:"Use colors",description:"Apply colors to status line items",enabled:Boolean(useColors),orderable:!1,sectionBreakAfter:!0},...orderedIds.map((id)=>{let item=STATUS_LINE_ITEMS.get(id);return{id,label:item.label,enabled:enabled.has(id),orderable:!0}})]}function buildPreviewSegments(items,snapshot={},{useColors=!0}={}){let segments=[];for(let setupItem of Array.isArray(items)?items:[]){if(!setupItem?.enabled||setupItem.id===USE_COLORS_ID)continue;let item=STATUS_LINE_ITEMS.get(setupItem.id);if(!item)continue;let text=null;try{text=item.value(snapshot)}catch{text=null}let value=text==null||String(text).trim()===""?item.placeholder:String(text).trim();if(value==null||String(value).trim()==="")continue;let color=TONE_COLORS2[item.tone]??null;segments.push({id:item.id,text:String(value).trim(),color:useColors?color:null,dim:!useColors||color==null})}return segments}var USE_COLORS_ID="use-colors",TONE_COLORS2;var init_setup_items=__esm(()=>{init_items7();TONE_COLORS2={model:"yellow",dir:"cyan",state:"green",accent:"blue",dim:null}});function searchableText(item){return[item?.label,item?.right,item?.name,item?.groupName,item?.description,item?.value].filter((value)=>value!=null&&value!=="").join(" ")}function matchIndices(text,query){let source=String(text??""),needle=String(query??"");if(!needle)return[];let lowerSource=source.toLowerCase(),lowerNeedle=needle.toLowerCase(),indices=[],cursor=0;for(let ch of lowerNeedle){let hit=lowerSource.indexOf(ch,cursor);if(hit===-1)return null;indices.push(hit),cursor=hit+1}return indices}function matchScore(text,query){let source=String(text??"").toLowerCase(),needle=String(query??"").toLowerCase();if(!needle)return 0;let cursor=0,prevHit=-2,consecutive=0,maxConsecutive=0,firstPos=-1;for(let ch of needle){let hit=source.indexOf(ch,cursor);if(hit===-1)return null;if(firstPos===-1)firstPos=hit;if(consecutive=hit===prevHit+1?consecutive+1:1,consecutive>maxConsecutive)maxConsecutive=consecutive;prevHit=hit,cursor=hit+1}let gap=prevHit-firstPos+1-needle.length,score=0;if(score+=maxConsecutive*100,score-=firstPos,score-=gap*10,firstPos===0&&maxConsecutive===needle.length)score+=1000;return score}function filterItems(items,query){let list=Array.isArray(items)?items:[],trimmed=String(query??"").trim();if(!trimmed)return list;return list.map((item)=>({item,score:matchScore(searchableText(item),trimmed)})).filter((entry)=>entry.score!==null).sort((a,b)=>b.score-a.score).map((entry)=>entry.item)}function highlightSegments(text,query){let source=String(text??""),indices=matchIndices(source,query);if(!indices||indices.length===0)return source===""?[]:[{text:source,hit:!1}];let hits=new Set(indices),segments=[],position=0;for(let character of source){let hit=hits.has(position),last=segments[segments.length-1];if(last&&last.hit===hit)last.text+=character;else segments.push({text:character,hit});position+=character.length}return segments}function resolveField(field,context){return typeof field==="function"?field(context):field}function createFlowState(steps,initialContext={}){let list=Array.isArray(steps)?steps.filter(Boolean):[];return advancePastSkipped({steps:list,index:0,context:{...initialContext},done:!1},1)}function advancePastSkipped(state,direction){let{steps,context}=state,index=state.index;while(index>=0&&index<steps.length){let step=steps[index];if(!resolveField(step.skip,context))return{...state,index,done:!1};index+=direction}if(index>=steps.length)return{...state,index:steps.length,done:!0};let forward=0;while(forward<steps.length&&resolveField(steps[forward].skip,context))forward+=1;if(forward>=steps.length)return{...state,index:steps.length,done:!0};return{...state,index:forward,done:!1}}function currentStep(state){if(state.done)return null;return state.steps[state.index]??null}function stepView(state){let step=currentStep(state);if(!step)return null;let{context}=state;return{key:step.key,title:resolveField(step.title,context)??"",subtitle:resolveField(step.subtitle,context)??void 0,emptyText:resolveField(step.emptyText,context)??void 0,searchable:resolveField(step.searchable,context)??!0,items:resolveField(step.items,context)??[],selected:resolveField(step.preselect,context)??null,canGoBack:hasPreviousStep(state)}}function hasPreviousStep(state){for(let index=state.index-1;index>=0;index-=1)if(!resolveField(state.steps[index].skip,state.context))return!0;return!1}function selectValue(state,value){let step=currentStep(state);if(!step)return state;let context={...state.context,[step.key]:value};return advancePastSkipped({...state,context,index:state.index+1},1)}function goBack(state){if(!hasPreviousStep(state))return null;let previous=advancePastSkipped({...state,index:state.index-1,done:!1},-1),step=previous.steps[previous.index];if(!step)return null;let context={...previous.context};return delete context[step.key],{...previous,context}}function sanitizeInput(input){return String(input??"").replace(/[\r\n]+/g,"").replace(/[\u0000-\u001F\u007F]/g,"")}function isReservedKey(key){return Boolean(key.ctrl||key.meta||key.tab||key.pageUp||key.pageDown||key.leftArrow||key.rightArrow||key.home||key.end)}function pickerAction(input,key,{searchable=!0,hasQuery=!1}={}){if(key.escape)return hasQuery?{type:"clear-query"}:{type:"cancel"};if(key.return)return{type:"confirm"};if(key.upArrow)return{type:"move",delta:-1};if(key.downArrow)return{type:"move",delta:1};if(!searchable){if(input==="k")return{type:"move",delta:-1};if(input==="j")return{type:"move",delta:1};return{type:"none"}}if(key.backspace||key.delete)return{type:"backspace"};if(isReservedKey(key))return{type:"none"};let text=sanitizeInput(input);return text?{type:"append",text}:{type:"none"}}function footerHint({searchable=!0,canGoBack=!1}={}){let parts=[];if(searchable)parts.push("Type to filter");return parts.push("↑↓ to select","Enter to confirm"),parts.push(canGoBack?"Esc to go back":"Esc to cancel"),parts.join(" · ")}class Picker{options;query="";index;rows;constructor(options){this.options=options;this.rows=normalizeItems(options.items??[]),this.index=initialIndex(this.rows,options.selected??null)}setItems(items){this.options.items=items,this.rows=normalizeItems(items)}filtered(){return this.options.searchable===!1?this.rows:filterItems(this.rows,this.query)}clamped(filtered){return Math.max(0,Math.min(this.index,filtered.length-1))}onKey(input,key){let searchable=this.options.searchable!==!1,action=pickerAction(input,key,{searchable,hasQuery:this.query.length>0}),filtered=this.filtered(),clamped=this.clamped(filtered);switch(action.type){case"cancel":this.options.onCancel?.();return;case"clear-query":this.query="",this.index=0;return;case"confirm":{let row=filtered[clamped];if(!row)return;if(row.disabled){let next=moveIndex(filtered,clamped,1);if(next!==clamped&&!filtered[next]?.disabled)this.index=next;return}this.options.onSelect?.(row.source,row);return}case"move":if(filtered.length===0)return;this.index=moveIndex(filtered,clamped,action.delta);return;case"append":this.query+=action.text,this.index=0;return;case"backspace":if(this.query.length>0)this.query=[...this.query].slice(0,-1).join(""),this.index=0;return;default:}}onPaste(text){if(this.options.searchable===!1)return;let line=text.split(/\r?\n/)[0].replace(/[\u0000-\u001F\u007F]/g,"");if(!line)return;this.query+=line,this.index=0}render(width,rows){let{title,subtitle,color="cyan",searchable=!0,searchPlaceholder="Type to filter…",emptyText="No matching items",footerHint:footerHint2,canGoBack=!1,compactColumns=!1,embed=null,renderRight}=this.options,filtered=this.filtered(),clamped=this.clamped(filtered),windowRows=embed?embed.rows:rows,embedded=embed!=null,density=pickerDensity(windowRows),showTitle=!embedded&&density!=="minimal"&&Boolean(title),showSubtitle=density==="full"&&Boolean(subtitle),showSearch=searchable&&density!=="minimal",showHint=!embedded&&density==="full",spacious=density==="full",reservedRows=embedded?(showSubtitle?1:0)+(showSearch?spacious?2:1:0)+(spacious?1:0)+1:1+(showTitle?1:0)+(showSubtitle?1:0)+(showSearch?spacious?2:1:0)+(showHint?2:0)+2,viewport=pickerViewport({index:clamped,total:filtered.length,rows:windowRows,reservedRows,maxVisible:MAX_VISIBLE}),visible=filtered.slice(viewport.start,viewport.end),innerWidth=Math.max(embed?embed.columns:width,1),hint=footerHint2??footerHint({searchable,canGoBack}),view={lines:[],cursor:null},out=view.lines;if(showTitle)out.push(style(truncate4(title,innerWidth),{bold:!0,color}));if(showSubtitle){if(!embedded)out.push("");out.push(dim(truncate4(compactColumns?`${" ".repeat(MARKER_ACTIVE.length)}${subtitle}`:subtitle,innerWidth)))}if(showSearch){if(spacious)out.push("");let text=style("> ",{color})+(this.query?this.query:dim(searchPlaceholder));view.cursor={row:out.length,col:Math.min(stringWidth2(`> ${this.query}`),innerWidth)},out.push(truncate4(text,innerWidth))}if(spacious)out.push("");if(visible.forEach((row,offset)=>{let active=viewport.start+offset===viewport.index,marker=innerWidth>=2?active?MARKER_ACTIVE:MARKER_IDLE:active?"→":" ",right=renderRight?String(renderRight(row.source,row)??""):row.right,normalLayout=splitRowWidth(innerWidth,marker.length,right),compactLayout=compactRowWidth(innerWidth,marker.length,row.label),compact=compactColumns&&Boolean(right)&&compactLayout.showRight,layout=compact?compactLayout:normalLayout,groupText=row.groupName&&!layout.showRight?` [${row.groupName}]`:"",currentText=row.current?" (current)":"",suffixWidth=stringWidth2(groupText)+stringWidth2(currentText),label=truncateToCellWidth(row.label,Math.max(0,layout.leftWidth-suffixWidth)),shownRight=layout.showRight?truncateToCellWidth(right,layout.rightWidth):"",gap=!layout.showRight?0:compact?1:Math.max(1,innerWidth-marker.length-stringWidth2(label)-suffixWidth-stringWidth2(shownRight)),accent=active&&!row.disabled?color:void 0,text=style(marker,{color:accent});if(row.disabled)text+=label;else{let segments=searchable&&this.query?highlightSegments(label,this.query):[{text:label,hit:!1}];text+=segments.map((segment)=>style(segment.text,{color:segment.hit||active?color:void 0,bold:segment.hit,underline:segment.hit})).join("")}if(groupText)text+=style(groupText,{dim:!active});if(currentText)text+=style(currentText,{dim:!active});if(layout.showRight)text+=" ".repeat(gap)+style(shownRight,{color:accent,dim:!active});out.push(truncate4(row.disabled?dim(text):text,innerWidth))}),filtered.length===0)out.push(dim(emptyText));if(viewport.above>0||viewport.below>0)out.push(dim(` (${viewport.index+1}/${filtered.length})`));if(showHint)out.push(""),out.push(dim(truncate4(hint,innerWidth)));return view}}class PickerFlow{onComplete;onCancel;color;state;picker=null;stepKey=null;finished=!1;constructor(steps,initialContext,onComplete,onCancel,color="cyan"){this.onComplete=onComplete;this.onCancel=onCancel;this.color=color;if(this.state=createFlowState(steps,initialContext),stepView(this.state)==null)queueMicrotask(()=>this.complete(this.state.context))}complete(context){if(this.finished)return;this.finished=!0,this.onComplete(context)}current(){let view=stepView(this.state);if(view==null)return null;if(this.picker&&this.stepKey===`${this.state.index}:${view.key}`)return this.picker;return this.stepKey=`${this.state.index}:${view.key}`,this.picker=new Picker({title:view.title,subtitle:view.subtitle,items:view.items,selected:view.selected,color:this.color,searchable:view.searchable,emptyText:view.emptyText,canGoBack:view.canGoBack,onSelect:(item)=>{let next=selectValue(this.state,item?.value??null);if(next.done){this.complete(next.context);return}this.state=next},onCancel:()=>{let previous=goBack(this.state);if(previous==null){this.onCancel();return}this.state=previous}}),this.picker}onKey(input,key){this.current()?.onKey(input,key)}onPaste(text){this.current()?.onPaste(text)}render(width,rows){return this.current()?.render(width,rows)??{lines:[]}}}var MAX_VISIBLE=10,MARKER_ACTIVE="→ ",MARKER_IDLE=" ";var init_picker=__esm(()=>{init_markdown_width();init_picker_rows();init_layout()});function cleanInput(input){return String(input??"").replace(/[\r\n]+/g,"").replace(/[\u0000-\u001F\u007F]/g,"")}function popChar(text){return[...text].slice(0,-1).join("")}class InputPrompt{options;text;constructor(options){this.options=options;this.text=options.value??""}onKey(input,key){if(key.escape)return this.options.onCancel();if(key.return)return this.options.onSubmit(this.text);if(key.backspace||key.delete){this.text=popChar(this.text);return}if(key.ctrl||key.meta)return;if(input)this.text+=cleanInput(input)}onPaste(text){this.text+=cleanInput(text.split(/\r?\n/)[0])}render(width){let inner=Math.max(1,width-4),line=`> ${this.options.secret?"•".repeat([...this.text].length):this.text}`,content=[style(truncate4(this.options.title,inner),{bold:!0,color:"cyan"}),truncate4(line,inner),dim(truncate4(this.options.hint??"Enter to save · Esc to go back",inner))];return{lines:border(content,width,{color:"cyan",paddingX:1}),cursor:{row:2,col:2+Math.min(stringWidth2(line),inner)}}}}function windowStart(index,total,size){if(total<=size)return 0;return Math.max(0,Math.min(index-Math.floor(size/2),total-size))}class PermissionDialog{options;index=0;scroll=0;lastPageSize=MAX_BODY_LINES;lastMaxScroll=0;constructor(options){this.options=options}onKey(input,key){let{items,escapeValue,onResolve}=this.options;if(key.escape)return onResolve(escapeValue??null);if(key.pageUp){this.scroll=Math.max(0,this.scroll-this.lastPageSize);return}if(key.pageDown){this.scroll=Math.min(this.lastMaxScroll,this.scroll+this.lastPageSize);return}if(items.length===0)return;if(key.upArrow||input==="k"){this.index=(this.index-1+items.length)%items.length;return}if(key.downArrow||input==="j"){this.index=(this.index+1)%items.length;return}let digit=Number.parseInt(input,10);if(Number.isInteger(digit)&&digit>=1&&digit<=items.length)return onResolve(items[digit-1].value);if(key.return)onResolve(items[this.index].value)}render(width,rows){let{toolCall,items}=this.options,{diff,text}=permissionReview(toolCall),rawReview=text.replace(/\r\n?/g,`
2314
2259
  `),allLines=rawReview?rawReview.split(`
2315
- `):[],planReview=isPlanReview(toolCall),expanded=planReview||Boolean(diff)||toolCall?.kind==="edit"||toolCall?.kind==="delete"||allLines.length>MAX_BODY_LINES,bodyBudget=expanded?Math.max(MAX_BODY_LINES,rows-12):MAX_BODY_LINES,diffWidth=Math.max(1,columns-6),diffPageRows=Math.max(1,bodyBudget-2),diffRows=diff?diffLineCount(diff,diffWidth):0,pageSize=diff?diffPageRows:bodyBudget,maxScroll=Math.max(0,(diff?diffRows:allLines.length)-pageSize),command=allLines.slice(scroll,scroll+bodyBudget);use_input_default((input,key)=>{if(key.escape){onResolve(escapeValue??null);return}if(key.pageUp){setScroll((value)=>Math.max(0,value-pageSize));return}if(key.pageDown){setScroll((value)=>Math.min(maxScroll,value+pageSize));return}if(items.length===0)return;if(key.upArrow||input==="k"){setIndex((value)=>(value-1+items.length)%items.length);return}if(key.downArrow||input==="j"){setIndex((value)=>(value+1)%items.length);return}let digit=Number.parseInt(input,10);if(Number.isInteger(digit)&&digit>=1&&digit<=items.length){onResolve(items[digit-1].value);return}if(key.return)onResolve(items[index].value)});let title=permissionTitle(toolCall),accent=toolCall?.kind==="delete"?"red":planReview?"cyan":"yellow",visibleSize=Math.min(items.length,MAX_VISIBLE_OPTIONS),visibleStart=windowStart(index,items.length,visibleSize),visibleItems=items.slice(visibleStart,visibleStart+visibleSize);return $jsxs(Box_default,{flexDirection:"column",borderStyle:expanded?"single":"round",borderLeft:!expanded,borderRight:!expanded,borderColor:accent,paddingX:1,children:[$jsx(Text,{bold:!0,color:accent,children:planReview?"Ready to code?":expanded?`Review ${title}`:title}),diff?$jsx(Box_default,{flexDirection:"column",marginTop:1,paddingLeft:2,children:$jsx(DiffView,{diff,mode:"full",offset:scroll,maxLines:diffPageRows,width:diffWidth,showHeader:!1})}):command.length>0?$jsxs(Box_default,{flexDirection:"column",marginTop:1,paddingLeft:2,children:[command.map((line,offset)=>$jsx(Text,{color:toolCall?.kind==="delete"?"red":void 0,children:line||" "},`${scroll}-${offset}`)),maxScroll>0?$jsxs(Text,{dimColor:!0,children:["… lines ",scroll+1,"-",Math.min(allLines.length,scroll+bodyBudget)," of ",allLines.length]}):null]}):null,toolCall?.title&&toolCall.title!==title?$jsx(Box_default,{paddingLeft:2,children:$jsx(Text,{dimColor:!0,children:toolCall.title})}):null,$jsx(Box_default,{marginTop:1,children:$jsx(Text,{children:planReview?"Would you like to proceed with this plan?":"Do you want to proceed?"})}),visibleItems.map((item,offset)=>{let itemIndex=visibleStart+offset,active=itemIndex===index;return $jsxs(Text,{color:active?accent:void 0,bold:active,children:[active?"❯ ":" ",itemIndex+1,". ",item.label]},item.value??offset)}),items.length===0?$jsx(Text,{dimColor:!0,children:"(No options available · Esc to cancel)"}):null,$jsx(Box_default,{marginTop:1,children:$jsxs(Text,{dimColor:!0,children:["↑↓ to select · Enter to confirm · Esc to cancel",expanded&&maxScroll>0?" · PgUp/PgDn review":"",items.length>visibleSize?` · ${index+1}/${items.length}`:""]})})]})}var MAX_BODY_LINES=5,MAX_VISIBLE_OPTIONS=3;var init_PermissionDialog=__esm(async()=>{init_react_production();init_permission_review();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_DiffView()])});function PlanReviewDialog({plan,path,onResolve}){let[revising,setRevising]=$useState(!1);if(revising)return $jsx(InputPrompt,{title:"Plan changes",hint:"Enter to send feedback · Esc to return",onSubmit:(feedback)=>onResolve({action:"revise",feedback}),onCancel:()=>setRevising(!1)});return $jsx(PermissionDialog,{toolCall:{kind:"plan",title:path,rawInput:{plan}},items:ITEMS,escapeValue:"dismiss",onResolve:(value)=>{if(value==="revise")setRevising(!0);else onResolve({action:value??"dismiss"})}})}var ITEMS;var init_PlanReviewDialog=__esm(async()=>{init_react_production();init_react_jsx_runtime_production();await __promiseAll([init_InputPrompt(),init_PermissionDialog()]);ITEMS=[{value:"approve",label:"Approve and implement"},{value:"revise",label:"Request changes"},{value:"reject",label:"Reject and exit Plan Mode"}]});function hasQuestionPreview(question){return!question?.multiSelect&&question?.options?.some((option)=>option.preview)}function visibleQuestionOptions(question){let options=Array.isArray(question?.options)?question.options:[];if(hasQuestionPreview(question))return options;return[...options,{label:"Other",description:"Type a custom answer",value:"__other__"}]}function initialQuestionState(question){return{focused:0,selected:question.multiSelect?[]:null,custom:"",notes:""}}function createUserQuestionState(questions){return{index:0,view:"question",editing:null,reviewIndex:0,questions:Object.fromEntries(questions.map((question)=>[question.id,initialQuestionState(question)]))}}function updateCurrent(state,questions,update){let question=questions[state.index];if(!question)return state;return{...state,questions:{...state.questions,[question.id]:update(state.questions[question.id]??initialQuestionState(question),question)}}}function userQuestionReducer(state,action,questions){let lastTab=questions.length;switch(action.type){case"switch-tab":{let tab=Math.max(0,Math.min(lastTab,action.index)),onReview=tab===lastTab;return{...state,index:Math.min(tab,Math.max(0,questions.length-1)),view:onReview?"review":"question",editing:null}}case"step-tab":{let next=((state.view==="review"?lastTab:state.index)+action.delta+lastTab+1)%(lastTab+1);return userQuestionReducer(state,{type:"switch-tab",index:next},questions)}case"move-option":return updateCurrent(state,questions,(current,question)=>{let count=visibleQuestionOptions(question).length+(hasQuestionPreview(question)?1:0);if(count===0)return current;return{...current,focused:(current.focused+action.delta+count)%count}});case"select-single":return updateCurrent(state,questions,(current)=>({...current,selected:action.value}));case"toggle-multi":return updateCurrent(state,questions,(current)=>{let selected=Array.isArray(current.selected)?current.selected:[];return{...current,selected:selected.includes(action.value)?selected.filter((value)=>value!==action.value):[...selected,action.value]}});case"begin-edit":return{...state,editing:action.field};case"end-edit":return{...state,editing:null};case"set-text":return updateCurrent(state,questions,(current)=>({...current,[action.field]:action.value}));case"move-review":return{...state,reviewIndex:(state.reviewIndex+action.delta+2)%2};default:return state}}function answerForQuestion(question,state){if(!state)return"";if(question.multiSelect)return(Array.isArray(state.selected)?state.selected:[]).map((value)=>value==="__other__"?state.custom.trim():value).filter(Boolean).join(", ");if(state.selected==="__other__")return state.custom.trim();return typeof state.selected==="string"?state.selected:""}function annotationEntry(preview,notes){if(!preview&&!notes)return null;return{...preview?{preview}:{},...notes?{notes}:{}}}function buildUserQuestionResult(questions,state){let answers={},annotations={};for(let question of questions){let questionState=state.questions[question.id],answer=answerForQuestion(question,questionState);if(answer)answers[question.id]=answer;let selectedOption=!question.multiSelect?question.options.find((option)=>option.label===questionState?.selected):null,annotation=annotationEntry(selectedOption?.preview,questionState?.notes?.trim());if(annotation)annotations[question.id]=annotation}return{answers,...Object.keys(annotations).length>0?{annotations}:{}}}function allQuestionsAnswered(questions,state){return questions.every((question)=>Boolean(answerForQuestion(question,state.questions[question.id])))}var OTHER_VALUE="__other__";var init_user_question_state=()=>{};function cleanInput(input){return String(input??"").replace(/[\r\n]+/g,"").replace(/[\u0000-\u001F\u007F]/g,"")}function Navigation({questions,state,columns,showReview}){if(questions.length===1&&!showReview)return null;let tabCount=questions.length+(showReview?1:0),labelWidth=Math.max(3,Math.floor((columns-8)/Math.max(1,tabCount))-4);return $jsxs(Box_default,{marginBottom:1,children:[$jsx(Text,{dimColor:state.view==="question"&&state.index===0,children:"← "}),questions.map((question,index)=>{let active=state.view==="question"&&state.index===index,answered=Boolean(answerForQuestion(question,state.questions[question.id])),label=truncateToCellWidth(question.header||`Q${index+1}`,labelWidth);return $jsx(Text,{inverse:active,color:active?"cyan":void 0,children:` ${answered?"[x]":"[ ]"} ${label} `},question.id)}),showReview?$jsx(Text,{inverse:state.view==="review",color:state.view==="review"?"cyan":void 0,children:" ✓ Submit "}):null,$jsx(Text,{dimColor:state.view==="review",children:" →"})]})}function OptionRow({option,index,active,selected,multiSelect,editing,input}){let choice=multiSelect?`[${selected?"x":" "}]`:selected?"●":"○",other=option.value===OTHER_VALUE;return $jsxs(Box_default,{flexDirection:"column",children:[$jsxs(Text,{color:active?"cyan":void 0,children:[active?"❯":" "," ",index+1,". ",choice," ",option.label,other&&(editing||input)?$jsxs(Text,{children:[" ",input||"Type something…"]}):null]}),option.description?$jsx(Box_default,{paddingLeft:5,children:$jsx(Text,{dimColor:!0,children:option.description})}):null]})}function ReviewView({questions,state}){let complete=allQuestionsAnswered(questions,state);return $jsxs(Box_default,{flexDirection:"column",children:[$jsx(Text,{bold:!0,children:"Review your answers"}),!complete?$jsx(Text,{color:"yellow",children:"! You have not answered all questions"}):null,$jsx(Box_default,{flexDirection:"column",marginTop:1,children:questions.map((question)=>{let answer=answerForQuestion(question,state.questions[question.id]);return $jsxs(Box_default,{flexDirection:"column",marginBottom:1,children:[$jsxs(Text,{children:["• ",question.question]}),$jsx(Box_default,{paddingLeft:2,children:$jsxs(Text,{color:answer?"green":void 0,dimColor:!answer,children:["→ ",answer||"Not answered"]})})]},question.id)})}),$jsx(Text,{dimColor:!0,children:"Ready to submit your answers?"}),$jsxs(Text,{color:state.reviewIndex===0?"cyan":void 0,children:[state.reviewIndex===0?"❯":" "," 1. Submit answers"]}),$jsxs(Text,{color:state.reviewIndex===1?"cyan":void 0,children:[state.reviewIndex===1?"❯":" "," 2. Cancel"]})]})}function UserQuestionDialog({questions,onResolve}){let safeQuestions=Array.isArray(questions)?questions:[],{rows=24,columns=80}=use_window_size_default(),[state,dispatch]=$useReducer((current,action)=>userQuestionReducer(current,action,safeQuestions),safeQuestions,createUserQuestionState),inputRef=$useRef(null),question=safeQuestions[state.index],questionState=question?state.questions[question.id]:null,previewQuestion=hasQuestionPreview(question),options=$useMemo(()=>visibleQuestionOptions(question),[question]),showReview=safeQuestions.length>1||safeQuestions.some((item)=>item.multiSelect),editingValue=state.editing&&questionState?questionState[state.editing]:"",editingPrefix=state.editing==="notes"?"Notes: ":`${questionState?.focused+1}. ○ Other `;useInputCursor(inputRef,state.editing?stringWidth2(editingPrefix+editingValue):null,{truncate:!0});let reduce=(action)=>userQuestionReducer(state,action,safeQuestions),submit=(nextState=state)=>onResolve(buildUserQuestionResult(safeQuestions,nextState)),advance=(nextState)=>{if(!showReview&&safeQuestions.length===1)submit(nextState);else if(state.index+1<safeQuestions.length)dispatch({type:"switch-tab",index:state.index+1});else dispatch({type:"switch-tab",index:safeQuestions.length})};if(use_input_default((input,key)=>{if(!question&&state.view!=="review")return;if(state.editing){if(key.escape)return dispatch({type:"end-edit"});if(key.return){let next=reduce({type:"end-edit"});if(dispatch({type:"end-edit"}),state.editing==="custom"&&!question.multiSelect&&questionState.custom.trim())advance(next);return}if(key.backspace||key.delete){dispatch({type:"set-text",field:state.editing,value:[...editingValue].slice(0,-1).join("")});return}if(key.ctrl||key.meta||key.tab)return;let text=cleanInput(input);if(text)dispatch({type:"set-text",field:state.editing,value:editingValue+text});return}if(key.escape)return onResolve(null);if(key.tab||key.leftArrow||key.rightArrow){if(!showReview)return;let delta=key.leftArrow||key.tab&&key.shift?-1:1;dispatch({type:"step-tab",delta});return}if(state.view==="review"){if(key.upArrow||input==="k")return dispatch({type:"move-review",delta:-1});if(key.downArrow||input==="j")return dispatch({type:"move-review",delta:1});if(input==="1")return submit();if(input==="2")return onResolve(null);if(key.return)return state.reviewIndex===0?submit():onResolve(null);return}if(key.upArrow||input==="k")return dispatch({type:"move-option",delta:-1});if(key.downArrow||input==="j")return dispatch({type:"move-option",delta:1});let focusedOption=options[questionState.focused],notesFocused=previewQuestion&&questionState.focused===options.length,activate=(option)=>{if(!option)return;let value=option.value??option.label;if(question.multiSelect){let wasSelected=questionState.selected.includes(value);if(dispatch({type:"toggle-multi",value}),value===OTHER_VALUE&&!wasSelected)dispatch({type:"begin-edit",field:"custom"});return}let selectedState=reduce({type:"select-single",value});if(dispatch({type:"select-single",value}),value===OTHER_VALUE)dispatch({type:"begin-edit",field:"custom"});else advance(selectedState)},digit=Number.parseInt(input,10);if(Number.isInteger(digit)&&digit>=1&&digit<=options.length)return activate(options[digit-1]);if(input===" "&&question.multiSelect)return activate(focusedOption);if(key.return){if(notesFocused)return dispatch({type:"begin-edit",field:"notes"});if(question.multiSelect&&focusedOption?.value===OTHER_VALUE){if(!questionState.selected.includes(OTHER_VALUE))dispatch({type:"toggle-multi",value:OTHER_VALUE});return dispatch({type:"begin-edit",field:"custom"})}if(question.multiSelect)return advance(state);return activate(focusedOption)}}),!question)return null;let previewOption=previewQuestion?options[questionState.focused]??null:null,maxPreviewLines=Math.max(3,rows-15),previewLines=previewOption?.preview?renderMarkdown(previewOption.preview).split(`
2316
- `):["No preview available"],shownPreview=previewLines.slice(0,maxPreviewLines).join(`
2317
- `),previewTruncated=previewLines.length>maxPreviewLines,sideBySide=previewQuestion&&columns>=72,hint=()=>{if(state.editing)return"Enter to save · Esc to return";if(state.view==="review")return"↑↓ to select · Enter to confirm · Tab/Shift+Tab to revisit · Esc to cancel";if(question.multiSelect)return"↑↓ to navigate · Space to toggle · Enter for next · Tab/Shift+Tab to navigate · Esc to cancel";return`${safeQuestions.length===1?"↑↓":"Tab/Shift+Tab · ↑↓"} to navigate · Enter to select · Esc to cancel`};return $jsxs(Box_default,{flexDirection:"column",borderTop:!0,borderColor:"gray",children:[$jsx(Navigation,{questions:safeQuestions,state,columns,showReview}),state.view==="review"?$jsx(ReviewView,{questions:safeQuestions,state}):$jsxs($Fragment,{children:[$jsx(Text,{bold:!0,children:question.question}),$jsxs(Box_default,{flexDirection:sideBySide?"row":"column",gap:sideBySide?2:0,marginTop:1,children:[$jsxs(Box_default,{flexDirection:"column",width:sideBySide?Math.min(34,Math.floor(columns*0.4)):void 0,children:[options.map((option,index)=>{let value=option.value??option.label,selected=question.multiSelect?questionState.selected.includes(value):questionState.selected===value;return $jsx(Box_default,{ref:state.editing==="custom"&&index===questionState.focused?inputRef:void 0,children:$jsx(OptionRow,{option,index,active:questionState.focused===index,selected,multiSelect:question.multiSelect,editing:state.editing==="custom"&&index===questionState.focused,input:questionState.custom})},value)}),previewQuestion?$jsx(Box_default,{ref:state.editing==="notes"?inputRef:void 0,marginTop:1,children:$jsxs(Text,{color:questionState.focused===options.length?"cyan":void 0,children:[questionState.focused===options.length?"❯":" "," Notes: ",questionState.notes||$jsx(Text,{dimColor:!0,children:"optional"})]})}):null]}),previewQuestion?$jsxs(Box_default,{flexDirection:"column",borderStyle:"single",borderColor:"gray",paddingX:1,marginTop:sideBySide?0:1,flexGrow:1,children:[$jsx(Text,{children:shownPreview}),previewTruncated?$jsx(Text,{dimColor:!0,children:"… preview truncated"}):null]}):null]})]}),$jsx(Box_default,{marginTop:1,children:$jsx(Text,{dimColor:!0,children:hint()})})]})}var init_UserQuestionDialog=__esm(async()=>{init_react_production();init_markdown();init_markdown_width();init_picker_rows();init_user_question_state();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_use_input_cursor()])});function searchableText(item){return[item?.label,item?.right,item?.name,item?.groupName,item?.description,item?.value].filter((value)=>value!=null&&value!=="").join(" ")}function matchIndices(text,query){let source=String(text??""),needle=String(query??"");if(!needle)return[];let lowerSource=source.toLowerCase(),lowerNeedle=needle.toLowerCase(),indices=[],cursor=0;for(let ch of lowerNeedle){let hit=lowerSource.indexOf(ch,cursor);if(hit===-1)return null;indices.push(hit),cursor=hit+1}return indices}function matchScore(text,query){let source=String(text??"").toLowerCase(),needle=String(query??"").toLowerCase();if(!needle)return 0;let cursor=0,prevHit=-2,consecutive=0,maxConsecutive=0,firstPos=-1;for(let ch of needle){let hit=source.indexOf(ch,cursor);if(hit===-1)return null;if(firstPos===-1)firstPos=hit;if(consecutive=hit===prevHit+1?consecutive+1:1,consecutive>maxConsecutive)maxConsecutive=consecutive;prevHit=hit,cursor=hit+1}let gap=prevHit-firstPos+1-needle.length,score=0;if(score+=maxConsecutive*100,score-=firstPos,score-=gap*10,firstPos===0&&maxConsecutive===needle.length)score+=1000;return score}function filterItems(items,query){let list=Array.isArray(items)?items:[],trimmed=String(query??"").trim();if(!trimmed)return list;return list.map((item)=>({item,score:matchScore(searchableText(item),trimmed)})).filter((entry)=>entry.score!==null).sort((a,b)=>b.score-a.score).map((entry)=>entry.item)}function highlightSegments(text,query){let source=String(text??""),indices=matchIndices(source,query);if(!indices||indices.length===0)return source===""?[]:[{text:source,hit:!1}];let hits=new Set(indices),segments=[],position=0;for(let character of source){let hit=hits.has(position),last=segments[segments.length-1];if(last&&last.hit===hit)last.text+=character;else segments.push({text:character,hit});position+=character.length}return segments}function sanitizeInput(input){return String(input??"").replace(/[\r\n]+/g,"").replace(/[\u0000-\u001F\u007F]/g,"")}function isReservedKey(key){return Boolean(key.ctrl||key.meta||key.tab||key.pageUp||key.pageDown||key.leftArrow||key.rightArrow||key.home||key.end)}function pickerAction(input,key,{searchable=!0,hasQuery=!1}={}){if(key.escape)return hasQuery?{type:"clear-query"}:{type:"cancel"};if(key.return)return{type:"confirm"};if(key.upArrow)return{type:"move",delta:-1};if(key.downArrow)return{type:"move",delta:1};if(!searchable){if(input==="k")return{type:"move",delta:-1};if(input==="j")return{type:"move",delta:1};return{type:"none"}}if(key.backspace||key.delete)return{type:"backspace"};if(isReservedKey(key))return{type:"none"};let text=sanitizeInput(input);return text?{type:"append",text}:{type:"none"}}function footerHint({searchable=!0,canGoBack=!1}={}){let parts=[];if(searchable)parts.push("Type to filter");return parts.push("↑↓ to select","Enter to confirm"),parts.push(canGoBack?"Esc to go back":"Esc to cancel"),parts.join(" · ")}function Picker({title,subtitle,items=[],selected=null,color="cyan",searchable=!0,searchPlaceholder="Type to filter…",emptyText="No matching items",footerHint:footerHint2,canGoBack=!1,compactColumns=!1,active=!0,embed=null,renderRight,onSelect,onCancel}){let{stdout}=useStdout(),columns=stdout?.columns??80,rows=normalizeItems(items),[query,setQuery]=$useState(""),[index,setIndex]=$useState(()=>initialIndex(rows,selected)),filtered=$useMemo(()=>searchable?filterItems(rows,query):rows,[rows,query,searchable]),clamped=Math.max(0,Math.min(index,filtered.length-1)),setQueryAndReset=(next)=>{setQuery(next),setIndex(0)};use_input_default((input,key)=>{let action=pickerAction(input,key,{searchable,hasQuery:query.length>0});switch(action.type){case"cancel":onCancel?.();return;case"clear-query":setQueryAndReset("");return;case"confirm":{let row=filtered[clamped];if(!row)return;if(row.disabled){let next=moveIndex(filtered,clamped,1);if(next!==clamped&&!filtered[next]?.disabled)setIndex(next);return}onSelect?.(row.source,row);return}case"move":if(filtered.length===0)return;setIndex(moveIndex(filtered,clamped,action.delta));return;case"append":setQueryAndReset(query+action.text);return;case"backspace":if(query.length>0)setQueryAndReset([...query].slice(0,-1).join(""));return;default:}},{isActive:active});let windowRows=embed?embed.rows:stdout?.rows,embedded=embed!=null,density=pickerDensity(windowRows),showTitle=!embedded&&density!=="minimal"&&Boolean(title),showSubtitle=density==="full"&&Boolean(subtitle),showSearch=searchable&&density!=="minimal",showHint=!embedded&&density==="full",spacious=density==="full",searchRef=$useRef(null);useInputCursor(searchRef,active&&showSearch?stringWidth2("> "+query):null,{truncate:!0});let reservedRows=embedded?(showSubtitle?1:0)+(showSearch?spacious?2:1:0)+(spacious?1:0)+1:1+(showTitle?1:0)+(showSubtitle?1:0)+(showSearch?spacious?2:1:0)+(showHint?2:0)+2,viewport=pickerViewport({index:clamped,total:filtered.length,rows:windowRows,reservedRows,maxVisible:MAX_VISIBLE}),visible=filtered.slice(viewport.start,viewport.end),innerWidth=Math.max(embed?embed.columns:columns,1),hint=footerHint2??footerHint({searchable,canGoBack}),renderLabel=(row,active)=>(searchable&&query?highlightSegments(row.label,query):[{text:row.label,hit:!1}]).map((segment,offset)=>$jsx(Text,{color:segment.hit||active?color:void 0,bold:segment.hit,underline:segment.hit,children:segment.text},`${row.key}-seg-${offset}`)),renderRow=(row,offset)=>{let active=viewport.start+offset===viewport.index,marker=innerWidth>=2?active?MARKER_ACTIVE:MARKER_IDLE:active?"→":" ",right=renderRight?String(renderRight(row.source,row)??""):row.right,normalLayout=splitRowWidth(innerWidth,marker.length,right),compactLayout=compactRowWidth(innerWidth,marker.length,row.label),compact=compactColumns&&Boolean(right)&&compactLayout.showRight,layout=compact?compactLayout:normalLayout,groupText=row.groupName&&!layout.showRight?` [${row.groupName}]`:"",currentText=row.current?" (current)":"",suffixWidth=stringWidth2(groupText)+stringWidth2(currentText),label=truncateToCellWidth(row.label,Math.max(0,layout.leftWidth-suffixWidth)),shownRight=layout.showRight?truncateToCellWidth(right,layout.rightWidth):"",gap=!layout.showRight?0:compact?1:Math.max(1,innerWidth-marker.length-stringWidth2(label)-suffixWidth-stringWidth2(shownRight));return $jsxs(Text,{dimColor:row.disabled,wrap:"truncate",children:[$jsx(Text,{color:active&&!row.disabled?color:void 0,children:marker}),row.disabled?label:renderLabel({...row,label},active),groupText?$jsx(Text,{dimColor:!active,children:groupText}):null,currentText?$jsx(Text,{dimColor:!active,children:currentText}):null,layout.showRight?$jsxs($Fragment,{children:[" ".repeat(gap),$jsx(Text,{color:active&&!row.disabled?color:void 0,dimColor:!active,children:shownRight})]}):null]},row.key)};return $jsxs(Box_default,{flexDirection:"column",children:[showTitle?$jsx(Text,{bold:!0,color,children:title}):null,showSubtitle?$jsx(Box_default,{marginTop:embedded?0:1,children:$jsx(Text,{dimColor:!0,wrap:"truncate-end",children:compactColumns?`${" ".repeat(MARKER_ACTIVE.length)}${subtitle}`:subtitle})}):null,showSearch?$jsx(Box_default,{marginTop:spacious?1:0,ref:searchRef,children:$jsxs(Text,{wrap:"truncate",children:[$jsx(Text,{color,children:"> "}),query?$jsx(Text,{children:query}):$jsx(Text,{dimColor:!0,children:searchPlaceholder})]})}):null,$jsxs(Box_default,{flexDirection:"column",marginTop:spacious?1:0,children:[visible.map(renderRow),filtered.length===0?$jsx(Text,{dimColor:!0,children:emptyText}):null,viewport.above>0||viewport.below>0?$jsx(Text,{dimColor:!0,children:` (${viewport.index+1}/${filtered.length})`}):null]}),showHint?$jsx(Box_default,{marginTop:1,children:$jsx(Text,{dimColor:!0,wrap:"truncate",children:hint})}):null]})}var MAX_VISIBLE=10,MARKER_ACTIVE="→ ",MARKER_IDLE=" ";var init_Picker=__esm(async()=>{init_react_production();init_markdown_width();init_picker_rows();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_use_input_cursor()])});function resolveField(field,context){return typeof field==="function"?field(context):field}function createFlowState(steps,initialContext={}){let list=Array.isArray(steps)?steps.filter(Boolean):[];return advancePastSkipped({steps:list,index:0,context:{...initialContext},done:!1},1)}function advancePastSkipped(state,direction){let{steps,context}=state,index=state.index;while(index>=0&&index<steps.length){let step=steps[index];if(!resolveField(step.skip,context))return{...state,index,done:!1};index+=direction}if(index>=steps.length)return{...state,index:steps.length,done:!0};let forward=0;while(forward<steps.length&&resolveField(steps[forward].skip,context))forward+=1;if(forward>=steps.length)return{...state,index:steps.length,done:!0};return{...state,index:forward,done:!1}}function currentStep(state){if(state.done)return null;return state.steps[state.index]??null}function stepView(state){let step=currentStep(state);if(!step)return null;let{context}=state;return{key:step.key,title:resolveField(step.title,context)??"",subtitle:resolveField(step.subtitle,context)??void 0,emptyText:resolveField(step.emptyText,context)??void 0,searchable:resolveField(step.searchable,context)??!0,items:resolveField(step.items,context)??[],selected:resolveField(step.preselect,context)??null,canGoBack:hasPreviousStep(state)}}function hasPreviousStep(state){for(let index=state.index-1;index>=0;index-=1)if(!resolveField(state.steps[index].skip,state.context))return!0;return!1}function selectValue(state,value){let step=currentStep(state);if(!step)return state;let context={...state.context,[step.key]:value};return advancePastSkipped({...state,context,index:state.index+1},1)}function goBack(state){if(!hasPreviousStep(state))return null;let previous=advancePastSkipped({...state,index:state.index-1,done:!1},-1),step=previous.steps[previous.index];if(!step)return null;let context={...previous.context};return delete context[step.key],{...previous,context}}function PickerFlow({steps,initialContext,color="cyan",onComplete,onCancel}){let[state,setState]=$useState(()=>createFlowState(steps,initialContext)),view=stepView(state),finished=view==null;if($useEffect(()=>{if(finished)onComplete?.(state.context)},[finished]),finished)return null;let handleSelect=(item)=>{let next=selectValue(state,item?.value??null);if(next.done){onComplete?.(next.context);return}setState(next)},handleCancel=()=>{let previous=goBack(state);if(previous==null){onCancel?.();return}setState(previous)};return $jsx(Picker,{title:view.title,subtitle:view.subtitle,items:view.items,selected:view.selected,color,searchable:view.searchable,emptyText:view.emptyText,canGoBack:view.canGoBack,onSelect:handleSelect,onCancel:handleCancel},view.key)}var init_PickerFlow=__esm(async()=>{init_react_production();init_react_jsx_runtime_production();await init_Picker()});function ConfigPanel({options=[],focusId=null,switching=null,onChange,onCancel}){let[pickingId,setPickingId]=$useState(null),listed=options.filter((option)=>option?.id),picking=pickingId?listed.find((option)=>option.id===pickingId):null,valuePicker=picking?$jsx(Picker,{title:picking.name??picking.id,items:configChoices(picking).map((choice)=>({value:choice.value,label:choice.groupName?`${choice.groupName} / ${choice.name??choice.value}`:String(choice.name??choice.value),current:Boolean(choice.current)})),emptyText:"No matching values",canGoBack:!0,onSelect:(item)=>{if(setPickingId(null),item?.value!=null&&item.value!==picking.currentValue)onChange?.(picking,item.value)},onCancel:()=>setPickingId(null)},`config-value-${picking.id}`):null,activate=(option)=>{if(switching||!option||isConfigOptionLocked(option))return;if(configChoices(option).length===2){let next=toggleConfigValue(option);if(next!=null&&next!==option.currentValue)onChange?.(option,next);return}setPickingId(option.id)};return $jsxs($Fragment,{children:[$jsx(Box_default,{display:picking?"none":"flex",flexDirection:"column",children:$jsx(Picker,{title:"Config",subtitle:switching||void 0,active:!picking,items:listed.map((option)=>{let display=configDisplayValue(option);return{value:option.id,label:option.name??option.id,right:display,description:[option.category??"",display].filter(Boolean).join(" "),disabled:isConfigOptionLocked(option)}}),selected:focusId==null?null:Math.max(0,listed.findIndex((option)=>option.id===focusId)),emptyText:"No matching settings",onSelect:(item)=>activate(listed.find((option)=>option.id===item?.value)),onCancel:()=>onCancel?.()})}),valuePicker]})}var init_ConfigPanel=__esm(async()=>{init_react_production();init_config_options();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_Picker()])});function goalIndicator(snapshot,{useColors=!0}={}){if(snapshot==null||typeof snapshot.status!=="string")return null;let status=snapshot.status.trim();if(status.length===0)return null;let elapsed=Number.isFinite(snapshot.wallClockMs)?Math.max(0,snapshot.wallClockMs):0,color=GOAL_STATUS_COLORS[status]??null;return{mark:GOAL_INDICATOR_MARK,text:`${GOAL_INDICATOR_MARK} /goal ${status} (${formatElapsed(elapsed)})`,color:useColors?color:null,dim:!useColors}}var GOAL_INDICATOR_MARK="◎",GOAL_STATUS_COLORS;var init_goal_indicator=__esm(()=>{init_goal();GOAL_STATUS_COLORS={pending:"yellow",active:"cyan",pausing:"yellow",paused:"yellow",blocked:"red",complete:"green"}});function buildStatusLineSegments(ids,snapshot={},{useColors=!0}={}){let{items,invalid}=parseStatusLineItems(ids),segments=[];for(let id of items){let item=STATUS_LINE_ITEMS.get(id);if(!item)continue;let text=null;try{text=item.value(snapshot)}catch{text=null}if(text==null)continue;let value=String(text).trim();if(value.length===0)continue;segments.push({id,text:value,color:useColors?TONE_COLORS[item.tone]??null:null,dim:!useColors||TONE_COLORS[item.tone]==null})}return{segments,invalid}}var STATUS_LINE_SEPARATOR=" · ",TONE_COLORS;var init_render2=__esm(()=>{init_items7();TONE_COLORS={model:"yellow",dir:"cyan",state:"green",accent:"blue",dim:null}});function StatusBar({status,connectionStage,agentBin,busy,cancelling,switching,exitConfirming,statusLineItems,statusLineUseColors=!0,statusLineSnapshot=null,goal=null,inputHint=null,hidden=!1}){let connecting=status==="connecting",spinner=useSpinner(connecting||switching!=null),content;if(exitConfirming)content=$jsx(Text,{color:"yellow",children:"Press Ctrl+C again to exit"});else if(switching)content=$jsxs(Text,{color:"cyan",children:[spinner," ",switching]});else if(connecting)content=$jsxs(Text,{color:"cyan",children:[spinner," ",connectionStage??`Connecting to ${agentBin} ACP…`]});else if(status==="failed")content=$jsx(Text,{color:"red",children:"Disconnected · restart miro to retry · Ctrl+C twice to exit"});else if(cancelling)content=$jsx(Text,{color:"yellow",children:"Interrupting…"});else if(hidden)return null;else{if(statusLineItems?.length===0)return null;if(inputHint)return $jsx(Box_default,{paddingX:1,children:$jsx(Text,{dimColor:!0,wrap:"truncate",children:inputHint})});let{segments}=buildStatusLineSegments(statusLineItems??DEFAULT_STATUS_LINE_ITEMS,statusLineSnapshot??{},{useColors:statusLineUseColors});if(segments.length===0)return null;let indicator=goalIndicator(goal,{useColors:statusLineUseColors});return $jsxs(Box_default,{paddingX:1,justifyContent:"space-between",children:[$jsx(Box_default,{flexShrink:1,children:$jsx(Text,{wrap:"truncate",children:segments.map((segment,index)=>$jsxs(Text,{children:[index>0?$jsx(Text,{dimColor:!0,children:STATUS_LINE_SEPARATOR}):null,$jsx(Text,{color:busy||segment.color==null?void 0:segment.color,dimColor:busy||segment.dim,children:segment.text})]},segment.id))})}),indicator?$jsx(Box_default,{flexShrink:0,marginLeft:2,children:$jsx(Text,{color:indicator.color,dimColor:indicator.dim,wrap:"truncate",children:indicator.text})}):null]})}return $jsx(Box_default,{paddingX:1,children:$jsx(Text,{wrap:"truncate",children:content})})}var init_StatusBar=__esm(async()=>{init_use_spinner();init_settings_file();init_goal_indicator();init_render2();init_react_jsx_runtime_production();await init_build4()});function buildSetupItems(configuredIds,useColors=!0){let{items:configured}=parseStatusLineItems(configuredIds),enabled=new Set(configured),orderedIds=[...configured,...Array.from(STATUS_LINE_ITEMS.keys()).filter((id)=>!enabled.has(id))];return[{id:USE_COLORS_ID,label:"Use colors",description:"Apply colors to status line items",enabled:Boolean(useColors),orderable:!1,sectionBreakAfter:!0},...orderedIds.map((id)=>{let item=STATUS_LINE_ITEMS.get(id);return{id,label:item.label,enabled:enabled.has(id),orderable:!0}})]}function buildPreviewSegments(items,snapshot={},{useColors=!0}={}){let segments=[];for(let setupItem of Array.isArray(items)?items:[]){if(!setupItem?.enabled||setupItem.id===USE_COLORS_ID)continue;let item=STATUS_LINE_ITEMS.get(setupItem.id);if(!item)continue;let text=null;try{text=item.value(snapshot)}catch{text=null}let value=text==null||String(text).trim()===""?item.placeholder:String(text).trim();if(value==null||String(value).trim()==="")continue;let color=TONE_COLORS2[item.tone]??null;segments.push({id:item.id,text:String(value).trim(),color:useColors?color:null,dim:!useColors||color==null})}return segments}var USE_COLORS_ID="use-colors",TONE_COLORS2;var init_setup_items=__esm(()=>{init_items7();TONE_COLORS2={model:"yellow",dir:"cyan",state:"green",accent:"blue",dim:null}});function cleanItems(items){return(Array.isArray(items)?items:[]).map((item)=>({...item,enabled:Boolean(item.enabled),orderable:item.orderable!==!1}))}function searchableText2(item){return[item.id,item.name,item.label,item.description].filter((value)=>value!=null).join(" ").toLowerCase()}function filterMultiSelectItems(items,query){let needle=String(query??"").trim().toLowerCase();if(!needle)return items;return items.filter((item)=>searchableText2(item).includes(needle))}function createMultiSelectState(items){let normalized=cleanItems(items);return{items:normalized,query:"",selectedId:normalized[0]?.id??null}}function selectedVisibleIndex(state,visible){let index=visible.findIndex((item)=>item.id===state.selectedId);return index<0?0:index}function multiSelectReducer(state,action){switch(action.type){case"move-cursor":{let visible=filterMultiSelectItems(state.items,state.query);if(visible.length===0)return state;let next=(selectedVisibleIndex(state,visible)+action.delta+visible.length)%visible.length;return{...state,selectedId:visible[next].id}}case"toggle":{if(action.id==null)return state;return{...state,items:state.items.map((item)=>item.id===action.id?{...item,enabled:!item.enabled}:item)}}case"reorder":{if(state.query||action.id==null)return state;let index=state.items.findIndex((item)=>item.id===action.id),target=index+action.delta;if(index<0||target<0||target>=state.items.length)return state;if(state.items[index].orderable===!1||state.items[target].orderable===!1)return state;let items=[...state.items];return[items[index],items[target]]=[items[target],items[index]],{...state,items}}case"set-query":{let query=action.query,visible=filterMultiSelectItems(state.items,query);return{...state,query,selectedId:visible[0]?.id??null}}default:return state}}function multiSelectConfirmation(state){let items=state.items.map((item)=>({...item}));return{items,useColors:Boolean(items.find((item)=>item.id==="use-colors")?.enabled)}}function windowStart2(index,total,size){if(total<=size)return 0;return Math.max(0,Math.min(index-Math.floor(size/2),total-size))}function sanitizeInput2(input){return String(input??"").replace(/[\r\n]+/g,"").replace(/[\u0000-\u001F\u007F]/g,"")}function itemName(item){if(item.name!=null)return String(item.name);if(item.id==="use-colors")return"Use colors";return String(item.id??"")}function itemDescription(item){if(item.description!=null)return String(item.description);if(item.label!=null&&String(item.label)!==itemName(item))return String(item.label);return""}function previewSegments(preview){if(Array.isArray(preview))return preview;if(Array.isArray(preview?.segments))return preview.segments;return null}function MultiSelectPicker({title,subtitle,items=[],columns=80,renderPreview,onConfirm,onCancel}){let[state,dispatch]=$useReducer(multiSelectReducer,items,createMultiSelectState),visibleItems=filterMultiSelectItems(state.items,state.query),index=selectedVisibleIndex(state,visibleItems),selected=visibleItems[index]??null,useColors=Boolean(state.items.find((item)=>item.id==="use-colors")?.enabled),queryRef=$useRef(null);useInputCursor(queryRef,stringWidth2(state.query),{truncate:!0}),use_input_default((input,key)=>{if(key.escape){if(state.query)dispatch({type:"set-query",query:""});else onCancel();return}if(key.return){onConfirm(multiSelectConfirmation(state));return}if(key.upArrow){dispatch({type:"move-cursor",delta:-1});return}if(key.downArrow){dispatch({type:"move-cursor",delta:1});return}if(input===" "){if(selected)dispatch({type:"toggle",id:selected.id});return}if(key.leftArrow||key.ctrl&&input==="h"){if(selected)dispatch({type:"reorder",id:selected.id,delta:-1});return}if(key.rightArrow||key.ctrl&&input==="l"){if(selected)dispatch({type:"reorder",id:selected.id,delta:1});return}if(key.backspace||key.delete){dispatch({type:"set-query",query:[...state.query].slice(0,-1).join("")});return}if(key.ctrl||key.meta||key.tab||key.pageUp||key.pageDown)return;if(key.home||key.end)return;let text=sanitizeInput2(input);if(text)dispatch({type:"set-query",query:state.query+text})});let size=Math.min(visibleItems.length,MULTI_SELECT_MAX_VISIBLE),start=windowStart2(index,visibleItems.length,size),visible=visibleItems.slice(start,start+size),above=start,below=Math.max(0,visibleItems.length-start-size),preview=renderPreview?.(state.items,{useColors}),segments=previewSegments(preview),hasSegments=segments&&segments.length>0,hasCustomPreview=segments==null&&preview!=null&&preview!=="",innerWidth=Math.max(24,columns-4);return $jsxs(Box_default,{flexDirection:"column",children:[$jsx(Text,{inverse:!0,bold:!0,children:` ${title} `}),subtitle?$jsx(Text,{dimColor:!0,children:subtitle}):null,$jsx(Box_default,{marginTop:1,borderStyle:"single",borderColor:state.query?"cyan":"gray",paddingX:1,children:$jsx(Box_default,{ref:queryRef,children:$jsx(Text,{wrap:"truncate",children:state.query||$jsx(Text,{dimColor:!0,children:"Type to search..."})})})}),$jsxs(Box_default,{flexDirection:"column",marginTop:1,children:[above>0?$jsx(Text,{dimColor:!0,children:`↑ ${above} more above`}):null,visible.map((item,offset)=>{let active=start+offset===index,description=itemDescription(item);return $jsxs(Box_default,{flexDirection:"column",children:[$jsxs(Text,{wrap:"truncate",children:[$jsxs(Text,{color:active?"cyan":void 0,bold:active,children:[active?"> ":" ","[",item.enabled?"x":" ","] ",itemName(item)]}),description?$jsxs(Text,{dimColor:!0,children:[" ",description]}):null]}),item.sectionBreakAfter||item.section_break_after?$jsxs(Text,{dimColor:!0,children:[" ","─".repeat(Math.max(1,innerWidth-2))]}):null]},item.id??`${start}-${offset}`)}),below>0?$jsx(Text,{dimColor:!0,children:`↓ ${below} more below`}):null,visibleItems.length===0?$jsx(Text,{dimColor:!0,children:"No matching items"}):null]}),$jsx(Box_default,{marginTop:1,children:$jsx(Text,{wrap:"truncate",dimColor:!useColors||!hasSegments&&!hasCustomPreview,children:hasSegments?segments.map((segment,segmentIndex)=>$jsxs(Text,{children:[segmentIndex>0?$jsx(Text,{dimColor:!0,children:PREVIEW_SEPARATOR}):null,$jsx(Text,{color:useColors?segment.color:void 0,dimColor:!useColors||segment.dim,children:segment.text})]},segment.id??segmentIndex)):hasCustomPreview?preview:$jsx(Text,{dimColor:!0,children:"Status line hidden"})})}),$jsx(Box_default,{marginTop:1,children:$jsx(Text,{dimColor:!0,children:"Space to toggle · ←/→ to move · Enter to save · Esc to cancel · type to search"})})]})}var MULTI_SELECT_MAX_VISIBLE=10,PREVIEW_SEPARATOR=" · ";var init_MultiSelectPicker=__esm(async()=>{init_react_production();init_markdown_width();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_use_input_cursor()])});function StatusLineSetup({configuredIds,useColors,snapshot,onConfirm,onCancel}){let{stdout}=useStdout(),columns=stdout?.columns??80,items=buildSetupItems(configuredIds,useColors);return $jsx(Box_default,{flexDirection:"column",paddingX:1,children:$jsx(MultiSelectPicker,{title:"Configure Status Line",subtitle:"Select which items to display in the status line.",items,columns,renderPreview:(nextItems,options)=>buildPreviewSegments(nextItems,snapshot,{useColors:options?.useColors??useColors}),onConfirm,onCancel})})}var init_StatusLineSetup=__esm(async()=>{init_setup_items();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_MultiSelectPicker()])});function frameBodyRows(rows){return Math.max(3,rows-FRAME_CHROME_ROWS)}function ReviewFrame({label,footer,rows,children}){return $jsxs(Box_default,{flexDirection:"column",height:rows,children:[$jsx(Box_default,{borderStyle:"single",borderColor:"cyan",borderTop:!1,borderLeft:!1,borderRight:!1,paddingX:1,children:$jsxs(Text,{wrap:"truncate-end",children:[$jsx(Text,{bold:!0,inverse:!0,color:"cyan",children:"Review"}),label?$jsxs($Fragment,{children:[$jsx(Text,{dimColor:!0,children:" · "}),$jsx(Text,{bold:!0,children:label})]}):null]})}),$jsx(Box_default,{flexDirection:"column",height:frameBodyRows(rows),paddingX:FRAME_BODY_PADDING_X,overflow:"hidden",children}),$jsx(Box_default,{borderStyle:"single",borderColor:"gray",borderLeft:!1,borderRight:!1,paddingX:1,children:$jsx(Text,{dimColor:!0,wrap:"truncate-end",children:footer})})]})}function detailLines(item,width){let status=item.status??"unknown",duration=item.elapsed==null?null:formatDuration(item.elapsed),rows=[{kind:"status",status,text:`Status: ${status}${duration?` · ${duration}`:""}`}],sections=[["input","Input",item.detail?.input],["output","Output",item.detail?.output],["locations","Locations",item.detail?.locations]];for(let[section,title,text]of sections){if(!text)continue;rows.push({kind:"blank",text:""},{kind:"section",section,text:title});for(let line of String(text).split(`
2318
- `)){let wrapped=wrapVisualRows(line,Math.max(1,width-2));for(let part of wrapped)rows.push({kind:"content",section,text:part})}}if(sections.every(([,,text])=>!text))for(let line of item.preview?.lines??[])for(let part of wrapVisualRows(line,Math.max(1,width-2)))rows.push({kind:"content",section:"output",text:part});return rows}function subagentLines(item,width,{includeTools=!0}={}){let subagent=item?.subagent??{},request=subagent.request??{},duration=item?.elapsed==null?null:formatDuration(item.elapsed),rows=[{kind:"status",status:item?.status??"unknown",text:`Status: ${item?.status??"unknown"}${duration?` · ${duration}`:""}`}],addSection=(section,title,value)=>{if(value==null||String(value).length===0)return;rows.push({kind:"blank",text:""},{kind:"section",section,text:title});for(let line of String(value).split(`
2260
+ `):[],planReview=toolCall?.kind==="plan",expanded=planReview||Boolean(diff)||toolCall?.kind==="edit"||toolCall?.kind==="delete"||allLines.length>MAX_BODY_LINES,bodyBudget=expanded?Math.max(MAX_BODY_LINES,rows-12):MAX_BODY_LINES,diffWidth=Math.max(1,width-6),diffPageRows=Math.max(1,bodyBudget-2),diffRows=diff?diffLineCount(diff,diffWidth):0,pageSize=diff?diffPageRows:bodyBudget,maxScroll=Math.max(0,(diff?diffRows:allLines.length)-pageSize);this.lastPageSize=pageSize,this.lastMaxScroll=maxScroll,this.scroll=Math.min(this.scroll,maxScroll);let command=allLines.slice(this.scroll,this.scroll+bodyBudget),title=permissionTitle(toolCall),accent=toolCall?.kind==="delete"?"red":planReview?"cyan":"yellow",visibleSize=Math.min(items.length,MAX_VISIBLE_OPTIONS),visibleStart=windowStart(this.index,items.length,visibleSize),visibleItems=items.slice(visibleStart,visibleStart+visibleSize),sides=expanded?{left:!1,right:!1}:{},inner=Math.max(1,width-2-(expanded?0:2)),content=[style(truncate4(planReview?"Ready to code?":expanded?`Review ${title}`:title,inner),{bold:!0,color:accent})];if(diff){content.push("");for(let line of renderDiff(diff,{mode:"full",offset:this.scroll,maxLines:diffPageRows,width:diffWidth,showHeader:!1}))content.push(` ${line}`)}else if(command.length>0){content.push("");for(let line of command)content.push(` ${style(truncate4(line||" ",Math.max(1,inner-2)),{color:toolCall?.kind==="delete"?"red":void 0})}`);if(maxScroll>0)content.push(` ${dim(`… lines ${this.scroll+1}-${Math.min(allLines.length,this.scroll+bodyBudget)} of ${allLines.length}`)}`)}if(toolCall?.title&&toolCall.title!==title)content.push(` ${dim(truncate4(toolCall.title,Math.max(1,inner-2)))}`);if(content.push(""),content.push(planReview?"Would you like to proceed with this plan?":"Do you want to proceed?"),visibleItems.forEach((item,offset)=>{let itemIndex=visibleStart+offset,active=itemIndex===this.index;content.push(style(`${active?"❯ ":" "}${itemIndex+1}. ${item.label}`,{color:active?accent:void 0,bold:active}))}),items.length===0)content.push(dim("(No options available · Esc to cancel)"));return content.push(""),content.push(dim("↑↓ to select · Enter to confirm · Esc to cancel"+(expanded&&maxScroll>0?" · PgUp/PgDn review":"")+(items.length>visibleSize?` · ${this.index+1}/${items.length}`:""))),{lines:border(content,width,{style:expanded?"single":"round",color:accent,sides,paddingX:1}),cursor:null}}}class PlanReviewDialog{options;revising=null;dialog;constructor(options){this.options=options;this.dialog=new PermissionDialog({toolCall:{kind:"plan",title:options.path,rawInput:{plan:options.plan}},items:PLAN_ITEMS,escapeValue:"dismiss",onResolve:(value)=>{if(value==="revise")this.revising=new InputPrompt({title:"Plan changes",hint:"Enter to send feedback · Esc to return",onSubmit:(feedback)=>this.options.onResolve({action:"revise",feedback}),onCancel:()=>{this.revising=null}});else this.options.onResolve({action:value??"dismiss"})}})}onKey(input,key){(this.revising??this.dialog).onKey(input,key)}onPaste(text){this.revising?.onPaste(text)}render(width,rows){return(this.revising??this.dialog).render(width,rows)}}class ConfigPanel{options;list;valuePicker=null;constructor(options){this.options=options;let listed=this.listed();this.list=new Picker({title:"Config",items:this.listItems(listed),selected:options.focusId==null?null:Math.max(0,listed.findIndex((option)=>option.id===options.focusId)),emptyText:"No matching settings",onSelect:(item)=>this.activate(this.listed().find((option)=>option.id===item?.value)),onCancel:()=>this.options.onCancel()})}listed(){return this.options.getOptions().filter((option)=>option?.id)}listItems(listed){return listed.map((option)=>{let display=configDisplayValue(option);return{value:option.id,label:option.name??option.id,right:display,description:[option.category??"",display].filter(Boolean).join(" "),disabled:isConfigOptionLocked(option)}})}activate(option){if(useStore.getState().switching||!option||isConfigOptionLocked(option))return;let choices=configChoices(option);if(choices.length===2){let next=toggleConfigValue(option);if(next!=null&&next!==option.currentValue)this.options.onChange(option,next);return}this.valuePicker=new Picker({title:option.name??option.id,items:choices.map((choice)=>({value:choice.value,label:choice.groupName?`${choice.groupName} / ${choice.name??choice.value}`:String(choice.name??choice.value),current:Boolean(choice.current)})),emptyText:"No matching values",canGoBack:!0,onSelect:(item)=>{if(this.valuePicker=null,item?.value!=null&&item.value!==option.currentValue)this.options.onChange(option,item.value)},onCancel:()=>{this.valuePicker=null}})}onKey(input,key){(this.valuePicker??this.list).onKey(input,key)}onPaste(text){(this.valuePicker??this.list).onPaste(text)}render(width,rows){if(this.valuePicker)return this.valuePicker.render(width,rows);return this.list.setItems(this.listItems(this.listed())),this.list.options.subtitle=useStore.getState().switching||void 0,this.list.render(width,rows)}}function oneLine(item){return String(item.display??item.text??"").replace(/\s+/g," ").trim()||"(empty)"}class QueueEditor{options;index=0;draft=null;constructor(options){this.options=options}sync(){let{queuedInputs:items,pendingInputs:pending}=useStore.getState();if(items.length===0&&pending.length===0){queueMicrotask(()=>this.options.onClose());return}if(items.length===0)this.index=0;else if(this.index>=items.length)this.index=items.length-1}onKey(input,key){let store=useStore.getState(),items=store.queuedInputs;if(this.draft!=null){if(key.escape){this.draft=null;return}if(key.return){if(this.draft.trim())store.updateQueuedInput(this.index,this.draft);this.draft=null;return}if(key.backspace||key.delete){this.draft=popChar(this.draft);return}if(key.ctrl||key.meta||!input)return;this.draft+=input.replace(/[\r\n]+/g," ");return}if(key.escape||key.ctrl&&input==="q")return this.options.onClose();if(input==="r"&&store.queuePaused)return this.options.onResume();if(!items.length)return;if(key.upArrow&&key.shift){store.moveQueuedInput(this.index,-1),this.index=Math.max(0,this.index-1);return}if(key.downArrow&&key.shift){store.moveQueuedInput(this.index,1),this.index=Math.min(items.length-1,this.index+1);return}if(key.upArrow){this.index=(this.index-1+items.length)%items.length;return}if(key.downArrow){this.index=(this.index+1)%items.length;return}if(key.return||input==="e"){this.draft=items[this.index]?.text??"";return}if(input==="d"){store.removeQueuedInput(this.index),this.sync();return}if(input==="x")store.clearQueuedInputs(),this.sync()}onPaste(text){if(this.draft!=null)this.draft+=text.replace(/[\r\n]+/g," ")}render(width,rows){this.sync();let{queuedInputs:items,pendingInputs:pending,queuePaused:paused}=useStore.getState(),inner=Math.max(1,width-2),pad=(line)=>` ${truncate4(line,inner)}`,rule=dim("─".repeat(width)),maxVisible=Math.max(3,rows-7-Math.min(pending.length+1,4)),start=Math.max(0,Math.min(this.index-Math.floor(maxVisible/2),items.length-maxVisible)),body=[],cursor=null;if(pending.length)body.push(pad(dim("Steering waiting for the current response and tools (read only)")));for(let item of pending.slice(0,3))body.push(pad(style(oneLine(item),{color:"cyan"})));if(items.slice(start,start+maxVisible).forEach((item,offset)=>{let itemIndex=start+offset,active=itemIndex===this.index;body.push(pad(style(`${active?"❯ ":" "}${itemIndex+1}. ${oneLine(item)}`,{color:active?"cyan":void 0,bold:active})))}),this.draft!=null){body.push("");let box=border([dim("Edit message"),truncate4(this.draft,Math.max(1,inner-4))],inner,{color:"cyan",paddingX:1});cursor={row:body.length+2,col:3+Math.min(stringWidth2(this.draft),Math.max(1,inner-4))},body.push(...box.map((line)=>` ${line}`))}let header=[rule,pad(style("Queued messages",{bold:!0,color:"cyan"})+dim(` · ${items.length}`)),rule],footerText=this.draft!=null?"Enter save · Esc cancel edit":`${paused?"r resume sending · ":""}↑↓ select · Shift+↑↓ reorder · Enter/e edit · d delete · x clear · Ctrl+Q/Esc close`,footer=[rule,pad(dim(footerText)),rule],bodyRows=Math.max(1,rows-1-header.length-footer.length),shownBody=body.slice(0,bodyRows);while(shownBody.length<bodyRows)shownBody.push("");return{lines:[...header,...shownBody,...footer],cursor:cursor&&cursor.row<bodyRows?{row:cursor.row+header.length,col:cursor.col}:null}}}function multiSelectSearchText(item){return[item.id,item.name,item.label,item.description].filter((value)=>value!=null).join(" ").toLowerCase()}function filterMultiSelectItems(items,query){let needle=String(query??"").trim().toLowerCase();if(!needle)return items;return items.filter((item)=>multiSelectSearchText(item).includes(needle))}function itemName(item){if(item.name!=null)return String(item.name);if(item.id==="use-colors")return"Use colors";return String(item.id??"")}function itemDescription(item){if(item.description!=null)return String(item.description);if(item.label!=null&&String(item.label)!==itemName(item))return String(item.label);return""}class StatusLineSetup{options;items;query="";selectedId;constructor(options){this.options=options;this.items=buildSetupItems(options.configuredIds,options.useColors).map((item)=>({...item,enabled:Boolean(item.enabled),orderable:item.orderable!==!1})),this.selectedId=this.items[0]?.id??null}visible(){return filterMultiSelectItems(this.items,this.query)}selectedIndex(visible){let index=visible.findIndex((item)=>item.id===this.selectedId);return index<0?0:index}setQuery(query){this.query=query,this.selectedId=filterMultiSelectItems(this.items,query)[0]?.id??null}reorder(id,delta){if(this.query||id==null)return;let index=this.items.findIndex((item)=>item.id===id),target=index+delta;if(index<0||target<0||target>=this.items.length)return;if(this.items[index].orderable===!1||this.items[target].orderable===!1)return;[this.items[index],this.items[target]]=[this.items[target],this.items[index]]}onKey(input,key){let visible=this.visible(),selected=visible[this.selectedIndex(visible)]??null;if(key.escape){if(this.query)this.setQuery("");else this.options.onCancel();return}if(key.return){let items=this.items.map((item)=>({...item}));this.options.onConfirm({items,useColors:Boolean(items.find((item)=>item.id==="use-colors")?.enabled)});return}if(key.upArrow||key.downArrow){if(visible.length===0)return;let delta=key.upArrow?-1:1,next=(this.selectedIndex(visible)+delta+visible.length)%visible.length;this.selectedId=visible[next].id;return}if(input===" "){if(selected)this.items=this.items.map((item)=>item.id===selected.id?{...item,enabled:!item.enabled}:item);return}if(key.leftArrow||key.ctrl&&input==="h"){if(selected)this.reorder(selected.id,-1);return}if(key.rightArrow||key.ctrl&&input==="l"){if(selected)this.reorder(selected.id,1);return}if(key.backspace||key.delete){this.setQuery(popChar(this.query));return}if(key.ctrl||key.meta||key.tab||key.pageUp||key.pageDown||key.home||key.end)return;let text=cleanInput(input);if(text)this.setQuery(this.query+text)}render(width){let inner=Math.max(1,width-2),pad=(line)=>` ${truncate4(line,inner)}`,visibleItems=this.visible(),index=this.selectedIndex(visibleItems),useColors=Boolean(this.items.find((item)=>item.id==="use-colors")?.enabled),size=Math.min(visibleItems.length,MULTI_SELECT_MAX_VISIBLE),start=windowStart(index,visibleItems.length,size),shown=visibleItems.slice(start,start+size),above=start,below=Math.max(0,visibleItems.length-start-size),preview=buildPreviewSegments(this.items,this.options.snapshot,{useColors}),segments=Array.isArray(preview)?preview:Array.isArray(preview?.segments)?preview.segments:null,lines=[pad(style(" Configure Status Line ",{inverse:!0,bold:!0}))];lines.push(pad(dim("Select which items to display in the status line."))),lines.push("");let box=border([this.query||dim("Type to search...")],inner,{style:"single",color:this.query?"cyan":"gray",paddingX:1}),cursorRow=lines.length+1;if(lines.push(...box.map((line)=>` ${line}`)),lines.push(""),above>0)lines.push(pad(dim(`↑ ${above} more above`)));if(shown.forEach((item,offset)=>{let active=start+offset===index,description=itemDescription(item);if(lines.push(pad(style(`${active?"> ":" "}[${item.enabled?"x":" "}] ${itemName(item)}`,{color:active?"cyan":void 0,bold:active})+(description?dim(` ${description}`):""))),item.sectionBreakAfter||item.section_break_after)lines.push(pad(dim(` ${"─".repeat(Math.max(1,Math.max(24,width-4)-2))}`)))}),below>0)lines.push(pad(dim(`↓ ${below} more below`)));if(visibleItems.length===0)lines.push(pad(dim("No matching items")));if(lines.push(""),segments&&segments.length>0)lines.push(pad(segments.map((segment,segmentIndex)=>(segmentIndex>0?dim(PREVIEW_SEPARATOR):"")+style(segment.text,{color:useColors?segment.color:void 0,dim:!useColors||segment.dim})).join("")));else lines.push(pad(dim("Status line hidden")));return lines.push(""),lines.push(pad(dim("Space to toggle · ←/→ to move · Enter to save · Esc to cancel · type to search"))),{lines,cursor:{row:cursorRow,col:3+Math.min(stringWidth2(this.query),Math.max(1,inner-4))}}}}var MAX_BODY_LINES=5,MAX_VISIBLE_OPTIONS=3,PLAN_ITEMS,MULTI_SELECT_MAX_VISIBLE=10,PREVIEW_SEPARATOR=" · ";var init_dialogs=__esm(()=>{init_config_options();init_permission_review();init_markdown_width();init_setup_items();init_store();init_layout();init_diff2();init_picker();PLAN_ITEMS=[{value:"approve",label:"Approve and implement"},{value:"revise",label:"Request changes"},{value:"reject",label:"Reject and exit Plan Mode"}]});function frameRows(rows){return Math.max(6,rows-1)}function frameBodyRows(rows){return Math.max(3,frameRows(rows)-FRAME_CHROME_ROWS)}function frame(label,footer,body,width,rows){let inner=Math.max(1,width-2),head=style("Review",{bold:!0,inverse:!0,color:"cyan"})+(label?dim(" · ")+style(label,{bold:!0}):""),bodyRows=frameBodyRows(rows),shown=body.slice(0,bodyRows).map((line)=>" ".repeat(FRAME_BODY_PADDING_X)+truncate4(line,Math.max(1,width-FRAME_BODY_PADDING_X*2)));while(shown.length<bodyRows)shown.push("");return[` ${truncate4(head,inner)}`,style("─".repeat(width),{color:"cyan"}),...shown,dim("─".repeat(width)),` ${dim(truncate4(footer,inner))}`]}function detailLines(item,width){let status=item.status??"unknown",duration=item.elapsed==null?null:formatDuration(item.elapsed),rows=[{kind:"status",status,text:`Status: ${status}${duration?` · ${duration}`:""}`}],sections=[["input","Input",item.detail?.input],["output","Output",item.detail?.output],["locations","Locations",item.detail?.locations]];for(let[section,title,text]of sections){if(!text)continue;rows.push({kind:"blank",text:""},{kind:"section",section,text:title});for(let line of String(text).split(`
2261
+ `))for(let part of wrapVisualRows(line,Math.max(1,width-2)))rows.push({kind:"content",section,text:part})}if(sections.every(([,,text])=>!text))for(let line of item.preview?.lines??[])for(let part of wrapVisualRows(line,Math.max(1,width-2)))rows.push({kind:"content",section:"output",text:part});return rows}function subagentLines(item,width){let subagent=item?.subagent??{},request=subagent.request??{},duration=item?.elapsed==null?null:formatDuration(item.elapsed),rows=[{kind:"status",status:item?.status??"unknown",text:`Status: ${item?.status??"unknown"}${duration?` · ${duration}`:""}`}],addSection=(section,title,value)=>{if(value==null||String(value).length===0)return;rows.push({kind:"blank",text:""},{kind:"section",section,text:title});for(let line of String(value).split(`
2319
2262
  `))for(let part of wrapVisualRows(line,Math.max(1,width-2)))rows.push({kind:"content",section,text:part})},requestFields=[["Description",request.description],["Model",request.model],["Effort",request.effort]].filter(([,value])=>value!=null&&String(value).length>0).map(([name,value])=>`${name}: ${value}`).join(`
2320
- `);addSection("request","Request",requestFields),addSection("request","Task",request.message??subagent.taskSummary),addSection("output","Output",subagent.text||"No output retained.");let tools=includeTools?(subagent.tools??[]).filter((tool)=>!tool.removed):[];if(tools.length>0){rows.push({kind:"blank",text:""},{kind:"section",section:"tools",text:`Tool calls (${tools.length})`});for(let tool of tools){let label=tool.args?`${tool.name}(${tool.args})`:tool.name;if(rows.push({kind:"content",section:"tools",text:`${tool.status??""} ${label}`.trim()}),tool.result)for(let line of String(tool.result).split(`
2321
- `))for(let part of wrapVisualRows(` ${line}`,Math.max(1,width-2)))rows.push({kind:"content",section:"output",text:part})}}return rows}function statusColor(status){if(["completed","done","success"].includes(status))return"green";if(["failed","error","rejected"].includes(status))return"red";return"yellow"}function DetailLine({line}){if(line.kind==="blank")return $jsx(Text,{children:" "});if(line.kind==="status")return $jsx(Text,{bold:!0,color:statusColor(line.status),children:line.text});let color=DETAIL_SECTION_COLORS[line.section]??"cyan";if(line.kind==="section")return $jsx(Text,{bold:!0,inverse:!0,color,children:` ${line.text} `});return $jsxs(Text,{wrap:"truncate-end",children:[$jsx(Text,{bold:!0,color,children:"│ "}),$jsx(Text,{children:line.text.length>0?line.text:" "})]})}function wrapRenderedMarkdown(text,width){let rendered=renderMarkdown(text);try{return Bun.wrapAnsi(rendered,Math.max(1,width),{hard:!0,wordWrap:!0,trim:!1}).split(`
2322
- `)}catch{return rendered.split(`
2323
- `)}}function entryLabel(entry){if(entry?.kind==="thought"){let thought=entry.thought,title=thought.title??splitThinkingText(thought.text).title,duration=thought.durationMs==null?null:formatDuration(thought.durationMs);return[title?`Thought: ${title}`:"Thought",duration].filter(Boolean).join(" · ")}if(entry?.kind==="bash"){let command=entry.card?.command??"";return command?`Shell: ${command}`:"Shell"}if(entry?.kind==="subagent"){let item=entry.item;return`Sub-agent: ${item?.label?.args?`${item.label.name}(${item.label.args})`:item?.label?.name??"Sub-agent"}`}let item=entry?.item;return`Tool: ${item?.label?.args?`${item.label.name}(${item.label.args})`:item?.label?.name??"Tool"}`}function entryType(entry){if(entry?.kind==="subagent")return"Agent";if(entry?.kind==="thought")return"Thought";if(entry?.kind==="bash")return"Shell";return"Tool"}function entryTitle(entry){if(entry?.kind==="thought")return entry.thought?.title??splitThinkingText(entry.thought?.text).title??"Thinking";if(entry?.kind==="bash")return entry.card?.command??"Shell";let item=entry?.item;return item?.label?.args?`${item.label.name}(${item.label.args})`:item?.label?.name??"Tool"}function listLeftColumn(index,total,type){return`${String(index+1).padStart(String(total).length," ")} ${type.padEnd(TYPE_COLUMN_WIDTH)}`}function listItem(entry,index,total){return{value:index,label:listLeftColumn(index,total,entryType(entry)),right:entryTitle(entry)}}function listHeader(total){return`${"#".padStart(String(total).length," ")} ${"Type".padEnd(TYPE_COLUMN_WIDTH)} Title`}function subagentToolEntries(entry){return(entry?.item?.subagent?.tools??[]).filter((tool)=>!tool.removed).map((tool,index)=>({id:`${entry.id??"subagent"}:child:${index}`,kind:"tool",item:{label:{name:tool.name??"Tool",args:tool.args??""},status:tool.status,detail:tool.result==null?void 0:{output:tool.result}}}))}function ReviewList({label,entries,selected,onSelect,onBack,canGoBack=!1}){let{rows=24,columns=80}=use_window_size_default();return $jsx(ReviewFrame,{label,rows,footer:footerHint({canGoBack}),children:$jsx(Picker,{embed:{rows:frameBodyRows(rows),columns:Math.max(1,columns-FRAME_BODY_PADDING_X*2)},subtitle:listHeader(entries.length),items:entries.map((entry,index)=>listItem(entry,index,entries.length)),selected,color:"cyan",compactColumns:!0,canGoBack,onSelect:(row)=>onSelect(row.value),onCancel:onBack,emptyText:"No retained items"})})}function ReviewDetail({entry,position,onBack,onOpenTools,onStep}){let{rows=24,columns=80}=use_window_size_default(),[offset,setOffset]=$useState(0),bodyRows=frameBodyRows(rows),contentWidth=Math.max(1,columns-2),{index=0,total=1}=position??{};$useEffect(()=>{setOffset(0)},[entry?.id]);let thoughtLines=$useMemo(()=>{if(entry?.kind!=="thought")return[];let body=splitThinkingText(entry.thought?.text).body;return body?wrapRenderedMarkdown(body,contentWidth):["No retained details."]},[entry,contentWidth]),toolLines=$useMemo(()=>{if(entry?.kind!=="tool"||entry.item?.diff)return[];return detailLines(entry.item,contentWidth)},[entry,contentWidth]),subagentDetailLines=$useMemo(()=>{if(entry?.kind!=="subagent")return[];return subagentLines(entry.item,contentWidth,{includeTools:!1})},[entry,contentWidth]),bashLines=$useMemo(()=>{if(entry?.kind!=="bash")return[];let card=entry.card??{},out=[];for(let line of card.lines??[])out.push({err:Boolean(line.err),text:wrapVisualRows(line.text,contentWidth).join(`
2324
- `)});if(card.hidden>0)out.push({text:`… ${card.hidden} more lines not retained`});return out},[entry,contentWidth]),isDiff=entry?.kind==="tool"&&!!entry.item?.diff,diffRows=isDiff?diffLineCount(entry.item.diff,contentWidth):0,lineCount=isDiff?diffRows:entry?.kind==="thought"?thoughtLines.length:entry?.kind==="bash"?bashLines.length:entry?.kind==="subagent"?subagentDetailLines.length:toolLines.length,pageRows=isDiff?Math.max(1,bodyRows-3):bodyRows,maxOffset=Math.max(0,lineCount-pageRows),hasSubagentTools=entry?.kind==="subagent"&&subagentToolEntries(entry).length>0,safeOffset=Math.min(offset,maxOffset);use_input_default((input,key)=>{if(key.escape)return onBack();if(key.return&&hasSubagentTools)return onOpenTools();if(key.leftArrow)return onStep?.(-1);if(key.rightArrow)return onStep?.(1);if(key.home)return setOffset(0);if(key.end)return setOffset(maxOffset);if(key.upArrow)return setOffset((value)=>Math.max(0,value-1));if(key.downArrow)return setOffset((value)=>Math.min(maxOffset,value+1));if(key.pageUp)return setOffset((value)=>Math.max(0,value-pageRows));if(key.pageDown)return setOffset((value)=>Math.min(maxOffset,value+pageRows))});let footer=["↑↓/Pg/Home/End scroll",total>1?"←→ switch item":null,hasSubagentTools?"Enter to view tool calls":null,"Esc to go back",maxOffset>0?`${safeOffset+1}-${Math.min(lineCount,safeOffset+pageRows)}/${lineCount}`:null].filter(Boolean).join(" · ");return $jsx(ReviewFrame,{label:total>1?`${index+1}/${total} · ${entryLabel(entry)}`:entryLabel(entry),rows,footer,children:isDiff?$jsx(DiffView,{diff:entry.item.diff,mode:"full",offset:safeOffset,maxLines:pageRows,width:contentWidth}):entry?.kind==="tool"?toolLines.slice(safeOffset,safeOffset+pageRows).map((line,lineIndex)=>$jsx(DetailLine,{line},`${entry?.id??"entry"}-${safeOffset}-${lineIndex}`)):entry?.kind==="bash"?bashLines.slice(safeOffset,safeOffset+pageRows).map((line,lineIndex)=>$jsx(Text,{dimColor:!0,color:line.err?"yellow":void 0,wrap:"truncate-end",children:line.text.length>0?line.text:" "},`${entry?.id??"entry"}-${safeOffset}-${lineIndex}`)):entry?.kind==="subagent"?subagentDetailLines.slice(safeOffset,safeOffset+pageRows).map((line,lineIndex)=>$jsx(DetailLine,{line},`${entry?.id??"entry"}-${safeOffset}-${lineIndex}`)):thoughtLines.slice(safeOffset,safeOffset+pageRows).map((line,lineIndex)=>$jsx(Text,{wrap:"truncate-end",children:line.length>0?line:" "},`${entry?.id??"entry"}-${safeOffset}-${lineIndex}`))})}function detailList(entries,page){if(page.kind!=="tool-detail")return entries;return subagentToolEntries(entries[page.selected]??null)}function ReviewBrowser({entries=[],initialIndex=0,onClose}){let initial=Math.max(0,Math.min(entries.length-1,initialIndex)),[page,setPage]=$useState({kind:"root",selected:initial});if(page.kind==="root")return $jsx(ReviewList,{label:`${entries.length} item${entries.length===1?"":"s"}`,entries,selected:page.selected,onSelect:(selected)=>setPage({kind:"detail",selected}),onBack:onClose});if(page.kind==="agent-tools"){let tools=subagentToolEntries(entries[page.selected]??null);return $jsx(ReviewList,{label:"Agent tool calls",entries:tools,selected:page.toolSelected,onSelect:(toolSelected)=>setPage({kind:"tool-detail",selected:page.selected,toolSelected}),onBack:()=>setPage({kind:"detail",selected:page.selected}),canGoBack:!0})}let list=detailList(entries,page),selected=page.kind==="detail"?page.selected:page.toolSelected,step=(delta)=>{let next=Math.max(0,Math.min(list.length-1,selected+delta));if(next===selected)return;setPage(page.kind==="detail"?{kind:"detail",selected:next}:{kind:"tool-detail",selected:page.selected,toolSelected:next})};return $jsx(ReviewDetail,{entry:list[selected]??null,position:{index:selected,total:list.length},onBack:()=>setPage(page.kind==="detail"?{kind:"root",selected:page.selected}:{kind:"agent-tools",selected:page.selected,toolSelected:page.toolSelected}),onOpenTools:()=>setPage({kind:"agent-tools",selected:page.selected,toolSelected:0}),onStep:step})}var FRAME_CHROME_ROWS=5,FRAME_BODY_PADDING_X=1,DETAIL_SECTION_COLORS,TYPE_COLUMN_WIDTH=7;var init_ReviewBrowser=__esm(async()=>{init_react_production();init_markdown();init_thinking();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_DiffView(),init_Picker()]);DETAIL_SECTION_COLORS={input:"yellow",output:"green",locations:"blue",request:"magenta",tools:"cyan"}});function oneLine(item){return String(item.display??item.text??"").replace(/\s+/g," ").trim()||"(empty)"}function QueueEditor({onClose,onResume}){let{rows=24}=use_window_size_default(),items=useStore2((state)=>state.queuedInputs),pending=useStore2((state)=>state.pendingInputs),paused=useStore2((state)=>state.queuePaused),update=useStore2((state)=>state.updateQueuedInput),remove=useStore2((state)=>state.removeQueuedInput),move=useStore2((state)=>state.moveQueuedInput),clear=useStore2((state)=>state.clearQueuedInputs),[index,setIndex]=$useState(0),[draft,setDraft]=$useState(null),draftRowRef=$useRef(null);useInputCursor(draftRowRef,draft==null?null:stringWidth2(draft)),$useEffect(()=>{if(items.length===0&&pending.length===0)onClose();else if(items.length===0)setIndex(0);else if(index>=items.length)setIndex(items.length-1)},[items.length,pending.length,index,onClose]),use_input_default((input,key)=>{if(draft!=null){if(key.escape)return setDraft(null);if(key.return){if(draft.trim())update(index,draft);return setDraft(null)}if(key.backspace||key.delete)return setDraft((value)=>[...value].slice(0,-1).join(""));if(key.ctrl||key.meta||!input)return;return setDraft((value)=>value+input.replace(/[\r\n]+/g," "))}if(key.escape||key.ctrl&&input==="q")return onClose();if(input==="r"&&paused)return onResume?.();if(!items.length)return;if(key.upArrow&&key.shift)return move(index,-1),setIndex(Math.max(0,index-1));if(key.downArrow&&key.shift)return move(index,1),setIndex(Math.min(items.length-1,index+1));if(key.upArrow)return setIndex((value)=>(value-1+items.length)%items.length);if(key.downArrow)return setIndex((value)=>(value+1)%items.length);if(key.return||input==="e")return setDraft(items[index]?.text??"");if(input==="d")return remove(index);if(input==="x")return clear()});let maxVisible=Math.max(3,rows-7-Math.min(pending.length+1,4)),start=Math.max(0,Math.min(index-Math.floor(maxVisible/2),items.length-maxVisible));return $jsxs(Box_default,{flexDirection:"column",height:rows,children:[$jsxs(Box_default,{borderStyle:"single",borderLeft:!1,borderRight:!1,paddingX:1,children:[$jsx(Text,{bold:!0,color:"cyan",children:"Queued messages"}),$jsxs(Text,{dimColor:!0,children:[" · ",items.length]})]}),$jsxs(Box_default,{flexDirection:"column",flexGrow:1,paddingX:1,children:[pending.length?$jsx(Text,{dimColor:!0,children:"Steering waiting for the current response and tools (read only)"}):null,pending.slice(0,3).map((item)=>$jsx(Text,{color:"cyan",wrap:"truncate-end",children:oneLine(item)},item.id)),items.slice(start,start+maxVisible).map((item,offset)=>{let itemIndex=start+offset,active=itemIndex===index;return $jsxs(Text,{color:active?"cyan":void 0,bold:active,wrap:"truncate-end",children:[active?"❯ ":" ",itemIndex+1,". ",oneLine(item)]},itemIndex)}),draft!=null?$jsxs(Box_default,{flexDirection:"column",marginTop:1,borderStyle:"round",borderColor:"cyan",paddingX:1,children:[$jsx(Text,{dimColor:!0,children:"Edit message"}),$jsx(Box_default,{ref:draftRowRef,children:$jsx(Text,{children:draft})})]}):null]}),$jsx(Box_default,{borderStyle:"single",borderLeft:!1,borderRight:!1,paddingX:1,children:$jsx(Text,{dimColor:!0,children:draft!=null?"Enter save · Esc cancel edit":`${paused?"r resume sending · ":""}↑↓ select · Shift+↑↓ reorder · Enter/e edit · d delete · x clear · Ctrl+Q/Esc close`})})]})}var init_QueueEditor=__esm(async()=>{init_react_production();init_markdown_width();init_store();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_use_input_cursor()])});function Transcript(){let blocks=useStore2((state)=>state.blocks),epoch=useStore2((state)=>state.epoch),{columns}=use_window_size_default();return $jsx(Static,{items:blocks,style:{width:columns},children:(block)=>$jsx(Message,{block,width:columns},block.id)},epoch)}var init_Transcript=__esm(async()=>{init_store();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_Message()])});import{readFileSync as readFileSync15,writeFileSync as writeFileSync10}from"node:fs";import{hostname as hostname2}from"node:os";import{randomUUID as randomUUID7}from"node:crypto";import{join as join17}from"node:path";function prepareSubmittedInput(raw,display){let content=String(raw??""),commandText=content.trim();if(!commandText)return null;return{content,commandText,display:display==null?null:String(display),transcriptText:content}}function bareExitCommand(text){let lower=String(text??"").trim().toLowerCase();return lower==="exit"||lower==="quit"?{key:"exit",args:""}:null}function resolveStartupModel(config,startupModel,savedModel){let choices=modelChoices(config);if(!config||choices.length===0)return{value:null,unavailable:startupModel!=null};let matched=matchConfigChoice(config,startupModel??savedModel);if(startupModel!=null&&!matched)return{value:null,unavailable:!0};return{value:matched?.value??choices[0].value,unavailable:!1}}function resolveStartupEffort(config,startupEffort,savedEffort){let matched=startupEffort!=null?matchConfigChoice(config,startupEffort):effortChoices(config).find((choice)=>choice.value===savedEffort);return{value:matched?.value??null,unavailable:startupEffort!=null&&!matched}}function buildPermissionDialogItems(options){let kindRank={allow_once:0,allow_session:1,allow_family:2,reject_once:3,reject_always:4};return[...options??[]].sort((a,b)=>(kindRank[a.kind]??9)-(kindRank[b.kind]??9)).map((option)=>({value:option.optionId,label:option.name,allow:option.kind?.startsWith("allow")??!1}))}function permissionOptionIdForChoice(options,value){return value}function isAwaitingInputOverlay(kind){return AWAITING_INPUT_OVERLAYS.has(kind)}function composerIsHidden(connecting,overlayKind){return Boolean(connecting)||SCREEN_TAKEOVER_OVERLAYS.has(overlayKind)||["model","effort","config","statusline","permissions","thinking"].includes(overlayKind)}function statusLineIsHidden({helpOpen=!1,completionOpen=!1,overlay=null}={}){return helpOpen||completionOpen||overlay!=null}function ctrlCIntent({hasOverlay,hasDraft}){if(hasOverlay)return"overlay";return hasDraft?"draft":"turn"}function cancelOverlay(overlay){if(!overlay)return;if(typeof overlay.resolve==="function"){overlay.resolve(overlay.escapeValue);return}overlay.onCancel?.()}function isClockRunning({activeTools=[],busy=!1,awaitingInput=!1,overlayKind=null,goalActive=!1}={}){if(!busy&&activeTools.length===0&&!goalActive)return!1;if(awaitingInput)return!1;return!SCREEN_TAKEOVER_OVERLAYS.has(overlayKind)}function refreshActiveGoal(client){let store=useStore2.getState();if(store.goal?.status!=="active")return null;let snapshot=client?.goalSnapshot?.();if(snapshot==null)return null;return store.setGoal(snapshot),snapshot}function ComposerSurface({hidden,disabled,...props}){return $jsx(Box_default,{display:hidden?"none":"flex",flexDirection:"column",children:$jsx(Composer,{disabled:hidden||disabled,...props})})}function emptyComposerSnapshot(){return{value:"",cursor:0,pastes:new Map,nextPasteId:1}}function shouldRecordUiState({composer,queuedInputs,pendingInputs,alreadyRecorded}){if(alreadyRecorded)return!0;if(queuedInputs?.length>0)return!0;if(pendingInputs?.length>0)return!0;return Boolean(composer?.value)||(composer?.pastes?.size??0)>0}function formatSessionAge(ts){let diff=Date.now()-ts,min=Math.floor(diff/60000);if(min<1)return"just now";if(min<60)return`${min}m ago`;let hr=Math.floor(min/60);if(hr<24)return`${hr}h ago`;return`${Math.floor(hr/24)}d ago`}function App2({continueSessionId=null,startupAcp=null,startupModel=null,startupEffort=null,startupPermissionMode=null,startupInteractionMode=null}){let{exit}=useApp(),{write}=useStdout(),clientRef=$useRef(null),providerRef=$useRef(null),recorderRef=$useRef(null),uiCheckpointTimerRef=$useRef(null),pendingSessionKeyRef=$useRef(0),goalTakeoverRef=$useRef(null),goalAfterStopNoticeRef=$useRef(null),composerSnapshotRef=$useRef(null),composerControlsRef=$useRef(null),uiStateRecordedRef=$useRef(!1),[composerSession,setComposerSession]=$useState({key:null,snapshot:null}),[hasComposerDraft,setHasComposerDraft]=$useState(!1),checkpointUiState=()=>{if(uiCheckpointTimerRef.current!=null)clearTimeout(uiCheckpointTimerRef.current),uiCheckpointTimerRef.current=null;if(!recorderRef.current||!composerSnapshotRef.current)return;let composer=composerSnapshotRef.current,{queuedInputs,pendingInputs,queuePaused}=useStore2.getState();if(!shouldRecordUiState({composer,queuedInputs,pendingInputs,alreadyRecorded:uiStateRecordedRef.current}))return;uiStateRecordedRef.current=!0,recorderRef.current.recordUiState({composer,queuedInputs,pendingInputs,queuePaused})},scheduleUiCheckpoint=()=>{if(!recorderRef.current||!composerSnapshotRef.current)return;if(uiCheckpointTimerRef.current!=null)clearTimeout(uiCheckpointTimerRef.current);uiCheckpointTimerRef.current=setTimeout(checkpointUiState,200)},handleComposerSnapshotChange=(snapshot)=>{composerSnapshotRef.current=snapshot,setHasComposerDraft(composerHasDraft(snapshot)),scheduleUiCheckpoint()},stageSessionUiState=(key,uiState=null)=>{let snapshot=uiState?.composer??emptyComposerSnapshot();composerSnapshotRef.current=snapshot,setHasComposerDraft(composerHasDraft(snapshot)),uiStateRecordedRef.current=uiState!=null,useStore2.getState().replaceQueuedInputs(uiState?.queuedInputs??[]),useStore2.setState({pendingInputs:[],queuePaused:uiState?.queuePaused===!0}),setComposerSession({key,snapshot})},exitRef=$useRef(exit);exitRef.current=exit;let[exiting,setExiting]=$useState(!1),requestExit=()=>setExiting(!0);$useEffect(()=>{if(exiting)exitRef.current()},[exiting]);let bashTaskRef=$useRef(null),thoughtQueueRef=$useRef(""),thoughtTimerRef=$useRef(null),exitConfirmUntilRef=$useRef(0),exitConfirmTimerRef=$useRef(null),[exitConfirming,setExitConfirming]=$useState(!1),modeSwitchingRef=$useRef(!1),[modeSwitching,setModeSwitching]=$useState(!1),[helpOpen,setHelpOpen]=$useState(!1),[completionOpen,setCompletionOpen]=$useState(!1),[agentBin,setAgentBin]=$useState("provider"),status=useStore2((state)=>state.status),connectionStage=useStore2((state)=>state.connectionStage),busy=useStore2((state)=>state.busy),cancelling=useStore2((state)=>state.cancelling),compacting=useStore2((state)=>state.compacting),retryNotice=useStore2((state)=>state.retryNotice),switching=useStore2((state)=>state.switching),overlay=useStore2((state)=>state.overlay),pending=useStore2((state)=>state.pending),activeTools=useStore2((state)=>state.activeTools),pendingToolGroup=useStore2((state)=>state.pendingToolGroup),modelConfig=useStore2((state)=>state.modelConfig),effortConfig=useStore2((state)=>state.effortConfig),configOptions=useStore2((state)=>state.configOptions),turnStartedAt=useStore2((state)=>state.turnStartedAt),toolRound=useStore2((state)=>state.toolRound),providerCommands=useStore2((state)=>state.providerCommands),queuedInputs=useStore2((state)=>state.queuedInputs),pendingInputs=useStore2((state)=>state.pendingInputs),queuePaused=useStore2((state)=>state.queuePaused),bashCard=useStore2((state)=>state.bashCard),modes=useStore2((state)=>state.modes),providerName=useStore2((state)=>state.providerName),sessionId=useStore2((state)=>state.sessionId),sessionTitle=useStore2((state)=>state.sessionTitle),usage=useStore2((state)=>state.usage),sessionTokens=useStore2((state)=>state.sessionTokens),sessionCost=useStore2((state)=>state.sessionCost),planProgress=useStore2((state)=>state.planProgress),goal=useStore2((state)=>state.goal),gitBranch=useStore2((state)=>state.gitBranch),thinking=useStore2((state)=>state.thought!=null);$useEffect(()=>{scheduleUiCheckpoint()},[queuedInputs,pendingInputs,queuePaused]),$useEffect(()=>{if(overlay!=null)setHelpOpen(!1)},[overlay]);let awaitingInput=isAwaitingInputOverlay(overlay?.kind);$useEffect(()=>{useStore2.getState().setThoughtPaused(awaitingInput)},[awaitingInput]);let[statusLineConfig,setStatusLineConfig]=$useState(()=>{let{items,useColors}=readStatusLineSettings();return{items:items??DEFAULT_STATUS_LINE_ITEMS,useColors}}),[initialThinkingSettings]=$useState(()=>readThinkingSettings()),[thinkingDisplay,setThinkingDisplay]=$useState(initialThinkingSettings.display);$useEffect(()=>{useStore2.getState().setThinkingDisplay(thinkingDisplay)},[thinkingDisplay]);let[permissionMode,setPermissionMode]=$useState(DEFAULT_PERMISSION_MODE),permissionModeRef=$useRef(startupPermissionMode),applyPermissionModeToClient=async(client,value)=>{let store=useStore2.getState(),mode=normalizePermissionMode(value);return await client?.setPermissionMode?.(mode),permissionModeRef.current=mode,setPermissionMode(mode),store.push("system",permissionModeMessage(mode)),mode},[language,setLanguage]=$useState(()=>readLanguageSetting()),languageRef=$useRef(language);languageRef.current=language;let panelConfigOptions=$useMemo(()=>withLanguageOption(configOptions,language),[configOptions,language]),statusLineParsed=parseStatusLineItems(statusLineConfig.items),statusLineWarnedRef=$useRef(!1);$useEffect(()=>{if(status!=="ready"||statusLineWarnedRef.current)return;if(statusLineParsed.invalid.length===0)return;statusLineWarnedRef.current=!0;let label=statusLineParsed.invalid.length===1?"item":"items";useStore2.getState().push("system",`Ignored invalid status line ${label}: ${statusLineParsed.invalid.join(", ")}.`)},[status]);let usesGitBranch=statusLineParsed.items.includes("git-branch");$useEffect(()=>{if(!usesGitBranch)return;let cancelled=!1;return loadGitBranch(process.cwd()).then((branch)=>{if(!cancelled)useStore2.getState().setGitBranch(branch)}),()=>{cancelled=!0}},[usesGitBranch,sessionId]);let flushQueuedThought=()=>{if(thoughtTimerRef.current!=null)clearTimeout(thoughtTimerRef.current),thoughtTimerRef.current=null;let text=thoughtQueueRef.current;if(thoughtQueueRef.current="",!text)return;let store=useStore2.getState();if(!store.busy||store.cancelling)return;store.noteThought(text)},discardQueuedThought=()=>{if(thoughtTimerRef.current!=null)clearTimeout(thoughtTimerRef.current),thoughtTimerRef.current=null;thoughtQueueRef.current=""},queueThought=(text)=>{let store=useStore2.getState();if(!store.busy||store.cancelling)return;let chunk=String(text??"");if(!chunk)return;if(thoughtQueueRef.current+=chunk,thoughtTimerRef.current==null)thoughtTimerRef.current=setTimeout(()=>{thoughtTimerRef.current=null,flushQueuedThought()},THOUGHT_UI_FLUSH_MS)},[now,setNow]=$useState(Date.now()),clockRunning=isClockRunning({activeTools,busy,awaitingInput,overlayKind:overlay?.kind,goalActive:goal?.status==="active"});$useEffect(()=>{if(!clockRunning)return;let timer=setInterval(()=>{setNow(Date.now()),refreshActiveGoal(clientRef.current)},1000);return()=>clearInterval(timer)},[clockRunning]);let attachClient=(client)=>{let store=useStore2.getState(),beginSession=({modelConfig:config,sessionId,resumed})=>{if(!sessionId||recorderRef.current?.sessionId===sessionId)return;let savedMeta=null,savedUiState=null,savedGoalState=null;if(resumed){let saved=loadSessionBlocks(sessionId,process.cwd(),useStore2.getState().providerId);if(saved){if(saved.blocks.length>0)useStore2.getState().hydrate(saved.blocks),client.suppressReplay=!0;useStore2.getState().setSessionMeta(saved.meta),savedMeta=saved.meta,savedUiState=saved.uiState,savedGoalState=saved.goalState}useStore2.getState().push("system",`Resumed session: ${sessionId}`)}stageSessionUiState(`session:${pendingSessionKeyRef.current}:${sessionId}`,savedUiState);let recorder=new SessionRecorder({sessionId,providerId:useStore2.getState().providerId,model:currentModelName(config)});if(savedMeta?.title!=null)recorder.meta.title=savedMeta.title;if(recorderRef.current=recorder,setRecorder(recorder),savedGoalState!=null&&typeof client.restoreGoal==="function")client.restoreGoal(savedGoalState)};client.on("progress",(stage)=>useStore2.getState().setConnectionStage(stage)),client.on("ready",({agentName,modelConfig:config,effortConfig:effort,configOptions:configs,modes,sessionId,resumed})=>{useStore2.getState().connected({providerName:agentName,sessionId,modelConfig:config,effortConfig:effort,configOptions:configs,modes}),beginSession({modelConfig:config,sessionId,resumed});let resumeQueue=()=>{if(useStore2.getState().queuedInputs.length>0)drainQueue()};(async()=>{if(startupInteractionMode!=null&&modes?.availableModes?.some((mode)=>mode.id===startupInteractionMode))await client.setMode(startupInteractionMode);if(startupModel!=null||!resumed)await applyStartupModel(config);if(startupEffort!=null||!resumed)await applyStartupEffort()})().finally(resumeQueue)}),client.on("chunk",(text,messageId)=>{flushQueuedThought(),useStore2.getState().appendChunk(text,messageId)}),client.on("user_chunk",(text,messageId)=>{flushQueuedThought(),useStore2.getState().appendUserChunk(text,messageId)}),client.on("info",(text)=>{flushQueuedThought(),useStore2.getState().push("system",text.trim())}),client.on("tool",(payload)=>{flushQueuedThought(),useStore2.getState().upsertTool(payload)}),client.on("auto_review",(payload)=>{useStore2.getState().upsertTool({toolCallId:payload.toolCallId,autoReview:payload})}),client.on("thought",queueThought),client.on("input_applied",(input)=>{if(client!==clientRef.current)return;flushQueuedThought(),useStore2.getState().applyInput(input),checkpointUiState()}),client.on("input_returned",({inputs,paused})=>{if(client!==clientRef.current)return;useStore2.getState().returnInputs(inputs,paused),checkpointUiState()}),client.on("plan",(entries)=>{flushQueuedThought(),useStore2.getState().setPlan(entries)}),client.on("commands",(commands)=>useStore2.getState().setProviderCommands(commands)),client.on("goal",(snapshot)=>{useStore2.getState().setGoal(snapshot),recorderRef.current?.recordGoalState?.(snapshot)}),client.on("plan_mode",(snapshot)=>{recorderRef.current?.recordPlanModeState?.(snapshot)}),client.on("usage",(payload)=>useStore2.getState().setUsage(payload)),client.on("session_info",({title})=>useStore2.getState().setSessionTitle(title)),client.on("token_usage",(payload)=>useStore2.getState().setTokens(payload)),client.on("compaction_state",(active)=>{if(client===clientRef.current)useStore2.getState().setCompacting(active)}),client.on("context_checkpoint",(state)=>{if(client===clientRef.current)useStore2.getState().recordContextState(state)}),client.on("retry",(payload)=>useStore2.getState().setRetryNotice(payload)),client.on("compacted",(payload)=>{flushQueuedThought();let text=typeof payload?.notice==="string"&&payload.notice.length>0?payload.notice:null;if(text)useStore2.getState().push("system",text)}),client.on("config",(configs)=>useStore2.getState().setConfigs(configs)),client.on("mode",(modes)=>{if(client!==clientRef.current)return;if(useStore2.getState().setModes(modes),typeof client.setPermissionMode==="function"){let mode=normalizePermissionMode(client.permissionMode);permissionModeRef.current=mode,setPermissionMode(mode)}}),client.on("stderr",(text)=>useStore2.getState().push("stderr",`${client.bin}
2325
- ${text}`)),client.on("fatal",({error,message})=>{useStore2.getState().setFatalError(error),useStore2.getState().push("error",message)}),client.onPermissionRequest=(params)=>new Promise((resolve)=>{let options=params.options??[],reject=options.find((option)=>option.kind==="reject_once"),toolCall={name:params.toolCall?.name??null,title:params.toolCall?.title??null,kind:params.toolCall?.kind??null,rawInput:params.toolCall?.rawInput??null,content:params.toolCall?.content??null,locations:params.toolCall?.locations??null,command:params.toolCall?.rawInput?.command??params.toolCall?.rawInput?.sub_content??null},settled=!1,finish=(optionId)=>{if(settled)return;if(settled=!0,params.signal?.removeEventListener("abort",onAbort),useStore2.getState().overlay?.resolve===resolveChoice)store.setOverlay(null);resolve(optionId)},onAbort=()=>finish(null),resolveChoice=async(value)=>{if(settled)return;let optionId=permissionOptionIdForChoice(options,value),chosen=options.find((option)=>option.optionId===optionId),verdict="Cancelled";if(chosen)verdict=chosen.kind?.startsWith("allow")?"Allowed":"Denied";store.push("system",`${verdict}: ${toolCall.command??toolCall.title??"tool call"}`),finish(optionId)};if(store.setOverlay({kind:"permission",toolCall,escapeValue:reject?.optionId??null,items:buildPermissionDialogItems(options),resolve:resolveChoice}),params.signal?.addEventListener("abort",onAbort,{once:!0}),params.signal?.aborted)onAbort()}),client.onPlanEntryRequest=()=>new Promise((resolve)=>{store.setOverlay({kind:"permission",toolCall:{kind:"mode",title:"Enter Plan Mode",rawInput:null},escapeValue:"decline",items:[{value:"approve",label:"Enter Plan Mode"},{value:"decline",label:"Continue normally"}],resolve:(value)=>{store.setOverlay(null),resolve(value==="approve")}})}),client.onPlanReviewRequest=({plan,path})=>new Promise((resolve)=>{store.setOverlay({kind:"plan-review",plan,path,resolve:(value)=>{store.setOverlay(null),resolve(value??{action:"dismiss"})}})}),client.onUserInputRequest=(questions)=>new Promise((resolve)=>{store.setOverlay({kind:"user-question",questions,resolve:(value)=>{store.setOverlay(null),resolve(value)}})})},startClient=(provider,sessionId=null)=>{goalTakeoverRef.current=null,goalAfterStopNoticeRef.current=null,recorderRef.current=null,setRecorder(null),stageSessionUiState(`pending:${++pendingSessionKeyRef.current}`);let settings=readHomeSettings(),{contextText,files}=loadStartupContext({cwd:process.cwd(),settings,resumed:sessionId!=null}),common={contextText,continueSessionId:sessionId},client=isMiroProvider(provider)?new MiroAgentClient({...common,settings,permissionMode:permissionModeRef.current}):new AcpClient({bin:provider.bin,args:provider.args,sessionMeta:provider.sessionMeta,settings,recordRawThinking:initialThinkingSettings.recordRaw,...common});client.agentsFiles=files,clientRef.current=client,providerRef.current=provider,setPermissionMode(isMiroProvider(provider)?normalizePermissionMode(client.permissionMode):null),setAgentBin(isMiroProvider(provider)?provider.id:provider.bin),useStore2.getState().setProviderId(provider.id),attachClient(client),client.run().then((error)=>{if(error)useStore2.getState().setFatalError(error)}).finally(()=>{if(client!==clientRef.current)return;requestExit()})};$useEffect(()=>{let provider=startupAcp==null?{id:"miro",name:"Miro",kind:"miro"}:detectProviders().find((item)=>!isMiroProvider(item)&&item.id===startupAcp);if(!provider){let available=detectProviders().filter((item)=>!isMiroProvider(item)).map((item)=>item.id).join(", ")||"none";useStore2.getState().setFatalError(Error(`ACP provider "${startupAcp}" is not available; available ACP providers: ${available}`)),requestExit()}else startClient(provider,continueSessionId);return()=>{if(exitConfirmTimerRef.current)clearTimeout(exitConfirmTimerRef.current);checkpointUiState(),discardQueuedThought(),clientRef.current?.close()}},[]);let shutdown=()=>{checkpointUiState(),clientRef.current?.close()},clearScreen=()=>{write(CLEAR_TERMINAL),useStore2.getState().clearTranscript()},interrupt=()=>{let store=useStore2.getState();if(bashTaskRef.current)return bashTaskRef.current.interrupt(),!0;if(!store.busy||store.cancelling)return!1;return discardQueuedThought(),store.setCancelling(!0),clientRef.current?.cancel(),!0},cancelExitConfirm=()=>{if(exitConfirmTimerRef.current)clearTimeout(exitConfirmTimerRef.current);exitConfirmTimerRef.current=null,exitConfirmUntilRef.current=0,setExitConfirming(!1)},exitSession=()=>{cancelExitConfirm(),shutdown(),requestExit()},confirmExit=()=>{let now=Date.now();if(now<exitConfirmUntilRef.current){exitSession();return}if(exitConfirmUntilRef.current=now+2000,setExitConfirming(!0),exitConfirmTimerRef.current)clearTimeout(exitConfirmTimerRef.current);exitConfirmTimerRef.current=setTimeout(()=>{exitConfirmUntilRef.current=0,exitConfirmTimerRef.current=null,setExitConfirming(!1)},2000)},applyStartupModel=async(config)=>{let store=useStore2.getState(),saved=startupModel==null?readModelPreference(readHomeSettings(),useStore2.getState().providerId):null,{value:desired,unavailable}=resolveStartupModel(config,startupModel,saved);if(unavailable){store.push("error",`Model "${startupModel}" is not available.`);return}if(desired==null)return;if(desired===config.currentValue)return;store.setSwitching("Applying model preference…");try{await clientRef.current.setModel(desired)}catch(error){store.push("error",`Failed to apply model preference: ${errorMessage(error)}`)}finally{store.setSwitching(null)}},applyStartupEffort=async()=>{let store=useStore2.getState();try{await clientRef.current.enableThinking()}catch(error){store.push("error",`Failed to enable thinking: ${errorMessage(error)}`)}let config=useStore2.getState().effortConfig,saved=startupEffort==null?readEffortPreference(readHomeSettings(),useStore2.getState().providerId):null,{value:desired,unavailable}=resolveStartupEffort(config,startupEffort,saved);if(unavailable){store.push("error",`Effort "${startupEffort}" is not available.`);return}if(desired==null||desired===config?.currentValue)return;store.setSwitching("Applying effort preference…");try{await clientRef.current.setEffort(desired)}catch(error){store.push("error",`Failed to apply effort preference: ${errorMessage(error)}`)}finally{store.setSwitching(null)}},applyModel=async(value,{chainEffort=!1}={})=>{let store=useStore2.getState(),config=store.modelConfig;if(value==null||value===config?.currentValue)return!1;let next=modelChoices(config).find((choice)=>choice.value===value);store.setSwitching(`Switching to ${next?.name??value}…`);let switched=!1;try{let name=await clientRef.current.setModel(value);switched=!0,recorderRef.current?.recordModel(name);try{await saveModel(value,useStore2.getState().providerId)}catch(error){store.push("system",`Failed to save model preference: ${errorMessage(error)}`)}}catch(error){store.push("error",`Failed to switch model: ${errorMessage(error)}`)}finally{store.setSwitching(null)}if(chainEffort&&switched&&effortChoices(useStore2.getState().effortConfig).length>0&&useStore2.getState().overlay?.kind!=="config")openEffortPicker();return switched},refreshMiroCatalog=()=>{let client=clientRef.current;if(typeof client?.reloadSessionOptions==="function")client.reloadSessionOptions()},guardModelChoices=()=>{let store=useStore2.getState();if(store.overlay||store.switching)return null;if(store.busy)return store.push("system","Please wait for the current response to finish before switching models."),null;let choices=modelChoices(store.modelConfig);if(!store.modelConfig||choices.length===0)return store.push("system","The current ACP session does not offer switchable models."),null;return choices},openModelPicker=()=>{refreshMiroCatalog();let store=useStore2.getState(),choices=guardModelChoices();if(!choices)return;let sorted=[...choices.filter((c)=>c.current),...choices.filter((c)=>!c.current)];store.setOverlay({kind:"model",title:"Select model",emptyText:"No matching models",escapeValue:null,items:sorted.map((choice)=>({value:choice.value,label:choice.name,groupName:choice.groupName||"",current:Boolean(choice.current)})),resolve:(value)=>{if(useStore2.getState().setOverlay(null),value==null)return;applyModel(value,{chainEffort:!0})}})},setModelByName=(args)=>{refreshMiroCatalog();let store=useStore2.getState(),choices=guardModelChoices();if(!choices)return;let hit=matchConfigChoice(store.modelConfig,args);if(!hit){let names=choices.map((choice)=>choice.groupName?`${choice.groupName} / ${choice.name}`:choice.name).join(", ");store.push("error",`Model "${args}" not found. Available models: ${names}`);return}applyModel(hit.value,{chainEffort:!0})},applyEffort=async(value)=>{let store=useStore2.getState(),config=store.effortConfig;if(value==null||value===config?.currentValue)return;let next=effortChoices(config).find((choice)=>choice.value===value);store.setSwitching(`Setting effort level ${next?.name??value}…`);try{await clientRef.current.setEffort(value);try{await saveEffort(value,useStore2.getState().providerId)}catch(error){store.push("system",`Failed to save effort preference: ${errorMessage(error)}`)}}catch(error){store.push("error",`Failed to set effort level: ${errorMessage(error)}`)}finally{store.setSwitching(null)}},guardEffortChoices=()=>{let store=useStore2.getState();if(store.overlay||store.switching)return null;if(store.busy)return store.push("system","Please wait for the current response to finish before setting effort level."),null;let choices=effortChoices(store.effortConfig);if(!store.effortConfig||choices.length===0)return store.push("system","The current model does not support effort selection."),null;return choices},openEffortPicker=()=>{let store=useStore2.getState(),choices=guardEffortChoices();if(!choices)return;store.setOverlay({kind:"effort",title:"Select effort level",emptyText:"No matching effort levels",escapeValue:null,items:choices.map((choice)=>({value:choice.value,label:choice.name??choice.value,current:Boolean(choice.current)})),resolve:(value)=>{store.setOverlay(null),applyEffort(value)}})},openPermissionPicker=()=>{let store=useStore2.getState();if(store.overlay||store.switching)return;if(!isMiroProvider({id:store.providerId})){store.push("system","Permission mode is only available in Miro; ACP providers control their own approvals.");return}let current=normalizePermissionMode(clientRef.current?.permissionMode);store.setOverlay({kind:"permissions",title:"Select permission mode",emptyText:"No matching permission modes",escapeValue:null,footerHint:"Enter to apply · Esc to cancel",items:PERMISSION_MODE_CHOICES.map((choice)=>({value:choice.value,label:choice.name,right:choice.description,current:choice.value===current})),resolve:(value)=>{if(store.setOverlay(null),value)applyPermissionMode(value)}})},applyPermissionMode=(value)=>applyPermissionModeToClient(clientRef.current,value),setPermissionModeByName=(args)=>{let store=useStore2.getState();if(!isMiroProvider({id:store.providerId})){store.push("system","Permission mode is only available in Miro; ACP providers control their own approvals.");return}let hit=matchPermissionMode(args);if(!hit){let names=PERMISSION_MODE_CHOICES.map((choice)=>choice.value).join(", ");store.push("error",`Invalid permission mode "${args}". Available modes: ${names}`);return}applyPermissionMode(hit.value)},applyThinkingDisplay=async(value)=>{let mode=normalizeThinkingDisplayMode(value),store=useStore2.getState();setThinkingDisplay(mode),store.setThinkingDisplay(mode);try{if(await saveThinkingDisplay(mode),!useStore2.getState().busy)store.push("system",`Thinking display: ${mode}.`)}catch(error){if(!useStore2.getState().busy)store.push("system",`Thinking display set to ${mode} for this session, but failed to save: ${errorMessage(error)}`)}},openThinkingPicker=()=>{let store=useStore2.getState();if(store.overlay||store.switching)return;if(store.busy){store.push("system","Use /thinking compact|full|hidden while a response is running.");return}store.setOverlay({kind:"thinking",title:"Thinking display",emptyText:"No matching display modes",escapeValue:null,footerHint:"Enter to apply · Esc to cancel",items:THINKING_DISPLAY_CHOICES.map((choice)=>({value:choice.value,label:choice.name,right:choice.description,current:choice.value===thinkingDisplay})),resolve:(value)=>{if(store.setOverlay(null),value)applyThinkingDisplay(value)}})},setThinkingDisplayByName=(args)=>{let hit=matchThinkingDisplayMode(args);if(!hit){let names=THINKING_DISPLAY_CHOICES.map((choice)=>choice.value).join(", ");useStore2.getState().push("error",`Invalid thinking display "${args}". Available modes: ${names}`);return}applyThinkingDisplay(hit.value)},setEffortByName=(args)=>{let store=useStore2.getState(),choices=guardEffortChoices();if(!choices)return;let lower=args.toLowerCase(),hit=choices.find((choice)=>String(choice.value).toLowerCase()===lower)??choices.find((choice)=>String(choice.name??"").toLowerCase()===lower);if(!hit){let names=choices.map((choice)=>choice.name??choice.value).join(", ");store.push("error",`Invalid effort level "${args}". Available levels: ${names}`);return}applyEffort(hit.value)},applyMode=async(modeId)=>{let store=useStore2.getState(),modes=store.modes;if(modeSwitchingRef.current||modeId==null||modeId===modes?.currentModeId)return;modeSwitchingRef.current=!0,setModeSwitching(!0);try{await clientRef.current.setMode(modeId)}catch(error){store.push("error",`Failed to switch mode: ${errorMessage(error)}`)}finally{modeSwitchingRef.current=!1,setModeSwitching(!1)}},handlePlanCommand=(args)=>{let store=useStore2.getState(),modes=store.modes;if(!(modes?.availableModes?.map((mode)=>mode.id)??[]).includes("plan")){store.push("system","Plan Mode is not available for this provider.");return}let value=String(args??"").trim().toLowerCase();if(value==="status"){store.push("system",`${modes.currentModeId==="plan"?"Plan":"Default"} Mode is active.`);return}if(value&&!["on","off"].includes(value)){store.push("error","Usage: /plan [on|off|status]");return}if(store.busy){store.push("system","Please wait for the current response to finish before switching Plan Mode.");return}applyMode((()=>{if(value==="on")return"plan";if(value==="off")return"default";return modes.currentModeId==="plan"?"default":"plan"})())},applyConfigOptionValue=async(option,value)=>{if(option==null||value==null||value===option.currentValue)return;let store=useStore2.getState();if(isLanguageOption(option)){await applyLanguage(value);return}if(store.modelConfig&&option.id===store.modelConfig.id){await applyModel(value);return}if(store.effortConfig&&option.id===store.effortConfig.id){await applyEffort(value);return}if(option.id==="mode"||option.category==="mode"){await applyMode(value);return}store.setSwitching(`Setting ${option.name??option.id}…`);try{await clientRef.current.setConfigOption(option.id,value)}catch(error){store.push("error",`Failed to set ${option.name??option.id}: ${errorMessage(error)}`)}finally{store.setSwitching(null)}},applyLanguage=async(value)=>{let store=useStore2.getState();if(value==null||value===languageRef.current)return;setLanguage(value),languageRef.current=value;let label=languageDisplayName(value);try{await saveLanguage(value),store.push("system",`Prompt language set to ${label}.`)}catch(error){store.push("system",`Prompt language set to ${label} for this session, but failed to save: ${errorMessage(error)}`)}},openConfigPanel=(focusId=null)=>{let store=useStore2.getState();if(store.overlay||store.switching)return;if(store.busy){store.push("system","Please wait for the current response to finish before changing config.");return}store.setOverlay({kind:"config",focusId,escapeValue:null,resolve:()=>useStore2.getState().setOverlay(null)})},openStatusLineSetup=()=>{let store=useStore2.getState();if(store.overlay||store.switching)return;if(store.busy){store.push("system","Please wait for the current response to finish before changing the status line.");return}store.setOverlay({kind:"statusline",escapeValue:null,configuredIds:statusLineConfig.items,useColors:statusLineConfig.useColors,snapshot:{modelName:modelConfig?currentModelName(modelConfig):null,effortName:currentEffortName(effortConfig),modeName:modes?.availableModes?.find((mode)=>mode.id===modes?.currentModeId)?.name??modes?.currentModeId??null,cwd:process.cwd(),projectName:projectNameFor(process.cwd()),hostname:hostname2(),gitBranch,providerName,sessionId,sessionTitle,version:APP_VERSION,usage,sessionTokens,sessionCost,plan:planProgress,busy,cancelling,thinking,goal},resolve:(value)=>{if(useStore2.getState().setOverlay(null),!value)return;let next={items:(value.items??[]).filter((item)=>item.enabled&&item.id!=="use-colors").map((item)=>item.id),useColors:Boolean(value.useColors)};setStatusLineConfig(next);try{writeStatusLineSettings({items:next.items,useColors:next.useColors}),useStore2.getState().push("system","Status line updated.")}catch(error){useStore2.getState().push("system",`Status line updated for this session, but failed to save: ${errorMessage(error)}`)}}})},resetStatusLine=()=>{let store=useStore2.getState();if(store.overlay||store.switching||store.busy)return;let next={items:DEFAULT_STATUS_LINE_ITEMS,useColors:!0};setStatusLineConfig(next);try{writeStatusLineSettings({items:next.items,useColors:next.useColors}),store.push("system","Status line reset.")}catch(error){store.push("system",`Status line reset for this session, but failed to save: ${errorMessage(error)}`)}},handleConfigCommand=(args)=>{let store=useStore2.getState();if(!args){openConfigPanel();return}if(store.overlay||store.switching)return;if(store.busy){store.push("system","Please wait for the current response to finish before changing config.");return}let listed=withLanguageOption(store.configOptions,languageRef.current),space=args.search(/\s/),head=space===-1?args:args.slice(0,space),rest=space===-1?"":args.slice(space).trim(),option=matchConfigOption(listed,head);if(!option){let names=listed.filter((item)=>item?.id).map((item)=>item.name??item.id).join(", ");store.push("error",`Config option "${head}" not found.${names?` Available: ${names}`:""}`);return}if(!rest){openConfigPanel(option.id);return}let choices=configChoices(option);if(choices.length===0){store.push("system",`${option.name??option.id} has no selectable values.`);return}let hit=matchConfigChoice(option,rest);if(!hit){let names=choices.map((choice)=>choice.name??choice.value).join(", ");store.push("error",`Invalid value "${rest}" for ${option.name??option.id}. Available: ${names}`);return}applyConfigOptionValue(option,hit.value)},cycleMode=()=>{let store=useStore2.getState();if(store.overlay||store.switching||store.busy||modeSwitchingRef.current)return;let nextId=getNextModeId(store.modes);if(nextId==null)return;applyMode(nextId)},guardSessions=()=>{let store=useStore2.getState();if(store.overlay||store.switching)return null;if(store.busy)return store.push("system","Please wait for the current response to finish before switching sessions."),null;return listSessions(process.cwd(),store.providerId)},resumeSession=(sessionId)=>{let store=useStore2.getState(),provider=providerRef.current;if(!provider)return;store.setSwitching("Resuming session…");try{checkpointUiState(),clientRef.current?.close(),store.clearTranscript(),store.reconnecting(),startClient(provider,sessionId)}finally{store.setSwitching(null)}},resumeById=(args)=>{let sessions=guardSessions();if(!sessions)return;let store=useStore2.getState();if(sessions.length===0){store.push("system","No saved sessions for this project yet.");return}let hit=sessions.find((s)=>s.sessionId===args)??sessions.find((s)=>s.sessionId.startsWith(args));if(!hit){store.push("error",`Session "${args}" not found. Use /sessions to list saved sessions.`);return}resumeSession(hit.sessionId)},openSessionPicker=()=>{let sessions=guardSessions();if(!sessions)return;let store=useStore2.getState();if(sessions.length===0){store.push("system","No saved sessions for this project yet.");return}let byId=new Map(sessions.map((s)=>[s.sessionId,s]));store.setOverlay({kind:"session",title:"Resume session",emptyText:"No matching sessions",escapeValue:null,items:sessions.map((s)=>({value:s.sessionId,label:`${formatSessionAge(s.updatedAt)} ${s.title} · ${s.messages} msgs`,right:""})),resolve:(value)=>{store.setOverlay(null);let hit=byId.get(value);if(hit)resumeSession(hit.sessionId)}})},startNewSession=({clearTerminal=!1}={})=>{let store=useStore2.getState();if(store.busy||store.overlay||store.switching){store.push("system","Please wait for the current action to finish before starting a new session.");return}let provider=providerRef.current;if(!provider)return;if(clearTerminal)write(CLEAR_TERMINAL);checkpointUiState(),clientRef.current?.close(),store.clearTranscript(),store.setSessionMeta(null),store.reconnecting(),startClient(provider,null)},listSessionsSummary=()=>{let sessions=guardSessions();if(!sessions)return;let store=useStore2.getState();if(sessions.length===0){store.push("system","No saved sessions for this project yet.");return}let lines=sessions.slice(0,20).map((s)=>` ${s.sessionId.slice(0,8)} ${s.providerId??"?"} ${formatSessionAge(s.updatedAt)} ${s.messages} msgs ${s.title}`).join(`
2263
+ `);return addSection("request","Request",requestFields),addSection("request","Task",request.message??subagent.taskSummary),addSection("output","Output",subagent.text||"No output retained."),rows}function statusColor(status){if(["completed","done","success"].includes(status))return"green";if(["failed","error","rejected"].includes(status))return"red";return"yellow"}function detailLine(line){if(line.kind==="blank")return"";if(line.kind==="status")return style(line.text,{bold:!0,color:statusColor(line.status)});let color=DETAIL_SECTION_COLORS[line.section]??"cyan";if(line.kind==="section")return style(` ${line.text} `,{bold:!0,inverse:!0,color});return style("│ ",{bold:!0,color})+(line.text.length>0?line.text:" ")}function entryLabel(entry){if(entry?.kind==="thought"){let thought=entry.thought,title=thought.title??splitThinkingText(thought.text).title,duration=thought.durationMs==null?null:formatDuration(thought.durationMs);return[title?`Thought: ${title}`:"Thought",duration].filter(Boolean).join(" · ")}if(entry?.kind==="bash"){let command=entry.card?.command??"";return command?`Shell: ${command}`:"Shell"}let item=entry?.item,label=item?.label?.args?`${item.label.name}(${item.label.args})`:item?.label?.name??(entry?.kind==="subagent"?"Sub-agent":"Tool");return entry?.kind==="subagent"?`Sub-agent: ${label}`:`Tool: ${label}`}function entryType(entry){if(entry?.kind==="subagent")return"Agent";if(entry?.kind==="thought")return"Thought";if(entry?.kind==="bash")return"Shell";return"Tool"}function entryTitle(entry){if(entry?.kind==="thought")return entry.thought?.title??splitThinkingText(entry.thought?.text).title??"Thinking";if(entry?.kind==="bash")return entry.card?.command??"Shell";let item=entry?.item;return item?.label?.args?`${item.label.name}(${item.label.args})`:item?.label?.name??"Tool"}function listItem(entry,index,total){return{value:index,label:`${String(index+1).padStart(String(total).length," ")} ${entryType(entry).padEnd(TYPE_COLUMN_WIDTH)}`,right:entryTitle(entry)}}function listHeader(total){return`${"#".padStart(String(total).length," ")} ${"Type".padEnd(TYPE_COLUMN_WIDTH)} Title`}function subagentToolEntries(entry){return(entry?.item?.subagent?.tools??[]).filter((tool)=>!tool.removed).map((tool,index)=>({id:`${entry.id??"subagent"}:child:${index}`,kind:"tool",item:{label:{name:tool.name??"Tool",args:tool.args??""},status:tool.status,detail:tool.result==null?void 0:{output:tool.result}}}))}class ReviewBrowser{entries;onClose;page;list=null;listKey="";offset=0;offsetKey="";lastPageRows=1;lastMaxOffset=0;constructor(entries,initialIndex,onClose){this.entries=entries;this.onClose=onClose;this.page={kind:"root",selected:Math.max(0,Math.min(entries.length-1,initialIndex))}}listPicker(entries,selected,canGoBack,onSelect,onBack){let key=`${this.page.kind}:${this.page.selected}`;if(this.list&&this.listKey===key)return this.list;return this.listKey=key,this.list=new Picker({subtitle:listHeader(entries.length),items:entries.map((entry,index)=>listItem(entry,index,entries.length)),selected,color:"cyan",compactColumns:!0,canGoBack,emptyText:"No retained items",embed:{rows:0,columns:0},onSelect:(row)=>onSelect(row.value),onCancel:onBack}),this.list}currentList(){if(this.page.kind==="root"){let entries=this.entries;return{label:`${entries.length} item${entries.length===1?"":"s"}`,canGoBack:!1,picker:this.listPicker(entries,this.page.selected,!1,(selected)=>{this.page={kind:"detail",selected}},this.onClose)}}if(this.page.kind==="agent-tools"){let parent=this.page.selected,tools=subagentToolEntries(this.entries[parent]??null);return{label:"Agent tool calls",canGoBack:!0,picker:this.listPicker(tools,this.page.toolSelected??0,!0,(toolSelected)=>{this.page={kind:"tool-detail",selected:parent,toolSelected}},()=>{this.page={kind:"detail",selected:parent}})}}return null}detailEntries(){return this.page.kind==="tool-detail"?subagentToolEntries(this.entries[this.page.selected]??null):this.entries}detailIndex(){return this.page.kind==="detail"?this.page.selected:this.page.toolSelected??0}onKey(input,key){let list=this.currentList();if(list){list.picker.onKey(input,key);return}let entries=this.detailEntries(),selected=this.detailIndex(),entry=entries[selected]??null,hasSubagentTools=entry?.kind==="subagent"&&subagentToolEntries(entry).length>0;if(key.escape){this.page=this.page.kind==="detail"?{kind:"root",selected:this.page.selected}:{kind:"agent-tools",selected:this.page.selected,toolSelected:this.page.toolSelected};return}if(key.return&&hasSubagentTools){this.page={kind:"agent-tools",selected:this.page.selected,toolSelected:0};return}if(key.leftArrow||key.rightArrow){let next=Math.max(0,Math.min(entries.length-1,selected+(key.leftArrow?-1:1)));if(next===selected)return;this.page=this.page.kind==="detail"?{kind:"detail",selected:next}:{kind:"tool-detail",selected:this.page.selected,toolSelected:next};return}if(key.home)this.offset=0;else if(key.end)this.offset=this.lastMaxOffset;else if(key.upArrow)this.offset=Math.max(0,this.offset-1);else if(key.downArrow)this.offset=Math.min(this.lastMaxOffset,this.offset+1);else if(key.pageUp)this.offset=Math.max(0,this.offset-this.lastPageRows);else if(key.pageDown)this.offset=Math.min(this.lastMaxOffset,this.offset+this.lastPageRows)}onPaste(text){this.currentList()?.picker.onPaste(text)}render(width,rows){let bodyRows=frameBodyRows(rows),list=this.currentList();if(list){list.picker.options.embed={rows:bodyRows,columns:Math.max(1,width-FRAME_BODY_PADDING_X*2)};let view=list.picker.render(width,rows),lines=frame(list.label,footerHint({canGoBack:list.canGoBack}),view.lines,width,rows),cursor=view.cursor&&view.cursor.row<bodyRows?{row:view.cursor.row+2,col:view.cursor.col+FRAME_BODY_PADDING_X}:null;return{lines,cursor}}let entries=this.detailEntries(),index=this.detailIndex(),entry=entries[index]??null,total=entries.length,contentWidth=Math.max(1,width-2),key=`${this.page.kind}:${this.page.selected}:${index}`;if(key!==this.offsetKey)this.offsetKey=key,this.offset=0;let isDiff=entry?.kind==="tool"&&!!entry.item?.diff,body=[],lineCount=0,pageRows=isDiff?Math.max(1,bodyRows-3):bodyRows;if(isDiff)lineCount=diffLineCount(entry.item.diff,contentWidth);else if(entry?.kind==="thought"){let text=splitThinkingText(entry.thought?.text).body;body=text?wrap(renderMarkdown(text),contentWidth):["No retained details."]}else if(entry?.kind==="bash"){let card=entry.card??{};for(let line of card.lines??[])for(let row of wrapVisualRows(line.text,contentWidth))body.push(style(row.length>0?row:" ",{dim:!0,color:line.err?"yellow":void 0}));if(card.hidden>0)body.push(dim(`… ${card.hidden} more lines not retained`))}else if(entry?.kind==="subagent")body=subagentLines(entry.item,contentWidth).map(detailLine);else if(entry)body=detailLines(entry.item,contentWidth).map(detailLine);if(!isDiff)lineCount=body.length;let maxOffset=Math.max(0,lineCount-pageRows);this.offset=Math.min(this.offset,maxOffset),this.lastPageRows=pageRows,this.lastMaxOffset=maxOffset;let shown=isDiff?renderDiff(entry.item.diff,{mode:"full",offset:this.offset,maxLines:pageRows,width:contentWidth}):body.slice(this.offset,this.offset+pageRows),hasSubagentTools=entry?.kind==="subagent"&&subagentToolEntries(entry).length>0,footer=["↑↓/Pg/Home/End scroll",total>1?"←→ switch item":null,hasSubagentTools?"Enter to view tool calls":null,"Esc to go back",maxOffset>0?`${this.offset+1}-${Math.min(lineCount,this.offset+pageRows)}/${lineCount}`:null].filter(Boolean).join(" · "),label=total>1?`${index+1}/${total} · ${entryLabel(entry)}`:entryLabel(entry);return{lines:frame(label,footer,shown,width,rows),cursor:null}}}var FRAME_CHROME_ROWS=4,FRAME_BODY_PADDING_X=1,DETAIL_SECTION_COLORS,TYPE_COLUMN_WIDTH=7;var init_review_browser=__esm(()=>{init_markdown();init_thinking();init_layout();init_diff2();init_picker();DETAIL_SECTION_COLORS={input:"yellow",output:"green",locations:"blue",request:"magenta",tools:"cyan"}});function hasQuestionPreview(question){return!question?.multiSelect&&question?.options?.some((option)=>option.preview)}function visibleQuestionOptions(question){let options=Array.isArray(question?.options)?question.options:[];if(hasQuestionPreview(question))return options;return[...options,{label:"Other",description:"Type a custom answer",value:"__other__"}]}function initialQuestionState(question){return{focused:0,selected:question.multiSelect?[]:null,custom:"",notes:""}}function createUserQuestionState(questions){return{index:0,view:"question",editing:null,reviewIndex:0,questions:Object.fromEntries(questions.map((question)=>[question.id,initialQuestionState(question)]))}}function updateCurrent(state,questions,update){let question=questions[state.index];if(!question)return state;return{...state,questions:{...state.questions,[question.id]:update(state.questions[question.id]??initialQuestionState(question),question)}}}function userQuestionReducer(state,action,questions){let lastTab=questions.length;switch(action.type){case"switch-tab":{let tab=Math.max(0,Math.min(lastTab,action.index)),onReview=tab===lastTab;return{...state,index:Math.min(tab,Math.max(0,questions.length-1)),view:onReview?"review":"question",editing:null}}case"step-tab":{let next=((state.view==="review"?lastTab:state.index)+action.delta+lastTab+1)%(lastTab+1);return userQuestionReducer(state,{type:"switch-tab",index:next},questions)}case"move-option":return updateCurrent(state,questions,(current,question)=>{let count=visibleQuestionOptions(question).length+(hasQuestionPreview(question)?1:0);if(count===0)return current;return{...current,focused:(current.focused+action.delta+count)%count}});case"select-single":return updateCurrent(state,questions,(current)=>({...current,selected:action.value}));case"toggle-multi":return updateCurrent(state,questions,(current)=>{let selected=Array.isArray(current.selected)?current.selected:[];return{...current,selected:selected.includes(action.value)?selected.filter((value)=>value!==action.value):[...selected,action.value]}});case"begin-edit":return{...state,editing:action.field};case"end-edit":return{...state,editing:null};case"set-text":return updateCurrent(state,questions,(current)=>({...current,[action.field]:action.value}));case"move-review":return{...state,reviewIndex:(state.reviewIndex+action.delta+2)%2};default:return state}}function answerForQuestion(question,state){if(!state)return"";if(question.multiSelect)return(Array.isArray(state.selected)?state.selected:[]).map((value)=>value==="__other__"?state.custom.trim():value).filter(Boolean).join(", ");if(state.selected==="__other__")return state.custom.trim();return typeof state.selected==="string"?state.selected:""}function annotationEntry(preview,notes){if(!preview&&!notes)return null;return{...preview?{preview}:{},...notes?{notes}:{}}}function buildUserQuestionResult(questions,state){let answers={},annotations={};for(let question of questions){let questionState=state.questions[question.id],answer=answerForQuestion(question,questionState);if(answer)answers[question.id]=answer;let selectedOption=!question.multiSelect?question.options.find((option)=>option.label===questionState?.selected):null,annotation=annotationEntry(selectedOption?.preview,questionState?.notes?.trim());if(annotation)annotations[question.id]=annotation}return{answers,...Object.keys(annotations).length>0?{annotations}:{}}}function allQuestionsAnswered(questions,state){return questions.every((question)=>Boolean(answerForQuestion(question,state.questions[question.id])))}var OTHER_VALUE="__other__";var init_user_question_state=()=>{};function cleanInput2(input){return String(input??"").replace(/[\r\n]+/g,"").replace(/[\u0000-\u001F\u007F]/g,"")}class UserQuestionDialog{onResolve;questions;state;constructor(questions,onResolve){this.onResolve=onResolve;this.questions=Array.isArray(questions)?questions:[],this.state=createUserQuestionState(this.questions)}dispatch(action){return this.state=userQuestionReducer(this.state,action,this.questions),this.state}get showReview(){return this.questions.length>1||this.questions.some((item)=>item.multiSelect)}submit(state=this.state){this.onResolve(buildUserQuestionResult(this.questions,state))}advance(nextState){if(!this.showReview&&this.questions.length===1)this.submit(nextState);else if(this.state.index+1<this.questions.length)this.dispatch({type:"switch-tab",index:this.state.index+1});else this.dispatch({type:"switch-tab",index:this.questions.length})}onPaste(text){if(!this.state.editing)return;let question=this.questions[this.state.index],current=this.state.questions[question.id][this.state.editing];this.dispatch({type:"set-text",field:this.state.editing,value:current+cleanInput2(text)})}onKey(input,key){let state=this.state,question=this.questions[state.index];if(!question&&state.view!=="review")return;let questionState=question?state.questions[question.id]:null,options=visibleQuestionOptions(question),previewQuestion=hasQuestionPreview(question);if(state.editing){let editingValue=questionState[state.editing];if(key.escape){this.dispatch({type:"end-edit"});return}if(key.return){let editing=state.editing,next=this.dispatch({type:"end-edit"});if(editing==="custom"&&!question.multiSelect&&questionState.custom.trim())this.advance(next);return}if(key.backspace||key.delete){this.dispatch({type:"set-text",field:state.editing,value:[...editingValue].slice(0,-1).join("")});return}if(key.ctrl||key.meta||key.tab)return;let text=cleanInput2(input);if(text)this.dispatch({type:"set-text",field:state.editing,value:editingValue+text});return}if(key.escape)return this.onResolve(null);if(key.tab||key.leftArrow||key.rightArrow){if(!this.showReview)return;let delta=key.leftArrow||key.tab&&key.shift?-1:1;this.dispatch({type:"step-tab",delta});return}if(state.view==="review"){if(key.upArrow||input==="k")return void this.dispatch({type:"move-review",delta:-1});if(key.downArrow||input==="j")return void this.dispatch({type:"move-review",delta:1});if(input==="1")return this.submit();if(input==="2")return this.onResolve(null);if(key.return)return state.reviewIndex===0?this.submit():this.onResolve(null);return}if(key.upArrow||input==="k")return void this.dispatch({type:"move-option",delta:-1});if(key.downArrow||input==="j")return void this.dispatch({type:"move-option",delta:1});let focusedOption=options[questionState.focused],notesFocused=previewQuestion&&questionState.focused===options.length,activate=(option)=>{if(!option)return;let value=option.value??option.label;if(question.multiSelect){let wasSelected=questionState.selected.includes(value);if(this.dispatch({type:"toggle-multi",value}),value===OTHER_VALUE&&!wasSelected)this.dispatch({type:"begin-edit",field:"custom"});return}let selectedState=this.dispatch({type:"select-single",value});if(value===OTHER_VALUE)this.dispatch({type:"begin-edit",field:"custom"});else this.advance(selectedState)},digit=Number.parseInt(input,10);if(Number.isInteger(digit)&&digit>=1&&digit<=options.length)return activate(options[digit-1]);if(input===" "&&question.multiSelect)return activate(focusedOption);if(key.return){if(notesFocused)return void this.dispatch({type:"begin-edit",field:"notes"});if(question.multiSelect&&focusedOption?.value===OTHER_VALUE){if(!questionState.selected.includes(OTHER_VALUE))this.dispatch({type:"toggle-multi",value:OTHER_VALUE});return void this.dispatch({type:"begin-edit",field:"custom"})}if(question.multiSelect)return this.advance(state);return activate(focusedOption)}}navigation(width){let{questions,state}=this;if(questions.length===1&&!this.showReview)return null;let tabCount=questions.length+(this.showReview?1:0),labelWidth=Math.max(3,Math.floor((width-8)/Math.max(1,tabCount))-4),line=style("← ",{dim:state.view==="question"&&state.index===0});if(questions.forEach((question,index)=>{let active=state.view==="question"&&state.index===index,answered=Boolean(answerForQuestion(question,state.questions[question.id])),label=truncateToCellWidth(question.header||`Q${index+1}`,labelWidth);line+=style(` ${answered?"[x]":"[ ]"} ${label} `,{inverse:active,color:active?"cyan":void 0})}),this.showReview){let active=state.view==="review";line+=style(" ✓ Submit ",{inverse:active,color:active?"cyan":void 0})}return line+=style(" →",{dim:state.view==="review"}),truncate4(line,width)}render(width,rows){let{questions,state}=this,question=questions[state.index];if(!question)return{lines:[]};let questionState=state.questions[question.id],options=visibleQuestionOptions(question),previewQuestion=hasQuestionPreview(question),lines=[dim("─".repeat(width))],nav=this.navigation(width);if(nav)lines.push(nav,"");let cursor=null;if(state.view==="review"){let complete=allQuestionsAnswered(questions,state);if(lines.push(style("Review your answers",{bold:!0})),!complete)lines.push(style("! You have not answered all questions",{color:"yellow"}));lines.push("");for(let item of questions){let answer=answerForQuestion(item,state.questions[item.id]);lines.push(...wrap(`• ${item.question}`,width)),lines.push(` ${style(`→ ${answer||"Not answered"}`,{color:answer?"green":void 0,dim:!answer})}`),lines.push("")}lines.push(dim("Ready to submit your answers?")),lines.push(style(`${state.reviewIndex===0?"❯":" "} 1. Submit answers`,{color:state.reviewIndex===0?"cyan":void 0})),lines.push(style(`${state.reviewIndex===1?"❯":" "} 2. Cancel`,{color:state.reviewIndex===1?"cyan":void 0}))}else{lines.push(...wrap(style(question.question,{bold:!0}),width)),lines.push("");let sideBySide=previewQuestion&&width>=72,leftWidth=sideBySide?Math.min(34,Math.floor(width*0.4)):width,left=[],leftCursor=null;if(options.forEach((option,index)=>{let value=option.value??option.label,selected=question.multiSelect?questionState.selected.includes(value):questionState.selected===value,active=questionState.focused===index,editing=state.editing==="custom"&&index===questionState.focused,choice=question.multiSelect?`[${selected?"x":" "}]`:selected?"●":"○",head=`${active?"❯":" "} ${index+1}. ${choice} ${option.label}`,extra=option.value===OTHER_VALUE&&(editing||questionState.custom)?` ${questionState.custom||"Type something…"}`:"";if(editing)leftCursor={row:left.length,col:Math.min(stringWidth2(`${head} ${questionState.custom}`),leftWidth)};if(left.push(truncate4(style(head,{color:active?"cyan":void 0})+extra,leftWidth)),option.description)for(let row of wrap(option.description,Math.max(1,leftWidth-5)))left.push(` ${dim(row)}`)}),previewQuestion){let active=questionState.focused===options.length;if(left.push(""),state.editing==="notes")leftCursor={row:left.length,col:Math.min(stringWidth2(` Notes: ${questionState.notes}`),leftWidth)};left.push(truncate4(style(`${active?"❯":" "} Notes: `,{color:active?"cyan":void 0})+(questionState.notes||dim("optional")),leftWidth))}if(previewQuestion){let previewOption=options[questionState.focused]??null,maxPreviewLines=Math.max(3,rows-15),previewWidth=sideBySide?Math.max(10,width-leftWidth-2):width,previewLines=previewOption?.preview?wrap(renderMarkdown(previewOption.preview),Math.max(1,previewWidth-4)):["No preview available"],shown=previewLines.slice(0,maxPreviewLines);if(previewLines.length>maxPreviewLines)shown.push(dim("… preview truncated"));let box=border(shown,previewWidth,{style:"single",color:"gray",paddingX:1}),top=lines.length;if(sideBySide){let height=Math.max(left.length,box.length);for(let row=0;row<height;row+=1)lines.push(padEnd(left[row]??"",leftWidth)+" "+(box[row]??""))}else lines.push(...left,"",...box);if(leftCursor)cursor={row:top+leftCursor.row,col:leftCursor.col}}else{if(leftCursor)cursor={row:lines.length+leftCursor.row,col:leftCursor.col};lines.push(...left)}}let hint=(()=>{if(state.editing)return"Enter to save · Esc to return";if(state.view==="review")return"↑↓ to select · Enter to confirm · Tab/Shift+Tab to revisit · Esc to cancel";if(question.multiSelect)return"↑↓ to navigate · Space to toggle · Enter for next · Tab/Shift+Tab to navigate · Esc to cancel";return`${questions.length===1?"↑↓":"Tab/Shift+Tab · ↑↓"} to navigate · Enter to select · Esc to cancel`})();return lines.push("",dim(truncate4(hint,width))),{lines,cursor}}}var init_user_question=__esm(()=>{init_markdown();init_markdown_width();init_picker_rows();init_user_question_state();init_layout()});function appendView(target,child){let offset=target.lines.length;if(target.lines.push(...child.lines),child.cursor)target.cursor={row:child.cursor.row+offset,col:child.cursor.col}}import{readFileSync as readFileSync14,writeFileSync as writeFileSync10}from"node:fs";import{hostname as hostname2}from"node:os";import{randomUUID as randomUUID7}from"node:crypto";import{join as join16}from"node:path";function prepareSubmittedInput(raw,display){let content=String(raw??""),commandText=content.trim();if(!commandText)return null;return{content,commandText,display:display==null?null:String(display),transcriptText:content}}function bareExitCommand(text){let lower=String(text??"").trim().toLowerCase();return lower==="exit"||lower==="quit"?{key:"exit",args:""}:null}function resolveStartupModel(config,startupModel,savedModel){let choices=modelChoices(config);if(!config||choices.length===0)return{value:null,unavailable:startupModel!=null};let matched=matchConfigChoice(config,startupModel??savedModel);if(startupModel!=null&&!matched)return{value:null,unavailable:!0};return{value:matched?.value??choices[0].value,unavailable:!1}}function resolveStartupEffort(config,startupEffort,savedEffort){let matched=startupEffort!=null?matchConfigChoice(config,startupEffort):effortChoices(config).find((choice)=>choice.value===savedEffort);return{value:matched?.value??null,unavailable:startupEffort!=null&&!matched}}function buildPermissionDialogItems(options){let kindRank={allow_once:0,allow_session:1,allow_family:2,reject_once:3,reject_always:4};return[...options??[]].sort((a,b)=>(kindRank[a.kind]??9)-(kindRank[b.kind]??9)).map((option)=>({value:option.optionId,label:option.name,allow:option.kind?.startsWith("allow")??!1}))}function permissionOptionIdForChoice(options,value){return value}function isAwaitingInputOverlay(kind){return AWAITING_INPUT_OVERLAYS.has(kind)}function composerIsHidden(connecting,overlayKind){return Boolean(connecting)||SCREEN_TAKEOVER_OVERLAYS.has(overlayKind)||["model","effort","config","statusline","permissions","thinking"].includes(overlayKind)}function statusLineIsHidden({helpOpen=!1,completionOpen=!1,overlay=null}={}){return helpOpen||completionOpen||overlay!=null}function ctrlCIntent({hasOverlay,hasDraft}){if(hasOverlay)return"overlay";return hasDraft?"draft":"turn"}function cancelOverlay(overlay){if(!overlay)return;if(typeof overlay.resolve==="function"){overlay.resolve(overlay.escapeValue);return}overlay.onCancel?.()}function isClockRunning({activeTools=[],busy=!1,awaitingInput=!1,overlayKind=null,goalActive=!1}={}){if(!busy&&activeTools.length===0&&!goalActive)return!1;if(awaitingInput)return!1;return!SCREEN_TAKEOVER_OVERLAYS.has(overlayKind)}function refreshActiveGoal(client){let store=useStore.getState();if(store.goal?.status!=="active")return null;let snapshot=client?.goalSnapshot?.();if(snapshot==null)return null;return store.setGoal(snapshot),snapshot}function emptyComposerSnapshot(){return{value:"",cursor:0,pastes:new Map,nextPasteId:1}}function shouldRecordUiState({composer,queuedInputs,pendingInputs,alreadyRecorded}){if(alreadyRecorded)return!0;if(queuedInputs?.length>0)return!0;if(pendingInputs?.length>0)return!0;return Boolean(composer?.value)||(composer?.pastes?.size??0)>0}function formatSessionAge(ts){let diff=Date.now()-ts,min=Math.floor(diff/60000);if(min<1)return"just now";if(min<60)return`${min}m ago`;let hr=Math.floor(min/60);if(hr<24)return`${hr}h ago`;return`${Math.floor(hr/24)}d ago`}function ref5(value){return{current:value}}function createTuiApp({continueSessionId=null,startupAcp=null,startupModel=null,startupEffort=null,startupPermissionMode=null,startupInteractionMode=null},host){let{write,invalidate}=host,clientRef=ref5(null),providerRef=ref5(null),recorderRef=ref5(null),uiCheckpointTimerRef=ref5(null),pendingSessionKeyRef=ref5(0),goalTakeoverRef=ref5(null),goalAfterStopNoticeRef=ref5(null),composerSnapshotRef=ref5(null),uiStateRecordedRef=ref5(!1),composer=new Composer({onSubmit:(raw,display,meta)=>void handleSubmit(raw,display,meta),onCycleMode:()=>cycleMode(),onSnapshotChange:(snapshot)=>handleComposerSnapshotChange(snapshot),onInvalidate:invalidate}),checkpointUiState=()=>{if(uiCheckpointTimerRef.current!=null)clearTimeout(uiCheckpointTimerRef.current),uiCheckpointTimerRef.current=null;if(!recorderRef.current||!composerSnapshotRef.current)return;let composer=composerSnapshotRef.current,{queuedInputs,pendingInputs,queuePaused}=useStore.getState();if(!shouldRecordUiState({composer,queuedInputs,pendingInputs,alreadyRecorded:uiStateRecordedRef.current}))return;uiStateRecordedRef.current=!0,recorderRef.current.recordUiState({composer,queuedInputs,pendingInputs,queuePaused})},scheduleUiCheckpoint=()=>{if(!recorderRef.current||!composerSnapshotRef.current)return;if(uiCheckpointTimerRef.current!=null)clearTimeout(uiCheckpointTimerRef.current);uiCheckpointTimerRef.current=setTimeout(checkpointUiState,200)},handleComposerSnapshotChange=(snapshot)=>{composerSnapshotRef.current=snapshot,scheduleUiCheckpoint()},stageSessionUiState=(key,uiState=null)=>{let snapshot=uiState?.composer??emptyComposerSnapshot();composerSnapshotRef.current=snapshot,uiStateRecordedRef.current=uiState!=null,useStore.getState().replaceQueuedInputs(uiState?.queuedInputs??[]),useStore.setState({pendingInputs:[],queuePaused:uiState?.queuePaused===!0}),composer.restore(key,snapshot),invalidate()},exiting=!1,requestExit=()=>{if(exiting)return;exiting=!0,invalidate(),queueMicrotask(()=>host.exit())},bashTaskRef=ref5(null),thoughtQueueRef=ref5(""),thoughtTimerRef=ref5(null),exitConfirmUntilRef=ref5(0),exitConfirmTimerRef=ref5(null),exitConfirming=!1,setExitConfirming=(value)=>{exitConfirming=value,invalidate()},modeSwitchingRef=ref5(!1),modeSwitching=!1,setModeSwitching=(value)=>{modeSwitching=value,invalidate()},agentBin="provider",statusLineConfig=(()=>{let{items,useColors}=readStatusLineSettings();return{items:items??DEFAULT_STATUS_LINE_ITEMS,useColors}})(),setStatusLineConfig=(next)=>{statusLineConfig=next,refreshGitBranch(),invalidate()},initialThinkingSettings=readThinkingSettings(),thinkingDisplay=initialThinkingSettings.display,setThinkingDisplay=(value)=>{thinkingDisplay=value,useStore.getState().setThinkingDisplay(value)};useStore.getState().setThinkingDisplay(thinkingDisplay);let permissionMode=DEFAULT_PERMISSION_MODE,setPermissionMode=(value)=>{permissionMode=value,invalidate()},permissionModeRef=ref5(startupPermissionMode),applyPermissionModeToClient=async(client,value)=>{let store=useStore.getState(),mode=normalizePermissionMode(value);return await client?.setPermissionMode?.(mode),permissionModeRef.current=mode,setPermissionMode(mode),store.push("system",permissionModeMessage(mode)),mode},languageRef=ref5(readLanguageSetting()),setLanguage=(value)=>{languageRef.current=value,invalidate()},panelConfigOptions=()=>withLanguageOption(useStore.getState().configOptions,languageRef.current),statusLineWarnedRef=ref5(!1),warnInvalidStatusLine=()=>{if(useStore.getState().status!=="ready"||statusLineWarnedRef.current)return;let parsed=parseStatusLineItems(statusLineConfig.items);if(parsed.invalid.length===0)return;statusLineWarnedRef.current=!0;let label=parsed.invalid.length===1?"item":"items";useStore.getState().push("system",`Ignored invalid status line ${label}: ${parsed.invalid.join(", ")}.`)},gitBranchRequest=0,refreshGitBranch=()=>{if(!parseStatusLineItems(statusLineConfig.items).items.includes("git-branch"))return;let seq=++gitBranchRequest;loadGitBranch(process.cwd()).then((branch)=>{if(seq===gitBranchRequest)useStore.getState().setGitBranch(branch)})},flushQueuedThought=()=>{if(thoughtTimerRef.current!=null)clearTimeout(thoughtTimerRef.current),thoughtTimerRef.current=null;let text=thoughtQueueRef.current;if(thoughtQueueRef.current="",!text)return;let store=useStore.getState();if(!store.busy||store.cancelling)return;store.noteThought(text)},discardQueuedThought=()=>{if(thoughtTimerRef.current!=null)clearTimeout(thoughtTimerRef.current),thoughtTimerRef.current=null;thoughtQueueRef.current=""},queueThought=(text)=>{let store=useStore.getState();if(!store.busy||store.cancelling)return;let chunk=String(text??"");if(!chunk)return;if(thoughtQueueRef.current+=chunk,thoughtTimerRef.current==null)thoughtTimerRef.current=setTimeout(()=>{thoughtTimerRef.current=null,flushQueuedThought()},THOUGHT_UI_FLUSH_MS)},clockTimer=null,releaseAnimation=null,lastAwaiting=!1,syncTimers=()=>{let state=useStore.getState(),awaitingInput=isAwaitingInputOverlay(state.overlay?.kind),clockRunning=!exiting&&isClockRunning({activeTools:state.activeTools,busy:state.busy,awaitingInput,overlayKind:state.overlay?.kind,goalActive:state.goal?.status==="active"});if(clockRunning&&clockTimer==null)clockTimer=setInterval(()=>{refreshActiveGoal(clientRef.current),invalidate()},1000);else if(!clockRunning&&clockTimer!=null)clearInterval(clockTimer),clockTimer=null;let animating=!exiting&&(state.busy&&!awaitingInput||state.status==="connecting"||state.switching!=null);if(animating&&releaseAnimation==null)releaseAnimation=acquireAnimationClock();else if(!animating&&releaseAnimation!=null)releaseAnimation(),releaseAnimation=null},unsubscribe=useStore.subscribe((state,previous)=>{if(state.queuedInputs!==previous.queuedInputs||state.pendingInputs!==previous.pendingInputs||state.queuePaused!==previous.queuePaused)scheduleUiCheckpoint();if(state.overlay!==previous.overlay){if(state.overlay!=null)composer.helpOpen=!1;if(SCREEN_TAKEOVER_OVERLAYS.has(previous.overlay?.kind)&&!SCREEN_TAKEOVER_OVERLAYS.has(state.overlay?.kind))host.redrawAll();let awaiting=isAwaitingInputOverlay(state.overlay?.kind);if(awaiting!==lastAwaiting)lastAwaiting=awaiting,useStore.getState().setThoughtPaused(awaiting)}if(state.status!==previous.status)warnInvalidStatusLine();if(state.sessionId!==previous.sessionId)refreshGitBranch();syncTimers(),invalidate()});refreshGitBranch();let attachClient=(client)=>{let store=useStore.getState(),beginSession=({modelConfig:config,sessionId,resumed})=>{if(!sessionId||recorderRef.current?.sessionId===sessionId)return;let savedMeta=null,savedUiState=null,savedGoalState=null;if(resumed){let saved=loadSessionBlocks(sessionId,process.cwd(),useStore.getState().providerId);if(saved){if(saved.blocks.length>0)useStore.getState().hydrate(saved.blocks),client.suppressReplay=!0;useStore.getState().setSessionMeta(saved.meta),savedMeta=saved.meta,savedUiState=saved.uiState,savedGoalState=saved.goalState}useStore.getState().push("system",`Resumed session: ${sessionId}`)}stageSessionUiState(`session:${pendingSessionKeyRef.current}:${sessionId}`,savedUiState);let recorder=new SessionRecorder({sessionId,providerId:useStore.getState().providerId,model:currentModelName(config)});if(savedMeta?.title!=null)recorder.meta.title=savedMeta.title;if(recorderRef.current=recorder,setRecorder(recorder),savedGoalState!=null&&typeof client.restoreGoal==="function")client.restoreGoal(savedGoalState)};client.on("progress",(stage)=>useStore.getState().setConnectionStage(stage)),client.on("ready",({agentName,modelConfig:config,effortConfig:effort,configOptions:configs,modes,sessionId,resumed})=>{useStore.getState().connected({providerName:agentName,sessionId,modelConfig:config,effortConfig:effort,configOptions:configs,modes}),beginSession({modelConfig:config,sessionId,resumed});let resumeQueue=()=>{if(useStore.getState().queuedInputs.length>0)drainQueue()};(async()=>{if(startupInteractionMode!=null&&modes?.availableModes?.some((mode)=>mode.id===startupInteractionMode))await client.setMode(startupInteractionMode);if(startupModel!=null||!resumed)await applyStartupModel(config);if(startupEffort!=null||!resumed)await applyStartupEffort()})().finally(resumeQueue)}),client.on("chunk",(text,messageId)=>{flushQueuedThought(),useStore.getState().appendChunk(text,messageId)}),client.on("user_chunk",(text,messageId)=>{flushQueuedThought(),useStore.getState().appendUserChunk(text,messageId)}),client.on("info",(text)=>{flushQueuedThought(),useStore.getState().push("system",text.trim())}),client.on("tool",(payload)=>{flushQueuedThought(),useStore.getState().upsertTool(payload)}),client.on("auto_review",(payload)=>{useStore.getState().upsertTool({toolCallId:payload.toolCallId,autoReview:payload})}),client.on("thought",queueThought),client.on("input_applied",(input)=>{if(client!==clientRef.current)return;flushQueuedThought(),useStore.getState().applyInput(input),checkpointUiState()}),client.on("input_returned",({inputs,paused})=>{if(client!==clientRef.current)return;useStore.getState().returnInputs(inputs,paused),checkpointUiState()}),client.on("plan",(entries)=>{flushQueuedThought(),useStore.getState().setPlan(entries)}),client.on("commands",(commands)=>useStore.getState().setProviderCommands(commands)),client.on("goal",(snapshot)=>{useStore.getState().setGoal(snapshot),recorderRef.current?.recordGoalState?.(snapshot)}),client.on("plan_mode",(snapshot)=>{recorderRef.current?.recordPlanModeState?.(snapshot)}),client.on("usage",(payload)=>useStore.getState().setUsage(payload)),client.on("session_info",({title})=>useStore.getState().setSessionTitle(title)),client.on("token_usage",(payload)=>useStore.getState().setTokens(payload)),client.on("compaction_state",(active)=>{if(client===clientRef.current)useStore.getState().setCompacting(active)}),client.on("context_checkpoint",(state)=>{if(client===clientRef.current)useStore.getState().recordContextState(state)}),client.on("retry",(payload)=>useStore.getState().setRetryNotice(payload)),client.on("compacted",(payload)=>{flushQueuedThought();let text=typeof payload?.notice==="string"&&payload.notice.length>0?payload.notice:null;if(text)useStore.getState().push("system",text)}),client.on("config",(configs)=>useStore.getState().setConfigs(configs)),client.on("mode",(modes)=>{if(client!==clientRef.current)return;if(useStore.getState().setModes(modes),typeof client.setPermissionMode==="function"){let mode=normalizePermissionMode(client.permissionMode);permissionModeRef.current=mode,setPermissionMode(mode)}}),client.on("stderr",(text)=>useStore.getState().push("stderr",`${client.bin}
2264
+ ${text}`)),client.on("fatal",({error,message})=>{useStore.getState().setFatalError(error),useStore.getState().push("error",message)}),client.onPermissionRequest=(params)=>new Promise((resolve)=>{let options=params.options??[],reject=options.find((option)=>option.kind==="reject_once"),toolCall={name:params.toolCall?.name??null,title:params.toolCall?.title??null,kind:params.toolCall?.kind??null,rawInput:params.toolCall?.rawInput??null,content:params.toolCall?.content??null,locations:params.toolCall?.locations??null,command:params.toolCall?.rawInput?.command??params.toolCall?.rawInput?.sub_content??null},settled=!1,finish=(optionId)=>{if(settled)return;if(settled=!0,params.signal?.removeEventListener("abort",onAbort),useStore.getState().overlay?.resolve===resolveChoice)store.setOverlay(null);resolve(optionId)},onAbort=()=>finish(null),resolveChoice=async(value)=>{if(settled)return;let optionId=permissionOptionIdForChoice(options,value),chosen=options.find((option)=>option.optionId===optionId),verdict="Cancelled";if(chosen)verdict=chosen.kind?.startsWith("allow")?"Allowed":"Denied";store.push("system",`${verdict}: ${toolCall.command??toolCall.title??"tool call"}`),finish(optionId)};if(store.setOverlay({kind:"permission",toolCall,escapeValue:reject?.optionId??null,items:buildPermissionDialogItems(options),resolve:resolveChoice}),params.signal?.addEventListener("abort",onAbort,{once:!0}),params.signal?.aborted)onAbort()}),client.onPlanEntryRequest=()=>new Promise((resolve)=>{store.setOverlay({kind:"permission",toolCall:{kind:"mode",title:"Enter Plan Mode",rawInput:null},escapeValue:"decline",items:[{value:"approve",label:"Enter Plan Mode"},{value:"decline",label:"Continue normally"}],resolve:(value)=>{store.setOverlay(null),resolve(value==="approve")}})}),client.onPlanReviewRequest=({plan,path})=>new Promise((resolve)=>{store.setOverlay({kind:"plan-review",plan,path,resolve:(value)=>{store.setOverlay(null),resolve(value??{action:"dismiss"})}})}),client.onUserInputRequest=(questions)=>new Promise((resolve)=>{store.setOverlay({kind:"user-question",questions,resolve:(value)=>{store.setOverlay(null),resolve(value)}})})},startClient=(provider,sessionId=null)=>{goalTakeoverRef.current=null,goalAfterStopNoticeRef.current=null,recorderRef.current=null,setRecorder(null),stageSessionUiState(`pending:${++pendingSessionKeyRef.current}`);let settings=readHomeSettings(),{contextText,files}=loadStartupContext({cwd:process.cwd(),settings,resumed:sessionId!=null}),common={contextText,continueSessionId:sessionId},client=isMiroProvider(provider)?new MiroAgentClient({...common,settings,permissionMode:permissionModeRef.current}):new AcpClient({bin:provider.bin,args:provider.args,sessionMeta:provider.sessionMeta,settings,recordRawThinking:initialThinkingSettings.recordRaw,...common});client.agentsFiles=files,clientRef.current=client,providerRef.current=provider,setPermissionMode(isMiroProvider(provider)?normalizePermissionMode(client.permissionMode):null),agentBin=isMiroProvider(provider)?provider.id:provider.bin,resetActivityCaches(),useStore.getState().setProviderId(provider.id),attachClient(client),client.run().then((error)=>{if(error)useStore.getState().setFatalError(error)}).finally(()=>{if(client!==clientRef.current)return;requestExit()})},shutdown=()=>{checkpointUiState(),clientRef.current?.close()},clearScreen=()=>{host.clearScreen(),useStore.getState().clearTranscript()},interrupt=()=>{let store=useStore.getState();if(bashTaskRef.current)return bashTaskRef.current.interrupt(),!0;if(!store.busy||store.cancelling)return!1;return discardQueuedThought(),store.setCancelling(!0),clientRef.current?.cancel(),!0},cancelExitConfirm=()=>{if(exitConfirmTimerRef.current)clearTimeout(exitConfirmTimerRef.current);exitConfirmTimerRef.current=null,exitConfirmUntilRef.current=0,setExitConfirming(!1)},exitSession=()=>{cancelExitConfirm(),shutdown(),requestExit()},confirmExit=()=>{let now=Date.now();if(now<exitConfirmUntilRef.current){exitSession();return}if(exitConfirmUntilRef.current=now+2000,setExitConfirming(!0),exitConfirmTimerRef.current)clearTimeout(exitConfirmTimerRef.current);exitConfirmTimerRef.current=setTimeout(()=>{exitConfirmUntilRef.current=0,exitConfirmTimerRef.current=null,setExitConfirming(!1)},2000)},applyStartupModel=async(config)=>{let store=useStore.getState(),saved=startupModel==null?readModelPreference(readHomeSettings(),useStore.getState().providerId):null,{value:desired,unavailable}=resolveStartupModel(config,startupModel,saved);if(unavailable){store.push("error",`Model "${startupModel}" is not available.`);return}if(desired==null)return;if(desired===config.currentValue)return;store.setSwitching("Applying model preference…");try{await clientRef.current.setModel(desired)}catch(error){store.push("error",`Failed to apply model preference: ${errorMessage(error)}`)}finally{store.setSwitching(null)}},applyStartupEffort=async()=>{let store=useStore.getState();try{await clientRef.current.enableThinking()}catch(error){store.push("error",`Failed to enable thinking: ${errorMessage(error)}`)}let config=useStore.getState().effortConfig,saved=startupEffort==null?readEffortPreference(readHomeSettings(),useStore.getState().providerId):null,{value:desired,unavailable}=resolveStartupEffort(config,startupEffort,saved);if(unavailable){store.push("error",`Effort "${startupEffort}" is not available.`);return}if(desired==null||desired===config?.currentValue)return;store.setSwitching("Applying effort preference…");try{await clientRef.current.setEffort(desired)}catch(error){store.push("error",`Failed to apply effort preference: ${errorMessage(error)}`)}finally{store.setSwitching(null)}},applyModel=async(value,{chainEffort=!1}={})=>{let store=useStore.getState(),config=store.modelConfig;if(value==null||value===config?.currentValue)return!1;let next=modelChoices(config).find((choice)=>choice.value===value);store.setSwitching(`Switching to ${next?.name??value}…`);let switched=!1;try{let name=await clientRef.current.setModel(value);switched=!0,recorderRef.current?.recordModel(name);try{await saveModel(value,useStore.getState().providerId)}catch(error){store.push("system",`Failed to save model preference: ${errorMessage(error)}`)}}catch(error){store.push("error",`Failed to switch model: ${errorMessage(error)}`)}finally{store.setSwitching(null)}if(chainEffort&&switched&&effortChoices(useStore.getState().effortConfig).length>0&&useStore.getState().overlay?.kind!=="config")openEffortPicker();return switched},refreshMiroCatalog=()=>{let client=clientRef.current;if(typeof client?.reloadSessionOptions==="function")client.reloadSessionOptions()},guardModelChoices=()=>{let store=useStore.getState();if(store.overlay||store.switching)return null;if(store.busy)return store.push("system","Please wait for the current response to finish before switching models."),null;let choices=modelChoices(store.modelConfig);if(!store.modelConfig||choices.length===0)return store.push("system","The current ACP session does not offer switchable models."),null;return choices},openModelPicker=()=>{refreshMiroCatalog();let store=useStore.getState(),choices=guardModelChoices();if(!choices)return;let sorted=[...choices.filter((c)=>c.current),...choices.filter((c)=>!c.current)];store.setOverlay({kind:"model",title:"Select model",emptyText:"No matching models",escapeValue:null,items:sorted.map((choice)=>({value:choice.value,label:choice.name,groupName:choice.groupName||"",current:Boolean(choice.current)})),resolve:(value)=>{if(useStore.getState().setOverlay(null),value==null)return;applyModel(value,{chainEffort:!0})}})},setModelByName=(args)=>{refreshMiroCatalog();let store=useStore.getState(),choices=guardModelChoices();if(!choices)return;let hit=matchConfigChoice(store.modelConfig,args);if(!hit){let names=choices.map((choice)=>choice.groupName?`${choice.groupName} / ${choice.name}`:choice.name).join(", ");store.push("error",`Model "${args}" not found. Available models: ${names}`);return}applyModel(hit.value,{chainEffort:!0})},applyEffort=async(value)=>{let store=useStore.getState(),config=store.effortConfig;if(value==null||value===config?.currentValue)return;let next=effortChoices(config).find((choice)=>choice.value===value);store.setSwitching(`Setting effort level ${next?.name??value}…`);try{await clientRef.current.setEffort(value);try{await saveEffort(value,useStore.getState().providerId)}catch(error){store.push("system",`Failed to save effort preference: ${errorMessage(error)}`)}}catch(error){store.push("error",`Failed to set effort level: ${errorMessage(error)}`)}finally{store.setSwitching(null)}},guardEffortChoices=()=>{let store=useStore.getState();if(store.overlay||store.switching)return null;if(store.busy)return store.push("system","Please wait for the current response to finish before setting effort level."),null;let choices=effortChoices(store.effortConfig);if(!store.effortConfig||choices.length===0)return store.push("system","The current model does not support effort selection."),null;return choices},openEffortPicker=()=>{let store=useStore.getState(),choices=guardEffortChoices();if(!choices)return;store.setOverlay({kind:"effort",title:"Select effort level",emptyText:"No matching effort levels",escapeValue:null,items:choices.map((choice)=>({value:choice.value,label:choice.name??choice.value,current:Boolean(choice.current)})),resolve:(value)=>{store.setOverlay(null),applyEffort(value)}})},openPermissionPicker=()=>{let store=useStore.getState();if(store.overlay||store.switching)return;if(!isMiroProvider({id:store.providerId})){store.push("system","Permission mode is only available in Miro; ACP providers control their own approvals.");return}let current=normalizePermissionMode(clientRef.current?.permissionMode);store.setOverlay({kind:"permissions",title:"Select permission mode",emptyText:"No matching permission modes",escapeValue:null,footerHint:"Enter to apply · Esc to cancel",items:PERMISSION_MODE_CHOICES.map((choice)=>({value:choice.value,label:choice.name,right:choice.description,current:choice.value===current})),resolve:(value)=>{if(store.setOverlay(null),value)applyPermissionMode(value)}})},applyPermissionMode=(value)=>applyPermissionModeToClient(clientRef.current,value),setPermissionModeByName=(args)=>{let store=useStore.getState();if(!isMiroProvider({id:store.providerId})){store.push("system","Permission mode is only available in Miro; ACP providers control their own approvals.");return}let hit=matchPermissionMode(args);if(!hit){let names=PERMISSION_MODE_CHOICES.map((choice)=>choice.value).join(", ");store.push("error",`Invalid permission mode "${args}". Available modes: ${names}`);return}applyPermissionMode(hit.value)},applyThinkingDisplay=async(value)=>{let mode=normalizeThinkingDisplayMode(value),store=useStore.getState();setThinkingDisplay(mode),store.setThinkingDisplay(mode);try{if(await saveThinkingDisplay(mode),!useStore.getState().busy)store.push("system",`Thinking display: ${mode}.`)}catch(error){if(!useStore.getState().busy)store.push("system",`Thinking display set to ${mode} for this session, but failed to save: ${errorMessage(error)}`)}},openThinkingPicker=()=>{let store=useStore.getState();if(store.overlay||store.switching)return;if(store.busy){store.push("system","Use /thinking compact|full|hidden while a response is running.");return}store.setOverlay({kind:"thinking",title:"Thinking display",emptyText:"No matching display modes",escapeValue:null,footerHint:"Enter to apply · Esc to cancel",items:THINKING_DISPLAY_CHOICES.map((choice)=>({value:choice.value,label:choice.name,right:choice.description,current:choice.value===thinkingDisplay})),resolve:(value)=>{if(store.setOverlay(null),value)applyThinkingDisplay(value)}})},setThinkingDisplayByName=(args)=>{let hit=matchThinkingDisplayMode(args);if(!hit){let names=THINKING_DISPLAY_CHOICES.map((choice)=>choice.value).join(", ");useStore.getState().push("error",`Invalid thinking display "${args}". Available modes: ${names}`);return}applyThinkingDisplay(hit.value)},setEffortByName=(args)=>{let store=useStore.getState(),choices=guardEffortChoices();if(!choices)return;let lower=args.toLowerCase(),hit=choices.find((choice)=>String(choice.value).toLowerCase()===lower)??choices.find((choice)=>String(choice.name??"").toLowerCase()===lower);if(!hit){let names=choices.map((choice)=>choice.name??choice.value).join(", ");store.push("error",`Invalid effort level "${args}". Available levels: ${names}`);return}applyEffort(hit.value)},applyMode=async(modeId)=>{let store=useStore.getState(),modes=store.modes;if(modeSwitchingRef.current||modeId==null||modeId===modes?.currentModeId)return;modeSwitchingRef.current=!0,setModeSwitching(!0);try{await clientRef.current.setMode(modeId)}catch(error){store.push("error",`Failed to switch mode: ${errorMessage(error)}`)}finally{modeSwitchingRef.current=!1,setModeSwitching(!1)}},handlePlanCommand=(args)=>{let store=useStore.getState(),modes=store.modes;if(!(modes?.availableModes?.map((mode)=>mode.id)??[]).includes("plan")){store.push("system","Plan Mode is not available for this provider.");return}let value=String(args??"").trim().toLowerCase();if(value==="status"){store.push("system",`${modes.currentModeId==="plan"?"Plan":"Default"} Mode is active.`);return}if(value&&!["on","off"].includes(value)){store.push("error","Usage: /plan [on|off|status]");return}if(store.busy){store.push("system","Please wait for the current response to finish before switching Plan Mode.");return}applyMode((()=>{if(value==="on")return"plan";if(value==="off")return"default";return modes.currentModeId==="plan"?"default":"plan"})())},applyConfigOptionValue=async(option,value)=>{if(option==null||value==null||value===option.currentValue)return;let store=useStore.getState();if(isLanguageOption(option)){await applyLanguage(value);return}if(store.modelConfig&&option.id===store.modelConfig.id){await applyModel(value);return}if(store.effortConfig&&option.id===store.effortConfig.id){await applyEffort(value);return}if(option.id==="mode"||option.category==="mode"){await applyMode(value);return}store.setSwitching(`Setting ${option.name??option.id}…`);try{await clientRef.current.setConfigOption(option.id,value)}catch(error){store.push("error",`Failed to set ${option.name??option.id}: ${errorMessage(error)}`)}finally{store.setSwitching(null)}},applyLanguage=async(value)=>{let store=useStore.getState();if(value==null||value===languageRef.current)return;setLanguage(value);let label=languageDisplayName(value);try{await saveLanguage(value),store.push("system",`Prompt language set to ${label}.`)}catch(error){store.push("system",`Prompt language set to ${label} for this session, but failed to save: ${errorMessage(error)}`)}},openConfigPanel=(focusId=null)=>{let store=useStore.getState();if(store.overlay||store.switching)return;if(store.busy){store.push("system","Please wait for the current response to finish before changing config.");return}store.setOverlay({kind:"config",focusId,escapeValue:null,resolve:()=>useStore.getState().setOverlay(null)})},openStatusLineSetup=()=>{let store=useStore.getState();if(store.overlay||store.switching)return;if(store.busy){store.push("system","Please wait for the current response to finish before changing the status line.");return}let{modelConfig,effortConfig,modes,gitBranch,providerName,sessionId,sessionTitle,usage,sessionTokens,sessionCost,planProgress,busy,cancelling,goal}=store,thinking=store.thought!=null;store.setOverlay({kind:"statusline",escapeValue:null,configuredIds:statusLineConfig.items,useColors:statusLineConfig.useColors,snapshot:{modelName:modelConfig?currentModelName(modelConfig):null,effortName:currentEffortName(effortConfig),modeName:modes?.availableModes?.find((mode)=>mode.id===modes?.currentModeId)?.name??modes?.currentModeId??null,cwd:process.cwd(),projectName:projectNameFor(process.cwd()),hostname:hostname2(),gitBranch,providerName,sessionId,sessionTitle,version:APP_VERSION,usage,sessionTokens,sessionCost,plan:planProgress,busy,cancelling,thinking,goal},resolve:(value)=>{if(useStore.getState().setOverlay(null),!value)return;let next={items:(value.items??[]).filter((item)=>item.enabled&&item.id!=="use-colors").map((item)=>item.id),useColors:Boolean(value.useColors)};setStatusLineConfig(next);try{writeStatusLineSettings({items:next.items,useColors:next.useColors}),useStore.getState().push("system","Status line updated.")}catch(error){useStore.getState().push("system",`Status line updated for this session, but failed to save: ${errorMessage(error)}`)}}})},resetStatusLine=()=>{let store=useStore.getState();if(store.overlay||store.switching||store.busy)return;let next={items:DEFAULT_STATUS_LINE_ITEMS,useColors:!0};setStatusLineConfig(next);try{writeStatusLineSettings({items:next.items,useColors:next.useColors}),store.push("system","Status line reset.")}catch(error){store.push("system",`Status line reset for this session, but failed to save: ${errorMessage(error)}`)}},handleConfigCommand=(args)=>{let store=useStore.getState();if(!args){openConfigPanel();return}if(store.overlay||store.switching)return;if(store.busy){store.push("system","Please wait for the current response to finish before changing config.");return}let listed=withLanguageOption(store.configOptions,languageRef.current),space=args.search(/\s/),head=space===-1?args:args.slice(0,space),rest=space===-1?"":args.slice(space).trim(),option=matchConfigOption(listed,head);if(!option){let names=listed.filter((item)=>item?.id).map((item)=>item.name??item.id).join(", ");store.push("error",`Config option "${head}" not found.${names?` Available: ${names}`:""}`);return}if(!rest){openConfigPanel(option.id);return}let choices=configChoices(option);if(choices.length===0){store.push("system",`${option.name??option.id} has no selectable values.`);return}let hit=matchConfigChoice(option,rest);if(!hit){let names=choices.map((choice)=>choice.name??choice.value).join(", ");store.push("error",`Invalid value "${rest}" for ${option.name??option.id}. Available: ${names}`);return}applyConfigOptionValue(option,hit.value)},cycleMode=()=>{let store=useStore.getState();if(store.overlay||store.switching||store.busy||modeSwitchingRef.current)return;let nextId=getNextModeId(store.modes);if(nextId==null)return;applyMode(nextId)},guardSessions=()=>{let store=useStore.getState();if(store.overlay||store.switching)return null;if(store.busy)return store.push("system","Please wait for the current response to finish before switching sessions."),null;return listSessions(process.cwd(),store.providerId)},resumeSession=(sessionId)=>{let store=useStore.getState(),provider=providerRef.current;if(!provider)return;store.setSwitching("Resuming session…");try{checkpointUiState(),clientRef.current?.close(),store.clearTranscript(),store.reconnecting(),startClient(provider,sessionId)}finally{store.setSwitching(null)}},resumeById=(args)=>{let sessions=guardSessions();if(!sessions)return;let store=useStore.getState();if(sessions.length===0){store.push("system","No saved sessions for this project yet.");return}let hit=sessions.find((s)=>s.sessionId===args)??sessions.find((s)=>s.sessionId.startsWith(args));if(!hit){store.push("error",`Session "${args}" not found. Use /sessions to list saved sessions.`);return}resumeSession(hit.sessionId)},openSessionPicker=()=>{let sessions=guardSessions();if(!sessions)return;let store=useStore.getState();if(sessions.length===0){store.push("system","No saved sessions for this project yet.");return}let byId=new Map(sessions.map((s)=>[s.sessionId,s]));store.setOverlay({kind:"session",title:"Resume session",emptyText:"No matching sessions",escapeValue:null,items:sessions.map((s)=>({value:s.sessionId,label:`${formatSessionAge(s.updatedAt)} ${s.title} · ${s.messages} msgs`,right:""})),resolve:(value)=>{store.setOverlay(null);let hit=byId.get(value);if(hit)resumeSession(hit.sessionId)}})},startNewSession=({clearTerminal=!1}={})=>{let store=useStore.getState();if(store.busy||store.overlay||store.switching){store.push("system","Please wait for the current action to finish before starting a new session.");return}let provider=providerRef.current;if(!provider)return;if(clearTerminal)host.clearScreen();checkpointUiState(),clientRef.current?.close(),store.clearTranscript(),store.setSessionMeta(null),store.reconnecting(),startClient(provider,null)},listSessionsSummary=()=>{let sessions=guardSessions();if(!sessions)return;let store=useStore.getState();if(sessions.length===0){store.push("system","No saved sessions for this project yet.");return}let lines=sessions.slice(0,20).map((s)=>` ${s.sessionId.slice(0,8)} ${s.providerId??"?"} ${formatSessionAge(s.updatedAt)} ${s.messages} msgs ${s.title}`).join(`
2326
2265
  `);store.push("system",`Saved sessions (${sessions.length}):
2327
2266
  ${lines}
2328
2267
 
2329
- Use /resume <id> to resume one.`)},exportToFile=(filename,content=renderTranscript(useStore2.getState().blocks,useStore2.getState().pending))=>{let store=useStore2.getState();if(!content){store.push("system","Nothing to export yet.");return}let path=join17(process.cwd(),ensureTxtExtension(filename));try{writeFileSync10(path,content,"utf8"),store.push("system",`Conversation exported to: ${path}`)}catch(error){store.push("error",`Failed to export conversation: ${errorMessage(error)}`)}},openExportDialog=()=>{let store=useStore2.getState();if(store.overlay||store.switching)return;if(store.busy){store.push("system","Please wait for the current response to finish before exporting.");return}let content=renderTranscript(store.blocks,store.pending);if(!content){store.push("system","Nothing to export yet.");return}let defaultFilename=buildDefaultFilename(store.blocks),showChoices=()=>{useStore2.getState().setOverlay({kind:"export",title:"Export conversation",searchable:!1,escapeValue:null,items:[{value:"clipboard",label:"Copy to clipboard"},{value:"file",label:"Save to file"}],resolve:(value)=>{let current=useStore2.getState();if(value==="clipboard"){let sequence=osc52Copy(content);if(current.setOverlay(null),!sequence){current.push("system","Conversation is too large for the clipboard; please export to a file instead.");return}write(sequence),current.push("system","Conversation copied to clipboard");return}if(value==="file"){current.setOverlay({kind:"export-input",title:"Save conversation",value:defaultFilename,hint:"Enter to save · Esc to go back",onSubmit:(name)=>{current.setOverlay(null),exportToFile(name,content)},onCancel:showChoices});return}current.setOverlay(null),current.push("system","Export cancelled")}})};showChoices()},runReview=async(target)=>{let store=useStore2.getState(),hint=userFacingHint(target),prompt;try{prompt=await reviewPrompt(target,process.cwd(),languageRef.current)}catch(error){store.push("error",`Failed to start review: ${errorMessage(error)}`);return}store.push("system",`Reviewing ${hint}…`),await sendPrompt(buildReviewRequest(prompt,languageRef.current),`/review ${hint}`,{raw:!0,injectContext:!0,isolated:!0})},guardReview=async()=>{let store=useStore2.getState();if(store.overlay||store.switching)return!1;if(store.busy)return store.push("system","Please wait for the current response to finish before starting a review."),!1;if(store.status!=="ready")return store.push("system","Not connected to an ACP provider. Restart with --acp <provider-id>."),!1;if(!await isGitRepo(process.cwd()))return store.push("system","/review needs a git repository in the current directory."),!1;return!0},openReviewBranchPicker=async()=>{let store=useStore2.getState(),[branches,current]=await Promise.all([localBranches(process.cwd()),currentBranch(process.cwd())]);if(branches.length===0){store.push("system","No other local branches to compare against.");return}let head=current??"(detached HEAD)";store.setOverlay({kind:"review-branch",title:"Select a base branch",emptyText:"No matching branches",escapeValue:null,items:branches.map((branch)=>({value:branch,label:`${head} → ${branch}`})),resolve:(value)=>{if(useStore2.getState().setOverlay(null),value!=null)runReview({kind:"base-branch",branch:value})}})},openReviewCommitPicker=async()=>{let store=useStore2.getState(),commits=await recentCommits(process.cwd());if(commits.length===0){store.push("system","No commits found in this repository.");return}store.setOverlay({kind:"review-commit",title:"Select a commit to review",emptyText:"No matching commits",escapeValue:null,items:commits.map((commit)=>({value:commit.sha,label:`${commit.sha.slice(0,7)} ${commit.subject}`})),resolve:(value)=>{if(useStore2.getState().setOverlay(null),value==null)return;let hit=commits.find((commit)=>commit.sha===value);runReview({kind:"commit",sha:value,title:hit?.subject??null})}})},openReviewCustomPrompt=(showPresets)=>{useStore2.getState().setOverlay({kind:"review-input",title:"Custom review instructions",value:"",hint:"Enter to start review · Esc to go back",onSubmit:(text)=>{let instructions=String(text??"").trim();if(useStore2.getState().setOverlay(null),instructions.length===0){useStore2.getState().push("system","Review cancelled: no instructions given.");return}runReview({kind:"custom",instructions})},onCancel:showPresets})},openReviewPicker=async()=>{if(!await guardReview())return;let dirty=await hasUncommittedChanges(process.cwd()),showPresets=()=>{useStore2.getState().setOverlay({kind:"review",title:"Select a review preset",searchable:!1,escapeValue:null,items:[{value:"base-branch",label:"Review against a base branch (PR style)"},{value:"uncommitted",label:dirty?"Review uncommitted changes":"Review uncommitted changes (working tree is clean)"},{value:"commit",label:"Review a commit"},{value:"custom",label:"Custom review instructions"}],resolve:(value)=>{let current=useStore2.getState();if(value==="custom"){openReviewCustomPrompt(showPresets);return}if(current.setOverlay(null),value==null)return;if(value==="uncommitted"){if(!dirty){current.push("system","No uncommitted changes to review.");return}runReview({kind:"uncommitted"});return}if(value==="base-branch")openReviewBranchPicker();if(value==="commit")openReviewCommitPicker()}})};showPresets()},reviewWithInstructions=async(instructions)=>{if(!await guardReview())return;await runReview({kind:"custom",instructions})},runSimplify=async(target)=>{let store=useStore2.getState(),hint=userFacingHint2(target),prompt;try{prompt=await simplifyPrompt(target,process.cwd(),languageRef.current)}catch(error){store.push("error",`Failed to start simplify: ${errorMessage(error)}`);return}store.push("system",`Simplifying ${hint}…`),await sendPrompt(buildSimplifyRequest(prompt,languageRef.current),`/simplify ${hint}`,{raw:!0,injectContext:!0,isolated:!0})},guardSimplify=()=>{let store=useStore2.getState();if(store.overlay||store.switching)return!1;if(store.busy)return store.push("system","Please wait for the current response to finish before starting a simplify."),!1;if(store.status!=="ready")return store.push("system","Not connected to an ACP provider. Restart with --acp <provider-id>."),!1;return!0},openSimplifyBranchPicker=async()=>{let store=useStore2.getState(),[branches,current]=await Promise.all([localBranches(process.cwd()),currentBranch(process.cwd())]);if(branches.length===0){store.push("system","No other local branches to compare against.");return}let head=current??"(detached HEAD)";store.setOverlay({kind:"simplify-branch",title:"Select a base branch",emptyText:"No matching branches",escapeValue:null,items:branches.map((branch)=>({value:branch,label:`${head} → ${branch}`})),resolve:(value)=>{if(useStore2.getState().setOverlay(null),value!=null)runSimplify({kind:"base-branch",branch:value})}})},openSimplifyCommitPicker=async()=>{let store=useStore2.getState(),commits=await recentCommits(process.cwd());if(commits.length===0){store.push("system","No commits found in this repository.");return}store.setOverlay({kind:"simplify-commit",title:"Select a commit to simplify",emptyText:"No matching commits",escapeValue:null,items:commits.map((commit)=>({value:commit.sha,label:`${commit.sha.slice(0,7)} ${commit.subject}`})),resolve:(value)=>{if(useStore2.getState().setOverlay(null),value==null)return;let hit=commits.find((commit)=>commit.sha===value);runSimplify({kind:"commit",sha:value,title:hit?.subject??null})}})},openSimplifyInput=({title,emptyMessage,buildTarget,showPresets})=>{useStore2.getState().setOverlay({kind:"simplify-input",title,value:"",hint:"Enter to start simplify · Esc to go back",onSubmit:(text)=>{let entered=String(text??"").trim();if(useStore2.getState().setOverlay(null),entered.length===0){useStore2.getState().push("system",emptyMessage);return}runSimplify(buildTarget(entered))},onCancel:showPresets})},openSimplifyPicker=async()=>{if(!guardSimplify())return;let inRepo=await isGitRepo(process.cwd()),dirty=inRepo&&await hasUncommittedChanges(process.cwd()),uncommittedSuffix="";if(!inRepo)uncommittedSuffix=" (not a git repository)";else if(!dirty)uncommittedSuffix=" (working tree is clean)";let showPresets=()=>{useStore2.getState().setOverlay({kind:"simplify",title:"Select a simplify preset",searchable:!1,escapeValue:null,items:[{value:"uncommitted",label:`Simplify uncommitted changes${uncommittedSuffix}`},{value:"base-branch",label:"Simplify changes against a base branch (PR style)"},{value:"commit",label:"Simplify code from a commit"},{value:"paths",label:"Simplify specific files or directories"},{value:"custom",label:"Custom simplify instructions"}],resolve:(value)=>{let current=useStore2.getState();if(value==="paths"){openSimplifyInput({title:"Files or directories to simplify",emptyMessage:"Simplify cancelled: no paths given.",buildTarget:(paths)=>({kind:"paths",paths}),showPresets});return}if(value==="custom"){openSimplifyInput({title:"Custom simplify instructions",emptyMessage:"Simplify cancelled: no instructions given.",buildTarget:(instructions)=>({kind:"custom",instructions}),showPresets});return}if(current.setOverlay(null),value==null)return;if(!inRepo){current.push("system","/simplify needs a git repository for this preset.");return}switch(value){case"uncommitted":if(!dirty){current.push("system","No uncommitted changes to simplify.");return}runSimplify({kind:"uncommitted"});return;case"base-branch":openSimplifyBranchPicker();return;case"commit":openSimplifyCommitPicker();return}}})};showPresets()},simplifyWithArgs=async(args)=>{if(!guardSimplify())return;await runSimplify(looksLikePaths(args)?{kind:"paths",paths:args}:{kind:"custom",instructions:args})},runCommit=async(target)=>{let store=useStore2.getState(),hint=userFacingHint3(target),prompt;try{prompt=await commitPrompt7(target,process.cwd(),languageRef.current)}catch(error){store.push("error",`Failed to start commit: ${errorMessage(error)}`);return}store.push("system",`Committing ${hint}…`),await sendPrompt(buildCommitRequest(prompt,languageRef.current),`/commit ${hint}`,{raw:!0,injectContext:!0,isolated:!0})},guardCommit=async({command="/commit",action="starting a commit"}={})=>{let store=useStore2.getState();if(store.overlay||store.switching)return!1;if(store.busy)return store.push("system",`Please wait for the current response to finish before ${action}.`),!1;if(store.status!=="ready")return store.push("system","Not connected to an ACP provider. Restart with --acp <provider-id>."),!1;if(!await isGitRepo(process.cwd()))return store.push("system",`${command} needs a git repository.`),!1;return!0},commitTargetBlocker=async(target)=>{let cwd=process.cwd();if(target.kind==="staged"&&!await hasStagedChanges(cwd))return"Nothing staged to commit. Stage changes first, or use /commit without arguments.";if(target.kind==="amend"&&!await hasCommits(cwd))return"No existing commit to amend.";if((target.kind==="default"||target.kind==="message")&&!await hasUncommittedChanges(cwd))return"No changes to commit.";return null},startCommit=async(target)=>{let blocker=await commitTargetBlocker(target);if(blocker){useStore2.getState().push("system",blocker);return}await runCommit(target)},openCommitInput=({title,emptyMessage,buildTarget,showPresets})=>{useStore2.getState().setOverlay({kind:"commit-input",title,value:"",hint:"Enter to start commit · Esc to go back",onSubmit:(text)=>{let entered=String(text??"").trim();if(useStore2.getState().setOverlay(null),entered.length===0){useStore2.getState().push("system",emptyMessage);return}startCommit(buildTarget(entered))},onCancel:showPresets})},openCommitPicker=async()=>{if(!await guardCommit())return;let cwd=process.cwd(),[dirty,staged,committed]=await Promise.all([hasUncommittedChanges(cwd),hasStagedChanges(cwd),hasCommits(cwd)]),dirtySuffix=dirty?"":" (working tree is clean)",stagedSuffix=staged?"":" (nothing staged)",amendSuffix=committed?"":" (no commit to amend)",showPresets=()=>{useStore2.getState().setOverlay({kind:"commit",title:"Select a commit preset",searchable:!1,escapeValue:null,items:[{value:"default",label:`Commit all changes${dirtySuffix}`},{value:"staged",label:`Commit staged changes only${stagedSuffix}`},{value:"paths",label:"Commit specific files or directories"},{value:"message",label:"Commit with a message you provide"},{value:"amend",label:`Amend the last commit${amendSuffix}`}],resolve:(value)=>{let current=useStore2.getState();if(value==="paths"){openCommitInput({title:"Files or directories to commit",emptyMessage:"Commit cancelled: no paths given.",buildTarget:(paths)=>({kind:"paths",paths}),showPresets});return}if(value==="message"){openCommitInput({title:"Commit message",emptyMessage:"Commit cancelled: no message given.",buildTarget:(message)=>({kind:"message",message}),showPresets});return}if(current.setOverlay(null),value==null)return;startCommit({kind:value})}})};showPresets()},commitWithArgs=async(args)=>{if(!await guardCommit())return;await startCommit(parseCommitArgs(args))},commitPushPr=async()=>{if(!await guardCommit({command:"/commit-push-pr",action:"publishing changes"}))return;let store=useStore2.getState(),prompt;try{prompt=await commitPushPrPrompt(process.cwd(),languageRef.current)}catch(error){store.push("error",`Failed to start commit-push-pr: ${errorMessage(error)}`);return}store.push("system","Committing, pushing, and creating a pull request…"),await sendPrompt(buildCommitPushPrRequest(prompt,languageRef.current),"/commit-push-pr",{raw:!0,injectContext:!0,isolated:!0})},runBashCommand=async(command)=>{let store=useStore2.getState();if(!command){store.push("system","Please enter a command to run, e.g. !ls -la");return}store.startBashCard(command),store.startTurn("bash");let task=startBash(command);bashTaskRef.current=task;try{let{stdout,stderr,outcome}=await task.result;store.finishBashCard({stdout,stderr,outcome}),store.pushBashContext(formatBashContext({command,stdout,stderr,outcome}))}finally{bashTaskRef.current=null,store.endTurn()}},guardGoal=()=>{let store=useStore2.getState();if(store.overlay||store.switching)return null;if(store.status!=="ready")return store.push("system","Not connected to an ACP provider. Restart with --acp <provider-id>."),null;if(!isMiroProvider({id:store.providerId}))return store.push("system","Goals are only available in Miro."),null;let client=clientRef.current;if(typeof client?.promptGoal!=="function")return store.push("system","This provider does not support goals."),null;return client},showGoalStatus=()=>{let client=guardGoal();if(!client)return;let store=useStore2.getState(),goal=client.goalSnapshot();if(goal==null){store.push("system","No goal yet. Use /goal <objective> to start one.");return}let lines=[`Objective: ${goal.objective}`,goal.completionCriterion?`Done when: ${goal.completionCriterion}`:null,`Status: ${goal.status}${goal.terminalReason?` (${goal.terminalReason})`:""}`,`Progress: ${goal.turnsUsed} turns, ${goal.tokensUsed} tokens, ${formatElapsed(goal.wallClockMs)} elapsed`].filter((line)=>line!=null),budgets=[goal.budget.turnBudget!=null?`${goal.budget.remainingTurns} turns`:null,goal.budget.tokenBudget!=null?`${goal.budget.remainingTokens} tokens`:null,goal.budget.wallClockBudgetMs!=null?formatElapsed(goal.budget.remainingWallClockMs??0):null].filter((part)=>part!=null);if(budgets.length>0)lines.push(`Remaining budget: ${budgets.join(", ")}`);if(goal.status==="paused"||goal.status==="blocked")lines.push("Use /goal resume to continue it.");store.push("system",lines.join(`
2330
- `))},runGoal=async(start,displayText,{recordUser=!0}={})=>{let store=useStore2.getState();if(recordUser)store.push("user",displayText);store.startTurn("prompt");let result;try{result=await start()}catch(error){if(useStore2.getState().cancelling)result={stopReason:"cancelled"};else store.push("error",`Goal failed: ${errorMessage(error)}`)}finally{flushQueuedThought(),store.endTurn(result),drainQueue()}let goal=clientRef.current?.goalSnapshot?.();if(goal!=null&&["paused","blocked","complete"].includes(goal.status)){let reason=goal.terminalReason?` — ${goal.terminalReason}`:"";useStore2.getState().push("system",`Goal ${goal.status} after ${goal.turnsUsed} turns${reason}`)}},startGoal=(objective)=>{let client=guardGoal();if(!client)return;let store=useStore2.getState();if(store.busy){if(typeof client.createPendingGoal!=="function"||typeof client.activatePendingGoal!=="function"){store.push("system","This provider cannot safely start a goal while a response is running.");return}try{client.createPendingGoal(objective,{replace:!0}),goalTakeoverRef.current={client,displayText:`/goal ${objective}`},client.cancel()}catch(error){store.push("error",`Could not queue goal: ${errorMessage(error)}`)}return}runGoal(()=>client.promptGoal(objective,{replace:!0}),`/goal ${objective}`)},resumeGoal=()=>{let client=guardGoal();if(!client)return;let store=useStore2.getState(),goal=client.goalSnapshot();if(goal==null){store.push("system","No goal to resume. Use /goal <objective> to start one.");return}if(goal.status==="active"){store.push("system","The goal is already running.");return}if(goal.status==="complete"){store.push("system","That goal is already complete. Use /goal <objective> to start a new one.");return}if(store.busy){if(typeof client.queueResumeGoal!=="function"||typeof client.activatePendingGoal!=="function"){store.push("system","This provider cannot safely resume a goal while a response is running.");return}try{client.queueResumeGoal(),goalTakeoverRef.current={client,displayText:"/goal resume"},client.cancel()}catch(error){store.push("error",`Could not queue goal resume: ${errorMessage(error)}`)}return}runGoal(()=>client.resumeGoal(),"/goal resume")},pauseGoal=()=>{let client=guardGoal();if(!client)return;let store=useStore2.getState(),goal=client.goalSnapshot();if(goal==null||goal.status!=="active"){store.push("system","No running goal to pause.");return}if(store.busy){if(goalTakeoverRef.current=null,typeof client.requestPauseGoal!=="function"){store.push("system","This provider cannot safely pause a running goal.");return}client.requestPauseGoal("Paused by user"),client.cancel();return}client.pauseGoal("Paused by user"),store.push("system","Goal paused. Use /goal resume to continue it.")},cancelGoal=()=>{let client=guardGoal();if(!client)return;let store=useStore2.getState();if(client.goalSnapshot()==null){store.push("system","No goal to cancel.");return}if(goalTakeoverRef.current=null,client.cancelGoal(),store.busy){goalAfterStopNoticeRef.current="Goal cancelled.",client.cancel();return}store.push("system","Goal cancelled.")},handleGoalCommand=(args)=>{if(useStore2.getState().modes?.currentModeId==="plan"){useStore2.getState().push("system","Exit Plan Mode before starting or changing a goal.");return}let text=(args??"").trim();if(text.startsWith("replace ")){let objective=text.slice(8).trim();if(objective.length===0)useStore2.getState().push("error","Usage: /goal replace <objective>");else startGoal(objective);return}switch(text){case"":case"status":showGoalStatus();break;case"resume":case"continue":resumeGoal();break;case"pause":case"stop":pauseGoal();break;case"cancel":case"clear":cancelGoal();break;default:startGoal(text)}},sendPrompt=async(content,displayText,{raw=!1,injectContext=!raw,isolated=!1,inputId=null}={})=>{let store=useStore2.getState();if(store.busy){store.push("system","Please wait for the current operation to finish.");return}if(store.status!=="ready"){store.push("system","Not connected to an ACP provider. Restart with --acp <provider-id>.");return}if(inputId)store.applyInput({id:inputId,text:displayText});else store.push("user",displayText);store.startTurn("prompt");let bashContext=raw?[]:store.takeBashContext(),blocks=typeof content==="string"?[{type:"text",text:content}]:content,payload=bashContext.length>0?[...bashContext.map((item)=>({type:"text",text:item})),...blocks]:blocks,client=clientRef.current,detach=isolated&&typeof client.promptIsolated==="function",result;try{result=detach?await client.promptIsolated(payload,{displayText,injectContext}):await client.prompt(payload,{injectContext,inputId,displayText})}catch(error){if(bashContext.length>0)store.restoreBashContext(bashContext);if(useStore2.getState().cancelling)result={stopReason:"cancelled"};else store.push("error",`Request failed: ${errorMessage(error)}`)}finally{flushQueuedThought(),store.endTurn(result);let transition=result?.transition;if(transition?.type==="plan_entered")store.queueInput("Continue the current request in Plan Mode. Inspect the workspace, resolve material uncertainties, and write the implementation plan.","Continue in Plan Mode");else if(transition?.type==="plan_approved")store.pushProposedPlan(transition.plan,transition.path),store.queueInput(approvedPlanPrompt(transition.plan),"Implement approved plan");drainQueue()}},compactConversation=async(instructions,commandText)=>{let store=useStore2.getState(),client=clientRef.current;if(store.overlay||store.switching)return;if(store.status!=="ready"||!client){store.push("system","Wait for the session to be ready before compacting context.");return}if(store.busy){store.push("system","Wait for the current operation to finish, or press Esc before using /compact.");return}if(typeof client.compact!=="function"){if(matchProviderCommand(commandText,store.providerCommands))await sendPrompt(commandText,commandText,{raw:!0});else store.push("system","This provider does not support /compact.");return}store.startTurn("compact");let result;try{if(result=await client.compact({instructions}),result.reason==="nothing_to_compact")store.push("system","Not enough history to compact.")}catch(error){if(useStore2.getState().cancelling)result={stopReason:"cancelled"};else store.push("error",`Compaction failed: ${errorMessage(error)}`)}finally{store.endTurn(result),drainQueue()}},drainQueue=()=>{let state=useStore2.getState();if(state.busy||state.status!=="ready"||state.switching||state.queuePaused||state.overlay?.kind==="queue-review")return;let client=clientRef.current;if(client?.goalSnapshot?.()?.status==="pausing"&&typeof client.finishPauseGoal==="function")client.finishPauseGoal(),useStore2.getState().push("system","Goal paused. Use /goal resume to continue it.");let afterStopNotice=goalAfterStopNoticeRef.current;if(afterStopNotice!=null)goalAfterStopNoticeRef.current=null,useStore2.getState().push("system",afterStopNotice);let takeover=goalTakeoverRef.current;if(takeover!=null){if(goalTakeoverRef.current=null,takeover.client===clientRef.current&&typeof takeover.client.activatePendingGoal==="function"){runGoal(()=>takeover.client.activatePendingGoal(),takeover.displayText);return}}let queued=useStore2.getState().takeQueuedInput();if(queued!=null)handleSubmit(queued.text,queued.display,{intent:"dequeue",inputId:queued.id})},handleSubmit=async(raw,display,{intent="submit",inputId=null}={})=>{let store=useStore2.getState(),submitted=prepareSubmittedInput(raw,display);if(!submitted)return;let{content,commandText:text,display:shown,transcriptText}=submitted;if(store.busy){if(isBashInput(text)){store.push("system","Please wait for the current response to finish before running shell commands.");return}if(!parseCommandInput(text)&&!bareExitCommand(text)){let client=clientRef.current,capability=client?.steeringCapability?.();if(intent==="submit"&&!matchProviderCommand(text,store.providerCommands)&&!store.cancelling&&capability?.available&&typeof client.steerInput==="function"){let id=randomUUID7();if(client.steerInput({id,turnId:capability.turnId,content,display:transcriptText}).accepted){store.addPendingInput({id,text:content,display:transcriptText}),checkpointUiState();return}}if(store.queueInput(content,shown,randomUUID7()),checkpointUiState(),intent==="submit")store.push("system","This operation cannot accept steering; message queued for the next turn.");return}}if(intent!=="dequeue"&&!isBashInput(text)&&!parseCommandInput(text)&&!bareExitCommand(text)&&store.queuedInputs.length>0){if(store.queueInput(content,shown,randomUUID7()),checkpointUiState(),!store.queuePaused)drainQueue();return}if(isBashInput(text)){await runBashCommand(getBashCommand(text));return}let commandHandlers={mcp:async(args)=>{let client=clientRef.current;if(!(client instanceof MiroAgentClient)){store.push("system","MCP manager is available with the built-in miro agent.");return}if(store.busy||store.switching){store.push("system","Wait for the current activity before changing MCP servers.");return}let[action,serverName]=args.trim().split(/\s+/,2);if(action&&!["list","trust","reconnect"].includes(action)||action==="reconnect"&&!serverName){store.push("system","Usage: /mcp [list|trust|reconnect <server>]");return}store.setSwitching("Reloading MCP configuration…");try{await client.reloadMcp()}catch(error){if(client===clientRef.current&&!client.closed)store.push("error",errorMessage(error));return}finally{if(client===clientRef.current)store.setSwitching(null)}if(client!==clientRef.current||client.closed)return;let runtime=client.mcpRuntime;for(let diagnostic of runtime.diagnostics)store.push("system",diagnostic);if(action==="trust"){let trust=projectMcpTrust(process.cwd());if(!trust.exists){store.push("system",`No project MCP file at ${trust.file}`);return}let configured=[];try{configured=Object.entries(JSON.parse(readFileSync15(trust.file,"utf8")).mcpServers??{})}catch{}store.setOverlay({kind:"mcp-trust",title:`Trust MCP commands in ${trust.file}?`,searchable:!1,items:[...configured.map(([name,entry])=>({value:`show-${name}`,label:`${name}: ${entry.command??entry.url??"invalid"}`,disabled:!0})),{value:"trust",label:"Trust this file and load its servers"},{value:"cancel",label:"Cancel"}],resolve:(value)=>{if(store.setOverlay(null),value!=="trust")return;trustProjectMcp(process.cwd()),client.reloadMcp().then(()=>store.push("system","Project MCP servers loaded.")).catch((error)=>store.push("error",errorMessage(error)))}});return}if(action==="reconnect"&&serverName){runtime.reconnect(serverName).then((result)=>store.push("system",JSON.stringify(result))).catch((error)=>store.push("error",errorMessage(error)));return}if(action&&action!=="list"){store.push("system","Usage: /mcp [list|trust|reconnect <server>]");return}let servers=runtime.configured?.length?runtime.configured:[...runtime.servers.values()],trust=projectMcpTrust(process.cwd());if(servers.length===0){store.push("system",trust.exists&&!trust.trusted?`Project MCP config needs trust. Run /mcp trust. (${trust.file})`:"No MCP servers configured.");return}if(action==="list"){let serverState=(server)=>{if(server.enabled===!1)return"disabled";return runtime.connections.get(server.name)?.connected?"connected":"disconnected"};store.push("system",servers.map((server)=>`${server.name} (${server.type}, ${serverState(server)})`).join(`
2331
- `));return}store.setOverlay({kind:"mcp",title:"MCP servers",searchable:!1,items:servers.map((server)=>({value:server.name,label:`${server.name} ${server.type}${server.enabled===!1?" disabled":""}`})),resolve:(name)=>{if(store.setOverlay(null),!name)return;let server=servers.find((entry)=>entry.name===name),toggle=server.enabled===!1?{value:"enable",label:"Enable"}:{value:"disable",label:"Disable"},supportsOAuth=server.enabled!==!1&&server.type==="http"&&!Object.keys(runtime.servers.get(name)?.headers??{}).some((key)=>key.toLowerCase()==="authorization");store.setOverlay({kind:"mcp-action",title:`MCP ${name}`,searchable:!1,items:[...server.enabled===!1?[]:[{value:"tools",label:"Show tools"},{value:"reconnect",label:"Reconnect"}],toggle,...supportsOAuth?[{value:"login",label:"Sign in"},{value:"logout",label:"Sign out"}]:[]],resolve:(selected)=>{if(store.setOverlay(null),!selected)return;if(selected==="tools"||selected==="reconnect")(selected==="tools"?runtime.listTools({server:name}):runtime.reconnect(name)).then((result)=>store.push("system",JSON.stringify(result,null,2))).catch((error)=>store.push("error",errorMessage(error)));else if(selected==="login"){let isCurrent=()=>client===clientRef.current&&!client.closed,loginOverlay={kind:"mcp-login",title:`Signing in to MCP ${name}…`,searchable:!1,items:[{value:"cancel",label:"Cancel sign-in"}],escapeValue:null,resolve:()=>{if(isCurrent())client.cancel()}};store.setSwitching("Signing in to MCP…"),store.setOverlay(loginOverlay),client.loginMcp(name,{print:(message)=>{if(isCurrent())store.push("system",message)}}).catch((error)=>{if(!isCurrent())return;if(error?.name==="AbortError")store.push("system","MCP sign-in cancelled.");else store.push("error",errorMessage(error))}).finally(()=>{if(!isCurrent())return;if(store.setSwitching(null),useStore2.getState().overlay===loginOverlay)store.setOverlay(null)})}else if(selected==="logout")logoutMcp(runtime.servers.get(name)),runtime.reconnect(name).catch(()=>{}),store.push("system",`Signed out of MCP server ${name}.`);else try{updateMcpServerSetting(server,"enabled",selected==="enable",process.cwd()),client.reloadMcp().then(()=>store.push("system",`MCP ${name}: ${selected}`)).catch((error)=>store.push("error",errorMessage(error)))}catch(error){store.push("error",errorMessage(error))}}})}})},init:(args)=>void sendPrompt([{type:"text",text:buildInitPrompt(args,languageRef.current)}],args?`/init ${args}`:"/init",{isolated:!0}),model:(args)=>args?setModelByName(args):openModelPicker(),effort:(args)=>args?setEffortByName(args):openEffortPicker(),config:handleConfigCommand,statusline:(args)=>args.trim()==="reset"?resetStatusLine():openStatusLineSetup(),thinking:(args)=>args?setThinkingDisplayByName(args):openThinkingPicker(),permissions:(args)=>args?setPermissionModeByName(args):openPermissionPicker(),plan:handlePlanCommand,resume:(args)=>args?resumeById(args):openSessionPicker(),new:startNewSession,sessions:listSessionsSummary,compact:(args)=>void compactConversation(args,text),export:(args)=>args?exportToFile(args):openExportDialog(),review:(args)=>void(args?reviewWithInstructions(args):openReviewPicker()),goal:handleGoalCommand,simplify:(args)=>void(args?simplifyWithArgs(args):openSimplifyPicker()),commit:(args)=>void(args?commitWithArgs(args):openCommitPicker()),"commit-push-pr":()=>void commitPushPr(),clear:()=>startNewSession({clearTerminal:!0}),help:()=>store.push("system",HELP.trimEnd()),exit:exitSession},parsed=parseCommandInput(text)??bareExitCommand(text);if(parsed){commandHandlers[parsed.key]?.(parsed.args);return}if(matchProviderCommand(text,store.providerCommands)){await sendPrompt(text,shown??text,{raw:!0,inputId});return}await sendPrompt(content,transcriptText,{inputId})};use_input_default((input,key)=>{if(key.escape){if(helpOpen){setHelpOpen(!1);return}let store=useStore2.getState();if(!store.overlay&&(store.busy||bashTaskRef.current))interrupt();return}if(!key.ctrl)return;if(input==="m"){openModelPicker();return}if(input==="c"){let store=useStore2.getState(),controls=composerControlsRef.current;switch(ctrlCIntent({hasOverlay:Boolean(store.overlay),hasDraft:controls?.hasDraft()??!1})){case"overlay":cancelOverlay(store.overlay);return;case"draft":controls.clearDraft(),cancelExitConfirm();return;default:interrupt(),confirmExit();return}}if(input==="l")clearScreen();if(input==="o"){let store=useStore2.getState(),target=findReviewTarget(store);if(!target)return;switch(target.kind){case"close":store.setOverlay(null);return;case"review":store.setOverlay({kind:"review-browser",entries:target.entries,initialIndex:target.index,escapeValue:null,resolve:()=>useStore2.getState().setOverlay(null)});return}}if(input==="q"){let store=useStore2.getState();if(store.overlay?.kind==="queue-review")store.setOverlay(null),drainQueue();else if(!store.overlay&&(store.queuedInputs.length>0||store.pendingInputs.length>0))store.setOverlay({kind:"queue-review",escapeValue:null,resolve:()=>{useStore2.getState().setOverlay(null),drainQueue()}})}});let connecting=status==="connecting",canSteer=!cancelling&&clientRef.current?.steeringCapability?.().available===!0;return $jsxs(Box_default,{flexDirection:"column",children:[$jsx(Transcript,{}),overlay?.kind==="review-browser"?$jsx(ReviewBrowser,{entries:overlay.entries,initialIndex:overlay.initialIndex,onClose:()=>useStore2.getState().setOverlay(null)}):overlay?.kind==="queue-review"?$jsx(QueueEditor,{onClose:()=>{useStore2.getState().setOverlay(null),drainQueue()},onResume:()=>{useStore2.getState().resumeInputQueue(),useStore2.getState().setOverlay(null),checkpointUiState(),drainQueue()}}):null,$jsxs(Box_default,{flexDirection:"column",display:SCREEN_TAKEOVER_OVERLAYS.has(overlay?.kind)?"none":"flex",children:[bashCard?$jsx(BashCard,{card:bashCard}):null,pending?$jsx(Message,{block:pending}):null,$jsx(ActivitySlot,{now,busy,cancelling,activeTools,pendingToolGroup,hasBashActivity:Boolean(bashCard),awaitingInput}),$jsx(StatusVerb,{now,busy,cancelling,compacting,turnStartedAt,toolRound,hasBashActivity:Boolean(bashCard),awaitingInput,retryNotice}),$jsxs(Box_default,{flexDirection:"column",marginTop:1,children:[overlay?.kind==="permission"?$jsx(PermissionDialog,{toolCall:overlay.toolCall,items:overlay.items,escapeValue:overlay.escapeValue,onResolve:(value)=>overlay.resolve(value)}):overlay?.kind==="plan-review"?$jsx(PlanReviewDialog,{plan:overlay.plan,path:overlay.path,onResolve:(value)=>overlay.resolve(value)}):overlay?.kind==="user-question"?$jsx(UserQuestionDialog,{questions:overlay.questions,onResolve:(value)=>overlay.resolve(value)}):overlay?.kind==="export-input"||overlay?.kind==="review-input"||overlay?.kind==="simplify-input"||overlay?.kind==="commit-input"?$jsx(InputPrompt,{title:overlay.title,value:overlay.value,secret:overlay.secret,hint:overlay.hint,onSubmit:overlay.onSubmit,onCancel:overlay.onCancel}):overlay?.kind==="config"?$jsx(ConfigPanel,{options:panelConfigOptions,focusId:overlay.focusId,switching,onChange:(option,value)=>void applyConfigOptionValue(option,value),onCancel:()=>overlay.resolve(overlay.escapeValue)}):overlay?.kind==="statusline"?$jsx(StatusLineSetup,{configuredIds:overlay.configuredIds,useColors:overlay.useColors,snapshot:overlay.snapshot,onConfirm:(value)=>overlay.resolve(value),onCancel:()=>overlay.resolve(overlay.escapeValue)}):overlay?.steps?$jsx(PickerFlow,{steps:overlay.steps,initialContext:overlay.initialContext,color:"cyan",onComplete:(context)=>overlay.resolve(context),onCancel:()=>overlay.resolve(overlay.escapeValue)}):overlay?$jsx(Picker,{title:overlay.title,subtitle:overlay.subtitle,items:overlay.items,selected:overlay.selected,color:"cyan",searchable:overlay.searchable??!0,emptyText:overlay.emptyText,footerHint:overlay.footerHint,onSelect:(item)=>overlay.resolve(item?.value??overlay.escapeValue),onCancel:()=>overlay.resolve(overlay.escapeValue)}):null,$jsx(ComposerSurface,{hidden:composerIsHidden(connecting,overlay?.kind),disabled:overlay!=null||switching!=null,locked:modeSwitching||exiting,onSubmit:handleSubmit,busy,canSteer,onCycleMode:cycleMode,providerCommands,helpOpen,onHelpOpenChange:setHelpOpen,onCompletionOpenChange:setCompletionOpen,sessionKey:composerSession.key,initialSnapshot:composerSession.snapshot,onSnapshotChange:handleComposerSnapshotChange,controlsRef:composerControlsRef}),pendingInputs.length>0?$jsxs(Box_default,{paddingX:1,flexDirection:"column",children:[$jsxs(Text,{color:"cyan",children:[pendingInputs.length," steering message",pendingInputs.length>1?"s":""," waiting for the current response and tools"]}),pendingInputs.slice(0,3).map((input)=>$jsx(Text,{dimColor:!0,wrap:"truncate-end",children:String(input.display??input.text).replace(/\s+/g," ")},input.id))]}):null,$jsx(StatusBar,{status,connectionStage,agentBin,busy,cancelling,switching,exitConfirming,statusLineItems:statusLineConfig.items,statusLineUseColors:statusLineConfig.useColors,goal,inputHint:inputHint({busy,hasDraft:hasComposerDraft,canSteer,queuedCount:queuedInputs.length,queuePaused}),statusLineSnapshot:{modelName:modelConfig?currentModelName(modelConfig):null,effortName:currentEffortName(effortConfig),modeName:modes?.availableModes?.find((mode)=>mode.id===modes?.currentModeId)?.name??modes?.currentModeId??null,cwd:process.cwd(),projectName:projectNameFor(process.cwd()),hostname:hostname2(),permissionMode,gitBranch,providerName,sessionId,sessionTitle,version:APP_VERSION,usage,sessionTokens,sessionCost,plan:planProgress,goal,busy,cancelling,thinking},hidden:statusLineIsHidden({helpOpen,completionOpen,overlay})})]})]})]})}var AWAITING_INPUT_OVERLAYS,SCREEN_TAKEOVER_OVERLAYS;var init_App2=__esm(async()=>{init_react_production();init_acp_client();init_agent_client();init_mcp_config();init_mcp_oauth();init_goal();init_plan_mode();init_permission_mode();init_config();init_providers();init_agents_md();init_config_options();init_commands();init_bash();init_config();init_export();init_init();init_settings3();init_settings_file();init_thinking();init_language_config();init_language();init_items7();init_workspace_info();init_session_store();init_review_target();init_review();init_simplify();init_commit4();init_store();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_BashCard(),init_ActivitySlot(),init_StatusVerb(),init_Composer(),init_InputPrompt(),init_Message(),init_PermissionDialog(),init_PlanReviewDialog(),init_UserQuestionDialog(),init_Picker(),init_PickerFlow(),init_ConfigPanel(),init_StatusBar(),init_StatusLineSetup(),init_ReviewBrowser(),init_QueueEditor(),init_Transcript()]);AWAITING_INPUT_OVERLAYS=new Set(["permission","plan-review","user-question","review-input","export-input","simplify-input","commit-input"]);SCREEN_TAKEOVER_OVERLAYS=new Set(["review-browser","queue-review"])});function isEmptyChunk(chunk){return typeof chunk==="string"?chunk.length===0:chunk?.byteLength===0}function createSyncStdout(realStdout){return new Proxy(realStdout,{get(target,property){if(property==="write")return(...args)=>{let[chunk]=args;if(isEmptyChunk(chunk))return target.write(...args);let encoding=typeof args[1]==="string"?args[1]:void 0,payload=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk,encoding),wrapped=Buffer.concat([BSU_BUFFER,payload,ESU_BUFFER]),callback=typeof args[1]==="function"?args[1]:args[2];return typeof callback==="function"?target.write(wrapped,callback):target.write(wrapped)};let value=Reflect.get(target,property,target);return typeof value==="function"?value.bind(target):value}})}var BSU_BUFFER,ESU_BUFFER;var init_sync_stdout=__esm(()=>{BSU_BUFFER=Buffer.from("\x1B[?2026h"),ESU_BUFFER=Buffer.from("\x1B[?2026l")});function isSynchronizedOutputSupported(environment=process.env){if(environment.TMUX!==void 0)return!1;let{TERM_PROGRAM:termProgram,TERM:term}=environment;if(SYNC_OUTPUT_TERM_PROGRAMS.has(termProgram))return!0;if(term?.includes("kitty"))return!0;if(term==="xterm-ghostty")return!0;if(term?.startsWith("foot"))return!0;if(term?.includes("alacritty"))return!0;if(environment.KITTY_WINDOW_ID)return!0;if(environment.ZED_TERM)return!0;if(environment.WT_SESSION)return!0;let vteVersion=Number.parseInt(environment.VTE_VERSION,10);return Number.isFinite(vteVersion)&&vteVersion>=6800}function shouldWrapSyncOutput(environment=process.env){return isSynchronizedOutputSupported(environment)}var SYNC_OUTPUT_TERM_PROGRAMS;var init_term_caps=__esm(()=>{SYNC_OUTPUT_TERM_PROGRAMS=new Set(["iTerm.app","WezTerm","WarpTerminal","ghostty","contour","vscode","alacritty"])});import process29 from"node:process";async function runTui(options){if(!process29.stdin.isTTY||!process29.stdout.isTTY)return process29.stderr.write(`miro must be run in an interactive terminal. Use -p for non-interactive mode.
2332
- `),1;let stdout=shouldWrapSyncOutput()?createSyncStdout(process29.stdout):process29.stdout;process29.stdout.write(ENABLE_MODIFY_OTHER_KEYS);let app;try{app=render_default($jsx(App2,{continueSessionId:options.continueSessionId,startupAcp:options.acp,startupModel:options.model,startupEffort:options.effort,startupPermissionMode:options.permissionMode,startupInteractionMode:options.interactionMode}),{exitOnCtrlC:!1,stdout,kittyKeyboard:{mode:"enabled"}}),await app.waitUntilExit()}finally{process29.stdout.write(DISABLE_MODIFY_OTHER_KEYS)}let{fatalError,sessionId,sessionTokens,sessionCost}=useStore2.getState();if(fatalError)return process29.stderr.write(`miro: ${errorMessage(fatalError)}
2333
- `),1;let usageLine=formatSessionTokenUsage(sessionTokens,sessionCost);if(usageLine)process29.stdout.write(`
2268
+ Use /resume <id> to resume one.`)},exportToFile=(filename,content=renderTranscript(useStore.getState().blocks,useStore.getState().pending))=>{let store=useStore.getState();if(!content){store.push("system","Nothing to export yet.");return}let path=join16(process.cwd(),ensureTxtExtension(filename));try{writeFileSync10(path,content,"utf8"),store.push("system",`Conversation exported to: ${path}`)}catch(error){store.push("error",`Failed to export conversation: ${errorMessage(error)}`)}},openExportDialog=()=>{let store=useStore.getState();if(store.overlay||store.switching)return;if(store.busy){store.push("system","Please wait for the current response to finish before exporting.");return}let content=renderTranscript(store.blocks,store.pending);if(!content){store.push("system","Nothing to export yet.");return}let defaultFilename=buildDefaultFilename(store.blocks),showChoices=()=>{useStore.getState().setOverlay({kind:"export",title:"Export conversation",searchable:!1,escapeValue:null,items:[{value:"clipboard",label:"Copy to clipboard"},{value:"file",label:"Save to file"}],resolve:(value)=>{let current=useStore.getState();if(value==="clipboard"){let sequence=osc52Copy(content);if(current.setOverlay(null),!sequence){current.push("system","Conversation is too large for the clipboard; please export to a file instead.");return}write(sequence),current.push("system","Conversation copied to clipboard");return}if(value==="file"){current.setOverlay({kind:"export-input",title:"Save conversation",value:defaultFilename,hint:"Enter to save · Esc to go back",onSubmit:(name)=>{current.setOverlay(null),exportToFile(name,content)},onCancel:showChoices});return}current.setOverlay(null),current.push("system","Export cancelled")}})};showChoices()},runReview=async(target)=>{let store=useStore.getState(),hint=userFacingHint(target),prompt;try{prompt=await reviewPrompt(target,process.cwd(),languageRef.current)}catch(error){store.push("error",`Failed to start review: ${errorMessage(error)}`);return}store.push("system",`Reviewing ${hint}…`),await sendPrompt(buildReviewRequest(prompt,languageRef.current),`/review ${hint}`,{raw:!0,injectContext:!0,isolated:!0})},guardReview=async()=>{let store=useStore.getState();if(store.overlay||store.switching)return!1;if(store.busy)return store.push("system","Please wait for the current response to finish before starting a review."),!1;if(store.status!=="ready")return store.push("system","Not connected to an ACP provider. Restart with --acp <provider-id>."),!1;if(!await isGitRepo(process.cwd()))return store.push("system","/review needs a git repository in the current directory."),!1;return!0},openReviewBranchPicker=async()=>{let store=useStore.getState(),[branches,current]=await Promise.all([localBranches(process.cwd()),currentBranch(process.cwd())]);if(branches.length===0){store.push("system","No other local branches to compare against.");return}let head=current??"(detached HEAD)";store.setOverlay({kind:"review-branch",title:"Select a base branch",emptyText:"No matching branches",escapeValue:null,items:branches.map((branch)=>({value:branch,label:`${head} → ${branch}`})),resolve:(value)=>{if(useStore.getState().setOverlay(null),value!=null)runReview({kind:"base-branch",branch:value})}})},openReviewCommitPicker=async()=>{let store=useStore.getState(),commits=await recentCommits(process.cwd());if(commits.length===0){store.push("system","No commits found in this repository.");return}store.setOverlay({kind:"review-commit",title:"Select a commit to review",emptyText:"No matching commits",escapeValue:null,items:commits.map((commit)=>({value:commit.sha,label:`${commit.sha.slice(0,7)} ${commit.subject}`})),resolve:(value)=>{if(useStore.getState().setOverlay(null),value==null)return;let hit=commits.find((commit)=>commit.sha===value);runReview({kind:"commit",sha:value,title:hit?.subject??null})}})},openReviewCustomPrompt=(showPresets)=>{useStore.getState().setOverlay({kind:"review-input",title:"Custom review instructions",value:"",hint:"Enter to start review · Esc to go back",onSubmit:(text)=>{let instructions=String(text??"").trim();if(useStore.getState().setOverlay(null),instructions.length===0){useStore.getState().push("system","Review cancelled: no instructions given.");return}runReview({kind:"custom",instructions})},onCancel:showPresets})},openReviewPicker=async()=>{if(!await guardReview())return;let dirty=await hasUncommittedChanges(process.cwd()),showPresets=()=>{useStore.getState().setOverlay({kind:"review",title:"Select a review preset",searchable:!1,escapeValue:null,items:[{value:"base-branch",label:"Review against a base branch (PR style)"},{value:"uncommitted",label:dirty?"Review uncommitted changes":"Review uncommitted changes (working tree is clean)"},{value:"commit",label:"Review a commit"},{value:"custom",label:"Custom review instructions"}],resolve:(value)=>{let current=useStore.getState();if(value==="custom"){openReviewCustomPrompt(showPresets);return}if(current.setOverlay(null),value==null)return;if(value==="uncommitted"){if(!dirty){current.push("system","No uncommitted changes to review.");return}runReview({kind:"uncommitted"});return}if(value==="base-branch")openReviewBranchPicker();if(value==="commit")openReviewCommitPicker()}})};showPresets()},reviewWithInstructions=async(instructions)=>{if(!await guardReview())return;await runReview({kind:"custom",instructions})},runSimplify=async(target)=>{let store=useStore.getState(),hint=userFacingHint2(target),prompt;try{prompt=await simplifyPrompt(target,process.cwd(),languageRef.current)}catch(error){store.push("error",`Failed to start simplify: ${errorMessage(error)}`);return}store.push("system",`Simplifying ${hint}…`),await sendPrompt(buildSimplifyRequest(prompt,languageRef.current),`/simplify ${hint}`,{raw:!0,injectContext:!0,isolated:!0})},guardSimplify=()=>{let store=useStore.getState();if(store.overlay||store.switching)return!1;if(store.busy)return store.push("system","Please wait for the current response to finish before starting a simplify."),!1;if(store.status!=="ready")return store.push("system","Not connected to an ACP provider. Restart with --acp <provider-id>."),!1;return!0},openSimplifyBranchPicker=async()=>{let store=useStore.getState(),[branches,current]=await Promise.all([localBranches(process.cwd()),currentBranch(process.cwd())]);if(branches.length===0){store.push("system","No other local branches to compare against.");return}let head=current??"(detached HEAD)";store.setOverlay({kind:"simplify-branch",title:"Select a base branch",emptyText:"No matching branches",escapeValue:null,items:branches.map((branch)=>({value:branch,label:`${head} → ${branch}`})),resolve:(value)=>{if(useStore.getState().setOverlay(null),value!=null)runSimplify({kind:"base-branch",branch:value})}})},openSimplifyCommitPicker=async()=>{let store=useStore.getState(),commits=await recentCommits(process.cwd());if(commits.length===0){store.push("system","No commits found in this repository.");return}store.setOverlay({kind:"simplify-commit",title:"Select a commit to simplify",emptyText:"No matching commits",escapeValue:null,items:commits.map((commit)=>({value:commit.sha,label:`${commit.sha.slice(0,7)} ${commit.subject}`})),resolve:(value)=>{if(useStore.getState().setOverlay(null),value==null)return;let hit=commits.find((commit)=>commit.sha===value);runSimplify({kind:"commit",sha:value,title:hit?.subject??null})}})},openSimplifyInput=({title,emptyMessage,buildTarget,showPresets})=>{useStore.getState().setOverlay({kind:"simplify-input",title,value:"",hint:"Enter to start simplify · Esc to go back",onSubmit:(text)=>{let entered=String(text??"").trim();if(useStore.getState().setOverlay(null),entered.length===0){useStore.getState().push("system",emptyMessage);return}runSimplify(buildTarget(entered))},onCancel:showPresets})},openSimplifyPicker=async()=>{if(!guardSimplify())return;let inRepo=await isGitRepo(process.cwd()),dirty=inRepo&&await hasUncommittedChanges(process.cwd()),uncommittedSuffix="";if(!inRepo)uncommittedSuffix=" (not a git repository)";else if(!dirty)uncommittedSuffix=" (working tree is clean)";let showPresets=()=>{useStore.getState().setOverlay({kind:"simplify",title:"Select a simplify preset",searchable:!1,escapeValue:null,items:[{value:"uncommitted",label:`Simplify uncommitted changes${uncommittedSuffix}`},{value:"base-branch",label:"Simplify changes against a base branch (PR style)"},{value:"commit",label:"Simplify code from a commit"},{value:"paths",label:"Simplify specific files or directories"},{value:"custom",label:"Custom simplify instructions"}],resolve:(value)=>{let current=useStore.getState();if(value==="paths"){openSimplifyInput({title:"Files or directories to simplify",emptyMessage:"Simplify cancelled: no paths given.",buildTarget:(paths)=>({kind:"paths",paths}),showPresets});return}if(value==="custom"){openSimplifyInput({title:"Custom simplify instructions",emptyMessage:"Simplify cancelled: no instructions given.",buildTarget:(instructions)=>({kind:"custom",instructions}),showPresets});return}if(current.setOverlay(null),value==null)return;if(!inRepo){current.push("system","/simplify needs a git repository for this preset.");return}switch(value){case"uncommitted":if(!dirty){current.push("system","No uncommitted changes to simplify.");return}runSimplify({kind:"uncommitted"});return;case"base-branch":openSimplifyBranchPicker();return;case"commit":openSimplifyCommitPicker();return}}})};showPresets()},simplifyWithArgs=async(args)=>{if(!guardSimplify())return;await runSimplify(looksLikePaths(args)?{kind:"paths",paths:args}:{kind:"custom",instructions:args})},runCommit=async(target)=>{let store=useStore.getState(),hint=userFacingHint3(target),prompt;try{prompt=await commitPrompt7(target,process.cwd(),languageRef.current)}catch(error){store.push("error",`Failed to start commit: ${errorMessage(error)}`);return}store.push("system",`Committing ${hint}…`),await sendPrompt(buildCommitRequest(prompt,languageRef.current),`/commit ${hint}`,{raw:!0,injectContext:!0,isolated:!0})},guardCommit=async({command="/commit",action="starting a commit"}={})=>{let store=useStore.getState();if(store.overlay||store.switching)return!1;if(store.busy)return store.push("system",`Please wait for the current response to finish before ${action}.`),!1;if(store.status!=="ready")return store.push("system","Not connected to an ACP provider. Restart with --acp <provider-id>."),!1;if(!await isGitRepo(process.cwd()))return store.push("system",`${command} needs a git repository.`),!1;return!0},commitTargetBlocker=async(target)=>{let cwd=process.cwd();if(target.kind==="staged"&&!await hasStagedChanges(cwd))return"Nothing staged to commit. Stage changes first, or use /commit without arguments.";if(target.kind==="amend"&&!await hasCommits(cwd))return"No existing commit to amend.";if((target.kind==="default"||target.kind==="message")&&!await hasUncommittedChanges(cwd))return"No changes to commit.";return null},startCommit=async(target)=>{let blocker=await commitTargetBlocker(target);if(blocker){useStore.getState().push("system",blocker);return}await runCommit(target)},openCommitInput=({title,emptyMessage,buildTarget,showPresets})=>{useStore.getState().setOverlay({kind:"commit-input",title,value:"",hint:"Enter to start commit · Esc to go back",onSubmit:(text)=>{let entered=String(text??"").trim();if(useStore.getState().setOverlay(null),entered.length===0){useStore.getState().push("system",emptyMessage);return}startCommit(buildTarget(entered))},onCancel:showPresets})},openCommitPicker=async()=>{if(!await guardCommit())return;let cwd=process.cwd(),[dirty,staged,committed]=await Promise.all([hasUncommittedChanges(cwd),hasStagedChanges(cwd),hasCommits(cwd)]),dirtySuffix=dirty?"":" (working tree is clean)",stagedSuffix=staged?"":" (nothing staged)",amendSuffix=committed?"":" (no commit to amend)",showPresets=()=>{useStore.getState().setOverlay({kind:"commit",title:"Select a commit preset",searchable:!1,escapeValue:null,items:[{value:"default",label:`Commit all changes${dirtySuffix}`},{value:"staged",label:`Commit staged changes only${stagedSuffix}`},{value:"paths",label:"Commit specific files or directories"},{value:"message",label:"Commit with a message you provide"},{value:"amend",label:`Amend the last commit${amendSuffix}`}],resolve:(value)=>{let current=useStore.getState();if(value==="paths"){openCommitInput({title:"Files or directories to commit",emptyMessage:"Commit cancelled: no paths given.",buildTarget:(paths)=>({kind:"paths",paths}),showPresets});return}if(value==="message"){openCommitInput({title:"Commit message",emptyMessage:"Commit cancelled: no message given.",buildTarget:(message)=>({kind:"message",message}),showPresets});return}if(current.setOverlay(null),value==null)return;startCommit({kind:value})}})};showPresets()},commitWithArgs=async(args)=>{if(!await guardCommit())return;await startCommit(parseCommitArgs(args))},commitPushPr=async()=>{if(!await guardCommit({command:"/commit-push-pr",action:"publishing changes"}))return;let store=useStore.getState(),prompt;try{prompt=await commitPushPrPrompt(process.cwd(),languageRef.current)}catch(error){store.push("error",`Failed to start commit-push-pr: ${errorMessage(error)}`);return}store.push("system","Committing, pushing, and creating a pull request…"),await sendPrompt(buildCommitPushPrRequest(prompt,languageRef.current),"/commit-push-pr",{raw:!0,injectContext:!0,isolated:!0})},runBashCommand=async(command)=>{let store=useStore.getState();if(!command){store.push("system","Please enter a command to run, e.g. !ls -la");return}store.startBashCard(command),store.startTurn("bash");let task=startBash(command);bashTaskRef.current=task;try{let{stdout,stderr,outcome}=await task.result;store.finishBashCard({stdout,stderr,outcome}),store.pushBashContext(formatBashContext({command,stdout,stderr,outcome}))}finally{bashTaskRef.current=null,store.endTurn()}},guardGoal=()=>{let store=useStore.getState();if(store.overlay||store.switching)return null;if(store.status!=="ready")return store.push("system","Not connected to an ACP provider. Restart with --acp <provider-id>."),null;if(!isMiroProvider({id:store.providerId}))return store.push("system","Goals are only available in Miro."),null;let client=clientRef.current;if(typeof client?.promptGoal!=="function")return store.push("system","This provider does not support goals."),null;return client},showGoalStatus=()=>{let client=guardGoal();if(!client)return;let store=useStore.getState(),goal=client.goalSnapshot();if(goal==null){store.push("system","No goal yet. Use /goal <objective> to start one.");return}let lines=[`Objective: ${goal.objective}`,goal.completionCriterion?`Done when: ${goal.completionCriterion}`:null,`Status: ${goal.status}${goal.terminalReason?` (${goal.terminalReason})`:""}`,`Progress: ${goal.turnsUsed} turns, ${goal.tokensUsed} tokens, ${formatElapsed(goal.wallClockMs)} elapsed`].filter((line)=>line!=null),budgets=[goal.budget.turnBudget!=null?`${goal.budget.remainingTurns} turns`:null,goal.budget.tokenBudget!=null?`${goal.budget.remainingTokens} tokens`:null,goal.budget.wallClockBudgetMs!=null?formatElapsed(goal.budget.remainingWallClockMs??0):null].filter((part)=>part!=null);if(budgets.length>0)lines.push(`Remaining budget: ${budgets.join(", ")}`);if(goal.status==="paused"||goal.status==="blocked")lines.push("Use /goal resume to continue it.");store.push("system",lines.join(`
2269
+ `))},runGoal=async(start,displayText,{recordUser=!0}={})=>{let store=useStore.getState();if(recordUser)store.push("user",displayText);store.startTurn("prompt");let result;try{result=await start()}catch(error){if(useStore.getState().cancelling)result={stopReason:"cancelled"};else store.push("error",`Goal failed: ${errorMessage(error)}`)}finally{flushQueuedThought(),store.endTurn(result),drainQueue()}let goal=clientRef.current?.goalSnapshot?.();if(goal!=null&&["paused","blocked","complete"].includes(goal.status)){let reason=goal.terminalReason?` — ${goal.terminalReason}`:"";useStore.getState().push("system",`Goal ${goal.status} after ${goal.turnsUsed} turns${reason}`)}},startGoal=(objective)=>{let client=guardGoal();if(!client)return;let store=useStore.getState();if(store.busy){if(typeof client.createPendingGoal!=="function"||typeof client.activatePendingGoal!=="function"){store.push("system","This provider cannot safely start a goal while a response is running.");return}try{client.createPendingGoal(objective,{replace:!0}),goalTakeoverRef.current={client,displayText:`/goal ${objective}`},client.cancel()}catch(error){store.push("error",`Could not queue goal: ${errorMessage(error)}`)}return}runGoal(()=>client.promptGoal(objective,{replace:!0}),`/goal ${objective}`)},resumeGoal=()=>{let client=guardGoal();if(!client)return;let store=useStore.getState(),goal=client.goalSnapshot();if(goal==null){store.push("system","No goal to resume. Use /goal <objective> to start one.");return}if(goal.status==="active"){store.push("system","The goal is already running.");return}if(goal.status==="complete"){store.push("system","That goal is already complete. Use /goal <objective> to start a new one.");return}if(store.busy){if(typeof client.queueResumeGoal!=="function"||typeof client.activatePendingGoal!=="function"){store.push("system","This provider cannot safely resume a goal while a response is running.");return}try{client.queueResumeGoal(),goalTakeoverRef.current={client,displayText:"/goal resume"},client.cancel()}catch(error){store.push("error",`Could not queue goal resume: ${errorMessage(error)}`)}return}runGoal(()=>client.resumeGoal(),"/goal resume")},pauseGoal=()=>{let client=guardGoal();if(!client)return;let store=useStore.getState(),goal=client.goalSnapshot();if(goal==null||goal.status!=="active"){store.push("system","No running goal to pause.");return}if(store.busy){if(goalTakeoverRef.current=null,typeof client.requestPauseGoal!=="function"){store.push("system","This provider cannot safely pause a running goal.");return}client.requestPauseGoal("Paused by user"),client.cancel();return}client.pauseGoal("Paused by user"),store.push("system","Goal paused. Use /goal resume to continue it.")},cancelGoal=()=>{let client=guardGoal();if(!client)return;let store=useStore.getState();if(client.goalSnapshot()==null){store.push("system","No goal to cancel.");return}if(goalTakeoverRef.current=null,client.cancelGoal(),store.busy){goalAfterStopNoticeRef.current="Goal cancelled.",client.cancel();return}store.push("system","Goal cancelled.")},handleGoalCommand=(args)=>{if(useStore.getState().modes?.currentModeId==="plan"){useStore.getState().push("system","Exit Plan Mode before starting or changing a goal.");return}let text=(args??"").trim();if(text.startsWith("replace ")){let objective=text.slice(8).trim();if(objective.length===0)useStore.getState().push("error","Usage: /goal replace <objective>");else startGoal(objective);return}switch(text){case"":case"status":showGoalStatus();break;case"resume":case"continue":resumeGoal();break;case"pause":case"stop":pauseGoal();break;case"cancel":case"clear":cancelGoal();break;default:startGoal(text)}},sendPrompt=async(content,displayText,{raw=!1,injectContext=!raw,isolated=!1,inputId=null}={})=>{let store=useStore.getState();if(store.busy){store.push("system","Please wait for the current operation to finish.");return}if(store.status!=="ready"){store.push("system","Not connected to an ACP provider. Restart with --acp <provider-id>.");return}if(inputId)store.applyInput({id:inputId,text:displayText});else store.push("user",displayText);store.startTurn("prompt");let bashContext=raw?[]:store.takeBashContext(),blocks=typeof content==="string"?[{type:"text",text:content}]:content,payload=bashContext.length>0?[...bashContext.map((item)=>({type:"text",text:item})),...blocks]:blocks,client=clientRef.current,detach=isolated&&typeof client.promptIsolated==="function",result;try{result=detach?await client.promptIsolated(payload,{displayText,injectContext}):await client.prompt(payload,{injectContext,inputId,displayText})}catch(error){if(bashContext.length>0)store.restoreBashContext(bashContext);if(useStore.getState().cancelling)result={stopReason:"cancelled"};else store.push("error",`Request failed: ${errorMessage(error)}`)}finally{flushQueuedThought(),store.endTurn(result);let transition=result?.transition;if(transition?.type==="plan_entered")store.queueInput("Continue the current request in Plan Mode. Inspect the workspace, resolve material uncertainties, and write the implementation plan.","Continue in Plan Mode");else if(transition?.type==="plan_approved")store.pushProposedPlan(transition.plan,transition.path),store.queueInput(approvedPlanPrompt(transition.plan),"Implement approved plan");drainQueue()}},compactConversation=async(instructions,commandText)=>{let store=useStore.getState(),client=clientRef.current;if(store.overlay||store.switching)return;if(store.status!=="ready"||!client){store.push("system","Wait for the session to be ready before compacting context.");return}if(store.busy){store.push("system","Wait for the current operation to finish, or press Esc before using /compact.");return}if(typeof client.compact!=="function"){if(matchProviderCommand(commandText,store.providerCommands))await sendPrompt(commandText,commandText,{raw:!0});else store.push("system","This provider does not support /compact.");return}store.startTurn("compact");let result;try{if(result=await client.compact({instructions}),result.reason==="nothing_to_compact")store.push("system","Not enough history to compact.")}catch(error){if(useStore.getState().cancelling)result={stopReason:"cancelled"};else store.push("error",`Compaction failed: ${errorMessage(error)}`)}finally{store.endTurn(result),drainQueue()}},drainQueue=()=>{let state=useStore.getState();if(state.busy||state.status!=="ready"||state.switching||state.queuePaused||state.overlay?.kind==="queue-review")return;let client=clientRef.current;if(client?.goalSnapshot?.()?.status==="pausing"&&typeof client.finishPauseGoal==="function")client.finishPauseGoal(),useStore.getState().push("system","Goal paused. Use /goal resume to continue it.");let afterStopNotice=goalAfterStopNoticeRef.current;if(afterStopNotice!=null)goalAfterStopNoticeRef.current=null,useStore.getState().push("system",afterStopNotice);let takeover=goalTakeoverRef.current;if(takeover!=null){if(goalTakeoverRef.current=null,takeover.client===clientRef.current&&typeof takeover.client.activatePendingGoal==="function"){runGoal(()=>takeover.client.activatePendingGoal(),takeover.displayText);return}}let queued=useStore.getState().takeQueuedInput();if(queued!=null)handleSubmit(queued.text,queued.display,{intent:"dequeue",inputId:queued.id})},handleSubmit=async(raw,display,{intent="submit",inputId=null}={})=>{let store=useStore.getState(),submitted=prepareSubmittedInput(raw,display);if(!submitted)return;let{content,commandText:text,display:shown,transcriptText}=submitted;if(store.busy){if(isBashInput(text)){store.push("system","Please wait for the current response to finish before running shell commands.");return}if(!parseCommandInput(text)&&!bareExitCommand(text)){let client=clientRef.current,capability=client?.steeringCapability?.();if(intent==="submit"&&!matchProviderCommand(text,store.providerCommands)&&!store.cancelling&&capability?.available&&typeof client.steerInput==="function"){let id=randomUUID7();if(client.steerInput({id,turnId:capability.turnId,content,display:transcriptText}).accepted){store.addPendingInput({id,text:content,display:transcriptText}),checkpointUiState();return}}if(store.queueInput(content,shown,randomUUID7()),checkpointUiState(),intent==="submit")store.push("system","This operation cannot accept steering; message queued for the next turn.");return}}if(intent!=="dequeue"&&!isBashInput(text)&&!parseCommandInput(text)&&!bareExitCommand(text)&&store.queuedInputs.length>0){if(store.queueInput(content,shown,randomUUID7()),checkpointUiState(),!store.queuePaused)drainQueue();return}if(isBashInput(text)){await runBashCommand(getBashCommand(text));return}let commandHandlers={mcp:async(args)=>{let client=clientRef.current;if(!(client instanceof MiroAgentClient)){store.push("system","MCP manager is available with the built-in miro agent.");return}if(store.busy||store.switching){store.push("system","Wait for the current activity before changing MCP servers.");return}let[action,serverName]=args.trim().split(/\s+/,2);if(action&&!["list","trust","reconnect"].includes(action)||action==="reconnect"&&!serverName){store.push("system","Usage: /mcp [list|trust|reconnect <server>]");return}store.setSwitching("Reloading MCP configuration…");try{await client.reloadMcp()}catch(error){if(client===clientRef.current&&!client.closed)store.push("error",errorMessage(error));return}finally{if(client===clientRef.current)store.setSwitching(null)}if(client!==clientRef.current||client.closed)return;let runtime=client.mcpRuntime;for(let diagnostic of runtime.diagnostics)store.push("system",diagnostic);if(action==="trust"){let trust=projectMcpTrust(process.cwd());if(!trust.exists){store.push("system",`No project MCP file at ${trust.file}`);return}let configured=[];try{configured=Object.entries(JSON.parse(readFileSync14(trust.file,"utf8")).mcpServers??{})}catch{}store.setOverlay({kind:"mcp-trust",title:`Trust MCP commands in ${trust.file}?`,searchable:!1,items:[...configured.map(([name,entry])=>({value:`show-${name}`,label:`${name}: ${entry.command??entry.url??"invalid"}`,disabled:!0})),{value:"trust",label:"Trust this file and load its servers"},{value:"cancel",label:"Cancel"}],resolve:(value)=>{if(store.setOverlay(null),value!=="trust")return;trustProjectMcp(process.cwd()),client.reloadMcp().then(()=>store.push("system","Project MCP servers loaded.")).catch((error)=>store.push("error",errorMessage(error)))}});return}if(action==="reconnect"&&serverName){runtime.reconnect(serverName).then((result)=>store.push("system",JSON.stringify(result))).catch((error)=>store.push("error",errorMessage(error)));return}if(action&&action!=="list"){store.push("system","Usage: /mcp [list|trust|reconnect <server>]");return}let servers=runtime.configured?.length?runtime.configured:[...runtime.servers.values()],trust=projectMcpTrust(process.cwd());if(servers.length===0){store.push("system",trust.exists&&!trust.trusted?`Project MCP config needs trust. Run /mcp trust. (${trust.file})`:"No MCP servers configured.");return}if(action==="list"){let serverState=(server)=>{if(server.enabled===!1)return"disabled";return runtime.connections.get(server.name)?.connected?"connected":"disconnected"};store.push("system",servers.map((server)=>`${server.name} (${server.type}, ${serverState(server)})`).join(`
2270
+ `));return}store.setOverlay({kind:"mcp",title:"MCP servers",searchable:!1,items:servers.map((server)=>({value:server.name,label:`${server.name} ${server.type}${server.enabled===!1?" disabled":""}`})),resolve:(name)=>{if(store.setOverlay(null),!name)return;let server=servers.find((entry)=>entry.name===name),toggle=server.enabled===!1?{value:"enable",label:"Enable"}:{value:"disable",label:"Disable"},supportsOAuth=server.enabled!==!1&&server.type==="http"&&!Object.keys(runtime.servers.get(name)?.headers??{}).some((key)=>key.toLowerCase()==="authorization");store.setOverlay({kind:"mcp-action",title:`MCP ${name}`,searchable:!1,items:[...server.enabled===!1?[]:[{value:"tools",label:"Show tools"},{value:"reconnect",label:"Reconnect"}],toggle,...supportsOAuth?[{value:"login",label:"Sign in"},{value:"logout",label:"Sign out"}]:[]],resolve:(selected)=>{if(store.setOverlay(null),!selected)return;if(selected==="tools"||selected==="reconnect")(selected==="tools"?runtime.listTools({server:name}):runtime.reconnect(name)).then((result)=>store.push("system",JSON.stringify(result,null,2))).catch((error)=>store.push("error",errorMessage(error)));else if(selected==="login"){let isCurrent=()=>client===clientRef.current&&!client.closed,loginOverlay={kind:"mcp-login",title:`Signing in to MCP ${name}…`,searchable:!1,items:[{value:"cancel",label:"Cancel sign-in"}],escapeValue:null,resolve:()=>{if(isCurrent())client.cancel()}};store.setSwitching("Signing in to MCP…"),store.setOverlay(loginOverlay),client.loginMcp(name,{print:(message)=>{if(isCurrent())store.push("system",message)}}).catch((error)=>{if(!isCurrent())return;if(error?.name==="AbortError")store.push("system","MCP sign-in cancelled.");else store.push("error",errorMessage(error))}).finally(()=>{if(!isCurrent())return;if(store.setSwitching(null),useStore.getState().overlay===loginOverlay)store.setOverlay(null)})}else if(selected==="logout")logoutMcp(runtime.servers.get(name)),runtime.reconnect(name).catch(()=>{}),store.push("system",`Signed out of MCP server ${name}.`);else try{updateMcpServerSetting(server,"enabled",selected==="enable",process.cwd()),client.reloadMcp().then(()=>store.push("system",`MCP ${name}: ${selected}`)).catch((error)=>store.push("error",errorMessage(error)))}catch(error){store.push("error",errorMessage(error))}}})}})},init:(args)=>void sendPrompt([{type:"text",text:buildInitPrompt(args,languageRef.current)}],args?`/init ${args}`:"/init",{isolated:!0}),model:(args)=>args?setModelByName(args):openModelPicker(),effort:(args)=>args?setEffortByName(args):openEffortPicker(),config:handleConfigCommand,statusline:(args)=>args.trim()==="reset"?resetStatusLine():openStatusLineSetup(),thinking:(args)=>args?setThinkingDisplayByName(args):openThinkingPicker(),permissions:(args)=>args?setPermissionModeByName(args):openPermissionPicker(),plan:handlePlanCommand,resume:(args)=>args?resumeById(args):openSessionPicker(),new:startNewSession,sessions:listSessionsSummary,compact:(args)=>void compactConversation(args,text),export:(args)=>args?exportToFile(args):openExportDialog(),review:(args)=>void(args?reviewWithInstructions(args):openReviewPicker()),goal:handleGoalCommand,simplify:(args)=>void(args?simplifyWithArgs(args):openSimplifyPicker()),commit:(args)=>void(args?commitWithArgs(args):openCommitPicker()),"commit-push-pr":()=>void commitPushPr(),clear:()=>startNewSession({clearTerminal:!0}),help:()=>store.push("system",HELP.trimEnd()),exit:exitSession},parsed=parseCommandInput(text)??bareExitCommand(text);if(parsed){commandHandlers[parsed.key]?.(parsed.args);return}if(matchProviderCommand(text,store.providerCommands)){await sendPrompt(text,shown??text,{raw:!0,inputId});return}await sendPrompt(content,transcriptText,{inputId})},handleGlobalKey=(input,key,helpOpenBefore)=>{if(key.escape){if(helpOpenBefore){composer.helpOpen=!1;return}let store=useStore.getState();if(!store.overlay&&(store.busy||bashTaskRef.current))interrupt();return}if(!key.ctrl)return;if(input==="m"){openModelPicker();return}if(input==="c"){let store=useStore.getState();switch(ctrlCIntent({hasOverlay:Boolean(store.overlay),hasDraft:composer.hasDraft()})){case"overlay":cancelOverlay(store.overlay);return;case"draft":composer.clearDraft(),cancelExitConfirm();return;default:interrupt(),confirmExit();return}}if(input==="l")clearScreen();if(input==="o"){let store=useStore.getState(),target=findReviewTarget(store);if(!target)return;switch(target.kind){case"close":store.setOverlay(null);return;case"review":store.setOverlay({kind:"review-browser",entries:target.entries,initialIndex:target.index,escapeValue:null,resolve:()=>useStore.getState().setOverlay(null)});return}}if(input==="q"){let store=useStore.getState();if(store.overlay?.kind==="queue-review")store.setOverlay(null),drainQueue();else if(!store.overlay&&(store.queuedInputs.length>0||store.pendingInputs.length>0))store.setOverlay({kind:"queue-review",escapeValue:null,resolve:()=>{useStore.getState().setOverlay(null),drainQueue()}})}},overlayWidget=null,overlayWidgetFor=null,widgetForOverlay=(overlay)=>{if(!overlay)return null;if(overlay===overlayWidgetFor&&overlayWidget)return overlayWidget;return overlayWidgetFor=overlay,overlayWidget=createOverlayWidget(overlay),overlayWidget},createOverlayWidget=(overlay)=>{switch(overlay.kind){case"review-browser":return new ReviewBrowser(overlay.entries,overlay.initialIndex,()=>useStore.getState().setOverlay(null));case"queue-review":return new QueueEditor({onClose:()=>{useStore.getState().setOverlay(null),drainQueue()},onResume:()=>{useStore.getState().resumeInputQueue(),useStore.getState().setOverlay(null),checkpointUiState(),drainQueue()}});case"permission":return new PermissionDialog({toolCall:overlay.toolCall,items:overlay.items,escapeValue:overlay.escapeValue,onResolve:(value)=>overlay.resolve(value)});case"plan-review":return new PlanReviewDialog({plan:overlay.plan,path:overlay.path,onResolve:(value)=>overlay.resolve(value)});case"user-question":return new UserQuestionDialog(overlay.questions,(value)=>overlay.resolve(value));case"export-input":case"review-input":case"simplify-input":case"commit-input":return new InputPrompt({title:overlay.title,value:overlay.value,secret:overlay.secret,hint:overlay.hint,onSubmit:overlay.onSubmit,onCancel:overlay.onCancel});case"config":return new ConfigPanel({getOptions:panelConfigOptions,focusId:overlay.focusId,onChange:(option,value)=>void applyConfigOptionValue(option,value),onCancel:()=>overlay.resolve(overlay.escapeValue)});case"statusline":return new StatusLineSetup({configuredIds:overlay.configuredIds,useColors:overlay.useColors,snapshot:overlay.snapshot,onConfirm:(value)=>overlay.resolve(value),onCancel:()=>overlay.resolve(overlay.escapeValue)});default:break}if(overlay.steps)return new PickerFlow(overlay.steps,overlay.initialContext,(context)=>overlay.resolve(context),()=>overlay.resolve(overlay.escapeValue));return new Picker({title:overlay.title,subtitle:overlay.subtitle,items:overlay.items,selected:overlay.selected,color:"cyan",searchable:overlay.searchable??!0,emptyText:overlay.emptyText,footerHint:overlay.footerHint,onSelect:(item)=>overlay.resolve(item?.value??overlay.escapeValue),onCancel:()=>overlay.resolve(overlay.escapeValue)})},syncComposer=()=>{let state=useStore.getState();composer.disabled=composerIsHidden(state.status==="connecting",state.overlay?.kind)||state.overlay!=null||state.switching!=null,composer.locked=modeSwitching||exiting,composer.busy=state.busy,composer.canSteer=!state.cancelling&&clientRef.current?.steeringCapability?.().available===!0,composer.providerCommands=state.providerCommands},handleInput=(event)=>{if(exiting)return;syncComposer();let overlay=useStore.getState().overlay,target=overlay?widgetForOverlay(overlay):composer.disabled?null:composer;if(event.type==="paste"){target?.onPaste?.(event.text),invalidate();return}let helpOpenBefore=composer.helpOpen;if(handleGlobalKey(event.input,event.key,helpOpenBefore),target&&!exiting)target.onKey(event.input,event.key);invalidate()},buildLive=(width,rows)=>{syncComposer();let state=useStore.getState(),{overlay,status,busy,cancelling,bashCard,pending,pendingInputs,queuedInputs,queuePaused}=state,now=Date.now(),view={lines:[],cursor:null};if(SCREEN_TAKEOVER_OVERLAYS.has(overlay?.kind)){let widget=widgetForOverlay(overlay);if(widget)appendView(view,widget.render(width,rows));return{lines:view.lines,cursor:view.cursor??null}}let awaitingInput=isAwaitingInputOverlay(overlay?.kind);if(bashCard)view.lines.push(...renderBashCard(bashCard,width));if(pending)view.lines.push(...renderBlock(pending,{width}));if(view.lines.push(...renderActivitySlot({now,width,awaitingInput})),view.lines.push(...renderStatusVerb({now,width,awaitingInput})),view.lines.push(""),overlay){let widget=widgetForOverlay(overlay);if(widget)appendView(view,widget.render(width,rows))}else overlayWidget=null,overlayWidgetFor=null;if(!composerIsHidden(status==="connecting",overlay?.kind)){let composerView=composer.render(width,rows);appendView(view,overlay?{lines:composerView.lines}:composerView)}if(pendingInputs.length>0){let inner=Math.max(1,width-2);view.lines.push(` ${style(truncate4(`${pendingInputs.length} steering message${pendingInputs.length>1?"s":""} waiting for the current response and tools`,inner),{color:"cyan"})}`);for(let input of pendingInputs.slice(0,3))view.lines.push(` ${dim(truncate4(String(input.display??input.text).replace(/\s+/g," "),inner))}`)}let{modelConfig,effortConfig,modes}=state;return view.lines.push(...renderStatusBar({width,agentBin,exitConfirming,statusLineItems:statusLineConfig.items,statusLineUseColors:statusLineConfig.useColors,inputHint:inputHint({busy,hasDraft:composerHasDraft(composer.snapshot()),canSteer:composer.canSteer,queuedCount:queuedInputs.length,queuePaused}),statusLineSnapshot:{modelName:modelConfig?currentModelName(modelConfig):null,effortName:currentEffortName(effortConfig),modeName:modes?.availableModes?.find((mode)=>mode.id===modes?.currentModeId)?.name??modes?.currentModeId??null,cwd:process.cwd(),projectName:projectNameFor(process.cwd()),hostname:hostname2(),permissionMode,gitBranch:state.gitBranch,providerName:state.providerName,sessionId:state.sessionId,sessionTitle:state.sessionTitle,version:APP_VERSION,usage:state.usage,sessionTokens:state.sessionTokens,sessionCost:state.sessionCost,plan:state.planProgress,goal:state.goal,busy,cancelling,thinking:state.thought!=null},hidden:statusLineIsHidden({helpOpen:composer.helpOpen,completionOpen:composer.completionOpen,overlay})})),{lines:view.lines,cursor:exiting?null:view.cursor??null}},dispose=()=>{if(unsubscribe(),clockTimer)clearInterval(clockTimer);if(clockTimer=null,releaseAnimation?.(),releaseAnimation=null,exitConfirmTimerRef.current)clearTimeout(exitConfirmTimerRef.current);checkpointUiState(),discardQueuedThought(),composer.dispose(),clientRef.current?.close()},provider=startupAcp==null?{id:"miro",name:"Miro",kind:"miro"}:detectProviders().find((item)=>!isMiroProvider(item)&&item.id===startupAcp);if(!provider){let available=detectProviders().filter((item)=>!isMiroProvider(item)).map((item)=>item.id).join(", ")||"none";useStore.getState().setFatalError(Error(`ACP provider "${startupAcp}" is not available; available ACP providers: ${available}`)),requestExit()}else startClient(provider,continueSessionId);return syncTimers(),{handleInput,buildLive,dispose,requestExit,isExiting:()=>exiting}}var AWAITING_INPUT_OVERLAYS,SCREEN_TAKEOVER_OVERLAYS;var init_app=__esm(()=>{init_acp_client();init_agent_client();init_mcp_config();init_mcp_oauth();init_goal();init_plan_mode();init_permission_mode();init_config();init_providers();init_agents_md();init_config_options();init_commands();init_bash();init_config();init_export();init_init();init_settings3();init_settings_file();init_thinking();init_language_config();init_language();init_items7();init_workspace_info();init_session_store();init_review_target();init_review();init_simplify();init_commit4();init_store();init_animation_clock();init_layout();init_activity();init_blocks();init_composer();init_dialogs();init_picker();init_review_browser();init_user_question();AWAITING_INPUT_OVERLAYS=new Set(["permission","plan-review","user-question","review-input","export-input","simplify-input","commit-input"]);SCREEN_TAKEOVER_OVERLAYS=new Set(["review-browser","queue-review"])});class Screen{out;sync;liveRows=0;cursorRow=0;clearPending=!1;lastLive=[];lastCursor=null;constructor(out,sync){this.out=out;this.sync=sync}requestClear(){this.clearPending=!0}draw(commit,live,cursor,{width,rows}){let cap=Math.max(3,rows-1),liveLines=live,caret=cursor;if(liveLines.length>cap){let drop=liveLines.length-cap;if(liveLines=liveLines.slice(drop),caret)caret=caret.row>=drop?{row:caret.row-drop,col:caret.col}:null}let fit=(line)=>truncate4(line,width),fitted=liveLines.map(fit);if(commit.length===0&&!this.clearPending&&fitted.length===this.lastLive.length&&fitted.every((line,index)=>line===this.lastLive[index])&&(caret?.row??-1)===(this.lastCursor?.row??-1)&&(caret?.col??-1)===(this.lastCursor?.col??-1))return;this.lastLive=fitted,this.lastCursor=caret;let frame=(this.sync?BSU:"")+HIDE_CURSOR,clearing=this.clearPending;if(clearing)frame+=CLEAR_ALL;else if(frame+="\r",this.cursorRow>0)frame+=`\x1B[${this.cursorRow}A`;for(let line of commit)frame+=`${fit(line)}\x1B[K\r
2271
+ `;if(fitted.forEach((line,index)=>{if(frame+=`${line}\x1B[K`,index+1<fitted.length)frame+=`\r
2272
+ `}),commit.length>0||liveLines.length>1||liveLines.length===1&&liveLines[0].length>0)frame+="\x1B[J";else if(!clearing&&this.liveRows>1){for(let index=1;index<this.liveRows;index+=1)frame+="\x1B[B\x1B[2K";frame+=`\x1B[${this.liveRows-1}A`}let last=liveLines.length>0?liveLines.length-1:0;if(caret){let row=Math.min(caret.row,last),up=last-row;if(up>0)frame+=`\x1B[${up}A`;if(frame+="\r",caret.col>0)frame+=`\x1B[${caret.col}C`;frame+=SHOW_CURSOR,this.cursorRow=row}else this.cursorRow=last;if(this.liveRows=liveLines.length,this.clearPending=!1,this.sync)frame+=ESU;this.out.write(frame)}}var BSU="\x1B[?2026h",ESU="\x1B[?2026l",HIDE_CURSOR="\x1B[?25l",SHOW_CURSOR="\x1B[?25h",CLEAR_ALL="\x1B[H\x1B[2J\x1B[3J";var init_screen=__esm(()=>{init_layout()});function emptyKey(){return{upArrow:!1,downArrow:!1,leftArrow:!1,rightArrow:!1,pageUp:!1,pageDown:!1,home:!1,end:!1,return:!1,escape:!1,ctrl:!1,shift:!1,tab:!1,backspace:!1,delete:!1,meta:!1}}function keyEvent(input,patch={}){let key={...emptyKey(),...patch};if(!key.ctrl&&input.length===1&&/[A-Z]/.test(input))key.shift=!0;return{type:"key",input,key}}function keyFromCodepoint(cp,mods){switch(cp){case 13:return keyEvent("",{...mods,return:!0});case 9:return keyEvent("",{...mods,tab:!0});case 127:case 8:return keyEvent("",{...mods,backspace:!0});case 27:return keyEvent("",{...mods,escape:!0});default:break}if(cp>=57344&&cp<=63743)return null;if(cp<32||cp>1114111)return null;return keyEvent(String.fromCodePoint(cp),mods)}function isPrintable(ch){let cp=ch.codePointAt(0)??0;return cp>=32&&cp!==127&&!(cp>=128&&cp<160)}class KeyDecoder{buf="";inPaste=!1;paste="";feed(text){this.buf+=text}hasPending(){return this.buf.length>0&&!this.inPaste}drain(final=!1){let events=[];for(;;){let event=this.next(final);if(event===void 0)break;if(event)events.push(event)}return events}next(final){if(this.inPaste)return this.nextPaste();let s=this.buf;if(s.length===0)return;if(s[0]==="\x1B"){if(s.startsWith("\x1B[200~"))return this.consume(6),this.inPaste=!0,this.paste="",this.nextPaste();if("\x1B[200~".startsWith(s)&&!final)return;if(s.length===1){if(!final)return;return this.consume(1),keyEvent("",{escape:!0})}if(s[1]==="[")return this.csi(final);if(s[1]==="O")return this.ss3(final);if(s[1]==="\x1B"){if(this.consume(1),s.length===2)return this.consume(1),keyEvent("",{escape:!0,meta:!0});return keyEvent("",{escape:!0})}let event=this.single(1,final);if(event===void 0)return;if(event&&event.type==="key")event.key.meta=!0;return event}return this.single(0,final)}consume(n){this.buf=this.buf.slice(n)}nextPaste(){let s=this.buf,idx=s.indexOf("\x1B[201~");if(idx!==-1){this.paste+=s.slice(0,idx),this.consume(idx+6),this.inPaste=!1;let text=this.paste;return this.paste="",{type:"paste",text}}let keep=Math.min(s.length,5);this.paste+=s.slice(0,s.length-keep),this.buf=s.slice(s.length-keep);return}single(off,final){let s=this.buf;if(off>=s.length){if(!final)return;return this.consume(s.length),keyEvent("",{escape:!0})}let ch=s[off],code=ch.charCodeAt(0),event,n=1;if(ch==="\r")event=keyEvent("",{return:!0});else if(ch===`
2273
+ `)event=keyEvent("",{return:!0,shift:!0});else if(ch==="\t")event=keyEvent("",{tab:!0});else if(code===127||code===8)event=keyEvent("",{backspace:!0});else if(code===0)event=keyEvent(" ",{ctrl:!0});else if(code>=1&&code<=26)event=keyEvent(String.fromCharCode(96+code),{ctrl:!0});else if(code>=28&&code<=31)event=null;else{if(code>=55296&&code<=56319&&off+1>=s.length&&!final)return;if(off>0){let cp=s.codePointAt(off)??0;n=cp>65535?2:1,event=keyEvent(String.fromCodePoint(cp))}else{let end=0;for(let part of s){if(!isPrintable(part))break;end+=part.length}n=Math.max(1,end),event=keyEvent(s.slice(0,n))}}return this.consume(off+n),event}ss3(final){let s=this.buf;if(s.length<3){if(!final)return;return this.consume(2),keyEvent("O",{meta:!0})}switch(this.consume(3),s[2]){case"A":return keyEvent("",{upArrow:!0});case"B":return keyEvent("",{downArrow:!0});case"C":return keyEvent("",{rightArrow:!0});case"D":return keyEvent("",{leftArrow:!0});case"H":return keyEvent("",{home:!0});case"F":return keyEvent("",{end:!0});default:return null}}csi(final){let s=this.buf,j=2;while(j<s.length){let c=s.charCodeAt(j);if(c>=64&&c<=126)break;j+=1}if(j>=s.length){if(!final)return;return this.consume(s.length),null}let fin=s[j],raw=s.slice(2,j);if(this.consume(j+1),raw.startsWith("?")||raw.startsWith(">")||raw.startsWith("<"))return null;if(fin==="R"||(fin==="I"||fin==="O")&&raw==="")return null;let nums=raw.split(";").map((part)=>{let head=part.split(":")[0],value=Number.parseInt(head,10);return Number.isFinite(value)?value:0}),modBits=nums.length>=2&&nums[1]>0?nums[1]-1:0,mods={shift:(modBits&1)!==0,meta:(modBits&2)!==0,ctrl:(modBits&4)!==0};switch(fin){case"A":return keyEvent("",{...mods,upArrow:!0});case"B":return keyEvent("",{...mods,downArrow:!0});case"C":return keyEvent("",{...mods,rightArrow:!0});case"D":return keyEvent("",{...mods,leftArrow:!0});case"H":return keyEvent("",{...mods,home:!0});case"F":return keyEvent("",{...mods,end:!0});case"Z":return keyEvent("",{...mods,tab:!0,shift:!0});case"u":return keyFromCodepoint(nums[0],mods);case"~":{if(nums[0]===27&&nums.length>=3){let cpMods=nums[1]>0?nums[1]-1:0;return keyFromCodepoint(nums[2],{shift:(cpMods&1)!==0,meta:(cpMods&2)!==0,ctrl:(cpMods&4)!==0})}switch(nums[0]){case 1:case 7:return keyEvent("",{...mods,home:!0});case 4:case 8:return keyEvent("",{...mods,end:!0});case 3:return keyEvent("",{...mods,delete:!0});case 5:return keyEvent("",{...mods,pageUp:!0});case 6:return keyEvent("",{...mods,pageDown:!0});default:return null}}default:return null}}}import process18 from"node:process";class Terminal{stdin=process18.stdin;stdout=process18.stdout;decoder=new KeyDecoder;flushTimer=null;active=!1;handlers=null;get columns(){return this.stdout.columns>0?this.stdout.columns:80}get rows(){return this.stdout.rows>0?this.stdout.rows:24}start(handlers){this.handlers=handlers,this.active=!0,this.enterRaw(),this.stdin.setEncoding("utf8"),this.stdin.on("data",this.onData),this.stdin.resume(),this.stdout.on("resize",this.onResize),process18.on("SIGTERM",this.onSignal),process18.on("SIGHUP",this.onSignal),process18.on("SIGCONT",this.onContinue),process18.on("exit",this.restore)}restore=()=>{if(!this.active)return;if(this.active=!1,this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=null,this.stdin.off("data",this.onData),this.stdout.off("resize",this.onResize),process18.off("SIGTERM",this.onSignal),process18.off("SIGHUP",this.onSignal),process18.off("SIGCONT",this.onContinue),process18.off("exit",this.restore);try{this.stdout.write(DISABLE_PROTOCOLS+DEFAULT_CURSOR+SHOW_CURSOR2)}catch{}if(this.stdin.isTTY)this.stdin.setRawMode(!1);this.stdin.pause()};write(text){if(text)this.stdout.write(text)}enterRaw(){if(this.stdin.isTTY)this.stdin.setRawMode(!0);this.stdout.write(ENABLE_PROTOCOLS)}onData=(chunk)=>{this.decoder.feed(typeof chunk==="string"?chunk:chunk.toString("utf8")),this.dispatch(!1)};dispatch(final){if(this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=null;for(let event of this.decoder.drain(final)){if(!this.active)return;this.handlers?.onInput(event)}if(this.active&&this.decoder.hasPending())this.flushTimer=setTimeout(()=>this.dispatch(!0),ESCAPE_FLUSH_MS)}onResize=()=>this.handlers?.onResize();onSignal=()=>this.handlers?.onSignal();onContinue=()=>{if(!this.active)return;this.enterRaw(),this.handlers?.onResize()}}var ENABLE_PROTOCOLS="\x1B[?2004h\x1B[>1u\x1B[>4;2m",DISABLE_PROTOCOLS="\x1B[?2004l\x1B[<u\x1B[>4m",SHOW_CURSOR2="\x1B[?25h",ESCAPE_FLUSH_MS=30;var init_terminal2=()=>{};import process19 from"node:process";import{format as format6}from"node:util";async function runTui(options){if(!process19.stdin.isTTY||!process19.stdout.isTTY)return process19.stderr.write(`miro must be run in an interactive terminal. Use -p for non-interactive mode.
2274
+ `),1;let term=new Terminal,screen=new Screen(term,shouldWrapSyncOutput()),consoleLines=[],originalConsole=Object.fromEntries(CONSOLE_METHODS.map((name)=>[name,console[name]]));for(let name of CONSOLE_METHODS)console[name]=(...args)=>{consoleLines.push(...format6(...args).split(`
2275
+ `)),invalidate()};let committedEpoch=useStore.getState().epoch,committedCount=0,lastColumns=term.columns,replayAll=!1,cursorPinned=!1,scheduled=null,lastFrameAt=0,finished=!1,resolveExit,exited=new Promise((resolve)=>{resolveExit=resolve}),draw=()=>{if(scheduled=null,finished)return;lastFrameAt=Date.now();let{columns,rows}=term,width=Math.max(8,columns-1);if(columns!==lastColumns)lastColumns=columns,replayAll=!0;let state=useStore.getState();if(state.epoch!==committedEpoch)committedEpoch=state.epoch,committedCount=0;if(replayAll)screen.requestClear(),committedCount=0,replayAll=!1;let commit=consoleLines.splice(0);for(let block of state.blocks.slice(committedCount))commit.push(...renderBlock(block,{width}));committedCount=state.blocks.length;let live=app.buildLive(width,rows),pinned=live.cursor!=null;if(pinned!==cursorPinned)cursorPinned=pinned,term.write(pinned?STEADY_BAR_CURSOR:DEFAULT_CURSOR);screen.draw(commit,live.lines,live.cursor,{width,rows})},invalidate=()=>{if(scheduled!=null||finished)return;let wait=Math.max(0,FRAME_INTERVAL_MS-(Date.now()-lastFrameAt));scheduled=setTimeout(draw,wait)},app=createTuiApp({continueSessionId:options.continueSessionId,startupAcp:options.acp,startupModel:options.model,startupEffort:options.effort,startupPermissionMode:options.permissionMode,startupInteractionMode:options.interactionMode},{size:()=>({columns:term.columns,rows:term.rows}),write:(text)=>term.write(text),clearScreen:()=>{screen.requestClear(),invalidate()},redrawAll:()=>{replayAll=!0,invalidate()},invalidate,exit:()=>resolveExit()});term.start({onInput:(event)=>app.handleInput(event),onResize:invalidate,onSignal:()=>app.requestExit()}),draw();try{if(await exited,scheduled!=null)clearTimeout(scheduled);draw(),finished=!0,term.write(`\r
2276
+ `)}finally{finished=!0,app.dispose(),term.restore();for(let name of CONSOLE_METHODS)console[name]=originalConsole[name]}let{fatalError,sessionId,sessionTokens,sessionCost}=useStore.getState();if(fatalError)return process19.stderr.write(`miro: ${errorMessage(fatalError)}
2277
+ `),1;let usageLine=formatSessionTokenUsage(sessionTokens,sessionCost);if(usageLine)process19.stdout.write(`
2334
2278
  ${source_default.dim(usageLine)}
2335
- `);if(sessionId)process29.stdout.write(`
2279
+ `);if(sessionId)process19.stdout.write(`
2336
2280
  ${source_default.dim(`Resume this session with:
2337
2281
  miro -c ${sessionId}`)}
2338
- `);return 0}var ENABLE_MODIFY_OTHER_KEYS="\x1B[>4;2m",DISABLE_MODIFY_OTHER_KEYS="\x1B[>4m";var init_tui=__esm(async()=>{init_source2();init_store();init_sync_stdout();init_term_caps();init_items7();init_react_jsx_runtime_production();await __promiseAll([init_build4(),init_App2()])});import{randomBytes}from"node:crypto";import{accessSync,statSync}from"node:fs";import{createServer}from"node:http";import{access,readFile,writeFile}from"node:fs/promises";import{delimiter,join}from"node:path";import{Readable}from"node:stream";function randomUUIDv7(){let bytes=randomBytes(16),timestamp=Date.now();for(let index=5;index>=0;index-=1)bytes[index]=timestamp&255,timestamp=Math.floor(timestamp/256);bytes[6]=bytes[6]&15|112,bytes[8]=bytes[8]&63|128;let hex=bytes.toString("hex");return`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}function file(path){return{name:String(path),async text(){return readFile(path,"utf8")},async json(){return JSON.parse(await readFile(path,"utf8"))},async bytes(){return new Uint8Array(await readFile(path))},async arrayBuffer(){let buffer=await readFile(path);return buffer.buffer.slice(buffer.byteOffset,buffer.byteOffset+buffer.byteLength)},async exists(){try{return await access(path),!0}catch{return!1}}}}async function write(destination,data){let body;if(ArrayBuffer.isView(data))body=new Uint8Array(data.buffer,data.byteOffset,data.byteLength);else if(data instanceof ArrayBuffer)body=new Uint8Array(data);else if(typeof data?.arrayBuffer==="function")body=new Uint8Array(await data.arrayBuffer());else body=data;return await writeFile(destination,body),typeof body==="string"?Buffer.byteLength(body,"utf8"):body.byteLength}function serve(options){let handler=options.fetch,server=createServer((request,response)=>{(async()=>{let host=request.headers.host??`${options.hostname??"127.0.0.1"}:${options.port??0}`,method=request.method??"GET",init={method,headers:request.headers};if(method!=="GET"&&method!=="HEAD")init.body=Readable.toWeb(request),init.duplex="half";let result=await handler(new Request(`http://${host}${request.url??"/"}`,init));if(response.writeHead(result.status,Object.fromEntries(result.headers)),!result.body){response.end();return}Readable.fromWeb(result.body).pipe(response)})().catch((error)=>{if(response.headersSent){response.destroy(error);return}response.writeHead(500,{"content-type":"text/plain"}),response.end(String(error?.message??error))})});return server.listen(options.port??0,options.hostname),{hostname:options.hostname,get port(){return server.address()?.port??options.port??0},async stop(){server.close(),server.closeAllConnections(),await new Promise((resolve)=>server.once("close",resolve))},unref(){return server.unref(),this}}}function which(command){for(let dir of String(process.env.PATH??"").split(delimiter)){if(!dir)continue;let target=join(dir,command);try{if(!statSync(target).isFile())continue;return accessSync(target,1),target}catch{}}return null}var runtime=globalThis;if(typeof runtime.Bun>"u"){await Promise.resolve().then(() => init_wrap_ansi());runtime.Bun={randomUUIDv7,file,write,serve,wrapAnsi,which}}import process30 from"node:process";init_permission_mode();var OUTPUT_FORMATS=new Set(["text","json"]);function readValue(args,index,flag){let value=args[index+1];if(!value||value.startsWith("-"))throw Error(`${flag} requires a value`);return value}function parseCliArgs(args){let options={mode:"interactive",prompt:null,continueSessionId:null,continueLatest:!1,outputFormat:"text",acp:null,model:null,effort:null,permissionMode:null,interactionMode:null,help:!1,version:!1},promptParts=[],optionsEnded=!1;for(let index=0;index<args.length;index+=1){let arg=args[index];if(optionsEnded){promptParts.push(arg);continue}if(arg==="--"){optionsEnded=!0;continue}if(arg==="-h"||arg==="--help"){options.help=!0;continue}if(arg==="-v"||arg==="--version"){options.version=!0;continue}if(arg==="-p"||arg==="--print"){options.mode="print";continue}if(arg==="-c"||arg==="--continue"){let value=args[index+1];if(!value||value.startsWith("-")){options.continueLatest=!0;continue}options.continueSessionId=value,index+=1;continue}if(arg==="--resume"){options.continueSessionId=readValue(args,index,arg),index+=1;continue}if(arg==="--output-format"){let value=readValue(args,index,arg);if(!OUTPUT_FORMATS.has(value))throw Error(`${arg} must be one of: ${[...OUTPUT_FORMATS].join(", ")}`);options.outputFormat=value,index+=1;continue}if(arg==="--acp"||arg==="--model"||arg==="--effort"){options[arg.slice(2)]=readValue(args,index,arg),index+=1;continue}if(arg==="--provider")throw Error("--provider has been removed; use --acp <provider-id>");if(arg==="--permission-mode"){let value=readValue(args,index,arg);if(!PERMISSION_MODES.includes(value))throw Error(`${arg} must be one of: ${PERMISSION_MODES.join(", ")}`);options.permissionMode=value,index+=1;continue}if(arg==="--mode"){let value=readValue(args,index,arg);if(value!=="default"&&value!=="plan")throw Error(`${arg} must be one of: default, plan`);options.interactionMode=value,index+=1;continue}if(arg.startsWith("-"))throw Error(`Unknown option: ${arg}`);promptParts.push(arg)}if(promptParts.length>0)options.prompt=promptParts.join(" ");if(options.mode!=="print"){if(options.prompt!=null)throw Error("A prompt requires --print");if(options.outputFormat!=="text")throw Error("--output-format options require --print")}return options}init_config();if(process30.argv[2]==="mcp")try{await Promise.resolve().then(() => init_mcp_command());process30.exitCode=await runMcpCommand(process30.argv.slice(3))}catch(error){process30.stderr.write(`miro mcp: ${errorMessage(error)}
2339
- `),process30.exitCode=1}else{let options;try{options=parseCliArgs(process30.argv.slice(2))}catch(error){process30.stderr.write(`miro: ${errorMessage(error)}
2282
+ `);return 0}var FRAME_INTERVAL_MS=16,CONSOLE_METHODS;var init_tui=__esm(()=>{init_source2();init_store();init_term_caps();init_items7();init_app();init_screen();init_terminal2();init_blocks();CONSOLE_METHODS=["log","info","warn","error","debug"]});import{randomBytes}from"node:crypto";import{accessSync,statSync}from"node:fs";import{createServer}from"node:http";import{access,readFile,writeFile}from"node:fs/promises";import{delimiter,join}from"node:path";import{Readable}from"node:stream";function randomUUIDv7(){let bytes=randomBytes(16),timestamp=Date.now();for(let index=5;index>=0;index-=1)bytes[index]=timestamp&255,timestamp=Math.floor(timestamp/256);bytes[6]=bytes[6]&15|112,bytes[8]=bytes[8]&63|128;let hex=bytes.toString("hex");return`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}function file(path){return{name:String(path),async text(){return readFile(path,"utf8")},async json(){return JSON.parse(await readFile(path,"utf8"))},async bytes(){return new Uint8Array(await readFile(path))},async arrayBuffer(){let buffer=await readFile(path);return buffer.buffer.slice(buffer.byteOffset,buffer.byteOffset+buffer.byteLength)},async exists(){try{return await access(path),!0}catch{return!1}}}}async function write(destination,data){let body;if(ArrayBuffer.isView(data))body=new Uint8Array(data.buffer,data.byteOffset,data.byteLength);else if(data instanceof ArrayBuffer)body=new Uint8Array(data);else if(typeof data?.arrayBuffer==="function")body=new Uint8Array(await data.arrayBuffer());else body=data;return await writeFile(destination,body),typeof body==="string"?Buffer.byteLength(body,"utf8"):body.byteLength}function serve(options){let handler=options.fetch,server=createServer((request,response)=>{(async()=>{let host=request.headers.host??`${options.hostname??"127.0.0.1"}:${options.port??0}`,method=request.method??"GET",init={method,headers:request.headers};if(method!=="GET"&&method!=="HEAD")init.body=Readable.toWeb(request),init.duplex="half";let result=await handler(new Request(`http://${host}${request.url??"/"}`,init));if(response.writeHead(result.status,Object.fromEntries(result.headers)),!result.body){response.end();return}Readable.fromWeb(result.body).pipe(response)})().catch((error)=>{if(response.headersSent){response.destroy(error);return}response.writeHead(500,{"content-type":"text/plain"}),response.end(String(error?.message??error))})});return server.listen(options.port??0,options.hostname),{hostname:options.hostname,get port(){return server.address()?.port??options.port??0},async stop(){server.close(),server.closeAllConnections(),await new Promise((resolve)=>server.once("close",resolve))},unref(){return server.unref(),this}}}function which(command){for(let dir of String(process.env.PATH??"").split(delimiter)){if(!dir)continue;let target=join(dir,command);try{if(!statSync(target).isFile())continue;return accessSync(target,1),target}catch{}}return null}var runtime=globalThis;if(typeof runtime.Bun>"u"){await Promise.resolve().then(() => init_wrap_ansi());runtime.Bun={randomUUIDv7,file,write,serve,wrapAnsi,which}}import process20 from"node:process";init_permission_mode();var OUTPUT_FORMATS=new Set(["text","json"]);function readValue(args,index,flag){let value=args[index+1];if(!value||value.startsWith("-"))throw Error(`${flag} requires a value`);return value}function parseCliArgs(args){let options={mode:"interactive",prompt:null,continueSessionId:null,continueLatest:!1,outputFormat:"text",acp:null,model:null,effort:null,permissionMode:null,interactionMode:null,help:!1,version:!1},promptParts=[],optionsEnded=!1;for(let index=0;index<args.length;index+=1){let arg=args[index];if(optionsEnded){promptParts.push(arg);continue}if(arg==="--"){optionsEnded=!0;continue}if(arg==="-h"||arg==="--help"){options.help=!0;continue}if(arg==="-v"||arg==="--version"){options.version=!0;continue}if(arg==="-p"||arg==="--print"){options.mode="print";continue}if(arg==="-c"||arg==="--continue"){let value=args[index+1];if(!value||value.startsWith("-")){options.continueLatest=!0;continue}options.continueSessionId=value,index+=1;continue}if(arg==="--resume"){options.continueSessionId=readValue(args,index,arg),index+=1;continue}if(arg==="--output-format"){let value=readValue(args,index,arg);if(!OUTPUT_FORMATS.has(value))throw Error(`${arg} must be one of: ${[...OUTPUT_FORMATS].join(", ")}`);options.outputFormat=value,index+=1;continue}if(arg==="--acp"||arg==="--model"||arg==="--effort"){options[arg.slice(2)]=readValue(args,index,arg),index+=1;continue}if(arg==="--provider")throw Error("--provider has been removed; use --acp <provider-id>");if(arg==="--permission-mode"){let value=readValue(args,index,arg);if(!PERMISSION_MODES.includes(value))throw Error(`${arg} must be one of: ${PERMISSION_MODES.join(", ")}`);options.permissionMode=value,index+=1;continue}if(arg==="--mode"){let value=readValue(args,index,arg);if(value!=="default"&&value!=="plan")throw Error(`${arg} must be one of: default, plan`);options.interactionMode=value,index+=1;continue}if(arg.startsWith("-"))throw Error(`Unknown option: ${arg}`);promptParts.push(arg)}if(promptParts.length>0)options.prompt=promptParts.join(" ");if(options.mode!=="print"){if(options.prompt!=null)throw Error("A prompt requires --print");if(options.outputFormat!=="text")throw Error("--output-format options require --print")}return options}init_config();if(process20.argv[2]==="mcp")try{await Promise.resolve().then(() => init_mcp_command());process20.exitCode=await runMcpCommand(process20.argv.slice(3))}catch(error){process20.stderr.write(`miro mcp: ${errorMessage(error)}
2283
+ `),process20.exitCode=1}else{let options;try{options=parseCliArgs(process20.argv.slice(2))}catch(error){process20.stderr.write(`miro: ${errorMessage(error)}
2340
2284
  Use --help for usage.
2341
- `),process30.exit(1)}if(options.help)process30.stdout.write(HELP),process30.exit(0);if(options.version)process30.stdout.write(`${APP_VERSION}
2342
- `),process30.exit(0);if(options.continueLatest&&options.continueSessionId==null){await Promise.resolve().then(() => init_session_store());if(options.continueSessionId=latestSessionId(process30.cwd(),options.acp??"miro"),options.continueSessionId==null)process30.stderr.write(`miro: no saved sessions for this project to continue.
2343
- `),process30.exit(1)}if(options.mode==="print"){await Promise.resolve().then(() => init_headless());process30.exitCode=await runHeadless(options)}else{await init_tui();process30.exitCode=await runTui(options)}}
2285
+ `),process20.exit(1)}if(options.help)process20.stdout.write(HELP),process20.exit(0);if(options.version)process20.stdout.write(`${APP_VERSION}
2286
+ `),process20.exit(0);if(options.continueLatest&&options.continueSessionId==null){await Promise.resolve().then(() => init_session_store());if(options.continueSessionId=latestSessionId(process20.cwd(),options.acp??"miro"),options.continueSessionId==null)process20.stderr.write(`miro: no saved sessions for this project to continue.
2287
+ `),process20.exit(1)}if(options.mode==="print"){await Promise.resolve().then(() => init_headless());process20.exitCode=await runHeadless(options)}else{await Promise.resolve().then(() => init_tui());process20.exitCode=await runTui(options)}}