@quspect/qupai 0.7.7 → 0.7.11
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/bin/qupai.js +3 -1
- package/package.json +7 -7
- package/tui/qupai-tui.mjs +63 -60
package/tui/qupai-tui.mjs
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
1
|
// qupai's full-screen app (qupai-cli tui/); third-party licenses: THIRD-PARTY-NOTICES in this package.
|
|
2
|
-
import{spawnSync as
|
|
3
|
-
]`).replace("lheading",
|
|
2
|
+
import{execFile as ng,spawnSync as rg}from"node:child_process";function Cn(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ze=Cn();function bo(s){Ze=s}var Xe={exec:()=>null};function wt(s){let e=[];return t=>{let i=Math.max(0,Math.min(3,t-1)),n=e[i];return n||(n=s(i),e[i]=n),n}}function O(s,e=""){let t=typeof s=="string"?s:s.source,i={replace:(n,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(Z.caret,"$1"),t=t.replace(n,o),i},getRegex:()=>new RegExp(t,e)};return i}var jc=((s="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+s)}catch{return!1}})(),Z={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,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,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:s=>new RegExp(`^( {0,3}${s})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:wt(s=>new RegExp(`^ {0,${s}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:wt(s=>new RegExp(`^ {0,${s}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:wt(s=>new RegExp(`^ {0,${s}}(?:\`\`\`|~~~)`)),headingBeginRegex:wt(s=>new RegExp(`^ {0,${s}}#`)),htmlBeginRegex:wt(s=>new RegExp(`^ {0,${s}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:wt(s=>new RegExp(`^ {0,${s}}>`))},Gc=/^(?:[ \t]*(?:\n|$))+/,Qc=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Yc=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ii=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Xc=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,$n=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,yo=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,wo=O(yo).replace(/bull/g,$n).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(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Jc=O(yo).replace(/bull/g,$n).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(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),An=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Zc=/^[^\n]+/,Tn=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,eh=O(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Tn).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),th=O(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,$n).getRegex(),Yi="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",_n=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ih=O("^ {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[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",_n).replace("tag",Yi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),xo=s=>O(An).replace("hr",ii).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",s).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Yi).getRegex(),sh=xo(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),nh=xo(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),rh=O(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",nh).getRegex(),In={blockquote:rh,code:Qc,def:eh,fences:Yc,heading:Xc,hr:ii,html:ih,lheading:wo,list:th,newline:Gc,paragraph:sh,table:Xe,text:Zc},co=O("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ii).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Yi).getRegex(),oh={...In,lheading:Jc,table:co,paragraph:O(An).replace("hr",ii).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",co).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Yi).getRegex()},ah={...In,html:O(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",_n).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:Xe,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:O(An).replace("hr",ii).replace("heading",` *#{1,6} *[^
|
|
3
|
+
]`).replace("lheading",wo).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},lh=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ch=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,vo=/^( {2,}|\\)\n(?!\s*$)/,hh=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Re=/[\p{P}\p{S}]/u,vt=/[\s\p{P}\p{S}]/u,si=/[^\s\p{P}\p{S}]/u,uh=O(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,vt).getRegex(),dh=/[\p{Pi}\p{Ps}"']/u,ko=/(?!~)[\p{P}\p{S}]/u,ph=/(?!~)[\s\p{P}\p{S}]/u,fh=/(?:[^\s\p{P}\p{S}]|~)/u,mh=O(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",jc?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),So=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,gh=O(So,"u").replace(/punct/g,Re).getRegex(),bh=O(So,"u").replace(/punct/g,ko).getRegex(),yh=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,wh=O(yh,"u").replace(/openQuote/g,dh).replace(/punct/g,Re).getRegex(),Co="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",xh=O(Co,"gu").replace(/notPunctSpace/g,si).replace(/punctSpace/g,vt).replace(/punct/g,Re).getRegex(),vh=O(Co,"gu").replace(/notPunctSpace/g,fh).replace(/punctSpace/g,ph).replace(/punct/g,ko).getRegex(),kh="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",Sh=O(kh,"gu").replace(/notPunctSpace/g,si).replace(/punctSpace/g,vt).replace(/punct/g,Re).getRegex(),Ch=O("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,si).replace(/punctSpace/g,vt).replace(/punct/g,Re).getRegex(),$h="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",Ah=O($h,"gu").replace(/notPunctSpace/g,si).replace(/punctSpace/g,vt).replace(/punct/g,Re).getRegex(),Th=O(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Re).getRegex(),_h="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Ih=O(_h,"gu").replace(/notPunctSpace/g,si).replace(/punctSpace/g,vt).replace(/punct/g,Re).getRegex(),Ph=O(/\\(punct)/,"gu").replace(/punct/g,Re).getRegex(),Rh=O(/^<(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(),Mh=O(_n).replace("(?:-->|$)","-->").getRegex(),Eh=O("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Mh).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Gi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Lh=O(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Gi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),$o=O(/^!?\[(label)\]\[(ref)\]/).replace("label",Gi).replace("ref",Tn).getRegex(),Ao=O(/^!?\[(ref)\](?:\[\])?/).replace("ref",Tn).getRegex(),Oh=O("reflink|nolink(?!\\()","g").replace("reflink",$o).replace("nolink",Ao).getRegex(),ho=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Pn={_backpedal:Xe,anyPunctuation:Ph,autolink:Rh,blockSkip:mh,br:vo,code:ch,del:Xe,delLDelim:Xe,delRDelim:Xe,emStrongLDelim:gh,emStrongRDelimAst:xh,emStrongRDelimUnd:Ch,escape:lh,link:Lh,nolink:Ao,punctuation:uh,reflink:$o,reflinkSearch:Oh,tag:Eh,text:hh,url:Xe},qh={...Pn,emStrongLDelim:wh,emStrongRDelimAst:Sh,emStrongRDelimUnd:Ah,link:O(/^!?\[(label)\]\((.*?)\)/).replace("label",Gi).getRegex(),reflink:O(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Gi).getRegex()},vn={...Pn,emStrongRDelimAst:vh,emStrongLDelim:bh,delLDelim:Th,delRDelim:Ih,url:O(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",ho).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:O(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",ho).getRegex()},Dh={...vn,br:O(vo).replace("{2,}","*").getRegex(),text:O(vn.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ji={normal:In,gfm:oh,pedantic:ah},ei={normal:Pn,gfm:vn,breaks:Dh,pedantic:qh},Bh={"&":"&","<":"<",">":">",'"':""","'":"'"},uo=s=>Bh[s];function Ae(s,e){if(e){if(Z.escapeTest.test(s))return s.replace(Z.escapeReplace,uo)}else if(Z.escapeTestNoEncode.test(s))return s.replace(Z.escapeReplaceNoEncode,uo);return s}function po(s){try{s=encodeURI(s).replace(Z.percentDecode,"%")}catch{return null}return s}function fo(s,e){let t=s.replace(Z.findPipe,(r,o,a)=>{let l=!1,c=o;for(;--c>=0&&a[c]==="\\";)l=!l;return l?"|":" |"}),i=t.split(Z.splitPipe),n=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),e)if(i.length>e)i.splice(e);else for(;i.length<e;)i.push("");for(;n<i.length;n++)i[n]=i[n].trim().replace(Z.slashPipe,"|");return i}function Ue(s,e,t){let i=s.length;if(i===0)return"";let n=0;for(;n<i;){let r=s.charAt(i-n-1);if(r===e&&!t)n++;else if(r!==e&&t)n++;else break}return s.slice(0,i-n)}function mo(s){let e=s.split(`
|
|
4
4
|
`),t=e.length-1;for(;t>=0&&Z.blankLine.test(e[t]);)t--;return e.length-t<=2?s:e.slice(0,t+1).join(`
|
|
5
|
-
`)}function
|
|
5
|
+
`)}function Nh(s,e){if(s.indexOf(e[1])===-1)return-1;let t=0;for(let i=0;i<s.length;i++)if(s[i]==="\\")i++;else if(s[i]===e[0])t++;else if(s[i]===e[1]&&(t--,t<0))return i;return t>0?-2:-1}function Fh(s,e=0){let t=e,i="";for(let n of s)if(n===" "){let r=4-t%4;i+=" ".repeat(r),t+=r}else i+=n,t++;return i}function go(s,e,t,i,n){let r=e.href,o=e.title||null,a=s[1].replace(n.other.outputLinkReplace,"$1"),l=s[0].charAt(0)==="!";i.state.inLink=!0;let c=i.state.linkEmitted,h=i.state.inRawBlock;i.state.linkEmitted=!1;let u=i.inlineTokens(a),d=i.state.linkEmitted;if(i.state.linkEmitted=c,i.state.inLink=!1,!l){if(d){i.state.inRawBlock=h;return}i.state.linkEmitted=!0}return{type:l?"image":"link",raw:t,href:r,title:o,text:a,tokens:u}}function Wh(s,e,t){let i=s.match(t.other.indentCodeCompensation);if(i===null)return e;let n=i[1];return e.split(`
|
|
6
6
|
`).map(r=>{let o=r.match(t.other.beginningSpace);if(o===null)return r;let[a]=o;return a.length>=n.length?r.slice(n.length):r}).join(`
|
|
7
|
-
`)}var xt=class{options;rules;lexer;constructor(s){this.options=s||Ze}space(s){let e=this.rules.block.newline.exec(s);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(s){let e=this.rules.block.code.exec(s);if(e){let t=this.options.pedantic?e[0]:
|
|
8
|
-
`),depth:e[1].length,text:t,tokens:this.lexer.inline(t)}}}hr(s){let e=this.rules.block.hr.exec(s);if(e)return{type:"hr",raw:
|
|
9
|
-
`)}}blockquote(s){let e=this.rules.block.blockquote.exec(s);if(e){let t=
|
|
7
|
+
`)}var xt=class{options;rules;lexer;constructor(s){this.options=s||Ze}space(s){let e=this.rules.block.newline.exec(s);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(s){let e=this.rules.block.code.exec(s);if(e){let t=this.options.pedantic?e[0]:mo(e[0]),i=t.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t,codeBlockStyle:"indented",text:i}}}fences(s){let e=this.rules.block.fences.exec(s);if(e){let t=e[0],i=Wh(t,e[3]||"",this.rules);return{type:"code",raw:t,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:i}}}heading(s){let e=this.rules.block.heading.exec(s);if(e){let t=e[2].trim();if(this.rules.other.endingHash.test(t)){let i=Ue(t,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(t=i.trim())}return{type:"heading",raw:Ue(e[0],`
|
|
8
|
+
`),depth:e[1].length,text:t,tokens:this.lexer.inline(t)}}}hr(s){let e=this.rules.block.hr.exec(s);if(e)return{type:"hr",raw:Ue(e[0],`
|
|
9
|
+
`)}}blockquote(s){let e=this.rules.block.blockquote.exec(s);if(e){let t=Ue(e[0],`
|
|
10
10
|
`).split(`
|
|
11
11
|
`),i="",n="",r=[];for(;t.length>0;){let o=!1,a=[],l;for(l=0;l<t.length;l++)if(this.rules.other.blockquoteStart.test(t[l]))a.push(t[l]),o=!0;else if(!o)a.push(t[l]);else break;t=t.slice(l);let c=a.join(`
|
|
12
12
|
`),h=c.replace(this.rules.other.blockquoteSetextReplace,`
|
|
13
13
|
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
|
|
14
14
|
${c}`:c,n=n?`${n}
|
|
15
15
|
${h}`:h;let u=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(h,r,!0),this.lexer.state.top=u,t.length===0)break;let d=r.at(-1);if(d?.type==="code")break;if(d?.type==="blockquote"){let p=d,f=t.join(`
|
|
16
|
-
`),
|
|
17
|
-
`+f.replace(this.rules.other.blockquoteSetextReplace2,""),b=this.blockquote(
|
|
16
|
+
`),m=p.raw+`
|
|
17
|
+
`+f.replace(this.rules.other.blockquoteSetextReplace2,""),b=this.blockquote(m);r[r.length-1]=b,i=`${i}
|
|
18
18
|
${f}`,n=n.substring(0,n.length-p.text.length)+b.text;break}else if(d?.type==="list"){let p=d,f=p.raw+`
|
|
19
19
|
`+t.join(`
|
|
20
|
-
`),
|
|
21
|
-
`);continue}}return{type:"blockquote",raw:i,tokens:r,text:n}}}list(s){let e=this.rules.block.list.exec(s);if(e){let t=e[1].trim(),i=t.length>1,n={type:"list",raw:"",ordered:i,start:i?+t.slice(0,-1):"",loose:!1,items:[]};t=i?`\\d{1,9}\\${t.slice(-1)}`:`\\${t}`,this.options.pedantic&&(t=i?t:"[*+-]");let r=this.rules.other.listItemRegex(t),o=!1;for(;s;){let l=!1,c="",h="";if(!(e=r.exec(s))||this.rules.block.hr.test(s))break;c=e[0],s=s.substring(c.length);let u=
|
|
20
|
+
`),m=this.list(f);r[r.length-1]=m,i=i.substring(0,i.length-d.raw.length)+m.raw,n=n.substring(0,n.length-p.raw.length)+m.raw,t=f.substring(r.at(-1).raw.length).split(`
|
|
21
|
+
`);continue}}return{type:"blockquote",raw:i,tokens:r,text:n}}}list(s){let e=this.rules.block.list.exec(s);if(e){let t=e[1].trim(),i=t.length>1,n={type:"list",raw:"",ordered:i,start:i?+t.slice(0,-1):"",loose:!1,items:[]};t=i?`\\d{1,9}\\${t.slice(-1)}`:`\\${t}`,this.options.pedantic&&(t=i?t:"[*+-]");let r=this.rules.other.listItemRegex(t),o=!1;for(;s;){let l=!1,c="",h="";if(!(e=r.exec(s))||this.rules.block.hr.test(s))break;c=e[0],s=s.substring(c.length);let u=Fh(e[2].split(`
|
|
22
22
|
`,1)[0],e[1].length),d=s.split(`
|
|
23
23
|
`,1)[0],p=!u.trim(),f=0;if(this.options.pedantic?(f=2,h=u.trimStart()):p?f=e[1].length+1:(f=u.search(this.rules.other.nonSpaceChar),f=f>4?1:f,h=u.slice(f),f+=e[1].length),p&&this.rules.other.blankLine.test(d)&&(c+=d+`
|
|
24
|
-
`,s=s.substring(d.length+1),l=!0),!l){let
|
|
25
|
-
`,1)[0],v;if(d=
|
|
26
|
-
`+v.slice(f);else{if(p||u.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||
|
|
27
|
-
`+d}p=!d.trim(),c+=
|
|
28
|
-
`,s=s.substring(
|
|
29
|
-
`),href:i,title:n}}}table(s){let e=this.rules.block.table.exec(s);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let t=
|
|
30
|
-
`):[],r={type:"table",raw:
|
|
31
|
-
`),header:[],align:[],rows:[]};if(t.length===i.length){for(let o of i)this.rules.other.tableAlignRight.test(o)?r.align.push("right"):this.rules.other.tableAlignCenter.test(o)?r.align.push("center"):this.rules.other.tableAlignLeft.test(o)?r.align.push("left"):r.align.push(null);for(let o=0;o<t.length;o++)r.header.push({text:t[o],tokens:this.lexer.inline(t[o]),header:!0,align:r.align[o]});for(let o of n)r.rows.push(
|
|
24
|
+
`,s=s.substring(d.length+1),l=!0),!l){let m=this.rules.other.nextBulletRegex(f),b=this.rules.other.hrRegex(f),g=this.rules.other.fencesBeginRegex(f),y=this.rules.other.headingBeginRegex(f),w=this.rules.other.htmlBeginRegex(f),k=this.rules.other.blockquoteBeginRegex(f);for(;s;){let P=s.split(`
|
|
25
|
+
`,1)[0],v;if(d=P,this.options.pedantic?(d=d.replace(this.rules.other.listReplaceNesting," "),v=d):v=d.replace(this.rules.other.tabCharGlobal," "),g.test(d)||y.test(d)||w.test(d)||k.test(d)||m.test(d)||b.test(d))break;if(v.search(this.rules.other.nonSpaceChar)>=f||!d.trim())h+=`
|
|
26
|
+
`+v.slice(f);else{if(p||u.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||g.test(u)||y.test(u)||b.test(u))break;h+=`
|
|
27
|
+
`+d}p=!d.trim(),c+=P+`
|
|
28
|
+
`,s=s.substring(P.length+1),u=v.slice(f)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0)),n.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(h),loose:!1,text:h,tokens:[]}),n.raw+=c}let a=n.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let l of n.items)if(this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]),!n.loose){let c=l.tokens.filter(u=>u.type==="space"),h=c.length>0&&c.some(u=>this.rules.other.anyLine.test(u.raw));n.loose=h}for(let l of n.items){let c=l.tokens[0];if(l.task&&(c?.type==="text"||c?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let u=this.lexer.inlineQueue.length-1;u>=0;u--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[u].src)){this.lexer.inlineQueue[u].src=this.lexer.inlineQueue[u].src.replace(this.rules.other.listReplaceTask,"");break}let h=this.rules.other.listTaskCheckbox.exec(l.raw);if(h){let u={type:"checkbox",raw:h[0]+" ",checked:h[0]!=="[ ]"};l.checked=u.checked,n.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=u.raw+l.tokens[0].raw,l.tokens[0].text=u.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(u)):l.tokens.unshift({type:"paragraph",raw:u.raw,text:u.raw,tokens:[u]}):l.tokens.unshift(u)}}else l.task&&(l.task=!1)}if(n.loose)for(let l of n.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return n}}html(s){let e=this.rules.block.html.exec(s);if(e){let t=mo(e[0]);return{type:"html",block:!0,raw:t,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:t}}}def(s){let e=this.rules.block.def.exec(s);if(e){let t=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",n=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:t,raw:Ue(e[0],`
|
|
29
|
+
`),href:i,title:n}}}table(s){let e=this.rules.block.table.exec(s);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let t=fo(e[1]),i=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
30
|
+
`):[],r={type:"table",raw:Ue(e[0],`
|
|
31
|
+
`),header:[],align:[],rows:[]};if(t.length===i.length){for(let o of i)this.rules.other.tableAlignRight.test(o)?r.align.push("right"):this.rules.other.tableAlignCenter.test(o)?r.align.push("center"):this.rules.other.tableAlignLeft.test(o)?r.align.push("left"):r.align.push(null);for(let o=0;o<t.length;o++)r.header.push({text:t[o],tokens:this.lexer.inline(t[o]),header:!0,align:r.align[o]});for(let o of n)r.rows.push(fo(o,r.header.length).map((a,l)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[l]})));return r}}lheading(s){let e=this.rules.block.lheading.exec(s);if(e){let t=e[1].trim();return{type:"heading",raw:Ue(e[0],`
|
|
32
32
|
`),depth:e[2].charAt(0)==="="?1:2,text:t,tokens:this.lexer.inline(t)}}}paragraph(s){let e=this.rules.block.paragraph.exec(s);if(e){let t=e[1].charAt(e[1].length-1)===`
|
|
33
|
-
`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:t,tokens:this.lexer.inline(t)}}}text(s){let e=this.rules.block.text.exec(s);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(s){let e=this.rules.inline.escape.exec(s);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(s){let e=this.rules.inline.tag.exec(s);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(s){let e=this.rules.inline.link.exec(s);if(e){let t=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(t)){if(!this.rules.other.endAngleBracket.test(t))return;let r=
|
|
33
|
+
`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:t,tokens:this.lexer.inline(t)}}}text(s){let e=this.rules.block.text.exec(s);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(s){let e=this.rules.inline.escape.exec(s);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(s){let e=this.rules.inline.tag.exec(s);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(s){let e=this.rules.inline.link.exec(s);if(e){let t=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(t)){if(!this.rules.other.endAngleBracket.test(t))return;let r=Ue(t.slice(0,-1),"\\");if((t.length-r.length)%2===0)return}else{let r=Nh(e[2],"()");if(r===-2)return;if(r>-1){let o=(e[0].indexOf("!")===0?5:4)+e[1].length+r;e[2]=e[2].substring(0,r),e[0]=e[0].substring(0,o).trim(),e[3]=""}}let i=e[2],n="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(i);r&&(i=r[1],n=r[3])}else n=e[3]?e[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(t)?i=i.slice(1):i=i.slice(1,-1)),go(e,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(s,e){let t;if((t=this.rules.inline.reflink.exec(s))||(t=this.rules.inline.nolink.exec(s))){let i=(t[2]||t[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=e[i.toLowerCase()];if(!n){let r=t[0].charAt(0);return{type:"text",raw:r,text:r}}return go(t,n,t[0],this.lexer,this.rules)}}emStrong(s,e,t=""){let i=this.rules.inline.emStrongLDelim.exec(s);if(!(!i||!i[1]&&!i[2]&&!i[3]&&!i[4]||i[4]&&t.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[3])||!t||this.rules.inline.punctuation.exec(t))){let n=[...i[0]].length-1,r,o,a=n,l=0,c=i[0][0],h=t===c,u=c==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(u.lastIndex=0,e=e.slice(-1*s.length+n);(i=u.exec(e))!==null;){if(r=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!r)continue;if(o=[...r].length,i[3]||i[4]){a+=o;continue}else if(i[5]||i[6]){if(n%3&&!((n+o)%3)){l+=o;continue}if(h)break}if(a-=o,a>0)continue;o=Math.min(o,o+a+l);let d=[...i[0]][0].length,p=s.slice(0,n+i.index+d+o);if(Math.min(n,o)%2){let m=p.slice(1,-1);return{type:"em",raw:p,text:m,tokens:this.lexer.inlineTokens(m)}}let f=p.slice(2,-2);return{type:"strong",raw:p,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(s){let e=this.rules.inline.code.exec(s);if(e){let t=e[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(t),n=this.rules.other.startingSpaceChar.test(t)&&this.rules.other.endingSpaceChar.test(t);return i&&n&&(t=t.substring(1,t.length-1)),{type:"codespan",raw:e[0],text:t}}}br(s){let e=this.rules.inline.br.exec(s);if(e)return{type:"br",raw:e[0]}}del(s,e,t=""){let i=this.rules.inline.delLDelim.exec(s);if(i&&(!i[1]||!t||this.rules.inline.punctuation.exec(t))){let n=[...i[0]].length-1,r,o,a=n,l=this.rules.inline.delRDelim;for(l.lastIndex=0,e=e.slice(-1*s.length+n);(i=l.exec(e))!==null;){if(r=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!r||(o=[...r].length,o!==n))continue;if(i[3]||i[4]){a+=o;continue}if(a-=o,a>0)continue;o=Math.min(o,o+a);let c=[...i[0]][0].length,h=s.slice(0,n+i.index+c+o),u=h.slice(n,-n);return{type:"del",raw:h,text:u,tokens:this.lexer.inlineTokens(u)}}}}autolink(s){let e=this.rules.inline.autolink.exec(s);if(e){let t,i;return e[2]==="@"?(t=e[1],i="mailto:"+t):(t=e[1],i=t),{type:"link",raw:e[0],text:t,href:i,tokens:[{type:"text",raw:t,text:t}]}}}url(s){let e;if(e=this.rules.inline.url.exec(s)){let t,i;if(e[2]==="@")t=e[0],i="mailto:"+t;else{let n;do n=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(n!==e[0]);t=e[0],e[1]==="www."?i="http://"+e[0]:i=e[0]}return{type:"link",raw:e[0],text:t,href:i,tokens:[{type:"text",raw:t,text:t}]}}}inlineText(s){let e=this.rules.inline.text.exec(s);if(e){let t=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:t}}}},Se=class kn{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Ze,this.options.tokenizer=this.options.tokenizer||new xt,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let t={other:Z,block:ji.normal,inline:ei.normal};this.options.pedantic?(t.block=ji.pedantic,t.inline=ei.pedantic):this.options.gfm&&(t.block=ji.gfm,this.options.breaks?t.inline=ei.breaks:t.inline=ei.gfm),this.tokenizer.rules=t}static get rules(){return{block:ji,inline:ei}}static lex(e,t){return new kn(t).lex(e)}static lexInline(e,t){return new kn(t).inlineTokens(e)}lex(e){e=e.replace(Z.carriageReturn,`
|
|
34
34
|
`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let i=this.inlineQueue[t];this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],i=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(Z.tabCharGlobal," ").replace(Z.spaceLine,""));let n=1/0;for(;e;){if(e.length<n)n=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(a=>(r=a.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let a=t.at(-1);r.raw.length===1&&a!==void 0?a.raw+=`
|
|
35
35
|
`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let a=t.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
36
36
|
`)?"":`
|
|
@@ -44,7 +44,7 @@ ${f}`,n=n.substring(0,n.length-p.text.length)+b.text;break}else if(d?.type==="li
|
|
|
44
44
|
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):t.push(r),i=o.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let a=t.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
45
45
|
`)?"":`
|
|
46
46
|
`)+r.raw,a.text+=`
|
|
47
|
-
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}linkInText(e){if(!e.includes("["))return!1;let t=this.tokenizer.rules.inline.link;for(let i of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(t.test(i[0])&&e.charAt(i.index-1)!=="!")return!0;for(let i of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let n=i[0],r=n.lastIndexOf("[");if(!(n.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,n.slice(r+1,-1)))&&!(r>1&&this.linkInText(n.slice(1,r-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let i=e;if(this.tokens.links&&e.includes("[")){let a=this.tokenizer.rules.inline.reflinkSearch,l=c=>{let h=c.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,c.slice(h+1,-1)))return c;if(h>1&&c.charAt(0)!=="!"){let u=c.slice(1,h-1);if(this.linkInText(u))return"["+u.replace(a,l)+"]["+"a".repeat(c.length-h-2)+"]"}return"["+"a".repeat(c.length-2)+"]"};i=i.replace(a,l)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,a=>"+".repeat(a.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(a,l,c)=>{let h=c?c.length:0;return a.slice(0,h)+"["+"a".repeat(a.length-h-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let n=!1,r="",o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}n||(r=""),n=!1;let a;if(this.options.extensions?.inline?.some(c=>(a=c.call({lexer:this},e,t))?(e=e.substring(a.raw.length),t.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let c=t.at(-1);a.type==="text"&&c?.type==="text"?(c.raw+=a.raw,c.text+=a.text):t.push(a);continue}if(a=this.tokenizer.emStrong(e,i,r)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.del(e,i,r)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),t.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),t.push(a);continue}let l=e;if(this.options.extensions?.startInline){let c=1/0,h=e.slice(1),u;this.options.extensions.startInline.forEach(d=>{u=d.call({lexer:this},h),typeof u=="number"&&u>=0&&(c=Math.min(c,u))}),c<1/0&&c>=0&&(l=e.substring(0,c+1))}if(a=this.tokenizer.inlineText(l)){e=e.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(r=a.raw.slice(-1)),n=!0;let c=t.at(-1);c?.type==="text"?(c.raw+=a.raw,c.text+=a.text):t.push(a);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}},
|
|
47
|
+
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}linkInText(e){if(!e.includes("["))return!1;let t=this.tokenizer.rules.inline.link;for(let i of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(t.test(i[0])&&e.charAt(i.index-1)!=="!")return!0;for(let i of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let n=i[0],r=n.lastIndexOf("[");if(!(n.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,n.slice(r+1,-1)))&&!(r>1&&this.linkInText(n.slice(1,r-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let i=e;if(this.tokens.links&&e.includes("[")){let a=this.tokenizer.rules.inline.reflinkSearch,l=c=>{let h=c.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,c.slice(h+1,-1)))return c;if(h>1&&c.charAt(0)!=="!"){let u=c.slice(1,h-1);if(this.linkInText(u))return"["+u.replace(a,l)+"]["+"a".repeat(c.length-h-2)+"]"}return"["+"a".repeat(c.length-2)+"]"};i=i.replace(a,l)}i=i.replace(this.tokenizer.rules.inline.anyPunctuation,a=>"+".repeat(a.length)),i=i.replace(this.tokenizer.rules.inline.blockSkip,(a,l,c)=>{let h=c?c.length:0;return a.slice(0,h)+"["+"a".repeat(a.length-h-2)+"]"}),i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let n=!1,r="",o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}n||(r=""),n=!1;let a;if(this.options.extensions?.inline?.some(c=>(a=c.call({lexer:this},e,t))?(e=e.substring(a.raw.length),t.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let c=t.at(-1);a.type==="text"&&c?.type==="text"?(c.raw+=a.raw,c.text+=a.text):t.push(a);continue}if(a=this.tokenizer.emStrong(e,i,r)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.del(e,i,r)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),t.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),t.push(a);continue}let l=e;if(this.options.extensions?.startInline){let c=1/0,h=e.slice(1),u;this.options.extensions.startInline.forEach(d=>{u=d.call({lexer:this},h),typeof u=="number"&&u>=0&&(c=Math.min(c,u))}),c<1/0&&c>=0&&(l=e.substring(0,c+1))}if(a=this.tokenizer.inlineText(l)){e=e.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(r=a.raw.slice(-1)),n=!0;let c=t.at(-1);c?.type==="text"?(c.raw+=a.raw,c.text+=a.text):t.push(a);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}},Qi=class{options;parser;constructor(s){this.options=s||Ze}space(s){return""}code({text:s,lang:e,escaped:t}){let i=(e||"").match(Z.notSpaceStart)?.[0],n=s.replace(Z.endingNewline,"")+`
|
|
48
48
|
`;return i?'<pre><code class="language-'+Ae(i)+'">'+(t?n:Ae(n,!0))+`</code></pre>
|
|
49
49
|
`:"<pre><code>"+(t?n:Ae(n,!0))+`</code></pre>
|
|
50
50
|
`}blockquote({tokens:s}){return`<blockquote>
|
|
@@ -62,12 +62,12 @@ ${this.parser.parse(s)}</blockquote>
|
|
|
62
62
|
`}tablerow({text:s}){return`<tr>
|
|
63
63
|
${s}</tr>
|
|
64
64
|
`}tablecell(s){let e=this.parser.parseInline(s.tokens),t=s.header?"th":"td";return(s.align?`<${t} align="${s.align}">`:`<${t}>`)+e+`</${t}>
|
|
65
|
-
`}strong({tokens:s}){return`<strong>${this.parser.parseInline(s)}</strong>`}em({tokens:s}){return`<em>${this.parser.parseInline(s)}</em>`}codespan({text:s}){return`<code>${Ae(s,!0)}</code>`}br(s){return"<br>"}del({tokens:s}){return`<del>${this.parser.parseInline(s)}</del>`}link({href:s,title:e,tokens:t}){let i=this.parser.parseInline(t),n=
|
|
66
|
-
Please report this to https://github.com/markedjs/marked.`,s){let i="<p>An error occurred:</p><pre>"+Ae(t.message+"",!0)+"</pre>";return e?Promise.resolve(i):i}if(e)return Promise.reject(t);throw t}}},Je=new Qi;function W(s,e){return Je.parse(s,e)}W.options=W.setOptions=function(s){return Je.setOptions(s),W.defaults=Je.defaults,fo(W.defaults),W};W.getDefaults=kn;W.defaults=Ze;function Dh(...s){return Je.use(...s),W.defaults=Je.defaults,fo(W.defaults),W}W.use=Dh;W.walkTokens=function(s,e){return Je.walkTokens(s,e)};W.parseInline=Je.parseInline;W.Parser=Ce;W.parser=Ce.parse;W.Renderer=ji;W.TextRenderer=In;W.Lexer=Se;W.lexer=Se.lex;W.Tokenizer=xt;W.Hooks=ei;W.parse=W;var eg=W.options,tg=W.setOptions,ig=W.walkTokens,sg=W.parseInline;var ng=Ce.parse,rg=Se.lex;var Co=[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],$o=12288,Ao=65510,To=[12288,12288,65281,65376,65504,65510];var _o=4352,Io=262141,Rn=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var Yi=(s,e)=>{let t=0,i=Math.floor(s.length/2)-1;for(;t<=i;){let n=Math.floor((t+i)/2),r=n*2;if(e<s[r])i=n-1;else if(e>s[r+1])t=n+1;else return!0}return!1};var Ro=19968,[Fh,Wh]=Kh(Rn);function Kh(s){let e=s[0],t=s[1];for(let i=0;i<s.length;i+=2){let n=s[i],r=s[i+1];if(Ro>=n&&Ro<=r)return[n,r];r-n>t-e&&(e=n,t=r)}return[e,t]}var Po=s=>s<161||s>1114109?!1:Yi(Co,s),Mo=s=>s<$o||s>Ao?!1:Yi(To,s);var Eo=s=>s>=Fh&&s<=Wh?!0:s<_o||s>Io?!1:Yi(Rn,s);function Uh(s){if(!Number.isSafeInteger(s))throw new TypeError(`Expected a code point, got \`${typeof s}\`.`)}function Pn(s,{ambiguousAsWide:e=!1}={}){return Uh(s),Mo(s)||Eo(s)||e&&Po(s)?2:1}var me=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Hh=new Intl.Segmenter(void 0,{granularity:"word"});function St(){return me}function Ct(){return Hh}function zh(s){let e=s.codePointAt(0);return e>=126976&&e<=130047||e>=8960&&e<=9215||e>=9728&&e<=10175||e>=11088&&e<=11093||s.includes("\uFE0F")||s.length>2}var Vh=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),jh=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),Gh=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})$","v"),Qh=new RegExp("^\\p{Mark}$","v"),Lo=new RegExp("^(?:[\\p{Spacing_Mark}--[\\u1734\\u302E\\u302F]]|[\\u065F\\u0F7F\\u102B\\u102C\\u1031\\u1033-\\u1035\\u1038\\u103A-\\u103E])+$","v"),Yh=new RegExp("^\\p{RGI_Emoji}$","v"),Xh=512,si=new Map,$t=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u,Ln=new RegExp(`(?:(?=\\p{Punctuation})${$t.source}|[\uFF0C\uFF0E\uFF1A\uFF1B\uFF01\uFF1F\uFF08\uFF09\uFF3B\uFF3D\uFF5B\uFF5D\u201C\u201D\u2018\u2019\u2026\u2014])`,"u"),Ji=new RegExp(`(?:\\s|${Ln.source})`,"u"),Zi=new RegExp(`(?:^|${Ji.source})`,"u");function On(s){for(let e=0;e<s.length;e++){let t=s.charCodeAt(e);if(t<32||t>126)return!1}return!0}function Jh(s,e){if(e<=0||s.length===0)return{text:"",width:0};if(On(s)){let l=s.slice(0,e);return{text:l,width:l.length}}let t=s.includes("\x1B"),i=s.includes(" ");if(!t&&!i){let l="",c=0;for(let{segment:h}of me.segment(s)){let u=Me(h);if(c+u>e)break;l+=h,c+=u}return{text:l,width:c}}let n="",r=0,o=0,a="";for(;o<s.length;){let l=U(s,o);if(l){a+=l.code,o+=l.length;continue}if(s[o]===" "){if(r+3>e)break;a&&(n+=a,a=""),n+=" ",r+=3,o++;continue}let c=o;for(;c<s.length&&s[c]!==" "&&!U(s,c);)c++;for(let{segment:h}of me.segment(s.slice(o,c))){let u=Me(h);if(r+u>e)return{text:n,width:r};a&&(n+=a,a=""),n+=h,r+=u}o=c}return{text:n,width:r}}function Mn(s,e,t,i,n,r){let o="\x1B[0m",a=ou(s),l=e+i,c;return t.length>0?c=`${s}${a}${o}${t}${o}`:c=`${s}${a}${o}`,r?c+" ".repeat(Math.max(0,n-l)):c}function Me(s){if(s.length===1){let o=s.charCodeAt(0);if(o>=32&&o<=126)return 1;if(o===9)return 3}if(Lo.test(s))return[...s].length;if(Vh.test(s))return 0;if(zh(s)&&Yh.test(s))return 2;let e=s.replace(jh,""),t=e.codePointAt(0);if(t===void 0)return 0;if(t>=127462&&t<=127487)return 2;let i=Pn(t),n=!1,r=[...e];for(let o of r.slice(1))if(Lo.test(o))i+=1,n=!1;else if(Qh.test(o))n=!0;else if(!Gh.test(o)){let a=o.codePointAt(0);n||a>=65280&&a<=65519?i+=Pn(a):(a===3635||a===3763)&&(i+=1),n=!1}return i}function x(s){if(s.length===0)return 0;let e=nu(s);if(e!==-1)return e;let t=si.get(s);if(t!==void 0)return t;let i=s;s.includes(" ")&&(i=i.replace(/\t/g," "));let n=i.indexOf("\x1B");if(n!==-1){let o="",a=0;for(;n!==-1;){let l=et(i,n);l>0?(o+=i.slice(a,n),n+=l,a=n):n++,n=i.indexOf("\x1B",n)}i=o+i.slice(a)}let r=0;for(let{segment:o}of me.segment(i))r+=Me(o);if(si.size>=Xh){let o=si.keys().next().value;o!==void 0&&si.delete(o)}return si.set(s,r),r}function At(s){if(!s.includes("\x1B"))return s;let e="",t=0;for(;t<s.length;){let i=U(s,t);if(i){t+=i.length;continue}e+=s[t],t++}return e}function Oo(s){let e="",t=s.indexOf("\x1B");for(;t!==-1;){let i=et(s,t);i>0?(e+=s.substring(t,t+i),t+=i):t++,t=s.indexOf("\x1B",t)}return e}var Zh=/\s/;function eu(s){let e=0;for(;e<s.length;){let t=s.charCodeAt(e);if(t===27){let i=et(s,e);if(i===0)return!1;e+=i}else if(t===32||t>=9&&t<=13)e++;else{if(t<128||!Zh.test(s[e]))return!1;e++}}return!0}var tu=/[\u0000-\u001f\u007f-\u009f]+/g;function ni(s){return s.replace(tu," ")}function ri(s,e){let t=0,i=0;for(;i<s.length;){let n=U(s,i);if(n){i+=n.length;continue}let r=i;for(;r<s.length&&!U(s,r);)r++;for(let{segment:o}of me.segment(s.slice(i,r))){let a=Me(o);if(a>0&&e>=t&&e<t+a)return{start:t,end:t+a};t+=a}i=r}}function qn(s,e){let t,i=0,n=0;for(;n<s.length;){let r=U(s,n);if(r){let a=/^\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)$/.exec(r.code);a&&(t=a[1]||void 0),n+=r.length;continue}let o=n;for(;o<s.length&&!U(s,o);)o++;for(let{segment:a}of me.segment(s.slice(n,o))){let l=a===" "?3:Me(a);if(e>=i&&e<i+l)return t;i+=l}n=o}}var iu=/[\u0e33\u0eb3]/,su=/[\u0e33\u0eb3]/g;function qo(s){let e=s;if(iu.test(e)&&(e=e.replace(su,n=>n==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2")),!e.includes(" "))return e;let t="",i=0;for(;i<e.length;){let n=U(e,i);if(n){t+=n.code,i+=n.length;continue}t+=e[i]===" "?" ":e[i],i++}return t}function U(s,e){let t=et(s,e);return t>0?{code:s.substring(e,e+t),length:t}:null}function nu(s){let e=0,t=0;for(;t<s.length;){let i=s.charCodeAt(t);if(i>=32&&i<=126)e++,t++;else if(i===9)e+=3,t++;else if(i===27){let n=et(s,t);if(n===0)return-1;t+=n}else return-1}return e}function et(s,e){if(e>=s.length||s.charCodeAt(e)!==27)return 0;let t=s[e+1];if(t==="["){for(let i=e+2;i<s.length;i++){let n=s.charCodeAt(i);if(n===109||n===71||n===75||n===72||n===74)return i+1-e}return 0}if(t==="]"||t==="_"){for(let i=e+2;i<s.length;i++){let n=s.charCodeAt(i);if(n===7)return i+1-e;if(n===27&&s[i+1]==="\\")return i+2-e}return 0}return 0}function Do(s){if(!s.startsWith("\x1B]8;"))return;let e=s.endsWith("\x07")?"\x07":"\x1B\\",t=s.slice(4,e==="\x07"?-1:-2),i=t.indexOf(";");if(i===-1)return;let n=t.slice(0,i),r=t.slice(i+1);return r?{params:n,url:r,terminator:e}:null}function ru(s){return`\x1B]8;${s.params};${s.url}${s.terminator}`}function Bo(s){return`\x1B]8;;${s}`}function ou(s){if(!s.includes("\x1B]8;"))return"";let e=null,t=0;for(;t<s.length;){let i=U(s,t);if(i){let n=Do(i.code);n!==void 0&&(e=n),t+=i.length}else t++}return e?Bo(e.terminator):""}var kt=class{bold=!1;dim=!1;italic=!1;underline=!1;blink=!1;inverse=!1;hidden=!1;strikethrough=!1;fgColor=null;bgColor=null;activeHyperlink=null;process(e){let t=Do(e);if(t!==void 0){this.activeHyperlink=t;return}if(!e.endsWith("m"))return;let i=e.match(/\x1b\[([\d;]*)m/);if(!i)return;let n=i[1];if(n===""||n==="0"){this.reset();return}let r=n.split(";"),o=0;for(;o<r.length;){let a=Number.parseInt(r[o],10);if(a===38||a===48){if(r[o+1]==="5"&&r[o+2]!==void 0){let l=`${r[o]};${r[o+1]};${r[o+2]}`;a===38?this.fgColor=l:this.bgColor=l,o+=3;continue}else if(r[o+1]==="2"&&r[o+4]!==void 0){let l=`${r[o]};${r[o+1]};${r[o+2]};${r[o+3]};${r[o+4]}`;a===38?this.fgColor=l:this.bgColor=l,o+=5;continue}}switch(a){case 0:this.reset();break;case 1:this.bold=!0;break;case 2:this.dim=!0;break;case 3:this.italic=!0;break;case 4:this.underline=!0;break;case 5:this.blink=!0;break;case 7:this.inverse=!0;break;case 8:this.hidden=!0;break;case 9:this.strikethrough=!0;break;case 21:this.bold=!1;break;case 22:this.bold=!1,this.dim=!1;break;case 23:this.italic=!1;break;case 24:this.underline=!1;break;case 25:this.blink=!1;break;case 27:this.inverse=!1;break;case 28:this.hidden=!1;break;case 29:this.strikethrough=!1;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:a>=30&&a<=37||a>=90&&a<=97?this.fgColor=String(a):(a>=40&&a<=47||a>=100&&a<=107)&&(this.bgColor=String(a));break}o++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let e=[];this.bold&&e.push("1"),this.dim&&e.push("2"),this.italic&&e.push("3"),this.underline&&e.push("4"),this.blink&&e.push("5"),this.inverse&&e.push("7"),this.hidden&&e.push("8"),this.strikethrough&&e.push("9"),this.fgColor&&e.push(this.fgColor),this.bgColor&&e.push(this.bgColor);let t=e.length>0?`\x1B[${e.join(";")}m`:"";return this.activeHyperlink&&(t+=ru(this.activeHyperlink)),t}getActiveBackgroundCode(){return this.bgColor?`\x1B[${this.bgColor}m`:""}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let e="";return this.underline&&(e+="\x1B[24m"),this.strikethrough&&(e+="\x1B[29m"),this.activeHyperlink&&(e+=Bo(this.activeHyperlink.terminator)),e}};function Xi(s,e){let t=s.indexOf("\x1B");for(;t!==-1;){let i=et(s,t);i>0?(e.process(s.substring(t,t+i)),t+=i):t++,t=s.indexOf("\x1B",t)}}function No(s){let e=new kt;return Xi(s,e),e.getActiveBackgroundCode()}function*au(s){for(let{segment:e}of me.segment(s))yield e}function lu(s){let e=[],t="",i="",n=null,r=0,o=()=>{t&&(e.push(t),t="",n=null)};for(;r<s.length;){let a=U(s,r);if(a){i+=a.code,r+=a.length;continue}let l=s.indexOf("\x1B",r+1);for(;l!==-1&&et(s,l)===0;)l=s.indexOf("\x1B",l+1);l===-1&&(l=s.length);let c=s.slice(r,l),h=On(c);for(let u of h?c:au(c)){let d=u===" ";if(!h&&!d&&$t.test(u)){o();let f=i+u;i="",e.push(f);continue}let p=d?"space":"word";t&&n!==p&&o(),i&&(t+=i,i=""),n=p,t+=u}r=l}return i&&(t?t+=i:e.length>0?e[e.length-1]+=i:t=i),t&&e.push(t),e}function Tt(s){for(let e of s)Number(e)}function ge(s,e){if(!s)return[""];let t=s.split(/\r\n|\r|\n/),i=[],n=new kt;for(let r of t){let o=i.length>0?n.getActiveCodes():"",a=cu(o+r,e);for(let l of a)i.push(l);Xi(r,n)}return i.length>0?i:[""]}function cu(s,e){if(!s)return[""];if(x(s)<=e)return[s];let i=[],n=new kt,r=lu(s),o="",a=0;for(let l of r){let c=x(l),h=eu(l);if(c>e&&!h){if(o){o=o.trimEnd();let p=n.getLineEndReset();p&&(o+=p),i.push(o),o="",a=0}let d=hu(l,e,n);for(let p=0;p<d.length-1;p++)i.push(d[p]);o=d[d.length-1],a=x(o);continue}let u=a+c;if(u>e&&a>0){let d=o.trimEnd();h&&(d+=Oo(l),Xi(l,n));let p=n.getLineEndReset();if(p&&(d+=p),i.push(d),h){o=n.getActiveCodes(),a=0;continue}o=n.getActiveCodes()+l,a=c}else h&&u>e&&l.includes("\x1B")?o+=Oo(l):(o+=l,a+=c);Xi(l,n)}return o&&i.push(o),i.length>0?i.map(l=>l.trimEnd()):[""]}var Dn=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function ue(s){return/\s/.test(s)}function hu(s,e,t){let i=[],n=t.getActiveCodes(),r=0,o=0,a=[];for(;o<s.length;){let l=U(s,o);if(l)a.push({type:"ansi",value:l.code}),o+=l.length;else{let c=o;for(;c<s.length&&!U(s,c);)c++;let h=s.slice(o,c);for(let u of me.segment(h))a.push({type:"grapheme",value:u.segment});o=c}}for(let l of a){if(l.type==="ansi"){n+=l.value,t.process(l.value);continue}let c=l.value;if(!c)continue;let h=x(c);if(r+h>e){let u=t.getLineEndReset();u&&(n+=u),i.push(n),n=t.getActiveCodes(),r=0}n+=c,r+=h}return n&&i.push(n),i.length>0?i:[""]}function _t(s,e,t){let i=x(s),n=Math.max(0,e-i),r=" ".repeat(n),o=s+r;return t(o)}function _(s,e,t="...",i=!1){if(e<=0)return"";if(s.length===0)return i?" ".repeat(e):"";let n=x(t);if(n>=e){let g=x(s);if(g<=e)return i?s+" ".repeat(e-g):s;let b=Jh(t,e);return b.width===0?i?" ".repeat(e):"":Mn("",0,b.text,b.width,e,i)}if(On(s)){if(s.length<=e)return i?s+" ".repeat(e-s.length):s;let g=e-n;return Mn(s.slice(0,g),g,t,n,e,i)}let r=e-n,o="",a="",l=0,c=0,h=!0,u=!1,d=!1,p=s.includes("\x1B"),f=s.includes(" ");if(!p&&!f){for(let{segment:g}of me.segment(s)){let b=Me(g);if(h&&c+b<=r?(o+=g,c+=b):h=!1,l+=b,l>e){u=!0;break}}d=!u}else{let g=0;for(;g<s.length;){let b=U(s,g);if(b){a+=b.code,g+=b.length;continue}if(s[g]===" "){if(h&&c+3<=r?(a&&(o+=a,a=""),o+=" ",c+=3):(h=!1,a=""),l+=3,l>e){u=!0;break}g++;continue}let m=g;for(;m<s.length&&s[m]!==" "&&!U(s,m);)m++;for(let{segment:y}of me.segment(s.slice(g,m))){let w=Me(y);if(h&&c+w<=r?(a&&(o+=a,a=""),o+=y,c+=w):(h=!1,a=""),l+=w,l>e){u=!0;break}}if(u)break;g=m}d=g>=s.length}return!u&&d?i?s+" ".repeat(Math.max(0,e-l)):s:Mn(o,c,t,n,e,i)}function H(s,e,t,i=!1){return Bn(s,e,t,i).text}function Bn(s,e,t,i=!1){if(t<=0)return{text:"",width:0};let n=e+t,r="",o=0,a=0,l=0,c="";for(;l<s.length;){let h=U(s,l);if(h){a>=e&&a<n?(r+=c+h.code,c=""):a<e&&!h.code.startsWith("\x1B_")&&(c+=h.code),l+=h.length;continue}let u=l;for(;u<s.length&&!U(s,u);)u++;for(let{segment:d}of me.segment(s.slice(l,u))){let p=Me(d),f=a>=e&&a<n,g=!i||a+p<=n;if(f&&g&&(c&&(r+=c,c=""),r+=d,o+=p),a+=p,a>=n)break}if(l=u,a>=n)break}return{text:r,width:o}}var En=new kt;function Fo(s,e,t,i,n=!1){let r="",o=0,a="",l=0,c=0,h=0,u="",d=!1,p=t+i;for(En.clear();h<s.length;){let f=U(s,h);if(f){En.process(f.code),c<e?u+=f.code:c>=t&&c<p&&(d||f.code.startsWith("\x1B_"))&&(a+=f.code),h+=f.length;continue}let g=h;for(;g<s.length&&!U(s,g);)g++;for(let{segment:b}of me.segment(s.slice(h,g))){let m=Me(b);if(c<e&&c+m<=e?(u&&(r+=u,u=""),r+=b,o+=m):c>=t&&c<p&&(!n||c+m<=p)&&(d||(a+=En.getActiveCodes(),d=!0),a+=b,l+=m),c+=m,i<=0?c>=e:c>=p)break}if(h=g,i<=0?c>=e:c>=p)break}return{before:r,beforeWidth:o,after:a,afterWidth:l}}var Pg=new RegExp(`${Zi.source}$`,"u");var Ko=(s,[e,t,i])=>s.map(n=>n[0]*e+n[1]*t+n[2]*i);var uu=[[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,-.0638541728258133],[1,-.0894841775298119,-1.2914855480194092]],du=[[4.076741636075958,-3.307711539258063,.2309699031821043],[-1.2684379732850315,2.609757349287688,-.341319376002657],[-.0041960761386756,-.7034186179359362,1.7076146940746117]];var pu=.206,fu=.03,Eg=(1+pu)/(1+fu);var mu=s=>s>.0031308?1.055*s**(1/2.4)-.055:12.92*s;function Uo(s){return Ko(du,Ko(uu,s).map(e=>e**3))}function Nn(s){let[e,t,i]=s.map(n=>Math.round(Math.min(1,Math.max(0,mu(n)))*255));return{r:e,g:t,b:i}}function gu(s,e){if(!Number.isFinite(s))throw new Error(`${e} must be finite`)}function Ue(s,e,t){for(let[i,n]of[["r",s],["g",e],["b",t]])if(gu(n,i),n<0||n>255)throw new Error(`${i} must be between 0 and 255: ${n}`);return Object.freeze({kind:"rgb",r:s,g:e,b:t})}var It=String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`,Ng=new RegExp(`^oklch\\(\\s*(${It})(%)?\\s+(${It})\\s+(${It})(?:deg)?\\s*\\)$`,"i"),Fg=new RegExp(`^okhsl\\(\\s*(${It})(?:deg)?\\s+(${It})(%)?\\s+(${It})(%)?\\s*\\)$`,"i");var bu=[{r:0,g:0,b:0},{r:128,g:0,b:0},{r:0,g:128,b:0},{r:128,g:128,b:0},{r:0,g:0,b:128},{r:128,g:0,b:128},{r:0,g:128,b:128},{r:192,g:192,b:192},{r:128,g:128,b:128},{r:255,g:0,b:0},{r:0,g:255,b:0},{r:255,g:255,b:0},{r:0,g:0,b:255},{r:255,g:0,b:255},{r:0,g:255,b:255},{r:255,g:255,b:255}],Ee=[0,95,135,175,215,255],Ho=Array.from({length:24},(s,e)=>8+e*10);function yu(s){if(s<16)return{...bu[s]};if(s<232){let t=s-16;return{r:Ee[Math.floor(t/36)],g:Ee[Math.floor(t%36/6)],b:Ee[t%6]}}let e=8+(s-232)*10;return{r:e,g:e,b:e}}function zo(s){return s.every(t=>t>=-1e-7&&t<=1+1e-7)}function wu({l:s,c:e,h:t}){let i=t*Math.PI/180,n=Math.cos(i),r=Math.sin(i),o=u=>Uo([s,u*n,u*r]),a=o(e);if(zo(a))return Nn(a);let l=o(0),c=0,h=e;for(let u=0;u<20;u++){let d=(c+h)/2,p=o(d);zo(p)?(c=d,l=p):h=d}return Nn(l)}function jo(s){switch(s.kind){case"indexed":return yu(s.index);case"rgb":return{r:s.r,g:s.g,b:s.b};case"oklch":return wu(s)}}function es(s,e){let t=0,i=1/0;for(let n=0;n<s.length;n++){let r=Math.abs(e-s[n]);r<i&&(t=n,i=r)}return t}function Vo(s,e){let t=s.r-e.r,i=s.g-e.g,n=s.b-e.b;return t*t*.299+i*i*.587+n*n*.114}function xu(s){let e=es(Ee,s.r),t=es(Ee,s.g),i=es(Ee,s.b),n={r:Ee[e],g:Ee[t],b:Ee[i]},r=16+36*e+6*t+i,o=Math.round(.299*s.r+.587*s.g+.114*s.b),a=es(Ho,o),l=Ho[a];return Math.max(s.r,s.g,s.b)-Math.min(s.r,s.g,s.b)<10&&Vo(s,{r:l,g:l,b:l})<Vo(s,n)?232+a:r}function Go(s,e,t){if(s.kind==="indexed")return`\x1B[${t?48:38};5;${s.index}m`;let i=jo(s);return e==="truecolor"?`\x1B[${t?48:38};2;${Math.round(i.r)};${Math.round(i.g)};${Math.round(i.b)}m`:`\x1B[${t?48:38};5;${xu(i)}m`}function Qo(s,e){return Go(s,e,!1)}function Yo(s,e){return Go(s,e,!0)}function Rt(s,e,t){return Xo(s,e.fg&&Qo(e.fg,t),e.bg&&Yo(e.bg,t),e)}function Xo(s,e,t,i){let n="",r="";return e&&(n+=e,r="\x1B[39m"),t&&(n+=t,r=`\x1B[49m${r}`),i.bold&&(n+="\x1B[1m"),i.dim&&(n+="\x1B[2m"),(i.bold||i.dim)&&(r=`\x1B[22m${r}`),i.italic&&(n+="\x1B[3m",r=`\x1B[23m${r}`),i.underline&&(n+="\x1B[4m",r=`\x1B[24m${r}`),i.inverse&&(n+="\x1B[7m",r=`\x1B[27m${r}`),i.strikethrough&&(n+="\x1B[9m",r=`\x1B[29m${r}`),`${n}${s}${r}`}import{performance as ds}from"node:perf_hooks";var Le=!1;function hi(s){Le=s}var T={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:s=>`ctrl+${s}`,shift:s=>`shift+${s}`,alt:s=>`alt+${s}`,super:s=>`super+${s}`,ctrlShift:s=>`ctrl+shift+${s}`,shiftCtrl:s=>`shift+ctrl+${s}`,ctrlAlt:s=>`ctrl+alt+${s}`,altCtrl:s=>`alt+ctrl+${s}`,shiftAlt:s=>`shift+alt+${s}`,altShift:s=>`alt+shift+${s}`,ctrlSuper:s=>`ctrl+super+${s}`,superCtrl:s=>`super+ctrl+${s}`,shiftSuper:s=>`shift+super+${s}`,superShift:s=>`super+shift+${s}`,altSuper:s=>`alt+super+${s}`,superAlt:s=>`super+alt+${s}`,ctrlShiftAlt:s=>`ctrl+shift+alt+${s}`,ctrlShiftSuper:s=>`ctrl+shift+super+${s}`},ts=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),vu=new Set("~!@#$%^&*()_+|{}:<>?"),ku=["shift","alt","ctrl","super"],C={shift:1,alt:2,ctrl:4,super:8},Pt=192,F={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},Y={up:-1,down:-2,right:-3,left:-4},P={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15,f1:-21,f2:-22,f3:-23,f4:-24,f5:-25,f6:-26,f7:-27,f8:-28,f9:-29,f10:-30,f11:-31,f12:-32},Su=57344,Cu=63743,$u=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,Y.left],[57418,Y.right],[57419,Y.up],[57420,Y.down],[57421,P.pageUp],[57422,P.pageDown],[57423,P.home],[57424,P.end],[57425,P.insert],[57426,P.delete]]);function ci(s){return $u.get(s)??s}function is(s,e){return(e&~Pt&C.shift)!==0&&s>=65&&s<=90?s+32:s}function ea(s,e,t){if(s===void 0||(e&C.shift)===0)return;let i=ci(s);if(t.has(String.fromCharCode(i)))return{codepoint:i,modifier:e&~C.shift}}var be={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},Au={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},Tu={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]};var oe=(s,e)=>e.includes(s),de=(s,e,t)=>t===C.shift?oe(s,Au[e]):t===C.ctrl?oe(s,Tu[e]):!1,oi="press";function ui(s){return s.includes("\x1B[200~")?!1:!!(s.includes(":3u")||s.includes(":3~")||s.includes(":3A")||s.includes(":3B")||s.includes(":3C")||s.includes(":3D")||s.includes(":3H")||s.includes(":3F")||s.includes(":3P")||s.includes(":3Q")||s.includes(":3S"))}function ai(s){if(!s)return"press";let e=parseInt(s,10);return e===2?"repeat":e===3?"release":"press"}function _u(s){let e=s.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(e){let o=parseInt(e[1],10),a=e[2]&&e[2].length>0?parseInt(e[2],10):void 0,l=e[3]?parseInt(e[3],10):void 0,c=e[4]?parseInt(e[4],10):1,h=ai(e[5]);return oi=h,{codepoint:o,shiftedKey:a,baseLayoutKey:l,modifier:c-1,eventType:h}}let t=s.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(t){let o=parseInt(t[1],10),a=ai(t[2]),l={A:-1,B:-2,C:-3,D:-4};return oi=a,{codepoint:l[t[3]],modifier:o-1,eventType:a}}let i=s.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(i){let o=parseInt(i[1],10),a=i[2]?parseInt(i[2],10):1,l=ai(i[3]),h={2:P.insert,3:P.delete,5:P.pageUp,6:P.pageDown,7:P.home,8:P.end,11:P.f1,12:P.f2,13:P.f3,14:P.f4,15:P.f5,17:P.f6,18:P.f7,19:P.f8,20:P.f9,21:P.f10,23:P.f11,24:P.f12}[o];if(h!==void 0)return oi=l,{codepoint:h,modifier:a-1,eventType:l}}let n=s.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(n){let o=parseInt(n[1],10),a=ai(n[2]),l=n[3]==="H"?P.home:P.end;return oi=a,{codepoint:l,modifier:o-1,eventType:a}}let r=s.match(/^\x1b\[(?:1;(\d+)(?::(\d+))?)?([PQS])$/);if(r){let o=r[1]?parseInt(r[1],10):1,a=ai(r[2]),l={P:P.f1,Q:P.f2,S:P.f4};return oi=a,{codepoint:l[r[3]],modifier:o-1,eventType:a}}return null}function I(s,e,t){let i=_u(s);if(!i)return!1;let n=i.modifier&~Pt,r=t&~Pt,o=is(ci(i.codepoint),i.modifier),a=is(ci(e),t);if(n===r&&o===a)return!0;let l=ea(i.shiftedKey,n,ts);if(l&&(l.modifier&~Pt)===r&&l.codepoint===ci(e))return!0;if(n!==r)return!1;if(i.baseLayoutKey!==void 0&&i.baseLayoutKey===e){let c=o,h=c>=97&&c<=122,u=ts.has(String.fromCharCode(c));if(!h&&!u)return!0}return!1}function Fn(s){let e=s.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!e)return null;let t=parseInt(e[1],10);return{codepoint:parseInt(e[2],10),modifier:t-1}}function ye(s,e,t){let i=Fn(s);return i?i.codepoint===e&&i.modifier===t:!1}function Iu(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function Jo(s,e){return s==="\x7F"?e===0:s!=="\b"?!1:Iu()?e===C.ctrl:e===0}function Ru(s){let e=s.toLowerCase(),t=e.charCodeAt(0);return t>=97&&t<=122||e==="["||e==="\\"||e==="]"||e==="_"?String.fromCharCode(t&31):e==="-"?"":null}function Zo(s){return s>="0"&&s<="9"}function li(s,e,t){let i=Fn(s);if(!i)return!1;if(i.modifier===t&&is(i.codepoint,i.modifier)===is(e,t))return!0;let r=ea(i.codepoint,i.modifier,vu);return r?.modifier===t&&r.codepoint===e}function Pu(s){let e=s.toLowerCase(),t=new Set;for(;;){let i=ku.find(n=>e.startsWith(`${n}+`));if(!i)break;if(t.has(i))return null;t.add(i),e=e.slice(i.length+1)}return!e||e.includes("+")&&e!=="+"?null:{key:e,ctrl:t.has("ctrl"),shift:t.has("shift"),alt:t.has("alt"),super:t.has("super")}}function S(s,e){let t=Pu(e);if(!t)return!1;let{key:i,ctrl:n,shift:r,alt:o,super:a}=t,l=0;switch(r&&(l|=C.shift),o&&(l|=C.alt),n&&(l|=C.ctrl),a&&(l|=C.super),i){case"escape":case"esc":return l!==0?!1:s==="\x1B"||I(s,F.escape,0)||ye(s,F.escape,0);case"space":return!Le&&(l===C.ctrl&&s==="\0"||l===C.alt&&s==="\x1B ")?!0:l===0?s===" "||I(s,F.space,0)||ye(s,F.space,0):I(s,F.space,l)||ye(s,F.space,l);case"tab":return l===C.shift?s==="\x1B[Z"||I(s,F.tab,C.shift)||ye(s,F.tab,C.shift):l===0?s===" "||I(s,F.tab,0):I(s,F.tab,l)||ye(s,F.tab,l);case"enter":case"return":return l===C.shift?I(s,F.enter,C.shift)||I(s,F.kpEnter,C.shift)||ye(s,F.enter,C.shift)?!0:Le?s==="\x1B\r"||s===`
|
|
65
|
+
`}strong({tokens:s}){return`<strong>${this.parser.parseInline(s)}</strong>`}em({tokens:s}){return`<em>${this.parser.parseInline(s)}</em>`}codespan({text:s}){return`<code>${Ae(s,!0)}</code>`}br(s){return"<br>"}del({tokens:s}){return`<del>${this.parser.parseInline(s)}</del>`}link({href:s,title:e,tokens:t}){let i=this.parser.parseInline(t),n=po(s);if(n===null)return i;s=n;let r='<a href="'+s+'"';return e&&(r+=' title="'+Ae(e)+'"'),r+=">"+i+"</a>",r}image({href:s,title:e,text:t,tokens:i}){i&&(t=this.parser.parseInline(i,this.parser.textRenderer));let n=po(s);if(n===null)return Ae(t);s=n;let r=`<img src="${s}" alt="${Ae(t)}"`;return e&&(r+=` title="${Ae(e)}"`),r+=">",r}text(s){return"tokens"in s&&s.tokens?this.parser.parseInline(s.tokens):"escaped"in s&&s.escaped?s.text:Ae(s.text)}},Rn=class{strong({text:s}){return s}em({text:s}){return s}codespan({text:s}){return s}del({text:s}){return s}html({text:s}){return s}text({text:s}){return s}link({text:s}){return""+s}image({text:s}){return""+s}br(){return""}checkbox({raw:s}){return s}},Ce=class Sn{options;renderer;textRenderer;constructor(e){this.options=e||Ze,this.options.renderer=this.options.renderer||new Qi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Rn}static parse(e,t){return new Sn(t).parse(e)}static parseInline(e,t){return new Sn(t).parseInline(e)}parse(e){this.renderer.parser=this;let t="";for(let i=0;i<e.length;i++){let n=e[i];if(this.options.extensions?.renderers?.[n.type]){let o=n,a=this.options.extensions.renderers[o.type].call({parser:this},o);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){t+=a||"";continue}}let r=n;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 new Error(o)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let i="";for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let a=this.options.extensions.renderers[r.type].call({parser:this},r);if(a!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(r.type)){i+=a||"";continue}}let o=r;switch(o.type){case"escape":{i+=t.text(o);break}case"html":{i+=t.html(o);break}case"link":{i+=t.link(o);break}case"image":{i+=t.image(o);break}case"checkbox":{i+=t.checkbox(o);break}case"strong":{i+=t.strong(o);break}case"em":{i+=t.em(o);break}case"codespan":{i+=t.codespan(o);break}case"br":{i+=t.br(o);break}case"del":{i+=t.del(o);break}case"text":{i+=t.text(o);break}default:{let a='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return i}},ti=class{options;block;constructor(s){this.options=s||Ze}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(s){return s}postprocess(s){return s}processAllTokens(s){return s}emStrongMask(s){return s}provideLexer(s=this.block){return s?Se.lex:Se.lexInline}provideParser(s=this.block){return s?Ce.parse:Ce.parseInline}},Xi=class{defaults=Cn();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ce;Renderer=Qi;TextRenderer=Rn;Lexer=Se;Tokenizer=xt;Hooks=ti;constructor(...s){this.use(...s)}walkTokens(s,e){let t=[];for(let i of s)switch(t=t.concat(e.call(this,i)),i.type){case"table":{let n=i;for(let r of n.header)t=t.concat(this.walkTokens(r.tokens,e));for(let r of n.rows)for(let o of r)t=t.concat(this.walkTokens(o.tokens,e));break}case"list":{let n=i;t=t.concat(this.walkTokens(n.items,e));break}default:{let n=i;this.defaults.extensions?.childTokens?.[n.type]?this.defaults.extensions.childTokens[n.type].forEach(r=>{let o=n[r].flat(1/0);t=t.concat(this.walkTokens(o,e))}):n.tokens&&(t=t.concat(this.walkTokens(n.tokens,e)))}}return t}use(...s){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return s.forEach(t=>{let i={...t};if(i.async=this.defaults.async||i.async||!1,t.extensions&&(t.extensions.forEach(n=>{if(!n.name)throw new Error("extension name required");if("renderer"in n){let r=e.renderers[n.name];r?e.renderers[n.name]=function(...o){let a=n.renderer.apply(this,o);return a===!1&&(a=r.apply(this,o)),a}:e.renderers[n.name]=n.renderer}if("tokenizer"in n){if(!n.level||n.level!=="block"&&n.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=e[n.level];r?r.unshift(n.tokenizer):e[n.level]=[n.tokenizer],n.start&&(n.level==="block"?e.startBlock?e.startBlock.push(n.start):e.startBlock=[n.start]:n.level==="inline"&&(e.startInline?e.startInline.push(n.start):e.startInline=[n.start]))}"childTokens"in n&&n.childTokens&&(e.childTokens[n.name]=n.childTokens)}),i.extensions=e),t.renderer){let n=this.defaults.renderer||new Qi(this.defaults);for(let r in t.renderer){if(!(r in n))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let o=r,a=t.renderer[o],l=n[o];n[o]=(...c)=>{let h=a.apply(n,c);return h===!1&&(h=l.apply(n,c)),h||""}}i.renderer=n}if(t.tokenizer){let n=this.defaults.tokenizer||new xt(this.defaults);for(let r in t.tokenizer){if(!(r in n))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let o=r,a=t.tokenizer[o],l=n[o];n[o]=(...c)=>{let h=a.apply(n,c);return h===!1&&(h=l.apply(n,c)),h}}i.tokenizer=n}if(t.hooks){let n=this.defaults.hooks||new ti;for(let r in t.hooks){if(!(r in n))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let o=r,a=t.hooks[o],l=n[o];ti.passThroughHooks.has(r)?n[o]=c=>{if(this.defaults.async&&ti.passThroughHooksRespectAsync.has(r))return(async()=>{let u=await a.call(n,c);return l.call(n,u)})();let h=a.call(n,c);return l.call(n,h)}:n[o]=(...c)=>{if(this.defaults.async)return(async()=>{let u=await a.apply(n,c);return u===!1&&(u=await l.apply(n,c)),u})();let h=a.apply(n,c);return h===!1&&(h=l.apply(n,c)),h}}i.hooks=n}if(t.walkTokens){let n=this.defaults.walkTokens,r=t.walkTokens;i.walkTokens=function(o){let a=[];return a.push(r.call(this,o)),n&&(a=a.concat(n.call(this,o))),a}}this.defaults={...this.defaults,...i}}),this}setOptions(s){return this.defaults={...this.defaults,...s},this}lexer(s,e){return Se.lex(s,e??this.defaults)}parser(s,e){return Ce.parse(s,e??this.defaults)}parseMarkdown(s){return(e,t)=>{let i={...t},n={...this.defaults,...i},r=this.onError(!!n.silent,!!n.async);if(this.defaults.async===!0&&i.async===!1)return r(new 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 e>"u"||e===null)return r(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(n.hooks&&(n.hooks.options=n,n.hooks.block=s),n.async)return(async()=>{let o=n.hooks?await n.hooks.preprocess(e):e,a=await(n.hooks?await n.hooks.provideLexer(s):s?Se.lex:Se.lexInline)(o,n),l=n.hooks?await n.hooks.processAllTokens(a):a;n.walkTokens&&await Promise.all(this.walkTokens(l,n.walkTokens));let c=await(n.hooks?await n.hooks.provideParser(s):s?Ce.parse:Ce.parseInline)(l,n);return n.hooks?await n.hooks.postprocess(c):c})().catch(r);try{n.hooks&&(e=n.hooks.preprocess(e));let o=(n.hooks?n.hooks.provideLexer(s):s?Se.lex:Se.lexInline)(e,n);n.hooks&&(o=n.hooks.processAllTokens(o)),n.walkTokens&&this.walkTokens(o,n.walkTokens);let a=(n.hooks?n.hooks.provideParser(s):s?Ce.parse:Ce.parseInline)(o,n);return n.hooks&&(a=n.hooks.postprocess(a)),a}catch(o){return r(o)}}}onError(s,e){return t=>{if(t.message+=`
|
|
66
|
+
Please report this to https://github.com/markedjs/marked.`,s){let i="<p>An error occurred:</p><pre>"+Ae(t.message+"",!0)+"</pre>";return e?Promise.resolve(i):i}if(e)return Promise.reject(t);throw t}}},Je=new Xi;function W(s,e){return Je.parse(s,e)}W.options=W.setOptions=function(s){return Je.setOptions(s),W.defaults=Je.defaults,bo(W.defaults),W};W.getDefaults=Cn;W.defaults=Ze;function Uh(...s){return Je.use(...s),W.defaults=Je.defaults,bo(W.defaults),W}W.use=Uh;W.walkTokens=function(s,e){return Je.walkTokens(s,e)};W.parseInline=Je.parseInline;W.Parser=Ce;W.parser=Ce.parse;W.Renderer=Qi;W.TextRenderer=Rn;W.Lexer=Se;W.lexer=Se.lex;W.Tokenizer=xt;W.Hooks=ti;W.parse=W;var hg=W.options,ug=W.setOptions,dg=W.walkTokens,pg=W.parseInline;var fg=Ce.parse,mg=Se.lex;var To=[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],_o=12288,Io=65510,Po=[12288,12288,65281,65376,65504,65510];var Ro=4352,Mo=262141,Mn=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var Ji=(s,e)=>{let t=0,i=Math.floor(s.length/2)-1;for(;t<=i;){let n=Math.floor((t+i)/2),r=n*2;if(e<s[r])i=n-1;else if(e>s[r+1])t=n+1;else return!0}return!1};var Eo=19968,[zh,Vh]=jh(Mn);function jh(s){let e=s[0],t=s[1];for(let i=0;i<s.length;i+=2){let n=s[i],r=s[i+1];if(Eo>=n&&Eo<=r)return[n,r];r-n>t-e&&(e=n,t=r)}return[e,t]}var Lo=s=>s<161||s>1114109?!1:Ji(To,s),Oo=s=>s<_o||s>Io?!1:Ji(Po,s);var qo=s=>s>=zh&&s<=Vh?!0:s<Ro||s>Mo?!1:Ji(Mn,s);function Gh(s){if(!Number.isSafeInteger(s))throw new TypeError(`Expected a code point, got \`${typeof s}\`.`)}function En(s,{ambiguousAsWide:e=!1}={}){return Gh(s),Oo(s)||qo(s)||e&&Lo(s)?2:1}var me=new Intl.Segmenter(void 0,{granularity:"grapheme"}),Qh=new Intl.Segmenter(void 0,{granularity:"word"});function St(){return me}function Ct(){return Qh}function Yh(s){let e=s.codePointAt(0);return e>=126976&&e<=130047||e>=8960&&e<=9215||e>=9728&&e<=10175||e>=11088&&e<=11093||s.includes("\uFE0F")||s.length>2}var Xh=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),Jh=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),Zh=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})$","v"),eu=new RegExp("^\\p{Mark}$","v"),Do=new RegExp("^(?:[\\p{Spacing_Mark}--[\\u1734\\u302E\\u302F]]|[\\u065F\\u0F7F\\u102B\\u102C\\u1031\\u1033-\\u1035\\u1038\\u103A-\\u103E])+$","v"),tu=new RegExp("^\\p{RGI_Emoji}$","v"),iu=512,ni=new Map,$t=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u,qn=new RegExp(`(?:(?=\\p{Punctuation})${$t.source}|[\uFF0C\uFF0E\uFF1A\uFF1B\uFF01\uFF1F\uFF08\uFF09\uFF3B\uFF3D\uFF5B\uFF5D\u201C\u201D\u2018\u2019\u2026\u2014])`,"u"),es=new RegExp(`(?:\\s|${qn.source})`,"u"),ts=new RegExp(`(?:^|${es.source})`,"u");function Dn(s){for(let e=0;e<s.length;e++){let t=s.charCodeAt(e);if(t<32||t>126)return!1}return!0}function su(s,e){if(e<=0||s.length===0)return{text:"",width:0};if(Dn(s)){let l=s.slice(0,e);return{text:l,width:l.length}}let t=s.includes("\x1B"),i=s.includes(" ");if(!t&&!i){let l="",c=0;for(let{segment:h}of me.segment(s)){let u=Me(h);if(c+u>e)break;l+=h,c+=u}return{text:l,width:c}}let n="",r=0,o=0,a="";for(;o<s.length;){let l=K(s,o);if(l){a+=l.code,o+=l.length;continue}if(s[o]===" "){if(r+3>e)break;a&&(n+=a,a=""),n+=" ",r+=3,o++;continue}let c=o;for(;c<s.length&&s[c]!==" "&&!K(s,c);)c++;for(let{segment:h}of me.segment(s.slice(o,c))){let u=Me(h);if(r+u>e)return{text:n,width:r};a&&(n+=a,a=""),n+=h,r+=u}o=c}return{text:n,width:r}}function Ln(s,e,t,i,n,r){let o="\x1B[0m",a=uu(s),l=e+i,c;return t.length>0?c=`${s}${a}${o}${t}${o}`:c=`${s}${a}${o}`,r?c+" ".repeat(Math.max(0,n-l)):c}function Me(s){if(s.length===1){let o=s.charCodeAt(0);if(o>=32&&o<=126)return 1;if(o===9)return 3}if(Do.test(s))return[...s].length;if(Xh.test(s))return 0;if(Yh(s)&&tu.test(s))return 2;let e=s.replace(Jh,""),t=e.codePointAt(0);if(t===void 0)return 0;if(t>=127462&&t<=127487)return 2;let i=En(t),n=!1,r=[...e];for(let o of r.slice(1))if(Do.test(o))i+=1,n=!1;else if(eu.test(o))n=!0;else if(!Zh.test(o)){let a=o.codePointAt(0);n||a>=65280&&a<=65519?i+=En(a):(a===3635||a===3763)&&(i+=1),n=!1}return i}function x(s){if(s.length===0)return 0;let e=cu(s);if(e!==-1)return e;let t=ni.get(s);if(t!==void 0)return t;let i=s;s.includes(" ")&&(i=i.replace(/\t/g," "));let n=i.indexOf("\x1B");if(n!==-1){let o="",a=0;for(;n!==-1;){let l=et(i,n);l>0?(o+=i.slice(a,n),n+=l,a=n):n++,n=i.indexOf("\x1B",n)}i=o+i.slice(a)}let r=0;for(let{segment:o}of me.segment(i))r+=Me(o);if(ni.size>=iu){let o=ni.keys().next().value;o!==void 0&&ni.delete(o)}return ni.set(s,r),r}function At(s){if(!s.includes("\x1B"))return s;let e="",t=0;for(;t<s.length;){let i=K(s,t);if(i){t+=i.length;continue}e+=s[t],t++}return e}function Bo(s){let e="",t=s.indexOf("\x1B");for(;t!==-1;){let i=et(s,t);i>0?(e+=s.substring(t,t+i),t+=i):t++,t=s.indexOf("\x1B",t)}return e}var nu=/\s/;function ru(s){let e=0;for(;e<s.length;){let t=s.charCodeAt(e);if(t===27){let i=et(s,e);if(i===0)return!1;e+=i}else if(t===32||t>=9&&t<=13)e++;else{if(t<128||!nu.test(s[e]))return!1;e++}}return!0}var ou=/[\u0000-\u001f\u007f-\u009f]+/g;function ri(s){return s.replace(ou," ")}function oi(s,e){let t=0,i=0;for(;i<s.length;){let n=K(s,i);if(n){i+=n.length;continue}let r=i;for(;r<s.length&&!K(s,r);)r++;for(let{segment:o}of me.segment(s.slice(i,r))){let a=Me(o);if(a>0&&e>=t&&e<t+a)return{start:t,end:t+a};t+=a}i=r}}function Bn(s,e){let t,i=0,n=0;for(;n<s.length;){let r=K(s,n);if(r){let a=/^\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)$/.exec(r.code);a&&(t=a[1]||void 0),n+=r.length;continue}let o=n;for(;o<s.length&&!K(s,o);)o++;for(let{segment:a}of me.segment(s.slice(n,o))){let l=a===" "?3:Me(a);if(e>=i&&e<i+l)return t;i+=l}n=o}}var au=/[\u0e33\u0eb3]/,lu=/[\u0e33\u0eb3]/g;function No(s){let e=s;if(au.test(e)&&(e=e.replace(lu,n=>n==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2")),!e.includes(" "))return e;let t="",i=0;for(;i<e.length;){let n=K(e,i);if(n){t+=n.code,i+=n.length;continue}t+=e[i]===" "?" ":e[i],i++}return t}function K(s,e){let t=et(s,e);return t>0?{code:s.substring(e,e+t),length:t}:null}function cu(s){let e=0,t=0;for(;t<s.length;){let i=s.charCodeAt(t);if(i>=32&&i<=126)e++,t++;else if(i===9)e+=3,t++;else if(i===27){let n=et(s,t);if(n===0)return-1;t+=n}else return-1}return e}function et(s,e){if(e>=s.length||s.charCodeAt(e)!==27)return 0;let t=s[e+1];if(t==="["){for(let i=e+2;i<s.length;i++){let n=s.charCodeAt(i);if(n===109||n===71||n===75||n===72||n===74)return i+1-e}return 0}if(t==="]"||t==="_"){for(let i=e+2;i<s.length;i++){let n=s.charCodeAt(i);if(n===7)return i+1-e;if(n===27&&s[i+1]==="\\")return i+2-e}return 0}return 0}function Fo(s){if(!s.startsWith("\x1B]8;"))return;let e=s.endsWith("\x07")?"\x07":"\x1B\\",t=s.slice(4,e==="\x07"?-1:-2),i=t.indexOf(";");if(i===-1)return;let n=t.slice(0,i),r=t.slice(i+1);return r?{params:n,url:r,terminator:e}:null}function hu(s){return`\x1B]8;${s.params};${s.url}${s.terminator}`}function Wo(s){return`\x1B]8;;${s}`}function uu(s){if(!s.includes("\x1B]8;"))return"";let e=null,t=0;for(;t<s.length;){let i=K(s,t);if(i){let n=Fo(i.code);n!==void 0&&(e=n),t+=i.length}else t++}return e?Wo(e.terminator):""}var kt=class{bold=!1;dim=!1;italic=!1;underline=!1;blink=!1;inverse=!1;hidden=!1;strikethrough=!1;fgColor=null;bgColor=null;activeHyperlink=null;process(e){let t=Fo(e);if(t!==void 0){this.activeHyperlink=t;return}if(!e.endsWith("m"))return;let i=e.match(/\x1b\[([\d;]*)m/);if(!i)return;let n=i[1];if(n===""||n==="0"){this.reset();return}let r=n.split(";"),o=0;for(;o<r.length;){let a=Number.parseInt(r[o],10);if(a===38||a===48){if(r[o+1]==="5"&&r[o+2]!==void 0){let l=`${r[o]};${r[o+1]};${r[o+2]}`;a===38?this.fgColor=l:this.bgColor=l,o+=3;continue}else if(r[o+1]==="2"&&r[o+4]!==void 0){let l=`${r[o]};${r[o+1]};${r[o+2]};${r[o+3]};${r[o+4]}`;a===38?this.fgColor=l:this.bgColor=l,o+=5;continue}}switch(a){case 0:this.reset();break;case 1:this.bold=!0;break;case 2:this.dim=!0;break;case 3:this.italic=!0;break;case 4:this.underline=!0;break;case 5:this.blink=!0;break;case 7:this.inverse=!0;break;case 8:this.hidden=!0;break;case 9:this.strikethrough=!0;break;case 21:this.bold=!1;break;case 22:this.bold=!1,this.dim=!1;break;case 23:this.italic=!1;break;case 24:this.underline=!1;break;case 25:this.blink=!1;break;case 27:this.inverse=!1;break;case 28:this.hidden=!1;break;case 29:this.strikethrough=!1;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:a>=30&&a<=37||a>=90&&a<=97?this.fgColor=String(a):(a>=40&&a<=47||a>=100&&a<=107)&&(this.bgColor=String(a));break}o++}}reset(){this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let e=[];this.bold&&e.push("1"),this.dim&&e.push("2"),this.italic&&e.push("3"),this.underline&&e.push("4"),this.blink&&e.push("5"),this.inverse&&e.push("7"),this.hidden&&e.push("8"),this.strikethrough&&e.push("9"),this.fgColor&&e.push(this.fgColor),this.bgColor&&e.push(this.bgColor);let t=e.length>0?`\x1B[${e.join(";")}m`:"";return this.activeHyperlink&&(t+=hu(this.activeHyperlink)),t}getActiveBackgroundCode(){return this.bgColor?`\x1B[${this.bgColor}m`:""}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let e="";return this.underline&&(e+="\x1B[24m"),this.strikethrough&&(e+="\x1B[29m"),this.activeHyperlink&&(e+=Wo(this.activeHyperlink.terminator)),e}};function Zi(s,e){let t=s.indexOf("\x1B");for(;t!==-1;){let i=et(s,t);i>0?(e.process(s.substring(t,t+i)),t+=i):t++,t=s.indexOf("\x1B",t)}}function Uo(s){let e=new kt;return Zi(s,e),e.getActiveBackgroundCode()}function*du(s){for(let{segment:e}of me.segment(s))yield e}function pu(s){let e=[],t="",i="",n=null,r=0,o=()=>{t&&(e.push(t),t="",n=null)};for(;r<s.length;){let a=K(s,r);if(a){i+=a.code,r+=a.length;continue}let l=s.indexOf("\x1B",r+1);for(;l!==-1&&et(s,l)===0;)l=s.indexOf("\x1B",l+1);l===-1&&(l=s.length);let c=s.slice(r,l),h=Dn(c);for(let u of h?c:du(c)){let d=u===" ";if(!h&&!d&&$t.test(u)){o();let f=i+u;i="",e.push(f);continue}let p=d?"space":"word";t&&n!==p&&o(),i&&(t+=i,i=""),n=p,t+=u}r=l}return i&&(t?t+=i:e.length>0?e[e.length-1]+=i:t=i),t&&e.push(t),e}function Tt(s){for(let e of s)Number(e)}function ge(s,e){if(!s)return[""];let t=s.split(/\r\n|\r|\n/),i=[],n=new kt;for(let r of t){let o=i.length>0?n.getActiveCodes():"",a=fu(o+r,e);for(let l of a)i.push(l);Zi(r,n)}return i.length>0?i:[""]}function fu(s,e){if(!s)return[""];if(x(s)<=e)return[s];let i=[],n=new kt,r=pu(s),o="",a=0;for(let l of r){let c=x(l),h=ru(l);if(c>e&&!h){if(o){o=o.trimEnd();let p=n.getLineEndReset();p&&(o+=p),i.push(o),o="",a=0}let d=mu(l,e,n);for(let p=0;p<d.length-1;p++)i.push(d[p]);o=d[d.length-1],a=x(o);continue}let u=a+c;if(u>e&&a>0){let d=o.trimEnd();h&&(d+=Bo(l),Zi(l,n));let p=n.getLineEndReset();if(p&&(d+=p),i.push(d),h){o=n.getActiveCodes(),a=0;continue}o=n.getActiveCodes()+l,a=c}else h&&u>e&&l.includes("\x1B")?o+=Bo(l):(o+=l,a+=c);Zi(l,n)}return o&&i.push(o),i.length>0?i.map(l=>l.trimEnd()):[""]}var Nn=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function ue(s){return/\s/.test(s)}function mu(s,e,t){let i=[],n=t.getActiveCodes(),r=0,o=0,a=[];for(;o<s.length;){let l=K(s,o);if(l)a.push({type:"ansi",value:l.code}),o+=l.length;else{let c=o;for(;c<s.length&&!K(s,c);)c++;let h=s.slice(o,c);for(let u of me.segment(h))a.push({type:"grapheme",value:u.segment});o=c}}for(let l of a){if(l.type==="ansi"){n+=l.value,t.process(l.value);continue}let c=l.value;if(!c)continue;let h=x(c);if(r+h>e){let u=t.getLineEndReset();u&&(n+=u),i.push(n),n=t.getActiveCodes(),r=0}n+=c,r+=h}return n&&i.push(n),i.length>0?i:[""]}function _t(s,e,t){let i=x(s),n=Math.max(0,e-i),r=" ".repeat(n),o=s+r;return t(o)}function _(s,e,t="...",i=!1){if(e<=0)return"";if(s.length===0)return i?" ".repeat(e):"";let n=x(t);if(n>=e){let m=x(s);if(m<=e)return i?s+" ".repeat(e-m):s;let b=su(t,e);return b.width===0?i?" ".repeat(e):"":Ln("",0,b.text,b.width,e,i)}if(Dn(s)){if(s.length<=e)return i?s+" ".repeat(e-s.length):s;let m=e-n;return Ln(s.slice(0,m),m,t,n,e,i)}let r=e-n,o="",a="",l=0,c=0,h=!0,u=!1,d=!1,p=s.includes("\x1B"),f=s.includes(" ");if(!p&&!f){for(let{segment:m}of me.segment(s)){let b=Me(m);if(h&&c+b<=r?(o+=m,c+=b):h=!1,l+=b,l>e){u=!0;break}}d=!u}else{let m=0;for(;m<s.length;){let b=K(s,m);if(b){a+=b.code,m+=b.length;continue}if(s[m]===" "){if(h&&c+3<=r?(a&&(o+=a,a=""),o+=" ",c+=3):(h=!1,a=""),l+=3,l>e){u=!0;break}m++;continue}let g=m;for(;g<s.length&&s[g]!==" "&&!K(s,g);)g++;for(let{segment:y}of me.segment(s.slice(m,g))){let w=Me(y);if(h&&c+w<=r?(a&&(o+=a,a=""),o+=y,c+=w):(h=!1,a=""),l+=w,l>e){u=!0;break}}if(u)break;m=g}d=m>=s.length}return!u&&d?i?s+" ".repeat(Math.max(0,e-l)):s:Ln(o,c,t,n,e,i)}function H(s,e,t,i=!1){return Fn(s,e,t,i).text}function Fn(s,e,t,i=!1){if(t<=0)return{text:"",width:0};let n=e+t,r="",o=0,a=0,l=0,c="";for(;l<s.length;){let h=K(s,l);if(h){a>=e&&a<n?(r+=c+h.code,c=""):a<e&&!h.code.startsWith("\x1B_")&&(c+=h.code),l+=h.length;continue}let u=l;for(;u<s.length&&!K(s,u);)u++;for(let{segment:d}of me.segment(s.slice(l,u))){let p=Me(d),f=a>=e&&a<n,m=!i||a+p<=n;if(f&&m&&(c&&(r+=c,c=""),r+=d,o+=p),a+=p,a>=n)break}if(l=u,a>=n)break}return{text:r,width:o}}var On=new kt;function Ko(s,e,t,i,n=!1){let r="",o=0,a="",l=0,c=0,h=0,u="",d=!1,p=t+i;for(On.clear();h<s.length;){let f=K(s,h);if(f){On.process(f.code),c<e?u+=f.code:c>=t&&c<p&&(d||f.code.startsWith("\x1B_"))&&(a+=f.code),h+=f.length;continue}let m=h;for(;m<s.length&&!K(s,m);)m++;for(let{segment:b}of me.segment(s.slice(h,m))){let g=Me(b);if(c<e&&c+g<=e?(u&&(r+=u,u=""),r+=b,o+=g):c>=t&&c<p&&(!n||c+g<=p)&&(d||(a+=On.getActiveCodes(),d=!0),a+=b,l+=g),c+=g,i<=0?c>=e:c>=p)break}if(h=m,i<=0?c>=e:c>=p)break}return{before:r,beforeWidth:o,after:a,afterWidth:l}}var Wg=new RegExp(`${ts.source}$`,"u");var zo=(s,[e,t,i])=>s.map(n=>n[0]*e+n[1]*t+n[2]*i);var gu=[[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,-.0638541728258133],[1,-.0894841775298119,-1.2914855480194092]],bu=[[4.076741636075958,-3.307711539258063,.2309699031821043],[-1.2684379732850315,2.609757349287688,-.341319376002657],[-.0041960761386756,-.7034186179359362,1.7076146940746117]];var yu=.206,wu=.03,Kg=(1+yu)/(1+wu);var xu=s=>s>.0031308?1.055*s**(1/2.4)-.055:12.92*s;function Vo(s){return zo(bu,zo(gu,s).map(e=>e**3))}function Wn(s){let[e,t,i]=s.map(n=>Math.round(Math.min(1,Math.max(0,xu(n)))*255));return{r:e,g:t,b:i}}function vu(s,e){if(!Number.isFinite(s))throw new Error(`${e} must be finite`)}function Ke(s,e,t){for(let[i,n]of[["r",s],["g",e],["b",t]])if(vu(n,i),n<0||n>255)throw new Error(`${i} must be between 0 and 255: ${n}`);return Object.freeze({kind:"rgb",r:s,g:e,b:t})}var It=String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`,Qg=new RegExp(`^oklch\\(\\s*(${It})(%)?\\s+(${It})\\s+(${It})(?:deg)?\\s*\\)$`,"i"),Yg=new RegExp(`^okhsl\\(\\s*(${It})(?:deg)?\\s+(${It})(%)?\\s+(${It})(%)?\\s*\\)$`,"i");var ku=[{r:0,g:0,b:0},{r:128,g:0,b:0},{r:0,g:128,b:0},{r:128,g:128,b:0},{r:0,g:0,b:128},{r:128,g:0,b:128},{r:0,g:128,b:128},{r:192,g:192,b:192},{r:128,g:128,b:128},{r:255,g:0,b:0},{r:0,g:255,b:0},{r:255,g:255,b:0},{r:0,g:0,b:255},{r:255,g:0,b:255},{r:0,g:255,b:255},{r:255,g:255,b:255}],Ee=[0,95,135,175,215,255],jo=Array.from({length:24},(s,e)=>8+e*10);function Su(s){if(s<16)return{...ku[s]};if(s<232){let t=s-16;return{r:Ee[Math.floor(t/36)],g:Ee[Math.floor(t%36/6)],b:Ee[t%6]}}let e=8+(s-232)*10;return{r:e,g:e,b:e}}function Go(s){return s.every(t=>t>=-1e-7&&t<=1+1e-7)}function Cu({l:s,c:e,h:t}){let i=t*Math.PI/180,n=Math.cos(i),r=Math.sin(i),o=u=>Vo([s,u*n,u*r]),a=o(e);if(Go(a))return Wn(a);let l=o(0),c=0,h=e;for(let u=0;u<20;u++){let d=(c+h)/2,p=o(d);Go(p)?(c=d,l=p):h=d}return Wn(l)}function Yo(s){switch(s.kind){case"indexed":return Su(s.index);case"rgb":return{r:s.r,g:s.g,b:s.b};case"oklch":return Cu(s)}}function is(s,e){let t=0,i=1/0;for(let n=0;n<s.length;n++){let r=Math.abs(e-s[n]);r<i&&(t=n,i=r)}return t}function Qo(s,e){let t=s.r-e.r,i=s.g-e.g,n=s.b-e.b;return t*t*.299+i*i*.587+n*n*.114}function $u(s){let e=is(Ee,s.r),t=is(Ee,s.g),i=is(Ee,s.b),n={r:Ee[e],g:Ee[t],b:Ee[i]},r=16+36*e+6*t+i,o=Math.round(.299*s.r+.587*s.g+.114*s.b),a=is(jo,o),l=jo[a];return Math.max(s.r,s.g,s.b)-Math.min(s.r,s.g,s.b)<10&&Qo(s,{r:l,g:l,b:l})<Qo(s,n)?232+a:r}function Xo(s,e,t){if(s.kind==="indexed")return`\x1B[${t?48:38};5;${s.index}m`;let i=Yo(s);return e==="truecolor"?`\x1B[${t?48:38};2;${Math.round(i.r)};${Math.round(i.g)};${Math.round(i.b)}m`:`\x1B[${t?48:38};5;${$u(i)}m`}function Jo(s,e){return Xo(s,e,!1)}function Zo(s,e){return Xo(s,e,!0)}function Pt(s,e,t){return ea(s,e.fg&&Jo(e.fg,t),e.bg&&Zo(e.bg,t),e)}function ea(s,e,t,i){let n="",r="";return e&&(n+=e,r="\x1B[39m"),t&&(n+=t,r=`\x1B[49m${r}`),i.bold&&(n+="\x1B[1m"),i.dim&&(n+="\x1B[2m"),(i.bold||i.dim)&&(r=`\x1B[22m${r}`),i.italic&&(n+="\x1B[3m",r=`\x1B[23m${r}`),i.underline&&(n+="\x1B[4m",r=`\x1B[24m${r}`),i.inverse&&(n+="\x1B[7m",r=`\x1B[27m${r}`),i.strikethrough&&(n+="\x1B[9m",r=`\x1B[29m${r}`),`${n}${s}${r}`}import{performance as fs}from"node:perf_hooks";var Le=!1;function ui(s){Le=s}var T={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:s=>`ctrl+${s}`,shift:s=>`shift+${s}`,alt:s=>`alt+${s}`,super:s=>`super+${s}`,ctrlShift:s=>`ctrl+shift+${s}`,shiftCtrl:s=>`shift+ctrl+${s}`,ctrlAlt:s=>`ctrl+alt+${s}`,altCtrl:s=>`alt+ctrl+${s}`,shiftAlt:s=>`shift+alt+${s}`,altShift:s=>`alt+shift+${s}`,ctrlSuper:s=>`ctrl+super+${s}`,superCtrl:s=>`super+ctrl+${s}`,shiftSuper:s=>`shift+super+${s}`,superShift:s=>`super+shift+${s}`,altSuper:s=>`alt+super+${s}`,superAlt:s=>`super+alt+${s}`,ctrlShiftAlt:s=>`ctrl+shift+alt+${s}`,ctrlShiftSuper:s=>`ctrl+shift+super+${s}`},ss=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),Au=new Set("~!@#$%^&*()_+|{}:<>?"),Tu=["shift","alt","ctrl","super"],C={shift:1,alt:2,ctrl:4,super:8},Rt=192,F={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},Y={up:-1,down:-2,right:-3,left:-4},R={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15,f1:-21,f2:-22,f3:-23,f4:-24,f5:-25,f6:-26,f7:-27,f8:-28,f9:-29,f10:-30,f11:-31,f12:-32},_u=57344,Iu=63743,Pu=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,Y.left],[57418,Y.right],[57419,Y.up],[57420,Y.down],[57421,R.pageUp],[57422,R.pageDown],[57423,R.home],[57424,R.end],[57425,R.insert],[57426,R.delete]]);function hi(s){return Pu.get(s)??s}function ns(s,e){return(e&~Rt&C.shift)!==0&&s>=65&&s<=90?s+32:s}function sa(s,e,t){if(s===void 0||(e&C.shift)===0)return;let i=hi(s);if(t.has(String.fromCharCode(i)))return{codepoint:i,modifier:e&~C.shift}}var be={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D","\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},Ru={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},Mu={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]};var oe=(s,e)=>e.includes(s),de=(s,e,t)=>t===C.shift?oe(s,Ru[e]):t===C.ctrl?oe(s,Mu[e]):!1,ai="press";function di(s){return s.includes("\x1B[200~")?!1:!!(s.includes(":3u")||s.includes(":3~")||s.includes(":3A")||s.includes(":3B")||s.includes(":3C")||s.includes(":3D")||s.includes(":3H")||s.includes(":3F")||s.includes(":3P")||s.includes(":3Q")||s.includes(":3S"))}function li(s){if(!s)return"press";let e=parseInt(s,10);return e===2?"repeat":e===3?"release":"press"}function Eu(s){let e=s.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(e){let o=parseInt(e[1],10),a=e[2]&&e[2].length>0?parseInt(e[2],10):void 0,l=e[3]?parseInt(e[3],10):void 0,c=e[4]?parseInt(e[4],10):1,h=li(e[5]);return ai=h,{codepoint:o,shiftedKey:a,baseLayoutKey:l,modifier:c-1,eventType:h}}let t=s.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(t){let o=parseInt(t[1],10),a=li(t[2]),l={A:-1,B:-2,C:-3,D:-4};return ai=a,{codepoint:l[t[3]],modifier:o-1,eventType:a}}let i=s.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(i){let o=parseInt(i[1],10),a=i[2]?parseInt(i[2],10):1,l=li(i[3]),h={2:R.insert,3:R.delete,5:R.pageUp,6:R.pageDown,7:R.home,8:R.end,11:R.f1,12:R.f2,13:R.f3,14:R.f4,15:R.f5,17:R.f6,18:R.f7,19:R.f8,20:R.f9,21:R.f10,23:R.f11,24:R.f12}[o];if(h!==void 0)return ai=l,{codepoint:h,modifier:a-1,eventType:l}}let n=s.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(n){let o=parseInt(n[1],10),a=li(n[2]),l=n[3]==="H"?R.home:R.end;return ai=a,{codepoint:l,modifier:o-1,eventType:a}}let r=s.match(/^\x1b\[(?:1;(\d+)(?::(\d+))?)?([PQS])$/);if(r){let o=r[1]?parseInt(r[1],10):1,a=li(r[2]),l={P:R.f1,Q:R.f2,S:R.f4};return ai=a,{codepoint:l[r[3]],modifier:o-1,eventType:a}}return null}function I(s,e,t){let i=Eu(s);if(!i)return!1;let n=i.modifier&~Rt,r=t&~Rt,o=ns(hi(i.codepoint),i.modifier),a=ns(hi(e),t);if(n===r&&o===a)return!0;let l=sa(i.shiftedKey,n,ss);if(l&&(l.modifier&~Rt)===r&&l.codepoint===hi(e))return!0;if(n!==r)return!1;if(i.baseLayoutKey!==void 0&&i.baseLayoutKey===e){let c=o,h=c>=97&&c<=122,u=ss.has(String.fromCharCode(c));if(!h&&!u)return!0}return!1}function Un(s){let e=s.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!e)return null;let t=parseInt(e[1],10);return{codepoint:parseInt(e[2],10),modifier:t-1}}function ye(s,e,t){let i=Un(s);return i?i.codepoint===e&&i.modifier===t:!1}function Lu(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function ta(s,e){return s==="\x7F"?e===0:s!=="\b"?!1:Lu()?e===C.ctrl:e===0}function Ou(s){let e=s.toLowerCase(),t=e.charCodeAt(0);return t>=97&&t<=122||e==="["||e==="\\"||e==="]"||e==="_"?String.fromCharCode(t&31):e==="-"?"":null}function ia(s){return s>="0"&&s<="9"}function ci(s,e,t){let i=Un(s);if(!i)return!1;if(i.modifier===t&&ns(i.codepoint,i.modifier)===ns(e,t))return!0;let r=sa(i.codepoint,i.modifier,Au);return r?.modifier===t&&r.codepoint===e}function qu(s){let e=s.toLowerCase(),t=new Set;for(;;){let i=Tu.find(n=>e.startsWith(`${n}+`));if(!i)break;if(t.has(i))return null;t.add(i),e=e.slice(i.length+1)}return!e||e.includes("+")&&e!=="+"?null:{key:e,ctrl:t.has("ctrl"),shift:t.has("shift"),alt:t.has("alt"),super:t.has("super")}}function S(s,e){let t=qu(e);if(!t)return!1;let{key:i,ctrl:n,shift:r,alt:o,super:a}=t,l=0;switch(r&&(l|=C.shift),o&&(l|=C.alt),n&&(l|=C.ctrl),a&&(l|=C.super),i){case"escape":case"esc":return l!==0?!1:s==="\x1B"||I(s,F.escape,0)||ye(s,F.escape,0);case"space":return!Le&&(l===C.ctrl&&s==="\0"||l===C.alt&&s==="\x1B ")?!0:l===0?s===" "||I(s,F.space,0)||ye(s,F.space,0):I(s,F.space,l)||ye(s,F.space,l);case"tab":return l===C.shift?s==="\x1B[Z"||I(s,F.tab,C.shift)||ye(s,F.tab,C.shift):l===0?s===" "||I(s,F.tab,0):I(s,F.tab,l)||ye(s,F.tab,l);case"enter":case"return":return l===C.shift?I(s,F.enter,C.shift)||I(s,F.kpEnter,C.shift)||ye(s,F.enter,C.shift)?!0:Le?s==="\x1B\r"||s===`
|
|
67
67
|
`:!1:l===C.alt?I(s,F.enter,C.alt)||I(s,F.kpEnter,C.alt)||ye(s,F.enter,C.alt)?!0:Le?!1:s==="\x1B\r":l===0?s==="\r"||!Le&&s===`
|
|
68
|
-
`||s==="\x1BOM"||I(s,F.enter,0)||I(s,F.kpEnter,0):I(s,F.enter,l)||I(s,F.kpEnter,l)||ye(s,F.enter,l);case"backspace":return l===C.alt?s==="\x1B\x7F"||s==="\x1B\b"?!0:I(s,F.backspace,C.alt)||ye(s,F.backspace,C.alt):l===C.ctrl?Jo(s,C.ctrl)?!0:I(s,F.backspace,C.ctrl)||ye(s,F.backspace,C.ctrl):l===0?Jo(s,0)||I(s,F.backspace,0)||ye(s,F.backspace,0):I(s,F.backspace,l)||ye(s,F.backspace,l);case"insert":return l===0?oe(s,be.insert)||I(s,P.insert,0):de(s,"insert",l)?!0:I(s,P.insert,l);case"delete":return l===0?oe(s,be.delete)||I(s,P.delete,0):de(s,"delete",l)?!0:I(s,P.delete,l);case"clear":return l===0?oe(s,be.clear):de(s,"clear",l);case"home":return l===0?oe(s,be.home)||I(s,P.home,0):de(s,"home",l)?!0:I(s,P.home,l);case"end":return l===0?oe(s,be.end)||I(s,P.end,0):de(s,"end",l)?!0:I(s,P.end,l);case"pageup":return l===0?oe(s,be.pageUp)||I(s,P.pageUp,0):de(s,"pageUp",l)?!0:I(s,P.pageUp,l);case"pagedown":return l===0?oe(s,be.pageDown)||I(s,P.pageDown,0):de(s,"pageDown",l)?!0:I(s,P.pageDown,l);case"up":return l===C.alt?s==="\x1Bp"||I(s,Y.up,C.alt):l===0?oe(s,be.up)||I(s,Y.up,0):de(s,"up",l)?!0:I(s,Y.up,l);case"down":return l===C.alt?s==="\x1Bn"||I(s,Y.down,C.alt):l===0?oe(s,be.down)||I(s,Y.down,0):de(s,"down",l)?!0:I(s,Y.down,l);case"left":return l===C.alt?s==="\x1B[1;3D"||!Le&&s==="\x1BB"||s==="\x1Bb"||I(s,Y.left,C.alt):l===C.ctrl?s==="\x1B[1;5D"||de(s,"left",C.ctrl)||I(s,Y.left,C.ctrl):l===0?oe(s,be.left)||I(s,Y.left,0):de(s,"left",l)?!0:I(s,Y.left,l);case"right":return l===C.alt?s==="\x1B[1;3C"||!Le&&s==="\x1BF"||s==="\x1Bf"||I(s,Y.right,C.alt):l===C.ctrl?s==="\x1B[1;5C"||de(s,"right",C.ctrl)||I(s,Y.right,C.ctrl):l===0?oe(s,be.right)||I(s,Y.right,0):de(s,"right",l)?!0:I(s,Y.right,l);case"f1":case"f2":case"f3":case"f4":case"f5":case"f6":case"f7":case"f8":case"f9":case"f10":case"f11":case"f12":{let c=i;return l===0&&oe(s,be[c])?!0:I(s,P[c],l)}}if(i.length===1&&(i>="a"&&i<="z"||Zo(i)||ts.has(i))){let c=i.charCodeAt(0),h=Ru(i),u=i>="a"&&i<="z",d=Zo(i);return l===C.ctrl+C.alt&&!Le&&h&&s===`\x1B${h}`||l===C.alt&&!Le&&(u||d||ts.has(i))&&s===`\x1B${i}`?!0:l===C.ctrl?h&&s===h?!0:I(s,c,C.ctrl)||li(s,c,C.ctrl):l===C.shift+C.ctrl?I(s,c,C.shift+C.ctrl)||li(s,c,C.shift+C.ctrl):l===C.shift?u&&s===i.toUpperCase()?!0:I(s,c,C.shift)||li(s,c,C.shift):l!==0?I(s,c,l)||li(s,c,l):s===i||I(s,c,0)||li(s,c,0)}return!1}var Mu=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,Eu=C.shift|Pt;function ss(s){let e=s.match(Mu);if(!e)return;let t=Number.parseInt(e[1]??"",10);if(!Number.isFinite(t))return;let i=e[2]&&e[2].length>0?Number.parseInt(e[2],10):void 0,n=e[4]?Number.parseInt(e[4],10):1,r=Number.isFinite(n)?n-1:0;if((r&~Eu)!==0||r&(C.alt|C.ctrl))return;let o=t;if(r&C.shift&&typeof i=="number"&&(o=i),o=ci(o),!(!Number.isFinite(o)||o<32)&&!(o>=Su&&o<=Cu))try{return String.fromCodePoint(o)}catch{return}}function Lu(s){let e=Fn(s);if(!(!e||(e.modifier&~Pt&~C.shift)!==0)&&!(!Number.isFinite(e.codepoint)||e.codepoint<32))try{return String.fromCodePoint(e.codepoint)}catch{return}}function Wn(s){return ss(s)??Lu(s)}function Ou(s){let e=s.startsWith("#")?s.slice(1):s,t=parseInt(e.slice(0,2),16),i=parseInt(e.slice(2,4),16),n=parseInt(e.slice(4,6),16);return{r:t,g:i,b:n}}function Mt(s){if(!/^[0-9a-f]+$/i.test(s))return;let e=16**s.length-1;if(!(e<=0))return Math.round(parseInt(s,16)/e*255)}var qu=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,Du=/^(?:\x1b\[\?997;(1|2)n)+$/;function ta(s){let e=s.match(qu);return e?{target:e[1]==="10"?"foreground":e[1]==="11"?"background":Number.parseInt(e[2],10),rgb:Bu(e[3])}:void 0}function Bu(s){let e=s.trim();if(e.startsWith("#")){let c=e.slice(1);if(/^[0-9a-f]{6}$/i.test(c))return Ou(e);if(/^[0-9a-f]{12}$/i.test(c)){let h=Mt(c.slice(0,4)),u=Mt(c.slice(4,8)),d=Mt(c.slice(8,12));return h!==void 0&&u!==void 0&&d!==void 0?{r:h,g:u,b:d}:void 0}return}let t=e.replace(/^rgba?:/i,""),[i,n,r]=t.split("/");if(i===void 0||n===void 0||r===void 0)return;let o=Mt(i),a=Mt(n),l=Mt(r);return o!==void 0&&a!==void 0&&l!==void 0?{r:o,g:a,b:l}:void 0}function Kn(s){let e=s.match(Du);if(e)return e[1]==="2"?"light":"dark"}import{execSync as Nu}from"node:child_process";import{homedir as Fu}from"node:os";import{isAbsolute as Wu}from"node:path";import{pathToFileURL as Ku}from"node:url";var ns=null,ia={},aa={widthPx:9,heightPx:18};function rs(){return aa}function Hn(s){aa=s}function Uu(){try{return Nu("tmux display-message -p '#{client_termfeatures}'",{encoding:"utf8",timeout:250,stdio:["ignore","pipe","ignore"]}).split(",").map(e=>e.trim()).includes("hyperlinks")}catch{return!1}}function Hu(s){let e=process.env.TERM_PROGRAM?.toLowerCase()||"",t=process.env.TERMINAL_EMULATOR?.toLowerCase()||"",i=process.env.TERM?.toLowerCase()||"",n=process.env.COLORTERM?.toLowerCase()||"",r=n==="truecolor"||n==="24bit"||i.endsWith("-direct"),o=process.platform==="win32";return process.env.TMUX||i.startsWith("tmux")?{images:null,trueColor:r,hyperlinks:s()}:i.startsWith("screen")?{images:null,trueColor:r,hyperlinks:!1}:e==="herdr"?{images:"kitty",trueColor:r,hyperlinks:!0}:e==="rex"?{images:"kitty",trueColor:!0,hyperlinks:!0}:e==="orca"&&process.env.ORCA_IMAGE_PROTOCOL==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.KITTY_WINDOW_ID||e==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:e==="ghostty"||i.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||e==="wezterm"?{images:"kitty",trueColor:!0,hyperlinks:!0}:e==="warpterminal"||process.env.WARP_SESSION_ID||process.env.WARP_TERMINAL_SESSION_UUID?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||e==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:process.env.WT_SESSION?{images:null,trueColor:!0,hyperlinks:!0}:e==="alacritty"||i.startsWith("alacritty")||process.env.ALACRITTY_WINDOW_ID||e==="vscode"||e==="zed"?{images:null,trueColor:!0,hyperlinks:!0}:t==="jetbrains-jediterm"?{images:null,trueColor:!0,hyperlinks:!1}:o?{images:null,trueColor:!0,hyperlinks:!1}:{images:null,trueColor:r,hyperlinks:!1}}function sa(s){return s==="1"?!0:s==="0"?!1:void 0}function la(s=Uu){let e=sa(process.env.PI_HYPERLINKS),t=Hu(e===void 0?s:()=>e),i=process.env.PI_IMAGE_PROTOCOL?.toLowerCase(),n=i==="kitty"||i==="iterm2"?i:i==="none"||i==="0"?null:void 0,r=sa(process.env.PI_TRUE_COLOR);return{...t,...n!==void 0?{images:n}:{},...r!==void 0?{trueColor:r}:{},...e!==void 0?{hyperlinks:e}:{}}}function ae(){if(!ns){let s=ia.hyperlinks;ns={...la(s===void 0?void 0:()=>s),...ia}}return ns}function zn(s=ae()){return s.trueColor?"truecolor":"256color"}function os(s){ns=s}var Lt="\x1B_G",na="\x1B]1337;File=";function z(s){return s.startsWith(Lt)||s.startsWith(na)?!0:s.includes(Lt)||s.includes(na)}function Vn(){return Math.floor(Math.random()*4294967294)+1}function ca(s,e={}){let i=["a=T","f=100","q=2"];if(e.moveCursor===!1&&i.push("C=1"),e.columns&&i.push(`c=${e.columns}`),e.rows&&i.push(`r=${e.rows}`),e.imageId&&i.push(`i=${e.imageId}`),s.length<=4096)return`\x1B_G${i.join(",")};${s}\x1B\\`;let n=[],r=0,o=!0;for(;r<s.length;){let a=s.slice(r,r+4096),l=r+4096>=s.length;o?(n.push(`\x1B_G${i.join(",")},m=1;${a}\x1B\\`),o=!1):l?n.push(`\x1B_Gm=0;${a}\x1B\\`):n.push(`\x1B_Gm=1;${a}\x1B\\`),r+=4096}return n.join("")}function as(s){return`\x1B_Ga=d,d=I,i=${s},q=2\x1B\\`}function jn(){return"\x1B_Ga=d,d=A,q=2\x1B\\"}function Gn(){return"\x1B_Ga=d,d=a,q=2\x1B\\"}function ha(s,e={}){let t=[`inline=${e.inline!==!1?1:0}`,`size=${Buffer.byteLength(s,"base64")}`];if(e.width!==void 0&&t.push(`width=${e.width}`),e.height!==void 0&&t.push(`height=${e.height}`),e.name){let i=Buffer.from(e.name).toString("base64");t.push(`name=${i}`)}return e.preserveAspectRatio===!1&&t.push("preserveAspectRatio=0"),`\x1B]1337;File=${t.join(";")}:${s}\x07`}var Et=new Map,ra=0,Un=0;function zu(s){if(ra+=1,Un=Math.max(Un,s.rows),Et.delete(s.imageId),Et.set(s.imageId,{...s,transmissionGeneration:ra}),Et.size>1e3){let e=Et.keys().next().value;e!==void 0&&Et.delete(e)}}function ua(){return Un}function Qn(s){let e=/(?:^|,)i=(\d+)(?:,|$)/.exec(s)?.[1];return e===void 0?void 0:Et.get(Number.parseInt(e,10))}function Vu(s){let e=/\x1b_G([^;]*);/.exec(s)?.[1];return e===void 0?void 0:Qn(e)}function da(s){let e=/(?:^|,)r=(\d+)(?:,|$)/.exec(s)?.[1];if(e===void 0)return;let t=Number.parseInt(e,10);return t>0?t:void 0}function ju(s,e){return da(s)??e}function ls(s){let e=Vu(s);if(e)return{imageId:e.imageId,columns:e.columns,rows:e.rows,widthPx:e.widthPx,heightPx:e.heightPx}}var Gu=new Set(["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function pa(s){let e=/\x1b_G([^;]*);/.exec(s)?.[1];if(e===void 0)return;let t=da(e);return t!==void 0?t:Qn(e)?.rows}function fa(s){let e=/\x1b_G([^;]*);/.exec(s);if(!e)return;let t=Qn(e[1]);if(!t)return;let i=e.index,n=e[1],r;for(;;){let l=s.indexOf("\x1B\\",i+Lt.length);if(l===-1)return;if(r=l+2,!/(?:^|,)m=1(?:,|$)/.test(n))break;if(i=r,!s.startsWith(Lt,i))return;let c=s.indexOf(";",i+Lt.length);if(c===-1)return;n=s.slice(i+Lt.length,c)}let a=`\x1B_Ga=p,q=2,${e[1].split(",").filter(l=>Gu.has(l.split("=",1)[0]??"")).join(",")}\x1B\\`;return{imageId:t.imageId,transmissionGeneration:t.transmissionGeneration,transmissionBytes:r-e.index,estimatedDecodedBytes:t.widthPx*t.heightPx*4,rows:ju(e[1],t.rows),sequence:a,replacementLine:`${s.slice(0,e.index)}${a}${s.slice(r)}`}}function Yn(s,e,t){let i=ls(s),n=/\x1b_G([^;]*);/.exec(s);if(!i||!n||e<0||e>=i.rows||t<=0)return s;let r=Math.min(t,i.rows-e);if(e===0&&r===i.rows)return s;let o=Math.floor(i.heightPx*e/i.rows),a=Math.ceil(i.heightPx*(e+r)/i.rows),l=Math.max(1,Math.min(i.heightPx,a)-o),c=n[1].split(",").filter(h=>!/^[yhr]=/.test(h));return c.push(`y=${o}`,`h=${l}`,`r=${r}`),`${s.slice(0,n.index)}\x1B_G${c.join(",")};${s.slice(n.index+n[0].length)}`}function oa(s,e){if(s<=1)return s;let t=s-1,i=Math.max(s/e,e/s);return Math.max(t/e,e/t)<i?t:s}function Qu(s,e,t,i={widthPx:9,heightPx:18},n=!1){let r=Math.max(1,Math.floor(e)),o=t===void 0?void 0:Math.max(1,Math.floor(t)),a=Math.max(1,s.widthPx),l=Math.max(1,s.heightPx),c=r*i.widthPx/a,h=o===void 0?c:o*i.heightPx/l,u=Math.min(c,h),d=a*u,p=l*u,f=Math.max(1,Math.min(r,Math.ceil(d/i.widthPx))),g=p/i.heightPx,b=Math.max(1,Math.ceil(g));if(o!==void 0&&(b=Math.min(o,b)),!n)return{columns:f,rows:b};if(c<=h){let m=f*i.widthPx*l/(a*i.heightPx);b=oa(b,m)}else{let m=b*i.heightPx*a/(l*i.widthPx);f=oa(f,m)}return{columns:f,rows:b}}function cs(s){try{let e=Buffer.from(s,"base64");if(e.length<24||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return null;let t=e.readUInt32BE(16),i=e.readUInt32BE(20);return{widthPx:t,heightPx:i}}catch{return null}}function ma(s){try{let e=Buffer.from(s,"base64");if(e.length<2||e[0]!==255||e[1]!==216)return null;let t=2;for(;t<e.length-9;){if(e[t]!==255){t++;continue}let i=e[t+1];if(i>=192&&i<=194){let r=e.readUInt16BE(t+5);return{widthPx:e.readUInt16BE(t+7),heightPx:r}}if(t+3>=e.length)return null;let n=e.readUInt16BE(t+2);if(n<2)return null;t+=2+n}return null}catch{return null}}function ga(s){try{let e=Buffer.from(s,"base64");if(e.length<10)return null;let t=e.slice(0,6).toString("ascii");if(t!=="GIF87a"&&t!=="GIF89a")return null;let i=e.readUInt16LE(6),n=e.readUInt16LE(8);return{widthPx:i,heightPx:n}}catch{return null}}function ba(s){try{let e=Buffer.from(s,"base64");if(e.length<30)return null;let t=e.slice(0,4).toString("ascii"),i=e.slice(8,12).toString("ascii");if(t!=="RIFF"||i!=="WEBP")return null;let n=e.slice(12,16).toString("ascii");if(n==="VP8 "){if(e.length<30)return null;let r=e.readUInt16LE(26)&16383,o=e.readUInt16LE(28)&16383;return{widthPx:r,heightPx:o}}else if(n==="VP8L"){if(e.length<25)return null;let r=e.readUInt32LE(21),o=(r&16383)+1,a=(r>>14&16383)+1;return{widthPx:o,heightPx:a}}else if(n==="VP8X"){if(e.length<30)return null;let r=(e[24]|e[25]<<8|e[26]<<16)+1,o=(e[27]|e[28]<<8|e[29]<<16)+1;return{widthPx:r,heightPx:o}}return null}catch{return null}}function Xn(s,e){return e==="image/png"?cs(s):e==="image/jpeg"?ma(s):e==="image/gif"?ga(s):e==="image/webp"?ba(s):null}function Jn(s,e,t={}){let i=ae();if(!i.images)return null;let n=t.maxWidthCells??80,r=Qu(e,n,t.maxHeightCells,rs(),i.images==="kitty");return i.images==="kitty"?(t.imageId!==void 0&&zu({imageId:t.imageId,columns:r.columns,rows:r.rows,widthPx:e.widthPx,heightPx:e.heightPx}),{sequence:ca(s,{columns:r.columns,rows:r.rows,imageId:t.imageId,moveCursor:t.moveCursor}),columns:r.columns,rows:r.rows,imageId:t.imageId}):i.images==="iterm2"?{sequence:ha(s,{width:r.columns,height:"auto",preserveAspectRatio:t.preserveAspectRatio??!0}),columns:r.columns,rows:r.rows}:null}function hs(s,e){return`\x1B]8;;${e}\x1B\\${s}\x1B]8;;\x1B\\`}function Yu(s){let e=Fu();return e&&(s===e||s.startsWith(`${e}/`)||s.startsWith(`${e}\\`))?`~${s.slice(e.length)}`:s}function us(s,e,t){let i=[];if(t){let n=Yu(t);ae().hyperlinks&&Wu(t)?i.push(hs(n,Ku(t).href)):i.push(n)}return i.push(`[${s}]`),e&&i.push(`${e.widthPx}x${e.heightPx}`),`[Image: ${i.join(" ")}]`}function tt(s,e){let t=s.handleMouse?.(e);if(t){if("target"in t){let i=t;return i.focus&&s.handleInput?{...i,focusTarget:s}:i}if(!(!t.handled&&!t.capture&&!t.focus))return{...t,handled:!0,...t.focus?{focusTarget:s}:{},target:{component:s,originX:e.screenX-e.x,originY:e.screenY-e.y,width:e.width,height:e.height}}}}function wa(s,e){return{...s,x:s.screenX-e.originX,y:s.screenY-e.originY,width:e.width,height:e.height}}var ps=16,Xu=2+ps,Ju=`\x1B]10;?\x07\x1B]11;?\x07${Array.from({length:ps},(s,e)=>`\x1B]4;${e};?\x07`).join("")}\x1B[c`,Zu=/^\x1b\[\?[\d;]*c$/;function Zn(s){return s!==null&&"focused"in s}var pe="\x1B_pi:c\x07",er="\x1B_pi:fc\x07",xa="\x1B_pi:/fc\x07",ed=/(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;function it(s){return`${er}${s}${xa}`}function ya(s,e){if(s===void 0)return;if(typeof s=="number")return s;let t=s.match(/^(\d+(?:\.\d+)?)%$/);if(t)return Math.floor(e*parseFloat(t[1])/100)}var ee=class{children=[];mouseLayout;addChild(e){this.children.push(e)}removeChild(e){let t=this.children.indexOf(e);t!==-1&&this.children.splice(t,1)}clear(){this.children=[]}invalidate(){for(let e of this.children)e.invalidate?.()}handleMouse(e){if(e.y<0||e.y>=e.height)return;let t=this.mouseLayout?.width===e.width?this.mouseLayout.children:this.children.map(n=>({component:n,height:n.render(e.width).length})),i=0;for(let{component:n,height:r}of t){if(e.y>=i&&e.y<i+r){let o=tt(n,{...e,y:e.y-i,height:r});return o?.focus&&this.handleInput?{...o,focusTarget:this}:o}i+=r}}render(e){let t=[],i=[];for(let n of this.children){let r=n.render(e);i.push({component:n,height:r.length});for(let o of r)t.push(o)}return this.mouseLayout={width:e,children:i},t}},tr="\x1B[0m\x1B]8;;\x07";function He(s,e,t,i,n){if(z(s))return s;let r=t+i,o=Fo(s,t,r,n-r,!0),a=Bn(e,0,i,!0),l=Math.max(0,t-o.beforeWidth),c=Math.max(0,i-a.width),h=Math.max(t,o.beforeWidth),u=Math.max(i,a.width),d=Math.max(0,n-h-u),p=Math.max(0,d-o.afterWidth),f=o.before+" ".repeat(l)+tr+a.text+" ".repeat(c)+tr+o.after+" ".repeat(p);return x(f)<=n?f:H(f,0,n,!0)}var ir=Symbol.for("@earendil-works/pi-tui/viewport");function sr(s){return s[ir]===!0}var di=class s extends ee{terminal;focusedComponent=null;inputListeners=new Set;onDebug;renderRequested=!1;immediateRenderScheduled=!1;renderTimer;lastRenderAt=0;static MIN_RENDER_INTERVAL_MS=16;showHardwareCursor=!1;clearOnShrink=!1;fullRedrawCount=0;stopped=!1;pendingTerminalColorQueries=[];terminalColorSchemeListeners=new Set;terminalColorSchemeNotificationsEnabled=!1;logDirectory;focusOrderCounter=0;overlayStack=[];renderedOverlayLayouts=[];get hasOverlayEntries(){return this.overlayStack.length>0}overlayFocusRestore={status:"inactive"};constructor(e,t,i){super(),this.terminal=e,this.logDirectory=i,t!==void 0&&(this.showHardwareCursor=t)}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(e){}afterTerminalStop(e){}getExitRestorePrefix(){return`${this.terminalColorSchemeNotificationsEnabled?"\x1B[?2031l":""}\x1B[?25h`}getExitRestoreSuffix(){return""}exitRestoreHandler=()=>{if(!this.stopped)try{this.terminal.restoreOnExit?.(this.getExitRestorePrefix(),this.getExitRestoreSuffix())}catch{}};get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(e){this.showHardwareCursor!==e&&(this.showHardwareCursor=e,e||this.hideTerminalCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(e){this.clearOnShrink=e}getFocusedComponent(){return this.focusedComponent}setFocus(e){this.setFocusInternal({component:e,overlayFocusRestore:"clear"})}setFocusInternal({component:e,overlayFocusRestore:t}){let i=this.focusedComponent,n=e,r=i?this.overlayStack.find(c=>c.component===i&&this.isOverlayVisible(c)):void 0,o=n?this.overlayStack.some(c=>c.component===n):!1,a=this.getVisibleOverlayFocusRestore();n&&!o?a.status==="blocked"&&a.blockedBy===i?a.resume.status==="focus-target"||!this.isComponentMounted(a.blockedBy)?n=this.resolveBlockedOverlayFocusResume(a):this.overlayFocusRestore={status:"blocked",overlay:a.overlay,blockedBy:n,resume:a.resume}:r&&a.status!=="inactive"&&a.overlay===r&&!this.isOverlayFocusAncestor(r,n)&&(this.overlayFocusRestore={status:"blocked",overlay:r,blockedBy:n,resume:{status:"restore-overlay"}}):n===null&&(a.status==="blocked"&&a.blockedBy===i?n=this.resolveBlockedOverlayFocusResume(a):t==="clear"&&this.clearOverlayFocusRestore()),Zn(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=n,Zn(n)&&(n.focused=!0);let l=n?this.overlayStack.find(c=>c.component===n&&this.isOverlayVisible(c)):void 0;l&&(this.overlayFocusRestore={status:"eligible",overlay:l})}clearOverlayFocusRestore(){this.overlayFocusRestore={status:"inactive"}}clearOverlayFocusRestoreFor(e){this.overlayFocusRestore.status!=="inactive"&&this.overlayFocusRestore.overlay===e&&this.clearOverlayFocusRestore()}resolveBlockedOverlayFocusResume(e){return e.resume.status==="restore-overlay"?e.overlay.component:(this.clearOverlayFocusRestore(),e.resume.target)}getVisibleOverlayFocusRestore(){let e=this.overlayFocusRestore;return e.status==="inactive"?e:!this.overlayStack.includes(e.overlay)||!this.isOverlayVisible(e.overlay)?{status:"inactive"}:e}isOverlayFocusAncestor(e,t){let i=new Set,n=e.preFocus;for(;n&&!i.has(n);){if(i.add(n),n===t)return!0;n=this.overlayStack.find(r=>r.component===n)?.preFocus??null}return!1}retargetOverlayPreFocus(e){for(let t of this.overlayStack)t!==e&&t.preFocus===e.component&&(t.preFocus=e.preFocus)}getMountedRoots(){return this.children}isComponentMounted(e){return this.getMountedRoots().some(t=>this.containsComponent(t,e))}containsComponent(e,t){return e===t?!0:e instanceof ee?e.children.some(i=>this.containsComponent(i,t)):!1}showOverlay(e,t){let i={component:e,...t===void 0?{}:{options:t},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(i),!t?.nonCapturing&&this.isOverlayVisible(i)&&this.setFocus(e),this.hideTerminalCursor(),this.requestRender(),{hide:()=>{let n=this.overlayStack.indexOf(i);if(n!==-1){if(this.clearOverlayFocusRestoreFor(i),this.retargetOverlayPreFocus(i),this.overlayStack.splice(n,1),this.focusedComponent===e){let r=this.getTopmostVisibleOverlay();this.setFocus(r?.component??i.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}},setHidden:n=>{if(i.hidden!==n){if(i.hidden=n,n){if(this.clearOverlayFocusRestoreFor(i),this.focusedComponent===e){let r=this.getTopmostVisibleOverlay();this.setFocus(r?.component??i.preFocus)}}else!t?.nonCapturing&&this.isOverlayVisible(i)&&(i.focusOrder=++this.focusOrderCounter,this.setFocus(e));this.requestRender()}},isHidden:()=>i.hidden,focus:()=>{!this.overlayStack.includes(i)||!this.isOverlayVisible(i)||(i.focusOrder=++this.focusOrderCounter,this.setFocus(e),this.requestRender())},unfocus:n=>{let r=this.focusedComponent===e,o=this.overlayFocusRestore,a=o.status!=="inactive"&&o.overlay===i;if(!(!r&&!a)){if(o.status==="blocked"&&o.overlay===i&&this.focusedComponent===o.blockedBy){n?this.overlayFocusRestore={status:"blocked",overlay:i,blockedBy:o.blockedBy,resume:{status:"focus-target",target:n.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(i),r||n){let l=this.getTopmostVisibleOverlay(),c=l&&l!==i?l.component:i.preFocus;this.setFocus(n?n.target:c)}this.requestRender()}},isFocused:()=>this.focusedComponent===e,getBounds:()=>{if(!(!this.overlayStack.includes(i)||!this.isOverlayVisible(i)||!i.bounds))return{...i.bounds}}}}hideOverlay(){let e=this.overlayStack[this.overlayStack.length-1];if(e){if(this.clearOverlayFocusRestoreFor(e),this.retargetOverlayPreFocus(e),this.overlayStack.pop(),this.focusedComponent===e.component){let t=this.getTopmostVisibleOverlay();this.setFocus(t?.component??e.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}}hideTerminalCursor(){this.stopped||this.terminal.hideCursor()}hasOverlay(){return this.overlayStack.some(e=>this.isOverlayVisible(e))}isOverlayFocused(){return this.overlayStack.some(e=>e.component===this.focusedComponent&&this.isOverlayVisible(e))}resolveMouseFocusTarget(e){for(let t=this.overlayStack.length-1;t>=0;t--){let i=this.overlayStack[t];if(this.isOverlayVisible(i)&&this.containsComponent(i.component,e))return i.component}return e}dispatchMouseToOverlay(e){for(let t=this.renderedOverlayLayouts.length-1;t>=0;t--){let i=this.renderedOverlayLayouts[t];if(e.screenX<i.col||e.screenX>=i.col+i.width||e.screenY<i.row||e.screenY>=i.row+i.height)continue;let n=tt(i.entry.component,{...e,x:e.screenX-i.col,y:e.screenY-i.row,width:i.width,height:i.height});return n?{hit:!0,result:n.focus?{...n,focusTarget:i.entry.component}:n}:{hit:!0}}return{hit:!1}}isOverlayVisible(e){return e.hidden?!1:e.options?.visible?e.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){let e;for(let t of this.overlayStack)t.options?.nonCapturing||!this.isOverlayVisible(t)||(!e||t.focusOrder>e.focusOrder)&&(e=t);return e}invalidate(){for(let e of this.getMountedRoots())e.invalidate();for(let e of this.overlayStack)e.component.invalidate()}start(){this.stopped=!1,process.off("exit",this.exitRestoreHandler),process.on("exit",this.exitRestoreHandler),this.beforeTerminalStart(),this.terminal.start(e=>this.handleTerminalInput(e),()=>this.requestRender()),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031h"),this.queryCellSize(),this.requestRender()}addInputListener(e){return this.inputListeners.add(e),()=>{this.inputListeners.delete(e)}}removeInputListener(e){this.inputListeners.delete(e)}onTerminalColorSchemeChange(e){return this.terminalColorSchemeListeners.add(e),()=>{this.terminalColorSchemeListeners.delete(e)}}setTerminalColorSchemeNotifications(e){this.terminalColorSchemeNotificationsEnabled!==e&&(this.terminalColorSchemeNotificationsEnabled=e,this.stopped||this.terminal.write(e?"\x1B[?2031h":"\x1B[?2031l"))}queryCellSize(){ae().images&&this.terminal.write("\x1B[16t")}stop(e={}){this.stopped=!0,process.off("exit",this.exitRestoreHandler),this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(e),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(e)}renderNow(e=!1){e&&this.resetRenderState(),this.renderRequested=!1,this.cancelRenderTimer(),this.lastRenderAt=ds.now(),this.doRender()}requestRender(e=!1){if(e){this.resetRenderState(),this.requestImmediateRender();return}this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}requestImmediateRender(){this.cancelRenderTimer(),this.renderRequested=!0,!this.immediateRenderScheduled&&(this.immediateRenderScheduled=!0,process.nextTick(()=>{this.immediateRenderScheduled=!1,!(this.stopped||!this.renderRequested)&&(this.cancelRenderTimer(),this.renderRequested=!1,this.lastRenderAt=ds.now(),this.doRender())}))}cancelRenderTimer(){this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0)}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let e=ds.now()-this.lastRenderAt,t=Math.max(0,s.MIN_RENDER_INTERVAL_MS-e);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=ds.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},t)}handleTerminalInput(e){if(this.consumeTerminalColorResponse(e)||this.consumeTerminalColorSchemeReport(e))return;if(this.inputListeners.size>0){let n=e;for(let r of this.inputListeners){let o=r(n);if(o?.consume)return;o?.data!==void 0&&(n=o.data)}if(n.length===0)return;e=n}if(this.consumeCellSizeResponse(e))return;if(S(e,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let t=this.overlayStack.find(n=>n.component===this.focusedComponent);if(t&&!this.isOverlayVisible(t)){let n=this.getTopmostVisibleOverlay();n?this.setFocus(n.component):this.setFocusInternal({component:t.preFocus,overlayFocusRestore:"preserve"})}if(!this.overlayStack.some(n=>n.component===this.focusedComponent)){let n=this.getVisibleOverlayFocusRestore();n.status==="eligible"?this.setFocus(n.overlay.component):n.status==="blocked"&&n.blockedBy!==this.focusedComponent&&(n.resume.status==="restore-overlay"?this.setFocus(n.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(n.resume.target)))}if(this.focusedComponent?.handleInput){if(ui(e)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(e),this.requestImmediateRender()}}consumeTerminalColorResponse(e){let t=this.pendingTerminalColorQueries[0];if(!t)return!1;if(Zu.test(e))return this.pendingTerminalColorQueries.shift(),this.completeTerminalColorQuery(t),!0;let i=ta(e);if(!i)return!1;let{target:n,rgb:r}=i,o=String(n);return!t.deliver||t.replied.has(o)||(t.replied.add(o),n==="foreground"?t.foreground=r:n==="background"?t.background=r:n<ps&&(t.palette[n]=r),t.replied.size===Xu&&this.completeTerminalColorQuery(t)),!0}terminalColorQueryResult(e){let t=e.palette.every(i=>i!==void 0)?e.palette:void 0;return{foreground:e.foreground,background:e.background,palette:t}}completeTerminalColorQuery(e){let t=e.deliver;e.deliver=void 0,clearTimeout(e.timer),t?.(this.terminalColorQueryResult(e))}consumeTerminalColorSchemeReport(e){let t=Kn(e);if(!t)return!1;for(let i of this.terminalColorSchemeListeners)i(t);return!0}consumeCellSizeResponse(e){let t=e.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!t)return!1;let i=parseInt(t[1],10),n=parseInt(t[2],10);return i<=0||n<=0||(Hn({widthPx:n,heightPx:i}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(e,t,i,n){let r=e??{},o=typeof r.margin=="number"?{top:r.margin,right:r.margin,bottom:r.margin,left:r.margin}:r.margin??{},a=Math.max(0,o.top??0),l=Math.max(0,o.right??0),c=Math.max(0,o.bottom??0),h=Math.max(0,o.left??0),u=Math.max(1,i-h-l),d=Math.max(1,n-a-c),p=ya(r.width,i)??Math.min(80,u);r.minWidth!==void 0&&(p=Math.max(p,r.minWidth)),p=Math.max(1,Math.min(p,u));let f=ya(r.maxHeight,n);f!==void 0&&(f=Math.max(1,Math.min(f,d)));let g=f!==void 0?Math.min(t,f):t,b,m;if(r.row!==void 0)if(typeof r.row=="string"){let y=r.row.match(/^(\d+(?:\.\d+)?)%$/);if(y){let w=Math.max(0,d-g),k=parseFloat(y[1])/100;b=a+Math.floor(w*k)}else b=this.resolveAnchorRow("center",g,d,a)}else b=r.row;else{let y=r.anchor??"center";b=this.resolveAnchorRow(y,g,d,a)}if(r.col!==void 0)if(typeof r.col=="string"){let y=r.col.match(/^(\d+(?:\.\d+)?)%$/);if(y){let w=Math.max(0,u-p),k=parseFloat(y[1])/100;m=h+Math.floor(w*k)}else m=this.resolveAnchorCol("center",p,u,h)}else m=r.col;else{let y=r.anchor??"center";m=this.resolveAnchorCol(y,p,u,h)}return r.offsetY!==void 0&&(b+=r.offsetY),r.offsetX!==void 0&&(m+=r.offsetX),b=Math.max(a,Math.min(b,n-c-g)),m=Math.max(h,Math.min(m,i-l-p)),{width:p,row:b,col:m,maxHeight:f}}resolveAnchorRow(e,t,i,n){switch(e){case"top-left":case"top-center":case"top-right":return n;case"bottom-left":case"bottom-center":case"bottom-right":return n+i-t;case"left-center":case"center":case"right-center":return n+Math.floor((i-t)/2)}}resolveAnchorCol(e,t,i,n){switch(e){case"top-left":case"left-center":case"bottom-left":return n;case"top-right":case"right-center":case"bottom-right":return n+i-t;case"top-center":case"center":case"bottom-center":return n+Math.floor((i-t)/2)}}compositeOverlays(e,t,i){if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],e;let n=[...e];for(let h of this.overlayStack)h.bounds=void 0;let r=[],o=n.length,a=this.overlayStack.filter(h=>this.isOverlayVisible(h));a.sort((h,u)=>h.focusOrder-u.focusOrder);for(let h of a){let{component:u,options:d}=h,{width:p,maxHeight:f}=this.resolveOverlayLayout(d,0,t,i),g=this.resolveFakeCursors(u.render(p));f!==void 0&&g.length>f&&(g=g.slice(0,f));let{row:b,col:m}=this.resolveOverlayLayout(d,g.length,t,i);h.bounds={row:b,col:m,width:p,height:g.length},r.push({entry:h,overlayLines:g,row:b,col:m,w:p}),o=Math.max(o,b+g.length)}this.renderedOverlayLayouts=r.map(({entry:h,row:u,col:d,w:p,overlayLines:f})=>({entry:h,row:u,col:d,width:p,height:f.length}));let l=Math.max(n.length,i,o);for(;n.length<l;)n.push("");let c=Math.max(0,l-i);for(let{overlayLines:h,row:u,col:d,w:p}of r)for(let f=0;f<h.length;f++){let g=c+u+f;if(g>=0&&g<n.length){let b=x(h[f])>p?H(h[f],0,p,!0):h[f];n[g]=this.compositeLineAt(n[g],b,d,p,t)}}return n}applyLineResets(e){let t=tr;for(let i=0;i<e.length;i++){let n=e[i];z(n)||(e[i]=qo(n.replaceAll(pe,""))+t)}return e}compositeLineAt(e,t,i,n,r){return He(e,t,i,n,r)}extractCursorPosition(e,t){let i=Math.max(0,e.length-t);for(let n=e.length-1;n>=i;n--){let r=e[n],o=r.indexOf(pe);if(o!==-1){let a=r.slice(0,o),l=x(a);return e[n]=r.replaceAll(pe,""),{row:n,col:l}}}return null}resolveFakeCursors(e){return e.map(t=>t.includes(er)?(this.showHardwareCursor?t.replace(ed,"$1$2"):t).replaceAll(er,"\x1B[7m").replaceAll(xa,"\x1B[27m"):t)}queryTerminalColors({timeoutMs:e,onLateReply:t}){return new Promise(i=>{let n={palette:Array.from({length:ps},()=>{}),replied:new Set,deliver:i,timer:void 0};n.timer=setTimeout(()=>{n.deliver=t,i(this.terminalColorQueryResult(n))},e),this.pendingTerminalColorQueries.push(n),this.terminal.write(Ju)})}};var va={"tui.editor.cursorUp":{defaultKeys:"up",description:"Move cursor up"},"tui.editor.cursorDown":{defaultKeys:"down",description:"Move cursor down"},"tui.editor.historyPrevious":{defaultKeys:[],description:"Select previous prompt history entry"},"tui.editor.historyNext":{defaultKeys:[],description:"Select next prompt history entry"},"tui.editor.cursorLeft":{defaultKeys:["left","ctrl+b"],description:"Move cursor left"},"tui.editor.cursorRight":{defaultKeys:["right","ctrl+f"],description:"Move cursor right"},"tui.editor.cursorWordLeft":{defaultKeys:["alt+left","ctrl+left","alt+b"],description:"Move cursor word left"},"tui.editor.cursorWordRight":{defaultKeys:["alt+right","ctrl+right","alt+f"],description:"Move cursor word right"},"tui.editor.cursorLineStart":{defaultKeys:["home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+e"],description:"Move to line end"},"tui.editor.jumpForward":{defaultKeys:"ctrl+]",description:"Jump forward to character"},"tui.editor.jumpBackward":{defaultKeys:"ctrl+alt+]",description:"Jump backward to character"},"tui.editor.pageUp":{defaultKeys:["pageUp","ctrl+pageUp"],description:"Page up"},"tui.editor.pageDown":{defaultKeys:["pageDown","ctrl+pageDown"],description:"Page down"},"tui.editor.deleteCharBackward":{defaultKeys:"backspace",description:"Delete character backward"},"tui.editor.deleteCharForward":{defaultKeys:["delete","ctrl+d"],description:"Delete character forward"},"tui.editor.deleteWordBackward":{defaultKeys:["ctrl+w","alt+backspace"],description:"Delete word backward"},"tui.editor.deleteWordForward":{defaultKeys:["alt+d","alt+delete"],description:"Delete word forward"},"tui.editor.deleteToLineStart":{defaultKeys:"ctrl+u",description:"Delete to line start"},"tui.editor.deleteToLineEnd":{defaultKeys:"ctrl+k",description:"Delete to line end"},"tui.editor.yank":{defaultKeys:"ctrl+y",description:"Yank"},"tui.editor.yankPop":{defaultKeys:"alt+y",description:"Yank pop"},"tui.editor.undo":{defaultKeys:"ctrl+-",description:"Undo"},"tui.input.newLine":{defaultKeys:["shift+enter","ctrl+j"],description:"Insert newline"},"tui.input.submit":{defaultKeys:"enter",description:"Submit input"},"tui.input.tab":{defaultKeys:"tab",description:"Tab / autocomplete"},"tui.input.copy":{defaultKeys:"ctrl+c",description:"Copy selection"},"tui.select.up":{defaultKeys:"up",description:"Move selection up"},"tui.select.down":{defaultKeys:"down",description:"Move selection down"},"tui.select.pageUp":{defaultKeys:"pageUp",description:"Selection page up"},"tui.select.pageDown":{defaultKeys:"pageDown",description:"Selection page down"},"tui.select.confirm":{defaultKeys:"enter",description:"Confirm selection"},"tui.select.cancel":{defaultKeys:["escape","ctrl+c"],description:"Cancel selection"},"tui.altScreen.pageUp":{defaultKeys:"pageUp",description:"Scroll viewport up one page"},"tui.altScreen.pageDown":{defaultKeys:"pageDown",description:"Scroll viewport down one page"},"tui.altScreen.halfPageUp":{defaultKeys:[],description:"Scroll viewport up half a page"},"tui.altScreen.halfPageDown":{defaultKeys:[],description:"Scroll viewport down half a page"},"tui.altScreen.lineUp":{defaultKeys:[],description:"Scroll viewport up one line"},"tui.altScreen.lineDown":{defaultKeys:[],description:"Scroll viewport down one line"},"tui.altScreen.previousPrompt":{defaultKeys:["ctrl+shift+up","ctrl+up"],description:"Jump to previous semantic prompt"},"tui.altScreen.nextPrompt":{defaultKeys:["ctrl+shift+down","ctrl+down"],description:"Jump to next semantic prompt"},"tui.altScreen.search":{defaultKeys:"ctrl+shift+f",description:"Search the primary scroll view"},"tui.altScreen.searchNext":{defaultKeys:["enter","ctrl+g"],description:"Select the next search match"},"tui.altScreen.searchPrevious":{defaultKeys:["shift+enter","ctrl+shift+g"],description:"Select the previous search match"},"tui.altScreen.searchClose":{defaultKeys:"escape",description:"Close transcript search"},"tui.altScreen.top":{defaultKeys:"ctrl+home",description:"Scroll viewport to top"},"tui.altScreen.bottom":{defaultKeys:"ctrl+end",description:"Scroll viewport to bottom"}};function nr(s){if(s===void 0)return[];let e=Array.isArray(s)?s:[s],t=new Set,i=[];for(let n of e)t.has(n)||(t.add(n),i.push(n));return i}var fs=class{definitions;userBindings;keysById=new Map;conflicts=[];constructor(e,t={}){this.definitions=e,this.userBindings=t,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let e=new Map;for(let[t,i]of Object.entries(this.userBindings))if(t in this.definitions)for(let n of nr(i)){let r=e.get(n)??new Set;r.add(t),e.set(n,r)}for(let[t,i]of e)i.size>1&&this.conflicts.push({key:t,keybindings:[...i]});for(let[t,i]of Object.entries(this.definitions)){let n=this.userBindings[t],r=nr(n===void 0?i.defaultKeys:n);this.keysById.set(t,r)}}matches(e,t){let i=this.keysById.get(t)??[];for(let n of i)if(S(e,n))return!0;return!1}getKeys(e){return[...this.keysById.get(e)??[]]}getDefinition(e){return this.definitions[e]}getConflicts(){return this.conflicts.map(e=>({...e,keybindings:[...e.keybindings]}))}setUserBindings(e){this.userBindings=e,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let e={};for(let t of Object.keys(this.definitions)){let i=this.keysById.get(t)??[];e[t]=i.length===1?i[0]:[...i]}return e}},rr=null;function fe(){return rr||(rr=new fs(va)),rr}function ms(s,e,t,i,n){let r;if(s.matches(e,"tui.select.pageUp"))r=-1;else if(s.matches(e,"tui.select.pageDown"))r=1;else return;return Math.max(0,Math.min(i-1,t+r*n))}var ze=class{text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(e="",t=1,i=1,n){this.text=e,this.paddingX=t,this.paddingY=i,this.customBgFn=n}setText(e){e!==this.text&&(this.text=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0)}setCustomBgFn(e){this.customBgFn=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setPaddingX(e){this.paddingX=e,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;if(!this.text||this.text.trim()===""){let d=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=d,d}let t=this.text.replace(/\t/g," "),i=Math.min(this.paddingX,Math.max(0,Math.floor((e-1)/2))),n=Math.max(1,e-i*2),r=ge(t,n),o=" ".repeat(i),a=" ".repeat(i),l=[];for(let d of r){let p=o+d+a;if(this.customBgFn)l.push(_t(p,e,this.customBgFn));else{let f=x(p),g=Math.max(0,e-f);l.push(p+" ".repeat(g))}}let c=" ".repeat(e),h=[];for(let d=0;d<this.paddingY;d++){let p=this.customBgFn?_t(c,e,this.customBgFn):c;h.push(p)}let u=[...h,...l,...h];return Tt(u),this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=u,u.length>0?u:[""]}};var Ot=class{ring=[];push(e,t){if(e)if(t.accumulate&&this.ring.length>0){let i=this.ring.pop();this.ring.push(t.prepend?e+i:i+e)}else this.ring.push(e)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let e=this.ring.pop();this.ring.unshift(e)}}get length(){return this.ring.length}};var qt=class{stack=[];push(e){this.stack.push(structuredClone(e))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}};var ka=Ct();function gs(s,e,t){if(e<=0)return 0;let i=s.slice(0,e),n=t?.segment,r=t?.isAtomicSegment,o=n?[...n(i)]:[...ka.segment(i)],a=e;for(;o.length>0&&!r?.(o[o.length-1]?.segment||"")&&ue(o[o.length-1]?.segment||"");)a-=o.pop()?.segment.length||0;if(o.length===0)return a;let l=o[o.length-1];if(r?.(l.segment))a-=l.segment.length;else if(l.isWordLike){let c=l.segment,h=[...c.matchAll(new RegExp(Dn,"g"))];if(h.length<=0)a-=c.length;else{let u=h[h.length-1];a-=c.length-(u.index+u[0].length)}}else for(;o.length>0&&!r?.(o[o.length-1]?.segment||"")&&!o[o.length-1]?.isWordLike&&!ue(o[o.length-1]?.segment||"");)a-=o.pop()?.segment.length||0;return a}function bs(s,e,t){if(e>=s.length)return s.length;let i=s.slice(e),n=t?.segment,r=t?.isAtomicSegment,a=(n?n(i):ka.segment(i))[Symbol.iterator](),l=a.next(),c=e;for(;!l.done&&!r?.(l.value.segment)&&ue(l.value.segment);)c+=l.value.segment.length,l=a.next();if(l.done)return c;if(r?.(l.value.segment))c+=l.value.segment.length;else if(l.value.isWordLike)c+=Dn.exec(l.value.segment)?.index??l.value.segment.length;else for(;!l.done&&!r?.(l.value.segment)&&!l.value.isWordLike&&!ue(l.value.segment);)c+=l.value.segment.length,l=a.next();return c}var Sa=32,Ca=2,id=10,sd=s=>s.replace(/[\r\n]+/g," ").trim(),nd=(s,e,t)=>Math.max(e,Math.min(s,t)),Ve=class{capturesViewportInput=!0;items=[];filteredItems=[];selectedIndex=0;mousePressedIndex;maxVisible=5;theme;layout;onSelect;onCancel;onSelectionChange;constructor(e,t,i,n={}){this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=i,this.layout=n}setFilter(e){this.filteredItems=this.items.filter(t=>t.value.toLowerCase().startsWith(e.toLowerCase())),this.selectedIndex=0}setSelectedIndex(e){this.selectedIndex=Math.max(0,Math.min(e,this.filteredItems.length-1))}invalidate(){}render(e){let t=[];if(this.filteredItems.length===0)return t.push(this.theme.noMatch(" No matching commands")),t;let i=this.getPrimaryColumnWidth(),{startIndex:n,endIndex:r}=this.getVisibleRange();for(let o=n;o<r;o++){let a=this.filteredItems[o];if(!a)continue;let l=o===this.selectedIndex,c=a.description?sd(a.description):void 0;t.push(this.renderItem(a,l,e,c,i))}if(n>0||r<this.filteredItems.length){let o=` (${this.selectedIndex+1}/${this.filteredItems.length})`;t.push(this.theme.scrollInfo(_(o,e-2,"")))}return t}handleMouse(e){if(this.filteredItems.length===0)return;if(e.type==="wheel"&&e.wheelDelta){let r=e.wheelDelta<0?-1:1,o=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(this.filteredItems.length-1,this.selectedIndex+r)),this.selectedIndex!==o&&this.notifySelectionChange(),{handled:!0,render:this.selectedIndex!==o}}if(e.button!=="left"||e.type!=="press"&&e.type!=="click")return;let{startIndex:t,endIndex:i}=this.getVisibleRange(),n=t+e.y;if(!(n<t||n>=i)){if(e.type==="press")return this.mousePressedIndex=n,this.selectedIndex!==n&&(this.selectedIndex=n,this.notifySelectionChange()),{handled:!0,focus:!0};if(e.type==="click"){let r=this.mousePressedIndex??n;this.mousePressedIndex=void 0;let o=this.selectedIndex!==r;this.selectedIndex=r,o&&this.notifySelectionChange();let a=this.filteredItems[this.selectedIndex];return a&&this.onSelect?.(a),{handled:!0}}}}handleInput(e){let t=fe(),i=ms(t,e,this.selectedIndex,this.filteredItems.length,this.maxVisible);if(t.matches(e,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(t.matches(e,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(i!==void 0){if(this.filteredItems.length===0||i===this.selectedIndex)return;this.selectedIndex=i,this.notifySelectionChange()}else if(t.matches(e,"tui.select.confirm")){let n=this.filteredItems[this.selectedIndex];n&&this.onSelect&&this.onSelect(n)}else t.matches(e,"tui.select.cancel")&&this.onCancel&&this.onCancel()}getVisibleRange(){let e=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible));return{startIndex:e,endIndex:Math.min(e+this.maxVisible,this.filteredItems.length)}}renderItem(e,t,i,n,r){let o=t?"\u2192 ":" ",a=x(o);if(n&&i>40){let h=Math.max(1,Math.min(r,i-a-4)),u=Math.max(1,h-Ca),d=this.truncatePrimary(e,t,u,h),p=x(d),f=" ".repeat(Math.max(1,h-p)),g=a+p+f.length,b=i-g-2;if(b>id){let m=_(n,b,"");if(t)return this.theme.selectedText(`${o}${d}${f}${m}`);let y=this.theme.description(f+m);return o+d+y}}let l=i-a-2,c=this.truncatePrimary(e,t,l,l);return t?this.theme.selectedText(`${o}${c}`):o+c}getPrimaryColumnWidth(){let{min:e,max:t}=this.getPrimaryColumnBounds(),i=this.filteredItems.reduce((n,r)=>Math.max(n,x(this.getDisplayValue(r))+Ca),0);return nd(i,e,t)}getPrimaryColumnBounds(){let e=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??Sa,t=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??Sa;return{min:Math.max(1,Math.min(e,t)),max:Math.max(1,Math.max(e,t))}}truncatePrimary(e,t,i,n){let r=this.getDisplayValue(e),o=this.layout.truncatePrimary?this.layout.truncatePrimary({text:r,maxWidth:i,columnWidth:n,item:e,isSelected:t}):_(r,i,"");return _(o,i,"")}getDisplayValue(e){return e.label||e.value}notifySelectionChange(){let e=this.filteredItems[this.selectedIndex];e&&this.onSelectionChange&&this.onSelectionChange(e)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};var Ia=St(),rd=Ct(),Ra=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,Pa=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function Dt(s){return s.length>=10&&Pa.test(s)}function od(s,e,t){if(t.size===0||!s.includes("[paste #"))return e.segment(s);let i=[];for(let a of s.matchAll(Ra)){let l=Number.parseInt(a[1],10);t.has(l)&&i.push({start:a.index,end:a.index+a[0].length})}if(i.length===0)return e.segment(s);let n=e.segment(s),r=[],o=0;for(let a of n){for(;o<i.length&&i[o].end<=a.index;)o++;let l=o<i.length?i[o]:null;if(l&&a.index>=l.start&&a.index<l.end){if(a.index===l.start){let c=s.slice(l.start,l.end);r.push({segment:c,index:l.start,input:s})}}else r.push(a)}return r}function or(s,e,t){if(!s||e<=0)return[{text:"",startIndex:0,endIndex:0}];if(x(s)<=e)return[{text:s,startIndex:0,endIndex:s.length}];let n=[],r=t??[...Ia.segment(s)],o=0,a=0,l=-1,c=0;for(let h=0;h<r.length;h++){let u=r[h],d=u.segment,p=x(d),f=u.index,g=!Dt(d)&&ue(d);if(o+p>e&&(l>=0&&o-c+p<=e?(n.push({text:s.slice(a,l),startIndex:a,endIndex:l}),a=l,o-=c):a<f&&(n.push({text:s.slice(a,f),startIndex:a,endIndex:f}),a=f,o=0),l=-1),p>e){let m=or(d,e);for(let w=0;w<m.length-1;w++){let k=m[w];n.push({text:k.text,startIndex:f+k.startIndex,endIndex:f+k.endIndex})}let y=m[m.length-1];a=f+y.startIndex,o=x(y.text),l=-1;continue}o+=p;let b=r[h+1];if(g&&b&&(Dt(b.segment)||!ue(b.segment)))l=b.index,c=o;else if(!g&&b&&!ue(b.segment)){let m=!Dt(d)&&$t.test(d),y=!Dt(b.segment)&&$t.test(b.segment);(m||y)&&(l=b.index,c=o)}}return n.push({text:s.slice(a),startIndex:a,endIndex:s.length}),n}var ad={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ld=20,$a=["@","#"],ar=new RegExp(`(?:(?!${Ji.source}).)*`,"u"),Ma=`${Zi.source}[([{<\`]*`;function Ea(s){return s.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function Aa(s){return new RegExp(`${Ma}(?:@"[^"]*|[${s.map(Ea).join("")}]${ar.source})$`,"u")}function Ta(s){let e=s.filter(t=>t!=="@").map(Ea);return new RegExp(`${Ma}(?:@(?:"[^"]*|${ar.source})|[${e.join("")}]${ar.source})$`,"u")}function _a(s,e,t){let i=Math.max(0,t),n=` ${s} ${e} more `,r=x(n);if(r+2<=i){let h=Math.floor((i-r)/2);return"\u2500".repeat(h)+n+"\u2500".repeat(i-h-r)}let o=`\u2500\u2500\u2500 ${s} ${e} more `,a=i-x(o);if(a>=0)return o+"\u2500".repeat(a);let l="...".slice(0,i),c=i-x(l);return H(o,0,c,!0)+l}var st=class{state={lines:[""],cursorLine:0,cursorCol:0};focused=!1;get capturesViewportInput(){return this.autocompleteState!==null}tui;theme;paddingX=0;lastWidth=80;renderedVisibleLineCount=1;renderedAutocompleteHeight=0;scrollOffset=0;borderColor;autocompleteProvider;autocompleteTriggerCharacters=[...$a];autocompleteTriggerPattern=Aa(this.autocompleteTriggerCharacters);autocompleteDebouncePattern=Ta(this.autocompleteTriggerCharacters);autocompleteList;autocompleteState=null;autocompletePrefix="";autocompleteMaxVisible=5;autocompleteAbort;autocompleteDebounceTimer;autocompleteRequestTask=Promise.resolve();autocompleteStartToken=0;autocompleteRequestId=0;pastes=new Map;pasteCounter=0;pasteBuffer="";isInPaste=!1;history=[];historyIndex=-1;historyDraft=null;killRing=new Ot;lastAction=null;jumpMode=null;preferredVisualCol=null;snappedFromCursorCol=null;undoStack=new qt;onSubmit;onChange;disableSubmit=!1;constructor(e,t,i={}){this.tui=e,this.theme=t,this.borderColor=t.borderColor;let n=i.paddingX??0;this.paddingX=Number.isFinite(n)?Math.max(0,Math.floor(n)):0;let r=i.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(r)?Math.max(3,Math.min(20,Math.floor(r))):5}validPasteIds(){return new Set(this.pastes.keys())}segment(e,t){return od(e,t==="word"?rd:Ia,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;this.paddingX!==t&&(this.paddingX=t,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(e){let t=Number.isFinite(e)?Math.max(3,Math.min(20,Math.floor(e))):5;this.autocompleteMaxVisible!==t&&(this.autocompleteMaxVisible=t,this.tui.requestRender())}setAutocompleteProvider(e){this.cancelAutocomplete(),this.autocompleteProvider=e,this.setAutocompleteTriggerCharacters(e.triggerCharacters??[])}addToHistory(e){let t=e.trim();t&&(this.history.length>0&&this.history[0]===t||(this.history.unshift(t),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===0}isOnLastVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===e.length-1}navigateHistory(e){if(this.lastAction=null,this.history.length===0)return;let t=this.historyIndex-e;if(!(t<-1||t>=this.history.length))if(this.historyIndex===-1&&t>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=t,this.historyIndex===-1){let i=this.historyDraft;this.historyDraft=null,i?(this.state=i,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal("")}else this.setTextInternal(this.history[this.historyIndex]||"",e===-1?"start":"end")}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(e,t="end"){let i=e.split(`
|
|
69
|
-
`);this.state.lines=i.length===0?[""]:i,this.state.cursorLine=t==="start"?0:this.state.lines.length-1,this.setCursorCol(t==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){}renderTopBorder(e,t){let i=t>0?
|
|
70
|
-
`&&e.length===1){if(this.shouldSubmitOnBackslashEnter(e,t)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(t.matches(e,"tui.input.submit")){if(this.disableSubmit)return;let n=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&&n[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(t.matches(e,"tui.editor.cursorUp")){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||this.historyIndex>-1||this.state.cursorCol===0)?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(t.matches(e,"tui.editor.cursorDown")){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(t.matches(e,"tui.editor.cursorRight")){this.moveCursor(0,1);return}if(t.matches(e,"tui.editor.cursorLeft")){this.moveCursor(0,-1);return}if(t.matches(e,"tui.editor.pageUp")){this.pageScroll(-1);return}if(t.matches(e,"tui.editor.pageDown")){this.pageScroll(1);return}if(t.matches(e,"tui.editor.jumpForward")){this.jumpMode="forward";return}if(t.matches(e,"tui.editor.jumpBackward")){this.jumpMode="backward";return}if(S(e,"shift+space")){this.insertCharacter(" ");return}let i=
|
|
68
|
+
`||s==="\x1BOM"||I(s,F.enter,0)||I(s,F.kpEnter,0):I(s,F.enter,l)||I(s,F.kpEnter,l)||ye(s,F.enter,l);case"backspace":return l===C.alt?s==="\x1B\x7F"||s==="\x1B\b"?!0:I(s,F.backspace,C.alt)||ye(s,F.backspace,C.alt):l===C.ctrl?ta(s,C.ctrl)?!0:I(s,F.backspace,C.ctrl)||ye(s,F.backspace,C.ctrl):l===0?ta(s,0)||I(s,F.backspace,0)||ye(s,F.backspace,0):I(s,F.backspace,l)||ye(s,F.backspace,l);case"insert":return l===0?oe(s,be.insert)||I(s,R.insert,0):de(s,"insert",l)?!0:I(s,R.insert,l);case"delete":return l===0?oe(s,be.delete)||I(s,R.delete,0):de(s,"delete",l)?!0:I(s,R.delete,l);case"clear":return l===0?oe(s,be.clear):de(s,"clear",l);case"home":return l===0?oe(s,be.home)||I(s,R.home,0):de(s,"home",l)?!0:I(s,R.home,l);case"end":return l===0?oe(s,be.end)||I(s,R.end,0):de(s,"end",l)?!0:I(s,R.end,l);case"pageup":return l===0?oe(s,be.pageUp)||I(s,R.pageUp,0):de(s,"pageUp",l)?!0:I(s,R.pageUp,l);case"pagedown":return l===0?oe(s,be.pageDown)||I(s,R.pageDown,0):de(s,"pageDown",l)?!0:I(s,R.pageDown,l);case"up":return l===C.alt?s==="\x1Bp"||I(s,Y.up,C.alt):l===0?oe(s,be.up)||I(s,Y.up,0):de(s,"up",l)?!0:I(s,Y.up,l);case"down":return l===C.alt?s==="\x1Bn"||I(s,Y.down,C.alt):l===0?oe(s,be.down)||I(s,Y.down,0):de(s,"down",l)?!0:I(s,Y.down,l);case"left":return l===C.alt?s==="\x1B[1;3D"||!Le&&s==="\x1BB"||s==="\x1Bb"||I(s,Y.left,C.alt):l===C.ctrl?s==="\x1B[1;5D"||de(s,"left",C.ctrl)||I(s,Y.left,C.ctrl):l===0?oe(s,be.left)||I(s,Y.left,0):de(s,"left",l)?!0:I(s,Y.left,l);case"right":return l===C.alt?s==="\x1B[1;3C"||!Le&&s==="\x1BF"||s==="\x1Bf"||I(s,Y.right,C.alt):l===C.ctrl?s==="\x1B[1;5C"||de(s,"right",C.ctrl)||I(s,Y.right,C.ctrl):l===0?oe(s,be.right)||I(s,Y.right,0):de(s,"right",l)?!0:I(s,Y.right,l);case"f1":case"f2":case"f3":case"f4":case"f5":case"f6":case"f7":case"f8":case"f9":case"f10":case"f11":case"f12":{let c=i;return l===0&&oe(s,be[c])?!0:I(s,R[c],l)}}if(i.length===1&&(i>="a"&&i<="z"||ia(i)||ss.has(i))){let c=i.charCodeAt(0),h=Ou(i),u=i>="a"&&i<="z",d=ia(i);return l===C.ctrl+C.alt&&!Le&&h&&s===`\x1B${h}`||l===C.alt&&!Le&&(u||d||ss.has(i))&&s===`\x1B${i}`?!0:l===C.ctrl?h&&s===h?!0:I(s,c,C.ctrl)||ci(s,c,C.ctrl):l===C.shift+C.ctrl?I(s,c,C.shift+C.ctrl)||ci(s,c,C.shift+C.ctrl):l===C.shift?u&&s===i.toUpperCase()?!0:I(s,c,C.shift)||ci(s,c,C.shift):l!==0?I(s,c,l)||ci(s,c,l):s===i||I(s,c,0)||ci(s,c,0)}return!1}var Du=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,Bu=C.shift|Rt;function rs(s){let e=s.match(Du);if(!e)return;let t=Number.parseInt(e[1]??"",10);if(!Number.isFinite(t))return;let i=e[2]&&e[2].length>0?Number.parseInt(e[2],10):void 0,n=e[4]?Number.parseInt(e[4],10):1,r=Number.isFinite(n)?n-1:0;if((r&~Bu)!==0||r&(C.alt|C.ctrl))return;let o=t;if(r&C.shift&&typeof i=="number"&&(o=i),o=hi(o),!(!Number.isFinite(o)||o<32)&&!(o>=_u&&o<=Iu))try{return String.fromCodePoint(o)}catch{return}}function Nu(s){let e=Un(s);if(!(!e||(e.modifier&~Rt&~C.shift)!==0)&&!(!Number.isFinite(e.codepoint)||e.codepoint<32))try{return String.fromCodePoint(e.codepoint)}catch{return}}function Kn(s){return rs(s)??Nu(s)}function Fu(s){let e=s.startsWith("#")?s.slice(1):s,t=parseInt(e.slice(0,2),16),i=parseInt(e.slice(2,4),16),n=parseInt(e.slice(4,6),16);return{r:t,g:i,b:n}}function Mt(s){if(!/^[0-9a-f]+$/i.test(s))return;let e=16**s.length-1;if(!(e<=0))return Math.round(parseInt(s,16)/e*255)}var Wu=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,Uu=/^(?:\x1b\[\?997;(1|2)n)+$/;function na(s){let e=s.match(Wu);return e?{target:e[1]==="10"?"foreground":e[1]==="11"?"background":Number.parseInt(e[2],10),rgb:Ku(e[3])}:void 0}function Ku(s){let e=s.trim();if(e.startsWith("#")){let c=e.slice(1);if(/^[0-9a-f]{6}$/i.test(c))return Fu(e);if(/^[0-9a-f]{12}$/i.test(c)){let h=Mt(c.slice(0,4)),u=Mt(c.slice(4,8)),d=Mt(c.slice(8,12));return h!==void 0&&u!==void 0&&d!==void 0?{r:h,g:u,b:d}:void 0}return}let t=e.replace(/^rgba?:/i,""),[i,n,r]=t.split("/");if(i===void 0||n===void 0||r===void 0)return;let o=Mt(i),a=Mt(n),l=Mt(r);return o!==void 0&&a!==void 0&&l!==void 0?{r:o,g:a,b:l}:void 0}function Hn(s){let e=s.match(Uu);if(e)return e[1]==="2"?"light":"dark"}import{execSync as Hu}from"node:child_process";import{homedir as zu}from"node:os";import{isAbsolute as Vu}from"node:path";import{pathToFileURL as ju}from"node:url";var os=null,ra={},ha={widthPx:9,heightPx:18};function as(){return ha}function Vn(s){ha=s}function Gu(){try{return Hu("tmux display-message -p '#{client_termfeatures}'",{encoding:"utf8",timeout:250,stdio:["ignore","pipe","ignore"]}).split(",").map(e=>e.trim()).includes("hyperlinks")}catch{return!1}}function Qu(s){let e=process.env.TERM_PROGRAM?.toLowerCase()||"",t=process.env.TERMINAL_EMULATOR?.toLowerCase()||"",i=process.env.TERM?.toLowerCase()||"",n=process.env.COLORTERM?.toLowerCase()||"",r=n==="truecolor"||n==="24bit"||i.endsWith("-direct"),o=process.platform==="win32";return process.env.TMUX||i.startsWith("tmux")?{images:null,trueColor:r,hyperlinks:s()}:i.startsWith("screen")?{images:null,trueColor:r,hyperlinks:!1}:e==="herdr"?{images:"kitty",trueColor:r,hyperlinks:!0}:e==="rex"?{images:"kitty",trueColor:!0,hyperlinks:!0}:e==="orca"&&process.env.ORCA_IMAGE_PROTOCOL==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.KITTY_WINDOW_ID||e==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:e==="ghostty"||i.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||e==="wezterm"?{images:"kitty",trueColor:!0,hyperlinks:!0}:e==="warpterminal"||process.env.WARP_SESSION_ID||process.env.WARP_TERMINAL_SESSION_UUID?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||e==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:process.env.WT_SESSION?{images:null,trueColor:!0,hyperlinks:!0}:e==="alacritty"||i.startsWith("alacritty")||process.env.ALACRITTY_WINDOW_ID||e==="vscode"||e==="zed"?{images:null,trueColor:!0,hyperlinks:!0}:t==="jetbrains-jediterm"?{images:null,trueColor:!0,hyperlinks:!1}:o?{images:null,trueColor:!0,hyperlinks:!1}:{images:null,trueColor:r,hyperlinks:!1}}function oa(s){return s==="1"?!0:s==="0"?!1:void 0}function ua(s=Gu){let e=oa(process.env.PI_HYPERLINKS),t=Qu(e===void 0?s:()=>e),i=process.env.PI_IMAGE_PROTOCOL?.toLowerCase(),n=i==="kitty"||i==="iterm2"?i:i==="none"||i==="0"?null:void 0,r=oa(process.env.PI_TRUE_COLOR);return{...t,...n!==void 0?{images:n}:{},...r!==void 0?{trueColor:r}:{},...e!==void 0?{hyperlinks:e}:{}}}function ae(){if(!os){let s=ra.hyperlinks;os={...ua(s===void 0?void 0:()=>s),...ra}}return os}function jn(s=ae()){return s.trueColor?"truecolor":"256color"}function ls(s){os=s}var Lt="\x1B_G",aa="\x1B]1337;File=";function z(s){return s.startsWith(Lt)||s.startsWith(aa)?!0:s.includes(Lt)||s.includes(aa)}function Gn(){return Math.floor(Math.random()*4294967294)+1}function da(s,e={}){let i=["a=T","f=100","q=2"];if(e.moveCursor===!1&&i.push("C=1"),e.columns&&i.push(`c=${e.columns}`),e.rows&&i.push(`r=${e.rows}`),e.imageId&&i.push(`i=${e.imageId}`),s.length<=4096)return`\x1B_G${i.join(",")};${s}\x1B\\`;let n=[],r=0,o=!0;for(;r<s.length;){let a=s.slice(r,r+4096),l=r+4096>=s.length;o?(n.push(`\x1B_G${i.join(",")},m=1;${a}\x1B\\`),o=!1):l?n.push(`\x1B_Gm=0;${a}\x1B\\`):n.push(`\x1B_Gm=1;${a}\x1B\\`),r+=4096}return n.join("")}function cs(s){return`\x1B_Ga=d,d=I,i=${s},q=2\x1B\\`}function Qn(){return"\x1B_Ga=d,d=A,q=2\x1B\\"}function Yn(){return"\x1B_Ga=d,d=a,q=2\x1B\\"}function pa(s,e={}){let t=[`inline=${e.inline!==!1?1:0}`,`size=${Buffer.byteLength(s,"base64")}`];if(e.width!==void 0&&t.push(`width=${e.width}`),e.height!==void 0&&t.push(`height=${e.height}`),e.name){let i=Buffer.from(e.name).toString("base64");t.push(`name=${i}`)}return e.preserveAspectRatio===!1&&t.push("preserveAspectRatio=0"),`\x1B]1337;File=${t.join(";")}:${s}\x07`}var Et=new Map,la=0,zn=0;function Yu(s){if(la+=1,zn=Math.max(zn,s.rows),Et.delete(s.imageId),Et.set(s.imageId,{...s,transmissionGeneration:la}),Et.size>1e3){let e=Et.keys().next().value;e!==void 0&&Et.delete(e)}}function fa(){return zn}function Xn(s){let e=/(?:^|,)i=(\d+)(?:,|$)/.exec(s)?.[1];return e===void 0?void 0:Et.get(Number.parseInt(e,10))}function Xu(s){let e=/\x1b_G([^;]*);/.exec(s)?.[1];return e===void 0?void 0:Xn(e)}function ma(s){let e=/(?:^|,)r=(\d+)(?:,|$)/.exec(s)?.[1];if(e===void 0)return;let t=Number.parseInt(e,10);return t>0?t:void 0}function Ju(s,e){return ma(s)??e}function hs(s){let e=Xu(s);if(e)return{imageId:e.imageId,columns:e.columns,rows:e.rows,widthPx:e.widthPx,heightPx:e.heightPx}}var Zu=new Set(["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function ga(s){let e=/\x1b_G([^;]*);/.exec(s)?.[1];if(e===void 0)return;let t=ma(e);return t!==void 0?t:Xn(e)?.rows}function ba(s){let e=/\x1b_G([^;]*);/.exec(s);if(!e)return;let t=Xn(e[1]);if(!t)return;let i=e.index,n=e[1],r;for(;;){let l=s.indexOf("\x1B\\",i+Lt.length);if(l===-1)return;if(r=l+2,!/(?:^|,)m=1(?:,|$)/.test(n))break;if(i=r,!s.startsWith(Lt,i))return;let c=s.indexOf(";",i+Lt.length);if(c===-1)return;n=s.slice(i+Lt.length,c)}let a=`\x1B_Ga=p,q=2,${e[1].split(",").filter(l=>Zu.has(l.split("=",1)[0]??"")).join(",")}\x1B\\`;return{imageId:t.imageId,transmissionGeneration:t.transmissionGeneration,transmissionBytes:r-e.index,estimatedDecodedBytes:t.widthPx*t.heightPx*4,rows:Ju(e[1],t.rows),sequence:a,replacementLine:`${s.slice(0,e.index)}${a}${s.slice(r)}`}}function Jn(s,e,t){let i=hs(s),n=/\x1b_G([^;]*);/.exec(s);if(!i||!n||e<0||e>=i.rows||t<=0)return s;let r=Math.min(t,i.rows-e);if(e===0&&r===i.rows)return s;let o=Math.floor(i.heightPx*e/i.rows),a=Math.ceil(i.heightPx*(e+r)/i.rows),l=Math.max(1,Math.min(i.heightPx,a)-o),c=n[1].split(",").filter(h=>!/^[yhr]=/.test(h));return c.push(`y=${o}`,`h=${l}`,`r=${r}`),`${s.slice(0,n.index)}\x1B_G${c.join(",")};${s.slice(n.index+n[0].length)}`}function ca(s,e){if(s<=1)return s;let t=s-1,i=Math.max(s/e,e/s);return Math.max(t/e,e/t)<i?t:s}function ed(s,e,t,i={widthPx:9,heightPx:18},n=!1){let r=Math.max(1,Math.floor(e)),o=t===void 0?void 0:Math.max(1,Math.floor(t)),a=Math.max(1,s.widthPx),l=Math.max(1,s.heightPx),c=r*i.widthPx/a,h=o===void 0?c:o*i.heightPx/l,u=Math.min(c,h),d=a*u,p=l*u,f=Math.max(1,Math.min(r,Math.ceil(d/i.widthPx))),m=p/i.heightPx,b=Math.max(1,Math.ceil(m));if(o!==void 0&&(b=Math.min(o,b)),!n)return{columns:f,rows:b};if(c<=h){let g=f*i.widthPx*l/(a*i.heightPx);b=ca(b,g)}else{let g=b*i.heightPx*a/(l*i.widthPx);f=ca(f,g)}return{columns:f,rows:b}}function us(s){try{let e=Buffer.from(s,"base64");if(e.length<24||e[0]!==137||e[1]!==80||e[2]!==78||e[3]!==71)return null;let t=e.readUInt32BE(16),i=e.readUInt32BE(20);return{widthPx:t,heightPx:i}}catch{return null}}function ya(s){try{let e=Buffer.from(s,"base64");if(e.length<2||e[0]!==255||e[1]!==216)return null;let t=2;for(;t<e.length-9;){if(e[t]!==255){t++;continue}let i=e[t+1];if(i>=192&&i<=194){let r=e.readUInt16BE(t+5);return{widthPx:e.readUInt16BE(t+7),heightPx:r}}if(t+3>=e.length)return null;let n=e.readUInt16BE(t+2);if(n<2)return null;t+=2+n}return null}catch{return null}}function wa(s){try{let e=Buffer.from(s,"base64");if(e.length<10)return null;let t=e.slice(0,6).toString("ascii");if(t!=="GIF87a"&&t!=="GIF89a")return null;let i=e.readUInt16LE(6),n=e.readUInt16LE(8);return{widthPx:i,heightPx:n}}catch{return null}}function xa(s){try{let e=Buffer.from(s,"base64");if(e.length<30)return null;let t=e.slice(0,4).toString("ascii"),i=e.slice(8,12).toString("ascii");if(t!=="RIFF"||i!=="WEBP")return null;let n=e.slice(12,16).toString("ascii");if(n==="VP8 "){if(e.length<30)return null;let r=e.readUInt16LE(26)&16383,o=e.readUInt16LE(28)&16383;return{widthPx:r,heightPx:o}}else if(n==="VP8L"){if(e.length<25)return null;let r=e.readUInt32LE(21),o=(r&16383)+1,a=(r>>14&16383)+1;return{widthPx:o,heightPx:a}}else if(n==="VP8X"){if(e.length<30)return null;let r=(e[24]|e[25]<<8|e[26]<<16)+1,o=(e[27]|e[28]<<8|e[29]<<16)+1;return{widthPx:r,heightPx:o}}return null}catch{return null}}function Zn(s,e){return e==="image/png"?us(s):e==="image/jpeg"?ya(s):e==="image/gif"?wa(s):e==="image/webp"?xa(s):null}function er(s,e,t={}){let i=ae();if(!i.images)return null;let n=t.maxWidthCells??80,r=ed(e,n,t.maxHeightCells,as(),i.images==="kitty");return i.images==="kitty"?(t.imageId!==void 0&&Yu({imageId:t.imageId,columns:r.columns,rows:r.rows,widthPx:e.widthPx,heightPx:e.heightPx}),{sequence:da(s,{columns:r.columns,rows:r.rows,imageId:t.imageId,moveCursor:t.moveCursor}),columns:r.columns,rows:r.rows,imageId:t.imageId}):i.images==="iterm2"?{sequence:pa(s,{width:r.columns,height:"auto",preserveAspectRatio:t.preserveAspectRatio??!0}),columns:r.columns,rows:r.rows}:null}function ds(s,e){return`\x1B]8;;${e}\x1B\\${s}\x1B]8;;\x1B\\`}function td(s){let e=zu();return e&&(s===e||s.startsWith(`${e}/`)||s.startsWith(`${e}\\`))?`~${s.slice(e.length)}`:s}function ps(s,e,t){let i=[];if(t){let n=td(t);ae().hyperlinks&&Vu(t)?i.push(ds(n,ju(t).href)):i.push(n)}return i.push(`[${s}]`),e&&i.push(`${e.widthPx}x${e.heightPx}`),`[Image: ${i.join(" ")}]`}function tt(s,e){let t=s.handleMouse?.(e);if(t){if("target"in t){let i=t;return i.focus&&s.handleInput?{...i,focusTarget:s}:i}if(!(!t.handled&&!t.capture&&!t.focus))return{...t,handled:!0,...t.focus?{focusTarget:s}:{},target:{component:s,originX:e.screenX-e.x,originY:e.screenY-e.y,width:e.width,height:e.height}}}}function ka(s,e){return{...s,x:s.screenX-e.originX,y:s.screenY-e.originY,width:e.width,height:e.height}}var ms=16,id=2+ms,sd=`\x1B]10;?\x07\x1B]11;?\x07${Array.from({length:ms},(s,e)=>`\x1B]4;${e};?\x07`).join("")}\x1B[c`,nd=/^\x1b\[\?[\d;]*c$/;function tr(s){return s!==null&&"focused"in s}var pe="\x1B_pi:c\x07",ir="\x1B_pi:fc\x07",Sa="\x1B_pi:/fc\x07",rd=/(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;function it(s){return`${ir}${s}${Sa}`}function va(s,e){if(s===void 0)return;if(typeof s=="number")return s;let t=s.match(/^(\d+(?:\.\d+)?)%$/);if(t)return Math.floor(e*parseFloat(t[1])/100)}var ee=class{children=[];mouseLayout;addChild(e){this.children.push(e)}removeChild(e){let t=this.children.indexOf(e);t!==-1&&this.children.splice(t,1)}clear(){this.children=[]}invalidate(){for(let e of this.children)e.invalidate?.()}handleMouse(e){if(e.y<0||e.y>=e.height)return;let t=this.mouseLayout?.width===e.width?this.mouseLayout.children:this.children.map(n=>({component:n,height:n.render(e.width).length})),i=0;for(let{component:n,height:r}of t){if(e.y>=i&&e.y<i+r){let o=tt(n,{...e,y:e.y-i,height:r});return o?.focus&&this.handleInput?{...o,focusTarget:this}:o}i+=r}}render(e){let t=[],i=[];for(let n of this.children){let r=n.render(e);i.push({component:n,height:r.length});for(let o of r)t.push(o)}return this.mouseLayout={width:e,children:i},t}},sr="\x1B[0m\x1B]8;;\x07";function He(s,e,t,i,n){if(z(s))return s;let r=t+i,o=Ko(s,t,r,n-r,!0),a=Fn(e,0,i,!0),l=Math.max(0,t-o.beforeWidth),c=Math.max(0,i-a.width),h=Math.max(t,o.beforeWidth),u=Math.max(i,a.width),d=Math.max(0,n-h-u),p=Math.max(0,d-o.afterWidth),f=o.before+" ".repeat(l)+sr+a.text+" ".repeat(c)+sr+o.after+" ".repeat(p);return x(f)<=n?f:H(f,0,n,!0)}var nr=Symbol.for("@earendil-works/pi-tui/viewport");function rr(s){return s[nr]===!0}var pi=class s extends ee{terminal;focusedComponent=null;inputListeners=new Set;onDebug;renderRequested=!1;immediateRenderScheduled=!1;renderTimer;lastRenderAt=0;static MIN_RENDER_INTERVAL_MS=16;showHardwareCursor=!1;clearOnShrink=!1;fullRedrawCount=0;stopped=!1;pendingTerminalColorQueries=[];terminalColorSchemeListeners=new Set;terminalColorSchemeNotificationsEnabled=!1;logDirectory;focusOrderCounter=0;overlayStack=[];renderedOverlayLayouts=[];get hasOverlayEntries(){return this.overlayStack.length>0}overlayFocusRestore={status:"inactive"};constructor(e,t,i){super(),this.terminal=e,this.logDirectory=i,t!==void 0&&(this.showHardwareCursor=t)}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(e){}afterTerminalStop(e){}getExitRestorePrefix(){return`${this.terminalColorSchemeNotificationsEnabled?"\x1B[?2031l":""}\x1B[?25h`}getExitRestoreSuffix(){return""}exitRestoreHandler=()=>{if(!this.stopped)try{this.terminal.restoreOnExit?.(this.getExitRestorePrefix(),this.getExitRestoreSuffix())}catch{}};get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(e){this.showHardwareCursor!==e&&(this.showHardwareCursor=e,e||this.hideTerminalCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(e){this.clearOnShrink=e}getFocusedComponent(){return this.focusedComponent}setFocus(e){this.setFocusInternal({component:e,overlayFocusRestore:"clear"})}setFocusInternal({component:e,overlayFocusRestore:t}){let i=this.focusedComponent,n=e,r=i?this.overlayStack.find(c=>c.component===i&&this.isOverlayVisible(c)):void 0,o=n?this.overlayStack.some(c=>c.component===n):!1,a=this.getVisibleOverlayFocusRestore();n&&!o?a.status==="blocked"&&a.blockedBy===i?a.resume.status==="focus-target"||!this.isComponentMounted(a.blockedBy)?n=this.resolveBlockedOverlayFocusResume(a):this.overlayFocusRestore={status:"blocked",overlay:a.overlay,blockedBy:n,resume:a.resume}:r&&a.status!=="inactive"&&a.overlay===r&&!this.isOverlayFocusAncestor(r,n)&&(this.overlayFocusRestore={status:"blocked",overlay:r,blockedBy:n,resume:{status:"restore-overlay"}}):n===null&&(a.status==="blocked"&&a.blockedBy===i?n=this.resolveBlockedOverlayFocusResume(a):t==="clear"&&this.clearOverlayFocusRestore()),tr(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=n,tr(n)&&(n.focused=!0);let l=n?this.overlayStack.find(c=>c.component===n&&this.isOverlayVisible(c)):void 0;l&&(this.overlayFocusRestore={status:"eligible",overlay:l})}clearOverlayFocusRestore(){this.overlayFocusRestore={status:"inactive"}}clearOverlayFocusRestoreFor(e){this.overlayFocusRestore.status!=="inactive"&&this.overlayFocusRestore.overlay===e&&this.clearOverlayFocusRestore()}resolveBlockedOverlayFocusResume(e){return e.resume.status==="restore-overlay"?e.overlay.component:(this.clearOverlayFocusRestore(),e.resume.target)}getVisibleOverlayFocusRestore(){let e=this.overlayFocusRestore;return e.status==="inactive"?e:!this.overlayStack.includes(e.overlay)||!this.isOverlayVisible(e.overlay)?{status:"inactive"}:e}isOverlayFocusAncestor(e,t){let i=new Set,n=e.preFocus;for(;n&&!i.has(n);){if(i.add(n),n===t)return!0;n=this.overlayStack.find(r=>r.component===n)?.preFocus??null}return!1}retargetOverlayPreFocus(e){for(let t of this.overlayStack)t!==e&&t.preFocus===e.component&&(t.preFocus=e.preFocus)}getMountedRoots(){return this.children}isComponentMounted(e){return this.getMountedRoots().some(t=>this.containsComponent(t,e))}containsComponent(e,t){return e===t?!0:e instanceof ee?e.children.some(i=>this.containsComponent(i,t)):!1}showOverlay(e,t){let i={component:e,...t===void 0?{}:{options:t},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(i),!t?.nonCapturing&&this.isOverlayVisible(i)&&this.setFocus(e),this.hideTerminalCursor(),this.requestRender(),{hide:()=>{let n=this.overlayStack.indexOf(i);if(n!==-1){if(this.clearOverlayFocusRestoreFor(i),this.retargetOverlayPreFocus(i),this.overlayStack.splice(n,1),this.focusedComponent===e){let r=this.getTopmostVisibleOverlay();this.setFocus(r?.component??i.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}},setHidden:n=>{if(i.hidden!==n){if(i.hidden=n,n){if(this.clearOverlayFocusRestoreFor(i),this.focusedComponent===e){let r=this.getTopmostVisibleOverlay();this.setFocus(r?.component??i.preFocus)}}else!t?.nonCapturing&&this.isOverlayVisible(i)&&(i.focusOrder=++this.focusOrderCounter,this.setFocus(e));this.requestRender()}},isHidden:()=>i.hidden,focus:()=>{!this.overlayStack.includes(i)||!this.isOverlayVisible(i)||(i.focusOrder=++this.focusOrderCounter,this.setFocus(e),this.requestRender())},unfocus:n=>{let r=this.focusedComponent===e,o=this.overlayFocusRestore,a=o.status!=="inactive"&&o.overlay===i;if(!(!r&&!a)){if(o.status==="blocked"&&o.overlay===i&&this.focusedComponent===o.blockedBy){n?this.overlayFocusRestore={status:"blocked",overlay:i,blockedBy:o.blockedBy,resume:{status:"focus-target",target:n.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(i),r||n){let l=this.getTopmostVisibleOverlay(),c=l&&l!==i?l.component:i.preFocus;this.setFocus(n?n.target:c)}this.requestRender()}},isFocused:()=>this.focusedComponent===e,getBounds:()=>{if(!(!this.overlayStack.includes(i)||!this.isOverlayVisible(i)||!i.bounds))return{...i.bounds}}}}hideOverlay(){let e=this.overlayStack[this.overlayStack.length-1];if(e){if(this.clearOverlayFocusRestoreFor(e),this.retargetOverlayPreFocus(e),this.overlayStack.pop(),this.focusedComponent===e.component){let t=this.getTopmostVisibleOverlay();this.setFocus(t?.component??e.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}}hideTerminalCursor(){this.stopped||this.terminal.hideCursor()}hasOverlay(){return this.overlayStack.some(e=>this.isOverlayVisible(e))}isOverlayFocused(){return this.overlayStack.some(e=>e.component===this.focusedComponent&&this.isOverlayVisible(e))}resolveMouseFocusTarget(e){for(let t=this.overlayStack.length-1;t>=0;t--){let i=this.overlayStack[t];if(this.isOverlayVisible(i)&&this.containsComponent(i.component,e))return i.component}return e}dispatchMouseToOverlay(e){for(let t=this.renderedOverlayLayouts.length-1;t>=0;t--){let i=this.renderedOverlayLayouts[t];if(e.screenX<i.col||e.screenX>=i.col+i.width||e.screenY<i.row||e.screenY>=i.row+i.height)continue;let n=tt(i.entry.component,{...e,x:e.screenX-i.col,y:e.screenY-i.row,width:i.width,height:i.height});return n?{hit:!0,result:n.focus?{...n,focusTarget:i.entry.component}:n}:{hit:!0}}return{hit:!1}}isOverlayVisible(e){return e.hidden?!1:e.options?.visible?e.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){let e;for(let t of this.overlayStack)t.options?.nonCapturing||!this.isOverlayVisible(t)||(!e||t.focusOrder>e.focusOrder)&&(e=t);return e}invalidate(){for(let e of this.getMountedRoots())e.invalidate();for(let e of this.overlayStack)e.component.invalidate()}start(){this.stopped=!1,process.off("exit",this.exitRestoreHandler),process.on("exit",this.exitRestoreHandler),this.beforeTerminalStart(),this.terminal.start(e=>this.handleTerminalInput(e),()=>this.requestRender()),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031h"),this.queryCellSize(),this.requestRender()}addInputListener(e){return this.inputListeners.add(e),()=>{this.inputListeners.delete(e)}}removeInputListener(e){this.inputListeners.delete(e)}onTerminalColorSchemeChange(e){return this.terminalColorSchemeListeners.add(e),()=>{this.terminalColorSchemeListeners.delete(e)}}setTerminalColorSchemeNotifications(e){this.terminalColorSchemeNotificationsEnabled!==e&&(this.terminalColorSchemeNotificationsEnabled=e,this.stopped||this.terminal.write(e?"\x1B[?2031h":"\x1B[?2031l"))}queryCellSize(){ae().images&&this.terminal.write("\x1B[16t")}stop(e={}){this.stopped=!0,process.off("exit",this.exitRestoreHandler),this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(e),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(e)}renderNow(e=!1){e&&this.resetRenderState(),this.renderRequested=!1,this.cancelRenderTimer(),this.lastRenderAt=fs.now(),this.doRender()}requestRender(e=!1){if(e){this.resetRenderState(),this.requestImmediateRender();return}this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}requestImmediateRender(){this.cancelRenderTimer(),this.renderRequested=!0,!this.immediateRenderScheduled&&(this.immediateRenderScheduled=!0,process.nextTick(()=>{this.immediateRenderScheduled=!1,!(this.stopped||!this.renderRequested)&&(this.cancelRenderTimer(),this.renderRequested=!1,this.lastRenderAt=fs.now(),this.doRender())}))}cancelRenderTimer(){this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0)}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let e=fs.now()-this.lastRenderAt,t=Math.max(0,s.MIN_RENDER_INTERVAL_MS-e);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=fs.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},t)}handleTerminalInput(e){if(this.consumeTerminalColorResponse(e)||this.consumeTerminalColorSchemeReport(e))return;if(this.inputListeners.size>0){let n=e;for(let r of this.inputListeners){let o=r(n);if(o?.consume)return;o?.data!==void 0&&(n=o.data)}if(n.length===0)return;e=n}if(this.consumeCellSizeResponse(e))return;if(S(e,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let t=this.overlayStack.find(n=>n.component===this.focusedComponent);if(t&&!this.isOverlayVisible(t)){let n=this.getTopmostVisibleOverlay();n?this.setFocus(n.component):this.setFocusInternal({component:t.preFocus,overlayFocusRestore:"preserve"})}if(!this.overlayStack.some(n=>n.component===this.focusedComponent)){let n=this.getVisibleOverlayFocusRestore();n.status==="eligible"?this.setFocus(n.overlay.component):n.status==="blocked"&&n.blockedBy!==this.focusedComponent&&(n.resume.status==="restore-overlay"?this.setFocus(n.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(n.resume.target)))}if(this.focusedComponent?.handleInput){if(di(e)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(e),this.requestImmediateRender()}}consumeTerminalColorResponse(e){let t=this.pendingTerminalColorQueries[0];if(!t)return!1;if(nd.test(e))return this.pendingTerminalColorQueries.shift(),this.completeTerminalColorQuery(t),!0;let i=na(e);if(!i)return!1;let{target:n,rgb:r}=i,o=String(n);return!t.deliver||t.replied.has(o)||(t.replied.add(o),n==="foreground"?t.foreground=r:n==="background"?t.background=r:n<ms&&(t.palette[n]=r),t.replied.size===id&&this.completeTerminalColorQuery(t)),!0}terminalColorQueryResult(e){let t=e.palette.every(i=>i!==void 0)?e.palette:void 0;return{foreground:e.foreground,background:e.background,palette:t}}completeTerminalColorQuery(e){let t=e.deliver;e.deliver=void 0,clearTimeout(e.timer),t?.(this.terminalColorQueryResult(e))}consumeTerminalColorSchemeReport(e){let t=Hn(e);if(!t)return!1;for(let i of this.terminalColorSchemeListeners)i(t);return!0}consumeCellSizeResponse(e){let t=e.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!t)return!1;let i=parseInt(t[1],10),n=parseInt(t[2],10);return i<=0||n<=0||(Vn({widthPx:n,heightPx:i}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(e,t,i,n){let r=e??{},o=typeof r.margin=="number"?{top:r.margin,right:r.margin,bottom:r.margin,left:r.margin}:r.margin??{},a=Math.max(0,o.top??0),l=Math.max(0,o.right??0),c=Math.max(0,o.bottom??0),h=Math.max(0,o.left??0),u=Math.max(1,i-h-l),d=Math.max(1,n-a-c),p=va(r.width,i)??Math.min(80,u);r.minWidth!==void 0&&(p=Math.max(p,r.minWidth)),p=Math.max(1,Math.min(p,u));let f=va(r.maxHeight,n);f!==void 0&&(f=Math.max(1,Math.min(f,d)));let m=f!==void 0?Math.min(t,f):t,b,g;if(r.row!==void 0)if(typeof r.row=="string"){let y=r.row.match(/^(\d+(?:\.\d+)?)%$/);if(y){let w=Math.max(0,d-m),k=parseFloat(y[1])/100;b=a+Math.floor(w*k)}else b=this.resolveAnchorRow("center",m,d,a)}else b=r.row;else{let y=r.anchor??"center";b=this.resolveAnchorRow(y,m,d,a)}if(r.col!==void 0)if(typeof r.col=="string"){let y=r.col.match(/^(\d+(?:\.\d+)?)%$/);if(y){let w=Math.max(0,u-p),k=parseFloat(y[1])/100;g=h+Math.floor(w*k)}else g=this.resolveAnchorCol("center",p,u,h)}else g=r.col;else{let y=r.anchor??"center";g=this.resolveAnchorCol(y,p,u,h)}return r.offsetY!==void 0&&(b+=r.offsetY),r.offsetX!==void 0&&(g+=r.offsetX),b=Math.max(a,Math.min(b,n-c-m)),g=Math.max(h,Math.min(g,i-l-p)),{width:p,row:b,col:g,maxHeight:f}}resolveAnchorRow(e,t,i,n){switch(e){case"top-left":case"top-center":case"top-right":return n;case"bottom-left":case"bottom-center":case"bottom-right":return n+i-t;case"left-center":case"center":case"right-center":return n+Math.floor((i-t)/2)}}resolveAnchorCol(e,t,i,n){switch(e){case"top-left":case"left-center":case"bottom-left":return n;case"top-right":case"right-center":case"bottom-right":return n+i-t;case"top-center":case"center":case"bottom-center":return n+Math.floor((i-t)/2)}}compositeOverlays(e,t,i){if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],e;let n=[...e];for(let h of this.overlayStack)h.bounds=void 0;let r=[],o=n.length,a=this.overlayStack.filter(h=>this.isOverlayVisible(h));a.sort((h,u)=>h.focusOrder-u.focusOrder);for(let h of a){let{component:u,options:d}=h,{width:p,maxHeight:f}=this.resolveOverlayLayout(d,0,t,i),m=this.resolveFakeCursors(u.render(p));f!==void 0&&m.length>f&&(m=m.slice(0,f));let{row:b,col:g}=this.resolveOverlayLayout(d,m.length,t,i);h.bounds={row:b,col:g,width:p,height:m.length},r.push({entry:h,overlayLines:m,row:b,col:g,w:p}),o=Math.max(o,b+m.length)}this.renderedOverlayLayouts=r.map(({entry:h,row:u,col:d,w:p,overlayLines:f})=>({entry:h,row:u,col:d,width:p,height:f.length}));let l=Math.max(n.length,i,o);for(;n.length<l;)n.push("");let c=Math.max(0,l-i);for(let{overlayLines:h,row:u,col:d,w:p}of r)for(let f=0;f<h.length;f++){let m=c+u+f;if(m>=0&&m<n.length){let b=x(h[f])>p?H(h[f],0,p,!0):h[f];n[m]=this.compositeLineAt(n[m],b,d,p,t)}}return n}applyLineResets(e){let t=sr;for(let i=0;i<e.length;i++){let n=e[i];z(n)||(e[i]=No(n.replaceAll(pe,""))+t)}return e}compositeLineAt(e,t,i,n,r){return He(e,t,i,n,r)}extractCursorPosition(e,t){let i=Math.max(0,e.length-t);for(let n=e.length-1;n>=i;n--){let r=e[n],o=r.indexOf(pe);if(o!==-1){let a=r.slice(0,o),l=x(a);return e[n]=r.replaceAll(pe,""),{row:n,col:l}}}return null}resolveFakeCursors(e){return e.map(t=>t.includes(ir)?(this.showHardwareCursor?t.replace(rd,"$1$2"):t).replaceAll(ir,"\x1B[7m").replaceAll(Sa,"\x1B[27m"):t)}queryTerminalColors({timeoutMs:e,onLateReply:t}){return new Promise(i=>{let n={palette:Array.from({length:ms},()=>{}),replied:new Set,deliver:i,timer:void 0};n.timer=setTimeout(()=>{n.deliver=t,i(this.terminalColorQueryResult(n))},e),this.pendingTerminalColorQueries.push(n),this.terminal.write(sd)})}};var Ca={"tui.editor.cursorUp":{defaultKeys:"up",description:"Move cursor up"},"tui.editor.cursorDown":{defaultKeys:"down",description:"Move cursor down"},"tui.editor.historyPrevious":{defaultKeys:[],description:"Select previous prompt history entry"},"tui.editor.historyNext":{defaultKeys:[],description:"Select next prompt history entry"},"tui.editor.cursorLeft":{defaultKeys:["left","ctrl+b"],description:"Move cursor left"},"tui.editor.cursorRight":{defaultKeys:["right","ctrl+f"],description:"Move cursor right"},"tui.editor.cursorWordLeft":{defaultKeys:["alt+left","ctrl+left","alt+b"],description:"Move cursor word left"},"tui.editor.cursorWordRight":{defaultKeys:["alt+right","ctrl+right","alt+f"],description:"Move cursor word right"},"tui.editor.cursorLineStart":{defaultKeys:["home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+e"],description:"Move to line end"},"tui.editor.jumpForward":{defaultKeys:"ctrl+]",description:"Jump forward to character"},"tui.editor.jumpBackward":{defaultKeys:"ctrl+alt+]",description:"Jump backward to character"},"tui.editor.pageUp":{defaultKeys:["pageUp","ctrl+pageUp"],description:"Page up"},"tui.editor.pageDown":{defaultKeys:["pageDown","ctrl+pageDown"],description:"Page down"},"tui.editor.deleteCharBackward":{defaultKeys:"backspace",description:"Delete character backward"},"tui.editor.deleteCharForward":{defaultKeys:["delete","ctrl+d"],description:"Delete character forward"},"tui.editor.deleteWordBackward":{defaultKeys:["ctrl+w","alt+backspace"],description:"Delete word backward"},"tui.editor.deleteWordForward":{defaultKeys:["alt+d","alt+delete"],description:"Delete word forward"},"tui.editor.deleteToLineStart":{defaultKeys:"ctrl+u",description:"Delete to line start"},"tui.editor.deleteToLineEnd":{defaultKeys:"ctrl+k",description:"Delete to line end"},"tui.editor.yank":{defaultKeys:"ctrl+y",description:"Yank"},"tui.editor.yankPop":{defaultKeys:"alt+y",description:"Yank pop"},"tui.editor.undo":{defaultKeys:"ctrl+-",description:"Undo"},"tui.input.newLine":{defaultKeys:["shift+enter","ctrl+j"],description:"Insert newline"},"tui.input.submit":{defaultKeys:"enter",description:"Submit input"},"tui.input.tab":{defaultKeys:"tab",description:"Tab / autocomplete"},"tui.input.copy":{defaultKeys:"ctrl+c",description:"Copy selection"},"tui.select.up":{defaultKeys:"up",description:"Move selection up"},"tui.select.down":{defaultKeys:"down",description:"Move selection down"},"tui.select.pageUp":{defaultKeys:"pageUp",description:"Selection page up"},"tui.select.pageDown":{defaultKeys:"pageDown",description:"Selection page down"},"tui.select.confirm":{defaultKeys:"enter",description:"Confirm selection"},"tui.select.cancel":{defaultKeys:["escape","ctrl+c"],description:"Cancel selection"},"tui.altScreen.pageUp":{defaultKeys:"pageUp",description:"Scroll viewport up one page"},"tui.altScreen.pageDown":{defaultKeys:"pageDown",description:"Scroll viewport down one page"},"tui.altScreen.halfPageUp":{defaultKeys:[],description:"Scroll viewport up half a page"},"tui.altScreen.halfPageDown":{defaultKeys:[],description:"Scroll viewport down half a page"},"tui.altScreen.lineUp":{defaultKeys:[],description:"Scroll viewport up one line"},"tui.altScreen.lineDown":{defaultKeys:[],description:"Scroll viewport down one line"},"tui.altScreen.previousPrompt":{defaultKeys:["ctrl+shift+up","ctrl+up"],description:"Jump to previous semantic prompt"},"tui.altScreen.nextPrompt":{defaultKeys:["ctrl+shift+down","ctrl+down"],description:"Jump to next semantic prompt"},"tui.altScreen.search":{defaultKeys:"ctrl+shift+f",description:"Search the primary scroll view"},"tui.altScreen.searchNext":{defaultKeys:["enter","ctrl+g"],description:"Select the next search match"},"tui.altScreen.searchPrevious":{defaultKeys:["shift+enter","ctrl+shift+g"],description:"Select the previous search match"},"tui.altScreen.searchClose":{defaultKeys:"escape",description:"Close transcript search"},"tui.altScreen.top":{defaultKeys:"ctrl+home",description:"Scroll viewport to top"},"tui.altScreen.bottom":{defaultKeys:"ctrl+end",description:"Scroll viewport to bottom"}};function or(s){if(s===void 0)return[];let e=Array.isArray(s)?s:[s],t=new Set,i=[];for(let n of e)t.has(n)||(t.add(n),i.push(n));return i}var gs=class{definitions;userBindings;keysById=new Map;conflicts=[];constructor(e,t={}){this.definitions=e,this.userBindings=t,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let e=new Map;for(let[t,i]of Object.entries(this.userBindings))if(t in this.definitions)for(let n of or(i)){let r=e.get(n)??new Set;r.add(t),e.set(n,r)}for(let[t,i]of e)i.size>1&&this.conflicts.push({key:t,keybindings:[...i]});for(let[t,i]of Object.entries(this.definitions)){let n=this.userBindings[t],r=or(n===void 0?i.defaultKeys:n);this.keysById.set(t,r)}}matches(e,t){let i=this.keysById.get(t)??[];for(let n of i)if(S(e,n))return!0;return!1}getKeys(e){return[...this.keysById.get(e)??[]]}getDefinition(e){return this.definitions[e]}getConflicts(){return this.conflicts.map(e=>({...e,keybindings:[...e.keybindings]}))}setUserBindings(e){this.userBindings=e,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let e={};for(let t of Object.keys(this.definitions)){let i=this.keysById.get(t)??[];e[t]=i.length===1?i[0]:[...i]}return e}},ar=null;function fe(){return ar||(ar=new gs(Ca)),ar}function bs(s,e,t,i,n){let r;if(s.matches(e,"tui.select.pageUp"))r=-1;else if(s.matches(e,"tui.select.pageDown"))r=1;else return;return Math.max(0,Math.min(i-1,t+r*n))}var ze=class{text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(e="",t=1,i=1,n){this.text=e,this.paddingX=t,this.paddingY=i,this.customBgFn=n}setText(e){e!==this.text&&(this.text=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0)}setCustomBgFn(e){this.customBgFn=e,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}setPaddingX(e){this.paddingX=e,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;if(!this.text||this.text.trim()===""){let d=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=d,d}let t=this.text.replace(/\t/g," "),i=Math.min(this.paddingX,Math.max(0,Math.floor((e-1)/2))),n=Math.max(1,e-i*2),r=ge(t,n),o=" ".repeat(i),a=" ".repeat(i),l=[];for(let d of r){let p=o+d+a;if(this.customBgFn)l.push(_t(p,e,this.customBgFn));else{let f=x(p),m=Math.max(0,e-f);l.push(p+" ".repeat(m))}}let c=" ".repeat(e),h=[];for(let d=0;d<this.paddingY;d++){let p=this.customBgFn?_t(c,e,this.customBgFn):c;h.push(p)}let u=[...h,...l,...h];return Tt(u),this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=u,u.length>0?u:[""]}};var Ot=class{ring=[];push(e,t){if(e)if(t.accumulate&&this.ring.length>0){let i=this.ring.pop();this.ring.push(t.prepend?e+i:i+e)}else this.ring.push(e)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let e=this.ring.pop();this.ring.unshift(e)}}get length(){return this.ring.length}};var qt=class{stack=[];push(e){this.stack.push(structuredClone(e))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}};var $a=Ct();function ys(s,e,t){if(e<=0)return 0;let i=s.slice(0,e),n=t?.segment,r=t?.isAtomicSegment,o=n?[...n(i)]:[...$a.segment(i)],a=e;for(;o.length>0&&!r?.(o[o.length-1]?.segment||"")&&ue(o[o.length-1]?.segment||"");)a-=o.pop()?.segment.length||0;if(o.length===0)return a;let l=o[o.length-1];if(r?.(l.segment))a-=l.segment.length;else if(l.isWordLike){let c=l.segment,h=[...c.matchAll(new RegExp(Nn,"g"))];if(h.length<=0)a-=c.length;else{let u=h[h.length-1];a-=c.length-(u.index+u[0].length)}}else for(;o.length>0&&!r?.(o[o.length-1]?.segment||"")&&!o[o.length-1]?.isWordLike&&!ue(o[o.length-1]?.segment||"");)a-=o.pop()?.segment.length||0;return a}function ws(s,e,t){if(e>=s.length)return s.length;let i=s.slice(e),n=t?.segment,r=t?.isAtomicSegment,a=(n?n(i):$a.segment(i))[Symbol.iterator](),l=a.next(),c=e;for(;!l.done&&!r?.(l.value.segment)&&ue(l.value.segment);)c+=l.value.segment.length,l=a.next();if(l.done)return c;if(r?.(l.value.segment))c+=l.value.segment.length;else if(l.value.isWordLike)c+=Nn.exec(l.value.segment)?.index??l.value.segment.length;else for(;!l.done&&!r?.(l.value.segment)&&!l.value.isWordLike&&!ue(l.value.segment);)c+=l.value.segment.length,l=a.next();return c}var Aa=32,Ta=2,ad=10,ld=s=>s.replace(/[\r\n]+/g," ").trim(),cd=(s,e,t)=>Math.max(e,Math.min(s,t)),Ve=class{capturesViewportInput=!0;items=[];filteredItems=[];selectedIndex=0;mousePressedIndex;maxVisible=5;theme;layout;onSelect;onCancel;onSelectionChange;constructor(e,t,i,n={}){this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=i,this.layout=n}setFilter(e){this.filteredItems=this.items.filter(t=>t.value.toLowerCase().startsWith(e.toLowerCase())),this.selectedIndex=0}setSelectedIndex(e){this.selectedIndex=Math.max(0,Math.min(e,this.filteredItems.length-1))}invalidate(){}render(e){let t=[];if(this.filteredItems.length===0)return t.push(this.theme.noMatch(" No matching commands")),t;let i=this.getPrimaryColumnWidth(),{startIndex:n,endIndex:r}=this.getVisibleRange();for(let o=n;o<r;o++){let a=this.filteredItems[o];if(!a)continue;let l=o===this.selectedIndex,c=a.description?ld(a.description):void 0;t.push(this.renderItem(a,l,e,c,i))}if(n>0||r<this.filteredItems.length){let o=` (${this.selectedIndex+1}/${this.filteredItems.length})`;t.push(this.theme.scrollInfo(_(o,e-2,"")))}return t}handleMouse(e){if(this.filteredItems.length===0)return;if(e.type==="wheel"&&e.wheelDelta){let r=e.wheelDelta<0?-1:1,o=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(this.filteredItems.length-1,this.selectedIndex+r)),this.selectedIndex!==o&&this.notifySelectionChange(),{handled:!0,render:this.selectedIndex!==o}}if(e.button!=="left"||e.type!=="press"&&e.type!=="click")return;let{startIndex:t,endIndex:i}=this.getVisibleRange(),n=t+e.y;if(!(n<t||n>=i)){if(e.type==="press")return this.mousePressedIndex=n,this.selectedIndex!==n&&(this.selectedIndex=n,this.notifySelectionChange()),{handled:!0,focus:!0};if(e.type==="click"){let r=this.mousePressedIndex??n;this.mousePressedIndex=void 0;let o=this.selectedIndex!==r;this.selectedIndex=r,o&&this.notifySelectionChange();let a=this.filteredItems[this.selectedIndex];return a&&this.onSelect?.(a),{handled:!0}}}}handleInput(e){let t=fe(),i=bs(t,e,this.selectedIndex,this.filteredItems.length,this.maxVisible);if(t.matches(e,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(t.matches(e,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(i!==void 0){if(this.filteredItems.length===0||i===this.selectedIndex)return;this.selectedIndex=i,this.notifySelectionChange()}else if(t.matches(e,"tui.select.confirm")){let n=this.filteredItems[this.selectedIndex];n&&this.onSelect&&this.onSelect(n)}else t.matches(e,"tui.select.cancel")&&this.onCancel&&this.onCancel()}getVisibleRange(){let e=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible));return{startIndex:e,endIndex:Math.min(e+this.maxVisible,this.filteredItems.length)}}renderItem(e,t,i,n,r){let o=t?"\u2192 ":" ",a=x(o);if(n&&i>40){let h=Math.max(1,Math.min(r,i-a-4)),u=Math.max(1,h-Ta),d=this.truncatePrimary(e,t,u,h),p=x(d),f=" ".repeat(Math.max(1,h-p)),m=a+p+f.length,b=i-m-2;if(b>ad){let g=_(n,b,"");if(t)return this.theme.selectedText(`${o}${d}${f}${g}`);let y=this.theme.description(f+g);return o+d+y}}let l=i-a-2,c=this.truncatePrimary(e,t,l,l);return t?this.theme.selectedText(`${o}${c}`):o+c}getPrimaryColumnWidth(){let{min:e,max:t}=this.getPrimaryColumnBounds(),i=this.filteredItems.reduce((n,r)=>Math.max(n,x(this.getDisplayValue(r))+Ta),0);return cd(i,e,t)}getPrimaryColumnBounds(){let e=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??Aa,t=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??Aa;return{min:Math.max(1,Math.min(e,t)),max:Math.max(1,Math.max(e,t))}}truncatePrimary(e,t,i,n){let r=this.getDisplayValue(e),o=this.layout.truncatePrimary?this.layout.truncatePrimary({text:r,maxWidth:i,columnWidth:n,item:e,isSelected:t}):_(r,i,"");return _(o,i,"")}getDisplayValue(e){return e.label||e.value}notifySelectionChange(){let e=this.filteredItems[this.selectedIndex];e&&this.onSelectionChange&&this.onSelectionChange(e)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};var Ma=St(),hd=Ct(),Ea=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,La=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function Dt(s){return s.length>=10&&La.test(s)}function ud(s,e,t){if(t.size===0||!s.includes("[paste #"))return e.segment(s);let i=[];for(let a of s.matchAll(Ea)){let l=Number.parseInt(a[1],10);t.has(l)&&i.push({start:a.index,end:a.index+a[0].length})}if(i.length===0)return e.segment(s);let n=e.segment(s),r=[],o=0;for(let a of n){for(;o<i.length&&i[o].end<=a.index;)o++;let l=o<i.length?i[o]:null;if(l&&a.index>=l.start&&a.index<l.end){if(a.index===l.start){let c=s.slice(l.start,l.end);r.push({segment:c,index:l.start,input:s})}}else r.push(a)}return r}function lr(s,e,t){if(!s||e<=0)return[{text:"",startIndex:0,endIndex:0}];if(x(s)<=e)return[{text:s,startIndex:0,endIndex:s.length}];let n=[],r=t??[...Ma.segment(s)],o=0,a=0,l=-1,c=0;for(let h=0;h<r.length;h++){let u=r[h],d=u.segment,p=x(d),f=u.index,m=!Dt(d)&&ue(d);if(o+p>e&&(l>=0&&o-c+p<=e?(n.push({text:s.slice(a,l),startIndex:a,endIndex:l}),a=l,o-=c):a<f&&(n.push({text:s.slice(a,f),startIndex:a,endIndex:f}),a=f,o=0),l=-1),p>e){let g=lr(d,e);for(let w=0;w<g.length-1;w++){let k=g[w];n.push({text:k.text,startIndex:f+k.startIndex,endIndex:f+k.endIndex})}let y=g[g.length-1];a=f+y.startIndex,o=x(y.text),l=-1;continue}o+=p;let b=r[h+1];if(m&&b&&(Dt(b.segment)||!ue(b.segment)))l=b.index,c=o;else if(!m&&b&&!ue(b.segment)){let g=!Dt(d)&&$t.test(d),y=!Dt(b.segment)&&$t.test(b.segment);(g||y)&&(l=b.index,c=o)}}return n.push({text:s.slice(a),startIndex:a,endIndex:s.length}),n}var dd={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},pd=20,_a=["@","#"],cr=new RegExp(`(?:(?!${es.source}).)*`,"u"),Oa=`${ts.source}[([{<\`]*`;function qa(s){return s.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function Ia(s){return new RegExp(`${Oa}(?:@"[^"]*|[${s.map(qa).join("")}]${cr.source})$`,"u")}function Pa(s){let e=s.filter(t=>t!=="@").map(qa);return new RegExp(`${Oa}(?:@(?:"[^"]*|${cr.source})|[${e.join("")}]${cr.source})$`,"u")}function Ra(s,e,t){let i=Math.max(0,t),n=` ${s} ${e} more `,r=x(n);if(r+2<=i){let h=Math.floor((i-r)/2);return"\u2500".repeat(h)+n+"\u2500".repeat(i-h-r)}let o=`\u2500\u2500\u2500 ${s} ${e} more `,a=i-x(o);if(a>=0)return o+"\u2500".repeat(a);let l="...".slice(0,i),c=i-x(l);return H(o,0,c,!0)+l}var st=class{state={lines:[""],cursorLine:0,cursorCol:0};focused=!1;get capturesViewportInput(){return this.autocompleteState!==null}tui;theme;paddingX=0;lastWidth=80;renderedVisibleLineCount=1;renderedAutocompleteHeight=0;scrollOffset=0;borderColor;autocompleteProvider;autocompleteTriggerCharacters=[..._a];autocompleteTriggerPattern=Ia(this.autocompleteTriggerCharacters);autocompleteDebouncePattern=Pa(this.autocompleteTriggerCharacters);autocompleteList;autocompleteState=null;autocompletePrefix="";autocompleteMaxVisible=5;autocompleteAbort;autocompleteDebounceTimer;autocompleteRequestTask=Promise.resolve();autocompleteStartToken=0;autocompleteRequestId=0;pastes=new Map;pasteCounter=0;pasteBuffer="";isInPaste=!1;history=[];historyIndex=-1;historyDraft=null;killRing=new Ot;lastAction=null;jumpMode=null;preferredVisualCol=null;snappedFromCursorCol=null;undoStack=new qt;onSubmit;onChange;disableSubmit=!1;constructor(e,t,i={}){this.tui=e,this.theme=t,this.borderColor=t.borderColor;let n=i.paddingX??0;this.paddingX=Number.isFinite(n)?Math.max(0,Math.floor(n)):0;let r=i.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(r)?Math.max(3,Math.min(20,Math.floor(r))):5}validPasteIds(){return new Set(this.pastes.keys())}segment(e,t){return ud(e,t==="word"?hd:Ma,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;this.paddingX!==t&&(this.paddingX=t,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(e){let t=Number.isFinite(e)?Math.max(3,Math.min(20,Math.floor(e))):5;this.autocompleteMaxVisible!==t&&(this.autocompleteMaxVisible=t,this.tui.requestRender())}setAutocompleteProvider(e){this.cancelAutocomplete(),this.autocompleteProvider=e,this.setAutocompleteTriggerCharacters(e.triggerCharacters??[])}addToHistory(e){let t=e.trim();t&&(this.history.length>0&&this.history[0]===t||(this.history.unshift(t),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===0}isOnLastVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===e.length-1}navigateHistory(e){if(this.lastAction=null,this.history.length===0)return;let t=this.historyIndex-e;if(!(t<-1||t>=this.history.length))if(this.historyIndex===-1&&t>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=t,this.historyIndex===-1){let i=this.historyDraft;this.historyDraft=null,i?(this.state=i,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal("")}else this.setTextInternal(this.history[this.historyIndex]||"",e===-1?"start":"end")}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(e,t="end"){let i=e.split(`
|
|
69
|
+
`);this.state.lines=i.length===0?[""]:i,this.state.cursorLine=t==="start"?0:this.state.lines.length-1,this.setCursorCol(t==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){}renderTopBorder(e,t){let i=t>0?Ra("\u2191",t,e):"\u2500".repeat(e);return this.borderColor(i)}renderBottomBorder(e,t){let i=t>0?Ra("\u2193",t,e):"\u2500".repeat(e);return this.borderColor(i)}render(e){let t=Math.max(0,Math.floor((e-1)/2)),i=Math.min(this.paddingX,t),n=Math.max(1,e-i*2),r=Math.max(1,n-(i?0:1));this.lastWidth=r;let o=this.layoutText(r),a=this.tui.terminal.rows,l=Math.max(5,Math.floor(a*.3)),c=o.findIndex(g=>g.hasCursor);c===-1&&(c=0),c<this.scrollOffset?this.scrollOffset=c:c>=this.scrollOffset+l&&(this.scrollOffset=c-l+1);let h=Math.max(0,o.length-l);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,h));let u=o.slice(this.scrollOffset,this.scrollOffset+l);this.renderedVisibleLineCount=u.length;let d=[],p=" ".repeat(i),f=p;d.push(this.renderTopBorder(e,this.scrollOffset));let m=this.focused;for(let g of u){let y=g.text,w=x(g.text),k=!1;if(g.hasCursor&&g.cursorPos!==void 0){let A=y.slice(0,g.cursorPos),E=y.slice(g.cursorPos),B=m?pe:"";if(E.length>0){let L=[...this.segment(E,"grapheme")][0]?.segment||"",Q=E.slice(L.length),We=it(L);y=A+B+We+Q}else{let q=it(" ");y=A+B+q,w=w+1,w>n&&i>0&&(k=!0)}}let P=" ".repeat(Math.max(0,n-w)),v=k?f.slice(1):f;d.push(`${p}${y}${P}${v}`)}let b=o.length-(this.scrollOffset+u.length);if(d.push(this.renderBottomBorder(e,b)),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let g=this.autocompleteList.render(n);this.renderedAutocompleteHeight=g.length;for(let y of g){let w=x(y),k=" ".repeat(Math.max(0,n-w));d.push(`${p}${y}${k}${f}`)}}return d}handleMouse(e){let t=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&e.y>=t&&e.y<t+this.renderedAutocompleteHeight){let b=Math.max(0,Math.floor((e.width-1)/2)),g=Math.min(this.paddingX,b),y=Math.max(1,e.width-g*2),w=this.autocompleteList.handleMouse?.({...e,x:e.x-g,y:e.y-t,width:y,height:this.renderedAutocompleteHeight});return w?{...w,focus:!0}:void 0}if(e.type!=="click"||e.button!=="left")return;if(e.y<=0||e.y>this.renderedVisibleLineCount)return{handled:!0,focus:!0};let i=this.buildVisualLineMap(this.lastWidth),n=this.scrollOffset+e.y-1,r=i[n];if(!r)return{handled:!0,focus:!0};let o=this.state.lines[r.logicalLine]??"",a=r.startCol+r.length,l=o.slice(r.startCol,a),c=Math.max(0,Math.floor((e.width-1)/2)),h=Math.min(this.paddingX,c),u=Math.max(0,e.x-h),d=0,p=l.length,f=0;for(let b of this.segment(l,"grapheme")){let g=d+x(b.segment);if(f=b.index,u<g){p=b.index;break}d=g}return!(n===i.length-1||i[n+1]?.logicalLine!==r.logicalLine)&&p===l.length&&l.length>0&&(p=f),this.state.cursorLine=r.logicalLine,this.setCursorCol(r.startCol+p),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),{handled:!0,focus:!0}}handleInput(e){let t=fe();if(this.jumpMode!==null){if(t.matches(e,"tui.editor.jumpForward")||t.matches(e,"tui.editor.jumpBackward")){this.jumpMode=null;return}let n=Kn(e)??(e.charCodeAt(0)>=32?e:void 0);if(n!==void 0){let r=this.jumpMode;this.jumpMode=null,this.jumpToChar(n,r);return}this.jumpMode=null}if(e.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",e=e.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=e;let n=this.pasteBuffer.indexOf("\x1B[201~");if(n!==-1){let r=this.pasteBuffer.substring(0,n);r.length>0&&this.handlePaste(r),this.isInPaste=!1;let o=this.pasteBuffer.substring(n+6);this.pasteBuffer="",o.length>0&&this.handleInput(o);return}return}if(t.matches(e,"tui.input.copy"))return;if(t.matches(e,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(t.matches(e,"tui.select.cancel")){this.cancelAutocomplete();return}if(t.matches(e,"tui.select.up")||t.matches(e,"tui.select.down")||t.matches(e,"tui.select.pageUp")||t.matches(e,"tui.select.pageDown")){this.autocompleteList.handleInput(e);return}if(t.matches(e,"tui.input.tab")){let n=this.autocompleteList.getSelectedItem();if(n&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let r=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,n,this.autocompletePrefix);this.state.lines=r.lines,this.state.cursorLine=r.cursorLine,this.setCursorCol(r.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText())}return}if(t.matches(e,"tui.select.confirm")){let n=this.autocompleteList.getSelectedItem();if(n&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let r=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,n,this.autocompletePrefix);if(this.state.lines=r.lines,this.state.cursorLine=r.cursorLine,this.setCursorCol(r.cursorCol),this.autocompletePrefix.startsWith("/"))this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(t.matches(e,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(t.matches(e,"tui.editor.deleteToLineEnd")){this.deleteToEndOfLine();return}if(t.matches(e,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();return}if(t.matches(e,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(t.matches(e,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(t.matches(e,"tui.editor.deleteCharBackward")||S(e,"shift+backspace")){this.handleBackspace();return}if(t.matches(e,"tui.editor.deleteCharForward")||S(e,"shift+delete")){this.handleForwardDelete();return}if(t.matches(e,"tui.editor.yank")){this.yank();return}if(t.matches(e,"tui.editor.yankPop")){this.yankPop();return}if(t.matches(e,"tui.editor.historyPrevious")){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(t.matches(e,"tui.editor.historyNext")){this.cancelAutocomplete(),this.navigateHistory(1);return}if(t.matches(e,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(t.matches(e,"tui.editor.cursorLineEnd")){this.moveToLineEnd();return}if(t.matches(e,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(t.matches(e,"tui.editor.cursorWordRight")){this.moveWordForwards();return}if(t.matches(e,"tui.input.newLine")||e.charCodeAt(0)===10&&e.length>1||e==="\x1B\r"||e==="\x1B[13;2~"||e.length>1&&e.includes("\x1B")&&e.includes("\r")||e===`
|
|
70
|
+
`&&e.length===1){if(this.shouldSubmitOnBackslashEnter(e,t)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(t.matches(e,"tui.input.submit")){if(this.disableSubmit)return;let n=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&&n[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(t.matches(e,"tui.editor.cursorUp")){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||this.historyIndex>-1||this.state.cursorCol===0)?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(t.matches(e,"tui.editor.cursorDown")){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(t.matches(e,"tui.editor.cursorRight")){this.moveCursor(0,1);return}if(t.matches(e,"tui.editor.cursorLeft")){this.moveCursor(0,-1);return}if(t.matches(e,"tui.editor.pageUp")){this.pageScroll(-1);return}if(t.matches(e,"tui.editor.pageDown")){this.pageScroll(1);return}if(t.matches(e,"tui.editor.jumpForward")){this.jumpMode="forward";return}if(t.matches(e,"tui.editor.jumpBackward")){this.jumpMode="backward";return}if(S(e,"shift+space")){this.insertCharacter(" ");return}let i=Kn(e);if(i!==void 0){this.insertCharacter(i);return}e.charCodeAt(0)>=32&&this.insertCharacter(e)}layoutText(e){let t=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return t.push({text:"",hasCursor:!0,cursorPos:0}),t;for(let i=0;i<this.state.lines.length;i++){let n=this.state.lines[i]||"",r=i===this.state.cursorLine;if(x(n)<=e)r?t.push({text:n,hasCursor:!0,cursorPos:this.state.cursorCol}):t.push({text:n,hasCursor:!1});else{let a=lr(n,e,[...this.segment(n,"grapheme")]);for(let l=0;l<a.length;l++){let c=a[l];if(!c)continue;let h=this.state.cursorCol,u=l===a.length-1,d=!1,p=0;r&&(u?(d=h>=c.startIndex,p=h-c.startIndex):(d=h>=c.startIndex&&h<c.endIndex,d&&(p=h-c.startIndex,p>c.text.length&&(p=c.text.length)))),d?t.push({text:c.text,hasCursor:!0,cursorPos:p}):t.push({text:c.text,hasCursor:!1})}}}return t}getText(){return this.state.lines.join(`
|
|
71
71
|
`)}expandPasteMarkers(e){let t=e;for(let[i,n]of this.pastes){let r=new RegExp(`\\[paste #${i}( (\\+\\d+ lines|\\d+ chars))?\\]`,"g");t=t.replace(r,()=>n)}return t}getExpandedText(){return this.expandPasteMarkers(this.state.lines.join(`
|
|
72
72
|
`))}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(e){this.cancelAutocomplete(),this.lastAction=null,this.exitHistoryBrowsing();let t=this.normalizeText(e);this.getText()!==t&&this.pushUndoSnapshot(),this.pastes.clear(),this.pasteCounter=0,this.setTextInternal(t)}insertTextAtCursor(e){e&&(this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.exitHistoryBrowsing(),this.insertTextAtCursorInternal(e))}normalizeText(e){return e.replace(/\r\n/g,`
|
|
73
73
|
`).replace(/\r/g,`
|
|
@@ -75,51 +75,54 @@ Please report this to https://github.com/markedjs/marked.`,s){let i="<p>An error
|
|
|
75
75
|
`),n=this.state.lines[this.state.cursorLine]||"",r=n.slice(0,this.state.cursorCol),o=n.slice(this.state.cursorCol);i.length===1?(this.state.lines[this.state.cursorLine]=r+t+o,this.setCursorCol(this.state.cursorCol+t.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),r+i[0],...i.slice(1,-1),i[i.length-1]+o,...this.state.lines.slice(this.state.cursorLine+1)],this.state.cursorLine+=i.length-1,this.setCursorCol((i[i.length-1]||"").length)),this.onChange&&this.onChange(this.getText())}insertCharacter(e,t){this.exitHistoryBrowsing(),t||((ue(e)||this.lastAction!=="type-word")&&this.pushUndoSnapshot(),this.lastAction="type-word");let i=this.state.lines[this.state.cursorLine]||"",n=i.slice(0,this.state.cursorCol),r=i.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=n+e+r,this.setCursorCol(this.state.cursorCol+e.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(e==="/"&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(this.autocompleteTriggerCharacters.includes(e)){let a=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.autocompleteTriggerPattern.test(a)&&this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(e)||$t.test(e)){let a=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(a)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(a)&&this.tryTriggerAutocomplete()}}handlePaste(e){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let t=e.replace(/\x1b\[(\d+);5u/g,(a,l)=>{let c=Number(l);return c>=97&&c<=122?String.fromCharCode(c-96):c>=65&&c<=90?String.fromCharCode(c-64):a}),n=this.normalizeText(t).split("").filter(a=>a===`
|
|
76
76
|
`||a.charCodeAt(0)>=32).join("");if(/^[/~.]/.test(n)){let a=this.state.lines[this.state.cursorLine]||"",l=this.state.cursorCol>0?a[this.state.cursorCol-1]:"";l&&/\w/.test(l)&&(n=` ${n}`)}let r=n.split(`
|
|
77
77
|
`),o=n.length;if(r.length>10||o>1e3){this.pasteCounter++;let a=this.pasteCounter;this.pastes.set(a,n);let l=r.length>10?`[paste #${a} +${r.length} lines]`:`[paste #${a} ${o} chars]`;this.insertTextAtCursorInternal(l);return}if(r.length===1){this.insertTextAtCursorInternal(n);return}this.insertTextAtCursorInternal(n)}addNewLine(){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",t=e.slice(0,this.state.cursorCol),i=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=t,this.state.lines.splice(this.state.cursorLine+1,0,i),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(e,t){if(this.disableSubmit||!S(e,"enter"))return!1;let i=t.getKeys("tui.input.submit");if(!(i.includes("shift+enter")||i.includes("shift+return")))return!1;let r=this.state.lines[this.state.cursorLine]||"";return this.state.cursorCol>0&&r[this.state.cursorCol-1]==="\\"}submitValue(){this.cancelAutocomplete();let e=this.expandPasteMarkers(this.state.lines.join(`
|
|
78
|
-
`)).trim();this.state={lines:[""],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.exitHistoryBrowsing(),this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(""),this.onSubmit&&this.onSubmit(e)}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",t=e.slice(0,this.state.cursorCol),i=[...this.segment(t,"grapheme")],n=i[i.length-1],r=n?n.segment.length:1,o=
|
|
78
|
+
`)).trim();this.state={lines:[""],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.exitHistoryBrowsing(),this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(""),this.onSubmit&&this.onSubmit(e)}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",t=e.slice(0,this.state.cursorCol),i=[...this.segment(t,"grapheme")],n=i[i.length-1],r=n?n.segment.length:1,o=La.exec(n.segment);if(o){let c=Number(o[1]);this.pastes.delete(c),this.pasteCounter--;let h=[...this.pastes.keys()].filter(u=>u>c).sort((u,d)=>u-d);for(let u of h)this.pastes.set(u-1,this.pastes.get(u)),this.pastes.delete(u);this.state.lines=this.state.lines.map(u=>u.replace(Ea,(d,p,f)=>{let m=Number(p);return m<=c?d:`[paste #${m-1}${f??""}]`}))}e=this.state.lines[this.state.cursorLine]||"";let a=e.slice(0,this.state.cursorCol-r),l=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=a+l,this.setCursorCol(this.state.cursorCol-r)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||"",t=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(t)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(t)&&this.tryTriggerAutocomplete()}}setCursorCol(e){this.state.cursorCol=e,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(e,t,i){let n=e[t],r=e[i];if(!(n&&r))return;let o;if(this.snappedFromCursorCol!==null){let m=this.findVisualLineAt(e,n.logicalLine,this.snappedFromCursorCol);o=this.snappedFromCursorCol-e[m].startCol}else o=this.state.cursorCol-n.startCol;let l=t===e.length-1||e[t+1]?.logicalLine!==n.logicalLine?n.length:Math.max(0,n.length-1),h=i===e.length-1||e[i+1]?.logicalLine!==r.logicalLine?r.length:Math.max(0,r.length-1),u=this.computeVerticalMoveColumn(o,l,h);this.state.cursorLine=r.logicalLine;let d=r.startCol+u,p=this.state.lines[r.logicalLine]||"";this.state.cursorCol=Math.min(d,p.length);let f=[...this.segment(p,"grapheme")];for(let m of f){if(m.index>this.state.cursorCol)break;if(!(m.segment.length<=1)&&this.state.cursorCol<m.index+m.segment.length){let b=m.index<r.startCol,g=i>t;if(b&&g){let y=m.index+m.segment.length,w=i+1;for(;w<e.length&&e[w].logicalLine===r.logicalLine&&e[w].startCol<y;)w++;if(w<e.length){this.moveToVisualLine(e,t,w);return}}this.snappedFromCursorCol=this.state.cursorCol,this.state.cursorCol=m.index;return}}this.snappedFromCursorCol=null}computeVerticalMoveColumn(e,t,i){let n=this.preferredVisualCol!==null,r=e<t,o=i<e;if(!n||r)return o?(this.preferredVisualCol=e,i):(this.preferredVisualCol=null,e);let a=i<this.preferredVisualCol;if(o||a)return i;let l=this.preferredVisualCol;return this.preferredVisualCol=null,l}moveToLineStart(){this.lastAction=null,this.setCursorCol(0)}moveToLineEnd(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(e.length)}deleteToStartOfLine(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){this.pushUndoSnapshot();let t=e.slice(0,this.state.cursorCol);this.killRing.push(t,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
|
|
79
79
|
`,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}this.onChange&&this.onChange(this.getText())}deleteToEndOfLine(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<e.length){this.pushUndoSnapshot();let t=e.slice(this.state.cursorCol);this.killRing.push(t,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(0,this.state.cursorCol)}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
|
|
80
80
|
`,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}this.onChange&&this.onChange(this.getText())}deleteWordBackwards(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
|
|
81
81
|
`,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}}else{this.pushUndoSnapshot();let t=this.lastAction==="kill",i=this.state.cursorCol;this.moveWordBackwards();let n=this.state.cursorCol;this.setCursorCol(i);let r=e.slice(n,this.state.cursorCol);this.killRing.push(r,{prepend:!0,accumulate:t}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(0,n)+e.slice(this.state.cursorCol),this.setCursorCol(n)}this.onChange&&this.onChange(this.getText())}deleteWordForward(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=e.length){if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
|
|
82
|
-
`,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}}else{this.pushUndoSnapshot();let t=this.lastAction==="kill",i=this.state.cursorCol;this.moveWordForwards();let n=this.state.cursorCol;this.setCursorCol(i);let r=e.slice(this.state.cursorCol,n);this.killRing.push(r,{prepend:!1,accumulate:t}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(0,this.state.cursorCol)+e.slice(n)}this.onChange&&this.onChange(this.getText())}handleForwardDelete(){this.exitHistoryBrowsing(),this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<e.length){this.pushUndoSnapshot();let t=e.slice(this.state.cursorCol),n=[...this.segment(t,"grapheme")][0],r=n?n.segment.length:1,o=e.slice(0,this.state.cursorCol),a=e.slice(this.state.cursorCol+r);this.state.lines[this.state.cursorLine]=o+a}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let t=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let i=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(i)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(i)&&this.tryTriggerAutocomplete()}}buildVisualLineMap(e){let t=[];for(let i=0;i<this.state.lines.length;i++){let n=this.state.lines[i]||"",r=x(n);if(n.length===0)t.push({logicalLine:i,startCol:0,length:0});else if(r<=e)t.push({logicalLine:i,startCol:0,length:n.length});else{let o=
|
|
82
|
+
`,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let t=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}}else{this.pushUndoSnapshot();let t=this.lastAction==="kill",i=this.state.cursorCol;this.moveWordForwards();let n=this.state.cursorCol;this.setCursorCol(i);let r=e.slice(this.state.cursorCol,n);this.killRing.push(r,{prepend:!1,accumulate:t}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=e.slice(0,this.state.cursorCol)+e.slice(n)}this.onChange&&this.onChange(this.getText())}handleForwardDelete(){this.exitHistoryBrowsing(),this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<e.length){this.pushUndoSnapshot();let t=e.slice(this.state.cursorCol),n=[...this.segment(t,"grapheme")][0],r=n?n.segment.length:1,o=e.slice(0,this.state.cursorCol),a=e.slice(this.state.cursorCol+r);this.state.lines[this.state.cursorLine]=o+a}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let t=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let i=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(i)?this.tryTriggerAutocomplete():this.autocompleteTriggerPattern.test(i)&&this.tryTriggerAutocomplete()}}buildVisualLineMap(e){let t=[];for(let i=0;i<this.state.lines.length;i++){let n=this.state.lines[i]||"",r=x(n);if(n.length===0)t.push({logicalLine:i,startCol:0,length:0});else if(r<=e)t.push({logicalLine:i,startCol:0,length:n.length});else{let o=lr(n,e,[...this.segment(n,"grapheme")]);for(let a of o)t.push({logicalLine:i,startCol:a.startIndex,length:a.endIndex-a.startIndex})}}return t}findVisualLineAt(e,t,i){for(let n=0;n<e.length;n++){let r=e[n];if(!r||r.logicalLine!==t)continue;let o=i-r.startCol,a=n===e.length-1||e[n+1]?.logicalLine!==r.logicalLine;if(o>=0&&(o<r.length||a&&o===r.length))return n}return e.length-1}findCurrentVisualLine(e){return this.findVisualLineAt(e,this.state.cursorLine,this.state.cursorCol)}moveCursor(e,t){this.lastAction=null;let i=this.buildVisualLineMap(this.lastWidth),n=this.findCurrentVisualLine(i);if(e!==0){let r=n+e;r>=0&&r<i.length&&this.moveToVisualLine(i,n,r)}if(t!==0){let r=this.state.lines[this.state.cursorLine]||"";if(t>0)if(this.state.cursorCol<r.length){let o=r.slice(this.state.cursorCol),l=[...this.segment(o,"grapheme")][0];this.setCursorCol(this.state.cursorCol+(l?l.segment.length:1))}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else{let o=i[n];o&&(this.preferredVisualCol=this.state.cursorCol-o.startCol)}else if(this.state.cursorCol>0){let o=r.slice(0,this.state.cursorCol),a=[...this.segment(o,"grapheme")],l=a[a.length-1];this.setCursorCol(this.state.cursorCol-(l?l.segment.length:1))}else if(this.state.cursorLine>0){this.state.cursorLine--;let o=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(o.length)}}this.autocompleteState&&this.updateAutocomplete()}pageScroll(e){this.lastAction=null;let t=this.tui.terminal.rows,i=Math.max(5,Math.floor(t*.3)),n=this.buildVisualLineMap(this.lastWidth),r=this.findCurrentVisualLine(n),o=Math.max(0,Math.min(n.length-1,r+e*i));this.moveToVisualLine(n,r,o)}moveWordBackwards(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let t=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(t.length)}return}this.setCursorCol(ys(e,this.state.cursorCol,{segment:t=>this.segment(t,"word"),isAtomicSegment:Dt}))}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let e=this.killRing.peek();this.insertYankedText(e),this.lastAction="yank"}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let e=this.killRing.peek();this.insertYankedText(e),this.lastAction="yank"}insertYankedText(e){this.exitHistoryBrowsing();let t=e.split(`
|
|
83
83
|
`);if(t.length===1){let i=this.state.lines[this.state.cursorLine]||"",n=i.slice(0,this.state.cursorCol),r=i.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=n+e+r,this.setCursorCol(this.state.cursorCol+e.length)}else{let i=this.state.lines[this.state.cursorLine]||"",n=i.slice(0,this.state.cursorCol),r=i.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=n+(t[0]||"");for(let a=1;a<t.length-1;a++)this.state.lines.splice(this.state.cursorLine+a,0,t[a]||"");let o=this.state.cursorLine+t.length-1;this.state.lines.splice(o,0,(t[t.length-1]||"")+r),this.state.cursorLine=o,this.setCursorCol((t[t.length-1]||"").length)}this.onChange&&this.onChange(this.getText())}deleteYankedText(){let e=this.killRing.peek();if(!e)return;let t=e.split(`
|
|
84
|
-
`);if(t.length===1){let i=this.state.lines[this.state.cursorLine]||"",n=e.length,r=i.slice(0,this.state.cursorCol-n),o=i.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=r+o,this.setCursorCol(this.state.cursorCol-n)}else{let i=this.state.cursorLine-(t.length-1),n=(this.state.lines[i]||"").length-(t[0]||"").length,r=(this.state.lines[this.state.cursorLine]||"").slice(this.state.cursorCol),o=(this.state.lines[i]||"").slice(0,n);this.state.lines.splice(i,t.length,o+r),this.state.cursorLine=i,this.setCursorCol(n)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push({state:this.state,pastes:this.pastes,pasteCounter:this.pasteCounter})}undo(){this.exitHistoryBrowsing();let e=this.undoStack.pop();e&&(Object.assign(this.state,e.state),this.pastes=e.pastes,this.pasteCounter=e.pasteCounter,this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()))}jumpToChar(e,t){this.lastAction=null;let i=t==="forward",n=this.state.lines,r=i?n.length:-1,o=i?1:-1;for(let a=this.state.cursorLine;a!==r;a+=o){let l=n[a]||"",h=a===this.state.cursorLine?i?this.state.cursorCol+1:this.state.cursorCol-1:void 0,u=i?l.indexOf(e,h):l.lastIndexOf(e,h);if(u!==-1){this.state.cursorLine=a,this.setCursorCol(u);return}}}moveWordForwards(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=e.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(bs(e,this.state.cursorCol,{segment:t=>this.segment(t,"word"),isAtomicSegment:Dt}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return t.trim()===""||t.trim()==="/"}isInSlashCommandContext(e){return this.isSlashMenuAllowed()&&e.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(e,t){if(!t)return-1;let i=-1;for(let n=0;n<e.length;n++){let r=e[n].value;if(r===t)return n;i===-1&&r.startsWith(t)&&(i=n)}return i}createAutocompleteList(e,t){let i=e.startsWith("/")?ad:void 0,n=new Ve(t,this.autocompleteMaxVisible,this.theme.selectList,i);return n.onSelect=r=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let o=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,r,this.autocompletePrefix);this.state.lines=o.lines,this.state.cursorLine=o.cursorLine,this.setCursorCol(o.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText())},n}tryTriggerAutocomplete(e=!1){this.requestAutocomplete({force:!1,explicitTab:e})}handleTabCompletion(){if(!this.autocompleteProvider)return;let t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(t)&&!t.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(e=!1){this.requestAutocomplete({force:!0,explicitTab:e})}requestAutocomplete(e){if(!this.autocompleteProvider||e.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let t=++this.autocompleteStartToken,i=this.getAutocompleteDebounceMs(e);if(i>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(t,e)},i);return}this.startAutocompleteRequest(t,e)}async startAutocompleteRequest(e,t){let i=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await i,e!==this.autocompleteStartToken||!this.autocompleteProvider)return;let n=new AbortController;this.autocompleteAbort=n;let r=++this.autocompleteRequestId,o=this.getText(),a=this.state.cursorLine,l=this.state.cursorCol;await this.runAutocompleteRequest(r,n,o,a,l,t)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(e){let t=[...$a];for(let i of e)i.length!==1||i==="/"||ue(i)||t.includes(i)||t.push(i);this.autocompleteTriggerCharacters=t,this.autocompleteTriggerPattern=Aa(t),this.autocompleteDebouncePattern=Ta(t)}getAutocompleteDebounceMs(e){if(e.explicitTab||e.force)return 0;let i=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(i)?ld:0}async runAutocompleteRequest(e,t,i,n,r,o){if(!this.autocompleteProvider)return;let a=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:t.signal,force:o.force});if(this.isAutocompleteRequestCurrent(e,t,i,n,r)){if(this.autocompleteAbort=void 0,!a||!Array.isArray(a.items)||a.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(o.force&&o.explicitTab&&a.items.length===1){let l=a.items[0];this.pushUndoSnapshot(),this.lastAction=null;let c=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,l,a.prefix);this.state.lines=c.lines,this.state.cursorLine=c.cursorLine,this.setCursorCol(c.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(a,o.force?"force":"regular"),this.tui.requestRender()}}isAutocompleteRequestCurrent(e,t,i,n,r){return!t.signal.aborted&&e===this.autocompleteRequestId&&this.getText()===i&&this.state.cursorLine===n&&this.state.cursorCol===r}applyAutocompleteSuggestions(e,t){this.autocompletePrefix=e.prefix,this.autocompleteList=this.createAutocompleteList(e.prefix,e.items);let i=this.getBestAutocompleteMatchIndex(e.items,e.prefix);i>=0&&this.autocompleteList.setSelectedIndex(i),this.autocompleteState=t}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&(clearTimeout(this.autocompleteDebounceTimer),this.autocompleteDebounceTimer=void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=""}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var Bt=Symbol.for("@earendil-works/pi-tui/layout-node");function ys(s){let e=s;return typeof e[Bt]=="function"?e[Bt]():void 0}function cd(s){return!("render"in s)}function pi(s,e){return s===void 0||!Number.isFinite(s)?e:Math.max(0,Math.floor(s))}var fi=class extends ee{entries=[];gap;align;constructor(e=[],t={}){super(),this.gap=pi(t.gap,0),this.align=t.align??"stretch";for(let i of e)cd(i)?this.addChild(i.component,i):this.addChild(i)}addChild(e,t={}){super.addChild(e),this.entries.push({component:e,...t.basis===void 0?{}:{basis:t.basis},...t.grow===void 0?{}:{grow:pi(t.grow,0)},...t.shrink===void 0?{}:{shrink:pi(t.shrink,1)},...t.minSize===void 0?{}:{minSize:pi(t.minSize,0)},...t.maxSize===void 0?{}:{maxSize:pi(t.maxSize,Number.MAX_SAFE_INTEGER)},...t.visible===void 0?{}:{visible:t.visible}})}removeChild(e){super.removeChild(e);let t=this.entries.findIndex(i=>i.component===e);t!==-1&&this.entries.splice(t,1)}clear(){super.clear(),this.entries.length=0}[Bt](){return{type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function mi(s,e){return s.filter(t=>t.visible?.(e)??!0)}function hd(s,e){let t=Math.max(0,Math.floor(e.minSize??0)),i=Math.max(t,Math.floor(e.maxSize??Number.MAX_SAFE_INTEGER));return Math.max(t,Math.min(i,Math.max(0,Math.floor(s))))}function La(s,e,t,i){let n=t;for(;n>0;){let r=e.map((l,c)=>({entry:l,index:c})).filter(({entry:l,index:c})=>i==="grow"?(l.grow??0)>0&&s[c]<(l.maxSize??Number.MAX_SAFE_INTEGER):(l.shrink??1)>0&&s[c]>(l.minSize??0));if(r.length===0)return;let o=r.reduce((l,{entry:c,index:h})=>l+(i==="grow"?c.grow??0:(c.shrink??1)*Math.max(1,s[h])),0),a=0;for(let{entry:l,index:c}of r){if(n<=0)break;let h=i==="grow"?l.grow??0:(l.shrink??1)*Math.max(1,s[c]),u=Math.max(1,Math.floor(n*h/o)),d=i==="grow"?(l.maxSize??Number.MAX_SAFE_INTEGER)-s[c]:s[c]-(l.minSize??0),p=Math.min(n,u,d);p<=0||(s[c]=s[c]+(i==="grow"?p:-p),n-=p,a+=p)}if(a===0)return}}function Nt(s,e,t,i){let n=s.map((a,l)=>hd(a.basis===void 0||a.basis==="auto"?e[l]??0:a.basis,a));if(t===void 0)return n;let r=Math.max(0,Math.floor(t)-Math.max(0,s.length-1)*i),o=n.reduce((a,l)=>a+l,0);return o<r?La(n,s,r-o,"grow"):o>r&&La(n,s,o-r,"shrink"),n}var Oa,Ft=new Map;function ud(s,e){if(!Oa)return null;let t=Ft.get(s),i=t===void 0?Oa(s,e):t;return Ft.delete(s),Ft.set(s,i),Ft.size>32&&Ft.delete(Ft.keys().next().value),i}var gi=class{base64Data;mimeType;dimensions;theme;options;imageId;pngData;cachedLines;cachedWidth;constructor(e,t,i,n={},r){this.base64Data=e,this.mimeType=t,this.theme=i,this.options=n,this.dimensions=r||Xn(e,t)||{widthPx:800,heightPx:600},this.imageId=n.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(e){if(this.cachedLines&&this.cachedWidth===e)return this.cachedLines;let t=Math.max(1,Math.min(e-2,this.options.maxWidthCells??60)),i=rs(),n=Math.max(1,Math.ceil(t*i.widthPx/i.heightPx)),r=this.options.maxHeightCells??n,o=ae(),a=this.base64Data,l=this.dimensions;o.images==="kitty"&&this.mimeType!=="image/png"&&(this.pngData??=ud(this.base64Data,this.mimeType)??void 0,a=this.pngData??null,a&&(l=cs(a)??l));let c;if(o.images&&a){o.images==="kitty"&&this.imageId===void 0&&(this.imageId=Vn());let h=Jn(a,l,{maxWidthCells:t,maxHeightCells:r,imageId:this.imageId,moveCursor:!1});if(h)if(h.imageId&&(this.imageId=h.imageId),o.images==="kitty"){c=[h.sequence];for(let u=0;u<h.rows-1;u++)c.push("")}else{c=[];for(let p=0;p<h.rows-1;p++)c.push("");let u=h.rows-1,d=u>0?`\x1B[${u}A`:"";c.push(d+h.sequence)}else{let u=us(this.mimeType,this.dimensions,this.options.filename);c=[_(this.theme.fallbackColor(u),e)]}}else{let h=us(this.mimeType,this.dimensions,this.options.filename);c=[_(this.theme.fallbackColor(h),e)]}return this.cachedLines=c,this.cachedWidth=e,c}};var nt=St(),Te=class{value="";cursor=0;prompt;placeholder;placeholderStyle;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new Ot;lastAction=null;undoStack=new qt;constructor(e={}){this.prompt=e.prompt??"> ",this.placeholder=e.placeholder??"",this.placeholderStyle=e.placeholderStyle??(t=>t)}getValue(){return this.value}setValue(e){this.value=e,this.cursor=Math.min(this.cursor,e.length)}handleInput(e){if(e.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",e=e.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=e;let r=this.pasteBuffer.indexOf("\x1B[201~");if(r!==-1){let o=this.pasteBuffer.substring(0,r);this.handlePaste(o),this.isInPaste=!1;let a=this.pasteBuffer.substring(r+6);this.pasteBuffer="",a&&this.handleInput(a)}return}let t=fe();if(t.matches(e,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(t.matches(e,"tui.editor.undo")){this.undo();return}if(t.matches(e,"tui.input.submit")||e===`
|
|
85
|
-
`){this.onSubmit&&this.onSubmit(this.value);return}if(t.matches(e,"tui.editor.deleteCharBackward")){this.handleBackspace();return}if(t.matches(e,"tui.editor.deleteCharForward")){this.handleForwardDelete();return}if(t.matches(e,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(t.matches(e,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(t.matches(e,"tui.editor.deleteToLineStart")){this.deleteToLineStart();return}if(t.matches(e,"tui.editor.deleteToLineEnd")){this.deleteToLineEnd();return}if(t.matches(e,"tui.editor.yank")){this.yank();return}if(t.matches(e,"tui.editor.yankPop")){this.yankPop();return}if(t.matches(e,"tui.editor.cursorLeft")){if(this.lastAction=null,this.cursor>0){let r=this.value.slice(0,this.cursor),o=[...nt.segment(r)],a=o[o.length-1];this.cursor-=a?a.segment.length:1}return}if(t.matches(e,"tui.editor.cursorRight")){if(this.lastAction=null,this.cursor<this.value.length){let r=this.value.slice(this.cursor),a=[...nt.segment(r)][0];this.cursor+=a?a.segment.length:1}return}if(t.matches(e,"tui.editor.cursorLineStart")){this.lastAction=null,this.cursor=0;return}if(t.matches(e,"tui.editor.cursorLineEnd")){this.lastAction=null,this.cursor=this.value.length;return}if(t.matches(e,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(t.matches(e,"tui.editor.cursorWordRight")){this.moveWordForwards();return}let i=ss(e);if(i!==void 0){this.insertCharacter(i);return}[...e].some(r=>{let o=r.charCodeAt(0);return o<32||o===127||o>=128&&o<=159})||this.insertCharacter(e)}handleMouse(e){if(e.type!=="press"||e.button!=="left"||e.y!==0)return;let t=Math.max(0,e.x-2),i=this.renderedStartColumn+t,n=0;this.cursor=this.value.length;for(let r of nt.segment(this.value)){let o=n+x(r.segment);if(i<o){this.cursor=r.index;break}n=o}return this.lastAction=null,{handled:!0,focus:!0}}insertCharacter(e){(ue(e)||this.lastAction!=="type-word")&&this.pushUndo(),this.lastAction="type-word",this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let e=this.value.slice(0,this.cursor),t=[...nt.segment(e)],i=t[t.length-1],n=i?i.segment.length:1;this.value=this.value.slice(0,this.cursor-n)+this.value.slice(this.cursor),this.cursor-=n}}handleForwardDelete(){if(this.lastAction=null,this.cursor<this.value.length){this.pushUndo();let e=this.value.slice(this.cursor),i=[...nt.segment(e)][0],n=i?i.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+n)}}deleteToLineStart(){if(this.cursor===0)return;this.pushUndo();let e=this.value.slice(0,this.cursor);this.killRing.push(e,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(this.cursor),this.cursor=0}deleteToLineEnd(){if(this.cursor>=this.value.length)return;this.pushUndo();let e=this.value.slice(this.cursor);this.killRing.push(e,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(this.cursor===0)return;let e=this.lastAction==="kill";this.pushUndo();let t=this.cursor;this.moveWordBackwards();let i=this.cursor;this.cursor=t;let n=this.value.slice(i,this.cursor);this.killRing.push(n,{prepend:!0,accumulate:e}),this.lastAction="kill",this.value=this.value.slice(0,i)+this.value.slice(this.cursor),this.cursor=i}deleteWordForward(){if(this.cursor>=this.value.length)return;let e=this.lastAction==="kill";this.pushUndo();let t=this.cursor;this.moveWordForwards();let i=this.cursor;this.cursor=t;let n=this.value.slice(this.cursor,i);this.killRing.push(n,{prepend:!1,accumulate:e}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)+this.value.slice(i)}yank(){let e=this.killRing.peek();e&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length,this.lastAction="yank")}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndo();let e=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor-e.length)+this.value.slice(this.cursor),this.cursor-=e.length,this.killRing.rotate();let t=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length,this.lastAction="yank"}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){let e=this.undoStack.pop();e&&(this.value=e.value,this.cursor=e.cursor,this.lastAction=null)}moveWordBackwards(){this.cursor!==0&&(this.lastAction=null,this.cursor=gs(this.value,this.cursor))}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=bs(this.value,this.cursor))}handlePaste(e){this.lastAction=null,this.pushUndo();let t=e.replace(/\r\n/g,"").replace(/\r/g,"").replace(/\n/g,"").replace(/\t/g," ");this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length}invalidate(){}render(e){let t=e-x(this.prompt);if(t<=0)return[_(this.prompt,e,"")];if(this.value.length===0&&this.placeholder){let m=_(this.placeholder,t,""),w=[...nt.segment(m)][0]?.segment??" ",k=m.slice(w.length),R=this.focused?pe:"",v=it(this.placeholderStyle(w)),A=R+v+this.placeholderStyle(k),E=" ".repeat(Math.max(0,t-x(A)));return[this.prompt+A+E]}let i="",n=this.cursor;this.renderedStartColumn=0;let r=x(this.value);if(r<t)i=this.value;else{let m=this.cursor===this.value.length?t-1:t,y=x(this.value.slice(0,this.cursor));if(m>0){let w=Math.floor(m/2),k=0;y<w?k=0:y>r-w?k=Math.max(0,r-m):k=Math.max(0,y-w),this.renderedStartColumn=k,i=H(this.value,k,m,!0),n=H(this.value,k,Math.max(0,y-k),!0).length}else i="",n=0}let a=[...nt.segment(i.slice(n))][0],l=i.slice(0,n),c=a?.segment??" ",h=i.slice(n+c.length),u=this.focused?pe:"",d=it(c),p=l+u+d+h,f=x(p),g=" ".repeat(Math.max(0,t-f));return[this.prompt+p+g]}};var $e="\\u1100-\\u11ff\\u20a9\\u2329-\\u232a\\u2630-\\u2637\\u268a-\\u268f\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u2ff0-\\u303e\\u3041-\\u3096\\u3099-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u31e5\\u31ef-\\u321e\\u3220-\\u3247\\u3250-\\ua48c\\ua490-\\ua4c6\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufaff\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe66\\ufe68-\\ufe6b\\uff01-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\\uffe0-\\uffe6\\uffe8-\\uffee\\u{16fe0}-\\u{16fe4}\\u{16ff0}-\\u{16ff6}\\u{17000}-\\u{18cda}\\u{18cff}-\\u{18d20}\\u{18d80}-\\u{18df2}\\u{18e00}-\\u{19191}\\u{191a0}-\\u{191d2}\\u{1aff0}-\\u{1aff3}\\u{1aff5}-\\u{1affb}\\u{1affd}-\\u{1affe}\\u{1b000}-\\u{1b128}\\u{1b132}\\u{1b150}-\\u{1b152}\\u{1b155}\\u{1b164}-\\u{1b168}\\u{1b170}-\\u{1b2fb}\\u{1d300}-\\u{1d356}\\u{1d360}-\\u{1d376}\\u{1f1ae}\\u{1f200}\\u{1f202}\\u{1f210}-\\u{1f219}\\u{1f21b}-\\u{1f22e}\\u{1f230}-\\u{1f231}\\u{1f237}\\u{1f23b}\\u{1f240}-\\u{1f248}\\u{1f260}-\\u{1f265}\\u{1f7da}\\u{20000}-\\u{3fffd}",Wt=new RegExp(`[${$e}]`,"u"),dd=new RegExp(`^((?![*_])[\\s\\p{P}\\p{S}${$e}])`,"u");function Na(s,e,t){return new RegExp(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)${s}(\\*+)(?=[\\s]|$)|${t}(\\*+)(?!\\*)(?=${e}|$)|(?!\\*)${e}(\\*+)(?=${t})|[\\s](\\*+)(?!\\*)(?=${s})|(?!\\*)${s}(\\*+)(?!\\*)(?=${s})|${t}(\\*+)(?=${t})`,"gu")}function pd(s,e,t){return new RegExp(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)${s}(_+)(?=[\\s]|$)|${t}(_+)(?!_)(?=${e}|$)|(?!_)${e}(_+)(?=${t})|[\\s](_+)(?!_)(?=${s})|(?!_)${s}(_+)(?!_)(?=${s})`,"gu")}function fd(s,e,t){return new RegExp(`^[^~]+(?=[^~])|(?!~)${s}(~~?)(?=[\\s]|$)|${t}(~~?)(?!~)(?=${e}|$)|(?!~)${e}(~~?)(?=${t})|[\\s](~~?)(?!~)(?=${s})|(?!~)${s}(~~?)(?!~)(?=${s})|${t}(~~?)(?=${t})`,"gu")}var Fa=`[\\p{P}\\p{S}${$e}]`,Wa=`[\\s\\p{P}\\p{S}${$e}]`,Ka=`[^\\s\\p{P}\\p{S}${$e}]`,md=`(?![*_])[\\p{P}\\p{S}${$e}]`,gd=`(?![*_])[\\s\\p{P}\\p{S}${$e}]`,bd=`(?:[^\\s\\p{P}\\p{S}${$e}]|[*_])`,yd=`(?!~)[\\p{P}\\p{S}${$e}]`,wd=`(?!~)[\\s\\p{P}\\p{S}${$e}]`,xd=`(?:[^\\s\\p{P}\\p{S}${$e}]|~)`,vd=Na(Fa,Wa,Ka),kd=Na(yd,wd,xd),Sd=pd(Fa,Wa,Ka),qa=fd(md,gd,bd);function Da(s,e,t){let i=dd.test(s);if(!i&&s){let n=e.length-t.length;if(n>=1){let r=n-1,o=e.charCodeAt(r);if(o>=65024&&o<=65038&&r>=1&&(r--,o=e.charCodeAt(r)),(o&64512)===56320&&r>=1){let a=e.codePointAt(r-1);a!==void 0&&a>65535&&(a>=917760&&a<=917999?i=!0:i=Wt.test(String.fromCodePoint(a)))}else i=Wt.test(String.fromCharCode(o))}}return i}function Ba(s,e){if(!(s[1]||s[2]||s[3]||s[4]))return!1;let t=String.fromCodePoint(s[0].codePointAt(0)),i=s.index+s[0].length,n=i<e.length?String.fromCodePoint(e.codePointAt(i)):"";return Wt.test(t)||Wt.test(n)}function lr(s){return s.length>=5}function Cd(s){return!!(s[1]||s[2]||s[3]||s[4])}function $d(s){return lr(s)?!!s[4]:!!s[3]}function Ad(s){return lr(s)?s[1]||s[3]||"":s[1]||s[2]||""}function Ua(){return{tokenizer:{emStrong(s,e,t=""){let{rules:i}=this,n=i.inline.emStrongLDelim.exec(s);if(!n)return!1;let r=lr(n);if(r&&!Cd(n))return;if($d(n)&&t.match(i.other.unicodeAlphaNumeric))return!1;let o=Ad(n),a=Da(t,e,s);if(!o||!t||i.inline.punctuation.exec(t)||a||Wt.test(o)){let l=[...n[0]].length-1,c,h,u=l,d=0,p=r&&t===n[0][0],f=i.inline.emStrongRDelimAst.source.includes("(?!~)"),g;n[0][0]==="*"?g=f?kd:vd:g=Sd,g.lastIndex=0;let b=e.slice(-1*s.length+l),m;for(;(m=g.exec(b))!=null;){if(c=m[1]||m[2]||m[3]||m[4]||m[5]||m[6],!c)continue;h=[...c].length;let y=Ba(m,b),w=!!(m[3]||m[4]),k=!!(m[5]||m[6]);if(w&&!y){u+=h;continue}if(k||y){if(l%3&&!((l+h)%3)){d+=h;continue}if(p&&k)break}if(u-=h,u>0)continue;h=Math.min(h,h+u+d);let R=m[0].codePointAt(0)>65535?2:1,v=s.slice(0,l+m.index+R+h);if(Math.min(l,h)%2){let E=v.slice(1,-1);return{type:"em",raw:v,text:E,tokens:this.lexer.inlineTokens(E)}}let A=v.slice(2,-2);return{type:"strong",raw:v,text:A,tokens:this.lexer.inlineTokens(A)}}}},del(s,e,t=""){let{rules:i}=this,n=i.inline.delLDelim.exec(s);if(!n)return!1;let r=n[1]||"",o=Da(t,e,s);if(!r||!t||i.inline.punctuation.exec(t)||o||Wt.test(r)){let a=[...n[0]].length-1,l,c,h=a;qa.lastIndex=0;let u=e.slice(-1*s.length+a),d;for(;(d=qa.exec(u))!=null;){if(l=d[1]||d[2]||d[3]||d[4]||d[5]||d[6],!l||(c=[...l].length,c!==a))continue;let p=Ba(d,u);if((d[3]||d[4])&&!p){h+=c;continue}if(h-=c,h>0)continue;c=Math.min(c,c+h);let f=d[0].codePointAt(0)>65535?2:1,g=s.slice(0,a+d.index+f+c),b=g.slice(a,-a);return{type:"del",raw:g,text:b,tokens:this.lexer.inlineTokens(b)}}}}}}}var Td={alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03F5",varepsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",vartheta:"\u03D1",iota:"\u03B9",kappa:"\u03BA",varkappa:"\u03F0",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",pi:"\u03C0",varpi:"\u03D6",rho:"\u03C1",varrho:"\u03F1",sigma:"\u03C3",varsigma:"\u03C2",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03D5",varphi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",Gamma:"\u0393",Delta:"\u0394",Theta:"\u0398",Lambda:"\u039B",Xi:"\u039E",Pi:"\u03A0",Sigma:"\u03A3",Upsilon:"\u03A5",Phi:"\u03A6",Psi:"\u03A8",Omega:"\u03A9",pm:"\xB1",mp:"\u2213",times:"\xD7",div:"\xF7",cdot:"\xB7",ast:"\u2217",star:"\u22C6",circ:"\u2218",bullet:"\u2022",oplus:"\u2295",ominus:"\u2296",otimes:"\u2297",oslash:"\u2298",odot:"\u2299",bigcirc:"\u25CB",dagger:"\u2020",ddagger:"\u2021",amalg:"\u2A3F",uplus:"\u228E",sqcap:"\u2293",sqcup:"\u2294",bowtie:"\u22C8",Join:"\u22C8",ltimes:"\u22C9",rtimes:"\u22CA",leftouterjoin:"\u27D5",rightouterjoin:"\u27D6",fullouterjoin:"\u27D7",triangleleft:"\u25C1",triangleright:"\u25B7",wr:"\u2240",cap:"\u2229",cup:"\u222A",bigcap:"\u22C2",bigcup:"\u22C3",bigwedge:"\u22C0",bigvee:"\u22C1",bigsqcup:"\u2A06",biguplus:"\u2A04",bigoplus:"\u2A01",bigotimes:"\u2A02",bigodot:"\u2A00",setminus:"\u2216",in:"\u2208",notin:"\u2209",ni:"\u220B",subset:"\u2282",supset:"\u2283",subseteq:"\u2286",supseteq:"\u2287",sqsubset:"\u228F",sqsupset:"\u2290",sqsubseteq:"\u2291",sqsupseteq:"\u2292",prec:"\u227A",preceq:"\u227C",succ:"\u227B",succeq:"\u227D",ll:"\u226A",gg:"\u226B",le:"\u2264",leq:"\u2264",leqslant:"\u2264",ge:"\u2265",geq:"\u2265",geqslant:"\u2265",ne:"\u2260",neq:"\u2260",equiv:"\u2261",approx:"\u2248",sim:"\u223C",simeq:"\u2243",cong:"\u2245",asymp:"\u224D",doteq:"\u2250",propto:"\u221D",parallel:"\u2225",perp:"\u22A5",mid:"\u2223",vdash:"\u22A2",dashv:"\u22A3",models:"\u22A8",Vdash:"\u22A9",Vvdash:"\u22AA",nvdash:"\u22AC",nvDash:"\u22AD",forall:"\u2200",exists:"\u2203",nexists:"\u2204",neg:"\xAC",land:"\u2227",wedge:"\u2227",lor:"\u2228",vee:"\u2228",to:"\u2192",rightarrow:"\u2192",longrightarrow:"\u2192",leftarrow:"\u2190",longleftarrow:"\u2190",gets:"\u2190",leftrightarrow:"\u2194",longleftrightarrow:"\u2194",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",leftharpoonup:"\u21BC",leftharpoondown:"\u21BD",rightharpoonup:"\u21C0",rightharpoondown:"\u21C1",rightleftharpoons:"\u21CC",leftrightharpoons:"\u21CB",nearrow:"\u2197",searrow:"\u2198",swarrow:"\u2199",nwarrow:"\u2196",rightsquigarrow:"\u21DD",leadsto:"\u21DD",Rightarrow:"\u21D2",Longrightarrow:"\u21D2",Leftarrow:"\u21D0",Longleftarrow:"\u21D0",Leftrightarrow:"\u21D4",Longleftrightarrow:"\u21D4",implies:"\u21D2",iff:"\u21D4",mapsto:"\u21A6",longmapsto:"\u21A6",uparrow:"\u2191",downarrow:"\u2193",partial:"\u2202",nabla:"\u2207",int:"\u222B",iint:"\u222C",iiint:"\u222D",oint:"\u222E",sum:"\u2211",prod:"\u220F",coprod:"\u2210",infty:"\u221E",emptyset:"\u2205",varnothing:"\u2205",angle:"\u2220",therefore:"\u2234",because:"\u2235",aleph:"\u2135",beth:"\u2136",gimel:"\u2137",daleth:"\u2138",top:"\u22A4",bot:"\u22A5",triangle:"\u25B3",square:"\u25A1",lozenge:"\u25CA",checkmark:"\u2713",complement:"\u2201",wp:"\u2118",prime:"\u2032",ldots:"\u2026",dots:"\u2026",cdots:"\u22EF",vdots:"\u22EE",ddots:"\u22F1",ell:"\u2113",hbar:"\u210F",Im:"\u2111",Re:"\u211C",langle:"\u27E8",rangle:"\u27E9",vert:"|",lvert:"|",rvert:"|",Vert:"\u2016",lVert:"\u2016",rVert:"\u2016",lbrace:"{",rbrace:"}",backslash:"\\",lfloor:"\u230A",rfloor:"\u230B",lceil:"\u2308",rceil:"\u2309",colon:":"},_d=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"]),Id=new Set(["argmax","argmin","inf","injlim","lim","liminf","limsup","max","min","projlim","sup"]),Rd=new Set(["bigcap","bigcup","bigodot","bigoplus","bigotimes","bigsqcup","biguplus","bigvee","bigwedge","coprod","int","iint","iiint","oint","prod","sum"]),Pd=new Set(["Leftarrow","Leftrightarrow","Longleftarrow","Longleftrightarrow","Longrightarrow","Rightarrow","Join","Vdash","Vvdash","approx","asymp","bowtie","cong","dashv","fullouterjoin","doteq","downarrow","equiv","ge","geq","geqslant","gets","gg","hookleftarrow","hookrightarrow","iff","implies","in","leadsto","le","leftarrow","leftharpoondown","leftharpoonup","leftrightarrow","leftrightharpoons","leftouterjoin","leq","leqslant","ll","longleftarrow","longleftrightarrow","longmapsto","longrightarrow","ltimes","mapsto","mid","models","ne","nearrow","neq","ni","notin","nvdash","nvDash","nwarrow","parallel","perp","prec","preceq","propto","rightharpoondown","rightharpoonup","rightleftharpoons","rightouterjoin","rightarrow","rightsquigarrow","rtimes","searrow","sim","simeq","sqsubset","sqsubseteq","sqsupset","sqsupseteq","subset","subseteq","succ","succeq","supset","supseteq","swarrow","to","triangleleft","triangleright","twoheadleftarrow","twoheadrightarrow","uparrow","vdash"]),Md={"<":"\u226E",">":"\u226F","=":"\u2260","\u2208":"\u2209","\u220B":"\u220C","\u2223":"\u2224","\u2225":"\u2226","\u223C":"\u2241","\u2243":"\u2244","\u2245":"\u2247","\u2248":"\u2249","\u2261":"\u2262","\u2264":"\u2270","\u2265":"\u2271","\u227A":"\u2280","\u227B":"\u2281","\u2282":"\u2284","\u2283":"\u2285","\u2286":"\u2288","\u2287":"\u2289","\u22A2":"\u22AC","\u22A8":"\u22AD","\u2194":"\u21AE","\u2190":"\u219A","\u2192":"\u219B","\u21D2":"\u21CF","\u21D0":"\u21CD","\u21D4":"\u21CE","\u227C":"\u22E0","\u227D":"\u22E1"},Ed={C:"\u2102",H:"\u210D",N:"\u2115",P:"\u2119",Q:"\u211A",R:"\u211D",Z:"\u2124"},Ld={0:"\u2070",1:"\xB9",2:"\xB2",3:"\xB3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},Od={0:"\u2080",1:"\u2081",2:"\u2082",3:"\u2083",4:"\u2084",5:"\u2085",6:"\u2086",7:"\u2087",8:"\u2088",9:"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"},qd=new Set([",",":",";"," ",">","enspace","enskip","medspace","quad","qquad","thickspace","thinspace"]),Dd=new Set(["!","negmedspace","negthickspace","negthinspace"]),Ha="\0",Bd=new Set(["bf","cal","it","rm","sf","sl","tt"]),Nd=new Set(["displaystyle","limits","nolimits","scriptstyle","scriptscriptstyle","textstyle"]),Fd=new Set(["big","Big","bigg","Bigg","bigl","Bigl","biggl","Biggl","bigr","Bigr","biggr","Biggr"]),Wd=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"]),Kd={acute:"\u0301",bar:"\u0305",breve:"\u0306",check:"\u030C",ddot:"\u0308",dot:"\u0307",grave:"\u0300",hat:"\u0302",mathring:"\u030A",overleftarrow:"\u20D6",overleftrightarrow:"\u20E1",overline:"\u0305",overrightarrow:"\u20D7",tilde:"\u0303",underline:"\u0332",vec:"\u20D7",widehat:"\u0302",widetilde:"\u0303"};function Ud(s,e){let t="";for(let i of s){let n=e[i];if(n===void 0)return;t+=n}return t}function za(s){return s.trim().replace(/\s*([=+-])\s*/g,"$1")}function cr(s,e){return Ud(za(s),e==="sub"?Od:Ld)}function rt(s,e){s=za(s);let t=cr(s,e);if(t!==void 0)return t;let i=e==="sub"?"_":"^";return Array.from(s).length===1||e==="sub"&&/^[A-Za-z]+$/.test(s)?`${i}${s}`:`${i}(${s})`}function Hd(s,e){s=s.trim(),e=e.trim();let t=/^[\p{L}\p{N}.]+$/u.test(s),i=/^[\p{N}.]+$/u.test(e)||Array.from(e).length===1;return`${t?s:`(${s})`}/${i?e:`(${e})`}`}function ws(s,e="\u221A"){return s=s.trim(),/^[\p{L}\p{N}.]+$/u.test(s)?`${e}${s}`:`${e}(${s})`}var Va="\u{F0004}",at="\u{F0005}",zd=/(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu,Vd=/\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu;function ot(s){return s.replace(zd," ").replaceAll(Va,"").replace(Vd," ").replaceAll(at,"").split(`
|
|
84
|
+
`);if(t.length===1){let i=this.state.lines[this.state.cursorLine]||"",n=e.length,r=i.slice(0,this.state.cursorCol-n),o=i.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=r+o,this.setCursorCol(this.state.cursorCol-n)}else{let i=this.state.cursorLine-(t.length-1),n=(this.state.lines[i]||"").length-(t[0]||"").length,r=(this.state.lines[this.state.cursorLine]||"").slice(this.state.cursorCol),o=(this.state.lines[i]||"").slice(0,n);this.state.lines.splice(i,t.length,o+r),this.state.cursorLine=i,this.setCursorCol(n)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push({state:this.state,pastes:this.pastes,pasteCounter:this.pasteCounter})}undo(){this.exitHistoryBrowsing();let e=this.undoStack.pop();e&&(Object.assign(this.state,e.state),this.pastes=e.pastes,this.pasteCounter=e.pasteCounter,this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()))}jumpToChar(e,t){this.lastAction=null;let i=t==="forward",n=this.state.lines,r=i?n.length:-1,o=i?1:-1;for(let a=this.state.cursorLine;a!==r;a+=o){let l=n[a]||"",h=a===this.state.cursorLine?i?this.state.cursorCol+1:this.state.cursorCol-1:void 0,u=i?l.indexOf(e,h):l.lastIndexOf(e,h);if(u!==-1){this.state.cursorLine=a,this.setCursorCol(u);return}}}moveWordForwards(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=e.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(ws(e,this.state.cursorCol,{segment:t=>this.segment(t,"word"),isAtomicSegment:Dt}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return t.trim()===""||t.trim()==="/"}isInSlashCommandContext(e){return this.isSlashMenuAllowed()&&e.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(e,t){if(!t)return-1;let i=-1;for(let n=0;n<e.length;n++){let r=e[n].value;if(r===t)return n;i===-1&&r.startsWith(t)&&(i=n)}return i}createAutocompleteList(e,t){let i=e.startsWith("/")?dd:void 0,n=new Ve(t,this.autocompleteMaxVisible,this.theme.selectList,i);return n.onSelect=r=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let o=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,r,this.autocompletePrefix);this.state.lines=o.lines,this.state.cursorLine=o.cursorLine,this.setCursorCol(o.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText())},n}tryTriggerAutocomplete(e=!1){this.requestAutocomplete({force:!1,explicitTab:e})}handleTabCompletion(){if(!this.autocompleteProvider)return;let t=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(t)&&!t.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(e=!1){this.requestAutocomplete({force:!0,explicitTab:e})}requestAutocomplete(e){if(!this.autocompleteProvider||e.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let t=++this.autocompleteStartToken,i=this.getAutocompleteDebounceMs(e);if(i>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(t,e)},i);return}this.startAutocompleteRequest(t,e)}async startAutocompleteRequest(e,t){let i=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await i,e!==this.autocompleteStartToken||!this.autocompleteProvider)return;let n=new AbortController;this.autocompleteAbort=n;let r=++this.autocompleteRequestId,o=this.getText(),a=this.state.cursorLine,l=this.state.cursorCol;await this.runAutocompleteRequest(r,n,o,a,l,t)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(e){let t=[..._a];for(let i of e)i.length!==1||i==="/"||ue(i)||t.includes(i)||t.push(i);this.autocompleteTriggerCharacters=t,this.autocompleteTriggerPattern=Ia(t),this.autocompleteDebouncePattern=Pa(t)}getAutocompleteDebounceMs(e){if(e.explicitTab||e.force)return 0;let i=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(i)?pd:0}async runAutocompleteRequest(e,t,i,n,r,o){if(!this.autocompleteProvider)return;let a=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:t.signal,force:o.force});if(this.isAutocompleteRequestCurrent(e,t,i,n,r)){if(this.autocompleteAbort=void 0,!a||!Array.isArray(a.items)||a.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(o.force&&o.explicitTab&&a.items.length===1){let l=a.items[0];this.pushUndoSnapshot(),this.lastAction=null;let c=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,l,a.prefix);this.state.lines=c.lines,this.state.cursorLine=c.cursorLine,this.setCursorCol(c.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(a,o.force?"force":"regular"),this.tui.requestRender()}}isAutocompleteRequestCurrent(e,t,i,n,r){return!t.signal.aborted&&e===this.autocompleteRequestId&&this.getText()===i&&this.state.cursorLine===n&&this.state.cursorCol===r}applyAutocompleteSuggestions(e,t){this.autocompletePrefix=e.prefix,this.autocompleteList=this.createAutocompleteList(e.prefix,e.items);let i=this.getBestAutocompleteMatchIndex(e.items,e.prefix);i>=0&&this.autocompleteList.setSelectedIndex(i),this.autocompleteState=t}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&(clearTimeout(this.autocompleteDebounceTimer),this.autocompleteDebounceTimer=void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=""}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var Bt=Symbol.for("@earendil-works/pi-tui/layout-node");function xs(s){let e=s;return typeof e[Bt]=="function"?e[Bt]():void 0}function fd(s){return!("render"in s)}function fi(s,e){return s===void 0||!Number.isFinite(s)?e:Math.max(0,Math.floor(s))}var mi=class extends ee{entries=[];gap;align;constructor(e=[],t={}){super(),this.gap=fi(t.gap,0),this.align=t.align??"stretch";for(let i of e)fd(i)?this.addChild(i.component,i):this.addChild(i)}addChild(e,t={}){super.addChild(e),this.entries.push({component:e,...t.basis===void 0?{}:{basis:t.basis},...t.grow===void 0?{}:{grow:fi(t.grow,0)},...t.shrink===void 0?{}:{shrink:fi(t.shrink,1)},...t.minSize===void 0?{}:{minSize:fi(t.minSize,0)},...t.maxSize===void 0?{}:{maxSize:fi(t.maxSize,Number.MAX_SAFE_INTEGER)},...t.visible===void 0?{}:{visible:t.visible}})}removeChild(e){super.removeChild(e);let t=this.entries.findIndex(i=>i.component===e);t!==-1&&this.entries.splice(t,1)}clear(){super.clear(),this.entries.length=0}[Bt](){return{type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function gi(s,e){return s.filter(t=>t.visible?.(e)??!0)}function md(s,e){let t=Math.max(0,Math.floor(e.minSize??0)),i=Math.max(t,Math.floor(e.maxSize??Number.MAX_SAFE_INTEGER));return Math.max(t,Math.min(i,Math.max(0,Math.floor(s))))}function Da(s,e,t,i){let n=t;for(;n>0;){let r=e.map((l,c)=>({entry:l,index:c})).filter(({entry:l,index:c})=>i==="grow"?(l.grow??0)>0&&s[c]<(l.maxSize??Number.MAX_SAFE_INTEGER):(l.shrink??1)>0&&s[c]>(l.minSize??0));if(r.length===0)return;let o=r.reduce((l,{entry:c,index:h})=>l+(i==="grow"?c.grow??0:(c.shrink??1)*Math.max(1,s[h])),0),a=0;for(let{entry:l,index:c}of r){if(n<=0)break;let h=i==="grow"?l.grow??0:(l.shrink??1)*Math.max(1,s[c]),u=Math.max(1,Math.floor(n*h/o)),d=i==="grow"?(l.maxSize??Number.MAX_SAFE_INTEGER)-s[c]:s[c]-(l.minSize??0),p=Math.min(n,u,d);p<=0||(s[c]=s[c]+(i==="grow"?p:-p),n-=p,a+=p)}if(a===0)return}}function Nt(s,e,t,i){let n=s.map((a,l)=>md(a.basis===void 0||a.basis==="auto"?e[l]??0:a.basis,a));if(t===void 0)return n;let r=Math.max(0,Math.floor(t)-Math.max(0,s.length-1)*i),o=n.reduce((a,l)=>a+l,0);return o<r?Da(n,s,r-o,"grow"):o>r&&Da(n,s,o-r,"shrink"),n}var Ba,Ft=new Map;function gd(s,e){if(!Ba)return null;let t=Ft.get(s),i=t===void 0?Ba(s,e):t;return Ft.delete(s),Ft.set(s,i),Ft.size>32&&Ft.delete(Ft.keys().next().value),i}var bi=class{base64Data;mimeType;dimensions;theme;options;imageId;pngData;cachedLines;cachedWidth;constructor(e,t,i,n={},r){this.base64Data=e,this.mimeType=t,this.theme=i,this.options=n,this.dimensions=r||Zn(e,t)||{widthPx:800,heightPx:600},this.imageId=n.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0}render(e){if(this.cachedLines&&this.cachedWidth===e)return this.cachedLines;let t=Math.max(1,Math.min(e-2,this.options.maxWidthCells??60)),i=as(),n=Math.max(1,Math.ceil(t*i.widthPx/i.heightPx)),r=this.options.maxHeightCells??n,o=ae(),a=this.base64Data,l=this.dimensions;o.images==="kitty"&&this.mimeType!=="image/png"&&(this.pngData??=gd(this.base64Data,this.mimeType)??void 0,a=this.pngData??null,a&&(l=us(a)??l));let c;if(o.images&&a){o.images==="kitty"&&this.imageId===void 0&&(this.imageId=Gn());let h=er(a,l,{maxWidthCells:t,maxHeightCells:r,imageId:this.imageId,moveCursor:!1});if(h)if(h.imageId&&(this.imageId=h.imageId),o.images==="kitty"){c=[h.sequence];for(let u=0;u<h.rows-1;u++)c.push("")}else{c=[];for(let p=0;p<h.rows-1;p++)c.push("");let u=h.rows-1,d=u>0?`\x1B[${u}A`:"";c.push(d+h.sequence)}else{let u=ps(this.mimeType,this.dimensions,this.options.filename);c=[_(this.theme.fallbackColor(u),e)]}}else{let h=ps(this.mimeType,this.dimensions,this.options.filename);c=[_(this.theme.fallbackColor(h),e)]}return this.cachedLines=c,this.cachedWidth=e,c}};var nt=St(),Te=class{value="";cursor=0;prompt;placeholder;placeholderStyle;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new Ot;lastAction=null;undoStack=new qt;constructor(e={}){this.prompt=e.prompt??"> ",this.placeholder=e.placeholder??"",this.placeholderStyle=e.placeholderStyle??(t=>t)}getValue(){return this.value}setValue(e){this.value=e,this.cursor=Math.min(this.cursor,e.length)}handleInput(e){if(e.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",e=e.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=e;let r=this.pasteBuffer.indexOf("\x1B[201~");if(r!==-1){let o=this.pasteBuffer.substring(0,r);this.handlePaste(o),this.isInPaste=!1;let a=this.pasteBuffer.substring(r+6);this.pasteBuffer="",a&&this.handleInput(a)}return}let t=fe();if(t.matches(e,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(t.matches(e,"tui.editor.undo")){this.undo();return}if(t.matches(e,"tui.input.submit")||e===`
|
|
85
|
+
`){this.onSubmit&&this.onSubmit(this.value);return}if(t.matches(e,"tui.editor.deleteCharBackward")){this.handleBackspace();return}if(t.matches(e,"tui.editor.deleteCharForward")){this.handleForwardDelete();return}if(t.matches(e,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(t.matches(e,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(t.matches(e,"tui.editor.deleteToLineStart")){this.deleteToLineStart();return}if(t.matches(e,"tui.editor.deleteToLineEnd")){this.deleteToLineEnd();return}if(t.matches(e,"tui.editor.yank")){this.yank();return}if(t.matches(e,"tui.editor.yankPop")){this.yankPop();return}if(t.matches(e,"tui.editor.cursorLeft")){if(this.lastAction=null,this.cursor>0){let r=this.value.slice(0,this.cursor),o=[...nt.segment(r)],a=o[o.length-1];this.cursor-=a?a.segment.length:1}return}if(t.matches(e,"tui.editor.cursorRight")){if(this.lastAction=null,this.cursor<this.value.length){let r=this.value.slice(this.cursor),a=[...nt.segment(r)][0];this.cursor+=a?a.segment.length:1}return}if(t.matches(e,"tui.editor.cursorLineStart")){this.lastAction=null,this.cursor=0;return}if(t.matches(e,"tui.editor.cursorLineEnd")){this.lastAction=null,this.cursor=this.value.length;return}if(t.matches(e,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(t.matches(e,"tui.editor.cursorWordRight")){this.moveWordForwards();return}let i=rs(e);if(i!==void 0){this.insertCharacter(i);return}[...e].some(r=>{let o=r.charCodeAt(0);return o<32||o===127||o>=128&&o<=159})||this.insertCharacter(e)}handleMouse(e){if(e.type!=="press"||e.button!=="left"||e.y!==0)return;let t=Math.max(0,e.x-2),i=this.renderedStartColumn+t,n=0;this.cursor=this.value.length;for(let r of nt.segment(this.value)){let o=n+x(r.segment);if(i<o){this.cursor=r.index;break}n=o}return this.lastAction=null,{handled:!0,focus:!0}}insertCharacter(e){(ue(e)||this.lastAction!=="type-word")&&this.pushUndo(),this.lastAction="type-word",this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let e=this.value.slice(0,this.cursor),t=[...nt.segment(e)],i=t[t.length-1],n=i?i.segment.length:1;this.value=this.value.slice(0,this.cursor-n)+this.value.slice(this.cursor),this.cursor-=n}}handleForwardDelete(){if(this.lastAction=null,this.cursor<this.value.length){this.pushUndo();let e=this.value.slice(this.cursor),i=[...nt.segment(e)][0],n=i?i.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+n)}}deleteToLineStart(){if(this.cursor===0)return;this.pushUndo();let e=this.value.slice(0,this.cursor);this.killRing.push(e,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(this.cursor),this.cursor=0}deleteToLineEnd(){if(this.cursor>=this.value.length)return;this.pushUndo();let e=this.value.slice(this.cursor);this.killRing.push(e,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(this.cursor===0)return;let e=this.lastAction==="kill";this.pushUndo();let t=this.cursor;this.moveWordBackwards();let i=this.cursor;this.cursor=t;let n=this.value.slice(i,this.cursor);this.killRing.push(n,{prepend:!0,accumulate:e}),this.lastAction="kill",this.value=this.value.slice(0,i)+this.value.slice(this.cursor),this.cursor=i}deleteWordForward(){if(this.cursor>=this.value.length)return;let e=this.lastAction==="kill";this.pushUndo();let t=this.cursor;this.moveWordForwards();let i=this.cursor;this.cursor=t;let n=this.value.slice(this.cursor,i);this.killRing.push(n,{prepend:!1,accumulate:e}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)+this.value.slice(i)}yank(){let e=this.killRing.peek();e&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length,this.lastAction="yank")}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndo();let e=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor-e.length)+this.value.slice(this.cursor),this.cursor-=e.length,this.killRing.rotate();let t=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length,this.lastAction="yank"}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){let e=this.undoStack.pop();e&&(this.value=e.value,this.cursor=e.cursor,this.lastAction=null)}moveWordBackwards(){this.cursor!==0&&(this.lastAction=null,this.cursor=ys(this.value,this.cursor))}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=ws(this.value,this.cursor))}handlePaste(e){this.lastAction=null,this.pushUndo();let t=e.replace(/\r\n/g,"").replace(/\r/g,"").replace(/\n/g,"").replace(/\t/g," ");this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length}invalidate(){}render(e){let t=e-x(this.prompt);if(t<=0)return[_(this.prompt,e,"")];if(this.value.length===0&&this.placeholder){let g=_(this.placeholder,t,""),w=[...nt.segment(g)][0]?.segment??" ",k=g.slice(w.length),P=this.focused?pe:"",v=it(this.placeholderStyle(w)),A=P+v+this.placeholderStyle(k),E=" ".repeat(Math.max(0,t-x(A)));return[this.prompt+A+E]}let i="",n=this.cursor;this.renderedStartColumn=0;let r=x(this.value);if(r<t)i=this.value;else{let g=this.cursor===this.value.length?t-1:t,y=x(this.value.slice(0,this.cursor));if(g>0){let w=Math.floor(g/2),k=0;y<w?k=0:y>r-w?k=Math.max(0,r-g):k=Math.max(0,y-w),this.renderedStartColumn=k,i=H(this.value,k,g,!0),n=H(this.value,k,Math.max(0,y-k),!0).length}else i="",n=0}let a=[...nt.segment(i.slice(n))][0],l=i.slice(0,n),c=a?.segment??" ",h=i.slice(n+c.length),u=this.focused?pe:"",d=it(c),p=l+u+d+h,f=x(p),m=" ".repeat(Math.max(0,t-f));return[this.prompt+p+m]}};var $e="\\u1100-\\u11ff\\u20a9\\u2329-\\u232a\\u2630-\\u2637\\u268a-\\u268f\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u2ff0-\\u303e\\u3041-\\u3096\\u3099-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u31e5\\u31ef-\\u321e\\u3220-\\u3247\\u3250-\\ua48c\\ua490-\\ua4c6\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufaff\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe66\\ufe68-\\ufe6b\\uff01-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\\uffe0-\\uffe6\\uffe8-\\uffee\\u{16fe0}-\\u{16fe4}\\u{16ff0}-\\u{16ff6}\\u{17000}-\\u{18cda}\\u{18cff}-\\u{18d20}\\u{18d80}-\\u{18df2}\\u{18e00}-\\u{19191}\\u{191a0}-\\u{191d2}\\u{1aff0}-\\u{1aff3}\\u{1aff5}-\\u{1affb}\\u{1affd}-\\u{1affe}\\u{1b000}-\\u{1b128}\\u{1b132}\\u{1b150}-\\u{1b152}\\u{1b155}\\u{1b164}-\\u{1b168}\\u{1b170}-\\u{1b2fb}\\u{1d300}-\\u{1d356}\\u{1d360}-\\u{1d376}\\u{1f1ae}\\u{1f200}\\u{1f202}\\u{1f210}-\\u{1f219}\\u{1f21b}-\\u{1f22e}\\u{1f230}-\\u{1f231}\\u{1f237}\\u{1f23b}\\u{1f240}-\\u{1f248}\\u{1f260}-\\u{1f265}\\u{1f7da}\\u{20000}-\\u{3fffd}",Wt=new RegExp(`[${$e}]`,"u"),bd=new RegExp(`^((?![*_])[\\s\\p{P}\\p{S}${$e}])`,"u");function Ua(s,e,t){return new RegExp(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)${s}(\\*+)(?=[\\s]|$)|${t}(\\*+)(?!\\*)(?=${e}|$)|(?!\\*)${e}(\\*+)(?=${t})|[\\s](\\*+)(?!\\*)(?=${s})|(?!\\*)${s}(\\*+)(?!\\*)(?=${s})|${t}(\\*+)(?=${t})`,"gu")}function yd(s,e,t){return new RegExp(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)${s}(_+)(?=[\\s]|$)|${t}(_+)(?!_)(?=${e}|$)|(?!_)${e}(_+)(?=${t})|[\\s](_+)(?!_)(?=${s})|(?!_)${s}(_+)(?!_)(?=${s})`,"gu")}function wd(s,e,t){return new RegExp(`^[^~]+(?=[^~])|(?!~)${s}(~~?)(?=[\\s]|$)|${t}(~~?)(?!~)(?=${e}|$)|(?!~)${e}(~~?)(?=${t})|[\\s](~~?)(?!~)(?=${s})|(?!~)${s}(~~?)(?!~)(?=${s})|${t}(~~?)(?=${t})`,"gu")}var Ka=`[\\p{P}\\p{S}${$e}]`,Ha=`[\\s\\p{P}\\p{S}${$e}]`,za=`[^\\s\\p{P}\\p{S}${$e}]`,xd=`(?![*_])[\\p{P}\\p{S}${$e}]`,vd=`(?![*_])[\\s\\p{P}\\p{S}${$e}]`,kd=`(?:[^\\s\\p{P}\\p{S}${$e}]|[*_])`,Sd=`(?!~)[\\p{P}\\p{S}${$e}]`,Cd=`(?!~)[\\s\\p{P}\\p{S}${$e}]`,$d=`(?:[^\\s\\p{P}\\p{S}${$e}]|~)`,Ad=Ua(Ka,Ha,za),Td=Ua(Sd,Cd,$d),_d=yd(Ka,Ha,za),Na=wd(xd,vd,kd);function Fa(s,e,t){let i=bd.test(s);if(!i&&s){let n=e.length-t.length;if(n>=1){let r=n-1,o=e.charCodeAt(r);if(o>=65024&&o<=65038&&r>=1&&(r--,o=e.charCodeAt(r)),(o&64512)===56320&&r>=1){let a=e.codePointAt(r-1);a!==void 0&&a>65535&&(a>=917760&&a<=917999?i=!0:i=Wt.test(String.fromCodePoint(a)))}else i=Wt.test(String.fromCharCode(o))}}return i}function Wa(s,e){if(!(s[1]||s[2]||s[3]||s[4]))return!1;let t=String.fromCodePoint(s[0].codePointAt(0)),i=s.index+s[0].length,n=i<e.length?String.fromCodePoint(e.codePointAt(i)):"";return Wt.test(t)||Wt.test(n)}function hr(s){return s.length>=5}function Id(s){return!!(s[1]||s[2]||s[3]||s[4])}function Pd(s){return hr(s)?!!s[4]:!!s[3]}function Rd(s){return hr(s)?s[1]||s[3]||"":s[1]||s[2]||""}function Va(){return{tokenizer:{emStrong(s,e,t=""){let{rules:i}=this,n=i.inline.emStrongLDelim.exec(s);if(!n)return!1;let r=hr(n);if(r&&!Id(n))return;if(Pd(n)&&t.match(i.other.unicodeAlphaNumeric))return!1;let o=Rd(n),a=Fa(t,e,s);if(!o||!t||i.inline.punctuation.exec(t)||a||Wt.test(o)){let l=[...n[0]].length-1,c,h,u=l,d=0,p=r&&t===n[0][0],f=i.inline.emStrongRDelimAst.source.includes("(?!~)"),m;n[0][0]==="*"?m=f?Td:Ad:m=_d,m.lastIndex=0;let b=e.slice(-1*s.length+l),g;for(;(g=m.exec(b))!=null;){if(c=g[1]||g[2]||g[3]||g[4]||g[5]||g[6],!c)continue;h=[...c].length;let y=Wa(g,b),w=!!(g[3]||g[4]),k=!!(g[5]||g[6]);if(w&&!y){u+=h;continue}if(k||y){if(l%3&&!((l+h)%3)){d+=h;continue}if(p&&k)break}if(u-=h,u>0)continue;h=Math.min(h,h+u+d);let P=g[0].codePointAt(0)>65535?2:1,v=s.slice(0,l+g.index+P+h);if(Math.min(l,h)%2){let E=v.slice(1,-1);return{type:"em",raw:v,text:E,tokens:this.lexer.inlineTokens(E)}}let A=v.slice(2,-2);return{type:"strong",raw:v,text:A,tokens:this.lexer.inlineTokens(A)}}}},del(s,e,t=""){let{rules:i}=this,n=i.inline.delLDelim.exec(s);if(!n)return!1;let r=n[1]||"",o=Fa(t,e,s);if(!r||!t||i.inline.punctuation.exec(t)||o||Wt.test(r)){let a=[...n[0]].length-1,l,c,h=a;Na.lastIndex=0;let u=e.slice(-1*s.length+a),d;for(;(d=Na.exec(u))!=null;){if(l=d[1]||d[2]||d[3]||d[4]||d[5]||d[6],!l||(c=[...l].length,c!==a))continue;let p=Wa(d,u);if((d[3]||d[4])&&!p){h+=c;continue}if(h-=c,h>0)continue;c=Math.min(c,c+h);let f=d[0].codePointAt(0)>65535?2:1,m=s.slice(0,a+d.index+f+c),b=m.slice(a,-a);return{type:"del",raw:m,text:b,tokens:this.lexer.inlineTokens(b)}}}}}}}var Md={alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03F5",varepsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",vartheta:"\u03D1",iota:"\u03B9",kappa:"\u03BA",varkappa:"\u03F0",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",pi:"\u03C0",varpi:"\u03D6",rho:"\u03C1",varrho:"\u03F1",sigma:"\u03C3",varsigma:"\u03C2",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03D5",varphi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",Gamma:"\u0393",Delta:"\u0394",Theta:"\u0398",Lambda:"\u039B",Xi:"\u039E",Pi:"\u03A0",Sigma:"\u03A3",Upsilon:"\u03A5",Phi:"\u03A6",Psi:"\u03A8",Omega:"\u03A9",pm:"\xB1",mp:"\u2213",times:"\xD7",div:"\xF7",cdot:"\xB7",ast:"\u2217",star:"\u22C6",circ:"\u2218",bullet:"\u2022",oplus:"\u2295",ominus:"\u2296",otimes:"\u2297",oslash:"\u2298",odot:"\u2299",bigcirc:"\u25CB",dagger:"\u2020",ddagger:"\u2021",amalg:"\u2A3F",uplus:"\u228E",sqcap:"\u2293",sqcup:"\u2294",bowtie:"\u22C8",Join:"\u22C8",ltimes:"\u22C9",rtimes:"\u22CA",leftouterjoin:"\u27D5",rightouterjoin:"\u27D6",fullouterjoin:"\u27D7",triangleleft:"\u25C1",triangleright:"\u25B7",wr:"\u2240",cap:"\u2229",cup:"\u222A",bigcap:"\u22C2",bigcup:"\u22C3",bigwedge:"\u22C0",bigvee:"\u22C1",bigsqcup:"\u2A06",biguplus:"\u2A04",bigoplus:"\u2A01",bigotimes:"\u2A02",bigodot:"\u2A00",setminus:"\u2216",in:"\u2208",notin:"\u2209",ni:"\u220B",subset:"\u2282",supset:"\u2283",subseteq:"\u2286",supseteq:"\u2287",sqsubset:"\u228F",sqsupset:"\u2290",sqsubseteq:"\u2291",sqsupseteq:"\u2292",prec:"\u227A",preceq:"\u227C",succ:"\u227B",succeq:"\u227D",ll:"\u226A",gg:"\u226B",le:"\u2264",leq:"\u2264",leqslant:"\u2264",ge:"\u2265",geq:"\u2265",geqslant:"\u2265",ne:"\u2260",neq:"\u2260",equiv:"\u2261",approx:"\u2248",sim:"\u223C",simeq:"\u2243",cong:"\u2245",asymp:"\u224D",doteq:"\u2250",propto:"\u221D",parallel:"\u2225",perp:"\u22A5",mid:"\u2223",vdash:"\u22A2",dashv:"\u22A3",models:"\u22A8",Vdash:"\u22A9",Vvdash:"\u22AA",nvdash:"\u22AC",nvDash:"\u22AD",forall:"\u2200",exists:"\u2203",nexists:"\u2204",neg:"\xAC",land:"\u2227",wedge:"\u2227",lor:"\u2228",vee:"\u2228",to:"\u2192",rightarrow:"\u2192",longrightarrow:"\u2192",leftarrow:"\u2190",longleftarrow:"\u2190",gets:"\u2190",leftrightarrow:"\u2194",longleftrightarrow:"\u2194",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",leftharpoonup:"\u21BC",leftharpoondown:"\u21BD",rightharpoonup:"\u21C0",rightharpoondown:"\u21C1",rightleftharpoons:"\u21CC",leftrightharpoons:"\u21CB",nearrow:"\u2197",searrow:"\u2198",swarrow:"\u2199",nwarrow:"\u2196",rightsquigarrow:"\u21DD",leadsto:"\u21DD",Rightarrow:"\u21D2",Longrightarrow:"\u21D2",Leftarrow:"\u21D0",Longleftarrow:"\u21D0",Leftrightarrow:"\u21D4",Longleftrightarrow:"\u21D4",implies:"\u21D2",iff:"\u21D4",mapsto:"\u21A6",longmapsto:"\u21A6",uparrow:"\u2191",downarrow:"\u2193",partial:"\u2202",nabla:"\u2207",int:"\u222B",iint:"\u222C",iiint:"\u222D",oint:"\u222E",sum:"\u2211",prod:"\u220F",coprod:"\u2210",infty:"\u221E",emptyset:"\u2205",varnothing:"\u2205",angle:"\u2220",therefore:"\u2234",because:"\u2235",aleph:"\u2135",beth:"\u2136",gimel:"\u2137",daleth:"\u2138",top:"\u22A4",bot:"\u22A5",triangle:"\u25B3",square:"\u25A1",lozenge:"\u25CA",checkmark:"\u2713",complement:"\u2201",wp:"\u2118",prime:"\u2032",ldots:"\u2026",dots:"\u2026",cdots:"\u22EF",vdots:"\u22EE",ddots:"\u22F1",ell:"\u2113",hbar:"\u210F",Im:"\u2111",Re:"\u211C",langle:"\u27E8",rangle:"\u27E9",vert:"|",lvert:"|",rvert:"|",Vert:"\u2016",lVert:"\u2016",rVert:"\u2016",lbrace:"{",rbrace:"}",backslash:"\\",lfloor:"\u230A",rfloor:"\u230B",lceil:"\u2308",rceil:"\u2309",colon:":"},Ed=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"]),Ld=new Set(["argmax","argmin","inf","injlim","lim","liminf","limsup","max","min","projlim","sup"]),Od=new Set(["bigcap","bigcup","bigodot","bigoplus","bigotimes","bigsqcup","biguplus","bigvee","bigwedge","coprod","int","iint","iiint","oint","prod","sum"]),qd=new Set(["Leftarrow","Leftrightarrow","Longleftarrow","Longleftrightarrow","Longrightarrow","Rightarrow","Join","Vdash","Vvdash","approx","asymp","bowtie","cong","dashv","fullouterjoin","doteq","downarrow","equiv","ge","geq","geqslant","gets","gg","hookleftarrow","hookrightarrow","iff","implies","in","leadsto","le","leftarrow","leftharpoondown","leftharpoonup","leftrightarrow","leftrightharpoons","leftouterjoin","leq","leqslant","ll","longleftarrow","longleftrightarrow","longmapsto","longrightarrow","ltimes","mapsto","mid","models","ne","nearrow","neq","ni","notin","nvdash","nvDash","nwarrow","parallel","perp","prec","preceq","propto","rightharpoondown","rightharpoonup","rightleftharpoons","rightouterjoin","rightarrow","rightsquigarrow","rtimes","searrow","sim","simeq","sqsubset","sqsubseteq","sqsupset","sqsupseteq","subset","subseteq","succ","succeq","supset","supseteq","swarrow","to","triangleleft","triangleright","twoheadleftarrow","twoheadrightarrow","uparrow","vdash"]),Dd={"<":"\u226E",">":"\u226F","=":"\u2260","\u2208":"\u2209","\u220B":"\u220C","\u2223":"\u2224","\u2225":"\u2226","\u223C":"\u2241","\u2243":"\u2244","\u2245":"\u2247","\u2248":"\u2249","\u2261":"\u2262","\u2264":"\u2270","\u2265":"\u2271","\u227A":"\u2280","\u227B":"\u2281","\u2282":"\u2284","\u2283":"\u2285","\u2286":"\u2288","\u2287":"\u2289","\u22A2":"\u22AC","\u22A8":"\u22AD","\u2194":"\u21AE","\u2190":"\u219A","\u2192":"\u219B","\u21D2":"\u21CF","\u21D0":"\u21CD","\u21D4":"\u21CE","\u227C":"\u22E0","\u227D":"\u22E1"},Bd={C:"\u2102",H:"\u210D",N:"\u2115",P:"\u2119",Q:"\u211A",R:"\u211D",Z:"\u2124"},Nd={0:"\u2070",1:"\xB9",2:"\xB2",3:"\xB3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},Fd={0:"\u2080",1:"\u2081",2:"\u2082",3:"\u2083",4:"\u2084",5:"\u2085",6:"\u2086",7:"\u2087",8:"\u2088",9:"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"},Wd=new Set([",",":",";"," ",">","enspace","enskip","medspace","quad","qquad","thickspace","thinspace"]),Ud=new Set(["!","negmedspace","negthickspace","negthinspace"]),ja="\0",Kd=new Set(["bf","cal","it","rm","sf","sl","tt"]),Hd=new Set(["displaystyle","limits","nolimits","scriptstyle","scriptscriptstyle","textstyle"]),zd=new Set(["big","Big","bigg","Bigg","bigl","Bigl","biggl","Biggl","bigr","Bigr","biggr","Biggr"]),Vd=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"]),jd={acute:"\u0301",bar:"\u0305",breve:"\u0306",check:"\u030C",ddot:"\u0308",dot:"\u0307",grave:"\u0300",hat:"\u0302",mathring:"\u030A",overleftarrow:"\u20D6",overleftrightarrow:"\u20E1",overline:"\u0305",overrightarrow:"\u20D7",tilde:"\u0303",underline:"\u0332",vec:"\u20D7",widehat:"\u0302",widetilde:"\u0303"};function Gd(s,e){let t="";for(let i of s){let n=e[i];if(n===void 0)return;t+=n}return t}function Ga(s){return s.trim().replace(/\s*([=+-])\s*/g,"$1")}function ur(s,e){return Gd(Ga(s),e==="sub"?Fd:Nd)}function rt(s,e){s=Ga(s);let t=ur(s,e);if(t!==void 0)return t;let i=e==="sub"?"_":"^";return Array.from(s).length===1||e==="sub"&&/^[A-Za-z]+$/.test(s)?`${i}${s}`:`${i}(${s})`}function Qd(s,e){s=s.trim(),e=e.trim();let t=/^[\p{L}\p{N}.]+$/u.test(s),i=/^[\p{N}.]+$/u.test(e)||Array.from(e).length===1;return`${t?s:`(${s})`}/${i?e:`(${e})`}`}function vs(s,e="\u221A"){return s=s.trim(),/^[\p{L}\p{N}.]+$/u.test(s)?`${e}${s}`:`${e}(${s})`}var Qa="\u{F0004}",at="\u{F0005}",Yd=/(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu,Xd=/\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu;function ot(s){return s.replace(Yd," ").replaceAll(Qa,"").replace(Xd," ").replaceAll(at,"").split(`
|
|
86
86
|
`).map(e=>e.replace(/[ \t]+/g," ").trim()).filter((e,t,i)=>e.length>0||t>0&&t<i.length-1).join(`
|
|
87
|
-
`).trim()}var
|
|
88
|
-
`)){let r=[],o=0,a;for(let c of n.matchAll(
|
|
87
|
+
`).trim()}var Ut="\u{F0000}",yi="\u{F0001}",Jd=/\u{f0000}(\d+)\u{f0001}/gu,Zd=/\u{f0000}(\d+)\u{f0001}$/u,ks="\u{F0002}";function Oe(s,e,t=!1){let i=Math.max(0,e-x(s)),n=t?Math.floor(i/2):0;return`${" ".repeat(n)}${s}${" ".repeat(i-n)}`}function ep(s){if(s.length===0)return{lines:[""],width:0,baseline:0};let e=Math.max(...s.map(n=>n.baseline)),t=Math.max(...s.map(n=>n.lines.length-n.baseline-1)),i=[];for(let n=0;n<=e+t;n++){let r="";for(let o of s){let a=n-e+o.baseline;r+=a>=0&&a<o.lines.length?Oe(o.lines[a]??"",o.width):" ".repeat(o.width)}i.push(r.trimEnd())}return{lines:i,width:s.reduce((n,r)=>n+r.width,0),baseline:e}}function wi(s,e){let t=[],i=0;for(let n of s.split(`
|
|
88
|
+
`)){let r=[],o=0,a;for(let c of n.matchAll(Jd)){let h=c.index,u=e[Number(c[1])];if(u){if(h>o){let d=n.slice(o,h),p=(a?d.trimStart():d).trimEnd(),f=a?.type==="matrix"&&/^\s/.test(d),m=u.type==="matrix"&&/\s$/.test(d),b=p?`${f?" ":""}${p}${m?" ":""}`:f||m?" ":"";r.push({lines:[b],width:x(b),baseline:0})}if(u.type==="fraction"){let d=wi(u.numerator,e),p=wi(u.denominator,e),f=Math.max(d.width,p.width,1),m=f+2;r.push({lines:[...d.lines.map(b=>Oe(b,m,!0)),` ${"\u2500".repeat(f)} `,...p.lines.map(b=>Oe(b,m,!0))],width:m,baseline:d.lines.length})}else if(u.type==="operator"){let d=Math.max(x(u.operator),u.lower===void 0?0:x(u.lower),u.upper===void 0?0:x(u.upper)),p=[];u.upper!==void 0&&p.push(`${Oe(u.upper,d,!0)} `),p.push(`${Oe(u.operator,d,!0)} `),u.lower!==void 0&&p.push(`${Oe(u.lower,d,!0)} `),r.push({lines:p,width:d+1,baseline:u.upper===void 0?0:1})}else if(u.type==="script"){let d=u.upper===void 0?void 0:wi(u.upper,e),p=u.lower===void 0?void 0:wi(u.lower,e),f=Math.max(d?.width??0,p?.width??0);r.push({lines:[...d?.lines.map(m=>Oe(m,f))??[]," ".repeat(f),...p?.lines.map(m=>Oe(m,f))??[]],width:f,baseline:d?.lines.length??0})}else{let d=Math.max(0,...u.lines.map(p=>x(p)));r.push({lines:u.lines.map(p=>Oe(p,d)),width:d,baseline:u.baseline})}o=h+c[0].length,a=u}}if(o<n.length){let c=n.slice(o),h=a?c.trimStart():c,u=a?.type==="matrix"&&/^\s/.test(c)?` ${h}`:h;r.push({lines:[u],width:x(u),baseline:0})}let l=ep(r);t.length===0&&(i=l.baseline),t.push(...l.lines)}return{lines:t,width:Math.max(0,...t.map(n=>x(n))),baseline:i}}var dr=class s{source;layoutNodes;display;position=0;supported=!0;stackFractions=!0;scriptDepth=0;constructor(e,t,i){this.source=e,this.layoutNodes=t,this.display=i}render(){let e=this.parseSequence();if(!(!this.supported||this.position!==this.source.length))return ot(e)}parseSequence(e){let t="";for(;this.position<this.source.length;){let i=this.source[this.position];if(e&&i===e)return this.position++,t;if(i==="}")return this.supported=!1,t;if(i==="{"){this.position++,t+=this.parseSequence("}");continue}if(i==="\\"){let n=this.parseCommand();n===ja?(t=t.trimEnd(),t.endsWith(at)&&(t=t.slice(0,-at.length))):t+=n;continue}if(i==="^"||i==="_"){this.position++,t=t.trimEnd();let n=this.parseScripts(i);t.endsWith(at)?t=`${t.slice(0,-at.length)}${n}${at}`:t+=n;continue}if(/\s/.test(i)){t+=this.parseWhitespace();continue}if(i==="="||i==="<"||i===">"){t=`${t.trimEnd()} ${i} `,this.position++;continue}if(i==="&"){this.position++;continue}if(i==="~"){this.position++,t+=" ";continue}if(i==="."){let n=Zd.exec(t),r=n?this.layoutNodes[Number(n[1])]:void 0;if(r?.type==="matrix"){let o=r.lines.length-1;r.lines[o]=`${r.lines[o]??""}${i}`,this.position++;continue}}t+=i,this.position++}return e&&(this.supported=!1),t}parseScripts(e){let t={},i=[],n=d=>{let p=d==="_"?"sub":"sup";this.scriptDepth++;try{t[p]=this.parseRequiredArgument(!1)}finally{this.scriptDepth--}i.push(p)};n(e);let r=this.position;for(;r<this.source.length&&/\s/.test(this.source[r]??"");)r++;let o=this.source[r];(o==="^"||o==="_")&&o!==e&&(this.position=r+1,n(o));let a=t.sub===void 0?void 0:ur(t.sub,"sub"),l=t.sup===void 0?void 0:ur(t.sup,"sup"),c=![t.sub,t.sup].some(d=>d!==void 0&&(d.includes("/")||!d.includes(Ut)&&Array.from(d).length>1&&!/[A-Z*∗]/.test(d)));if(!(this.display&&c&&(this.scriptDepth>0||t.sub!==void 0&&a===void 0||t.sup!==void 0&&l===void 0)))return i.map(d=>d==="sub"?a??rt(t.sub??"",d):l??rt(t.sup??"",d)).join("");let u=this.layoutNodes.push({type:"script",lower:t.sub===void 0?void 0:ot(t.sub),upper:t.sup===void 0?void 0:ot(t.sup)})-1;return`${Ut}${u}${yi}`}parseWhitespace(){for(;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 e="",t=this.source[this.position]??"";if(t===`
|
|
89
89
|
`||t==="\r")return this.position++,t==="\r"&&this.source[this.position]===`
|
|
90
90
|
`&&this.position++," ";if(/[A-Za-z]/.test(t)){let r=this.position;for(;this.position<this.source.length&&/[A-Za-z]/.test(this.source[this.position]??"");)this.position++;e=this.source.slice(r,this.position)}else e=t,this.position++;if(e==="\\")return`
|
|
91
|
-
`;if(
|
|
92
|
-
`)}if(e==="cases"||e==="cases*")return this.renderCases(n);if(["array","matrix","smallmatrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix"].includes(e)){let r=e==="array"?n.replace(/^\s*\{[^}]*\}/,""):n;return this.renderMatrix(e,r)}return this.supported=!1,n}renderCases(e){let t=this.splitEnvironmentRows(e).map(c=>c.split("&").map(h=>this.renderNested(h,!1).trim())).filter(c=>c.some(Boolean)),i=Math.max(0,...t.map(c=>x((c[0]??"").replace(/,\s*$/,"")))),n=t.map(c=>{let h=(c[0]??"").replace(/,\s*$/,""),u=c[1]??"";if(!u)return h;let d=/^(?:if|when|for|otherwise)\b/i.test(u)?" ":" if ";return`${h}${
|
|
93
|
-
`);a=o.map((u,d)=>{let p=d===0?h[0]:d===o.length-1?h[4]:h[2],f=d===0?h[1]:d===o.length-1?h[5]:h[3];return`${p} ${u} ${f}`})}if(a.length<=1)return a[0]??"";let l=this.layoutNodes.push({type:"matrix",lines:a,baseline:0})-1;return`${
|
|
94
|
-
`).trimEnd().replaceAll(
|
|
95
|
-
`)?void 0:{type:"latex",raw:s.slice(0,i+t.length),text:n}}var
|
|
96
|
-
`);for(let t=0;t<e.length-1;t++){let i=e[t+1];if((i.includes("|")||e[t].includes("|"))&&
|
|
97
|
-
`)?1:0):void 0},tokenizer:
|
|
98
|
-
`).pop();!t||!i||i.length>=t.length||i!==t[0]?.repeat(i.length)||(e.text=e.text.slice(0,-i.length).replace(/\n$/,""))}var
|
|
91
|
+
`;if(Wd.has(e))return" ";if(Ud.has(e))return ja;if(Kd.has(e)){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;return""}if(Hd.has(e))return"";if(e==="{"||e==="}"||e==="$"||e==="%"||e==="#"||e==="_"||e==="&")return e;if(e==="|")return"\u2016";if(e==="not"){let r=this.parseRequiredArgument(!1).trim(),o=Dd[r];if(o!==void 0)return` ${o} `;let a=Array.from(r);return a.length===0?(this.supported=!1,""):` ${a[0]}\u0338${a.slice(1).join("")} `}if(Ld.has(e))return this.parseOperator(e,"bracket",!0,!0);let i=Md[e];if(i!==void 0)return Od.has(e)?this.parseOperator(i,"script",!0):e==="cdot"||e==="times"||qd.has(e)?` ${i} `:i;if(Ed.has(e))return`${Qa}${e}${at}`;if(zd.has(e))return"";if(e==="left"||e==="middle"||e==="right")return this.source[this.position]==="."&&this.position++,"";if(e==="frac"||e==="dfrac"||e==="tfrac"){let r=this.display&&this.stackFractions&&e!=="tfrac",o=this.parseRequiredArgument(!r),a=this.parseRequiredArgument(!r);if(r){let l=this.layoutNodes.push({type:"fraction",numerator:ot(o),denominator:ot(a)})-1;return`${Ut}${l}${yi}`}return Qd(o,a)}if(e==="sqrt"){let r=this.parseOptionalArgument()?.trim(),o=this.parseRequiredArgument();return r===void 0||r==="2"?vs(o):r==="3"?vs(o,"\u221B"):r==="4"?vs(o,"\u221C"):`${rt(r,"sup")}${vs(o)}`}if(e==="boxed"||e==="fbox")return`[${this.parseRequiredArgument().trim()}]`;if(e==="binom"||e==="dbinom"||e==="tbinom")return`(${this.parseRequiredArgument()} choose ${this.parseRequiredArgument()})`;let n=jd[e];if(n!==void 0){let r=this.parseRequiredArgument();return Array.from(r).length===1?`${r}${n}`:`${e}(${r})`}if(e==="mathbb"){let r=this.parseRequiredArgument();return Array.from(r,o=>Bd[o]??o).join("")}if(e==="operatorname"){let r=this.source[this.position]==="*";r&&this.position++;let o=ot(this.parseRequiredArgument()).trim();return this.parseOperator(o,"bracket",r,!0)}if(e==="mod"||e==="bmod")return" mod ";if(e==="pmod"||e==="pod"){let r=this.parseRequiredArgument().trim();return e==="pmod"?` (mod ${r})`:` (${r})`}if(e==="overset"||e==="stackrel"){let r=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${rt(r,"sup")}`}if(e==="underset"){let r=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${rt(r,"sub")}`}if(Vd.has(e)){let r=this.parseRequiredArgument();return e.startsWith("text")||e==="mbox"?r:r.trim()}return e==="begin"?this.parseEnvironment():e==="end"?(this.supported=!1,""):(this.supported=!1,`\\${e}`)}parseOperator(e,t,i,n=!1){let r=i,o=this.position;for(;o<this.source.length&&/[ \t]/.test(this.source[o]??"");)o++;let a=/^\\(limits|nolimits)(?![A-Za-z])/.exec(this.source.slice(o));a&&(r=a[1]==="limits",this.position=o+a[0].length);let l,c;for(;;){let u=this.position;for(;u<this.source.length&&/[ \t]/.test(this.source[u]??"");)u++;let d=this.source[u];if(d!=="_"&&d!=="^")break;this.position=u+1;let p=ot(this.parseRequiredArgument(!1)).replaceAll(" ","");d==="_"?(l!==void 0&&(this.supported=!1),l=p):(c!==void 0&&(this.supported=!1),c=p)}if(this.display&&r&&(l!==void 0||c!==void 0)){let u=this.layoutNodes.push({type:"operator",operator:e,lower:l,upper:c})-1;return`${Ut}${u}${yi}`}let h=e;return l!==void 0&&(h+=t==="bracket"?`[${l}]`:rt(l,"sub")),c!==void 0&&(h+=rt(c,"sup")),n?` ${h} `:h}parseRequiredArgument(e=!0){let t=this.stackFractions;this.stackFractions=t&&e;let i=this.parseRequiredArgumentValue();return this.stackFractions=t,i}parseRequiredArgumentValue(){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;if(this.position>=this.source.length)return this.supported=!1,"";if(this.source[this.position]==="{")return this.position++,this.parseSequence("}");if(this.source[this.position]==="\\")return this.parseCommand();let e=this.source[this.position]??"";return this.position++,e}parseOptionalArgument(){for(;this.position<this.source.length&&/[ \t]/.test(this.source[this.position]??"");)this.position++;if(this.source[this.position]!=="[")return;let e=this.source.indexOf("]",this.position+1);if(e<0){this.supported=!1;return}let t=this.source.slice(this.position+1,e);return this.position=e+1,this.renderNested(t)}readRawGroup(){for(;this.position<this.source.length&&/[ \t]/.test(this.source[this.position]??"");)this.position++;if(this.source[this.position]!=="{"){this.supported=!1;return}let e=++this.position,t=1;for(;this.position<this.source.length;){let i=this.source[this.position];if(i==="\\"){this.position+=2;continue}if(i==="{"&&t++,i==="}"&&t--,t===0){let n=this.source.slice(e,this.position);return this.position++,n}this.position++}this.supported=!1}splitEnvironmentRows(e){return e.split(/\\\\(?:\[[^\]\n]*\])?/)}parseEnvironment(){let e=this.readRawGroup();if(!e)return"";let t=`\\end{${e}}`,i=this.source.indexOf(t,this.position);if(i<0)return this.supported=!1,"";let n=this.source.slice(this.position,i);if(this.position=i+t.length,e==="equation"||e==="equation*"||e==="displaymath")return this.renderNested(n).trim();if(e==="aligned"||e==="align"||e==="align*"||e==="alignedat"||e==="alignat"||e==="alignat*"||e==="gather"||e==="gathered"||e==="multline"||e==="multline*"||e==="split"){let r=["alignedat","alignat","alignat*"].includes(e),o=r?n.replace(/^\s*\{[^}]*\}/,""):n;return this.splitEnvironmentRows(o).map(a=>{let l=a.split("&"),c=r?Array.from({length:Math.ceil(l.length/2)},(h,u)=>l.slice(u*2,u*2+2).join("")).join(" "):l.join("");return this.renderNested(c).trim()}).filter(Boolean).join(`
|
|
92
|
+
`)}if(e==="cases"||e==="cases*")return this.renderCases(n);if(["array","matrix","smallmatrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix"].includes(e)){let r=e==="array"?n.replace(/^\s*\{[^}]*\}/,""):n;return this.renderMatrix(e,r)}return this.supported=!1,n}renderCases(e){let t=this.splitEnvironmentRows(e).map(c=>c.split("&").map(h=>this.renderNested(h,!1).trim())).filter(c=>c.some(Boolean)),i=Math.max(0,...t.map(c=>x((c[0]??"").replace(/,\s*$/,"")))),n=t.map(c=>{let h=(c[0]??"").replace(/,\s*$/,""),u=c[1]??"";if(!u)return h;let d=/^(?:if|when|for|otherwise)\b/i.test(u)?" ":" if ";return`${h}${ks.repeat(i-x(h))}${d}${u}`});if(n.length<=1)return n.length===0?"":`\u23A7 ${n[0]}`;let r=Math.floor(n.length/2),o=[...n];n.length%2===0&&o.splice(r,0,void 0);let a=o.map((c,h)=>{let u=h===0?"\u23A7":h===o.length-1?"\u23A9":"\u23A8";return c===void 0?u:`${u} ${c}`}),l=this.layoutNodes.push({type:"matrix",lines:a,baseline:r})-1;return`${Ut}${l}${yi}`}renderMatrix(e,t){let i=this.splitEnvironmentRows(t).map(c=>c.split("&").map(h=>this.renderNested(h,!1).trim())).filter(c=>c.some(Boolean)),n=Math.max(0,...i.map(c=>c.length)),r=Array.from({length:n},(c,h)=>Math.max(0,...i.map(u=>x(u[h]??"")))),o=i.map(c=>Array.from({length:n},(h,u)=>{let d=c[u]??"";return`${d}${ks.repeat(Math.max(0,(r[u]??0)-x(d)))}`}).join(" \u2502 ")),a;if(e==="array"||e==="matrix"||e==="smallmatrix")a=o;else{let h={pmatrix:["\u239B","\u239E","\u239C","\u239F","\u239D","\u23A0"],bmatrix:["\u23A1","\u23A4","\u23A2","\u23A5","\u23A3","\u23A6"],Bmatrix:["\u23A7","\u23AB","\u23A8","\u23AC","\u23A9","\u23AD"],vmatrix:["\u2502","\u2502","\u2502","\u2502","\u2502","\u2502"],Vmatrix:["\u2551","\u2551","\u2551","\u2551","\u2551","\u2551"]}[e];if(!h)return this.supported=!1,o.join(`
|
|
93
|
+
`);a=o.map((u,d)=>{let p=d===0?h[0]:d===o.length-1?h[4]:h[2],f=d===0?h[1]:d===o.length-1?h[5]:h[3];return`${p} ${u} ${f}`})}if(a.length<=1)return a[0]??"";let l=this.layoutNodes.push({type:"matrix",lines:a,baseline:0})-1;return`${Ut}${l}${yi}`}renderNested(e,t=!0){let i=new s(e,this.layoutNodes,this.display&&t).render();return i===void 0?(this.supported=!1,e):i}};function Ss(s,e={}){let t=[],i=new dr(s,t,e.display===!0).render();if(i===void 0)return;if(t.length===0)return i.replaceAll(ks," ");let n=wi(i,t).lines,r=Math.min(...n.filter(o=>o.trim()).map(o=>o.length-o.trimStart().length));return n.map(o=>o.slice(r).trimEnd()).join(`
|
|
94
|
+
`).trimEnd().replaceAll(ks," ")}var tp=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,pr=class extends xt{url(e){let t=super.url(e);if(!t)return;let i=t.raw.search(qn);return i<0?t:super.url(t.raw.slice(0,i))}del(e){let t=tp.exec(e);if(!t)return;let i=t[2];return{type:"del",raw:t[0],text:i,tokens:this.lexer.inlineTokens(i)}}};function ip(s,e){let t=0;for(let i=e-1;i>=0&&s[i]==="\\";i--)t++;return t%2===1}function sp(s,e,t){let i=s.indexOf(e,t);for(;i>=0&&ip(s,i);)i=s.indexOf(e,i+e.length);return i}function Ya(s){return/\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(s)}function np(s){let e="",t="";if(s.startsWith("$$"))e="$$",t="$$";else if(s.startsWith("\\("))e="\\(",t="\\)";else if(s.startsWith("\\["))e="\\[",t="\\]";else if(s.startsWith("$")&&!/^\$\s/.test(s))e="$",t="$";else return;let i=sp(s,t,e.length);if(i>=0&&e==="$"&&(/\s$/.test(s.slice(e.length,i))||/^\d/.test(s.slice(i+1))||/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(s.slice(e.length,i))&&/^[A-Za-z_][A-Za-z0-9_]*/.test(s.slice(i+1))||s.slice(e.length,i).includes("`")))return;if(i<0){let o=s.slice(e.length);return e.startsWith("\\")||Ya(o)?{type:"latex",raw:s,text:o,pending:!0}:void 0}let n=s.slice(e.length,i);return!n||n.includes(`
|
|
95
|
+
`)?void 0:{type:"latex",raw:s.slice(0,i+t.length),text:n}}var rp=/^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;function Cs(s){let e=s.split(`
|
|
96
|
+
`);for(let t=0;t<e.length-1;t++){let i=e[t+1];if((i.includes("|")||e[t].includes("|"))&&rp.test(i))return!0}return!1}function op(s){let e=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(s);if(e?.[1]&&!Cs(e[1]))return{type:"latexBlock",raw:e[0],text:e[1].trim()};let t=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(s);if(t?.[1]&&!Cs(t[1]))return{type:"latexBlock",raw:t[0],text:t[1].trim()};let i=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(s);if(i?.[1]&&!Cs(i[1]))return{type:"latexBlock",raw:i[0],text:i[1],pending:!0};let n=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(s);if(n?.[1]&&Ya(n[1])&&!Cs(n[1]))return{type:"latexBlock",raw:n[0],text:n[1],pending:!0}}var ap=[{name:"latexBlock",level:"block",start(s){let e=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(s);return e?e.index+(e[0].startsWith(`
|
|
97
|
+
`)?1:0):void 0},tokenizer:op},{name:"latex",level:"inline",start(s){let e=[s.indexOf("$"),s.indexOf("\\("),s.indexOf("\\[")].filter(t=>t>=0);return e.length>0?Math.min(...e):void 0},tokenizer:np}];function fr(s){let e=s[s.length-1];if(e?.type==="list"){fr(e.items[e.items.length-1]?.tokens??[]);return}if(e?.type==="blockquote"){fr(e.tokens??[]);return}if(e?.type!=="code")return;let t=/^(`{3,}|~{3,})/.exec(e.raw)?.[1],i=e.raw.split(`
|
|
98
|
+
`).pop();!t||!i||i.length>=t.length||i!==t[0]?.repeat(i.length)||(e.text=e.text.slice(0,-i.length).replace(/\n$/,""))}var lp=/<!--[\s\S]*?(?:-->|$)/g;function Xa(s){return s.replace(lp,"")}function mr(s){for(let e=s.length-1;e>=0;e--){let t=s[e];if(t.type==="list")for(let i of t.items)mr(i.tokens);else t.type==="blockquote"?mr(t.tokens??[]):t.type==="html"&&Xa(t.raw).trim()===""&&(s.splice(e,1),s[e]?.type==="space"&&(e===0||s[e-1]?.type==="space")?s.splice(e,1):e===s.length&&s[e-1]?.type==="space"&&s.splice(--e,1))}}var gr=new Xi;gr.setOptions({tokenizer:new pr});gr.use({tokenizer:{emStrong:Va().tokenizer?.emStrong},extensions:[...ap]});var Kt=class{text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;cachedTokens;blocks;blockHighlightedCode;constructor(e,t,i,n,r,o){this.text=e,this.paddingX=t,this.paddingY=i,this.theme=n,this.defaultTextStyle=r,this.options=o?{...o}:{}}setText(e){this.text=e,this.clearRenderCache()}invalidate(){this.clearRenderCache(),this.blocks=void 0,this.defaultStylePrefix=void 0}clearRenderCache(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;let t=Math.max(1,e-this.paddingX*2),i=this.options.transform?.(this.text,t)??this.text;if(!i||i.trim()===""){this.blocks=void 0;let m=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=m,m}let n=i.replace(/\t/g," "),r=this.cachedTokens?.deref(),o=r?.source===n?r.tokens:void 0;o||(o=gr.lexer(n),fr(o),mr(o),this.cachedTokens=new WeakRef({source:n,tokens:o}));let a=Object.keys(o.links).length===0,l=this.blocks?.deref(),c=new Map;this.blocks=new WeakRef(c);let h=[];for(let m=0;m<o.length;m++){let b=o[m],g=o[m+1]?.type,w=(a?c.get(b.raw)??l?.get(b.raw):void 0)??{width:-1,nextTokenType:g,lines:[],highlightedCode:new Map};(w.width!==e||w.nextTokenType!==g)&&this.renderBlock(w,b,g,e,t),a&&c.set(b.raw,w);for(let k of w.lines)h.push(k)}let u=this.defaultTextStyle?.bgColor,d=" ".repeat(e),p=[];for(let m=0;m<this.paddingY;m++){let b=u?_t(d,e,u):d;p.push(b)}Tt(p);let f=p.concat(h,p);return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=f,f.length>0?f:[""]}renderBlock(e,t,i,n,r){this.blockHighlightedCode=e.highlightedCode;let o=" ".repeat(this.paddingX),a=" ".repeat(this.paddingX),l=this.defaultTextStyle?.bgColor,c=[];for(let h of this.renderToken(t,r,i)){if(z(h)){c.push(h);continue}for(let u of ge(h,r)){let d=o+u+a;if(l)c.push(_t(d,n,l));else{let p=Math.max(0,n-x(d));c.push(d+" ".repeat(p))}}}this.blockHighlightedCode=void 0,Tt(c),e.lines=c,e.width=n,e.nextTokenType=i}applyDefaultStyle(e){if(!this.defaultTextStyle)return e;let t=e;return this.defaultTextStyle.color&&(t=this.defaultTextStyle.color(t)),this.defaultTextStyle.bold&&(t=this.theme.bold(t)),this.defaultTextStyle.italic&&(t=this.theme.italic(t)),this.defaultTextStyle.strikethrough&&(t=this.theme.strikethrough(t)),this.defaultTextStyle.underline&&(t=this.theme.underline(t)),t}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let e="\0",t=e;this.defaultTextStyle.color&&(t=this.defaultTextStyle.color(t)),this.defaultTextStyle.bold&&(t=this.theme.bold(t)),this.defaultTextStyle.italic&&(t=this.theme.italic(t)),this.defaultTextStyle.strikethrough&&(t=this.theme.strikethrough(t)),this.defaultTextStyle.underline&&(t=this.theme.underline(t));let i=t.indexOf(e);return this.defaultStylePrefix=i>=0?t.slice(0,i):"",this.defaultStylePrefix}getStylePrefix(e){let i=e("\0"),n=i.indexOf("\0");return n>=0?i.slice(0,n):""}getDefaultInlineStyleContext(){return{applyText:e=>this.applyDefaultStyle(e),stylePrefix:this.getDefaultStylePrefix()}}renderToken(e,t,i,n){let r=[];switch(e.type){case"heading":{let o=e.depth,a=`${"#".repeat(o)} `,l;o===1?l=d=>this.theme.heading(this.theme.bold(this.theme.underline(d))):l=d=>this.theme.heading(this.theme.bold(d));let c={applyText:l,stylePrefix:this.getStylePrefix(l)},h=this.renderInlineTokens(e.tokens||[],c),u=o>=3?l(a)+h:h;r.push(u),i&&i!=="space"&&r.push("");break}case"paragraph":{let o=this.renderInlineTokens(e.tokens||[],n);r.push(o),i&&i!=="list"&&i!=="space"&&r.push("");break}case"text":r.push(this.renderInlineTokens([e],n));break;case"latexBlock":{let o=e,a=!o.pending&&this.options.renderLatex!==!1?Ss(o.text,{display:!0}):void 0;(a===void 0||a.split(`
|
|
99
99
|
`).some(l=>x(l)>t))&&(a=o.raw.trim());for(let l of a.split(`
|
|
100
100
|
`))r.push(this.applyDefaultStyle(l));i&&i!=="space"&&r.push("");break}case"code":{let o=this.theme.codeBlockIndent??" ";if(r.push(this.theme.codeBlockBorder(`\`\`\`${e.lang||""}`)),this.theme.highlightCode){let a=`${e.lang??""}\0${e.text}`,l=this.blockHighlightedCode?.get(a);l||(l=this.theme.highlightCode(e.text,e.lang),this.blockHighlightedCode?.set(a,l));for(let c of l)r.push(`${o}${c}`)}else{let a=e.text.split(`
|
|
101
|
-
`);for(let l of a)r.push(`${o}${this.theme.codeBlock(l)}`)}r.push(this.theme.codeBlockBorder("```")),i&&i!=="space"&&r.push("");break}case"list":{let o=this.renderList(e,0,t,n);r.push(...o);break}case"table":{let o=this.renderTable(e,t,i,n);r.push(...o);break}case"blockquote":{let o=p=>this.theme.quote(this.theme.italic(p)),a=this.getStylePrefix(o),l=p=>{if(!a)return o(p);let f=p.replace(/\x1b\[0m/g,`\x1B[0m${a}`);return o(f)};if(t<3){let p=e.tokens||[];for(let f=0;f<p.length;f++)for(let
|
|
101
|
+
`);for(let l of a)r.push(`${o}${this.theme.codeBlock(l)}`)}r.push(this.theme.codeBlockBorder("```")),i&&i!=="space"&&r.push("");break}case"list":{let o=this.renderList(e,0,t,n);r.push(...o);break}case"table":{let o=this.renderTable(e,t,i,n);r.push(...o);break}case"blockquote":{let o=p=>this.theme.quote(this.theme.italic(p)),a=this.getStylePrefix(o),l=p=>{if(!a)return o(p);let f=p.replace(/\x1b\[0m/g,`\x1B[0m${a}`);return o(f)};if(t<3){let p=e.tokens||[];for(let f=0;f<p.length;f++)for(let m of this.renderToken(p[f],t,p[f+1]?.type,n))r.push(m);break}let c=t-2,h={applyText:p=>p,stylePrefix:a},u=e.tokens||[],d=[];for(let p=0;p<u.length;p++){let f=u[p],m=u[p+1];for(let b of this.renderToken(f,c,m?.type,h))d.push(b)}for(;d.length>0&&d[d.length-1]==="";)d.pop();for(let p of d){let f=l(p),m=ge(f,c);for(let b of m)r.push(this.theme.quoteBorder("\u2502 ")+b)}i&&i!=="space"&&r.push("");break}case"hr":r.push(this.theme.hr("\u2500".repeat(Math.min(t,80)))),i&&i!=="space"&&r.push("");break;case"html":"raw"in e&&typeof e.raw=="string"&&r.push(this.applyDefaultStyle(Xa(e.raw).trim()));break;case"space":r.push("");break;default:"text"in e&&typeof e.text=="string"&&r.push(e.text)}return r}renderInlineTokens(e,t){let i="",n=t??this.getDefaultInlineStyleContext(),{applyText:r,stylePrefix:o}=n,a=c=>c.split(`
|
|
102
102
|
`).map(u=>r(u)).join(`
|
|
103
|
-
`),l=!1;for(let c=0;c<e.length;c++){let h=e[c];switch(l&&h.type==="text"&&!h.tokens?.length&&/^[ \t]/.test(h.text)&&(h={...h,text:h.text.replace(/^[ \t]+/,"")}),l=!1,h.type){case"latex":{let u=h,d=!u.pending&&this.options.renderLatex!==!1?
|
|
104
|
-
`;break;case"del":{let u=this.renderInlineTokens(h.tokens||[],n);i+=this.theme.strikethrough(u)+o;break}case"html":h.raw.startsWith("<!--")?l=c===0||/[ \t]$/.test(e[c-1].raw):i+=a(h.raw);break;default:"text"in h&&typeof h.text=="string"&&(i+=a(h.text))}}for(;o&&i.endsWith(o);)i=i.slice(0,-o.length);return i}getOrderedListMarker(e){let t=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(e.raw);return t?`${t[1]} `:void 0}getUnorderedListMarker(e){let t=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(e.raw);return t?`${t[1]} `:void 0}renderList(e,t,i,n){let r=[],o=" ".repeat(t),a=typeof e.start=="number"?e.start:1;for(let l=0;l<e.items.length;l++){let c=e.items[l],h=l===e.items.length-1,u=e.ordered?this.options.preserveOrderedListMarkers?this.getOrderedListMarker(c)??`${a+l}. `:`${a+l}. `:this.options.preserveOrderedListMarkers?this.getUnorderedListMarker(c)??"- ":"- ",d=c.task?`[${c.checked?"x":" "}] `:"",p=u+d,f=o+this.theme.listBullet(p),g=o+" ".repeat(x(p)),b=Math.max(1,i-x(f)),m=!1;for(let y of c.tokens){if(y.type==="list"){r.push(...this.renderList(y,t+1,i,n)),m=!0;continue}let w=this.renderToken(y,b,void 0,n);for(let k of w)for(let R of ge(k,b)){let v=m?g:f;r.push(v+R),m=!0}}m||r.push(f),e.loose&&!h&&r.push("")}return r}getLongestWordWidth(e,t){let i=e.split(/\s+/).filter(r=>r.length>0),n=0;for(let r of i)n=Math.max(n,x(r));return t===void 0?n:Math.min(n,t)}wrapCellText(e,t,i=""){let n=ge(e,Math.max(1,t));return n.map((r,o)=>{let a=o<n.length-1?"\x1B[22;23;24;25;27;28;29;39m":"";return`${r}${a}${i}`})}renderTable(e,t,i,n){let r=[],o=e.header.length;if(o===0)return r;let a=3*o+1,l=t-a;if(l<o){let v=e.raw?ge(e.raw,t):[];return i&&i!=="space"&&v.push(""),v}let c=30,h=[],u=[];for(let v=0;v<o;v++){let A=this.renderInlineTokens(e.header[v].tokens||[],n);h[v]=x(A),u[v]=Math.max(1,this.getLongestWordWidth(A,c))}for(let v of e.rows)for(let A=0;A<v.length;A++){let E=this.renderInlineTokens(v[A].tokens||[],n);h[A]=Math.max(h[A]||0,x(E)),u[A]=Math.max(u[A]||1,this.getLongestWordWidth(E,c))}let d=u,p=d.reduce((v,A)=>v+A,0);if(p>l){d=new Array(o).fill(1);let v=l-o;if(v>0){let A=u.reduce((L,Q)=>L+Math.max(0,Q-1),0),E=u.map(L=>{let Q=Math.max(0,L-1);return A>0?Math.floor(Q/A*v):0});for(let L=0;L<o;L++)d[L]+=E[L]??0;let B=E.reduce((L,Q)=>L+Q,0),q=v-B;for(let L=0;q>0&&L<o;L++)d[L]++,q--}p=d.reduce((A,E)=>A+E,0)}let f=h.reduce((v,A)=>v+A,0)+a,g;if(f<=t)g=h.map((v,A)=>Math.max(v,d[A]));else{let v=h.reduce((q,L,Q)=>q+Math.max(0,L-d[Q]),0),A=Math.max(0,l-p);g=d.map((q,L)=>{let Q=h[L],We=Math.max(0,Q-q),Re=0;return v>0&&(Re=Math.floor(We/v*A)),q+Re});let E=g.reduce((q,L)=>q+L,0),B=l-E;for(;B>0;){let q=!1;for(let L=0;L<o&&B>0;L++)g[L]<h[L]&&(g[L]++,B--,q=!0);if(!q)break}}let b=g.map(v=>"\u2500".repeat(v));r.push(`\u250C\u2500${b.join("\u2500\u252C\u2500")}\u2500\u2510`);let m=e.header.map((v,A)=>{let E=this.renderInlineTokens(v.tokens||[],n);return this.wrapCellText(E,g[A],n?.stylePrefix)}),y=Math.max(...m.map(v=>v.length));for(let v=0;v<y;v++){let A=m.map((E,B)=>{let q=E[v]||"",L=q+" ".repeat(Math.max(0,g[B]-x(q)));return this.theme.bold(L)});r.push(`\u2502 ${A.join(" \u2502 ")} \u2502`)}let k=`\u251C\u2500${g.map(v=>"\u2500".repeat(v)).join("\u2500\u253C\u2500")}\u2500\u2524`;r.push(k);for(let v=0;v<e.rows.length;v++){let E=e.rows[v].map((q,L)=>{let Q=this.renderInlineTokens(q.tokens||[],n);return this.wrapCellText(Q,g[L],n?.stylePrefix)}),B=Math.max(...E.map(q=>q.length));for(let q=0;q<B;q++){let L=E.map((Q,We)=>{let Re=Q[q]||"";return Re+" ".repeat(Math.max(0,g[We]-x(Re)))});r.push(`\u2502 ${L.join(" \u2502 ")} \u2502`)}v<e.rows.length-1&&r.push(k)}let R=g.map(v=>"\u2500".repeat(v));return r.push(`\u2514\u2500${R.join("\u2500\u2534\u2500")}\u2500\u2518`),i&&i!=="space"&&r.push(""),r}};var lt=class extends ee{child;followEnd;primary;overscroll;scrollbarTrackStyle;scrollbarThumbStyle;currentScrollbar;scrollbarHideDelayMs;currentScrollTop=0;contentHeight=0;currentViewportHeight=0;followingEnd;followSuppressedAtEnd=!1;requestRenderCallback;transientScrollbarVisible=!1;scrollbarActive=!1;scrollbarHideTimer;constructor(e,t={}){if(super(),t.axis!==void 0&&t.axis!=="vertical")throw new Error(`Unsupported ScrollView axis: ${t.axis}`);this.child=e,this.children.push(e),this.followEnd=(t.follow??"none")==="end",this.followingEnd=this.followEnd,this.primary=t.primary??!1,this.overscroll=t.overscroll??"chain",this.currentScrollbar=t.scrollbar??"hidden",this.scrollbarTrackStyle=t.scrollbarTrackStyle??(i=>`\x1B[90m${i}\x1B[39m`),this.scrollbarThumbStyle=t.scrollbarThumbStyle??(i=>`\x1B[37m${i}\x1B[39m`),this.scrollbarHideDelayMs=Math.max(0,Math.floor(t.scrollbarHideDelayMs??1e3))}get scrollTop(){return this.currentScrollTop}get isFollowingEnd(){return this.followingEnd}get viewportHeight(){return this.currentViewportHeight}get scrollbar(){return this.currentScrollbar}get isScrollbarVisible(){return this.scrollbar==="always"?this.currentViewportHeight>0:this.scrollbar==="auto"&&this.contentHeight>this.currentViewportHeight&&this.transientScrollbarVisible}get isScrollbarActive(){return this.scrollbarActive}setScrollbar(e){e!==this.currentScrollbar&&(this.currentScrollbar=e,e!=="auto"?this.hideTransientScrollbar():this.scrollbarActive&&this.markScrollbarActivity(),this.requestRenderCallback?.())}getContentWidth(e){return this.scrollbar==="always"&&e>1?e-1:e}markScrollbarActivity(){this.scrollbar!=="auto"||this.contentHeight<=this.currentViewportHeight||(this.transientScrollbarVisible=!0,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0),!this.scrollbarActive&&(this.scrollbarHideTimer=setTimeout(()=>{this.scrollbarHideTimer=void 0,this.transientScrollbarVisible=!1,this.requestRenderCallback?.()},this.scrollbarHideDelayMs),this.scrollbarHideTimer.unref()))}hideTransientScrollbar(){this.transientScrollbarVisible=!1,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0)}setScrollbarActive(e){e!==this.scrollbarActive&&(this.scrollbarActive=e,this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollTo(e,t={}){let i=Number.isFinite(e)?Math.trunc(e):this.currentScrollTop,n=Math.max(0,this.contentHeight-this.currentViewportHeight),r=Math.max(0,Math.min(n,i)),o=t.disableFollow===!0&&r===n,a=!o&&this.followEnd&&r===n;if(r===this.currentScrollTop&&a===this.followingEnd&&o===this.followSuppressedAtEnd)return;let l=r!==this.currentScrollTop;this.currentScrollTop=r,this.followingEnd=a,this.followSuppressedAtEnd=o,l&&this.markScrollbarActivity(),this.requestRenderCallback?.()}scrollBy(e){let t=Number.isFinite(e)?Math.trunc(e):0;if(t===0)return 0;let i=Math.max(0,this.contentHeight-this.currentViewportHeight),n=this.followingEnd?i:this.currentScrollTop,r=Math.max(0,Math.min(i,n+t)),o=r-n,a=this.followingEnd;return this.currentScrollTop=r,this.followingEnd=this.followEnd&&r===i,this.followSuppressedAtEnd=!1,o!==0&&this.markScrollbarActivity(),(o!==0||this.followingEnd!==a)&&this.requestRenderCallback?.(),t-o}scrollToStart(){let e=this.currentScrollTop!==0||this.followingEnd!==(this.followEnd&&this.contentHeight<=this.currentViewportHeight);this.currentScrollTop=0,this.followingEnd=this.followEnd&&this.contentHeight<=this.currentViewportHeight,this.followSuppressedAtEnd=!1,e&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollToEnd(){let e=Math.max(0,this.contentHeight-this.currentViewportHeight),t=this.currentScrollTop!==e||this.followingEnd!==this.followEnd;this.currentScrollTop=e,this.followingEnd=this.followEnd,this.followSuppressedAtEnd=!1,t&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}updateLayout(e,t,i){this.contentHeight=Math.max(0,Math.floor(e)),this.currentViewportHeight=Math.max(0,Math.floor(t)),this.requestRenderCallback=i;let n=Math.max(0,this.contentHeight-this.currentViewportHeight);this.followingEnd?this.currentScrollTop=n:this.currentScrollTop=Math.max(0,Math.min(this.currentScrollTop,n)),this.currentScrollTop<n&&(this.followSuppressedAtEnd=!1),this.followEnd&&this.currentScrollTop===n&&!this.followSuppressedAtEnd&&(this.followingEnd=!0),this.contentHeight<=this.currentViewportHeight&&this.hideTransientScrollbar()}addChild(e){throw new Error("ScrollView has exactly one child")}removeChild(e){throw new Error("ScrollView child cannot be removed")}clear(){throw new Error("ScrollView child cannot be cleared")}render(e){let t=this.getContentWidth(e),i=this.child.render(t);return t===e?i:i.map(n=>`${n} `)}[Bt](){return{type:"scroll",component:this.child,state:this}}};var wi=class extends fi{layoutType="vstack";constructor(e=[],t={}){super(e,t)}render(e){let t={width:Math.max(1,e),height:Number.MAX_SAFE_INTEGER},i=mi(this.entries,t),n=i.map(a=>a.component.render(t.width)),r=Nt(i,n.map(a=>a.length),void 0,this.gap),o=[];for(let a=0;a<i.length;a++){if(a>0)for(let c=0;c<this.gap;c++)o.push("");let l=n[a].slice(0,r[a]);o.push(...l);for(let c=l.length;c<r[a];c++)o.push("")}return o}};import{createRequire as lp}from"node:module";import*as Ya from"node:path";import{createRequire as np}from"node:module";import{dirname as mr,join as Ss}from"node:path";import{fileURLToPath as rp}from"node:url";var op=np(import.meta.url),ap="@earendil-works/pi-tui";function Qa(s,e={}){let t=mr(rp(e.moduleUrl??import.meta.url)),i=[];try{let n=(e.resolvePackage??op.resolve)(ap);i.push(Ss(mr(n),"..",s))}catch{}return i.push(Ss(t,"..",s),Ss(t,s),Ss(mr(e.execPath??process.execPath),s)),Array.from(new Set(i))}var cp=lp(import.meta.url),Cs=new Map;function hp(s,e=""){let t=process.arch;if(t!=="x64"&&t!=="arm64")return;let i=Ya.join("native",s,"prebuilds",`${s}-${t}`,`${s}-platform${e}.node`);if(Cs.has(i))return Cs.get(i);for(let n of Qa(i))try{let r=cp(n);if(typeof r?.getText=="function"&&typeof r.getImage=="function")return Cs.set(i,r),r}catch{}Cs.set(i,void 0)}function $s(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return hp(process.platform)}var Xa="\x1B]7501;?\x1B\\";function Ja(s){return/^\x1b\]7501;\?[^\x07\x1b]*(?:\x07|\x1b\\)$/.test(s)}var up=/^[A-Za-z0-9_.+-]{1,32}$/,dp=2048;function pp(s,e){if(Buffer.byteLength(s,"utf8")<=e)return s;let t=0,i=0;for(let n of s){let r=Buffer.byteLength(n,"utf8");if(t+r>e)break;t+=r,i+=n.length}return s.slice(0,i)}function xi(s){let e=[`state=${s.state}`];s.app!==void 0&&up.test(s.app)&&e.push(`app=${s.app}`),s.state==="blocked"&&s.kind&&e.push(`kind=${s.kind}`);let t=pp(ni(s.message??"").trim(),dp);return t&&e.push(`msg=${Buffer.from(t,"utf8").toString("base64")}`),`\x1B]7501;${e.join(":")}\x1B\\`}import{EventEmitter as fp}from"events";var se="\x1B",mp=50,gp=10,Za="\x1B[200~",As="\x1B[201~",tl=/^\x1b(?:\](?:1[01];|4;\d{1,3};|7501;\?)|P>\||_G(?:[a-z]=\d+,)*[a-z]=\d+;)/;function il(s){return s.startsWith(`${se}]`)||s.startsWith(`${se}P`)||s.startsWith(`${se}_`)}function bp(s){if(!s.startsWith(se))return"not-escape";if(s.length===1)return"incomplete";let e=s.slice(1);return e.startsWith("[")?e.startsWith("[M")?s.length>=6?"complete":"incomplete":yp(s):e.startsWith("]")?wp(s):e.startsWith("P")?xp(s):e.startsWith("_")?vp(s):e.startsWith("O")?e.length>=2?"complete":"incomplete":(e.length===1,"complete")}function yp(s){if(!s.startsWith(`${se}[`))return"complete";if(s.length<3)return"incomplete";let e=s.slice(2),t=e[e.length-1],i=t.charCodeAt(0);if(i>=64&&i<=126){if(e.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(e))return"complete";if(t==="M"||t==="m"){let r=e.slice(1,-1).split(";");if(r.length===3&&r.every(o=>/^\d+$/.test(o)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function wp(s){return!s.startsWith(`${se}]`)||s.endsWith(`${se}\\`)||s.endsWith("\x07")?"complete":"incomplete"}function xp(s){return!s.startsWith(`${se}P`)||s.endsWith(`${se}\\`)?"complete":"incomplete"}function vp(s){return!s.startsWith(`${se}_`)||s.endsWith(`${se}\\`)?"complete":"incomplete"}function kp(s){let e=s.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!e)return;let t=parseInt(e[1],10);return t>=32?t:void 0}function el(s){let e=[],t=0;for(;t<s.length;){let i=s.slice(t);if(i.startsWith(se)){let n=il(i)&&tl.test(i),r=1;for(;r<=i.length;){if(n&&r>2){let l=i[r-1];if(l===""||l===""){t+=r;break}if(l===se&&r<i.length&&i[r]!=="\\"){t+=r-1;break}}let o=i.slice(0,r),a=bp(o);if(a==="complete"){if(o==="\x1B\x1B"){let l=i[r];if(l==="["||l==="]"||l==="O"||l==="P"||l==="_"){e.push(se),t+=1;break}}e.push(o),t+=r;break}else if(a==="incomplete")r++;else{e.push(o),t+=r;break}}if(r>i.length)return{sequences:e,remainder:i}}else e.push(i[0]),t++}return{sequences:e,remainder:""}}var vi=class extends fp{buffer="";timeout=null;timeoutMs;escapeTimeoutMs;pasteMode=!1;pasteBuffer="";pendingKittyPrintableCodepoint;constructor(e={}){super(),this.timeoutMs=e.timeout??mp,this.escapeTimeoutMs=e.escapeTimeout??gp}process(e){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let t;if(Buffer.isBuffer(e))if(e.length===1&&e[0]>127){let r=e[0]-128;t=`\x1B${String.fromCharCode(r)}`}else t=e.toString();else t=e;if(t.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=t,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let r=this.pasteBuffer.indexOf(As);if(r!==-1){let o=this.pasteBuffer.slice(0,r),a=this.pasteBuffer.slice(r+As.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",o),a.length>0&&this.process(a)}return}let i=this.buffer.indexOf(Za);if(i!==-1){if(i>0){let o=this.buffer.slice(0,i),a=el(o);for(let l of a.sequences)this.emitDataSequence(l)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(i+Za.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let r=this.pasteBuffer.indexOf(As);if(r!==-1){let o=this.pasteBuffer.slice(0,r),a=this.pasteBuffer.slice(r+As.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",o),a.length>0&&this.process(a)}return}let n=el(this.buffer);this.buffer=n.remainder;for(let r of n.sequences)this.emitDataSequence(r);if(this.buffer.length>0){if(tl.test(this.buffer))return;let r=this.buffer===se?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let o=this.flush();for(let a of o)a.length>2&&il(a)?(this.emitDataSequence(a.slice(0,2)),this.process(a.slice(2))):this.emitDataSequence(a)},r)}}emitDataSequence(e){let t=e.length===1?e.codePointAt(0):void 0;if(t!==void 0&&t===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=kp(e),this.emit("data",e)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return[];let e=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,e}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}};import*as Ht from"node:fs";import*as al from"node:path";function sl(s){let e=$s();if(!e?.isModifierPressed)return!1;try{return e.isModifierPressed(s)===!0}catch{return!1}}var Sp=1e3,nl="\x1B]9;4;3\x07",gr="\x1B]9;4;0\x07",Cp="\x1B[13;2u",$p=7,Ap=150,Tp=`\x1B[>${$p}u\x1B[?u`,_p="\x1B[c";function rl(s){let e=s.match(/^\x1b\[\?(\d+)u$/);if(e)return{type:"kitty-flags",flags:Number.parseInt(e[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(s))return{type:"device-attributes"}}function ol(s){return s==="\x1B["||/^\x1b\[\?[\d;]*$/.test(s)}function ll(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function Ip(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.pid,"SIGWINCH")}catch{}}function cl(s){return s==="\r"||s==="\x1B\r"}function Rp(s,e,t){return e&&cl(s)&&t?Cp:s}var Pp=10,Mp=100;function Ep(s=process.env){let e=Number(s.PI_TUI_ESC_TIMEOUT);return Number.isFinite(e)&&e>0?e:s.SSH_CONNECTION||s.SSH_TTY?Mp:Pp}var ki=class{wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;keyboardProtocolPushed=!1;pendingKeyboardProtocolDeviceAttributes=0;keyboardProtocolNegotiationBuffer="";keyboardProtocolBufferFlushTimer;stdinBuffer;stdinDataHandler;progressInterval;programStatus;programStatusSupported=!1;programStatusQueryPending=!1;writeLogPath=(()=>{let e=process.env.PI_TUI_WRITE_LOG||"";if(!e)return"";try{if(Ht.statSync(e).isDirectory()){let t=new Date,i=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}_${String(t.getHours()).padStart(2,"0")}-${String(t.getMinutes()).padStart(2,"0")}-${String(t.getSeconds()).padStart(2,"0")}`;return al.join(e,`tui-${i}-${process.pid}.log`)}}catch{}return e})();get kittyProtocolActive(){return this._kittyProtocolActive}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(e,t){this.inputHandler=e,this.resizeHandler=t,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdout.write("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),Ip(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new vi({escapeTimeout:Ep()}),this.stdinBuffer.on("data",e=>{if(Ja(e)){this.programStatusQueryPending&&(this.programStatusQueryPending=!1,this.programStatusSupported=!0,this.writeProgramStatus());return}let t=this.readKeyboardProtocolNegotiationSequence(e);if(t==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}t&&this.handleKeyboardProtocolNegotiationSequence(t.parsed)||this.forwardInputSequence(t?.sequence??e)}),this.stdinBuffer.on("paste",e=>{this.inputHandler&&this.inputHandler(`\x1B[200~${e}\x1B[201~`)}),this.stdinDataHandler=e=>{this.stdinBuffer.process(e)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),this.keyboardProtocolPushed=!0,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer();let e=process.env.PI_PROGRAM_STATUS;this.programStatusSupported=e==="1",this.programStatusQueryPending=e!=="1"&&e!=="0";let t=this.programStatusQueryPending?Xa:"";process.stdout.write(`${Tp}${t}${_p}`),this.writeProgramStatus()}handleKeyboardProtocolNegotiationSequence(e){if(this.clearKeyboardProtocolNegotiationBuffer(),e.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return!1;this.pendingKeyboardProtocolDeviceAttributes-=1,this.pendingKeyboardProtocolDeviceAttributes===0&&(this.programStatusQueryPending=!1)}return e.type==="kitty-flags"?(e.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,hi(!0))):this.enableModifyOtherKeys(),!0):(this._kittyProtocolActive||this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(e){if(this.keyboardProtocolNegotiationBuffer){let i=this.keyboardProtocolNegotiationBuffer+e,n=rl(i);if(n)return this.clearKeyboardProtocolNegotiationBuffer(),{parsed:n,sequence:i};if(ol(i))return this.setKeyboardProtocolNegotiationBuffer(i),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let t=rl(e);if(t)return{parsed:t,sequence:e};if(ol(e))return this.setKeyboardProtocolNegotiationBuffer(e),"pending"}setKeyboardProtocolNegotiationBuffer(e){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=e}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(){if(!this.keyboardProtocolNegotiationBuffer)return;let e=this.keyboardProtocolNegotiationBuffer;this.clearKeyboardProtocolNegotiationBuffer(),this.forwardInputSequence(e)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput()},Ap))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(e){if(!this.inputHandler)return;let t=cl(e)&&(ll()||process.platform==="win32"),i=Rp(e,t,t&&sl("shift"));this.inputHandler(i)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(process.stdout.write("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform==="win32")try{$s()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(e=1e3,t=50){let i=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),i&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,hi(!1)),this.disableModifyOtherKeys();let n=this.inputHandler;this.inputHandler=void 0;let r=Date.now(),o=()=>{r=Date.now()};process.stdin.on("data",o);let a=Date.now()+e;try{for(;;){let l=Date.now(),c=a-l;if(c<=0||l-r>=t)break;await new Promise(h=>setTimeout(h,Math.min(t,c)))}}finally{process.stdin.removeListener("data",o),this.inputHandler=n}}stop(){this.clearProgressInterval()&&process.stdout.write(gr),this.programStatusSupported&&this.programStatus&&process.stdout.write(xi({state:"clear"})),this.programStatusSupported=!1,this.programStatusQueryPending=!1,process.stdout.write("\x1B[?2004l");let e=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),e&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,hi(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode&&process.stdin.setRawMode(this.wasRaw)}restoreOnExit(e,t){let i=e;this.progressInterval&&(i+=gr),i+="\x1B[?2004l",(this.keyboardProtocolPushed||this._kittyProtocolActive)&&(i+="\x1B[<u"),this._modifyOtherKeysActive&&(i+="\x1B[>4;0m"),i+=t;try{Ht.writeSync(process.stdout.fd,i)}catch{}}write(e){if(process.stdout.write(e),this.writeLogPath)try{Ht.appendFileSync(this.writeLogPath,e,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(e){e>0?process.stdout.write(`\x1B[${e}B`):e<0&&process.stdout.write(`\x1B[${-e}A`)}hideCursor(){process.stdout.write("\x1B[?25l")}showCursor(){process.stdout.write("\x1B[?25h")}clearLine(){process.stdout.write("\x1B[K")}clearFromCursor(){process.stdout.write("\x1B[J")}clearScreen(){process.stdout.write("\x1B[2J\x1B[H")}setTitle(e){process.stdout.write(`\x1B]0;${ni(e)}\x07`)}setProgramStatus(e){this.programStatus=e.state==="clear"?void 0:e,this.programStatusSupported&&process.stdout.write(xi(e))}writeProgramStatus(){this.programStatusSupported&&this.programStatus&&process.stdout.write(xi(this.programStatus))}setProgress(e){e?(process.stdout.write(nl),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(nl)},Sp))):(this.clearProgressInterval(),process.stdout.write(gr))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var Lp=St(),Op=/^[\x20-\x7e]*$/;function qp(s){let e=[],t=[],i=0,n=!1,r=()=>{n&&(e.push(" "),i+=1,n=!1)};for(let o=0;o<s.length;o++){let a=At(s[o]??""),l=0;if(Op.test(a)){let c=0;for(;c<a.length;){if(a.charCodeAt(c)===32){i>0&&(n=!0),l+=1,c+=1;continue}let h=c+1;for(;h<a.length&&a.charCodeAt(h)!==32;)h+=1;r();let u=a.slice(c,h);e.push(u),t.push({textStart:i,textEnd:i+u.length,row:o,startCol:l,endCol:l+u.length,linearColumns:!0}),i+=u.length,l+=u.length,c=h}}else for(let c of Lp.segment(a)){let h=c.segment,u=x(h);if(/^\s+$/u.test(h)){i>0&&(n=!0),l+=u;continue}r(),e.push(h),t.push({textStart:i,textEnd:i+h.length,row:o,startCol:l,endCol:l+u,linearColumns:!1}),i+=h.length,l+=u}i>0&&(n=!0)}return{text:e.join(""),spans:t}}function Dp(s){return s.replace(/\s+/gu," ").trim()}function Bp(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Np(s,e){if(!e)return[];let t=new RegExp(Bp(e),"giu"),i=[],n=0;for(let r of s.text.matchAll(t)){let o=r.index,a=o+r[0].length;for(;n<s.spans.length&&s.spans[n].textEnd<=o;)n+=1;let l=[];for(let c=n;c<s.spans.length;c++){let h=s.spans[c];if(h.textStart>=a)break;if(h.textEnd<=o)continue;let u=h.linearColumns?h.startCol+Math.max(o,h.textStart)-h.textStart:h.startCol,d=h.linearColumns?h.startCol+Math.min(a,h.textEnd)-h.textStart:h.endCol,p=l[l.length-1];p&&p.row===h.row&&u<=p.endCol?p.endCol=Math.max(p.endCol,d):l.push({row:h.row,startCol:u,endCol:d})}for(;n<s.spans.length&&s.spans[n].textEnd<=a;)n+=1;l.length>0&&i.push({segments:l})}return i}var Ts=class{sourceLines;corpus;normalizedQuery;matches=[];search(e,t){let i=this.sourceLines?.length!==e.length;if(!i&&this.sourceLines){for(let o=0;o<e.length;o++)if(this.sourceLines[o]!==e[o]){i=!0;break}}(i||!this.corpus)&&(this.sourceLines=Array.from(e),this.corpus=qp(e));let n=Dp(t),r=i||n!==this.normalizedQuery;return r&&(this.normalizedQuery=n,this.matches=Np(this.corpus,n)),{matches:this.matches,changed:r}}};function br(s){let e=s.segments[0],t=s.segments[s.segments.length-1];return e&&t?`${e.row}:${e.startCol}:${t.row}:${t.endCol}`:""}var _s=class{input=new Te({prompt:" ",placeholder:"Find in transcript",placeholderStyle:e=>`\x1B[2m${e}\x1B[22m`});onQueryChange;navigationButtonStyle;resultCount=0;resultIndex=-1;previousButtonStart=-1;previousButtonEnd=-1;nextButtonStart=-1;nextButtonEnd=-1;hoveredNavigationDirection;_focused=!1;constructor(e,t=i=>i){this.onQueryChange=e,this.navigationButtonStyle=t}get focused(){return this._focused}set focused(e){this._focused=e,this.input.focused=e}setResult(e,t){this.resultIndex=e,this.resultCount=t}getNavigationDirectionAt(e,t){if(e===2){if(t>=this.previousButtonStart&&t<this.previousButtonEnd)return-1;if(t>=this.nextButtonStart&&t<this.nextButtonEnd)return 1}}setHoveredNavigationDirection(e){return e===this.hoveredNavigationDirection?!1:(this.hoveredNavigationDirection=e,!0)}handleInput(e){let t=this.input.getValue();this.input.handleInput(e);let i=this.input.getValue();i!==t&&this.onQueryChange(i)}invalidate(){this.input.invalidate()}render(e){let t=Math.max(1,e),i=Math.max(0,t-2),n=We=>We?We.split("+").map(Re=>process.platform==="darwin"&&Re.toLowerCase()==="alt"?"Option":Re.charAt(0).toUpperCase()+Re.slice(1)).join("+"):"Unbound",r=fe(),o=n(r.getKeys("tui.altScreen.searchPrevious")[0]),a=n(r.getKeys("tui.altScreen.searchNext")[0]),c=this.input.getValue()?this.resultCount===0?"No matches":`${this.resultIndex+1}/${this.resultCount}`:"",h=Math.max(0,i-3),u=_(c,h,""),d=u?`\x1B[2m ${u} \x1B[22m`:"",p=Math.max(0,i-x(d)),f=_(this.input.render(Math.max(1,p))[0]??"",p,""),g=" ".repeat(Math.max(0,p-x(f))),b=`${f}${g}${d}`,m=`\u2191 ${o}`,y=`\u2193 ${a}`,w=" \xB7 ",k=1,R=Math.max(0,i-k*2-1),v=x(m)+x(w)+x(y);v>R&&(m="\u2191",y="\u2193",w=" ",v=x(m)+x(w)+x(y));let A=v<=R,E=A?this.navigationButtonStyle(m,this.hoveredNavigationDirection===-1)+w+this.navigationButtonStyle(y,this.hoveredNavigationDirection===1):"",B=A?k*2:0,q=E&&i>v+B?1:0,L=Math.max(0,i-(A?v:0)-B-q),Q=1+L+k;return this.previousButtonStart=A?Q:-1,this.previousButtonEnd=A?Q+x(m):-1,this.nextButtonStart=A?this.previousButtonEnd+x(w):-1,this.nextButtonEnd=A?this.nextButtonStart+x(y):-1,t===1?["\u250C","\u2502","\u2514"]:[`\u250C${"\u2500".repeat(i)}\u2510`,`\u2502${b}\u2502`,`\u2514${"\u2500".repeat(L)}${E?" ":""}${E}${E?" ":""}${"\u2500".repeat(q)}\u2518`]}};var Fp=1e3,Is=class{entries=[];nextId=0;requestRender;constructor(e){this.requestRender=e}flash(e,t=Fp){let i=this.nextId++,n=setTimeout(()=>{let r=this.entries.findIndex(o=>o.id===i);r!==-1&&(this.entries.splice(r,1),this.requestRender())},Math.max(0,t));n.unref(),this.entries.push({id:i,message:e,timer:n}),this.requestRender()}dispose(){for(let e of this.entries)clearTimeout(e.timer);this.entries.length=0}invalidate(){}render(e){return this.entries.map(t=>`\x1B[7m${_(` ${t.message} `,e,"")}\x1B[27m`)}};var Wp=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function Si(s,e){let t=Math.max(s.x,e.x),i=Math.max(s.y,e.y),n=Math.min(s.x+s.width,e.x+e.width),r=Math.min(s.y+s.height,e.y+e.height);return{x:t,y:i,width:Math.max(0,n-t),height:Math.max(0,r-i)}}function Ps(s,e,t){let i=Math.max(1,Math.floor(t)),n=s.renderCache.get(e);n||(n=new Map,s.renderCache.set(e,n));let r=n.get(i);return r||(r=e.render(i),n.set(i,r)),r}function hl(s,e,t){return Ps(s,e,t).length}function Kp(s,e,t){return Ps(s,e,t).reduce((i,n)=>Math.max(i,x(n)),0)}function ul(s,e){return s.parent=e,s}function dl(s,e){s.rect.y+=e;for(let t of s.children)dl(t,e)}function pl(s,e){s.clip=Si(e,s.rect);for(let t of s.children)pl(t,s.clip)}function Rs(s,e,t,i,n,r,o){let a=Math.max(1,Math.floor(n)),l=ys(e);if(!l){let y=Ps(s,e,a),w=r===void 0?y.length:Math.max(0,Math.floor(r)),k=0;if(y.length>w&&w>0){let R=y.findIndex(v=>v.includes(pe));R>=w&&(k=R-w+1)}return{component:e,rect:{x:t,y:i,width:a,height:w},clip:Si(o,{x:t,y:i,width:a,height:w}),children:[],lines:y,lineOffset:k,layer:0}}if(l.type==="scroll"){let y=l.state.scrollTop,w=l.state.getContentWidth(a),k=Rs(s,l.component,t,i-y,w,void 0,o),R=k.rect.height,v=r===void 0?R:Math.max(0,Math.floor(r));l.state.updateLayout(R,v,s.requestRender),dl(k,y-l.state.scrollTop);let A=l.state;(l.state.primary||!s.primaryScrollView)&&(s.primaryScrollView=A);let E={x:t,y:i,width:a,height:v},B=Si(o,E),q={component:e,rect:E,clip:B,children:[k],scrollView:A,scrollContentLines:Ps(s,l.component,w),layer:0};return k.parent=q,pl(k,B),q}let c=mi(l.entries,s.viewport),h=Math.max(0,c.length-1)*l.gap;if(l.type==="vstack"){let y=c.map(B=>typeof B.basis=="number"?B.basis:hl(s,B.component,a)),w=Nt(c,y,r,l.gap),k=w.reduce((B,q)=>B+q,0)+h,R=r===void 0?k:Math.max(0,Math.floor(r)),v={x:t,y:i,width:a,height:R},A={component:e,rect:v,clip:Si(o,v),children:[],layer:0},E=i;for(let B=0;B<c.length;B++)A.children.push(ul(Rs(s,c[B].component,t,E,a,w[B],A.clip),A)),E+=w[B]+l.gap;return A}let u=c.map(y=>typeof y.basis=="number"?y.basis:Kp(s,y.component,a)),d=Nt(c,u,a,l.gap),p=c.map((y,w)=>hl(s,y.component,Math.max(1,d[w]))),f=r===void 0?p.reduce((y,w)=>Math.max(y,w),0):Math.max(0,r),g={x:t,y:i,width:a,height:f},b={component:e,rect:g,clip:Si(o,g),children:[],layer:0},m=t;for(let y=0;y<c.length;y++){let w=p[y],k=l.align==="stretch"?f:Math.min(f,w),R=i;l.align==="center"?R+=Math.floor((f-k)/2):l.align==="end"&&(R+=f-k);let v=d[y];v===0?b.children.push({component:c[y].component,rect:{x:m,y:R,width:0,height:k},clip:{x:m,y:R,width:0,height:0},children:[],parent:b,layer:0}):b.children.push(ul(Rs(s,c[y].component,m,R,v,k,b.clip),b)),m+=v+l.gap}return b}function Up(s,e,t,i,n){if(z(s))return s;let r=ri(s,e),o=r?.start??e,a=r?.end??e+1,l=H(s,0,o,!0),c=H(s,o,a-o,!0),h=H(s,a,Math.max(0,t-a),!0),u="",d=0;for(;d<c.length;){let m=U(c,d);if(!m)break;u+=m.code,d+=m.length}let p=" ".repeat(Math.max(0,o-x(l))),f=" ".repeat(Math.max(0,e-o)),g=" ".repeat(Math.max(0,a-e-1)),b=`\x1B[0m\x1B]8;;\x07${n?No(u):""}`;return`${l}${p}${b}${f}${i}${g}${h}`}function zt(s,e=!1){if(!s.scrollView||s.rect.width<=0||s.rect.height<=0)return;let t=s.children[0]?.rect.height??s.scrollContentLines?.length??0,i=s.rect.height,n=e&&s.scrollView.scrollbar==="auto"&&t>i;if(!s.scrollView.isScrollbarVisible&&!n)return;let r=Math.min(2,i),o=Math.max(r,Math.min(i,Math.round(i*i/t))),a=Math.max(0,t-i),l=i-o,c=a===0?0:Math.round(s.scrollView.scrollTop/a*l),h=s.rect.x+s.rect.width-1;if(!(h<s.clip.x||h>=s.clip.x+s.clip.width))return{column:h,trackTop:s.rect.y,trackHeight:i,thumbTop:s.rect.y+c,thumbHeight:o,maxScrollTop:a}}function Hp(s,e,t){let i=zt(s);if(!(!i||!s.scrollView))for(let n=0;n<i.trackHeight;n++){let r=i.trackTop+n;if(r<s.clip.y||r>=s.clip.y+s.clip.height||r<0||r>=e.length)continue;let a=r>=i.thumbTop&&r<i.thumbTop+i.thumbHeight?s.scrollView.scrollbarThumbStyle(s.scrollView.isScrollbarActive?"\u2588":"\u2503"):s.scrollView.scrollbarTrackStyle("\u2502");e[r]=Up(e[r]??"",i.column,t,a,s.scrollView.scrollbar!=="always")}}function fl(s,e,t){if(s.lines){let i=s.lineOffset??0,n=Math.max(s.rect.y,s.clip.y,0),r=Math.min(s.rect.y+s.rect.height,s.clip.y+s.clip.height,e.length);for(let o=n;o<r;o++){let a=s.lines[i+o-s.rect.y];if(a===void 0)continue;let l=a.replace(Wp,""),c=ls(l);if(c){let h=Math.min(e.length,s.clip.y+s.clip.height),u=Math.min(c.rows,h-o);u<c.rows&&(l=Yn(l,0,u))}s.rect.x===0&&s.rect.width>=t&&(z(l)||!e[o])?e[o]=l:e[o]=He(e[o]??"",l,s.rect.x,s.rect.width,t)}}for(let i of s.children)fl(i,e,t);if(s.scrollView&&s.scrollContentLines&&s.scrollView.scrollTop>0&&s.rect.height>0){let i=s.scrollView.scrollTop,n=Math.max(0,i-ua());for(let r=i-1;r>=n;r--){let o=s.scrollContentLines[r]??"";if(!z(o))continue;let a=ls(o);if(!a)continue;let l=i-r;if(l<a.rows){let c=Math.min(s.rect.height,a.rows-l),h=Yn(o,l,c);s.rect.x===0&&s.rect.width>=t&&(e[s.rect.y]=h)}break}}Hp(s,e,t)}function wr(s,e,t,i){let n=Math.max(1,Math.floor(e)),r=Math.max(1,Math.floor(t)),o={viewport:{width:n,height:r},renderCache:new Map,requestRender:i,primaryScrollView:void 0},a=Rs(o,s,0,0,n,r,{x:0,y:0,width:n,height:r}),l=Array.from({length:r},()=>"");return fl(a,l,n),{root:a,width:n,height:r,lines:l,...o.primaryScrollView===void 0?{}:{primaryScrollView:o.primaryScrollView}}}function yr(s,e,t){return e>=s.x&&e<s.x+s.width&&t>=s.y&&t<s.y+s.height}function ml(s,e,t){let i=[],n=(r,o)=>{if(yr(r.clip,e,t)){i.push({box:r,depth:o});for(let a of r.children)n(a,o+1)}};return n(s.root,0),i.sort((r,o)=>o.box.layer-r.box.layer||o.depth-r.depth),i.map(({box:r})=>r)}function we(s,e){let t=i=>{if(i.scrollView===e)return i;for(let n of i.children){let r=t(n);if(r)return r}};return t(s.root)}function Ms(s,e,t){let i=[],n=(r,o)=>{if(yr(r.clip,e,t)){r.scrollView&&yr(r.rect,e,t)&&i.push({scrollView:r.scrollView,depth:o});for(let a of r.children)n(a,o+1)}};return n(s.root,0),i.sort((r,o)=>o.depth-r.depth),i.map(r=>r.scrollView)}function zp(){let s=process.env;return process.platform==="darwin"&&s.SSH_CONNECTION===void 0&&s.SSH_CLIENT===void 0&&s.SSH_TTY===void 0}var Es=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(e="auto",t=!zp()){this.lines=e,this.accelerate=t}setLines(e){this.lines=e,this.reset()}next(e,t){if(this.lines!=="auto")return Number.isFinite(this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let i=t-this.lastTime,n=e===this.lastDirection&&i<=200;if(this.lastTime=t,this.lastDirection=e,!n)return this.averageGap=void 0,this.carry=0,1;if(i<5)return 1;this.averageGap=this.averageGap===void 0?i:(this.averageGap+i)/2;let r=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,o=Math.floor(r);return this.carry=r-o,o}reset(){this.lastTime=Number.NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}};var Vp="\x1B[?1049h",xr="\x1B[?1049l",gl="\x1B[?7l",vr="\x1B[?7h",jp="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",Gp="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",bl="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",Qp="\x1B[I",Yp="\x1B[O",Ls="\x1B[?2026h",Ci="\x1B[?2026l",yl=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,Xp=/^\x1b\]133;A(?:\x07|\x1b\\)/,wl=4,Jp=5,Zp=16,ef=32*1024*1024,tf=64*1024*1024,xl=500,sf=5e3,nf=new Set(["/","-","+","\\","~","_","."]),rf=Ct(),$i=class extends di{mode="fullscreen";[ir]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity="character";selectionInitialRange;lastClick;selectionDragPointer;selectionAutoScrollDirection=0;selectionAutoScrollTimer;selectionPressActive=!1;scrollbarDrag;scrollbarHover;scrollToEndIndicatorRect;activeSearch;pressedUrl;selectionDragged=!1;mouseCapture;mousePressTarget;mousePressPoint;mousePressMoved=!1;lastComponentClick;wheelScroll;mouseEnabled;searchMatchStyle;searchCurrentMatchStyle;searchNavigationButtonStyle;scrollToEndIndicator;openUrl;onRightClickPaste;copyOnSelect;copySelection;constructor(e,t,i,n={}){super(e,t,i),this.implicitDocument={render:r=>super.render(r),handleMouse:r=>super.handleMouse(r),invalidate:()=>{for(let r of this.children)r.invalidate()}},this.implicitScrollView=new lt(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new Is(()=>this.requestRender()),this.wheelScroll=new Es(n.wheelScrollLines??1),this.mouseEnabled=n.mouse??!0,this.searchMatchStyle=n.searchMatchStyle??(r=>`\x1B[4m${r}\x1B[24m`),this.searchCurrentMatchStyle=n.searchCurrentMatchStyle??(r=>`\x1B[1;7m${r}\x1B[22;27m`),this.searchNavigationButtonStyle=n.searchNavigationButtonStyle??(r=>r),this.scrollToEndIndicator=n.scrollToEndIndicator,this.openUrl=n.openUrl,this.onRightClickPaste=n.onRightClickPaste,this.copyOnSelect=n.copyOnSelect??!0,this.copySelection=n.copySelection,this.addInputListener(r=>this.handleViewportInput(r))}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}setWheelScrollLines(e){this.wheelScroll.setLines(e)}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(e){this.copyOnSelect=e}hasActiveSelection(){return this.getActiveSelectionText()!==void 0}async copyActiveSelectionToClipboard(){let e=this.getActiveSelectionText();return e?this.copyTextToClipboard(e):!1}resetTextSelection(){this.clearTextSelection(),this.lastClick=void 0}getScreenLines(){return[...this.previousScreen]}setLayoutRoot(e){this.layoutRoot!==e&&(this.layoutRoot=e,this.currentLayout=void 0,this.requestRender())}render(e){return this.layoutRoot?.render(e)??super.render(e)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=!0;let e=ae();this.imageProtocol=e.images,this.uploadedKittyImages.clear(),e.images==="iterm2"&&(this.savedCapabilities=e,os({...e,images:null}),this.invalidate()),this.lastDocument=[],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let t=process.env.TERM?.toLowerCase()??"",i=process.env.TMUX!==void 0||process.env.ZELLIJ!==void 0||process.env.STY!==void 0||t.startsWith("tmux")||t.startsWith("screen")?jp:Gp;this.terminal.write(`${Vp}${gl}${this.mouseEnabled?i:""}\x1B[2J\x1B[H\x1B[?25l`)}beforeTerminalStop(e){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${Ls}${this.deleteKittyImages()}${this.mouseEnabled?bl:""}${vr}${Ci}`),this.uploadedKittyImages.clear())}afterTerminalStop(e){if(this.altScreenActive){if(this.altScreenActive=!1,e.preserveScreen)this.terminal.write(`${Ls}${xr}\x1B[?25h${Ci}`);else{let t=Math.max(1,this.terminal.columns),i=this.resolveFakeCursors(this.render(t)).map(r=>r.replace(yl,""));this.lastDocument=this.applyLineResets(i.map(r=>r.replaceAll(pe,""))).map(r=>z(r)||x(r)<=t?r:H(r,0,t,!0));let n=`${Ls}${xr}${gl}`;for(let r=0;r<this.lastDocument.length;r++)r>0&&(n+=`\r
|
|
105
|
-
`),n+=`\r\x1B[2K${this.lastDocument[r]??""}`;n+=`\x1B[0m${
|
|
106
|
-
\x1B[?25h${Ci}`,this.terminal.write(n)}this.savedCapabilities&&(os(this.savedCapabilities),this.savedCapabilities=void 0)}}getExitRestorePrefix(){let e=super.getExitRestorePrefix();return this.altScreenActive?`${Ci}${this.mouseEnabled?bl:""}${vr}${e}`:e}getExitRestoreSuffix(){return`${super.getExitRestoreSuffix()}${this.altScreenActive?`${xr}\x1B[?25h`:""}`}deleteKittyImages(){return this.imageProtocol==="kitty"?jn():""}prepareKittyScreen(e){let t=new Set,i=e.map(l=>{let c=fa(l);if(!c)return l;t.add(c.imageId);let h=this.uploadedKittyImages.get(c.imageId),u={transmissionGeneration:c.transmissionGeneration,transmissionBytes:c.transmissionBytes,estimatedDecodedBytes:c.estimatedDecodedBytes};return h&&this.uploadedKittyImages.delete(c.imageId),this.uploadedKittyImages.set(c.imageId,u),h?.transmissionGeneration===c.transmissionGeneration?c.replacementLine:l}),n=0,r=0,o=0;for(let[l,c]of this.uploadedKittyImages)t.has(l)||(n+=1,r+=c.transmissionBytes,o+=c.estimatedDecodedBytes);let a="";for(let[l,c]of this.uploadedKittyImages){if(n<=Zp&&r<=ef&&o<=tf)break;t.has(l)||(a+=as(l),this.uploadedKittyImages.delete(l),n-=1,r-=c.transmissionBytes,o-=c.estimatedDecodedBytes)}return{lines:i,evictedImageDeletion:a}}resetRenderState(){this.previousScreen=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(e){this.getPrimaryScrollView().scrollBy(e),this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender()}scrollToPrompt(e){if(!this.currentLayout)return;let t=this.getPrimaryScrollView(),i=we(this.currentLayout,t)?.scrollContentLines;if(i){for(let n=t.scrollTop+e;n>=0&&n<i.length;n+=e)if(Xp.test(i[n]??"")){t.scrollTo(n),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let e=new _s(i=>this.updateSearchQuery(i),this.searchNavigationButtonStyle),t={component:e,index:new Ts,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=t,t.overlay=this.showOverlay(e,{anchor:"top-right",width:"40%",minWidth:32,margin:1})}closeSearch(){let e=this.activeSearch;e&&(this.activeSearch=void 0,e.overlay?.hide(),this.requestRender())}updateSearchQuery(e){let t=this.activeSearch;if(!t||e===t.query)return;let i=t.matches[t.selectedIndex];t.anchorRow=i?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,t.query=e,t.selectionMode="query",t.component.setResult(-1,0),this.requestRender()}navigateSearch(e){let t=this.activeSearch;t?.query&&(t.selectionMode=e<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(e,t){let i=this.activeSearch,n=i?.overlay?.getBounds();if(!(!i||!n)&&!(e<n.col||e>=n.col+n.width||t<n.row||t>=n.row+n.height))return i.component.getNavigationDirectionAt(t-n.row,e-n.col)}handleSearchMouseEvent(e){let t=this.activeSearch;if(!t)return!1;let i=this.getSearchNavigationDirectionAt(e.x,e.y);return t.component.setHoveredNavigationDirection(i)&&this.requestRender(),i===void 0||e.release||(e.button&32)!==0||(e.button&3)!==0?!1:(this.navigateSearch(i),!0)}refreshSearch(e){let t=this.activeSearch;if(!t)return!1;let i=e.primaryScrollView??this.implicitScrollView,n=we(e,i),r=n?.scrollContentLines;if(!r||!t.query.trim())return t.matches=[],t.selectedIndex=-1,t.selectedKey=void 0,t.selectionMode="retain",t.component.setResult(-1,0),!1;let o=t.selectionMode!=="retain",a=t.index.search(r,t.query),l=a.matches;if(t.matches=l,!a.changed&&t.selectionMode==="retain")return!1;let c=a.changed?t.selectedKey?l.findIndex(m=>br(m)===t.selectedKey):-1:t.selectedIndex,h=-1;if(l.length>0)if(t.selectionMode==="query"){let m=0,y=l.length;for(;m<y;){let w=m+Math.floor((y-m)/2);(l[w].segments[0]?.row??0)<t.anchorRow?m=w+1:y=w}h=m<l.length?m:0}else if(t.selectionMode==="next"){let m=c>=0?c:Math.min(t.selectedIndex,l.length-1);h=m<0?0:(m+1)%l.length}else if(t.selectionMode==="previous"){let m=c>=0?c:Math.min(t.selectedIndex,l.length-1);h=m<0?l.length-1:(m-1+l.length)%l.length}else h=c>=0?c:Math.min(Math.max(0,t.selectedIndex),l.length-1);if(t.selectedIndex=h,t.selectedKey=h>=0?br(l[h]):void 0,t.selectionMode="retain",t.component.setResult(h,l.length),!o)return!1;let u=l[h],d=u?.segments[0],p=u?.segments[u.segments.length-1];if(!n||!d||!p||i.viewportHeight<=0)return!1;let f=i.scrollTop,g=f+i.viewportHeight-1,b=f;return(d.row<f||p.row>g)&&(b=d.row-Math.floor(i.viewportHeight/3)),i.scrollTo(b,{disableFollow:!0}),i.scrollTop!==f}flash(e,t){this.flashes.flash(e,t)}shouldDeferViewportInput(){return this.getFocusedComponent()?.capturesViewportInput?!0:this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(e){if(e===Yp){let o=this.selectionPressActive,a=o&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,o&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,a&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(e===Qp)return{consume:!0};let t=this.parseWheelEvent(e);if(t){let o=this.wheelScroll.next(t.direction,performance.now()),a=t.direction*((t.button&8)!==0?o*Jp:o),l=this.createMouseEvent("wheel",t.button,t.x,t.y,{wheelDelta:a}),c=this.dispatchMouseToOverlay(l),h=c.result??(c.hit?void 0:this.dispatchMouseToLayout(l));return h?(this.applyMouseDispatchResult(l,h)&&this.requestRender(),{consume:!0}):(this.routeWheel(t,a),{consume:!0})}let i=this.parseSgrMouseEvent(e);if(i)return this.handleMouseEvent(i),{consume:!0};if(this.isMouseSequence(e))return{consume:!0};let n=fe(),r=ui(e);if(n.matches(e,"tui.altScreen.search"))return r||this.toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(n.matches(e,"tui.altScreen.searchNext"))return r||this.navigateSearch(1),{consume:!0};if(n.matches(e,"tui.altScreen.searchPrevious"))return r||this.navigateSearch(-1),{consume:!0};if(n.matches(e,"tui.altScreen.searchClose"))return r||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInput()){if(n.matches(e,"tui.altScreen.pageUp"))return r||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-wl)),{consume:!0};if(n.matches(e,"tui.altScreen.pageDown"))return r||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-wl)),{consume:!0};if(n.matches(e,"tui.altScreen.halfPageUp"))return r||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(n.matches(e,"tui.altScreen.halfPageDown"))return r||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(n.matches(e,"tui.altScreen.lineUp"))return r||this.scrollBy(-1),{consume:!0};if(n.matches(e,"tui.altScreen.lineDown"))return r||this.scrollBy(1),{consume:!0};if(n.matches(e,"tui.altScreen.previousPrompt"))return r||this.scrollToPrompt(-1),{consume:!0};if(n.matches(e,"tui.altScreen.nextPrompt"))return r||this.scrollToPrompt(1),{consume:!0};if(n.matches(e,"tui.altScreen.top"))return r||this.scrollToTop(),{consume:!0};if(n.matches(e,"tui.altScreen.bottom"))return r||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(e){switch(e&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}createMouseEvent(e,t,i,n,r={}){return{type:e,button:e==="wheel"?"none":this.decodeMouseButton(t),x:i,y:n,screenX:i,screenY:n,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(t&4)!==0,alt:(t&8)!==0,ctrl:(t&16)!==0,...r.wheelDelta===void 0?{}:{wheelDelta:r.wheelDelta},...r.clickCount===void 0?{}:{clickCount:r.clickCount}}}dispatchMouseToLayout(e){if(!this.currentLayout)return;let t=new Set,i=ml(this.currentLayout,e.screenX,e.screenY);for(let n of i){if(t.has(n.component)||ys(n.component)&&n.component.handleMouse===ee.prototype.handleMouse)continue;t.add(n.component);let r=tt(n.component,{...e,x:e.screenX-n.rect.x,y:e.screenY-n.rect.y,width:n.rect.width,height:n.rect.height});if(r)return r}}applyMouseDispatchResult(e,t){let i=this.resolveMouseFocusTarget(t.focusTarget??t.target.component),n=t.focus===!0&&this.getFocusedComponent()!==i;return t.focus&&this.setFocus(i),t.capture&&(this.mouseCapture=t.target),t.render??(n||e.type==="press"||e.type==="click"||e.type==="drag"||e.type==="wheel")}dispatchMouseToTarget(e,t){return tt(t.component,wa(e,t))}getComponentClickCount(e,t,i){let n=Date.now(),r=this.lastComponentClick,o=r&&n-r.timestamp<=xl&&r.component===e.component&&r.x===t&&r.y===i?r.count%3+1:1;return this.lastComponentClick={timestamp:n,count:o,component:e.component,x:t,y:i},o}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(e){let t=(e.button&32)!==0,i=e.release?"release":t?this.decodeMouseButton(e.button)==="none"?"move":"drag":"press",n=this.createMouseEvent(i,e.button,e.x,e.y);if(this.mouseCapture||this.mousePressTarget){let a=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(e.x!==this.mousePressPoint.x||e.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let l=!1,c=this.dispatchMouseToTarget(n,a);if(c&&(l=this.applyMouseDispatchResult(n,c)),e.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===e.x&&this.mousePressPoint.y===e.y){let h=this.createMouseEvent("click",e.button,e.x,e.y,{clickCount:this.getComponentClickCount(a,e.x,e.y)}),u=this.dispatchMouseToTarget(h,a);u&&(l=this.applyMouseDispatchResult(h,u)||l)}this.clearComponentMouseGesture()}l&&this.requestRender();return}if(this.handleSearchMouseEvent(e))return;let r=this.dispatchMouseToOverlay(n);if(r.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(e))return;let a=this.handleScrollbarMouseEvent(e);if(this.scrollbarDrag||this.updateScrollbarHover(e.x,e.y),a)return}let o=r.result??(r.hit?void 0:this.dispatchMouseToLayout(n));if(o){let a=this.applyMouseDispatchResult(n,o);i==="press"&&(this.clearTextSelection(),this.mousePressTarget=o.target,this.mousePressPoint={x:e.x,y:e.y},this.mousePressMoved=!1),a&&this.requestRender();return}this.handleRightClickPaste(e)||this.handleSelectionMouseEvent(e)}parseWheelEvent(e){let t=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(e);if(t){let i=Number.parseInt(t[1],10);if((i&64)===0)return;let n=i&3;return n!==0&&n!==1?void 0:{direction:n===0?-1:1,x:Number.parseInt(t[2],10)-1,y:Number.parseInt(t[3],10)-1,button:i}}if(e.length===6&&e.startsWith("\x1B[M")){let i=e.charCodeAt(3)-32;if((i&64)===0)return;let n=i&3;return n!==0&&n!==1?void 0:{direction:n===0?-1:1,x:e.charCodeAt(4)-33,y:e.charCodeAt(5)-33,button:i}}}routeWheel(e,t){let i=t,n=new Set;for(let o of this.currentLayout?Ms(this.currentLayout,e.x,e.y):[])if(n.add(o),i=o.scrollBy(i),i===0||o.overscroll==="contain")break;let r=this.getPrimaryScrollView();i!==0&&!n.has(r)&&r.scrollBy(i),this.updateScrollbarHover(e.x,e.y),this.requestRender()}parseSgrMouseEvent(e){let t=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(e);if(t)return{button:Number.parseInt(t[1],10),x:Number.parseInt(t[2],10)-1,y:Number.parseInt(t[3],10)-1,release:t[4]==="m"}}handleRightClickPaste(e){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||e.release||e.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(e){let t=this.scrollToEndIndicatorRect;return!t||e.release||(e.button&32)!==0||(e.button&3)!==0||e.y!==t.row||e.x<t.column||e.x>=t.column+t.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(e,t,i=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let n of Ms(this.currentLayout,e,t)){let r=we(this.currentLayout,n),o=r?zt(r,i):void 0;if(o&&e===o.column&&t>=o.trackTop&&t<o.trackTop+o.trackHeight)return{scrollView:n,geometry:o}}}setScrollbarHover(e){e!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=e,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(e,t){this.setScrollbarHover(this.getScrollbarTargetAt(e,t,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(e,t,i,n){let r=t.trackHeight-t.thumbHeight,o=Math.max(0,Math.min(r,i-t.trackTop-n)),a=r===0?0:Math.round(o/r*t.maxScrollTop);e.scrollTo(a)}handleScrollbarMouseEvent(e){if(this.scrollbarDrag){if(e.release)return this.stopScrollbarDrag(),!0;let r=this.currentLayout?we(this.currentLayout,this.scrollbarDrag.scrollView):void 0,o=r?zt(r):void 0;return o&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,o,e.y,this.scrollbarDrag.grabOffset),!0}if(e.release||(e.button&32)!==0||(e.button&3)!==0)return!1;let t=this.getScrollbarTargetAt(e.x,e.y);if(!t)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.setScrollbarHover(t.scrollView);let i=e.y>=t.geometry.thumbTop&&e.y<t.geometry.thumbTop+t.geometry.thumbHeight,n=i?e.y-t.geometry.thumbTop:Math.floor(t.geometry.thumbHeight/2);return i||this.scrollScrollbarToPointer(t.scrollView,t.geometry,e.y,n),this.scrollbarDrag={scrollView:t.scrollView,grabOffset:n},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(e,t,i){if(!this.currentLayout)return;let n=we(this.currentLayout,e);if(!n||n.rect.height<=0||n.clip.height<=0)return;let r=Math.max(0,n.rect.y,n.clip.y),o=Math.min(this.terminal.rows-1,n.rect.y+n.rect.height-1,n.clip.y+n.clip.height-1);if(o<r)return;let a=Math.max(r,Math.min(o,i)),l=Math.max(0,(n.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(l,e.scrollTop+a-n.rect.y)),col:Math.max(0,Math.min(n.rect.width-1,t-n.rect.x)),scrollView:e}}getSelectionPoint(e,t){if(t){let i=this.getScrollSelectionPoint(t,e.x,e.y);if(i)return i}return{row:Math.max(0,Math.min(this.terminal.rows-1,e.y)),col:Math.max(0,Math.min(this.terminal.columns-1,e.x))}}getSelectionSourceLine(e){if(e.scrollView&&this.currentLayout){let t=we(this.currentLayout,e.scrollView)?.scrollContentLines;if(t)return t[e.row]??""}return this.previousScreen[e.row]??""}getWordSelection(e){let t=At(this.getSelectionSourceLine(e)),i=[],n=0;for(let c of rf.segment(t)){let h=n+x(c.segment),u=nf.has(c.segment);i.push({start:n,end:h,selectable:c.isWordLike===!0||u,joiner:u}),n=h}let r=i.findIndex(c=>e.col>=c.start&&e.col<c.end);if(r<0)return;let o=(c,h)=>c.selectable&&h.selectable&&(c.joiner||h.joiner),a=i[r].start,l=i[r].end;for(let c=r;c>0&&o(i[c-1],i[c]);c--)a=i[c-1].start;for(let c=r;c<i.length-1&&o(i[c],i[c+1]);c++)l=i[c+1].end;return{start:{...e,col:a},end:{...e,col:l,boundary:!0}}}getLineSelection(e){return{start:{...e,col:0},end:{...e,col:x(this.getSelectionSourceLine(e)),boundary:!0}}}updateSelectionFocus(e){if(this.selectionGranularity==="character"||!this.selectionInitialRange){this.selectionFocus=e;return}let t=this.selectionGranularity==="word"?this.getWordSelection(e):this.getLineSelection(e);if(!t)return;let i=this.selectionInitialRange;t.start.row<i.start.row||t.start.row===i.start.row&&t.start.col<i.start.col?(this.selectionAnchor=i.end,this.selectionFocus=t.start):(this.selectionAnchor=i.start,this.selectionFocus=t.end)}getClickCount(e,t){let i=Date.now(),n=this.lastClick,r=t&&n&&i-n.timestamp<=xl&&n.row===e.row&&n.scrollView===e.scrollView&&n.wordStart===t.start.col&&n.wordEnd===t.end.col?n.count%3+1:1;return this.lastClick=t?{timestamp:i,count:r,row:e.row,scrollView:e.scrollView,wordStart:t.start.col,wordEnd:t.end.col}:void 0,r}updateSelectionAutoScroll(e){let t=this.selectionAnchor?.scrollView;if(!t||!this.currentLayout){this.stopSelectionAutoScroll();return}let i=we(this.currentLayout,t);if(!i||i.rect.height<=0||i.clip.height<=0){this.stopSelectionAutoScroll();return}let n=Math.max(0,i.rect.y,i.clip.y),r=Math.min(this.terminal.rows-1,i.rect.y+i.rect.height-1,i.clip.y+i.clip.height-1);if(this.selectionDragPointer={x:e.x,y:e.y},this.selectionAutoScrollDirection=e.y<=n?-1:e.y>=r?1:0,this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref())}autoScrollSelection(){let e=this.selectionAnchor?.scrollView,t=this.selectionDragPointer,i=this.selectionAutoScrollDirection;if(!e||!t||i===0){this.stopSelectionAutoScroll();return}if(e.scrollBy(i)===i){this.stopSelectionAutoScroll();return}let r=this.getScrollSelectionPoint(e,t.x,t.y);r&&this.updateSelectionFocus(r),this.requestRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&(clearInterval(this.selectionAutoScrollTimer),this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(e){let t=e.button&3;if(t!==0&&!(e.release&&t===3))return;let i=this.selectionAnchor?.scrollView,n=this.getSelectionPoint(e,i);if(e.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(n);let h=!this.selectionDragged&&this.selectionAnchor.scrollView===n.scrollView&&this.selectionAnchor.row===n.row&&this.selectionAnchor.col===n.col,u=h?this.pressedUrl:void 0;if(this.pressedUrl=void 0,u&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(u)}catch{}this.requestRender();return}if(h){let d=this.createMouseEvent("click",e.button,e.x,e.y,{clickCount:this.lastClick?.count??1}),p=this.dispatchMouseToOverlay(d),f=p.result??(p.hit?void 0:this.dispatchMouseToLayout(d));if(f){let g=this.applyMouseDispatchResult(d,f);this.clearTextSelection(),g&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if((e.button&32)!==0){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=!0,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(n),this.updateSelectionAutoScroll(e),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let r=!this.hasOverlay()&&this.currentLayout?Ms(this.currentLayout,e.x,e.y)[0]:void 0,o=this.getSelectionPoint(e,r),a=this.getWordSelection(o),l=this.getClickCount(o,a),c=l===2?a:l===3?this.getLineSelection(o):void 0;this.selectionGranularity=c?l===2?"word":"line":"character",this.selectionInitialRange=c,this.selectionAnchor=c?.start??o,this.selectionFocus=c?.end??o,this.selectionDragged=!1,this.pressedUrl=c?void 0:qn(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,e.y))]??"",Math.max(0,Math.min(this.terminal.columns-1,e.x))),this.requestRender()}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let e=this.selectionAnchor.row<this.selectionFocus.row||this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col<this.selectionFocus.col;if(!(this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col===this.selectionFocus.col))return e?{start:this.selectionAnchor,end:this.selectionFocus}:{start:this.selectionFocus,end:this.selectionAnchor}}getSelectionColumns(e,t,i,n=0,r=x(e)){let o=x(e),a=Math.max(0,n),l=Math.min(o,r);return t===i.start.row&&(a=ri(e,i.start.col)?.start??Math.min(i.start.col,o)),t===i.end.row&&(l=i.end.boundary?Math.min(i.end.col,o):ri(e,i.end.col)?.end??Math.min(i.end.col+1,o)),{start:Math.max(n,a),end:Math.min(r,l)}}getActiveSelectionText(){let e=this.getSelectionBounds();if(!e)return;let t=this.previousScreen;if(e.start.scrollView){if(!this.currentLayout)return;let r=we(this.currentLayout,e.start.scrollView);if(!r?.scrollContentLines)return;t=r.scrollContentLines}let i=[];for(let r=e.start.row;r<=e.end.row;r++){let o=t[r]??"",a=this.getSelectionColumns(o,r,e);i.push(At(H(o,a.start,Math.max(0,a.end-a.start),!0)).trimEnd())}let n=i.join(`
|
|
107
|
-
`);return n.length===0?void 0:n}async copySelectionToClipboard(){let e=this.getActiveSelectionText();return e?this.copyTextToClipboard(e):!1}async copyTextToClipboard(e){if(this.copySelection){let t=await this.copySelection(e),i=t===!0;return this.flash(i?"Copied!":typeof t=="string"?t:"Copy failed",i?void 0:sf),i}return this.terminal.write(`\x1B]52;c;${Buffer.from(e).toString("base64")}\x07`),this.flash("Copied!"),!0}applySearchTextHighlight(e,t){let i=t?this.searchCurrentMatchStyle:this.searchMatchStyle,n="",r=0,o=0;for(;o<e.length;){let a=U(e,o);if(!a){o+=1;continue}o>r&&(n+=i(e.slice(r,o))),n+=a.code,o+=a.length,r=o}return r<e.length&&(n+=i(e.slice(r))),n}applySearchHighlights(e,t){let i=this.activeSearch;if(!i||i.selectedIndex<0||i.matches.length===0)return e;let n=t.primaryScrollView??this.implicitScrollView,r=we(t,n);if(!r)return e;let o=new Map,a=zt(r)?.column,l=Math.max(0,r.rect.y,r.clip.y),c=Math.min(e.length,r.rect.y+r.rect.height,r.clip.y+r.clip.height),h=Math.max(0,r.rect.x,r.clip.x),u=Math.min(this.terminal.columns,r.rect.x+r.rect.width,r.clip.x+r.clip.width,a??Number.POSITIVE_INFINITY),d=n.scrollTop+l-r.rect.y,p=n.scrollTop+c-r.rect.y-1,f=0,g=i.matches.length;for(;f<g;){let m=f+Math.floor((g-f)/2),y=i.matches[m];(y.segments[y.segments.length-1]?.row??-1)<d?f=m+1:g=m}for(let m=f;m<i.matches.length;m++){let y=i.matches[m];if((y.segments[0]?.row??0)>p)break;for(let w of y.segments){let k=r.rect.y+w.row-n.scrollTop;if(k<l||k>=c)continue;let R=Math.max(h,r.rect.x+w.startCol),v=Math.min(u,r.rect.x+w.endCol);if(v<=R)continue;let A=o.get(k)??[];A.push({startCol:R,endCol:v,current:m===i.selectedIndex}),o.set(k,A)}}let b=[...e];for(let[m,y]of o){let w=b[m]??"";if(z(w))continue;let k=x(w);for(let R of y.sort((v,A)=>A.startCol-v.startCol)){let v=Math.min(R.startCol,k),A=Math.min(R.endCol,k);if(A<=v)continue;let E=H(w,0,v,!0),B=H(w,v,A-v,!0),q=H(w,A,Math.max(0,k-A),!0);w=`${E}${this.applySearchTextHighlight(B,R.current)}${q}`}b[m]=w}return b}applySelectionHighlight(e){let t="\x1B[7m",i=0;for(;i<e.length;){let n=U(e,i);if(!n){t+=e[i],i+=1;continue}t+=n.code,n.code.endsWith("m")&&(t+="\x1B[7m"),i+=n.length}return`${t}\x1B[27m`}applySelection(e,t=this.currentLayout){let i=this.getSelectionBounds();if(!i)return e;let n=i,r=0,o=e.length-1,a=0,l=this.terminal.columns;if(i.start.scrollView){if(!t)return e;let c=we(t,i.start.scrollView);if(!c)return e;r=Math.max(0,c.rect.y,c.clip.y),o=Math.min(e.length-1,c.rect.y+c.rect.height-1,c.clip.y+c.clip.height-1),a=Math.max(0,c.rect.x,c.clip.x),l=Math.min(this.terminal.columns,c.rect.x+c.rect.width,c.clip.x+c.clip.width),n={start:{...i.start,row:c.rect.y+i.start.row-i.start.scrollView.scrollTop,col:c.rect.x+i.start.col},end:{...i.end,row:c.rect.y+i.end.row-i.start.scrollView.scrollTop,col:c.rect.x+i.end.col}}}return e.map((c,h)=>{if(h<r||h>o||h<n.start.row||h>n.end.row||z(c))return c;let u=x(c),d=this.getSelectionColumns(c,h,n,a,l);if(d.end<=d.start)return c;let p=H(c,0,d.start,!0),f=H(c,d.start,d.end-d.start,!0),g=H(c,d.end,Math.max(0,u-d.end),!0);return`${p}${this.applySelectionHighlight(f)}${g}`})}isMouseSequence(e){return/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(e)||e.length===6&&e.startsWith("\x1B[M")}compositeScrollToEndIndicator(e,t,i){this.scrollToEndIndicatorRect=void 0;let n=t.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!n.followEnd||n.isFollowingEnd)return e;let r=we(t,n),o=r?.clip;if(!o||o.width<=0||o.height<=0)return e;let a=o.y+o.height-1;if(a>=e.length||z(e[a]??""))return e;let l=r?zt(r)?.column:void 0,c=_(this.scrollToEndIndicator(),o.width,""),h=x(c),u=o.x+Math.floor((o.width-h)/2),d=l??o.x+o.width,p=Math.max(0,d-u),f=_(c,p,""),g=x(f);if(g===0)return e;let b=[...e];return b[a]=He(b[a]??"",f,u,g,i),this.scrollToEndIndicatorRect={row:a,column:u,width:g},b}compositeFlashes(e,t,i){let n=this.flashes.render(t).slice(-i);if(n.length===0)return e;let r=[...e];for(;r.length<i;)r.push("");for(let o=0;o<n.length;o++){let a=n[o],l=x(a);l!==0&&(r[o]=He(r[o]??"",a,t-l,l,t))}return r}doRender(){if(this.stopped||!this.altScreenActive)return;let e=Math.max(1,this.terminal.columns),t=Math.max(1,this.terminal.rows),i=this.layoutRoot??this.implicitScrollView,n=wr(i,e,t,()=>this.requestRender());this.refreshSearch(n)&&(n=wr(i,e,t,()=>this.requestRender()));let r=this.resolveFakeCursors(n.lines.map(m=>m.replace(yl,"")));r=this.applySearchHighlights(r,n),r=this.compositeScrollToEndIndicator(r,n,e),r=this.compositeOverlays(r,e,t),r.length>t&&(r=r.slice(r.length-t)),r=this.applySelection(r,n),r=this.compositeFlashes(r,e,t);let o=this.extractCursorPosition(r,t);r=this.applyLineResets(r).map(m=>z(m)||x(m)<=e?m:H(m,0,e,!0));let a=this.previousScreen.length===0||this.previousScreenWidth!==e||this.previousScreenHeight!==t,l=r.map((m,y)=>m!==this.previousScreen[y]),c=r.some((m,y)=>l[y]&&(z(m)||z(this.previousScreen[y]??""))),h=!c&&this.imageProtocol==="kitty"&&l.some(Boolean)&&r.some((m,y)=>{let w=pa(m);if(w===void 0)return!1;for(let k=y;k<y+w;k++)if(l[k])return!0;return!1}),u=c||h,d=a||u,p=this.uploadedKittyImages.size>0,f=d&&this.imageProtocol==="kitty"?this.prepareKittyScreen(r):{lines:r,evictedImageDeletion:""},g=Ls;if(a){this.fullRedrawCount+=1;let m=this.imageProtocol==="kitty"&&p?Gn():this.deleteKittyImages();g+=`${m}\x1B[2J`}else u&&(this.imageProtocol==="iterm2"?g+="\x1B[2J":this.imageProtocol==="kitty"&&(g+=Gn()));if(g+=f.evictedImageDeletion,d&&this.imageProtocol==="kitty"&&r.some(z)){for(let m=0;m<t;m++)!a&&!u&&r[m]===this.previousScreen[m]||(g+=`\x1B[${m+1};1H\x1B[2K`);for(let m=0;m<t;m++)!a&&!u&&r[m]===this.previousScreen[m]||z(f.lines[m]??"")||(g+=`\x1B[${m+1};1H${f.lines[m]??""}`);for(let m=0;m<t;m++)!a&&!u&&r[m]===this.previousScreen[m]||z(f.lines[m]??"")&&(g+=`\x1B[${m+1};1H${f.lines[m]??""}`)}else for(let m=0;m<t;m++)!a&&!u&&r[m]===this.previousScreen[m]||(g+=`\x1B[${m+1};1H\x1B[2K${f.lines[m]??""}`);o?(g+=`\x1B[${o.row+1};${Math.min(e,o.col)+1}H`,g+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):g+="\x1B[?25l",g+=Ci,this.terminal.write(g),this.previousScreen=r,this.previousScreenWidth=e,this.previousScreenHeight=t,this.currentLayout=n}};var dw=1024*1024;import{spawn as Nm}from"node:child_process";import{existsSync as qc,statSync as Dc}from"node:fs";import{homedir as Fm}from"node:os";import{basename as mn,join as gn,relative as Wm,sep as Bc}from"node:path";import{mkdirSync as Vf,readFileSync as jf,renameSync as Gf,writeFileSync as Qf}from"node:fs";import{dirname as Yf}from"node:path";import{randomBytes as Ul}from"node:crypto";import{createWriteStream as Tf,openAsBlob as _f,renameSync as If,rmSync as Rf}from"node:fs";import{basename as zs,dirname as Pf,join as Mf}from"node:path";import{Readable as Fl}from"node:stream";import{pipeline as Ef}from"node:stream/promises";var $=s=>!!s&&typeof s=="object"&&!Array.isArray(s),N=s=>typeof s=="number"&&Number.isFinite(s),V=s=>typeof s=="number"&&Number.isSafeInteger(s)&&s>0,kr=s=>typeof s=="number"&&Number.isSafeInteger(s)&&s>=1&&s<=4096,ne=s=>typeof s=="string"&&!!s.trim(),ct=s=>{if(typeof s!="string")return s;try{return JSON.parse(s)}catch{return null}},of=s=>s.replace(/^mcp__(?:listing_)?(.+)__(.+)$/,"$1.$2");function qs(s,e){let t=of(s.name),i=$(s.resultData)?s.resultData:{},n=$(i._meta)?i._meta:{},r=$(n["com.qupai/tool-source"])?n["com.qupai/tool-source"]:{};return e.filter(o=>{if(o===t)return!0;let a=o.indexOf(".");return a>0&&s.name===o.slice(a+1)&&r.tool===s.name&&r.server===`listing_${o.slice(0,a).replace(/[^a-zA-Z0-9_]/g,"_")}`}).length===1}var af=s=>$(s.counts),lf=s=>s.ok===!0,Cl=s=>N(s.min_energy)&&$(s.optimal_parameters)||N(s.value)&&$(s.gradient);function Vt(s,e=af){let t=ct(s);if(!$(t)||t.isError===!0)return null;if($(t.structuredContent))return Vt(t.structuredContent,e);if($(t.result))return Vt(t.result,e);if(Array.isArray(t.content)){for(let i of t.content)if($(i)&&i.type==="text"){let n=Vt(i.text,e);if(n)return n}}return e(t)?t:null}function cf(s){let e=s.args??ct(s.input);if(!$(e)||typeof e.code!="string"||!e.code.trim())return null;let t=ct(e.parameters??{});if(!$(t)||Object.values(t).some(c=>!N(c))||/\bParameter\b/.test(e.code)&&!Object.keys(t).length)return null;let i=Vt(s.resultData??s.result);if(!i||!$(i.counts))return null;let{shots:n,num_qubits:r,counts:o}=i;if(!V(n)||!kr(r)||e.shots!==void 0&&e.shots!==n)return null;let a=Object.entries(o);if(!a.length||a.length>65536)return null;let l=a[0][0].length;return!l||l>r||a.some(([c,h])=>c.length!==l||!/^[01]+$/.test(c)||!Number.isSafeInteger(h)||h<0)||a.reduce((c,[,h])=>c+h,0)!==n?null:{kind:"distribution",toolCallId:s.id,qubits:r,shots:n,counts:{...o}}}function vl(s){return typeof s=="string"?s.trim()?{name:s}:void 0:$(s)&&typeof s.name=="string"&&s.name.trim()&&N(s.bond_length)?{name:s.name,bondLength:s.bond_length}:void 0}function hf(s){return s?Array.isArray(s.points)?"scan":"max_cut"in s?"maxcut":"min_energy"in s||"value"in s&&"gradient"in s?"energy":null:null}function uf(s){let e=s.args??ct(s.input);if(!$(e)||!Array.isArray(e.hamiltonian))return null;let t=0;for(let i of e.hamiltonian){if(!$(i)||!Array.isArray(i.qubits))return null;for(let n of i.qubits){if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)return null;t=Math.max(t,n+1)}}return t>=1?t:null}function df(s,e,t){if(t==="energy"&&!ne(e.result_ref)&&Cl(e)){let n=kr(e.num_qubits)?e.num_qubits:uf(s);return n?{kind:"energy",toolCallId:s.id,qubits:n,minEnergy:N(e.min_energy)?e.min_energy:e.value}:null}if(!kr(e.num_qubits))return null;let i={toolCallId:s.id,qubits:e.num_qubits};if(t==="energy"){if(!ne(e.result_ref)||!N(e.min_energy))return null;let n={kind:"energy",...i,minEnergy:e.min_energy},r=vl(e.molecule);return r?.bondLength!==void 0&&(n.molecule=r),N(e.exact_energy)&&(n.exactEnergy=e.exact_energy),n}if(t==="scan"){let n=vl(e.molecule);if(typeof e.molecule!="string"||!n||!Array.isArray(e.points))return null;let r=e.points.flatMap((a,l)=>$(a)&&ne(a.result_ref)&&N(a.min_energy)&&N(a.bond_length)&&a.failed===void 0&&a.skipped===void 0?[{index:l,bondLength:a.bond_length,minEnergy:a.min_energy}]:[]);if(!r.length)return null;let o=r.reduce((a,l)=>l.minEnergy<a.minEnergy?l:a);return{kind:"energy",...i,molecule:n,scan:{points:r,defaultPoint:o.index}}}return!ne(e.result_ref)||!V(e.shots)?null:{kind:"maxcut",...i,shots:e.shots}}function pf(s,e){if(s.state!=="done"||!qs(s,e))return null;let t=s.resultData??s.result,i=Vt(t,lf)??Vt(t,Cl),n=hf(i);return n?df(s,i,n):cf(s)}function Os(s){let e=ct(s);if(!$(e)||e.isError||e.error||e.ok===!1)return null;if($(e.structuredContent))return Os(e.structuredContent);if($(e.result))return Os(e.result);if(Array.isArray(e.content)){for(let t of e.content)if($(t)&&t.type==="text"){let i=Os(t.text);if(i)return i}}return typeof e.best_objective_value=="number"?e:null}function ff(s,e){if(s.state!=="done"||!qs(s,e))return null;let t=s.resolvedArgs??s.args??ct(s.input);if(!$(t))return null;let i=t.matrix!=null,n=t.fields!=null;if(i===n)return null;let r=i?"qubo":"ising",o=Os(s.resultData??s.result);if(!o)return null;let a=o.num_variables,l=o.best_objective_value,c=o[r==="qubo"?"best_bits":"best_spins"];return!Number.isSafeInteger(a)||a<1||a>2048||!N(l)||!Array.isArray(c)||c.length!==a||c.some(h=>!(r==="qubo"?[0,1]:[-1,1]).includes(h))?null:{kind:"optimization",toolCallId:s.id,problem:r,numVariables:a,objective:l}}function Ge(s){if(s.id==="hardware-verification")return"logicqubit";let e=/^hardware-verification-([a-z][a-z0-9-]{0,63})$/.exec(s.id);return e?e[1]:null}function Sr(s){let e=new Map;for(let t of s){let i=Ge(t);i&&!e.has(i)&&e.set(i,t)}return e}var Cr=new Set(["originq","tianyan"]);function $r(s,e){let t=s["compute.providers"];return t==null?!0:Array.isArray(t)&&t.includes(e)}function Ds(s,e,t){if(!t?.length||e.state!=="complete"||s.state!=="done")return null;let i=t.filter(o=>Ge(o)!==null),n=i.filter(o=>qs(s,o.source_tools));if(n.length){let o=pf(s,n[0].source_tools);if(o){let a=n.find(l=>l.id==="hardware-verification")??n[0];return{candidate:o,action:a,actions:i.filter(l=>qs(s,l.source_tools))}}}let r=t.find(o=>o.id==="optimization-verification");if(r){let o=ff(s,r.source_tools);if(o)return{candidate:o,action:r,actions:[]}}return null}function $l(s,e,t,i){if(s.candidate.kind==="optimization")return["isingq"];if(i)return[i];let n=Ge(s.action),r=s.candidate,o=r.kind==="distribution"||r.kind==="energy"&&!r.scan,a=[...Sr(s.actions).keys()].filter(l=>l===n||o&&!!e?.some(c=>c.id===l&&c.integration==="implemented"&&c.source_kind==="hardware")&&(!t||$r(t,l)));return a.length?a:n?[n]:[]}function Al(s,e){let i=e?.find(n=>n.id===s)?.name;return i?i.en||i.zh||Object.values(i).find(Boolean)||s:s==="isingq"?"isingq":s}var mf=4096,_i=1024;function Tl(s){return s.kind==="energy"?mf:s.shots}function Bs(s,e){let t=typeof s.largest_connected_qubits=="number"?s.largest_connected_qubits:s.num_qubits;return t==null||t>=e}function Ai(s,e){return s.online!==!1&&Bs(s,e)}function Ar(s,e){return[...s.filter(t=>Ai(t,e)),...s.filter(t=>!Ai(t,e))]}function _l(s,e){if(!s.length||new Set(s).size!==s.length)return!1;if(s.length===1)return!0;let t=new Set(s),i=new Set([s[0]]),n=[s[0]];for(;n.length;){let r=n.pop();for(let[o,a]of e){let l=o===r?a:a===r?o:void 0;l&&t.has(l)&&!i.has(l)&&(i.add(l),n.push(l))}}return i.size===s.length}function Tr(s,e,t,i,n){if(!t.includes(s))return!1;let r=e.includes(s)?e.filter(o=>o!==s):[...e,s];return r.length<=n&&(!r.length||_l(r,i))}function Il(s,e,t){return s.length===t&&s.every(i=>/^(0|[1-9][0-9]*)$/.test(i)&&Number.isSafeInteger(Number(i))&&e.qubit_ids.includes(i))&&_l(s,e.couplings)}function Rl(s,e){let t=s.qubit_metrics.find(o=>o.id===e);if(!t)return"no figures";let i=o=>N(o)?`${o>=100?o.toFixed(0):o.toFixed(1)} \xB5s`:"\u2014",n=o=>N(o)?o.toFixed(3):"\u2014",r=[`T1 ${i(t.t1_us)}`,`T2e ${i(t.t2e_us)}`,`T2* ${i(t.t2star_us)}`,`F0 ${n(t.readout_f0)}`,`F1 ${n(t.readout_f1)}`];return N(t.xeb_fidelity)&&r.push(`XEB ${n(t.xeb_fidelity)}`),N(t.single_qubit_gate_fidelity)&&r.push(`1q ${n(t.single_qubit_gate_fidelity)}`),r.join(" ")}function ht(s){if(s<10&&!Number.isInteger(s))return`${s<1?s.toFixed(2):s.toFixed(1)} s`;let e=Math.round(s);if(e<60)return`${e} s`;let t=i=>String(i).padStart(2,"0");return e<3600?`${Math.floor(e/60)} min ${t(e%60)} s`:`${Math.floor(e/3600)} h ${t(Math.floor(e%3600/60))} min`}function Pl(s){let e=s.online===!1?"offline":s.online===null?`status unknown${s.status?` (${s.status})`:""}`:s.status??"online",t=s.queue_depth!==null&&s.queue_depth!==void 0?`${s.queue_depth} queued`:s.idle_eta_seconds!=null?s.idle_eta_seconds>0?`free in about ${ht(s.idle_eta_seconds)}`:"free now":"queue not reported";return{state:e,queue:t}}var je=class extends Error{errorType;constructor(e,t){super(e),this.name="PreviewRefused",this.errorType=t}},Ns=s=>"kind"in s&&(s.kind==="energy"||s.kind==="maxcut"),Fs=s=>"workload"in s&&s.workload==="quadratic_optimization",Ti=s=>Array.isArray(s)&&s.every(e=>Number.isSafeInteger(e)&&e>=0);function Ml(s){if(!$(s)||s.status!=="preview"||!ne(s.preview_id)||!ne(s.target)||!Ti(s.qids)||!V(s.shots)||!["auto","physical_pool"].includes(String(s.layout_mode))||!$(s.compilation))return!1;let e=s.baseline;return $(e)&&$(e.input)&&typeof e.input.code=="string"&&$(e.result)&&$(e.result.counts)&&V(e.result.shots)&&(s.mode===void 0||s.mode==="sandbox")}function El(s){if(!$(s)||s.status!=="preview"||!ne(s.preview_id)||!["energy","maxcut"].includes(String(s.kind))||!ne(s.target)||!V(s.shots)||typeof s.readout_correction!="boolean"||!Ti(s.qids))return!1;let e=s.variational;return $(e)&&V(e.circuits)&&V(e.total_shots)&&Ti(e.qubits)&&$(s.baseline)&&(s.mode===void 0||s.mode==="sandbox")}function gf(s){if(!$(s)||s.status!=="preview"||s.provider!=="isingq"||s.workload!=="quadratic_optimization"||!ne(s.preview_id)||!$(s.options)||!$(s.machine)||!$(s.baseline))return!1;let e=s.options,t=s.machine,i=s.baseline;return V(t.computer_type_id)&&typeof t.name=="string"&&V(t.max_variables)&&t.computer_type_id===e.computer_type_id&&V(e.calculate_count)&&typeof e.post_process=="boolean"&&typeof e.use_credit=="boolean"&&N(i.objective_value)&&V(i.num_variables)&&typeof i.model_hash=="string"}function bf(s){return Array.isArray(s.content)?s.content.filter(e=>$(e)&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
|
|
108
|
-
`):""}function Ll(s){let e=$(s)?s:{},t=bf(e);if(e.isError===!0){let n=$(e.structuredContent)?e.structuredContent:{};throw new je(t||"The service refused this preview",typeof n.error_type=="string"?n.error_type:null)}let i=e.structuredContent;if(i==null&&t&&(i=ct(t)),$(i)&&"result"in i&&$(i.result)&&(i=i.result),El(i)||Ml(i)||gf(i))return i;throw new Error("the server returned an incomplete hardware preview")}function _r(s){return $(s)&&typeof s.id=="string"&&s.id&&["compiling","ready","failed"].includes(String(s.state))?s:null}function Ol(s){if(s.state==="failed")throw new je(s.error||"The sandbox could not compile this run","sandbox_compile_failed");let e=s.preview;if(!(El(e)||Ml(e))||e.mode!=="sandbox"||e.preview_id!==s.id)throw new Error("the server returned an incomplete hardware preview");return e}function Ir(s){let[e,t]=Ns(s)?[s.variational.readout_note,s.readout_correction]:[s.readout_correction_note,s.compilation.readout_correction];return typeof e=="string"&&e.trim()?{note:e,fixedOn:t===!0}:null}var Ws=s=>(Math.ceil(s*100-1e-6)/100).toFixed(2),Ii=s=>s.replace(/\d/g,e=>"\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089"[Number(e)]).replace(/\+/g,"\u207A"),Ri=s=>s.replace(/^-/,"\u2212");function Rr(s){let e=$(s)&&$(s.device_queue)?s.device_queue:null;if(!e)return null;let t=e.jobs,i=e.idle_eta_s,n=typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t===0?"No task is waiting for this chip (read from the provider as this preview was made).":`${t} task${t===1?" is":"s are"} waiting for this chip (read from the provider as this preview was made).`:N(i)&&i>=0?i<1?"This chip is free now (as its provider said when this preview was made).":`This chip expects to be free in ${ht(i)} (as its provider said when this preview was made).`:null,r=N(e.typical_s)&&V(e.typical_runs)?`The last ${e.typical_runs} task${e.typical_runs===1?"":"s"} sent to this chip from here took about ${ht(e.typical_s)} from sending to the result.`:null;return!n&&!r?null:[n,r].filter(Boolean).join(" ")}function ql(s,e){let t=$(s)&&$(s.progress)?s.progress:null;if(!t||!["queued","running","sent"].includes(String(t.phase))||!N(t.phase_s)||t.phase_s<0)return null;let i=ht(Math.floor(t.phase_s)),n=typeof t.device_jobs=="number"&&t.device_jobs>0?t.device_jobs:0,r=t.phase==="running"?`Running on the chip \xB7 ${i} so far`:t.phase==="queued"&&V(t.queue_position)?`Waiting in the chip's queue, place ${t.queue_position} \xB7 ${i} so far`:n?`Waiting in the chip's queue (${n} task${n===1?" is":"s are"} waiting for it now) \xB7 ${i} so far`:t.phase==="queued"?`Waiting in the chip's queue \xB7 ${i} so far`:`Sent, waiting for the chip's result \xB7 ${i} so far`,o=V(t.circuit)&&e&&e>1?`Circuit ${t.circuit} of ${e}: `:"",a=N(t.typical_s)&&V(t.typical_runs)?` \xB7 tasks on this chip lately took about ${ht(t.typical_s)}`:"";return`${o}${r}${a}`}function Ks(s){if(!$(s)||!ne(s.preview_id)||!ne(s.target)||!V(s.shots)||!Ti(s.qids)||!$(s.compilation))return null;let e=s.baseline;return!$(e)||!$(e.source)||!ne(e.source.turn_id)||!ne(e.source.tool_call_id)||!$(e.result)||!$(e.result.counts)||!V(e.result.shots)||s.hardware!==void 0&&(!$(s.hardware)||!$(s.hardware.counts))?null:s}var kl=s=>s===null||N(s),Sl=s=>N(s)&&s>=0&&s<=1;function yf(s){return N(s.hardware_energy)&&N(s.standard_error)&&s.standard_error>=0&&N(s.simulated_energy)&&(s.exact_energy===void 0||N(s.exact_energy))&&(s.difference_mha===void 0||N(s.difference_mha))}function wf(s){let e=s.most_frequent,t=s.ideal;return kl(s.approximation_ratio)&&Sl(s.p_optimal)&&N(s.expected_cut)&&N(s.max_cut)&&$(e)&&typeof e.bits=="string"&&/^[01]+$/.test(e.bits)&&N(e.cut)&&$(t)&&N(t.expected_cut)&&kl(t.approximation_ratio)&&Sl(t.p_optimal)}function Pi(s){return!$(s)||!ne(s.preview_id)||!["energy","maxcut"].includes(String(s.kind))||!$(s.source)||!ne(s.target)||!V(s.shots)||!Ti(s.qids)||typeof s.readout_correction!="boolean"||!$(s.baseline)||!$(s.baseline.result)||!$(s.variational)||!V(s.variational.circuits)||s.readout!==void 0&&(!$(s.readout)||typeof s.readout.readout_corrected!="boolean"||!(s.kind==="energy"?yf(s.readout):wf(s.readout)))?null:s}function jt(s){return!$(s)||s.workload!=="quadratic_optimization"||s.provider!=="isingq"||typeof s.preview_id!="string"||!$(s.baseline)||!N(s.baseline.objective_value)||s.hardware!=null&&(!$(s.hardware)||!N(s.hardware.objective_value))?null:s}function Dl(s){let e=Ks(s);if(e)return{turnId:e.baseline.source.turn_id,toolCallId:e.baseline.source.tool_call_id};let t=Pi(s);return t?{turnId:t.source.turn_id,toolCallId:t.source.tool_call_id,point:t.baseline.point}:null}function Bl(s,e=8){let t=s.hardware;if(!t)return{rows:[],more:0,comparable:!1};let i=s.baseline.result,n=Object.keys(i.counts),r=Object.keys(t.counts),o=!!s.comparison&&s.comparison.bit_order==="q0_left"&&t.bit_order==="q0_left"&&s.comparison.shots.baseline===i.shots&&s.comparison.shots.hardware===t.shots&&(!n.length||r.every(u=>u.length===n[0].length)),a=r.reduce((u,d)=>u+(t.counts[d]??0),0)||1,l=u=>t.probabilities?.[u]!==void 0?t.probabilities[u]:(t.counts[u]??0)/a,c=[...new Set([...o?n:[],...r])].sort((u,d)=>l(d)-l(u)||(i.counts[d]??0)-(i.counts[u]??0)||u.localeCompare(d));return{rows:c.slice(0,e).map(u=>({state:u,hardware:l(u),...o?{simulation:(i.counts[u]??0)/i.shots}:{}})),more:Math.max(0,c.length-e),comparable:o}}function ut(s,e){let t=Math.max(0,Math.min(1,s)),i=Math.round(t*e*8),n=Math.floor(i/8),r=i%8;return"\u2588".repeat(n)+(r?"\u258F\u258E\u258D\u258C\u258B\u258A\u2589"[r-1]:"")}var Us=s=>`${(s*100).toFixed(1)}%`;import{createCipheriv as xf,createHash as vf,createPublicKey as kf,diffieHellman as Sf,generateKeyPairSync as Cf,randomBytes as $f}from"node:crypto";var Hs=s=>Buffer.from(s).toString("base64url");function Af(s,e,t=256,i=Buffer.alloc(0),n=Buffer.alloc(0)){let r=c=>{let h=Buffer.alloc(4);return h.writeUInt32BE(c),h},o=c=>Buffer.concat([r(c.length),c]),a=o(Buffer.from(e,"ascii")),l=Buffer.concat([a,o(i),o(n),r(t)]);return vf("sha256").update(Buffer.concat([r(1),s,l])).digest().subarray(0,t/8)}function Nl(s,e,t=new Date){let i=(s.keys??[]).find(b=>b.use==="enc"&&b.alg==="ECDH-ES"&&b.kty==="EC"&&b.crv==="P-256");if(!i?.kid||!i.x||!i.y)throw new Error("the platform gave no key to encrypt with");let n=kf({key:{kty:"EC",crv:"P-256",x:i.x,y:i.y},format:"jwk"}),r=Cf("ec",{namedCurve:"P-256"}),o=r.publicKey.export({format:"jwk"}),a={alg:"ECDH-ES",enc:"A256GCM",kid:i.kid,epk:{kty:"EC",crv:"P-256",x:o.x,y:o.y}},l=Hs(Buffer.from(JSON.stringify(a),"utf8")),c=Sf({privateKey:r.privateKey,publicKey:n}),h=Af(c,"A256GCM"),u=$f(12),d=xf("aes-256-gcm",h,u);d.setAAD(Buffer.from(l,"ascii"));let p=Buffer.from(JSON.stringify({v:1,provider:e.provider,tenant:e.tenantId,user:e.userId,iat:Math.floor(t.getTime()/1e3),secret:e.secret}),"utf8"),f=Buffer.concat([d.update(p),d.final()]),g=d.getAuthTag();return p.fill(0),h.fill(0),c.fill(0),`${l}..${Hs(u)}.${Hs(f)}.${Hs(g)}`}var Lf=10*6e4,Ei=class extends Error{},Of="https://qupai.quspect.com";function Wl(s){return qf(s,Of)?"qupai login":`qupai login -server ${s.replace(/\/+$/,"")}`}function Gs(s){try{let e=new URL(s.trim()),t=e.port||{"http:":"80","https:":"443"}[e.protocol]||"";return`${e.protocol}//${e.hostname.toLowerCase()}:${t}${e.pathname.replace(/\/+$/,"")}`}catch{return s.trim().replace(/\/+$/,"")}}function qf(s,e){return Gs(s)===Gs(e)}var D=class extends Error{status;type;detail;constructor(e,t,i,n){super(n),this.status=e,this.type=t,this.detail=i}};function Df(s,e,t,i,n,r){let o=r.trim().replace(/\.$/,"")||Bf(i),a=n.replace(/^urn:qupai:problem:/,"");return i===401?`${s} did not accept your sign-in (${o}): the key was revoked or has ended; run ${Wl(s)}`:a==="lab-role-required"?`no access: ${o}. Your role on that lab is not enough: ask for access on the lab's page in the app (QuPai staff decide who uses a lab)`:a==="sign-in-required"?`no access with a personal API key: ${o}. This needs your own sign-in in the app`:a==="partner-sign-in-required"?`no access: ${o}. Your account signs in through your partner's site: sign in there first, then run ${Wl(s)}`:a==="account-deleting"?`no access: ${o}. Your account is being deleted: restore it in the app to use it again`:i===403?`no access: ${o}. Ask your organization's admin in the app for the permission or app it needs`:a==="insufficient-credits"||i===402?`not enough credits: ${o}. Top up in the app, or ask your organization's admin`:`${e} ${t}: ${i} ${o}`}function Bf(s){return{400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",409:"Conflict",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable"}[s]??`status ${s}`}var dt=class extends Error{},Qs=class{signIn;fetchFn;retryMs;constructor(e){this.signIn=e.signIn,this.fetchFn=e.fetch??fetch.bind(globalThis),this.retryMs=e.retryMs??500}get server(){return this.signIn.handoff.server}async send(e,t,i,n,r){for(let o=0;;o++){let a=this.signIn.token(),l;try{l=await this.fetchFn(this.server+t,{method:e,headers:{Authorization:`Bearer ${a}`,...i===void 0||i instanceof FormData?{}:{"Content-Type":"application/json"},...n},body:i===void 0?void 0:i instanceof FormData?i:JSON.stringify(i),signal:r})}catch(c){throw r?.aborted?c:new dt(`${this.server} does not answer (${c instanceof Error?c.cause instanceof Error?c.cause.message:c.message:String(c)})`)}if(l.status===401&&o===0){let c=await l.text(),h=!1;try{h=await this.signIn.renew(a)}catch(u){throw new D(401,"","",u instanceof Error?u.message:String(u))}if(h)continue;return new Response(c,{status:401,headers:l.headers})}return l}}async call(e,t,i){return(await this.answer(e,t,i)).body}async answer(e,t,i,n={}){let r=await this.send(e,t,i,{Accept:"application/json",...n}),o=await r.text();if(!r.ok)throw this.refusal(e,t,r.status,o);return{status:r.status,body:o?JSON.parse(o):void 0}}refusal(e,t,i,n){let r="",o="";try{let a=JSON.parse(n);r=a.type??"",o=a.detail||a.title||""}catch{o=n.trim().slice(0,300)}return new D(i,r,o,Df(this.server,e,t,i,r,o))}me=()=>this.call("GET","/v1/me");products=()=>this.call("GET","/v1/products");myAgents=async()=>{try{let e=await this.call("GET","/v1/agents");return{items:e.items??[],given:e.given===!0}}catch(e){if(e instanceof D&&(e.status===404||e.status===403))return{items:[],given:!1};throw e}};labs=async()=>{try{return(await this.call("GET","/v1/labs")).items??[]}catch(e){if(e instanceof D&&e.status===404)return[];throw e}};threads=async(e=30)=>(await this.call("GET",`/v1/threads?limit=${e}`)).items??[];thread=async e=>(await this.call("GET",`/v1/threads/${encodeURIComponent(e)}`)).thread;threadTurns=(e,t=20)=>this.call("GET",`/v1/threads/${encodeURIComponent(e)}/turns?limit=${t}`);createThread=(e,t)=>this.call("POST","/v1/threads",{product_id:e,agent_id:t});submitTurn=(e,t)=>this.call("POST",`/v1/threads/${encodeURIComponent(e)}/turns`,{input:{text:t}});turn=e=>this.call("GET",`/v1/turns/${encodeURIComponent(e)}`);approvals=async e=>(await this.call("GET",`/v1/turns/${encodeURIComponent(e)}/approvals`)).items??[];answerApproval=(e,t)=>this.call("POST",`/v1/turns/${encodeURIComponent(e)}/approval`,t);cancelTurn=e=>this.call("POST",`/v1/turns/${encodeURIComponent(e)}/cancel`);settings=async()=>(await this.call("GET","/v1/settings")).values??{};credential=e=>this.call("GET",`/v1/external-credentials/${encodeURIComponent(e)}`);saveCredential=async(e,t,i)=>{let n=i.trim();if(!n)throw new Error("no key to save");let r=`/v1/external-credentials/${encodeURIComponent(e)}`,o=async()=>{let a=await this.call("GET","/v1/credential-encryption-key"),l=Nl(a,{provider:e,tenantId:t.tenantId,userId:t.userId,secret:n});return this.call("PUT",r,{secret_jwe:l})};try{return await o().catch(a=>{if(a instanceof D&&a.type==="urn:qupai:problem:stale-encryption-key")return o();throw a})}catch(a){throw a instanceof D&&a.status===400&&a.detail.includes("does not match this request")?new Ei("this computer's clock is more than five minutes off: set it right, then save the key again"):a}};subsystemToken=e=>this.call("POST","/v1/subsystem-tokens",{audience:e});previewToolAction=async(e,t,i={})=>{let n=encodeURIComponent(e),r=await this.answer("POST",`/v1/threads/${n}/tool-actions/preview`,t);if(r.status!==202||!r.body||!("preview_job"in r.body))return Ll(r.body);let o=_r(r.body.preview_job);if(!o)throw new Error("the server returned an incomplete hardware preview");i.onCompiling?.();let a=i.wait??((h,u)=>Uf(h,u)),l=i.now??Date.now,c=l();for(;o.state==="compiling";){if(l()-c>Lf)throw new je("The sandbox is still compiling this run after 10 minutes: close this and try again later","sandbox_compile_timeout");if(await a(i.pollMs??1500,i.signal),o=_r(await this.call("GET",`/v1/threads/${n}/tool-actions/preview-jobs/${encodeURIComponent(o.id)}`)),!o)throw new Error("the server returned an incomplete hardware preview")}return Ol(o)};submitToolAction=(e,t)=>this.call("POST",`/v1/threads/${encodeURIComponent(e)}/tool-actions`,t);turnJobs=async e=>(await this.call("GET",`/v1/turns/${encodeURIComponent(e)}/jobs`)).items??[];cancelJob=e=>this.call("POST",`/v1/jobs/${encodeURIComponent(e)}/cancel`);uploadFile=async e=>{let t=zs(e);try{return await this.postFile("/v1/files",e)}catch(i){throw i instanceof D&&i.status===413?new D(413,i.type,i.detail,`${t} is larger than the platform takes for an attachment`):i}};createThreadIn=(e,t,i,n)=>this.call("POST","/v1/threads",{product_id:e,agent_id:t,title:[...i].slice(0,200).join(""),scope:n});sendMessage=(e,t,i)=>this.call("POST",`/v1/threads/${encodeURIComponent(e)}/messages`,{id:Ff(),input:{text:t,...i.length?{file_ids:i}:{}},delivery:"queue"});withdrawMessage=(e,t)=>this.call("DELETE",`/v1/threads/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}`);deleteThread=e=>this.call("DELETE",`/v1/threads/${encodeURIComponent(e)}`);threadFiles=e=>this.call("GET",`/v1/threads/${encodeURIComponent(e)}/sandbox/files`);notifications=(e=50)=>this.call("GET",`/v1/me/notifications?limit=${e}`);readNotifications=async e=>(await this.call("POST","/v1/me/notifications/read",e?.length?{ids:e}:{})).unread;lab=e=>this.call("GET",`/v1/labs/${encodeURIComponent(e)}`);labMachines=async e=>(await this.call("GET",`/v1/labs/${encodeURIComponent(e)}/machines`)).machines??[];requestLabAccess=(e,t)=>this.call("POST",`/v1/labs/${encodeURIComponent(e)}/access-requests`,t?{note:t}:{});withdrawLabAccess=(e,t)=>this.call("DELETE",`/v1/labs/${encodeURIComponent(e)}/access-requests/${encodeURIComponent(t)}`);places=e=>this.call("GET",`/v1/scopes/${encodeURIComponent(e)}`);placeFiles=e=>this.call("GET",`/v1/scopes/${encodeURIComponent(e.app)}/${encodeURIComponent(e.key)}/files`);artifacts=async()=>(await this.call("GET","/v1/artifacts")).items??[];artifact=e=>this.call("GET",`/v1/artifacts/${encodeURIComponent(e)}`);billing=()=>this.call("GET","/v1/billing/account");usage=(e,t)=>this.call("GET",`/v1/billing/usage?${new URLSearchParams({days:String(e),tz:t})}`);async postFile(e,t){let i=zs(t),n=new FormData;return n.append("file",await _f(t,{type:Kf(i)}),i),(await this.answer("POST",e,n)).body}models=async()=>(await this.call("GET","/v1/models")).items??[];customization=(e,t)=>this.call("GET",Kl(e,t));putCustomization=(e,t,i)=>this.call("PUT",Kl(e,t),i);createMyAgent=(e,t,i)=>this.call("POST","/v1/agents",{product_id:e,agent_id:t,name:i});renameMyAgent=(e,t)=>this.call("PATCH",`/v1/agents/${encodeURIComponent(e)}`,{name:t});deleteMyAgent=e=>this.call("DELETE",`/v1/agents/${encodeURIComponent(e)}`);knowledgeBases=async()=>(await this.call("GET","/v1/knowledge-bases")).items??[];createKnowledgeBase=(e,t="")=>this.call("POST","/v1/knowledge-bases",{name:e,description:t});deleteKnowledgeBase=e=>this.call("DELETE",Vs(e));knowledgeDocuments=async e=>(await this.call("GET",`${Vs(e)}/documents`)).items??[];addKnowledgeDocument=async(e,t)=>{try{return await this.postFile(`${Vs(e)}/documents`,t)}catch(i){throw i instanceof D&&i.status===413?new D(413,i.type,i.detail,`${zs(t)} is larger than the platform takes for a knowledge base`):i}};searchKnowledgeBase=async(e,t,i=5)=>(await this.call("POST",`${Vs(e)}/search`,{query:t,top_k:i})).items??[];connections=async()=>(await this.call("GET","/v1/connections")).items??[];connection=e=>this.call("GET",Mi(e));testConnection=e=>this.call("POST",`${Mi(e)}/test`);authorizeConnection=async(e,t)=>(await this.call("POST",`${Mi(e)}/authorize`,{return_to:t})).authorization_url;setConnectionEnabled=(e,t)=>this.call("PATCH",Mi(e),{enabled:t});deleteConnection=e=>this.call("DELETE",Mi(e));schedules=async()=>(await this.call("GET","/v1/schedules")).items??[];setScheduleEnabled=(e,t)=>this.call("PATCH",Pr(e),{enabled:t});runScheduleNow=e=>this.call("POST",`${Pr(e)}/run`);deleteSchedule=e=>this.call("DELETE",Pr(e));goals=async()=>(await this.call("GET","/v1/goals")).items??[];goal=e=>this.call("GET",Mr(e));actOnGoal=(e,t)=>this.call("POST",`${Mr(e)}/${encodeURIComponent(t)}`);steerGoal=(e,t)=>this.call("POST",`${Mr(e)}/directives`,{text:t});workspaces=async()=>(await this.call("GET","/v1/workspaces")).items??[];workspace=e=>this.call("GET",js(e));openWorkspace=e=>this.call("POST",`${js(e)}/open`);closeWorkspace=e=>this.call("POST",`${js(e)}/close`);deleteWorkspace=e=>this.call("DELETE",js(e));async download(e,t){let i=await this.send("GET",e,void 0,{});if(!i.ok)throw this.refusal("GET",e,i.status,await i.text());let n=Mf(Pf(t),`.${zs(t)}-${Ul(4).toString("hex")}`),r=0;try{let o=i.body?Fl.fromWeb(i.body):Fl.from([]);o.on("data",a=>r+=a.length),await Ef(o,Tf(n,{mode:420})),If(n,t)}catch(o){throw Rf(n,{force:!0}),o}return r}async*follow(e,t,i={}){let n=t,r=this.retryMs,o=`/v1/turns/${encodeURIComponent(e)}/events`;for(;;){if(i.signal?.aborted)return;try{let a=await this.send("GET",`${o}?from=${n}`,void 0,{Accept:"text/event-stream"},i.signal);if(!a.ok||!a.body){let h=await a.text();throw a.status>=500||a.status===429?new dt(`the turn's events: ${a.status}`):this.refusal("GET",o,a.status,h)}let l=new TextDecoder,c="";for await(let h of a.body){c+=l.decode(h,{stream:!0});let[u,d]=zf(c);c=d;for(let p of u)if(!(p.seq<=n)&&(n=p.seq,r=this.retryMs,yield p,Nf.has(p.event)))return}i.onRetry?.(new dt("the turn's stream ended early"))}catch(a){if(i.signal?.aborted)return;if(a instanceof D)throw a;i.onRetry?.(a instanceof Error?a:new Error(String(a)))}await Hf(r,i.signal),r=Math.min(r*2,1e4)}}},Nf=new Set(["complete","aborted","error"]),Hl=(s,e)=>`/v1/threads/${encodeURIComponent(s)}/sandbox/file?${new URLSearchParams({path:e})}`,zl=(s,e)=>`/v1/scopes/${encodeURIComponent(s.app)}/${encodeURIComponent(s.key)}/file?${new URLSearchParams({path:e})}`,Vl=(s,e,t)=>`/v1/artifacts/${encodeURIComponent(s)}/versions/${e}/files/${t.split("/").map(encodeURIComponent).join("/")}`,Kl=(s,e)=>`/v1/products/${encodeURIComponent(s)}/agents/${encodeURIComponent(e)}/customization`,Vs=s=>`/v1/knowledge-bases/${encodeURIComponent(s)}`,Mi=s=>`/v1/connections/${encodeURIComponent(s)}`,Pr=s=>`/v1/schedules/${encodeURIComponent(s)}`,Mr=s=>`/v1/goals/${encodeURIComponent(s)}`,js=s=>`/v1/workspaces/${encodeURIComponent(s)}`;function Ff(s=Date.now()){let e=Ul(16);for(let i=0;i<6;i++)e[i]=Math.floor(s/2**(40-8*i))&255;e[6]=e[6]&15|112,e[8]=e[8]&63|128;let t=e.toString("hex");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Wf={".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".tsv":"text/tab-separated-values",".json":"application/json",".yaml":"application/yaml",".yml":"application/yaml",".xml":"application/xml",".html":"text/html",".htm":"text/html",".py":"text/x-python",".ipynb":"application/x-ipynb+json",".tex":"application/x-tex",".bib":"application/x-bibtex",".qasm":"text/plain",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".zip":"application/zip",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function Kf(s){let e=s.lastIndexOf(".");return e>0&&Wf[s.slice(e).toLowerCase()]||"application/octet-stream"}function Uf(s,e){return new Promise((t,i)=>{if(e?.aborted)return i(e.reason);let n=setTimeout(()=>{e?.removeEventListener("abort",r),t()},s),r=()=>{clearTimeout(n),i(e.reason)};e?.addEventListener("abort",r,{once:!0})})}function Hf(s,e){return new Promise(t=>{let i=setTimeout(t,s);e?.addEventListener("abort",()=>{clearTimeout(i),t()})})}function zf(s){let e=[],t=s.split(/\r?\n\r?\n/),i=t.pop()??"";for(let n of t){let r="";for(let o of n.split(/\r?\n/))o.startsWith("data:")&&(r+=o.slice(5).trimStart());if(r)try{let o=JSON.parse(r);typeof o.seq=="number"&&typeof o.event=="string"&&e.push({...o,data:o.data??{}})}catch{}}return[e,i]}function K(s,e=""){return s&&(s.en||s.zh||Object.values(s).find(Boolean))||e}var le=(s,e)=>`${s}/${e}`,Xf=["general","specialist","lab"],Jf=s=>s.kind&&Xf.includes(s.kind)?s.kind:"general";function Zf(s){let e=s.default,t="",i="";if(typeof e=="string")[t="",i=""]=e.split("/");else if(e&&typeof e=="object"){let n=e;t=typeof n.product_id=="string"?n.product_id:"",i=typeof n.agent_id=="string"?n.agent_id:""}if(t)return i||(i=s.items.find(n=>n.product_id===t)?.agents?.[0]?.id??""),i?{product_id:t,agent_id:i}:void 0}function em(s,e){return s.map(t=>{let i=e.flatMap(n=>{if(n.product_id!==t.product_id)return[];let r=t.agents?.find(a=>a.id===n.base_agent_id);return r?[{...r,id:n.id,name:{en:n.name},description:n.description?{en:n.description}:null,mine:{base:r.id}}]:[]});return i.length?{...t,agents:[...t.agents??[],...i]}:t})}function Xs(s){return s.filter(e=>e.available).flatMap(e=>(e.agents??[]).map(t=>({product:e,agent:t})))}function Gl(s){let e=s.agent.mine?.base??s.agent.id,t=s.product.agents?.find(n=>n.id===e)??s.agent;if(Jf(t)==="general")return!0;let i=s.agent.tools??[];return!(i.length>0&&i.every(n=>n.available===!1))}function jl(s,e){if(e)return s.find(t=>t.product.product_id===e.product_id&&t.agent.mine?.base===e.agent_id)}var tm=s=>{let[e,t]=s?.split("/")??[];return e&&t?{product_id:e,agent_id:t}:null};function im(s,e,t,i){let n=Xs(s).filter(Gl),r=c=>c?n.find(h=>le(h.product.product_id,h.agent.id)===c):void 0,o=()=>r(e)??r(t?le(t.product_id,t.agent_id):null)??n[0];if(!i)return o();let a=n.filter(c=>c.agent.mine),l=r(e);return(l?.agent.mine?l:void 0)??jl(a,tm(e))??jl(a,t)??a[0]??o()}function sm(s,e,t){return!!e&&s.product.product_id===e.product_id&&(s.agent.mine?.base??s.agent.id)===e.agent_id&&(!t||!!s.agent.mine)}function Er(s,e,t){let i=e.given||s.given===!0;return{products:em(s.items??[],e.items),labs:t,fallback:Zf(s),given:i}}function Ql(s,e){return{productId:e.product.product_id,agentId:e.agent.id,name:K(e.agent.name,e.agent.id),from:"product",isDefault:sm(e,s.fallback,s.given),productName:K(e.product.name,e.product.product_id)}}function Yl(s){if(s.agent)return{productId:s.agent.product_id,agentId:s.agent.agent_id,name:K(s.agent.name,K(s.name)),from:"lab",lab:s.id,labName:K(s.name,s.id),isDefault:!1}}function pt(s){let t=Xs(s.products).filter(n=>Gl(n)&&(!s.given||!!n.agent.mine)).map(n=>Ql(s,n));return[...[...t.filter(n=>n.isDefault),...t.filter(n=>!n.isDefault)],...Li(s)]}function Li(s){return s.labs.flatMap(e=>e.status==="paused"?[]:Yl(e)??[])}function Lr(s,e){if(e&&"lab"in e){let n=s.labs.find(o=>o.id===e.lab&&o.status!=="paused"),r=n&&Yl(n);if(r)return r}let t=e&&"product"in e?le(e.product,e.agent):null,i=im(s.products,t,s.fallback,s.given);return i?Ql(s,i):void 0}function Xl(s){return s.from==="lab"&&s.lab?{lab:s.lab}:{product:s.productId,agent:s.agentId}}var Ys=class s{file;constructor(e){this.file=e}static key(e,t){return`${Gs(e)} ${t}`}read(){if(!this.file)return{};try{let e=JSON.parse(jf(this.file,"utf8"));return e.picks&&typeof e.picks=="object"?e.picks:{}}catch{return{}}}get(e,t){let i=this.read()[s.key(e,t)];return i&&"lab"in i&&typeof i.lab=="string"?{lab:i.lab}:i&&"product"in i&&typeof i.product=="string"&&typeof i.agent=="string"?{product:i.product,agent:i.agent}:null}set(e,t,i){if(!this.file)return!1;try{let n={...this.read(),[s.key(e,t)]:i};Vf(Yf(this.file),{recursive:!0,mode:448});let r=`${this.file}.${process.pid}.tmp`;return Qf(r,`${JSON.stringify({picks:n},null,2)}
|
|
109
|
-
`,{mode:384}),
|
|
110
|
-
`):""}function
|
|
111
|
-
`))return null;let n=Nr(i);if(!n.length)return null;let r=[];for(let o of n){if(!/^(\/|~|file:\/\/|\.{1,2}\/|[A-Za-z]:[\\/])/.test(o)&&!o.includes("/"))return null;let a=Gt(o,e,t);try{if(!am(a).isFile())return null}catch{return null}r.push(a)}return r}function nc(s,e){let t=lm(e||"artifact"),i=s.replace(/[\x00-\x1f\x7f/\\:*?"<>|]+/g," ").replace(/\s+/g," ").trim().replace(/^\.+/,"");if(!i)return t;let n=ec(t);return n&&ec(i).toLowerCase()!==n.toLowerCase()?`${i}${n}`:i}function en(s){return s.qupai_staff?"staff":s.my_role?String(s.my_role):s.access_request==="pending"?"none (asked)":s.access_request==="declined"?"none (declined)":"none"}var tn=s=>!!s.my_role||!!s.qupai_staff;function Wr(s){return s==="real"?"lab PC":s==="api"?"API":s}function dm(s){return s.occupancy==="held"?"busy":s.occupancy==="watch"?"watch only":s.health||"unknown"}function pm(s){let e=s.holder;return e?`${e.kind==="external"?"outside the platform":e.kind}: ${e.label}${e.by?` (${e.by})`:""}${e.other_org?", another organization":""}, since ${X(e.since)}`:""}function rc(s,e,t){let i=[`Lab ${K(s.name,s.id)} (${s.id})`,...s.provider&&s.provider.name?[`Run by ${s.provider.name}`]:[],...s.field?[`Field ${s.field}`]:[],`Your role ${en(s)}`,`Status ${s.status}`,`Connected by ${Wr(s.connection)}`,`Access ${s.access==="open"?"open to every member":"the people QuPai staff let in"}`,`Its agent ${s.agent?`${K(s.agent.name,s.id)} (Enter in /lab talks with it)`:"none offered to you"}`,`In the app ${Kr(t,s.id)}`,""];if(typeof e=="string")return[...i,`Machines: ${e}`];if(!e.length&&s.connection==="api")return[...i,`Machines: an API lab's devices come from the device information service (qupai device list${s.provider_ref?` -provider ${s.provider_ref}`:""} shows them).`];if(!e.length)return[...i,"The lab reports no machines."];i.push("Machines");let n=o=>e.some(a=>a.id===o),r=(o,a)=>{let l=[`${a}${o.name||o.id}`,[o.kind,o.mode].filter(Boolean).join(", "),dm(o)];o.queue&&l.push(`queue ${o.queue.count}`);let c=[l.filter(Boolean).join(" \xB7 ")],h=pm(o);h&&c.push(`${a} held by ${h}`);for(let u of o.holds??[])(!o.holder||u.by!==o.holder.label)&&c.push(`${a} holds ${u.what} for ${u.by}`);return o.note&&c.push(`${a} ${o.note}`),c};for(let o of e)if(!(o.twin_of&&n(o.twin_of.machine))){i.push(...r(o," "));for(let a of e)a.twin_of&&a.twin_of.machine===o.id&&i.push(...r(a," twin "))}return i}function Kr(s,e){return`${s.replace(/\/+$/,"")}/lab/machines?${new URLSearchParams({lab:e})}`}var fm=/^0{8}-0{4}-0{4}-0{4}-0{12}$/;function oc(s){return s.thread_id&&!fm.test(s.thread_id)?{thread:s.thread_id}:s.place?.app==="lab"&&s.place.key?{lab:s.place.key}:null}function Di(s){return{answer_ready:"answer ready",answer_failed:"answer failed",approval_needed:"approval needed",job_finished:"job finished",woken:"woken by a job",goal_waiting:"goal waiting",goal_stalled:"goal stalled",goal_ended:"goal ended",lab_access_requested:"lab access asked",lab_access_granted:"lab access given",lab_access_declined:"lab access declined",lab_access_removed:"lab access removed"}[s]??s.replaceAll("_"," ")}function xe(s,e){let t=s.split(/\s+/).filter(Boolean).join(" "),i=[...t];return i.length<=e?t:`${i.slice(0,e-1).join("")}\u2026`}var ac={brand:Ue(22,131,255),needs:Ue(217,154,0),stopped:Ue(138,144,153),failed:Ue(201,52,63),ok:Ue(46,157,91),muted:Ue(138,144,153)};function mm(s=process.env){return typeof s.NO_COLOR=="string"&&s.NO_COLOR!==""}function lc(s={}){let e=s.color??!mm(),t=s.mode??zn(),i=(n,r)=>n&&Rt(n,r,t);return{color:e,tone:(n,r)=>e&&n?Rt(n,{fg:ac[r]},t):n,bold:n=>i(n,{bold:!0}),dim:n=>e?i(n,{dim:!0}):n,italic:n=>i(n,{italic:!0}),inverse:n=>i(n,{inverse:!0}),wordmark:()=>e?Rt("QuPai",{fg:ac.brand,bold:!0},t):Rt("QuPai",{bold:!0},t)}}function cc(s){return{heading:e=>s.bold(s.tone(e,"brand")),link:e=>s.tone(e,"brand"),linkUrl:e=>s.dim(e),code:e=>s.tone(e,"brand"),codeBlock:e=>e,codeBlockBorder:e=>s.dim(e),quote:e=>s.italic(e),quoteBorder:e=>s.dim(e),hr:e=>s.dim(e),listBullet:e=>s.tone(e,"brand"),bold:e=>s.bold(e),italic:e=>s.italic(e),strikethrough:e=>e,underline:e=>e}}function sn(s){return{selectedPrefix:e=>s.tone(e,"brand"),selectedText:e=>s.bold(s.tone(e,"brand")),description:e=>s.dim(e),scrollInfo:e=>s.dim(e),noMatch:e=>s.dim(e)}}function nn(s){return{borderColor:e=>s.tone(e,"brand"),selectList:sn(s)}}function hc(s){return{fallbackColor:e=>s.dim(e)}}var uc="iVBORw0KGgoAAAANSUhEUgAAARgAAAEYCAYAAACHjumMAAAQ1UlEQVR42u2d3ZGjShKF2wSe5lkmYAImyIQyAROIGAMwARNkAiZgAiZgQm/cWHqvordnhCSqKk/m93De9s6qUekj8+RPffz6/fmBEEI5xENACAEYhBCAQQghAIMQAjAIIQCDEEIABiEEYBBCAAYhhAAMQgjAIIQADEIIARiEEIBBCAEYhBACMAg5UvPr92f3TS2AQQgdVbuDY/j1+3P69ftz/vX7c/v1+/PzSS37f/uPbvu/94+u+7/fABiE/OpyB5LbDoTPwtr2/++0fx4Ag5BoavNP5DC+EZGU0LzDpgEwCNmOTtKe4qxGYfIoshnOBg0HA6HXdRUGShHQcEgQej5KuTkCyp+07n4RgEEoM1T6SoasBY0ABqHzDdrIUPmp/N0AGITeg0qU9KcYZDhYKLq63ajdgMj5kOGAocgp0Ao08kKGw4aiteQTrbyvCcAg9K8Shu3pugIYFD0NGohWsjbkNQAGRexbGQGLjR4ZDiTyBJaJH31xXQAM8l5mnvmh24xiOKAIsKB3vRgAgwALyqYEYJAHjwWwiPXFcHAR5i3KliZxgBFgQWeoBTCIBjmUSz2AQQot/QwgOvJhONTISmWIWSFtzQAGURlCRY1eDjmq6bPww/QlAIOq64rPAmAQIh1Cbw8+cvAR6RA6Sx2AQaRDCMAg+aiF6z/o5gUw6HT1dOFi8gIYhImLAAwiakEABsW9Z4ioBTEqgE4XpWcEYFAWr4XBxP8+g3kH7bCX5Ltdlx+qat2d+v2/mR2llgOAQXgtrw3xzXcQaTNBO+2lfdXnmwAMeqevJYrXsu67TdKjO38yPmvFq247AINe7cb1HrXc9ujsYuzZK+3JYScvohv3W5RyJTU9zY8CMOipN+fqECpjJg+lVEuA1Whm9ASYZn/zDPsbdt61fiuZ3eu70w9EYpSfN7FI5cjZtwiZqzpgchhf36sDF1IiN0bu/LfbBoHM6WpUAVP6CovtzvBrg6VEm4MUaAjyorgY+r6Wv31WdokcC7HT3ygtrpFoRba6Z7bBzjpgRsNuee/kLanekTuR1ppIaVslwCj5AItwZKPa2/KVBjWY8f97SZi8k9oiYBrhN+okVJ0aRcGSAIq5KGZSAoyHi84Xwz8ExSrRAlgeKlksT1sDTO9wQM5SKN+KNc7N9Cs99eIwmR5ZAUzjeNZlM2BGJsBCmlQjPbICmCiLi0qDphFKO1fAIvcb6lQAE22/yFSgiU+lBI15qxmlrkc/G81C/tIBha7cDbCc/p2bGG60BpgxMGDud5Fcgvgt1sxvT8vXq95BbRUwbKQ/z6OZ8KBCq+pyb6uA4d7in2c7mifN3Nl4KtgCADeASUqAASh/TiWuB0PjFQMXWep9ATA6kGlE54nwWXw2240Axg9cWsHO5xmfxXUV6QJgfMwzNWJmLmVn/4C5vfLZAIwOXKyauSPpUIhGu04RMJSpj812WFxlQXt/nFGB+dXPBmCMX/uwezEbJi76i26WStN08grc6Wu07X+hp8WklsyR6ocqYIbglaJOqO1/4IccsgcmKQOmowxtHrxELXErSOu7ny/qNi7K0Jkaq5CrLCCpAybaPNKjMvREhQgZKZSsZ3w+ln2XLUM3AmXoGxUi/JezGiejb0Wnx4VuXG53zBS9WAHMJTBcrKy2xMjV1GQ5erF0bcniFC6DQAMdrf662ixHL5YAMwZroLMAl6M7Z1CsNZnJI2DaQHCx0J1LSkR69Kdz8eERMJ7K1cm4oT0dSIla0qaQ6VHnGTAjcMmu/kDj43iXQvX8kMNUj+YcnzXy1Qsl/Yxk4PN1B57/QjoVdnr64h0wqtWkR3NFyYDf8ujwpAMhN8OONnTJVEn8iACYBFyKd+VOJ8MKac0ebTn9Novb0TfgUmS9wqsdxHT8+iqGZPXZInUnRoJLOuC3bAWiI2Q7wl9yf+YoOWZJuIzGzdx0ctcnBrDu5HQXETCWd/Vavq/oyI99rFT+RvYWS00lPnf0i6S8pEWPlliVuPKElEnnpbuV+q4iLtLxBpf5wWFpC5b/SZk0bINiEWf0y6TU4TIVMHOpMvkqfCwlP3vUdYAR4FIb0BNgMBm9tADGhhdjGS5JJPqjMc9W9FK8GzvyUmOvcBkNmuMsEK8fvaw1TPjo9754g8tXqdxiNzSl7LrRSxXIR989qgKXZ43Ti9HB0YlSdpXopdr9VpEnSJ+FS601l9sbxpzFq3nxZcpaA2tNqEeeIn3GXVeES40+mJJ/F127x1R177LSQ885aZ2cwsV6NEO/TN7opXqrQPRp0keHvHECF8vRDPdf5znjqwW/K/pMxiO4LE7TB2vRDHNM/565Vblq5AEwHXA5LZpZMX9d+oxmosKo/QFjcLj8dIsA5m/9SunmJTVSB8w73siUGV6KP6yroea8qMOSU4FqKIB5Qj1wOR3aMxUm6bTf3M0P6l/M8mSO3xjcRtc6ADcT2fWv65kt/m1RyP8ILom3tFkDeMLYPRQFXwBMndz1yAgAcPk5ZboZgczstIx9lrF7tfo3eukd2F7sB6jVpZuce1019g4r6uY9wvPyRfVCXbq9aCq6AZnTK3fun4fn+Q2LvS6TeKRoYczAw2LxMzp2JXqGvOaz05MwAi72dvN4bsgbo6TZHgfFLPa6LA6fM5Cp1/Mi87JiUhXf4J1S9gZkntYa6TyxxCe/X+B5StjCas7Ncpn25J4XOaBGgUutC8giDO5Z6ZdJAmcw3PgEOzbyKdpVHROQyToOIFkkYM6DRjpv5m9ymBrJFgl4q56vIShcLK1+SI5So015EZfng97T6xK6wpScpOfSqbbntyjlaCaya0NmDDhW4h4wl0oVI+Bic7ygFmQ6omF/gKlxoLlEDMicPUjrJhrG1KViBGRsrWHYPN2ugKnLpWGRemWuAufQVf8UYwDOdqACmarp7LvVM3fRcISNdswYAZlSkFlocfAHGExdIGPhOxyJhv0BBlOX788CZBIVI3+ASXTqAhkD/Uvv+C7uo2Fa0eNupQMy70cQ744CuJ+4p6ciYG8CkDkNMjdSbX+AmZz2T9CMV7cZ71mjdaB/yh9gEs10QMaAx9bi4/kDDL4LkLECmZ6KkS/AMMQYS5fK+2SOrEmYgYsfwNDvwtIqa9//My+9sEUCfJefdeMHHnbG7F7tCZFW6EiYtxhzRrxg3oPDozMaugLJnBHXjShorAiZIy+cjjRbDzADJWl0UlNbiUa8xO0SOoDpKh0ifshUEt8pXydm1uwDptZNjJSkKV+fcedVz/dkGzBcloYsV5ZoXxAGzNVYatTsDVXMItlSb7yyhAwCplb42x6sXvDmwvTlHixhwMzGUqOOngbzpu8quOIBwAQJedcHh3cjPJYYJ/gUmL4GMAEPSfdiYxeQwY9xdX+0d8Asxt48HTk4fgwtDj4AMxg06FZycEk/ZsP0BTAWUqN0IvCYuqY/hk5wo4CpkRrNGd6CGH0MRTLLZgwwg0Fjt8Hoo3TNgnh9wNRqqDsSaUy0kJMq0emrDZjZsAn3Lvw4WKRKFAAqAqY3PAV7RvrG24tUCT+mEmBqlRLXwgY0kCFVwo+pAJib0Hj9u7uAuWqWBjzOQUHAdIK9CT15OAuq6I/RAMxqsCxd4g0IZOprMJAqDQDG3xc8GzELgUx9rQYg0wGYPCGq+hfaUraU19UAYFaujvVjss0n/x09kJHXbAAyE4DxUSbMEY5OQIayNaVrO4BZnUQv937MAmSkNRkATKjVDh63jOU00866K3uhGa9a2dpCFHMDMJrLf1Yhw5CO37hRTJhUydugWamJ5h7IEMWQKpUHzKVyGVDxTbgxsxI2ipkAjM4XV6NbchGMvpCdKMZ9A56nMmCNobKz1wJwR3asvhj3DXhevrCaoWZ7sqnNjt9YfTGuXyxevqyrs8M60ysjl+IqRuAygJkDmbt/Usow5k+FSes7s9ggKg+Y2tGLpdWEY4ZSJpDxt2UxjNHvwSyzFlpOHDxK1hi+5wCG2/TKQRfzN59J/4nhaxMwM19G1sFIBiXjLKRyafiql/la4/n9kqnFvAMKboZzXUerisuk7n9okU1Erqv12dnrqsNX+Qu5CeX4W8ZnQMrkryfGTdla2XnvxYzELWPlgVK27nJ61ysdlHsH1ELINvNzI2XyVU2y1ERaFDBWDLFG9BBvmcNqUiY/1ST5HijVL2ETf1NumZ8N+2X0m+5cRDG11kVGN8DaAmnmSDQjPZvkIopRJfzsJOffCrz96JnR9mGko5hnzV0rD3x0dKA3npcpfRLF1AGMpW7Hwdlbcyv0FiSa0dl05yKKUW1E8rYBrCn4fPFmyq7cCN3dq9pK7XHFYEnIEM1oNdzJeo+qw2Cz08PdFA7Rb15XNTrZ1Ss/ac2cBv0YG13AUoCZvAHG4qTphheQZdcMaZN9wEjdCKmYHimPCig0fk2kTaYBI1WyVtj7Evry8P3v3Cq8JYfA1SbrgFk8AcbqQ47UPNZWmgHbAi4cbwQAI2P2Kueja8CDv1R81h0eDC/YswEzGH/IEU3JqXL1rgMwvGDPAsxs/CHPQT2C3sBz73i2LL1/FzCbwEOOWlrtDHw/HkFzEwLMqAyYi8hDXoIC5us7WoxEkl5AswoBZlUGTAfJZczfyRDsE/4L1aQjgBnEHrS3cmq7g/PovFBv7M2q2EczCQImqQJm5GFXg8r6Qz9Ke/C/txTib/uPthVJNz8FdVMFzCz6wJMTqLz6tzVGv7vZ+Hejet5XAFOH6o0TqLw6TWs1xbUY1QzCZ930XJ7yPIZSm3uzzxRNJ6UwR+8/6oxXRdbdO6ppVCYHZ70DMPUNx0sFoIwZy8jLwb+pEentWCrAZnJyxgcAY8cH6E8mfrvDZNh/yGvhKO1oqtGLvRTGjBPzSazfRbZNIxpgfnprzjschjv4fNdwp2n/b6zccNk+CcNF9MUw7MC5vPEi6J2BxfzITHTAqB+qV39so5O///YN/sMPL4TZKVQADDK9Q7cL8MOLJACDzJXfG0dGJ4ChDwYZXfh0FZmcRwAGZdiNW6q0fuOZAxiGHWNoqtShSTQDYIoAJvGlhd2t0jipNAEYFk6hO5/F2jAglSYAk3VlJofLl8/yajRDusxEdRbAECbnnyFRWcp0wfin0S7SvUjqBq7q9awJE9jkeZK92XHhCwQsNOgxTZ0LMFSTAMvfBghJm9gH8xZgMHsBS7T1B1SQCgPmypf4VFVoDAKWn6pN+DMYvE8D5oM2crdXdeSoNuHPlFPvBTANb6c/Lq1KwaHypwok/kx+XbwA5svUAzL/+istIKEbuPL6jg9PgIleVfpaTN0ADoxgA7p6BEy0SGYjWgE0jAeUBYzFa0pzpEBXgABoiF7qAMZbR+e257SJFIjSNqVpG4BRN/JWIhUiGsEX4SUaYO4PySJA/x5PBdCISqolIueMymQg9N3uLu3q+PHSR8PUtA/AfD8oY4HDsp50AyCiM9hqi8QHgHnuLueva1jnB9HOdve/m7/d4kdkEscQ7oOmT4tq4YGDixR1DTQbd1OuanJYkXr65DmqGdW/Iw4p8rT8anLSU7N5aZ3gYCKvKZQqbEZPjZ4cRhSh3D0K9Ge53H7IAUTRPJu0/5hXI53krrcfcuhQdN8mFerTui85j1HGUzhkCP1/lNPt1anhDj5fWg6Monzptv8b/f5vhhui5UAhhAAMQgjAIIQQgEEIARiEEIBBCCEAgxACMAghAIMQQgAGIQRgEEIABiGEAAxCCMAghAAMQggBGIQQgEEIARiEEHpN/wF1mouh7lkMKgAAAABJRU5ErkJggg==",dc=[" \u28C0\u28E4\u28E4\u28E4\u2840"," \u2880\u28E4\u28C4\u28C0 \u28E0\u2876\u281F\u281B\u2809\u2819\u28FF\u2847"," \u2808\u28BF\u289F\u28F5\u281F\u28AD\u28C4 \u2880\u285F"," \u28E0\u285F\u2801 \u2819\u28B7\u28C4\u2820\u280B"," \u28FC\u284F\u2818\u28A6\u2840 \u2839\u28F7\u2840","\u28B8\u28FF\u28E6\u28C0\u28E0\u281D\u2836\u28E4\u28C0\u28E0\u28FF\u28F7","\u2808\u2809\u2809\u2801 \u2809\u281B\u281B\u280B"];function J(s,e){let t=x(s);return t>=e?_(s,e,""):s+" ".repeat(e-t)}function M(s,e){let t=[];for(let i of s.split(`
|
|
112
|
-
`))t.push(...i?ge(i,Math.max(1,e)):[""]);return t.map(i=>_(i,e,""))}function mt(s){if(!s)return"no agent";let e=s.from==="lab"?` (lab ${s.labName??s.lab})`:"";return`${s.name}${e}${s.isDefault?" (organization default)":""}`}function
|
|
103
|
+
`),l=!1;for(let c=0;c<e.length;c++){let h=e[c];switch(l&&h.type==="text"&&!h.tokens?.length&&/^[ \t]/.test(h.text)&&(h={...h,text:h.text.replace(/^[ \t]+/,"")}),l=!1,h.type){case"latex":{let u=h,d=!u.pending&&this.options.renderLatex!==!1?Ss(u.text)??u.raw:u.raw;i+=a(d);break}case"escape":i+=a(this.options.preserveBackslashEscapes?h.raw:h.text);break;case"text":h.tokens&&h.tokens.length>0?i+=this.renderInlineTokens(h.tokens,n):i+=a(h.text);break;case"paragraph":i+=this.renderInlineTokens(h.tokens||[],n);break;case"strong":{let u=this.renderInlineTokens(h.tokens||[],n);i+=this.theme.bold(u)+o;break}case"em":{let u=this.renderInlineTokens(h.tokens||[],n);i+=this.theme.italic(u)+o;break}case"codespan":i+=this.theme.code(h.text)+o;break;case"link":{let u=this.renderInlineTokens(h.tokens||[],n),d=this.theme.link(this.theme.underline(u));if(ae().hyperlinks)i+=ds(d,h.href)+o;else{let p=h.href.startsWith("mailto:")?h.href.slice(7):h.href;h.text===h.href||h.text===p?i+=d+o:i+=d+this.theme.linkUrl(` (${h.href})`)+o}break}case"br":i+=`
|
|
104
|
+
`;break;case"del":{let u=this.renderInlineTokens(h.tokens||[],n);i+=this.theme.strikethrough(u)+o;break}case"html":h.raw.startsWith("<!--")?l=c===0||/[ \t]$/.test(e[c-1].raw):i+=a(h.raw);break;default:"text"in h&&typeof h.text=="string"&&(i+=a(h.text))}}for(;o&&i.endsWith(o);)i=i.slice(0,-o.length);return i}getOrderedListMarker(e){let t=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(e.raw);return t?`${t[1]} `:void 0}getUnorderedListMarker(e){let t=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(e.raw);return t?`${t[1]} `:void 0}renderList(e,t,i,n){let r=[],o=" ".repeat(t),a=typeof e.start=="number"?e.start:1;for(let l=0;l<e.items.length;l++){let c=e.items[l],h=l===e.items.length-1,u=e.ordered?this.options.preserveOrderedListMarkers?this.getOrderedListMarker(c)??`${a+l}. `:`${a+l}. `:this.options.preserveOrderedListMarkers?this.getUnorderedListMarker(c)??"- ":"- ",d=c.task?`[${c.checked?"x":" "}] `:"",p=u+d,f=o+this.theme.listBullet(p),m=o+" ".repeat(x(p)),b=Math.max(1,i-x(f)),g=!1;for(let y of c.tokens){if(y.type==="list"){r.push(...this.renderList(y,t+1,i,n)),g=!0;continue}let w=this.renderToken(y,b,void 0,n);for(let k of w)for(let P of ge(k,b)){let v=g?m:f;r.push(v+P),g=!0}}g||r.push(f),e.loose&&!h&&r.push("")}return r}getLongestWordWidth(e,t){let i=e.split(/\s+/).filter(r=>r.length>0),n=0;for(let r of i)n=Math.max(n,x(r));return t===void 0?n:Math.min(n,t)}wrapCellText(e,t,i=""){let n=ge(e,Math.max(1,t));return n.map((r,o)=>{let a=o<n.length-1?"\x1B[22;23;24;25;27;28;29;39m":"";return`${r}${a}${i}`})}renderTable(e,t,i,n){let r=[],o=e.header.length;if(o===0)return r;let a=3*o+1,l=t-a;if(l<o){let v=e.raw?ge(e.raw,t):[];return i&&i!=="space"&&v.push(""),v}let c=30,h=[],u=[];for(let v=0;v<o;v++){let A=this.renderInlineTokens(e.header[v].tokens||[],n);h[v]=x(A),u[v]=Math.max(1,this.getLongestWordWidth(A,c))}for(let v of e.rows)for(let A=0;A<v.length;A++){let E=this.renderInlineTokens(v[A].tokens||[],n);h[A]=Math.max(h[A]||0,x(E)),u[A]=Math.max(u[A]||1,this.getLongestWordWidth(E,c))}let d=u,p=d.reduce((v,A)=>v+A,0);if(p>l){d=new Array(o).fill(1);let v=l-o;if(v>0){let A=u.reduce((L,Q)=>L+Math.max(0,Q-1),0),E=u.map(L=>{let Q=Math.max(0,L-1);return A>0?Math.floor(Q/A*v):0});for(let L=0;L<o;L++)d[L]+=E[L]??0;let B=E.reduce((L,Q)=>L+Q,0),q=v-B;for(let L=0;q>0&&L<o;L++)d[L]++,q--}p=d.reduce((A,E)=>A+E,0)}let f=h.reduce((v,A)=>v+A,0)+a,m;if(f<=t)m=h.map((v,A)=>Math.max(v,d[A]));else{let v=h.reduce((q,L,Q)=>q+Math.max(0,L-d[Q]),0),A=Math.max(0,l-p);m=d.map((q,L)=>{let Q=h[L],We=Math.max(0,Q-q),Pe=0;return v>0&&(Pe=Math.floor(We/v*A)),q+Pe});let E=m.reduce((q,L)=>q+L,0),B=l-E;for(;B>0;){let q=!1;for(let L=0;L<o&&B>0;L++)m[L]<h[L]&&(m[L]++,B--,q=!0);if(!q)break}}let b=m.map(v=>"\u2500".repeat(v));r.push(`\u250C\u2500${b.join("\u2500\u252C\u2500")}\u2500\u2510`);let g=e.header.map((v,A)=>{let E=this.renderInlineTokens(v.tokens||[],n);return this.wrapCellText(E,m[A],n?.stylePrefix)}),y=Math.max(...g.map(v=>v.length));for(let v=0;v<y;v++){let A=g.map((E,B)=>{let q=E[v]||"",L=q+" ".repeat(Math.max(0,m[B]-x(q)));return this.theme.bold(L)});r.push(`\u2502 ${A.join(" \u2502 ")} \u2502`)}let k=`\u251C\u2500${m.map(v=>"\u2500".repeat(v)).join("\u2500\u253C\u2500")}\u2500\u2524`;r.push(k);for(let v=0;v<e.rows.length;v++){let E=e.rows[v].map((q,L)=>{let Q=this.renderInlineTokens(q.tokens||[],n);return this.wrapCellText(Q,m[L],n?.stylePrefix)}),B=Math.max(...E.map(q=>q.length));for(let q=0;q<B;q++){let L=E.map((Q,We)=>{let Pe=Q[q]||"";return Pe+" ".repeat(Math.max(0,m[We]-x(Pe)))});r.push(`\u2502 ${L.join(" \u2502 ")} \u2502`)}v<e.rows.length-1&&r.push(k)}let P=m.map(v=>"\u2500".repeat(v));return r.push(`\u2514\u2500${P.join("\u2500\u2534\u2500")}\u2500\u2518`),i&&i!=="space"&&r.push(""),r}};var lt=class extends ee{child;followEnd;primary;overscroll;scrollbarTrackStyle;scrollbarThumbStyle;currentScrollbar;scrollbarHideDelayMs;currentScrollTop=0;contentHeight=0;currentViewportHeight=0;followingEnd;followSuppressedAtEnd=!1;requestRenderCallback;transientScrollbarVisible=!1;scrollbarActive=!1;scrollbarHideTimer;constructor(e,t={}){if(super(),t.axis!==void 0&&t.axis!=="vertical")throw new Error(`Unsupported ScrollView axis: ${t.axis}`);this.child=e,this.children.push(e),this.followEnd=(t.follow??"none")==="end",this.followingEnd=this.followEnd,this.primary=t.primary??!1,this.overscroll=t.overscroll??"chain",this.currentScrollbar=t.scrollbar??"hidden",this.scrollbarTrackStyle=t.scrollbarTrackStyle??(i=>`\x1B[90m${i}\x1B[39m`),this.scrollbarThumbStyle=t.scrollbarThumbStyle??(i=>`\x1B[37m${i}\x1B[39m`),this.scrollbarHideDelayMs=Math.max(0,Math.floor(t.scrollbarHideDelayMs??1e3))}get scrollTop(){return this.currentScrollTop}get isFollowingEnd(){return this.followingEnd}get viewportHeight(){return this.currentViewportHeight}get scrollbar(){return this.currentScrollbar}get isScrollbarVisible(){return this.scrollbar==="always"?this.currentViewportHeight>0:this.scrollbar==="auto"&&this.contentHeight>this.currentViewportHeight&&this.transientScrollbarVisible}get isScrollbarActive(){return this.scrollbarActive}setScrollbar(e){e!==this.currentScrollbar&&(this.currentScrollbar=e,e!=="auto"?this.hideTransientScrollbar():this.scrollbarActive&&this.markScrollbarActivity(),this.requestRenderCallback?.())}getContentWidth(e){return this.scrollbar==="always"&&e>1?e-1:e}markScrollbarActivity(){this.scrollbar!=="auto"||this.contentHeight<=this.currentViewportHeight||(this.transientScrollbarVisible=!0,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0),!this.scrollbarActive&&(this.scrollbarHideTimer=setTimeout(()=>{this.scrollbarHideTimer=void 0,this.transientScrollbarVisible=!1,this.requestRenderCallback?.()},this.scrollbarHideDelayMs),this.scrollbarHideTimer.unref()))}hideTransientScrollbar(){this.transientScrollbarVisible=!1,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0)}setScrollbarActive(e){e!==this.scrollbarActive&&(this.scrollbarActive=e,this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollTo(e,t={}){let i=Number.isFinite(e)?Math.trunc(e):this.currentScrollTop,n=Math.max(0,this.contentHeight-this.currentViewportHeight),r=Math.max(0,Math.min(n,i)),o=t.disableFollow===!0&&r===n,a=!o&&this.followEnd&&r===n;if(r===this.currentScrollTop&&a===this.followingEnd&&o===this.followSuppressedAtEnd)return;let l=r!==this.currentScrollTop;this.currentScrollTop=r,this.followingEnd=a,this.followSuppressedAtEnd=o,l&&this.markScrollbarActivity(),this.requestRenderCallback?.()}scrollBy(e){let t=Number.isFinite(e)?Math.trunc(e):0;if(t===0)return 0;let i=Math.max(0,this.contentHeight-this.currentViewportHeight),n=this.followingEnd?i:this.currentScrollTop,r=Math.max(0,Math.min(i,n+t)),o=r-n,a=this.followingEnd;return this.currentScrollTop=r,this.followingEnd=this.followEnd&&r===i,this.followSuppressedAtEnd=!1,o!==0&&this.markScrollbarActivity(),(o!==0||this.followingEnd!==a)&&this.requestRenderCallback?.(),t-o}scrollToStart(){let e=this.currentScrollTop!==0||this.followingEnd!==(this.followEnd&&this.contentHeight<=this.currentViewportHeight);this.currentScrollTop=0,this.followingEnd=this.followEnd&&this.contentHeight<=this.currentViewportHeight,this.followSuppressedAtEnd=!1,e&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollToEnd(){let e=Math.max(0,this.contentHeight-this.currentViewportHeight),t=this.currentScrollTop!==e||this.followingEnd!==this.followEnd;this.currentScrollTop=e,this.followingEnd=this.followEnd,this.followSuppressedAtEnd=!1,t&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}updateLayout(e,t,i){this.contentHeight=Math.max(0,Math.floor(e)),this.currentViewportHeight=Math.max(0,Math.floor(t)),this.requestRenderCallback=i;let n=Math.max(0,this.contentHeight-this.currentViewportHeight);this.followingEnd?this.currentScrollTop=n:this.currentScrollTop=Math.max(0,Math.min(this.currentScrollTop,n)),this.currentScrollTop<n&&(this.followSuppressedAtEnd=!1),this.followEnd&&this.currentScrollTop===n&&!this.followSuppressedAtEnd&&(this.followingEnd=!0),this.contentHeight<=this.currentViewportHeight&&this.hideTransientScrollbar()}addChild(e){throw new Error("ScrollView has exactly one child")}removeChild(e){throw new Error("ScrollView child cannot be removed")}clear(){throw new Error("ScrollView child cannot be cleared")}render(e){let t=this.getContentWidth(e),i=this.child.render(t);return t===e?i:i.map(n=>`${n} `)}[Bt](){return{type:"scroll",component:this.child,state:this}}};var xi=class extends mi{layoutType="vstack";constructor(e=[],t={}){super(e,t)}render(e){let t={width:Math.max(1,e),height:Number.MAX_SAFE_INTEGER},i=gi(this.entries,t),n=i.map(a=>a.component.render(t.width)),r=Nt(i,n.map(a=>a.length),void 0,this.gap),o=[];for(let a=0;a<i.length;a++){if(a>0)for(let c=0;c<this.gap;c++)o.push("");let l=n[a].slice(0,r[a]);o.push(...l);for(let c=l.length;c<r[a];c++)o.push("")}return o}};import{createRequire as pp}from"node:module";import*as Za from"node:path";import{createRequire as cp}from"node:module";import{dirname as br,join as $s}from"node:path";import{fileURLToPath as hp}from"node:url";var up=cp(import.meta.url),dp="@earendil-works/pi-tui";function Ja(s,e={}){let t=br(hp(e.moduleUrl??import.meta.url)),i=[];try{let n=(e.resolvePackage??up.resolve)(dp);i.push($s(br(n),"..",s))}catch{}return i.push($s(t,"..",s),$s(t,s),$s(br(e.execPath??process.execPath),s)),Array.from(new Set(i))}var fp=pp(import.meta.url),As=new Map;function mp(s,e=""){let t=process.arch;if(t!=="x64"&&t!=="arm64")return;let i=Za.join("native",s,"prebuilds",`${s}-${t}`,`${s}-platform${e}.node`);if(As.has(i))return As.get(i);for(let n of Ja(i))try{let r=fp(n);if(typeof r?.getText=="function"&&typeof r.getImage=="function")return As.set(i,r),r}catch{}As.set(i,void 0)}function Ts(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return mp(process.platform)}var el="\x1B]7501;?\x1B\\";function tl(s){return/^\x1b\]7501;\?[^\x07\x1b]*(?:\x07|\x1b\\)$/.test(s)}var gp=/^[A-Za-z0-9_.+-]{1,32}$/,bp=2048;function yp(s,e){if(Buffer.byteLength(s,"utf8")<=e)return s;let t=0,i=0;for(let n of s){let r=Buffer.byteLength(n,"utf8");if(t+r>e)break;t+=r,i+=n.length}return s.slice(0,i)}function vi(s){let e=[`state=${s.state}`];s.app!==void 0&&gp.test(s.app)&&e.push(`app=${s.app}`),s.state==="blocked"&&s.kind&&e.push(`kind=${s.kind}`);let t=yp(ri(s.message??"").trim(),bp);return t&&e.push(`msg=${Buffer.from(t,"utf8").toString("base64")}`),`\x1B]7501;${e.join(":")}\x1B\\`}import{EventEmitter as wp}from"events";var se="\x1B",xp=50,vp=10,il="\x1B[200~",_s="\x1B[201~",nl=/^\x1b(?:\](?:1[01];|4;\d{1,3};|7501;\?)|P>\||_G(?:[a-z]=\d+,)*[a-z]=\d+;)/;function rl(s){return s.startsWith(`${se}]`)||s.startsWith(`${se}P`)||s.startsWith(`${se}_`)}function kp(s){if(!s.startsWith(se))return"not-escape";if(s.length===1)return"incomplete";let e=s.slice(1);return e.startsWith("[")?e.startsWith("[M")?s.length>=6?"complete":"incomplete":Sp(s):e.startsWith("]")?Cp(s):e.startsWith("P")?$p(s):e.startsWith("_")?Ap(s):e.startsWith("O")?e.length>=2?"complete":"incomplete":(e.length===1,"complete")}function Sp(s){if(!s.startsWith(`${se}[`))return"complete";if(s.length<3)return"incomplete";let e=s.slice(2),t=e[e.length-1],i=t.charCodeAt(0);if(i>=64&&i<=126){if(e.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(e))return"complete";if(t==="M"||t==="m"){let r=e.slice(1,-1).split(";");if(r.length===3&&r.every(o=>/^\d+$/.test(o)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function Cp(s){return!s.startsWith(`${se}]`)||s.endsWith(`${se}\\`)||s.endsWith("\x07")?"complete":"incomplete"}function $p(s){return!s.startsWith(`${se}P`)||s.endsWith(`${se}\\`)?"complete":"incomplete"}function Ap(s){return!s.startsWith(`${se}_`)||s.endsWith(`${se}\\`)?"complete":"incomplete"}function Tp(s){let e=s.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!e)return;let t=parseInt(e[1],10);return t>=32?t:void 0}function sl(s){let e=[],t=0;for(;t<s.length;){let i=s.slice(t);if(i.startsWith(se)){let n=rl(i)&&nl.test(i),r=1;for(;r<=i.length;){if(n&&r>2){let l=i[r-1];if(l===""||l===""){t+=r;break}if(l===se&&r<i.length&&i[r]!=="\\"){t+=r-1;break}}let o=i.slice(0,r),a=kp(o);if(a==="complete"){if(o==="\x1B\x1B"){let l=i[r];if(l==="["||l==="]"||l==="O"||l==="P"||l==="_"){e.push(se),t+=1;break}}e.push(o),t+=r;break}else if(a==="incomplete")r++;else{e.push(o),t+=r;break}}if(r>i.length)return{sequences:e,remainder:i}}else e.push(i[0]),t++}return{sequences:e,remainder:""}}var ki=class extends wp{buffer="";timeout=null;timeoutMs;escapeTimeoutMs;pasteMode=!1;pasteBuffer="";pendingKittyPrintableCodepoint;constructor(e={}){super(),this.timeoutMs=e.timeout??xp,this.escapeTimeoutMs=e.escapeTimeout??vp}process(e){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let t;if(Buffer.isBuffer(e))if(e.length===1&&e[0]>127){let r=e[0]-128;t=`\x1B${String.fromCharCode(r)}`}else t=e.toString();else t=e;if(t.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=t,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let r=this.pasteBuffer.indexOf(_s);if(r!==-1){let o=this.pasteBuffer.slice(0,r),a=this.pasteBuffer.slice(r+_s.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",o),a.length>0&&this.process(a)}return}let i=this.buffer.indexOf(il);if(i!==-1){if(i>0){let o=this.buffer.slice(0,i),a=sl(o);for(let l of a.sequences)this.emitDataSequence(l)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(i+il.length),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let r=this.pasteBuffer.indexOf(_s);if(r!==-1){let o=this.pasteBuffer.slice(0,r),a=this.pasteBuffer.slice(r+_s.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",o),a.length>0&&this.process(a)}return}let n=sl(this.buffer);this.buffer=n.remainder;for(let r of n.sequences)this.emitDataSequence(r);if(this.buffer.length>0){if(nl.test(this.buffer))return;let r=this.buffer===se?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let o=this.flush();for(let a of o)a.length>2&&rl(a)?(this.emitDataSequence(a.slice(0,2)),this.process(a.slice(2))):this.emitDataSequence(a)},r)}}emitDataSequence(e){let t=e.length===1?e.codePointAt(0):void 0;if(t!==void 0&&t===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=Tp(e),this.emit("data",e)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return[];let e=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,e}clear(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}};import*as Ht from"node:fs";import*as hl from"node:path";function ol(s){let e=Ts();if(!e?.isModifierPressed)return!1;try{return e.isModifierPressed(s)===!0}catch{return!1}}var _p=1e3,al="\x1B]9;4;3\x07",yr="\x1B]9;4;0\x07",Ip="\x1B[13;2u",Pp=7,Rp=150,Mp=`\x1B[>${Pp}u\x1B[?u`,Ep="\x1B[c";function ll(s){let e=s.match(/^\x1b\[\?(\d+)u$/);if(e)return{type:"kitty-flags",flags:Number.parseInt(e[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(s))return{type:"device-attributes"}}function cl(s){return s==="\x1B["||/^\x1b\[\?[\d;]*$/.test(s)}function ul(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function Lp(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.pid,"SIGWINCH")}catch{}}function dl(s){return s==="\r"||s==="\x1B\r"}function Op(s,e,t){return e&&dl(s)&&t?Ip:s}var qp=10,Dp=100;function Bp(s=process.env){let e=Number(s.PI_TUI_ESC_TIMEOUT);return Number.isFinite(e)&&e>0?e:s.SSH_CONNECTION||s.SSH_TTY?Dp:qp}var Si=class{wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;keyboardProtocolPushed=!1;pendingKeyboardProtocolDeviceAttributes=0;keyboardProtocolNegotiationBuffer="";keyboardProtocolBufferFlushTimer;stdinBuffer;stdinDataHandler;progressInterval;programStatus;programStatusSupported=!1;programStatusQueryPending=!1;writeLogPath=(()=>{let e=process.env.PI_TUI_WRITE_LOG||"";if(!e)return"";try{if(Ht.statSync(e).isDirectory()){let t=new Date,i=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}_${String(t.getHours()).padStart(2,"0")}-${String(t.getMinutes()).padStart(2,"0")}-${String(t.getSeconds()).padStart(2,"0")}`;return hl.join(e,`tui-${i}-${process.pid}.log`)}}catch{}return e})();get kittyProtocolActive(){return this._kittyProtocolActive}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(e,t){this.inputHandler=e,this.resizeHandler=t,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdout.write("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),Lp(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new ki({escapeTimeout:Bp()}),this.stdinBuffer.on("data",e=>{if(tl(e)){this.programStatusQueryPending&&(this.programStatusQueryPending=!1,this.programStatusSupported=!0,this.writeProgramStatus());return}let t=this.readKeyboardProtocolNegotiationSequence(e);if(t==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}t&&this.handleKeyboardProtocolNegotiationSequence(t.parsed)||this.forwardInputSequence(t?.sequence??e)}),this.stdinBuffer.on("paste",e=>{this.inputHandler&&this.inputHandler(`\x1B[200~${e}\x1B[201~`)}),this.stdinDataHandler=e=>{this.stdinBuffer.process(e)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),this.keyboardProtocolPushed=!0,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer();let e=process.env.PI_PROGRAM_STATUS;this.programStatusSupported=e==="1",this.programStatusQueryPending=e!=="1"&&e!=="0";let t=this.programStatusQueryPending?el:"";process.stdout.write(`${Mp}${t}${Ep}`),this.writeProgramStatus()}handleKeyboardProtocolNegotiationSequence(e){if(this.clearKeyboardProtocolNegotiationBuffer(),e.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return!1;this.pendingKeyboardProtocolDeviceAttributes-=1,this.pendingKeyboardProtocolDeviceAttributes===0&&(this.programStatusQueryPending=!1)}return e.type==="kitty-flags"?(e.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,ui(!0))):this.enableModifyOtherKeys(),!0):(this._kittyProtocolActive||this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(e){if(this.keyboardProtocolNegotiationBuffer){let i=this.keyboardProtocolNegotiationBuffer+e,n=ll(i);if(n)return this.clearKeyboardProtocolNegotiationBuffer(),{parsed:n,sequence:i};if(cl(i))return this.setKeyboardProtocolNegotiationBuffer(i),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let t=ll(e);if(t)return{parsed:t,sequence:e};if(cl(e))return this.setKeyboardProtocolNegotiationBuffer(e),"pending"}setKeyboardProtocolNegotiationBuffer(e){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=e}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(){if(!this.keyboardProtocolNegotiationBuffer)return;let e=this.keyboardProtocolNegotiationBuffer;this.clearKeyboardProtocolNegotiationBuffer(),this.forwardInputSequence(e)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput()},Rp))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(e){if(!this.inputHandler)return;let t=dl(e)&&(ul()||process.platform==="win32"),i=Op(e,t,t&&ol("shift"));this.inputHandler(i)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(process.stdout.write("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform==="win32")try{Ts()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(e=1e3,t=50){let i=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),i&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,ui(!1)),this.disableModifyOtherKeys();let n=this.inputHandler;this.inputHandler=void 0;let r=Date.now(),o=()=>{r=Date.now()};process.stdin.on("data",o);let a=Date.now()+e;try{for(;;){let l=Date.now(),c=a-l;if(c<=0||l-r>=t)break;await new Promise(h=>setTimeout(h,Math.min(t,c)))}}finally{process.stdin.removeListener("data",o),this.inputHandler=n}}stop(){this.clearProgressInterval()&&process.stdout.write(yr),this.programStatusSupported&&this.programStatus&&process.stdout.write(vi({state:"clear"})),this.programStatusSupported=!1,this.programStatusQueryPending=!1,process.stdout.write("\x1B[?2004l");let e=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),e&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,ui(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode&&process.stdin.setRawMode(this.wasRaw)}restoreOnExit(e,t){let i=e;this.progressInterval&&(i+=yr),i+="\x1B[?2004l",(this.keyboardProtocolPushed||this._kittyProtocolActive)&&(i+="\x1B[<u"),this._modifyOtherKeysActive&&(i+="\x1B[>4;0m"),i+=t;try{Ht.writeSync(process.stdout.fd,i)}catch{}}write(e){if(process.stdout.write(e),this.writeLogPath)try{Ht.appendFileSync(this.writeLogPath,e,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(e){e>0?process.stdout.write(`\x1B[${e}B`):e<0&&process.stdout.write(`\x1B[${-e}A`)}hideCursor(){process.stdout.write("\x1B[?25l")}showCursor(){process.stdout.write("\x1B[?25h")}clearLine(){process.stdout.write("\x1B[K")}clearFromCursor(){process.stdout.write("\x1B[J")}clearScreen(){process.stdout.write("\x1B[2J\x1B[H")}setTitle(e){process.stdout.write(`\x1B]0;${ri(e)}\x07`)}setProgramStatus(e){this.programStatus=e.state==="clear"?void 0:e,this.programStatusSupported&&process.stdout.write(vi(e))}writeProgramStatus(){this.programStatusSupported&&this.programStatus&&process.stdout.write(vi(this.programStatus))}setProgress(e){e?(process.stdout.write(al),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(al)},_p))):(this.clearProgressInterval(),process.stdout.write(yr))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var Np=St(),Fp=/^[\x20-\x7e]*$/;function Wp(s){let e=[],t=[],i=0,n=!1,r=()=>{n&&(e.push(" "),i+=1,n=!1)};for(let o=0;o<s.length;o++){let a=At(s[o]??""),l=0;if(Fp.test(a)){let c=0;for(;c<a.length;){if(a.charCodeAt(c)===32){i>0&&(n=!0),l+=1,c+=1;continue}let h=c+1;for(;h<a.length&&a.charCodeAt(h)!==32;)h+=1;r();let u=a.slice(c,h);e.push(u),t.push({textStart:i,textEnd:i+u.length,row:o,startCol:l,endCol:l+u.length,linearColumns:!0}),i+=u.length,l+=u.length,c=h}}else for(let c of Np.segment(a)){let h=c.segment,u=x(h);if(/^\s+$/u.test(h)){i>0&&(n=!0),l+=u;continue}r(),e.push(h),t.push({textStart:i,textEnd:i+h.length,row:o,startCol:l,endCol:l+u,linearColumns:!1}),i+=h.length,l+=u}i>0&&(n=!0)}return{text:e.join(""),spans:t}}function Up(s){return s.replace(/\s+/gu," ").trim()}function Kp(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hp(s,e){if(!e)return[];let t=new RegExp(Kp(e),"giu"),i=[],n=0;for(let r of s.text.matchAll(t)){let o=r.index,a=o+r[0].length;for(;n<s.spans.length&&s.spans[n].textEnd<=o;)n+=1;let l=[];for(let c=n;c<s.spans.length;c++){let h=s.spans[c];if(h.textStart>=a)break;if(h.textEnd<=o)continue;let u=h.linearColumns?h.startCol+Math.max(o,h.textStart)-h.textStart:h.startCol,d=h.linearColumns?h.startCol+Math.min(a,h.textEnd)-h.textStart:h.endCol,p=l[l.length-1];p&&p.row===h.row&&u<=p.endCol?p.endCol=Math.max(p.endCol,d):l.push({row:h.row,startCol:u,endCol:d})}for(;n<s.spans.length&&s.spans[n].textEnd<=a;)n+=1;l.length>0&&i.push({segments:l})}return i}var Is=class{sourceLines;corpus;normalizedQuery;matches=[];search(e,t){let i=this.sourceLines?.length!==e.length;if(!i&&this.sourceLines){for(let o=0;o<e.length;o++)if(this.sourceLines[o]!==e[o]){i=!0;break}}(i||!this.corpus)&&(this.sourceLines=Array.from(e),this.corpus=Wp(e));let n=Up(t),r=i||n!==this.normalizedQuery;return r&&(this.normalizedQuery=n,this.matches=Hp(this.corpus,n)),{matches:this.matches,changed:r}}};function wr(s){let e=s.segments[0],t=s.segments[s.segments.length-1];return e&&t?`${e.row}:${e.startCol}:${t.row}:${t.endCol}`:""}var Ps=class{input=new Te({prompt:" ",placeholder:"Find in transcript",placeholderStyle:e=>`\x1B[2m${e}\x1B[22m`});onQueryChange;navigationButtonStyle;resultCount=0;resultIndex=-1;previousButtonStart=-1;previousButtonEnd=-1;nextButtonStart=-1;nextButtonEnd=-1;hoveredNavigationDirection;_focused=!1;constructor(e,t=i=>i){this.onQueryChange=e,this.navigationButtonStyle=t}get focused(){return this._focused}set focused(e){this._focused=e,this.input.focused=e}setResult(e,t){this.resultIndex=e,this.resultCount=t}getNavigationDirectionAt(e,t){if(e===2){if(t>=this.previousButtonStart&&t<this.previousButtonEnd)return-1;if(t>=this.nextButtonStart&&t<this.nextButtonEnd)return 1}}setHoveredNavigationDirection(e){return e===this.hoveredNavigationDirection?!1:(this.hoveredNavigationDirection=e,!0)}handleInput(e){let t=this.input.getValue();this.input.handleInput(e);let i=this.input.getValue();i!==t&&this.onQueryChange(i)}invalidate(){this.input.invalidate()}render(e){let t=Math.max(1,e),i=Math.max(0,t-2),n=We=>We?We.split("+").map(Pe=>process.platform==="darwin"&&Pe.toLowerCase()==="alt"?"Option":Pe.charAt(0).toUpperCase()+Pe.slice(1)).join("+"):"Unbound",r=fe(),o=n(r.getKeys("tui.altScreen.searchPrevious")[0]),a=n(r.getKeys("tui.altScreen.searchNext")[0]),c=this.input.getValue()?this.resultCount===0?"No matches":`${this.resultIndex+1}/${this.resultCount}`:"",h=Math.max(0,i-3),u=_(c,h,""),d=u?`\x1B[2m ${u} \x1B[22m`:"",p=Math.max(0,i-x(d)),f=_(this.input.render(Math.max(1,p))[0]??"",p,""),m=" ".repeat(Math.max(0,p-x(f))),b=`${f}${m}${d}`,g=`\u2191 ${o}`,y=`\u2193 ${a}`,w=" \xB7 ",k=1,P=Math.max(0,i-k*2-1),v=x(g)+x(w)+x(y);v>P&&(g="\u2191",y="\u2193",w=" ",v=x(g)+x(w)+x(y));let A=v<=P,E=A?this.navigationButtonStyle(g,this.hoveredNavigationDirection===-1)+w+this.navigationButtonStyle(y,this.hoveredNavigationDirection===1):"",B=A?k*2:0,q=E&&i>v+B?1:0,L=Math.max(0,i-(A?v:0)-B-q),Q=1+L+k;return this.previousButtonStart=A?Q:-1,this.previousButtonEnd=A?Q+x(g):-1,this.nextButtonStart=A?this.previousButtonEnd+x(w):-1,this.nextButtonEnd=A?this.nextButtonStart+x(y):-1,t===1?["\u250C","\u2502","\u2514"]:[`\u250C${"\u2500".repeat(i)}\u2510`,`\u2502${b}\u2502`,`\u2514${"\u2500".repeat(L)}${E?" ":""}${E}${E?" ":""}${"\u2500".repeat(q)}\u2518`]}};var zp=1e3,Rs=class{entries=[];nextId=0;requestRender;constructor(e){this.requestRender=e}flash(e,t=zp){let i=this.nextId++,n=setTimeout(()=>{let r=this.entries.findIndex(o=>o.id===i);r!==-1&&(this.entries.splice(r,1),this.requestRender())},Math.max(0,t));n.unref(),this.entries.push({id:i,message:e,timer:n}),this.requestRender()}dispose(){for(let e of this.entries)clearTimeout(e.timer);this.entries.length=0}invalidate(){}render(e){return this.entries.map(t=>`\x1B[7m${_(` ${t.message} `,e,"")}\x1B[27m`)}};var Vp=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function Ci(s,e){let t=Math.max(s.x,e.x),i=Math.max(s.y,e.y),n=Math.min(s.x+s.width,e.x+e.width),r=Math.min(s.y+s.height,e.y+e.height);return{x:t,y:i,width:Math.max(0,n-t),height:Math.max(0,r-i)}}function Es(s,e,t){let i=Math.max(1,Math.floor(t)),n=s.renderCache.get(e);n||(n=new Map,s.renderCache.set(e,n));let r=n.get(i);return r||(r=e.render(i),n.set(i,r)),r}function pl(s,e,t){return Es(s,e,t).length}function jp(s,e,t){return Es(s,e,t).reduce((i,n)=>Math.max(i,x(n)),0)}function fl(s,e){return s.parent=e,s}function ml(s,e){s.rect.y+=e;for(let t of s.children)ml(t,e)}function gl(s,e){s.clip=Ci(e,s.rect);for(let t of s.children)gl(t,s.clip)}function Ms(s,e,t,i,n,r,o){let a=Math.max(1,Math.floor(n)),l=xs(e);if(!l){let y=Es(s,e,a),w=r===void 0?y.length:Math.max(0,Math.floor(r)),k=0;if(y.length>w&&w>0){let P=y.findIndex(v=>v.includes(pe));P>=w&&(k=P-w+1)}return{component:e,rect:{x:t,y:i,width:a,height:w},clip:Ci(o,{x:t,y:i,width:a,height:w}),children:[],lines:y,lineOffset:k,layer:0}}if(l.type==="scroll"){let y=l.state.scrollTop,w=l.state.getContentWidth(a),k=Ms(s,l.component,t,i-y,w,void 0,o),P=k.rect.height,v=r===void 0?P:Math.max(0,Math.floor(r));l.state.updateLayout(P,v,s.requestRender),ml(k,y-l.state.scrollTop);let A=l.state;(l.state.primary||!s.primaryScrollView)&&(s.primaryScrollView=A);let E={x:t,y:i,width:a,height:v},B=Ci(o,E),q={component:e,rect:E,clip:B,children:[k],scrollView:A,scrollContentLines:Es(s,l.component,w),layer:0};return k.parent=q,gl(k,B),q}let c=gi(l.entries,s.viewport),h=Math.max(0,c.length-1)*l.gap;if(l.type==="vstack"){let y=c.map(B=>typeof B.basis=="number"?B.basis:pl(s,B.component,a)),w=Nt(c,y,r,l.gap),k=w.reduce((B,q)=>B+q,0)+h,P=r===void 0?k:Math.max(0,Math.floor(r)),v={x:t,y:i,width:a,height:P},A={component:e,rect:v,clip:Ci(o,v),children:[],layer:0},E=i;for(let B=0;B<c.length;B++)A.children.push(fl(Ms(s,c[B].component,t,E,a,w[B],A.clip),A)),E+=w[B]+l.gap;return A}let u=c.map(y=>typeof y.basis=="number"?y.basis:jp(s,y.component,a)),d=Nt(c,u,a,l.gap),p=c.map((y,w)=>pl(s,y.component,Math.max(1,d[w]))),f=r===void 0?p.reduce((y,w)=>Math.max(y,w),0):Math.max(0,r),m={x:t,y:i,width:a,height:f},b={component:e,rect:m,clip:Ci(o,m),children:[],layer:0},g=t;for(let y=0;y<c.length;y++){let w=p[y],k=l.align==="stretch"?f:Math.min(f,w),P=i;l.align==="center"?P+=Math.floor((f-k)/2):l.align==="end"&&(P+=f-k);let v=d[y];v===0?b.children.push({component:c[y].component,rect:{x:g,y:P,width:0,height:k},clip:{x:g,y:P,width:0,height:0},children:[],parent:b,layer:0}):b.children.push(fl(Ms(s,c[y].component,g,P,v,k,b.clip),b)),g+=v+l.gap}return b}function Gp(s,e,t,i,n){if(z(s))return s;let r=oi(s,e),o=r?.start??e,a=r?.end??e+1,l=H(s,0,o,!0),c=H(s,o,a-o,!0),h=H(s,a,Math.max(0,t-a),!0),u="",d=0;for(;d<c.length;){let g=K(c,d);if(!g)break;u+=g.code,d+=g.length}let p=" ".repeat(Math.max(0,o-x(l))),f=" ".repeat(Math.max(0,e-o)),m=" ".repeat(Math.max(0,a-e-1)),b=`\x1B[0m\x1B]8;;\x07${n?Uo(u):""}`;return`${l}${p}${b}${f}${i}${m}${h}`}function zt(s,e=!1){if(!s.scrollView||s.rect.width<=0||s.rect.height<=0)return;let t=s.children[0]?.rect.height??s.scrollContentLines?.length??0,i=s.rect.height,n=e&&s.scrollView.scrollbar==="auto"&&t>i;if(!s.scrollView.isScrollbarVisible&&!n)return;let r=Math.min(2,i),o=Math.max(r,Math.min(i,Math.round(i*i/t))),a=Math.max(0,t-i),l=i-o,c=a===0?0:Math.round(s.scrollView.scrollTop/a*l),h=s.rect.x+s.rect.width-1;if(!(h<s.clip.x||h>=s.clip.x+s.clip.width))return{column:h,trackTop:s.rect.y,trackHeight:i,thumbTop:s.rect.y+c,thumbHeight:o,maxScrollTop:a}}function Qp(s,e,t){let i=zt(s);if(!(!i||!s.scrollView))for(let n=0;n<i.trackHeight;n++){let r=i.trackTop+n;if(r<s.clip.y||r>=s.clip.y+s.clip.height||r<0||r>=e.length)continue;let a=r>=i.thumbTop&&r<i.thumbTop+i.thumbHeight?s.scrollView.scrollbarThumbStyle(s.scrollView.isScrollbarActive?"\u2588":"\u2503"):s.scrollView.scrollbarTrackStyle("\u2502");e[r]=Gp(e[r]??"",i.column,t,a,s.scrollView.scrollbar!=="always")}}function bl(s,e,t){if(s.lines){let i=s.lineOffset??0,n=Math.max(s.rect.y,s.clip.y,0),r=Math.min(s.rect.y+s.rect.height,s.clip.y+s.clip.height,e.length);for(let o=n;o<r;o++){let a=s.lines[i+o-s.rect.y];if(a===void 0)continue;let l=a.replace(Vp,""),c=hs(l);if(c){let h=Math.min(e.length,s.clip.y+s.clip.height),u=Math.min(c.rows,h-o);u<c.rows&&(l=Jn(l,0,u))}s.rect.x===0&&s.rect.width>=t&&(z(l)||!e[o])?e[o]=l:e[o]=He(e[o]??"",l,s.rect.x,s.rect.width,t)}}for(let i of s.children)bl(i,e,t);if(s.scrollView&&s.scrollContentLines&&s.scrollView.scrollTop>0&&s.rect.height>0){let i=s.scrollView.scrollTop,n=Math.max(0,i-fa());for(let r=i-1;r>=n;r--){let o=s.scrollContentLines[r]??"";if(!z(o))continue;let a=hs(o);if(!a)continue;let l=i-r;if(l<a.rows){let c=Math.min(s.rect.height,a.rows-l),h=Jn(o,l,c);s.rect.x===0&&s.rect.width>=t&&(e[s.rect.y]=h)}break}}Qp(s,e,t)}function vr(s,e,t,i){let n=Math.max(1,Math.floor(e)),r=Math.max(1,Math.floor(t)),o={viewport:{width:n,height:r},renderCache:new Map,requestRender:i,primaryScrollView:void 0},a=Ms(o,s,0,0,n,r,{x:0,y:0,width:n,height:r}),l=Array.from({length:r},()=>"");return bl(a,l,n),{root:a,width:n,height:r,lines:l,...o.primaryScrollView===void 0?{}:{primaryScrollView:o.primaryScrollView}}}function xr(s,e,t){return e>=s.x&&e<s.x+s.width&&t>=s.y&&t<s.y+s.height}function yl(s,e,t){let i=[],n=(r,o)=>{if(xr(r.clip,e,t)){i.push({box:r,depth:o});for(let a of r.children)n(a,o+1)}};return n(s.root,0),i.sort((r,o)=>o.box.layer-r.box.layer||o.depth-r.depth),i.map(({box:r})=>r)}function we(s,e){let t=i=>{if(i.scrollView===e)return i;for(let n of i.children){let r=t(n);if(r)return r}};return t(s.root)}function Ls(s,e,t){let i=[],n=(r,o)=>{if(xr(r.clip,e,t)){r.scrollView&&xr(r.rect,e,t)&&i.push({scrollView:r.scrollView,depth:o});for(let a of r.children)n(a,o+1)}};return n(s.root,0),i.sort((r,o)=>o.depth-r.depth),i.map(r=>r.scrollView)}function Yp(){let s=process.env;return process.platform==="darwin"&&s.SSH_CONNECTION===void 0&&s.SSH_CLIENT===void 0&&s.SSH_TTY===void 0}var Os=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(e="auto",t=!Yp()){this.lines=e,this.accelerate=t}setLines(e){this.lines=e,this.reset()}next(e,t){if(this.lines!=="auto")return Number.isFinite(this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let i=t-this.lastTime,n=e===this.lastDirection&&i<=200;if(this.lastTime=t,this.lastDirection=e,!n)return this.averageGap=void 0,this.carry=0,1;if(i<5)return 1;this.averageGap=this.averageGap===void 0?i:(this.averageGap+i)/2;let r=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,o=Math.floor(r);return this.carry=r-o,o}reset(){this.lastTime=Number.NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}};var Xp="\x1B[?1049h",kr="\x1B[?1049l",wl="\x1B[?7l",Sr="\x1B[?7h",Jp="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",Zp="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",xl="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",ef="\x1B[I",tf="\x1B[O",qs="\x1B[?2026h",$i="\x1B[?2026l",vl=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,sf=/^\x1b\]133;A(?:\x07|\x1b\\)/,kl=4,nf=5,rf=16,of=32*1024*1024,af=64*1024*1024,Sl=500,lf=5e3,cf=new Set(["/","-","+","\\","~","_","."]),hf=Ct(),Ai=class extends pi{mode="fullscreen";[nr]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity="character";selectionInitialRange;lastClick;selectionDragPointer;selectionAutoScrollDirection=0;selectionAutoScrollTimer;selectionPressActive=!1;scrollbarDrag;scrollbarHover;scrollToEndIndicatorRect;activeSearch;pressedUrl;selectionDragged=!1;mouseCapture;mousePressTarget;mousePressPoint;mousePressMoved=!1;lastComponentClick;wheelScroll;mouseEnabled;searchMatchStyle;searchCurrentMatchStyle;searchNavigationButtonStyle;scrollToEndIndicator;openUrl;onRightClickPaste;copyOnSelect;copySelection;constructor(e,t,i,n={}){super(e,t,i),this.implicitDocument={render:r=>super.render(r),handleMouse:r=>super.handleMouse(r),invalidate:()=>{for(let r of this.children)r.invalidate()}},this.implicitScrollView=new lt(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new Rs(()=>this.requestRender()),this.wheelScroll=new Os(n.wheelScrollLines??1),this.mouseEnabled=n.mouse??!0,this.searchMatchStyle=n.searchMatchStyle??(r=>`\x1B[4m${r}\x1B[24m`),this.searchCurrentMatchStyle=n.searchCurrentMatchStyle??(r=>`\x1B[1;7m${r}\x1B[22;27m`),this.searchNavigationButtonStyle=n.searchNavigationButtonStyle??(r=>r),this.scrollToEndIndicator=n.scrollToEndIndicator,this.openUrl=n.openUrl,this.onRightClickPaste=n.onRightClickPaste,this.copyOnSelect=n.copyOnSelect??!0,this.copySelection=n.copySelection,this.addInputListener(r=>this.handleViewportInput(r))}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}setWheelScrollLines(e){this.wheelScroll.setLines(e)}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(e){this.copyOnSelect=e}hasActiveSelection(){return this.getActiveSelectionText()!==void 0}async copyActiveSelectionToClipboard(){let e=this.getActiveSelectionText();return e?this.copyTextToClipboard(e):!1}resetTextSelection(){this.clearTextSelection(),this.lastClick=void 0}getScreenLines(){return[...this.previousScreen]}setLayoutRoot(e){this.layoutRoot!==e&&(this.layoutRoot=e,this.currentLayout=void 0,this.requestRender())}render(e){return this.layoutRoot?.render(e)??super.render(e)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=!0;let e=ae();this.imageProtocol=e.images,this.uploadedKittyImages.clear(),e.images==="iterm2"&&(this.savedCapabilities=e,ls({...e,images:null}),this.invalidate()),this.lastDocument=[],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let t=process.env.TERM?.toLowerCase()??"",i=process.env.TMUX!==void 0||process.env.ZELLIJ!==void 0||process.env.STY!==void 0||t.startsWith("tmux")||t.startsWith("screen")?Jp:Zp;this.terminal.write(`${Xp}${wl}${this.mouseEnabled?i:""}\x1B[2J\x1B[H\x1B[?25l`)}beforeTerminalStop(e){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${qs}${this.deleteKittyImages()}${this.mouseEnabled?xl:""}${Sr}${$i}`),this.uploadedKittyImages.clear())}afterTerminalStop(e){if(this.altScreenActive){if(this.altScreenActive=!1,e.preserveScreen)this.terminal.write(`${qs}${kr}\x1B[?25h${$i}`);else{let t=Math.max(1,this.terminal.columns),i=this.resolveFakeCursors(this.render(t)).map(r=>r.replace(vl,""));this.lastDocument=this.applyLineResets(i.map(r=>r.replaceAll(pe,""))).map(r=>z(r)||x(r)<=t?r:H(r,0,t,!0));let n=`${qs}${kr}${wl}`;for(let r=0;r<this.lastDocument.length;r++)r>0&&(n+=`\r
|
|
105
|
+
`),n+=`\r\x1B[2K${this.lastDocument[r]??""}`;n+=`\x1B[0m${Sr}\r
|
|
106
|
+
\x1B[?25h${$i}`,this.terminal.write(n)}this.savedCapabilities&&(ls(this.savedCapabilities),this.savedCapabilities=void 0)}}getExitRestorePrefix(){let e=super.getExitRestorePrefix();return this.altScreenActive?`${$i}${this.mouseEnabled?xl:""}${Sr}${e}`:e}getExitRestoreSuffix(){return`${super.getExitRestoreSuffix()}${this.altScreenActive?`${kr}\x1B[?25h`:""}`}deleteKittyImages(){return this.imageProtocol==="kitty"?Qn():""}prepareKittyScreen(e){let t=new Set,i=e.map(l=>{let c=ba(l);if(!c)return l;t.add(c.imageId);let h=this.uploadedKittyImages.get(c.imageId),u={transmissionGeneration:c.transmissionGeneration,transmissionBytes:c.transmissionBytes,estimatedDecodedBytes:c.estimatedDecodedBytes};return h&&this.uploadedKittyImages.delete(c.imageId),this.uploadedKittyImages.set(c.imageId,u),h?.transmissionGeneration===c.transmissionGeneration?c.replacementLine:l}),n=0,r=0,o=0;for(let[l,c]of this.uploadedKittyImages)t.has(l)||(n+=1,r+=c.transmissionBytes,o+=c.estimatedDecodedBytes);let a="";for(let[l,c]of this.uploadedKittyImages){if(n<=rf&&r<=of&&o<=af)break;t.has(l)||(a+=cs(l),this.uploadedKittyImages.delete(l),n-=1,r-=c.transmissionBytes,o-=c.estimatedDecodedBytes)}return{lines:i,evictedImageDeletion:a}}resetRenderState(){this.previousScreen=[],this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(e){this.getPrimaryScrollView().scrollBy(e),this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().scrollToEnd(),this.requestRender()}scrollToPrompt(e){if(!this.currentLayout)return;let t=this.getPrimaryScrollView(),i=we(this.currentLayout,t)?.scrollContentLines;if(i){for(let n=t.scrollTop+e;n>=0&&n<i.length;n+=e)if(sf.test(i[n]??"")){t.scrollTo(n),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let e=new Ps(i=>this.updateSearchQuery(i),this.searchNavigationButtonStyle),t={component:e,index:new Is,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=t,t.overlay=this.showOverlay(e,{anchor:"top-right",width:"40%",minWidth:32,margin:1})}closeSearch(){let e=this.activeSearch;e&&(this.activeSearch=void 0,e.overlay?.hide(),this.requestRender())}updateSearchQuery(e){let t=this.activeSearch;if(!t||e===t.query)return;let i=t.matches[t.selectedIndex];t.anchorRow=i?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,t.query=e,t.selectionMode="query",t.component.setResult(-1,0),this.requestRender()}navigateSearch(e){let t=this.activeSearch;t?.query&&(t.selectionMode=e<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(e,t){let i=this.activeSearch,n=i?.overlay?.getBounds();if(!(!i||!n)&&!(e<n.col||e>=n.col+n.width||t<n.row||t>=n.row+n.height))return i.component.getNavigationDirectionAt(t-n.row,e-n.col)}handleSearchMouseEvent(e){let t=this.activeSearch;if(!t)return!1;let i=this.getSearchNavigationDirectionAt(e.x,e.y);return t.component.setHoveredNavigationDirection(i)&&this.requestRender(),i===void 0||e.release||(e.button&32)!==0||(e.button&3)!==0?!1:(this.navigateSearch(i),!0)}refreshSearch(e){let t=this.activeSearch;if(!t)return!1;let i=e.primaryScrollView??this.implicitScrollView,n=we(e,i),r=n?.scrollContentLines;if(!r||!t.query.trim())return t.matches=[],t.selectedIndex=-1,t.selectedKey=void 0,t.selectionMode="retain",t.component.setResult(-1,0),!1;let o=t.selectionMode!=="retain",a=t.index.search(r,t.query),l=a.matches;if(t.matches=l,!a.changed&&t.selectionMode==="retain")return!1;let c=a.changed?t.selectedKey?l.findIndex(g=>wr(g)===t.selectedKey):-1:t.selectedIndex,h=-1;if(l.length>0)if(t.selectionMode==="query"){let g=0,y=l.length;for(;g<y;){let w=g+Math.floor((y-g)/2);(l[w].segments[0]?.row??0)<t.anchorRow?g=w+1:y=w}h=g<l.length?g:0}else if(t.selectionMode==="next"){let g=c>=0?c:Math.min(t.selectedIndex,l.length-1);h=g<0?0:(g+1)%l.length}else if(t.selectionMode==="previous"){let g=c>=0?c:Math.min(t.selectedIndex,l.length-1);h=g<0?l.length-1:(g-1+l.length)%l.length}else h=c>=0?c:Math.min(Math.max(0,t.selectedIndex),l.length-1);if(t.selectedIndex=h,t.selectedKey=h>=0?wr(l[h]):void 0,t.selectionMode="retain",t.component.setResult(h,l.length),!o)return!1;let u=l[h],d=u?.segments[0],p=u?.segments[u.segments.length-1];if(!n||!d||!p||i.viewportHeight<=0)return!1;let f=i.scrollTop,m=f+i.viewportHeight-1,b=f;return(d.row<f||p.row>m)&&(b=d.row-Math.floor(i.viewportHeight/3)),i.scrollTo(b,{disableFollow:!0}),i.scrollTop!==f}flash(e,t){this.flashes.flash(e,t)}shouldDeferViewportInput(){return this.getFocusedComponent()?.capturesViewportInput?!0:this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(e){if(e===tf){let o=this.selectionPressActive,a=o&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,o&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,a&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(e===ef)return{consume:!0};let t=this.parseWheelEvent(e);if(t){let o=this.wheelScroll.next(t.direction,performance.now()),a=t.direction*((t.button&8)!==0?o*nf:o),l=this.createMouseEvent("wheel",t.button,t.x,t.y,{wheelDelta:a}),c=this.dispatchMouseToOverlay(l),h=c.result??(c.hit?void 0:this.dispatchMouseToLayout(l));return h?(this.applyMouseDispatchResult(l,h)&&this.requestRender(),{consume:!0}):(this.routeWheel(t,a),{consume:!0})}let i=this.parseSgrMouseEvent(e);if(i)return this.handleMouseEvent(i),{consume:!0};if(this.isMouseSequence(e))return{consume:!0};let n=fe(),r=di(e);if(n.matches(e,"tui.altScreen.search"))return r||this.toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(n.matches(e,"tui.altScreen.searchNext"))return r||this.navigateSearch(1),{consume:!0};if(n.matches(e,"tui.altScreen.searchPrevious"))return r||this.navigateSearch(-1),{consume:!0};if(n.matches(e,"tui.altScreen.searchClose"))return r||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInput()){if(n.matches(e,"tui.altScreen.pageUp"))return r||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-kl)),{consume:!0};if(n.matches(e,"tui.altScreen.pageDown"))return r||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-kl)),{consume:!0};if(n.matches(e,"tui.altScreen.halfPageUp"))return r||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(n.matches(e,"tui.altScreen.halfPageDown"))return r||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(n.matches(e,"tui.altScreen.lineUp"))return r||this.scrollBy(-1),{consume:!0};if(n.matches(e,"tui.altScreen.lineDown"))return r||this.scrollBy(1),{consume:!0};if(n.matches(e,"tui.altScreen.previousPrompt"))return r||this.scrollToPrompt(-1),{consume:!0};if(n.matches(e,"tui.altScreen.nextPrompt"))return r||this.scrollToPrompt(1),{consume:!0};if(n.matches(e,"tui.altScreen.top"))return r||this.scrollToTop(),{consume:!0};if(n.matches(e,"tui.altScreen.bottom"))return r||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(e){switch(e&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}createMouseEvent(e,t,i,n,r={}){return{type:e,button:e==="wheel"?"none":this.decodeMouseButton(t),x:i,y:n,screenX:i,screenY:n,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(t&4)!==0,alt:(t&8)!==0,ctrl:(t&16)!==0,...r.wheelDelta===void 0?{}:{wheelDelta:r.wheelDelta},...r.clickCount===void 0?{}:{clickCount:r.clickCount}}}dispatchMouseToLayout(e){if(!this.currentLayout)return;let t=new Set,i=yl(this.currentLayout,e.screenX,e.screenY);for(let n of i){if(t.has(n.component)||xs(n.component)&&n.component.handleMouse===ee.prototype.handleMouse)continue;t.add(n.component);let r=tt(n.component,{...e,x:e.screenX-n.rect.x,y:e.screenY-n.rect.y,width:n.rect.width,height:n.rect.height});if(r)return r}}applyMouseDispatchResult(e,t){let i=this.resolveMouseFocusTarget(t.focusTarget??t.target.component),n=t.focus===!0&&this.getFocusedComponent()!==i;return t.focus&&this.setFocus(i),t.capture&&(this.mouseCapture=t.target),t.render??(n||e.type==="press"||e.type==="click"||e.type==="drag"||e.type==="wheel")}dispatchMouseToTarget(e,t){return tt(t.component,ka(e,t))}getComponentClickCount(e,t,i){let n=Date.now(),r=this.lastComponentClick,o=r&&n-r.timestamp<=Sl&&r.component===e.component&&r.x===t&&r.y===i?r.count%3+1:1;return this.lastComponentClick={timestamp:n,count:o,component:e.component,x:t,y:i},o}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(e){let t=(e.button&32)!==0,i=e.release?"release":t?this.decodeMouseButton(e.button)==="none"?"move":"drag":"press",n=this.createMouseEvent(i,e.button,e.x,e.y);if(this.mouseCapture||this.mousePressTarget){let a=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(e.x!==this.mousePressPoint.x||e.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let l=!1,c=this.dispatchMouseToTarget(n,a);if(c&&(l=this.applyMouseDispatchResult(n,c)),e.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===e.x&&this.mousePressPoint.y===e.y){let h=this.createMouseEvent("click",e.button,e.x,e.y,{clickCount:this.getComponentClickCount(a,e.x,e.y)}),u=this.dispatchMouseToTarget(h,a);u&&(l=this.applyMouseDispatchResult(h,u)||l)}this.clearComponentMouseGesture()}l&&this.requestRender();return}if(this.handleSearchMouseEvent(e))return;let r=this.dispatchMouseToOverlay(n);if(r.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(e))return;let a=this.handleScrollbarMouseEvent(e);if(this.scrollbarDrag||this.updateScrollbarHover(e.x,e.y),a)return}let o=r.result??(r.hit?void 0:this.dispatchMouseToLayout(n));if(o){let a=this.applyMouseDispatchResult(n,o);i==="press"&&(this.clearTextSelection(),this.mousePressTarget=o.target,this.mousePressPoint={x:e.x,y:e.y},this.mousePressMoved=!1),a&&this.requestRender();return}this.handleRightClickPaste(e)||this.handleSelectionMouseEvent(e)}parseWheelEvent(e){let t=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(e);if(t){let i=Number.parseInt(t[1],10);if((i&64)===0)return;let n=i&3;return n!==0&&n!==1?void 0:{direction:n===0?-1:1,x:Number.parseInt(t[2],10)-1,y:Number.parseInt(t[3],10)-1,button:i}}if(e.length===6&&e.startsWith("\x1B[M")){let i=e.charCodeAt(3)-32;if((i&64)===0)return;let n=i&3;return n!==0&&n!==1?void 0:{direction:n===0?-1:1,x:e.charCodeAt(4)-33,y:e.charCodeAt(5)-33,button:i}}}routeWheel(e,t){let i=t,n=new Set;for(let o of this.currentLayout?Ls(this.currentLayout,e.x,e.y):[])if(n.add(o),i=o.scrollBy(i),i===0||o.overscroll==="contain")break;let r=this.getPrimaryScrollView();i!==0&&!n.has(r)&&r.scrollBy(i),this.updateScrollbarHover(e.x,e.y),this.requestRender()}parseSgrMouseEvent(e){let t=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(e);if(t)return{button:Number.parseInt(t[1],10),x:Number.parseInt(t[2],10)-1,y:Number.parseInt(t[3],10)-1,release:t[4]==="m"}}handleRightClickPaste(e){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||e.release||e.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(e){let t=this.scrollToEndIndicatorRect;return!t||e.release||(e.button&32)!==0||(e.button&3)!==0||e.y!==t.row||e.x<t.column||e.x>=t.column+t.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(e,t,i=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let n of Ls(this.currentLayout,e,t)){let r=we(this.currentLayout,n),o=r?zt(r,i):void 0;if(o&&e===o.column&&t>=o.trackTop&&t<o.trackTop+o.trackHeight)return{scrollView:n,geometry:o}}}setScrollbarHover(e){e!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=e,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(e,t){this.setScrollbarHover(this.getScrollbarTargetAt(e,t,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(e,t,i,n){let r=t.trackHeight-t.thumbHeight,o=Math.max(0,Math.min(r,i-t.trackTop-n)),a=r===0?0:Math.round(o/r*t.maxScrollTop);e.scrollTo(a)}handleScrollbarMouseEvent(e){if(this.scrollbarDrag){if(e.release)return this.stopScrollbarDrag(),!0;let r=this.currentLayout?we(this.currentLayout,this.scrollbarDrag.scrollView):void 0,o=r?zt(r):void 0;return o&&this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,o,e.y,this.scrollbarDrag.grabOffset),!0}if(e.release||(e.button&32)!==0||(e.button&3)!==0)return!1;let t=this.getScrollbarTargetAt(e.x,e.y);if(!t)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.setScrollbarHover(t.scrollView);let i=e.y>=t.geometry.thumbTop&&e.y<t.geometry.thumbTop+t.geometry.thumbHeight,n=i?e.y-t.geometry.thumbTop:Math.floor(t.geometry.thumbHeight/2);return i||this.scrollScrollbarToPointer(t.scrollView,t.geometry,e.y,n),this.scrollbarDrag={scrollView:t.scrollView,grabOffset:n},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(e,t,i){if(!this.currentLayout)return;let n=we(this.currentLayout,e);if(!n||n.rect.height<=0||n.clip.height<=0)return;let r=Math.max(0,n.rect.y,n.clip.y),o=Math.min(this.terminal.rows-1,n.rect.y+n.rect.height-1,n.clip.y+n.clip.height-1);if(o<r)return;let a=Math.max(r,Math.min(o,i)),l=Math.max(0,(n.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(l,e.scrollTop+a-n.rect.y)),col:Math.max(0,Math.min(n.rect.width-1,t-n.rect.x)),scrollView:e}}getSelectionPoint(e,t){if(t){let i=this.getScrollSelectionPoint(t,e.x,e.y);if(i)return i}return{row:Math.max(0,Math.min(this.terminal.rows-1,e.y)),col:Math.max(0,Math.min(this.terminal.columns-1,e.x))}}getSelectionSourceLine(e){if(e.scrollView&&this.currentLayout){let t=we(this.currentLayout,e.scrollView)?.scrollContentLines;if(t)return t[e.row]??""}return this.previousScreen[e.row]??""}getWordSelection(e){let t=At(this.getSelectionSourceLine(e)),i=[],n=0;for(let c of hf.segment(t)){let h=n+x(c.segment),u=cf.has(c.segment);i.push({start:n,end:h,selectable:c.isWordLike===!0||u,joiner:u}),n=h}let r=i.findIndex(c=>e.col>=c.start&&e.col<c.end);if(r<0)return;let o=(c,h)=>c.selectable&&h.selectable&&(c.joiner||h.joiner),a=i[r].start,l=i[r].end;for(let c=r;c>0&&o(i[c-1],i[c]);c--)a=i[c-1].start;for(let c=r;c<i.length-1&&o(i[c],i[c+1]);c++)l=i[c+1].end;return{start:{...e,col:a},end:{...e,col:l,boundary:!0}}}getLineSelection(e){return{start:{...e,col:0},end:{...e,col:x(this.getSelectionSourceLine(e)),boundary:!0}}}updateSelectionFocus(e){if(this.selectionGranularity==="character"||!this.selectionInitialRange){this.selectionFocus=e;return}let t=this.selectionGranularity==="word"?this.getWordSelection(e):this.getLineSelection(e);if(!t)return;let i=this.selectionInitialRange;t.start.row<i.start.row||t.start.row===i.start.row&&t.start.col<i.start.col?(this.selectionAnchor=i.end,this.selectionFocus=t.start):(this.selectionAnchor=i.start,this.selectionFocus=t.end)}getClickCount(e,t){let i=Date.now(),n=this.lastClick,r=t&&n&&i-n.timestamp<=Sl&&n.row===e.row&&n.scrollView===e.scrollView&&n.wordStart===t.start.col&&n.wordEnd===t.end.col?n.count%3+1:1;return this.lastClick=t?{timestamp:i,count:r,row:e.row,scrollView:e.scrollView,wordStart:t.start.col,wordEnd:t.end.col}:void 0,r}updateSelectionAutoScroll(e){let t=this.selectionAnchor?.scrollView;if(!t||!this.currentLayout){this.stopSelectionAutoScroll();return}let i=we(this.currentLayout,t);if(!i||i.rect.height<=0||i.clip.height<=0){this.stopSelectionAutoScroll();return}let n=Math.max(0,i.rect.y,i.clip.y),r=Math.min(this.terminal.rows-1,i.rect.y+i.rect.height-1,i.clip.y+i.clip.height-1);if(this.selectionDragPointer={x:e.x,y:e.y},this.selectionAutoScrollDirection=e.y<=n?-1:e.y>=r?1:0,this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.unref())}autoScrollSelection(){let e=this.selectionAnchor?.scrollView,t=this.selectionDragPointer,i=this.selectionAutoScrollDirection;if(!e||!t||i===0){this.stopSelectionAutoScroll();return}if(e.scrollBy(i)===i){this.stopSelectionAutoScroll();return}let r=this.getScrollSelectionPoint(e,t.x,t.y);r&&this.updateSelectionFocus(r),this.requestRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&(clearInterval(this.selectionAutoScrollTimer),this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(e){let t=e.button&3;if(t!==0&&!(e.release&&t===3))return;let i=this.selectionAnchor?.scrollView,n=this.getSelectionPoint(e,i);if(e.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))return;this.updateSelectionFocus(n);let h=!this.selectionDragged&&this.selectionAnchor.scrollView===n.scrollView&&this.selectionAnchor.row===n.row&&this.selectionAnchor.col===n.col,u=h?this.pressedUrl:void 0;if(this.pressedUrl=void 0,u&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(u)}catch{}this.requestRender();return}if(h){let d=this.createMouseEvent("click",e.button,e.x,e.y,{clickCount:this.lastClick?.count??1}),p=this.dispatchMouseToOverlay(d),f=p.result??(p.hit?void 0:this.dispatchMouseToLayout(d));if(f){let m=this.applyMouseDispatchResult(d,f);this.clearTextSelection(),m&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if((e.button&32)!==0){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=!0,this.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(n),this.updateSelectionAutoScroll(e),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let r=!this.hasOverlay()&&this.currentLayout?Ls(this.currentLayout,e.x,e.y)[0]:void 0,o=this.getSelectionPoint(e,r),a=this.getWordSelection(o),l=this.getClickCount(o,a),c=l===2?a:l===3?this.getLineSelection(o):void 0;this.selectionGranularity=c?l===2?"word":"line":"character",this.selectionInitialRange=c,this.selectionAnchor=c?.start??o,this.selectionFocus=c?.end??o,this.selectionDragged=!1,this.pressedUrl=c?void 0:Bn(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,e.y))]??"",Math.max(0,Math.min(this.terminal.columns-1,e.x))),this.requestRender()}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let e=this.selectionAnchor.row<this.selectionFocus.row||this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col<this.selectionFocus.col;if(!(this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col===this.selectionFocus.col))return e?{start:this.selectionAnchor,end:this.selectionFocus}:{start:this.selectionFocus,end:this.selectionAnchor}}getSelectionColumns(e,t,i,n=0,r=x(e)){let o=x(e),a=Math.max(0,n),l=Math.min(o,r);return t===i.start.row&&(a=oi(e,i.start.col)?.start??Math.min(i.start.col,o)),t===i.end.row&&(l=i.end.boundary?Math.min(i.end.col,o):oi(e,i.end.col)?.end??Math.min(i.end.col+1,o)),{start:Math.max(n,a),end:Math.min(r,l)}}getActiveSelectionText(){let e=this.getSelectionBounds();if(!e)return;let t=this.previousScreen;if(e.start.scrollView){if(!this.currentLayout)return;let r=we(this.currentLayout,e.start.scrollView);if(!r?.scrollContentLines)return;t=r.scrollContentLines}let i=[];for(let r=e.start.row;r<=e.end.row;r++){let o=t[r]??"",a=this.getSelectionColumns(o,r,e);i.push(At(H(o,a.start,Math.max(0,a.end-a.start),!0)).trimEnd())}let n=i.join(`
|
|
107
|
+
`);return n.length===0?void 0:n}async copySelectionToClipboard(){let e=this.getActiveSelectionText();return e?this.copyTextToClipboard(e):!1}async copyTextToClipboard(e){if(this.copySelection){let t=await this.copySelection(e),i=t===!0;return this.flash(i?"Copied!":typeof t=="string"?t:"Copy failed",i?void 0:lf),i}return this.terminal.write(`\x1B]52;c;${Buffer.from(e).toString("base64")}\x07`),this.flash("Copied!"),!0}applySearchTextHighlight(e,t){let i=t?this.searchCurrentMatchStyle:this.searchMatchStyle,n="",r=0,o=0;for(;o<e.length;){let a=K(e,o);if(!a){o+=1;continue}o>r&&(n+=i(e.slice(r,o))),n+=a.code,o+=a.length,r=o}return r<e.length&&(n+=i(e.slice(r))),n}applySearchHighlights(e,t){let i=this.activeSearch;if(!i||i.selectedIndex<0||i.matches.length===0)return e;let n=t.primaryScrollView??this.implicitScrollView,r=we(t,n);if(!r)return e;let o=new Map,a=zt(r)?.column,l=Math.max(0,r.rect.y,r.clip.y),c=Math.min(e.length,r.rect.y+r.rect.height,r.clip.y+r.clip.height),h=Math.max(0,r.rect.x,r.clip.x),u=Math.min(this.terminal.columns,r.rect.x+r.rect.width,r.clip.x+r.clip.width,a??Number.POSITIVE_INFINITY),d=n.scrollTop+l-r.rect.y,p=n.scrollTop+c-r.rect.y-1,f=0,m=i.matches.length;for(;f<m;){let g=f+Math.floor((m-f)/2),y=i.matches[g];(y.segments[y.segments.length-1]?.row??-1)<d?f=g+1:m=g}for(let g=f;g<i.matches.length;g++){let y=i.matches[g];if((y.segments[0]?.row??0)>p)break;for(let w of y.segments){let k=r.rect.y+w.row-n.scrollTop;if(k<l||k>=c)continue;let P=Math.max(h,r.rect.x+w.startCol),v=Math.min(u,r.rect.x+w.endCol);if(v<=P)continue;let A=o.get(k)??[];A.push({startCol:P,endCol:v,current:g===i.selectedIndex}),o.set(k,A)}}let b=[...e];for(let[g,y]of o){let w=b[g]??"";if(z(w))continue;let k=x(w);for(let P of y.sort((v,A)=>A.startCol-v.startCol)){let v=Math.min(P.startCol,k),A=Math.min(P.endCol,k);if(A<=v)continue;let E=H(w,0,v,!0),B=H(w,v,A-v,!0),q=H(w,A,Math.max(0,k-A),!0);w=`${E}${this.applySearchTextHighlight(B,P.current)}${q}`}b[g]=w}return b}applySelectionHighlight(e){let t="\x1B[7m",i=0;for(;i<e.length;){let n=K(e,i);if(!n){t+=e[i],i+=1;continue}t+=n.code,n.code.endsWith("m")&&(t+="\x1B[7m"),i+=n.length}return`${t}\x1B[27m`}applySelection(e,t=this.currentLayout){let i=this.getSelectionBounds();if(!i)return e;let n=i,r=0,o=e.length-1,a=0,l=this.terminal.columns;if(i.start.scrollView){if(!t)return e;let c=we(t,i.start.scrollView);if(!c)return e;r=Math.max(0,c.rect.y,c.clip.y),o=Math.min(e.length-1,c.rect.y+c.rect.height-1,c.clip.y+c.clip.height-1),a=Math.max(0,c.rect.x,c.clip.x),l=Math.min(this.terminal.columns,c.rect.x+c.rect.width,c.clip.x+c.clip.width),n={start:{...i.start,row:c.rect.y+i.start.row-i.start.scrollView.scrollTop,col:c.rect.x+i.start.col},end:{...i.end,row:c.rect.y+i.end.row-i.start.scrollView.scrollTop,col:c.rect.x+i.end.col}}}return e.map((c,h)=>{if(h<r||h>o||h<n.start.row||h>n.end.row||z(c))return c;let u=x(c),d=this.getSelectionColumns(c,h,n,a,l);if(d.end<=d.start)return c;let p=H(c,0,d.start,!0),f=H(c,d.start,d.end-d.start,!0),m=H(c,d.end,Math.max(0,u-d.end),!0);return`${p}${this.applySelectionHighlight(f)}${m}`})}isMouseSequence(e){return/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(e)||e.length===6&&e.startsWith("\x1B[M")}compositeScrollToEndIndicator(e,t,i){this.scrollToEndIndicatorRect=void 0;let n=t.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||!n.followEnd||n.isFollowingEnd)return e;let r=we(t,n),o=r?.clip;if(!o||o.width<=0||o.height<=0)return e;let a=o.y+o.height-1;if(a>=e.length||z(e[a]??""))return e;let l=r?zt(r)?.column:void 0,c=_(this.scrollToEndIndicator(),o.width,""),h=x(c),u=o.x+Math.floor((o.width-h)/2),d=l??o.x+o.width,p=Math.max(0,d-u),f=_(c,p,""),m=x(f);if(m===0)return e;let b=[...e];return b[a]=He(b[a]??"",f,u,m,i),this.scrollToEndIndicatorRect={row:a,column:u,width:m},b}compositeFlashes(e,t,i){let n=this.flashes.render(t).slice(-i);if(n.length===0)return e;let r=[...e];for(;r.length<i;)r.push("");for(let o=0;o<n.length;o++){let a=n[o],l=x(a);l!==0&&(r[o]=He(r[o]??"",a,t-l,l,t))}return r}doRender(){if(this.stopped||!this.altScreenActive)return;let e=Math.max(1,this.terminal.columns),t=Math.max(1,this.terminal.rows),i=this.layoutRoot??this.implicitScrollView,n=vr(i,e,t,()=>this.requestRender());this.refreshSearch(n)&&(n=vr(i,e,t,()=>this.requestRender()));let r=this.resolveFakeCursors(n.lines.map(g=>g.replace(vl,"")));r=this.applySearchHighlights(r,n),r=this.compositeScrollToEndIndicator(r,n,e),r=this.compositeOverlays(r,e,t),r.length>t&&(r=r.slice(r.length-t)),r=this.applySelection(r,n),r=this.compositeFlashes(r,e,t);let o=this.extractCursorPosition(r,t);r=this.applyLineResets(r).map(g=>z(g)||x(g)<=e?g:H(g,0,e,!0));let a=this.previousScreen.length===0||this.previousScreenWidth!==e||this.previousScreenHeight!==t,l=r.map((g,y)=>g!==this.previousScreen[y]),c=r.some((g,y)=>l[y]&&(z(g)||z(this.previousScreen[y]??""))),h=!c&&this.imageProtocol==="kitty"&&l.some(Boolean)&&r.some((g,y)=>{let w=ga(g);if(w===void 0)return!1;for(let k=y;k<y+w;k++)if(l[k])return!0;return!1}),u=c||h,d=a||u,p=this.uploadedKittyImages.size>0,f=d&&this.imageProtocol==="kitty"?this.prepareKittyScreen(r):{lines:r,evictedImageDeletion:""},m=qs;if(a){this.fullRedrawCount+=1;let g=this.imageProtocol==="kitty"&&p?Yn():this.deleteKittyImages();m+=`${g}\x1B[2J`}else u&&(this.imageProtocol==="iterm2"?m+="\x1B[2J":this.imageProtocol==="kitty"&&(m+=Yn()));if(m+=f.evictedImageDeletion,d&&this.imageProtocol==="kitty"&&r.some(z)){for(let g=0;g<t;g++)!a&&!u&&r[g]===this.previousScreen[g]||(m+=`\x1B[${g+1};1H\x1B[2K`);for(let g=0;g<t;g++)!a&&!u&&r[g]===this.previousScreen[g]||z(f.lines[g]??"")||(m+=`\x1B[${g+1};1H${f.lines[g]??""}`);for(let g=0;g<t;g++)!a&&!u&&r[g]===this.previousScreen[g]||z(f.lines[g]??"")&&(m+=`\x1B[${g+1};1H${f.lines[g]??""}`)}else for(let g=0;g<t;g++)!a&&!u&&r[g]===this.previousScreen[g]||(m+=`\x1B[${g+1};1H\x1B[2K${f.lines[g]??""}`);o?(m+=`\x1B[${o.row+1};${Math.min(e,o.col)+1}H`,m+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):m+="\x1B[?25l",m+=$i,this.terminal.write(m),this.previousScreen=r,this.previousScreenWidth=e,this.previousScreenHeight=t,this.currentLayout=n}};var kw=1024*1024;import{spawn as Hm}from"node:child_process";import{existsSync as Bc,statSync as Nc}from"node:fs";import{homedir as zm}from"node:os";import{basename as bn,join as yn,relative as Vm,sep as Fc}from"node:path";import{mkdirSync as Xf,readFileSync as Jf,renameSync as Zf,writeFileSync as em}from"node:fs";import{dirname as tm}from"node:path";import{randomBytes as Vl}from"node:crypto";import{createWriteStream as Mf,openAsBlob as Ef,renameSync as Lf,rmSync as Of}from"node:fs";import{basename as js,dirname as qf,join as Df}from"node:path";import{Readable as Kl}from"node:stream";import{pipeline as Bf}from"node:stream/promises";var $=s=>!!s&&typeof s=="object"&&!Array.isArray(s),N=s=>typeof s=="number"&&Number.isFinite(s),V=s=>typeof s=="number"&&Number.isSafeInteger(s)&&s>0,Cr=s=>typeof s=="number"&&Number.isSafeInteger(s)&&s>=1&&s<=4096,ne=s=>typeof s=="string"&&!!s.trim(),ct=s=>{if(typeof s!="string")return s;try{return JSON.parse(s)}catch{return null}},uf=s=>s.replace(/^mcp__(?:listing_)?(.+)__(.+)$/,"$1.$2");function Bs(s,e){let t=uf(s.name),i=$(s.resultData)?s.resultData:{},n=$(i._meta)?i._meta:{},r=$(n["com.qupai/tool-source"])?n["com.qupai/tool-source"]:{};return e.filter(o=>{if(o===t)return!0;let a=o.indexOf(".");return a>0&&s.name===o.slice(a+1)&&r.tool===s.name&&r.server===`listing_${o.slice(0,a).replace(/[^a-zA-Z0-9_]/g,"_")}`}).length===1}var df=s=>$(s.counts),pf=s=>s.ok===!0,Tl=s=>N(s.min_energy)&&$(s.optimal_parameters)||N(s.value)&&$(s.gradient);function Vt(s,e=df){let t=ct(s);if(!$(t)||t.isError===!0)return null;if($(t.structuredContent))return Vt(t.structuredContent,e);if($(t.result))return Vt(t.result,e);if(Array.isArray(t.content)){for(let i of t.content)if($(i)&&i.type==="text"){let n=Vt(i.text,e);if(n)return n}}return e(t)?t:null}function ff(s){let e=s.args??ct(s.input);if(!$(e)||typeof e.code!="string"||!e.code.trim())return null;let t=ct(e.parameters??{});if(!$(t)||Object.values(t).some(c=>!N(c))||/\bParameter\b/.test(e.code)&&!Object.keys(t).length)return null;let i=Vt(s.resultData??s.result);if(!i||!$(i.counts))return null;let{shots:n,num_qubits:r,counts:o}=i;if(!V(n)||!Cr(r)||e.shots!==void 0&&e.shots!==n)return null;let a=Object.entries(o);if(!a.length||a.length>65536)return null;let l=a[0][0].length;return!l||l>r||a.some(([c,h])=>c.length!==l||!/^[01]+$/.test(c)||!Number.isSafeInteger(h)||h<0)||a.reduce((c,[,h])=>c+h,0)!==n?null:{kind:"distribution",toolCallId:s.id,qubits:r,shots:n,counts:{...o}}}function Cl(s){return typeof s=="string"?s.trim()?{name:s}:void 0:$(s)&&typeof s.name=="string"&&s.name.trim()&&N(s.bond_length)?{name:s.name,bondLength:s.bond_length}:void 0}function mf(s){return s?Array.isArray(s.points)?"scan":"max_cut"in s?"maxcut":"min_energy"in s||"value"in s&&"gradient"in s?"energy":null:null}function gf(s){let e=s.args??ct(s.input);if(!$(e)||!Array.isArray(e.hamiltonian))return null;let t=0;for(let i of e.hamiltonian){if(!$(i)||!Array.isArray(i.qubits))return null;for(let n of i.qubits){if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)return null;t=Math.max(t,n+1)}}return t>=1?t:null}function bf(s,e,t){if(t==="energy"&&!ne(e.result_ref)&&Tl(e)){let n=Cr(e.num_qubits)?e.num_qubits:gf(s);return n?{kind:"energy",toolCallId:s.id,qubits:n,minEnergy:N(e.min_energy)?e.min_energy:e.value}:null}if(!Cr(e.num_qubits))return null;let i={toolCallId:s.id,qubits:e.num_qubits};if(t==="energy"){if(!ne(e.result_ref)||!N(e.min_energy))return null;let n={kind:"energy",...i,minEnergy:e.min_energy},r=Cl(e.molecule);return r?.bondLength!==void 0&&(n.molecule=r),N(e.exact_energy)&&(n.exactEnergy=e.exact_energy),n}if(t==="scan"){let n=Cl(e.molecule);if(typeof e.molecule!="string"||!n||!Array.isArray(e.points))return null;let r=e.points.flatMap((a,l)=>$(a)&&ne(a.result_ref)&&N(a.min_energy)&&N(a.bond_length)&&a.failed===void 0&&a.skipped===void 0?[{index:l,bondLength:a.bond_length,minEnergy:a.min_energy}]:[]);if(!r.length)return null;let o=r.reduce((a,l)=>l.minEnergy<a.minEnergy?l:a);return{kind:"energy",...i,molecule:n,scan:{points:r,defaultPoint:o.index}}}return!ne(e.result_ref)||!V(e.shots)?null:{kind:"maxcut",...i,shots:e.shots}}function yf(s,e){if(s.state!=="done"||!Bs(s,e))return null;let t=s.resultData??s.result,i=Vt(t,pf)??Vt(t,Tl),n=mf(i);return n?bf(s,i,n):ff(s)}function Ds(s){let e=ct(s);if(!$(e)||e.isError||e.error||e.ok===!1)return null;if($(e.structuredContent))return Ds(e.structuredContent);if($(e.result))return Ds(e.result);if(Array.isArray(e.content)){for(let t of e.content)if($(t)&&t.type==="text"){let i=Ds(t.text);if(i)return i}}return typeof e.best_objective_value=="number"?e:null}function wf(s,e){if(s.state!=="done"||!Bs(s,e))return null;let t=s.resolvedArgs??s.args??ct(s.input);if(!$(t))return null;let i=t.matrix!=null,n=t.fields!=null;if(i===n)return null;let r=i?"qubo":"ising",o=Ds(s.resultData??s.result);if(!o)return null;let a=o.num_variables,l=o.best_objective_value,c=o[r==="qubo"?"best_bits":"best_spins"];return!Number.isSafeInteger(a)||a<1||a>2048||!N(l)||!Array.isArray(c)||c.length!==a||c.some(h=>!(r==="qubo"?[0,1]:[-1,1]).includes(h))?null:{kind:"optimization",toolCallId:s.id,problem:r,numVariables:a,objective:l}}function Ge(s){if(s.id==="hardware-verification")return"logicqubit";let e=/^hardware-verification-([a-z][a-z0-9-]{0,63})$/.exec(s.id);return e?e[1]:null}function $r(s){let e=new Map;for(let t of s){let i=Ge(t);i&&!e.has(i)&&e.set(i,t)}return e}var Ar=new Set(["originq","tianyan"]);function Tr(s,e){let t=s["compute.providers"];return t==null?!0:Array.isArray(t)&&t.includes(e)}function Ns(s,e,t){if(!t?.length||e.state!=="complete"||s.state!=="done")return null;let i=t.filter(o=>Ge(o)!==null),n=i.filter(o=>Bs(s,o.source_tools));if(n.length){let o=yf(s,n[0].source_tools);if(o){let a=n.find(l=>l.id==="hardware-verification")??n[0];return{candidate:o,action:a,actions:i.filter(l=>Bs(s,l.source_tools))}}}let r=t.find(o=>o.id==="optimization-verification");if(r){let o=wf(s,r.source_tools);if(o)return{candidate:o,action:r,actions:[]}}return null}function _l(s,e,t,i){if(s.candidate.kind==="optimization")return["isingq"];if(i)return[i];let n=Ge(s.action),r=s.candidate,o=r.kind==="distribution"||r.kind==="energy"&&!r.scan,a=[...$r(s.actions).keys()].filter(l=>l===n||o&&!!e?.some(c=>c.id===l&&c.integration==="implemented"&&c.source_kind==="hardware")&&(!t||Tr(t,l)));return a.length?a:n?[n]:[]}function Il(s,e){let i=e?.find(n=>n.id===s)?.name;return i?i.en||i.zh||Object.values(i).find(Boolean)||s:s==="isingq"?"isingq":s}var xf=4096,Ii=1024;function Pl(s){return s.kind==="energy"?xf:s.shots}function Fs(s,e){let t=typeof s.largest_connected_qubits=="number"?s.largest_connected_qubits:s.num_qubits;return t==null||t>=e}function Ti(s,e){return s.online!==!1&&Fs(s,e)}function _r(s,e){return[...s.filter(t=>Ti(t,e)),...s.filter(t=>!Ti(t,e))]}function Rl(s,e){if(!s.length||new Set(s).size!==s.length)return!1;if(s.length===1)return!0;let t=new Set(s),i=new Set([s[0]]),n=[s[0]];for(;n.length;){let r=n.pop();for(let[o,a]of e){let l=o===r?a:a===r?o:void 0;l&&t.has(l)&&!i.has(l)&&(i.add(l),n.push(l))}}return i.size===s.length}function Ir(s,e,t,i,n){if(!t.includes(s))return!1;let r=e.includes(s)?e.filter(o=>o!==s):[...e,s];return r.length<=n&&(!r.length||Rl(r,i))}function Ml(s,e,t){return s.length===t&&s.every(i=>/^(0|[1-9][0-9]*)$/.test(i)&&Number.isSafeInteger(Number(i))&&e.qubit_ids.includes(i))&&Rl(s,e.couplings)}function El(s,e){let t=s.qubit_metrics.find(o=>o.id===e);if(!t)return"no figures";let i=o=>N(o)?`${o>=100?o.toFixed(0):o.toFixed(1)} \xB5s`:"\u2014",n=o=>N(o)?o.toFixed(3):"\u2014",r=[`T1 ${i(t.t1_us)}`,`T2e ${i(t.t2e_us)}`,`T2* ${i(t.t2star_us)}`,`F0 ${n(t.readout_f0)}`,`F1 ${n(t.readout_f1)}`];return N(t.xeb_fidelity)&&r.push(`XEB ${n(t.xeb_fidelity)}`),N(t.single_qubit_gate_fidelity)&&r.push(`1q ${n(t.single_qubit_gate_fidelity)}`),r.join(" ")}function ht(s){if(s<10&&!Number.isInteger(s))return`${s<1?s.toFixed(2):s.toFixed(1)} s`;let e=Math.round(s);if(e<60)return`${e} s`;let t=i=>String(i).padStart(2,"0");return e<3600?`${Math.floor(e/60)} min ${t(e%60)} s`:`${Math.floor(e/3600)} h ${t(Math.floor(e%3600/60))} min`}function Ll(s){let e=s.online===!1?"offline":s.online===null?`status unknown${s.status?` (${s.status})`:""}`:s.status??"online",t=s.queue_depth!==null&&s.queue_depth!==void 0?`${s.queue_depth} queued`:s.idle_eta_seconds!=null?s.idle_eta_seconds>0?`free in about ${ht(s.idle_eta_seconds)}`:"free now":"queue not reported";return{state:e,queue:t}}var je=class extends Error{errorType;constructor(e,t){super(e),this.name="PreviewRefused",this.errorType=t}},Ws=s=>"kind"in s&&(s.kind==="energy"||s.kind==="maxcut"),Us=s=>"workload"in s&&s.workload==="quadratic_optimization",_i=s=>Array.isArray(s)&&s.every(e=>Number.isSafeInteger(e)&&e>=0);function Ol(s){if(!$(s)||s.status!=="preview"||!ne(s.preview_id)||!ne(s.target)||!_i(s.qids)||!V(s.shots)||!["auto","physical_pool"].includes(String(s.layout_mode))||!$(s.compilation))return!1;let e=s.baseline;return $(e)&&$(e.input)&&typeof e.input.code=="string"&&$(e.result)&&$(e.result.counts)&&V(e.result.shots)&&(s.mode===void 0||s.mode==="sandbox")}function ql(s){if(!$(s)||s.status!=="preview"||!ne(s.preview_id)||!["energy","maxcut"].includes(String(s.kind))||!ne(s.target)||!V(s.shots)||typeof s.readout_correction!="boolean"||!_i(s.qids))return!1;let e=s.variational;return $(e)&&V(e.circuits)&&V(e.total_shots)&&_i(e.qubits)&&$(s.baseline)&&(s.mode===void 0||s.mode==="sandbox")}function vf(s){if(!$(s)||s.status!=="preview"||s.provider!=="isingq"||s.workload!=="quadratic_optimization"||!ne(s.preview_id)||!$(s.options)||!$(s.machine)||!$(s.baseline))return!1;let e=s.options,t=s.machine,i=s.baseline;return V(t.computer_type_id)&&typeof t.name=="string"&&V(t.max_variables)&&t.computer_type_id===e.computer_type_id&&V(e.calculate_count)&&typeof e.post_process=="boolean"&&typeof e.use_credit=="boolean"&&N(i.objective_value)&&V(i.num_variables)&&typeof i.model_hash=="string"}function kf(s){return Array.isArray(s.content)?s.content.filter(e=>$(e)&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
|
|
108
|
+
`):""}function Dl(s){let e=$(s)?s:{},t=kf(e);if(e.isError===!0){let n=$(e.structuredContent)?e.structuredContent:{};throw new je(t||"The service refused this preview",typeof n.error_type=="string"?n.error_type:null)}let i=e.structuredContent;if(i==null&&t&&(i=ct(t)),$(i)&&"result"in i&&$(i.result)&&(i=i.result),ql(i)||Ol(i)||vf(i))return i;throw new Error("the server returned an incomplete hardware preview")}function Pr(s){return $(s)&&typeof s.id=="string"&&s.id&&["compiling","ready","failed"].includes(String(s.state))?s:null}function Bl(s){if(s.state==="failed")throw new je(s.error||"The sandbox could not compile this run","sandbox_compile_failed");let e=s.preview;if(!(ql(e)||Ol(e))||e.mode!=="sandbox"||e.preview_id!==s.id)throw new Error("the server returned an incomplete hardware preview");return e}function Rr(s){let[e,t]=Ws(s)?[s.variational.readout_note,s.readout_correction]:[s.readout_correction_note,s.compilation.readout_correction];return typeof e=="string"&&e.trim()?{note:e,fixedOn:t===!0}:null}var Ks=s=>(Math.ceil(s*100-1e-6)/100).toFixed(2),Pi=s=>s.replace(/\d/g,e=>"\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089"[Number(e)]).replace(/\+/g,"\u207A"),Ri=s=>s.replace(/^-/,"\u2212");function Mr(s){let e=$(s)&&$(s.device_queue)?s.device_queue:null;if(!e)return null;let t=e.jobs,i=e.idle_eta_s,n=typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t===0?"No task is waiting for this chip (read from the provider as this preview was made).":`${t} task${t===1?" is":"s are"} waiting for this chip (read from the provider as this preview was made).`:N(i)&&i>=0?i<1?"This chip is free now (as its provider said when this preview was made).":`This chip expects to be free in ${ht(i)} (as its provider said when this preview was made).`:null,r=N(e.typical_s)&&V(e.typical_runs)?`The last ${e.typical_runs} task${e.typical_runs===1?"":"s"} sent to this chip from here took about ${ht(e.typical_s)} from sending to the result.`:null;return!n&&!r?null:[n,r].filter(Boolean).join(" ")}function Nl(s,e){let t=$(s)&&$(s.progress)?s.progress:null;if(!t||!["queued","running","sent"].includes(String(t.phase))||!N(t.phase_s)||t.phase_s<0)return null;let i=ht(Math.floor(t.phase_s)),n=typeof t.device_jobs=="number"&&t.device_jobs>0?t.device_jobs:0,r=t.phase==="running"?`Running on the chip \xB7 ${i} so far`:t.phase==="queued"&&V(t.queue_position)?`Waiting in the chip's queue, place ${t.queue_position} \xB7 ${i} so far`:n?`Waiting in the chip's queue (${n} task${n===1?" is":"s are"} waiting for it now) \xB7 ${i} so far`:t.phase==="queued"?`Waiting in the chip's queue \xB7 ${i} so far`:`Sent, waiting for the chip's result \xB7 ${i} so far`,o=V(t.circuit)&&e&&e>1?`Circuit ${t.circuit} of ${e}: `:"",a=N(t.typical_s)&&V(t.typical_runs)?` \xB7 tasks on this chip lately took about ${ht(t.typical_s)}`:"";return`${o}${r}${a}`}function Hs(s){if(!$(s)||!ne(s.preview_id)||!ne(s.target)||!V(s.shots)||!_i(s.qids)||!$(s.compilation))return null;let e=s.baseline;return!$(e)||!$(e.source)||!ne(e.source.turn_id)||!ne(e.source.tool_call_id)||!$(e.result)||!$(e.result.counts)||!V(e.result.shots)||s.hardware!==void 0&&(!$(s.hardware)||!$(s.hardware.counts))?null:s}var $l=s=>s===null||N(s),Al=s=>N(s)&&s>=0&&s<=1;function Sf(s){return N(s.hardware_energy)&&N(s.standard_error)&&s.standard_error>=0&&N(s.simulated_energy)&&(s.exact_energy===void 0||N(s.exact_energy))&&(s.difference_mha===void 0||N(s.difference_mha))}function Cf(s){let e=s.most_frequent,t=s.ideal;return $l(s.approximation_ratio)&&Al(s.p_optimal)&&N(s.expected_cut)&&N(s.max_cut)&&$(e)&&typeof e.bits=="string"&&/^[01]+$/.test(e.bits)&&N(e.cut)&&$(t)&&N(t.expected_cut)&&$l(t.approximation_ratio)&&Al(t.p_optimal)}function Mi(s){return!$(s)||!ne(s.preview_id)||!["energy","maxcut"].includes(String(s.kind))||!$(s.source)||!ne(s.target)||!V(s.shots)||!_i(s.qids)||typeof s.readout_correction!="boolean"||!$(s.baseline)||!$(s.baseline.result)||!$(s.variational)||!V(s.variational.circuits)||s.readout!==void 0&&(!$(s.readout)||typeof s.readout.readout_corrected!="boolean"||!(s.kind==="energy"?Sf(s.readout):Cf(s.readout)))?null:s}function jt(s){return!$(s)||s.workload!=="quadratic_optimization"||s.provider!=="isingq"||typeof s.preview_id!="string"||!$(s.baseline)||!N(s.baseline.objective_value)||s.hardware!=null&&(!$(s.hardware)||!N(s.hardware.objective_value))?null:s}function Fl(s){let e=Hs(s);if(e)return{turnId:e.baseline.source.turn_id,toolCallId:e.baseline.source.tool_call_id};let t=Mi(s);return t?{turnId:t.source.turn_id,toolCallId:t.source.tool_call_id,point:t.baseline.point}:null}function Wl(s,e=8){let t=s.hardware;if(!t)return{rows:[],more:0,comparable:!1};let i=s.baseline.result,n=Object.keys(i.counts),r=Object.keys(t.counts),o=!!s.comparison&&s.comparison.bit_order==="q0_left"&&t.bit_order==="q0_left"&&s.comparison.shots.baseline===i.shots&&s.comparison.shots.hardware===t.shots&&(!n.length||r.every(u=>u.length===n[0].length)),a=r.reduce((u,d)=>u+(t.counts[d]??0),0)||1,l=u=>t.probabilities?.[u]!==void 0?t.probabilities[u]:(t.counts[u]??0)/a,c=[...new Set([...o?n:[],...r])].sort((u,d)=>l(d)-l(u)||(i.counts[d]??0)-(i.counts[u]??0)||u.localeCompare(d));return{rows:c.slice(0,e).map(u=>({state:u,hardware:l(u),...o?{simulation:(i.counts[u]??0)/i.shots}:{}})),more:Math.max(0,c.length-e),comparable:o}}function ut(s,e){let t=Math.max(0,Math.min(1,s)),i=Math.round(t*e*8),n=Math.floor(i/8),r=i%8;return"\u2588".repeat(n)+(r?"\u258F\u258E\u258D\u258C\u258B\u258A\u2589"[r-1]:"")}var zs=s=>`${(s*100).toFixed(1)}%`;import{createCipheriv as $f,createHash as Af,createPublicKey as Tf,diffieHellman as _f,generateKeyPairSync as If,randomBytes as Pf}from"node:crypto";var Vs=s=>Buffer.from(s).toString("base64url");function Rf(s,e,t=256,i=Buffer.alloc(0),n=Buffer.alloc(0)){let r=c=>{let h=Buffer.alloc(4);return h.writeUInt32BE(c),h},o=c=>Buffer.concat([r(c.length),c]),a=o(Buffer.from(e,"ascii")),l=Buffer.concat([a,o(i),o(n),r(t)]);return Af("sha256").update(Buffer.concat([r(1),s,l])).digest().subarray(0,t/8)}function Ul(s,e,t=new Date){let i=(s.keys??[]).find(b=>b.use==="enc"&&b.alg==="ECDH-ES"&&b.kty==="EC"&&b.crv==="P-256");if(!i?.kid||!i.x||!i.y)throw new Error("the platform gave no key to encrypt with");let n=Tf({key:{kty:"EC",crv:"P-256",x:i.x,y:i.y},format:"jwk"}),r=If("ec",{namedCurve:"P-256"}),o=r.publicKey.export({format:"jwk"}),a={alg:"ECDH-ES",enc:"A256GCM",kid:i.kid,epk:{kty:"EC",crv:"P-256",x:o.x,y:o.y}},l=Vs(Buffer.from(JSON.stringify(a),"utf8")),c=_f({privateKey:r.privateKey,publicKey:n}),h=Rf(c,"A256GCM"),u=Pf(12),d=$f("aes-256-gcm",h,u);d.setAAD(Buffer.from(l,"ascii"));let p=Buffer.from(JSON.stringify({v:1,provider:e.provider,tenant:e.tenantId,user:e.userId,iat:Math.floor(t.getTime()/1e3),secret:e.secret}),"utf8"),f=Buffer.concat([d.update(p),d.final()]),m=d.getAuthTag();return p.fill(0),h.fill(0),c.fill(0),`${l}..${Vs(u)}.${Vs(f)}.${Vs(m)}`}var Nf=10*6e4,Li=class extends Error{},Ff="https://qupai.quspect.com";function Hl(s){return Wf(s,Ff)?"qupai login":`qupai login -server ${s.replace(/\/+$/,"")}`}function Ys(s){try{let e=new URL(s.trim()),t=e.port||{"http:":"80","https:":"443"}[e.protocol]||"";return`${e.protocol}//${e.hostname.toLowerCase()}:${t}${e.pathname.replace(/\/+$/,"")}`}catch{return s.trim().replace(/\/+$/,"")}}function Wf(s,e){return Ys(s)===Ys(e)}var D=class extends Error{status;type;detail;constructor(e,t,i,n){super(n),this.status=e,this.type=t,this.detail=i}};function Uf(s,e,t,i,n,r){let o=r.trim().replace(/\.$/,"")||Kf(i),a=n.replace(/^urn:qupai:problem:/,"");return i===401?`${s} did not accept your sign-in (${o}): the key was revoked or has ended; run ${Hl(s)}`:a==="lab-role-required"?`no access: ${o}. Your role on that lab is not enough: ask for access on the lab's page in the app (QuPai staff decide who uses a lab)`:a==="sign-in-required"?`no access with a personal API key: ${o}. This needs your own sign-in in the app`:a==="partner-sign-in-required"?`no access: ${o}. Your account signs in through your partner's site: sign in there first, then run ${Hl(s)}`:a==="account-deleting"?`no access: ${o}. Your account is being deleted: restore it in the app to use it again`:i===403?`no access: ${o}. Ask your organization's admin in the app for the permission or app it needs`:a==="insufficient-credits"||i===402?`not enough credits: ${o}. Top up in the app, or ask your organization's admin`:`${e} ${t}: ${i} ${o}`}function Kf(s){return{400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",409:"Conflict",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable"}[s]??`status ${s}`}var dt=class extends Error{},Xs=class{signIn;fetchFn;retryMs;constructor(e){this.signIn=e.signIn,this.fetchFn=e.fetch??fetch.bind(globalThis),this.retryMs=e.retryMs??500}get server(){return this.signIn.handoff.server}async send(e,t,i,n,r){for(let o=0;;o++){let a=this.signIn.token(),l;try{l=await this.fetchFn(this.server+t,{method:e,headers:{Authorization:`Bearer ${a}`,...i===void 0||i instanceof FormData?{}:{"Content-Type":"application/json"},...n},body:i===void 0?void 0:i instanceof FormData?i:JSON.stringify(i),signal:r})}catch(c){throw r?.aborted?c:new dt(`${this.server} does not answer (${c instanceof Error?c.cause instanceof Error?c.cause.message:c.message:String(c)})`)}if(l.status===401&&o===0){let c=await l.text(),h=!1;try{h=await this.signIn.renew(a)}catch(u){throw new D(401,"","",u instanceof Error?u.message:String(u))}if(h)continue;return new Response(c,{status:401,headers:l.headers})}return l}}async call(e,t,i){return(await this.answer(e,t,i)).body}async answer(e,t,i,n={}){let r=await this.send(e,t,i,{Accept:"application/json",...n}),o=await r.text();if(!r.ok)throw this.refusal(e,t,r.status,o);return{status:r.status,body:o?JSON.parse(o):void 0}}refusal(e,t,i,n){let r="",o="";try{let a=JSON.parse(n);r=a.type??"",o=a.detail||a.title||""}catch{o=n.trim().slice(0,300)}return new D(i,r,o,Uf(this.server,e,t,i,r,o))}me=()=>this.call("GET","/v1/me");products=()=>this.call("GET","/v1/products");myAgents=async()=>{try{let e=await this.call("GET","/v1/agents");return{items:e.items??[],given:e.given===!0}}catch(e){if(e instanceof D&&(e.status===404||e.status===403))return{items:[],given:!1};throw e}};labs=async()=>{try{return(await this.call("GET","/v1/labs")).items??[]}catch(e){if(e instanceof D&&e.status===404)return[];throw e}};threads=async(e=30)=>(await this.call("GET",`/v1/threads?limit=${e}`)).items??[];thread=async e=>(await this.call("GET",`/v1/threads/${encodeURIComponent(e)}`)).thread;threadTurns=(e,t=20)=>this.call("GET",`/v1/threads/${encodeURIComponent(e)}/turns?limit=${t}`);createThread=(e,t)=>this.call("POST","/v1/threads",{product_id:e,agent_id:t});submitTurn=(e,t)=>this.call("POST",`/v1/threads/${encodeURIComponent(e)}/turns`,{input:{text:t}});turn=e=>this.call("GET",`/v1/turns/${encodeURIComponent(e)}`);approvals=async e=>(await this.call("GET",`/v1/turns/${encodeURIComponent(e)}/approvals`)).items??[];answerApproval=(e,t)=>this.call("POST",`/v1/turns/${encodeURIComponent(e)}/approval`,t);cancelTurn=e=>this.call("POST",`/v1/turns/${encodeURIComponent(e)}/cancel`);settings=async()=>(await this.call("GET","/v1/settings")).values??{};credential=e=>this.call("GET",`/v1/external-credentials/${encodeURIComponent(e)}`);saveCredential=async(e,t,i)=>{let n=i.trim();if(!n)throw new Error("no key to save");let r=`/v1/external-credentials/${encodeURIComponent(e)}`,o=async()=>{let a=await this.call("GET","/v1/credential-encryption-key"),l=Ul(a,{provider:e,tenantId:t.tenantId,userId:t.userId,secret:n});return this.call("PUT",r,{secret_jwe:l})};try{return await o().catch(a=>{if(a instanceof D&&a.type==="urn:qupai:problem:stale-encryption-key")return o();throw a})}catch(a){throw a instanceof D&&a.status===400&&a.detail.includes("does not match this request")?new Li("this computer's clock is more than five minutes off: set it right, then save the key again"):a}};subsystemToken=e=>this.call("POST","/v1/subsystem-tokens",{audience:e});previewToolAction=async(e,t,i={})=>{let n=encodeURIComponent(e),r=await this.answer("POST",`/v1/threads/${n}/tool-actions/preview`,t);if(r.status!==202||!r.body||!("preview_job"in r.body))return Dl(r.body);let o=Pr(r.body.preview_job);if(!o)throw new Error("the server returned an incomplete hardware preview");i.onCompiling?.();let a=i.wait??((h,u)=>Gf(h,u)),l=i.now??Date.now,c=l();for(;o.state==="compiling";){if(l()-c>Nf)throw new je("The sandbox is still compiling this run after 10 minutes: close this and try again later","sandbox_compile_timeout");if(await a(i.pollMs??1500,i.signal),o=Pr(await this.call("GET",`/v1/threads/${n}/tool-actions/preview-jobs/${encodeURIComponent(o.id)}`)),!o)throw new Error("the server returned an incomplete hardware preview")}return Bl(o)};submitToolAction=(e,t)=>this.call("POST",`/v1/threads/${encodeURIComponent(e)}/tool-actions`,t);turnJobs=async e=>(await this.call("GET",`/v1/turns/${encodeURIComponent(e)}/jobs`)).items??[];cancelJob=e=>this.call("POST",`/v1/jobs/${encodeURIComponent(e)}/cancel`);uploadFile=async e=>{let t=js(e);try{return await this.postFile("/v1/files",e)}catch(i){throw i instanceof D&&i.status===413?new D(413,i.type,i.detail,`${t} is larger than the platform takes for an attachment`):i}};createThreadIn=(e,t,i,n)=>this.call("POST","/v1/threads",{product_id:e,agent_id:t,title:[...i].slice(0,200).join(""),scope:n});sendMessage=(e,t,i)=>this.call("POST",`/v1/threads/${encodeURIComponent(e)}/messages`,{id:zf(),input:{text:t,...i.length?{file_ids:i}:{}},delivery:"queue"});withdrawMessage=(e,t)=>this.call("DELETE",`/v1/threads/${encodeURIComponent(e)}/messages/${encodeURIComponent(t)}`);deleteThread=e=>this.call("DELETE",`/v1/threads/${encodeURIComponent(e)}`);threadFiles=e=>this.call("GET",`/v1/threads/${encodeURIComponent(e)}/sandbox/files`);notifications=(e=50)=>this.call("GET",`/v1/me/notifications?limit=${e}`);readNotifications=async e=>(await this.call("POST","/v1/me/notifications/read",e?.length?{ids:e}:{})).unread;lab=e=>this.call("GET",`/v1/labs/${encodeURIComponent(e)}`);labMachines=async e=>(await this.call("GET",`/v1/labs/${encodeURIComponent(e)}/machines`)).machines??[];requestLabAccess=(e,t)=>this.call("POST",`/v1/labs/${encodeURIComponent(e)}/access-requests`,t?{note:t}:{});withdrawLabAccess=(e,t)=>this.call("DELETE",`/v1/labs/${encodeURIComponent(e)}/access-requests/${encodeURIComponent(t)}`);places=e=>this.call("GET",`/v1/scopes/${encodeURIComponent(e)}`);placeFiles=e=>this.call("GET",`/v1/scopes/${encodeURIComponent(e.app)}/${encodeURIComponent(e.key)}/files`);artifacts=async()=>(await this.call("GET","/v1/artifacts")).items??[];artifact=e=>this.call("GET",`/v1/artifacts/${encodeURIComponent(e)}`);billing=()=>this.call("GET","/v1/billing/account");usage=(e,t)=>this.call("GET",`/v1/billing/usage?${new URLSearchParams({days:String(e),tz:t})}`);async postFile(e,t){let i=js(t),n=new FormData;return n.append("file",await Ef(t,{type:jf(i)}),i),(await this.answer("POST",e,n)).body}models=async()=>(await this.call("GET","/v1/models")).items??[];customization=(e,t)=>this.call("GET",zl(e,t));putCustomization=(e,t,i)=>this.call("PUT",zl(e,t),i);createMyAgent=(e,t,i)=>this.call("POST","/v1/agents",{product_id:e,agent_id:t,name:i});renameMyAgent=(e,t)=>this.call("PATCH",`/v1/agents/${encodeURIComponent(e)}`,{name:t});deleteMyAgent=e=>this.call("DELETE",`/v1/agents/${encodeURIComponent(e)}`);knowledgeBases=async()=>(await this.call("GET","/v1/knowledge-bases")).items??[];createKnowledgeBase=(e,t="")=>this.call("POST","/v1/knowledge-bases",{name:e,description:t});deleteKnowledgeBase=e=>this.call("DELETE",Gs(e));knowledgeDocuments=async e=>(await this.call("GET",`${Gs(e)}/documents`)).items??[];addKnowledgeDocument=async(e,t)=>{try{return await this.postFile(`${Gs(e)}/documents`,t)}catch(i){throw i instanceof D&&i.status===413?new D(413,i.type,i.detail,`${js(t)} is larger than the platform takes for a knowledge base`):i}};searchKnowledgeBase=async(e,t,i=5)=>(await this.call("POST",`${Gs(e)}/search`,{query:t,top_k:i})).items??[];connections=async()=>(await this.call("GET","/v1/connections")).items??[];connection=e=>this.call("GET",Ei(e));testConnection=e=>this.call("POST",`${Ei(e)}/test`);authorizeConnection=async(e,t)=>(await this.call("POST",`${Ei(e)}/authorize`,{return_to:t})).authorization_url;setConnectionEnabled=(e,t)=>this.call("PATCH",Ei(e),{enabled:t});deleteConnection=e=>this.call("DELETE",Ei(e));schedules=async()=>(await this.call("GET","/v1/schedules")).items??[];setScheduleEnabled=(e,t)=>this.call("PATCH",Er(e),{enabled:t});runScheduleNow=e=>this.call("POST",`${Er(e)}/run`);deleteSchedule=e=>this.call("DELETE",Er(e));goals=async()=>(await this.call("GET","/v1/goals")).items??[];goal=e=>this.call("GET",Lr(e));actOnGoal=(e,t)=>this.call("POST",`${Lr(e)}/${encodeURIComponent(t)}`);steerGoal=(e,t)=>this.call("POST",`${Lr(e)}/directives`,{text:t});workspaces=async()=>(await this.call("GET","/v1/workspaces")).items??[];workspace=e=>this.call("GET",Qs(e));openWorkspace=e=>this.call("POST",`${Qs(e)}/open`);closeWorkspace=e=>this.call("POST",`${Qs(e)}/close`);deleteWorkspace=e=>this.call("DELETE",Qs(e));async download(e,t){let i=await this.send("GET",e,void 0,{});if(!i.ok)throw this.refusal("GET",e,i.status,await i.text());let n=Df(qf(t),`.${js(t)}-${Vl(4).toString("hex")}`),r=0;try{let o=i.body?Kl.fromWeb(i.body):Kl.from([]);o.on("data",a=>r+=a.length),await Bf(o,Mf(n,{mode:420})),Lf(n,t)}catch(o){throw Of(n,{force:!0}),o}return r}async*follow(e,t,i={}){let n=t,r=this.retryMs,o=`/v1/turns/${encodeURIComponent(e)}/events`;for(;;){if(i.signal?.aborted)return;try{let a=await this.send("GET",`${o}?from=${n}`,void 0,{Accept:"text/event-stream"},i.signal);if(!a.ok||!a.body){let h=await a.text();throw a.status>=500||a.status===429?new dt(`the turn's events: ${a.status}`):this.refusal("GET",o,a.status,h)}let l=new TextDecoder,c="";for await(let h of a.body){c+=l.decode(h,{stream:!0});let[u,d]=Yf(c);c=d;for(let p of u)if(!(p.seq<=n)&&(n=p.seq,r=this.retryMs,yield p,Hf.has(p.event)))return}i.onRetry?.(new dt("the turn's stream ended early"))}catch(a){if(i.signal?.aborted)return;if(a instanceof D)throw a;i.onRetry?.(a instanceof Error?a:new Error(String(a)))}await Qf(r,i.signal),r=Math.min(r*2,1e4)}}},Hf=new Set(["complete","aborted","error"]),jl=(s,e)=>`/v1/threads/${encodeURIComponent(s)}/sandbox/file?${new URLSearchParams({path:e})}`,Gl=(s,e)=>`/v1/scopes/${encodeURIComponent(s.app)}/${encodeURIComponent(s.key)}/file?${new URLSearchParams({path:e})}`,Ql=(s,e,t)=>`/v1/artifacts/${encodeURIComponent(s)}/versions/${e}/files/${t.split("/").map(encodeURIComponent).join("/")}`,zl=(s,e)=>`/v1/products/${encodeURIComponent(s)}/agents/${encodeURIComponent(e)}/customization`,Gs=s=>`/v1/knowledge-bases/${encodeURIComponent(s)}`,Ei=s=>`/v1/connections/${encodeURIComponent(s)}`,Er=s=>`/v1/schedules/${encodeURIComponent(s)}`,Lr=s=>`/v1/goals/${encodeURIComponent(s)}`,Qs=s=>`/v1/workspaces/${encodeURIComponent(s)}`;function zf(s=Date.now()){let e=Vl(16);for(let i=0;i<6;i++)e[i]=Math.floor(s/2**(40-8*i))&255;e[6]=e[6]&15|112,e[8]=e[8]&63|128;let t=e.toString("hex");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}var Vf={".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".tsv":"text/tab-separated-values",".json":"application/json",".yaml":"application/yaml",".yml":"application/yaml",".xml":"application/xml",".html":"text/html",".htm":"text/html",".py":"text/x-python",".ipynb":"application/x-ipynb+json",".tex":"application/x-tex",".bib":"application/x-bibtex",".qasm":"text/plain",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".zip":"application/zip",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation"};function jf(s){let e=s.lastIndexOf(".");return e>0&&Vf[s.slice(e).toLowerCase()]||"application/octet-stream"}function Gf(s,e){return new Promise((t,i)=>{if(e?.aborted)return i(e.reason);let n=setTimeout(()=>{e?.removeEventListener("abort",r),t()},s),r=()=>{clearTimeout(n),i(e.reason)};e?.addEventListener("abort",r,{once:!0})})}function Qf(s,e){return new Promise(t=>{let i=setTimeout(t,s);e?.addEventListener("abort",()=>{clearTimeout(i),t()})})}function Yf(s){let e=[],t=s.split(/\r?\n\r?\n/),i=t.pop()??"";for(let n of t){let r="";for(let o of n.split(/\r?\n/))o.startsWith("data:")&&(r+=o.slice(5).trimStart());if(r)try{let o=JSON.parse(r);typeof o.seq=="number"&&typeof o.event=="string"&&e.push({...o,data:o.data??{}})}catch{}}return[e,i]}function U(s,e=""){return s&&(s.en||s.zh||Object.values(s).find(Boolean))||e}var le=(s,e)=>`${s}/${e}`,im=["general","specialist","lab"],sm=s=>s.kind&&im.includes(s.kind)?s.kind:"general";function nm(s){let e=s.default,t="",i="";if(typeof e=="string")[t="",i=""]=e.split("/");else if(e&&typeof e=="object"){let n=e;t=typeof n.product_id=="string"?n.product_id:"",i=typeof n.agent_id=="string"?n.agent_id:""}if(t)return i||(i=s.items.find(n=>n.product_id===t)?.agents?.[0]?.id??""),i?{product_id:t,agent_id:i}:void 0}function rm(s,e){return s.map(t=>{let i=e.flatMap(n=>{if(n.product_id!==t.product_id)return[];let r=t.agents?.find(a=>a.id===n.base_agent_id);return r?[{...r,id:n.id,name:{en:n.name},description:n.description?{en:n.description}:null,mine:{base:r.id}}]:[]});return i.length?{...t,agents:[...t.agents??[],...i]}:t})}function Zs(s){return s.filter(e=>e.available).flatMap(e=>(e.agents??[]).map(t=>({product:e,agent:t})))}function Xl(s){let e=s.agent.mine?.base??s.agent.id,t=s.product.agents?.find(n=>n.id===e)??s.agent;if(sm(t)==="general")return!0;let i=s.agent.tools??[];return!(i.length>0&&i.every(n=>n.available===!1))}function Yl(s,e){if(e)return s.find(t=>t.product.product_id===e.product_id&&t.agent.mine?.base===e.agent_id)}var om=s=>{let[e,t]=s?.split("/")??[];return e&&t?{product_id:e,agent_id:t}:null};function am(s,e,t,i){let n=Zs(s).filter(Xl),r=c=>c?n.find(h=>le(h.product.product_id,h.agent.id)===c):void 0,o=()=>r(e)??r(t?le(t.product_id,t.agent_id):null)??n[0];if(!i)return o();let a=n.filter(c=>c.agent.mine),l=r(e);return(l?.agent.mine?l:void 0)??Yl(a,om(e))??Yl(a,t)??a[0]??o()}function lm(s,e,t){return!!e&&s.product.product_id===e.product_id&&(s.agent.mine?.base??s.agent.id)===e.agent_id&&(!t||!!s.agent.mine)}function Or(s,e,t){let i=e.given||s.given===!0;return{products:rm(s.items??[],e.items),labs:t,fallback:nm(s),given:i}}function Jl(s,e){return{productId:e.product.product_id,agentId:e.agent.id,name:U(e.agent.name,e.agent.id),from:"product",isDefault:lm(e,s.fallback,s.given),productName:U(e.product.name,e.product.product_id)}}function Zl(s){if(s.agent)return{productId:s.agent.product_id,agentId:s.agent.agent_id,name:U(s.agent.name,U(s.name)),from:"lab",lab:s.id,labName:U(s.name,s.id),isDefault:!1}}function pt(s){let t=Zs(s.products).filter(n=>Xl(n)&&(!s.given||!!n.agent.mine)).map(n=>Jl(s,n));return[...[...t.filter(n=>n.isDefault),...t.filter(n=>!n.isDefault)],...Oi(s)]}function Oi(s){return s.labs.flatMap(e=>e.status==="paused"?[]:Zl(e)??[])}function qr(s,e){if(e&&"lab"in e){let n=s.labs.find(o=>o.id===e.lab&&o.status!=="paused"),r=n&&Zl(n);if(r)return r}let t=e&&"product"in e?le(e.product,e.agent):null,i=am(s.products,t,s.fallback,s.given);return i?Jl(s,i):void 0}function ec(s){return s.from==="lab"&&s.lab?{lab:s.lab}:{product:s.productId,agent:s.agentId}}var Js=class s{file;constructor(e){this.file=e}static key(e,t){return`${Ys(e)} ${t}`}read(){if(!this.file)return{};try{let e=JSON.parse(Jf(this.file,"utf8"));return e.picks&&typeof e.picks=="object"?e.picks:{}}catch{return{}}}get(e,t){let i=this.read()[s.key(e,t)];return i&&"lab"in i&&typeof i.lab=="string"?{lab:i.lab}:i&&"product"in i&&typeof i.product=="string"&&typeof i.agent=="string"?{product:i.product,agent:i.agent}:null}set(e,t,i){if(!this.file)return!1;try{let n={...this.read(),[s.key(e,t)]:i};Xf(tm(this.file),{recursive:!0,mode:448});let r=`${this.file}.${process.pid}.tmp`;return em(r,`${JSON.stringify({picks:n},null,2)}
|
|
109
|
+
`,{mode:384}),Zf(r,this.file),!0}catch{return!1}}};function qi(){return{parts:[],state:"running",lastSeq:0,role:"assistant",open:{}}}var _e=s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},j=s=>typeof s=="string"?s:"";function cm(s){return typeof s=="string"?s:Array.isArray(s)?s.map(e=>{let t=_e(e);return t.type==="text"?j(t.text):t.type==="image"?"[image]":""}).filter(Boolean).join(`
|
|
110
|
+
`):""}function Dr(s,e){for(let t=s.parts.length-1;t>=0;t--){let i=s.parts[t];if(i&&i.kind==="tool"&&i.id===e)return i}}function Br(s,e){if(e.seq<=s.lastSeq)return s;s.lastSeq=e.seq;let t=_e(e.data);if(s.state==="awaiting_approval"&&e.event!=="interrupt"&&e.event!=="ping"){s.state="running";for(let i of s.parts)i.kind==="tool"&&i.state==="waiting"&&(i.state="running")}switch(e.event){case"message_start":s.role=_e(t.message).role==="user"?"user":"assistant",s.open={};break;case"content_block_start":{let i=typeof t.index=="number"?t.index:0,n=_e(t.content_block);if(n.type==="text"&&s.role==="assistant")s.parts.push({kind:"text",text:j(n.text)}),s.open[i]=s.parts.length-1;else if(n.type==="tool_use"||n.type==="server_tool_use"||n.type==="mcp_tool_use"){let r=n.input&&Object.keys(_e(n.input)).length?JSON.stringify(n.input):"";s.parts.push({kind:"tool",id:j(n.id),name:j(n.name)||"tool",input:r,args:r?n.input:void 0,state:"running"}),s.open[i]=s.parts.length-1}else if(n.type==="tool_result"||n.type==="mcp_tool_result"){let r=Dr(s,j(n.tool_use_id));if(r){r.result=cm(n.content),r.state=n.is_error===!0?"failed":"done";let o=_e(n.qupai);if(o.structured_content!=null||o.meta!=null){let l=Array.isArray(n.content)?n.content:typeof n.content=="string"?[{type:"text",text:n.content}]:[];r.resultData={content:l,structuredContent:o.structured_content??void 0,_meta:o.meta??void 0}}let a=_e(o.resolved_input);a.arguments&&typeof a.arguments=="object"&&!Array.isArray(a.arguments)&&(r.resolvedArgs=a.arguments)}}break}case"content_block_delta":{let i=s.open[typeof t.index=="number"?t.index:0],n=i===void 0?void 0:s.parts[i],r=_e(t.delta);n?.kind==="text"&&r.type==="text_delta"&&(n.text+=j(r.text)),n?.kind==="tool"&&r.type==="input_json_delta"&&(n.input+=j(r.partial_json));break}case"content_block_stop":{let i=s.open[typeof t.index=="number"?t.index:0],n=i===void 0?void 0:s.parts[i];if(n?.kind==="tool"&&n.input&&n.args===void 0)try{n.args=JSON.parse(n.input)}catch{n.args=n.input}break}case"tool_progress":{let i=Dr(s,j(t.tool_use_id));i&&j(t.message)&&(i.progress=j(t.message));break}case"interrupt":{let i=j(t.tool_use_id),n=j(t.interrupt_id)||i||`seq-${e.seq}`;s.parts.some(o=>o.kind==="interrupt"&&o.interruptId===n)||s.parts.push({kind:"interrupt",type:j(t.kind)||"tool_approval",interruptId:n,toolCallId:i,tool:j(t.tool)||void 0,seq:e.seq,detail:_e(t.detail)});let r=Dr(s,i);r&&t.kind!=="ask_user_question"&&(r.state="waiting"),t.kind!=="ask_user_question"&&(s.state="awaiting_approval");break}case"input":s.parts.push({kind:"input",text:j(t.text)});break;case"title":s.title=j(t.title)||s.title;break;case"complete":s.state="complete";break;case"aborted":s.state="aborted";break;case"error":s.state="error",s.error=j(t.message)||j(t.reason)||"the turn failed",s.errorCode=j(t.code)||void 0;break}if(s.state!=="running"&&s.state!=="awaiting_approval")for(let i of s.parts)i.kind==="tool"&&(i.state==="running"||i.state==="waiting")&&(i.state=s.state==="complete"?"done":"failed");return s}function Nr(s,e){let t=qi();for(let i of s)Br(t,i);return e==="succeeded"&&t.state==="running"&&(t.state="complete"),e==="failed"&&t.state==="running"&&(t.state="error"),e==="cancelled"&&t.state==="running"&&(t.state="aborted"),e==="awaiting_approval"&&(t.state="awaiting_approval"),t}function en(s){if(s.state==="awaiting_approval")for(let e=s.parts.length-1;e>=0;e--){let t=s.parts[e];if(t?.kind==="interrupt"&&t.type!=="ask_user_question")return t}}function tc(s,e){let t=n=>typeof n=="string"?n:typeof n=="number"||typeof n=="boolean"?String(n):"",i=_e(s);for(let n of["command","query","path","file_path","url","pattern","prompt","code","description","instrument","op"])if(t(i[n]))return t(i[n]).replace(/\s+/g," ");for(let n of Object.values(i))if(t(n))return t(n).replace(/\s+/g," ");return(typeof s=="string"?s:e).replace(/\s+/g," ")}var hm="qupai-device-catalog",Qe=class extends Error{status;code;constructor(e,t,i){super(i),this.status=e,this.code=t}};function um(s,e,t){let i=r=>r.trim().replace(/\/+$/,""),n=t?.trim()?[i(t)]:[];for(let r of[e,s])r&&n.push(`${i(r)}/qdev-api`);return[...new Set(n)]}var tn=class{platform;fetchFn;addresses;base;token;constructor(e){this.platform=e.platform,this.fetchFn=e.fetch??fetch.bind(globalThis),this.addresses=um(e.platform.server,e.web,e.override)}get address(){return this.base}async bearer(e=!1){if(!e&&this.token&&Date.now()<this.token.until)return this.token.value;let t=await this.platform.subsystemToken(hm),i=Date.parse(t.expires_at);return this.token={value:t.token,until:(Number.isFinite(i)?i:Date.now()+5*6e4)-3e4},t.token}async request(e,t,i,n){for(let r=0;;r++){let o=await this.bearer(r>0),a=await this.fetchFn(e+i,{method:t,headers:{Authorization:`Bearer ${o}`,Accept:"application/json"},signal:n});if(a.status===401&&r===0){await a.body?.cancel();continue}return a}}async read(e,t,i){let n=this.base??await this.locate(i),r;try{r=await this.request(n,e,t,i)}catch(a){throw i?.aborted?a:new Qe(0,"unreachable",`the device information service at ${n} does not answer`)}let o=await r.text();if(!r.ok){let a="service_unavailable";try{a=JSON.parse(o).code??a}catch{}throw new Qe(r.status,a,ic(r.status,a))}return JSON.parse(o)}async locate(e){await this.bearer();let t;for(let i of this.addresses){let n;try{n=await this.request(i,"GET","/v1/providers",e)}catch(o){if(e?.aborted)throw o;continue}let r=n.headers.get("content-type")??"";if(n.ok&&r.includes("json")){let o=await n.json().catch(()=>null);if(o&&Array.isArray(o.providers))return this.base=i,i;continue}await n.body?.cancel(),(n.status===401||n.status===403)&&r.includes("json")&&(t=new Qe(n.status,"forbidden",ic(n.status,"forbidden")))}throw t||new Qe(404,"not_found",`this platform shows no device information where the app looks for it (${this.addresses.join(", ")}): the web app's Compute is where hardware runs start there, or set QUPAI_DEVICES_URL`)}providers=async e=>(await this.read("GET","/v1/providers",e)).providers??[];catalog=(e,t)=>this.read("GET",`/v1/providers/${encodeURIComponent(e)}/devices`,t);refreshCatalog=(e,t)=>this.read("POST",`/v1/providers/${encodeURIComponent(e)}/refresh`,t);capabilities=(e,t,i)=>this.read("GET",`/v1/providers/${encodeURIComponent(e)}/devices/${encodeURIComponent(t)}/capabilities`,i)};function Di(s,e=Date.now()){if(!s||!["queued","running"].includes(s.refresh.state))return!1;let t=Date.parse(s.refresh.retry_at??"");return Math.max(1e3,Number.isFinite(t)?t-e:0)}function ic(s,e){switch(e){case"credential_missing":return"no key is saved for this provider";case"credential_invalid":return"the provider did not accept your saved key: save it again";case"provider_not_supported":return"the device service lists no devices for this provider";case"catalog_unavailable":return"the device list has not been read yet: try again in a moment";case"rate_limited":return"the device service is busy: try again in a moment";case"feature_disabled":return"your organization has not enabled this provider"}return s===401||s===403?`the device information service refused the sign-in (${e||s})`:s===429?"the device service is busy: try again in a moment":`the device information service answered ${s}${e?` (${e})`:""}`}import{statSync as dm}from"node:fs";import{homedir as rc}from"node:os";import{basename as pm,extname as sc,isAbsolute as fm,join as mm,resolve as nc}from"node:path";import{fileURLToPath as gm}from"node:url";var Fr=20;function ce(s){return s<1e3?`${s} B`:s<1e6?`${(s/1e3).toFixed(1)} KB`:s<1e9?`${(s/1e6).toFixed(1)} MB`:`${(s/1e9).toFixed(1)} GB`}function re(s){let e=s/1e6;return s!==0&&s>-1e4&&s<1e4?`\xA5${e.toFixed(4)}`:`\xA5${e.toFixed(2)}`}function X(s){if(s==null||s==="")return"-";let e=typeof s=="number"?new Date(s*1e3):new Date(s);if(Number.isNaN(e.getTime()))return"-";let t=i=>String(i).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}`}function oc(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return"UTC"}}function Gt(s,e,t=rc()){let i=s;if(/^file:\/\//i.test(i))try{i=gm(i)}catch{}return i==="~"?i=t:i.startsWith("~/")&&(i=mm(t,i.slice(2))),fm(i)?nc(i):nc(e,i)}function Wr(s){let e=[],t="",i="",n=!1;for(let r=0;r<s.length;r++){let o=s[r];if(i){o===i?i="":o==="\\"&&i==='"'&&r+1<s.length&&/["\\$`]/.test(s[r+1])?t+=s[++r]:t+=o;continue}o==="'"||o==='"'?(i=o,n=!0):o==="\\"&&r+1<s.length?(t+=s[++r],n=!0):/\s/.test(o)?(n&&e.push(t),t="",n=!1):(t+=o,n=!0)}return i?[]:(n&&e.push(t),e)}function Ur(s,e,t=rc()){let i=s.trim();if(!i||i.includes(`
|
|
111
|
+
`))return null;let n=Wr(i);if(!n.length)return null;let r=[];for(let o of n){if(!/^(\/|~|file:\/\/|\.{1,2}\/|[A-Za-z]:[\\/])/.test(o)&&!o.includes("/"))return null;let a=Gt(o,e,t);try{if(!dm(a).isFile())return null}catch{return null}r.push(a)}return r}function ac(s,e){let t=pm(e||"artifact"),i=s.replace(/[\x00-\x1f\x7f/\\:*?"<>|]+/g," ").replace(/\s+/g," ").trim().replace(/^\.+/,"");if(!i)return t;let n=sc(t);return n&&sc(i).toLowerCase()!==n.toLowerCase()?`${i}${n}`:i}function sn(s){return s.qupai_staff?"staff":s.my_role?String(s.my_role):s.access_request==="pending"?"none (asked)":s.access_request==="declined"?"none (declined)":"none"}var nn=s=>!!s.my_role||!!s.qupai_staff;function Kr(s){return s==="real"?"lab PC":s==="api"?"API":s}function bm(s){return s.occupancy==="held"?"busy":s.occupancy==="watch"?"watch only":s.health||"unknown"}function ym(s){let e=s.holder;return e?`${e.kind==="external"?"outside the platform":e.kind}: ${e.label}${e.by?` (${e.by})`:""}${e.other_org?", another organization":""}, since ${X(e.since)}`:""}function lc(s,e,t){let i=[`Lab ${U(s.name,s.id)} (${s.id})`,...s.provider&&s.provider.name?[`Run by ${s.provider.name}`]:[],...s.field?[`Field ${s.field}`]:[],`Your role ${sn(s)}`,`Status ${s.status}`,`Connected by ${Kr(s.connection)}`,`Access ${s.access==="open"?"open to every member":"the people QuPai staff let in"}`,`Its agent ${s.agent?`${U(s.agent.name,s.id)} (Enter in /lab talks with it)`:"none offered to you"}`,`In the app ${Hr(t,s.id)}`,""];if(typeof e=="string")return[...i,`Machines: ${e}`];if(!e.length&&s.connection==="api")return[...i,`Machines: an API lab's devices come from the device information service (qupai device list${s.provider_ref?` -provider ${s.provider_ref}`:""} shows them).`];if(!e.length)return[...i,"The lab reports no machines."];i.push("Machines");let n=o=>e.some(a=>a.id===o),r=(o,a)=>{let l=[`${a}${o.name||o.id}`,[o.kind,o.mode].filter(Boolean).join(", "),bm(o)];o.queue&&l.push(`queue ${o.queue.count}`);let c=[l.filter(Boolean).join(" \xB7 ")],h=ym(o);h&&c.push(`${a} held by ${h}`);for(let u of o.holds??[])(!o.holder||u.by!==o.holder.label)&&c.push(`${a} holds ${u.what} for ${u.by}`);return o.note&&c.push(`${a} ${o.note}`),c};for(let o of e)if(!(o.twin_of&&n(o.twin_of.machine))){i.push(...r(o," "));for(let a of e)a.twin_of&&a.twin_of.machine===o.id&&i.push(...r(a," twin "))}return i}function Hr(s,e){return`${s.replace(/\/+$/,"")}/lab/machines?${new URLSearchParams({lab:e})}`}var wm=/^0{8}-0{4}-0{4}-0{4}-0{12}$/;function cc(s){return s.thread_id&&!wm.test(s.thread_id)?{thread:s.thread_id}:s.place?.app==="lab"&&s.place.key?{lab:s.place.key}:null}function Bi(s){return{answer_ready:"answer ready",answer_failed:"answer failed",approval_needed:"approval needed",job_finished:"job finished",woken:"woken by a job",goal_waiting:"goal waiting",goal_stalled:"goal stalled",goal_ended:"goal ended",lab_access_requested:"lab access asked",lab_access_granted:"lab access given",lab_access_declined:"lab access declined",lab_access_removed:"lab access removed"}[s]??s.replaceAll("_"," ")}function xe(s,e){let t=s.split(/\s+/).filter(Boolean).join(" "),i=[...t];return i.length<=e?t:`${i.slice(0,e-1).join("")}\u2026`}var hc={brand:Ke(22,131,255),needs:Ke(217,154,0),stopped:Ke(138,144,153),failed:Ke(201,52,63),ok:Ke(46,157,91),muted:Ke(138,144,153)};function xm(s=process.env){return typeof s.NO_COLOR=="string"&&s.NO_COLOR!==""}function zr(s={}){let e=s.color??!xm(),t=s.mode??jn(),i=(n,r)=>n&&Pt(n,r,t);return{color:e,tone:(n,r)=>e&&n?Pt(n,{fg:hc[r]},t):n,bold:n=>i(n,{bold:!0}),dim:n=>e?i(n,{dim:!0}):n,italic:n=>i(n,{italic:!0}),inverse:n=>i(n,{inverse:!0}),wordmark:()=>e?Pt("QuPai",{fg:hc.brand,bold:!0},t):Pt("QuPai",{bold:!0},t)}}function uc(s){return{heading:e=>s.bold(s.tone(e,"brand")),link:e=>s.tone(e,"brand"),linkUrl:e=>s.dim(e),code:e=>s.tone(e,"brand"),codeBlock:e=>e,codeBlockBorder:e=>s.dim(e),quote:e=>s.italic(e),quoteBorder:e=>s.dim(e),hr:e=>s.dim(e),listBullet:e=>s.tone(e,"brand"),bold:e=>s.bold(e),italic:e=>s.italic(e),strikethrough:e=>e,underline:e=>e}}function rn(s){return{selectedPrefix:e=>s.tone(e,"brand"),selectedText:e=>s.bold(s.tone(e,"brand")),description:e=>s.dim(e),scrollInfo:e=>s.dim(e),noMatch:e=>s.dim(e)}}function on(s){return{borderColor:e=>s.tone(e,"brand"),selectList:rn(s)}}function dc(s){return{fallbackColor:e=>s.dim(e)}}var pc="iVBORw0KGgoAAAANSUhEUgAAARgAAAEYCAYAAACHjumMAAAQ1UlEQVR42u2d3ZGjShKF2wSe5lkmYAImyIQyAROIGAMwARNkAiZgAiZgQm/cWHqvordnhCSqKk/m93De9s6qUekj8+RPffz6/fmBEEI5xENACAEYhBCAQQghAIMQAjAIIQCDEEIABiEEYBBCAAYhhAAMQgjAIIQADEIIARiEEIBBCAEYhBACMAg5UvPr92f3TS2AQQgdVbuDY/j1+3P69ftz/vX7c/v1+/PzSS37f/uPbvu/94+u+7/fABiE/OpyB5LbDoTPwtr2/++0fx4Ag5BoavNP5DC+EZGU0LzDpgEwCNmOTtKe4qxGYfIoshnOBg0HA6HXdRUGShHQcEgQej5KuTkCyp+07n4RgEEoM1T6SoasBY0ABqHzDdrIUPmp/N0AGITeg0qU9KcYZDhYKLq63ajdgMj5kOGAocgp0Ao08kKGw4aiteQTrbyvCcAg9K8Shu3pugIYFD0NGohWsjbkNQAGRexbGQGLjR4ZDiTyBJaJH31xXQAM8l5mnvmh24xiOKAIsKB3vRgAgwALyqYEYJAHjwWwiPXFcHAR5i3KliZxgBFgQWeoBTCIBjmUSz2AQQot/QwgOvJhONTISmWIWSFtzQAGURlCRY1eDjmq6bPww/QlAIOq64rPAmAQIh1Cbw8+cvAR6RA6Sx2AQaRDCMAg+aiF6z/o5gUw6HT1dOFi8gIYhImLAAwiakEABsW9Z4ioBTEqgE4XpWcEYFAWr4XBxP8+g3kH7bCX5Ltdlx+qat2d+v2/mR2llgOAQXgtrw3xzXcQaTNBO+2lfdXnmwAMeqevJYrXsu67TdKjO38yPmvFq247AINe7cb1HrXc9ujsYuzZK+3JYScvohv3W5RyJTU9zY8CMOipN+fqECpjJg+lVEuA1Whm9ASYZn/zDPsbdt61fiuZ3eu70w9EYpSfN7FI5cjZtwiZqzpgchhf36sDF1IiN0bu/LfbBoHM6WpUAVP6CovtzvBrg6VEm4MUaAjyorgY+r6Wv31WdokcC7HT3ygtrpFoRba6Z7bBzjpgRsNuee/kLanekTuR1ppIaVslwCj5AItwZKPa2/KVBjWY8f97SZi8k9oiYBrhN+okVJ0aRcGSAIq5KGZSAoyHi84Xwz8ExSrRAlgeKlksT1sDTO9wQM5SKN+KNc7N9Cs99eIwmR5ZAUzjeNZlM2BGJsBCmlQjPbICmCiLi0qDphFKO1fAIvcb6lQAE22/yFSgiU+lBI15qxmlrkc/G81C/tIBha7cDbCc/p2bGG60BpgxMGDud5Fcgvgt1sxvT8vXq95BbRUwbKQ/z6OZ8KBCq+pyb6uA4d7in2c7mifN3Nl4KtgCADeASUqAASh/TiWuB0PjFQMXWep9ATA6kGlE54nwWXw2240Axg9cWsHO5xmfxXUV6QJgfMwzNWJmLmVn/4C5vfLZAIwOXKyauSPpUIhGu04RMJSpj812WFxlQXt/nFGB+dXPBmCMX/uwezEbJi76i26WStN08grc6Wu07X+hp8WklsyR6ocqYIbglaJOqO1/4IccsgcmKQOmowxtHrxELXErSOu7ny/qNi7K0Jkaq5CrLCCpAybaPNKjMvREhQgZKZSsZ3w+ln2XLUM3AmXoGxUi/JezGiejb0Wnx4VuXG53zBS9WAHMJTBcrKy2xMjV1GQ5erF0bcniFC6DQAMdrf662ixHL5YAMwZroLMAl6M7Z1CsNZnJI2DaQHCx0J1LSkR69Kdz8eERMJ7K1cm4oT0dSIla0qaQ6VHnGTAjcMmu/kDj43iXQvX8kMNUj+YcnzXy1Qsl/Yxk4PN1B57/QjoVdnr64h0wqtWkR3NFyYDf8ujwpAMhN8OONnTJVEn8iACYBFyKd+VOJ8MKac0ebTn9Novb0TfgUmS9wqsdxHT8+iqGZPXZInUnRoJLOuC3bAWiI2Q7wl9yf+YoOWZJuIzGzdx0ctcnBrDu5HQXETCWd/Vavq/oyI99rFT+RvYWS00lPnf0i6S8pEWPlliVuPKElEnnpbuV+q4iLtLxBpf5wWFpC5b/SZk0bINiEWf0y6TU4TIVMHOpMvkqfCwlP3vUdYAR4FIb0BNgMBm9tADGhhdjGS5JJPqjMc9W9FK8GzvyUmOvcBkNmuMsEK8fvaw1TPjo9754g8tXqdxiNzSl7LrRSxXIR989qgKXZ43Ti9HB0YlSdpXopdr9VpEnSJ+FS601l9sbxpzFq3nxZcpaA2tNqEeeIn3GXVeES40+mJJ/F127x1R177LSQ885aZ2cwsV6NEO/TN7opXqrQPRp0keHvHECF8vRDPdf5znjqwW/K/pMxiO4LE7TB2vRDHNM/565Vblq5AEwHXA5LZpZMX9d+oxmosKo/QFjcLj8dIsA5m/9SunmJTVSB8w73siUGV6KP6yroea8qMOSU4FqKIB5Qj1wOR3aMxUm6bTf3M0P6l/M8mSO3xjcRtc6ADcT2fWv65kt/m1RyP8ILom3tFkDeMLYPRQFXwBMndz1yAgAcPk5ZboZgczstIx9lrF7tfo3eukd2F7sB6jVpZuce1019g4r6uY9wvPyRfVCXbq9aCq6AZnTK3fun4fn+Q2LvS6TeKRoYczAw2LxMzp2JXqGvOaz05MwAi72dvN4bsgbo6TZHgfFLPa6LA6fM5Cp1/Mi87JiUhXf4J1S9gZkntYa6TyxxCe/X+B5StjCas7Ncpn25J4XOaBGgUutC8giDO5Z6ZdJAmcw3PgEOzbyKdpVHROQyToOIFkkYM6DRjpv5m9ymBrJFgl4q56vIShcLK1+SI5So015EZfng97T6xK6wpScpOfSqbbntyjlaCaya0NmDDhW4h4wl0oVI+Bic7ygFmQ6omF/gKlxoLlEDMicPUjrJhrG1KViBGRsrWHYPN2ugKnLpWGRemWuAufQVf8UYwDOdqACmarp7LvVM3fRcISNdswYAZlSkFlocfAHGExdIGPhOxyJhv0BBlOX788CZBIVI3+ASXTqAhkD/Uvv+C7uo2Fa0eNupQMy70cQ744CuJ+4p6ciYG8CkDkNMjdSbX+AmZz2T9CMV7cZ71mjdaB/yh9gEs10QMaAx9bi4/kDDL4LkLECmZ6KkS/AMMQYS5fK+2SOrEmYgYsfwNDvwtIqa9//My+9sEUCfJefdeMHHnbG7F7tCZFW6EiYtxhzRrxg3oPDozMaugLJnBHXjShorAiZIy+cjjRbDzADJWl0UlNbiUa8xO0SOoDpKh0ifshUEt8pXydm1uwDptZNjJSkKV+fcedVz/dkGzBcloYsV5ZoXxAGzNVYatTsDVXMItlSb7yyhAwCplb42x6sXvDmwvTlHixhwMzGUqOOngbzpu8quOIBwAQJedcHh3cjPJYYJ/gUmL4GMAEPSfdiYxeQwY9xdX+0d8Asxt48HTk4fgwtDj4AMxg06FZycEk/ZsP0BTAWUqN0IvCYuqY/hk5wo4CpkRrNGd6CGH0MRTLLZgwwg0Fjt8Hoo3TNgnh9wNRqqDsSaUy0kJMq0emrDZjZsAn3Lvw4WKRKFAAqAqY3PAV7RvrG24tUCT+mEmBqlRLXwgY0kCFVwo+pAJib0Hj9u7uAuWqWBjzOQUHAdIK9CT15OAuq6I/RAMxqsCxd4g0IZOprMJAqDQDG3xc8GzELgUx9rQYg0wGYPCGq+hfaUraU19UAYFaujvVjss0n/x09kJHXbAAyE4DxUSbMEY5OQIayNaVrO4BZnUQv937MAmSkNRkATKjVDh63jOU00866K3uhGa9a2dpCFHMDMJrLf1Yhw5CO37hRTJhUydugWamJ5h7IEMWQKpUHzKVyGVDxTbgxsxI2ipkAjM4XV6NbchGMvpCdKMZ9A56nMmCNobKz1wJwR3asvhj3DXhevrCaoWZ7sqnNjt9YfTGuXyxevqyrs8M60ysjl+IqRuAygJkDmbt/Usow5k+FSes7s9ggKg+Y2tGLpdWEY4ZSJpDxt2UxjNHvwSyzFlpOHDxK1hi+5wCG2/TKQRfzN59J/4nhaxMwM19G1sFIBiXjLKRyafiql/la4/n9kqnFvAMKboZzXUerisuk7n9okU1Erqv12dnrqsNX+Qu5CeX4W8ZnQMrkryfGTdla2XnvxYzELWPlgVK27nJ61ysdlHsH1ELINvNzI2XyVU2y1ERaFDBWDLFG9BBvmcNqUiY/1ST5HijVL2ETf1NumZ8N+2X0m+5cRDG11kVGN8DaAmnmSDQjPZvkIopRJfzsJOffCrz96JnR9mGko5hnzV0rD3x0dKA3npcpfRLF1AGMpW7Hwdlbcyv0FiSa0dl05yKKUW1E8rYBrCn4fPFmyq7cCN3dq9pK7XHFYEnIEM1oNdzJeo+qw2Cz08PdFA7Rb15XNTrZ1Ss/ac2cBv0YG13AUoCZvAHG4qTphheQZdcMaZN9wEjdCKmYHimPCig0fk2kTaYBI1WyVtj7Evry8P3v3Cq8JYfA1SbrgFk8AcbqQ47UPNZWmgHbAi4cbwQAI2P2Kueja8CDv1R81h0eDC/YswEzGH/IEU3JqXL1rgMwvGDPAsxs/CHPQT2C3sBz73i2LL1/FzCbwEOOWlrtDHw/HkFzEwLMqAyYi8hDXoIC5us7WoxEkl5AswoBZlUGTAfJZczfyRDsE/4L1aQjgBnEHrS3cmq7g/PovFBv7M2q2EczCQImqQJm5GFXg8r6Qz9Ke/C/txTib/uPthVJNz8FdVMFzCz6wJMTqLz6tzVGv7vZ+Hejet5XAFOH6o0TqLw6TWs1xbUY1QzCZ930XJ7yPIZSm3uzzxRNJ6UwR+8/6oxXRdbdO6ppVCYHZ70DMPUNx0sFoIwZy8jLwb+pEentWCrAZnJyxgcAY8cH6E8mfrvDZNh/yGvhKO1oqtGLvRTGjBPzSazfRbZNIxpgfnprzjschjv4fNdwp2n/b6zccNk+CcNF9MUw7MC5vPEi6J2BxfzITHTAqB+qV39so5O///YN/sMPL4TZKVQADDK9Q7cL8MOLJACDzJXfG0dGJ4ChDwYZXfh0FZmcRwAGZdiNW6q0fuOZAxiGHWNoqtShSTQDYIoAJvGlhd2t0jipNAEYFk6hO5/F2jAglSYAk3VlJofLl8/yajRDusxEdRbAECbnnyFRWcp0wfin0S7SvUjqBq7q9awJE9jkeZK92XHhCwQsNOgxTZ0LMFSTAMvfBghJm9gH8xZgMHsBS7T1B1SQCgPmypf4VFVoDAKWn6pN+DMYvE8D5oM2crdXdeSoNuHPlFPvBTANb6c/Lq1KwaHypwok/kx+XbwA5svUAzL/+istIKEbuPL6jg9PgIleVfpaTN0ADoxgA7p6BEy0SGYjWgE0jAeUBYzFa0pzpEBXgABoiF7qAMZbR+e257SJFIjSNqVpG4BRN/JWIhUiGsEX4SUaYO4PySJA/x5PBdCISqolIueMymQg9N3uLu3q+PHSR8PUtA/AfD8oY4HDsp50AyCiM9hqi8QHgHnuLueva1jnB9HOdve/m7/d4kdkEscQ7oOmT4tq4YGDixR1DTQbd1OuanJYkXr65DmqGdW/Iw4p8rT8anLSU7N5aZ3gYCKvKZQqbEZPjZ4cRhSh3D0K9Ge53H7IAUTRPJu0/5hXI53krrcfcuhQdN8mFerTui85j1HGUzhkCP1/lNPt1anhDj5fWg6Monzptv8b/f5vhhui5UAhhAAMQgjAIIQQgEEIARiEEIBBCCEAgxACMAghAIMQQgAGIQRgEEIABiGEAAxCCMAghAAMQggBGIQQgEEIARiEEHpN/wF1mouh7lkMKgAAAABJRU5ErkJggg==",fc=[" \u28C0\u28E4\u28E4\u28E4\u2840"," \u2880\u28E4\u28C4\u28C0 \u28E0\u2876\u281F\u281B\u2809\u2819\u28FF\u2847"," \u2808\u28BF\u289F\u28F5\u281F\u28AD\u28C4 \u2880\u285F"," \u28E0\u285F\u2801 \u2819\u28B7\u28C4\u2820\u280B"," \u28FC\u284F\u2818\u28A6\u2840 \u2839\u28F7\u2840","\u28B8\u28FF\u28E6\u28C0\u28E0\u281D\u2836\u28E4\u28C0\u28E0\u28FF\u28F7","\u2808\u2809\u2809\u2801 \u2809\u281B\u281B\u280B"],Ni=[[" \u28C0\u28E4\u2844"," \u2816\u2809\u2801","","","","",""],[" \u28C0\u28E4\u2844"," \u2860\u2816\u2809\u2801"," \u2880\u2874\u280B"," \u2809","","",""],[" \u28C0\u28E4\u2844"," \u2860\u2816\u2809\u2801"," \u2880\u2874\u280B"," \u2860\u280B"," \u287C\u2801","\u2818\u2803",""],[" \u28C0\u28E4\u2844"," \u2860\u2816\u2809\u2801"," \u2880\u2874\u280B"," \u2860\u280B"," \u287C\u2801","\u28B8\u28C7","\u2808\u2809\u2809\u2801"],[" \u28C0\u28E4\u2844"," \u2860\u2816\u2809\u2801"," \u2880\u2874\u280B"," \u2860\u280B"," \u287C\u2801","\u28B8\u28C7\u28E0\u28C0\u28E0\u2804","\u2808\u2809\u2809\u2801"],[" \u28C0\u28E4\u2844"," \u2860\u2816\u2809\u2801"," \u2880\u2874\u280B"," \u28E0\u285F"," \u28FC\u284F","\u28B8\u28FF\u28E6\u28C0\u28E0\u2804","\u2808\u2809\u2809\u2801"],[" \u28C0\u28E4\u2844"," \u28E0\u2876\u2809\u2801"," \u2880\u28F4\u281F\u2809"," \u28E0\u285F\u2801"," \u28FC\u284F","\u28B8\u28FF\u28E6\u28C0\u28E0\u2804","\u2808\u2809\u2809\u2801"],[" \u28C0\u28E4\u2844"," \u28E0\u2876\u281F\u281B\u2809\u2819\u2877"," \u2880\u28F4\u281F\u288D \u2801"," \u28E0\u285F\u2801"," \u28FC\u284F","\u28B8\u28FF\u28E6\u28C0\u28E0\u2804","\u2808\u2809\u2809\u2801"],[" \u28C0\u28E4\u2844"," \u28E0\u2876\u281F\u281B\u2809\u2819\u2877"," \u2880\u28F4\u281F\u288D \u2880\u2803"," \u28E0\u285F\u2801 \u2819\u28A6\u2840\u2820\u2801"," \u28FC\u284F \u2831\u2804","\u28B8\u28FF\u28E6\u28C0\u28E0\u2804","\u2808\u2809\u2809\u2801"],[" \u28C0\u28E4\u2844"," \u28E0\u2876\u281F\u281B\u2809\u2819\u28F7\u2846"," \u2880\u28F4\u281F\u288D \u2880\u285F"," \u28E0\u285F\u2801 \u2819\u28A6\u2840\u2820\u280B"," \u28FC\u284F \u2831\u2844","\u28B8\u28FF\u28E6\u28C0\u28E0\u2804 \u2824\u28C0\u28E0\u28F7","\u2808\u2809\u2809\u2801"],[" \u28C0\u28E4\u28E4\u28E4\u2840"," \u2844 \u28E0\u2876\u281F\u281B\u2809\u2819\u28FF\u2847"," \u2880\u28F4\u281F\u288D \u2880\u285F"," \u28E0\u285F\u2801 \u2819\u28A6\u2840\u2820\u280B"," \u28FC\u284F\u2808\u2822\u2840 \u2831\u2844","\u28B8\u28FF\u28E6\u28C0\u28E0\u280C\u2812\u2824\u28C0\u28E0\u28F7","\u2808\u2809\u2809\u2801"],[" \u28C0\u28E4\u28E4\u28E4\u2840"," \u2880\u2844 \u28E0\u2876\u281F\u281B\u2809\u2819\u28FF\u2847"," \u2808\u281F\u2880\u28F4\u281F\u288D \u2880\u285F"," \u28E0\u285F\u2801 \u2819\u28A6\u2840\u2820\u280B"," \u28FC\u284F\u2818\u28A6\u2840 \u2831\u2844","\u28B8\u28FF\u28E6\u28C0\u28E0\u281D\u2812\u2824\u28C0\u28E0\u28F7","\u2808\u2809\u2809\u2801"],[" \u28C0\u28E4\u28E4\u28E4\u2840"," \u2880\u2844 \u28E0\u2876\u281F\u281B\u2809\u2819\u28FF\u2847"," \u2808\u28BF\u2886\u28F4\u281F\u288D \u2880\u285F"," \u28E0\u285F\u2801 \u2819\u28A6\u2840\u2820\u280B"," \u28FC\u284F\u2818\u28A6\u2840 \u2831\u2844","\u28B8\u28FF\u28E6\u28C0\u28E0\u281D\u2836\u28E4\u28C0\u28E0\u28F7","\u2808\u2809\u2809\u2801 \u2809\u280B"],[" \u28C0\u28E4\u28E4\u28E4\u2840"," \u2880\u2844 \u2880 \u28E0\u2876\u281F\u281B\u2809\u2819\u28FF\u2847"," \u2808\u28BF\u289F\u28F5\u281F\u288D \u2880\u285F"," \u28E0\u285F\u2801 \u2819\u28A6\u2840\u2820\u280B"," \u28FC\u284F\u2818\u28A6\u2840 \u2831\u2844","\u28B8\u28FF\u28E6\u28C0\u28E0\u281D\u2836\u28E4\u28C0\u28E0\u28F7\u28E4","\u2808\u2809\u2809\u2801 \u2809\u281B\u281B\u280B"],[" \u28C0\u28E4\u28E4\u28E4\u2840"," \u2880\u28E4\u28C4\u28C0 \u28E0\u2876\u281F\u281B\u2809\u2819\u28FF\u2847"," \u2808\u28BF\u289F\u28F5\u281F\u288D \u2880\u285F"," \u28E0\u285F\u2801 \u2819\u28A6\u28C0\u2820\u280B"," \u28FC\u284F\u2818\u28A6\u2840 \u2839\u28F7\u2840","\u28B8\u28FF\u28E6\u28C0\u28E0\u281D\u2836\u28E4\u28C0\u28E0\u28FF\u28F7","\u2808\u2809\u2809\u2801 \u2809\u281B\u281B\u280B"],[" \u28C0\u28E4\u28E4\u28E4\u2840"," \u2880\u28E4\u28C4\u28C0 \u28E0\u2876\u281F\u281B\u2809\u2819\u28FF\u2847"," \u2808\u28BF\u289F\u28F5\u281F\u28AD\u28C4 \u2880\u285F"," \u28E0\u285F\u2801 \u2819\u28B7\u28C4\u2820\u280B"," \u28FC\u284F\u2818\u28A6\u2840 \u2839\u28F7\u2840","\u28B8\u28FF\u28E6\u28C0\u28E0\u281D\u2836\u28E4\u28C0\u28E0\u28FF\u28F7","\u2808\u2809\u2809\u2801 \u2809\u281B\u281B\u280B"]];function J(s,e){let t=x(s);return t>=e?_(s,e,""):s+" ".repeat(e-t)}function M(s,e){let t=[];for(let i of s.split(`
|
|
112
|
+
`))t.push(...i?ge(i,Math.max(1,e)):[""]);return t.map(i=>_(i,e,""))}function mt(s){if(!s)return"no agent";let e=s.from==="lab"?` (lab ${s.labName??s.lab})`:"";return`${s.name}${e}${s.isDefault?" (organization default)":""}`}function mc(s){try{let e=new URL(s);return e.host+(e.pathname==="/"?"":e.pathname.replace(/\/+$/,""))}catch{return s}}var an=class{paint;info;image;drawing;get draws(){return!this.image}constructor(e,t,i={}){this.paint=e,this.info=t,(i.image??ae().images==="kitty")&&e.color&&(this.image=new bi(pc,"image/png",dc(e),{maxWidthCells:14,maxHeightCells:7,filename:"qupai.png"}))}invalidate(){this.image?.invalidate()}details(){let e=this.paint,t=this.info(),i=[`${e.wordmark()} ${e.dim("the full-screen app of the qupai command")}`,""];return t.loading&&i.push(e.dim("Asking the platform\u2026")),t.who&&i.push(`${e.dim("Signed in as")} ${t.who}`),t.org&&i.push(`${e.dim("Organization")} ${t.org}`),i.push(`${e.dim("Platform ")} ${mc(t.platform)}`),i.push(`${e.dim("Agent ")} ${t.agent?mt(t.agent):t.loading?"\u2026":"none offered"}`),t.place&&i.push(`${e.dim("Project ")} ${t.place}`),i}hints(){let e=this.paint;return[`${e.tone("\u203A","brand")} Type a question and press Enter ${e.dim("(Shift+Enter for a new line)")}`,`${e.tone("\u203A","brand")} ${e.bold("/agent")} to choose an agent or a lab`,`${e.tone("\u203A","brand")} ${e.bold("/threads")} to continue a conversation ${e.dim("\xB7 ? for the keys")}`]}render(e){let t=this.paint,i=this.details(),n=[""];if(this.image){n.push(...this.image.render(Math.min(e,16)).map(r=>r.startsWith("\x1B")?r:_(" "+r,e,""))),n.push("");for(let r of i)n.push(_(" "+r,e,""))}else{let o=(this.drawing!==void 0&&Ni[this.drawing]||fc).map(a=>t.tone(J(a,14),"brand"));if(e>=64){let a=Math.max(o.length,i.length);for(let l=0;l<a;l++)n.push(_(` ${o[l]??" ".repeat(14)} ${i[l]??""}`,e,""))}else{for(let a of o)n.push(_(" "+a,e,""));n.push("");for(let a of i)n.push(_(" "+a,e,""))}}n.push("");for(let r of this.hints())n.push(_(" "+r,e,""));return n.push(""),n}},ft=class{paint;text;files;constructor(e,t,i=[]){this.paint=e,this.text=t,this.files=i}invalidate(){}render(e){let i=["",...M(this.text,Math.max(1,e-2)).map((n,r)=>r===0?`${this.paint.tone("\u203A","brand")} ${this.paint.bold(n)}`:` ${this.paint.bold(n)}`)];return this.files.length&&i.push(...M(this.paint.dim(`attached: ${this.files.join(", ")}`),Math.max(1,e-2)).map(n=>` ${n}`)),i}},vm={running:["running","brand"],done:["done","ok"],failed:["failed","failed"],waiting:["needs you","needs"]},km="[Run on hardware v]",Vr=class{part;expanded=!1;selected=!1;offer=null;onToggle;onAct;paint;button;constructor(e,t){this.paint=e,this.part=t}invalidate(){}act(){this.offer&&this.onAct?.()}handleMouse(e){if(e.type==="click"&&e.button==="left"&&e.y===0)return this.button&&e.x>=this.button.from&&e.x<this.button.to?(this.act(),{handled:!0}):(this.expanded=!this.expanded,this.onToggle?.(),{handled:!0})}render(e){let t=this.paint,i=this.part,[n,r]=vm[i.state],o=this.selected?t.tone("\u203A","brand"):" ",a=this.expanded?"\u25BE":"\u25B8",l=t.tone(n,r),c=`${o} ${t.dim(a)} ${t.bold(i.name)}`,h=this.offer?km:"",u=h?x(h)+1:0,d=e-x(c)-x(n)-u-4,p=d>4?_(tc(i.args,i.input),d):"",f=`${c} ${t.dim(p)}`,m=Math.max(0,e-x(n)-1-u);f=J(f,m),h?(this.button={from:m+1,to:m+1+x(h)},f+=" "+(this.selected?t.inverse(t.tone(h,"brand")):t.tone(h,"brand"))):this.button=void 0,f+=" "+l;let b=[_(f,e,"")];if(!this.expanded)return i.progress&&i.state==="running"&&b.push(_(` ${t.dim(i.progress)}`,e,"")),b;let g=Math.max(1,e-6),y=(w,k)=>{b.push(` ${t.dim(w)}`);for(let P of M(k,g))b.push(` ${P}`)};if(y("arguments",i.args===void 0?i.input||"(none)":JSON.stringify(i.args,null,2)),i.progress&&y("progress",i.progress),i.result!==void 0){let w=i.result.split(`
|
|
113
113
|
`),k=w.length>200?[...w.slice(0,200),`\u2026 ${w.length-200} more lines`]:w;y(i.state==="failed"?"error":"result",k.join(`
|
|
114
|
-
`)||"(empty)")}return b.map(w=>_(w,e,""))}},
|
|
115
|
-
`):this.editor.handleInput(e)}}render(e){let t=Math.max(4,e-4),i=[...M(this.intro,t),"",...this.editor.render(t)];return this.note&&i.push(...M(this.paint.tone(this.note,this.noteTone),t)),De(this.paint,e,this.title,i,"Enter a new line \xB7 Ctrl+S save \xB7 Esc cancel")}},Ye=class{paint;question;onAnswer;constructor(e,t){this.paint=e,this.question=t}invalidate(){}handleInput(e){e==="y"||e==="Y"?this.onAnswer?.(!0):(e==="n"||e==="N"||S(e,T.escape)||S(e,T.ctrl("c")))&&this.onAnswer?.(!1)}render(e){return De(this.paint,e,"Confirm",M(this.question,Math.max(4,e-4)),"Y yes \xB7 N or Esc no","needs")}},qe=s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},ve=s=>typeof s=="string"?s:"";function fc(s){for(let e of["oneOf","anyOf"]){let t=s[e];if(Array.isArray(t))return t.map(qe).filter(i=>typeof i.const=="string").map(i=>({value:i.const,label:String(i.title??i.const)}))}if(Array.isArray(s.enum)){let e=Array.isArray(s.enumNames)?s.enumNames:[];return s.enum.map((t,i)=>({value:String(t),label:String(e[i]??t)}))}}function wm(s){return(Array.isArray(s.requests)?s.requests:[]).map(qe).flatMap(t=>{if(typeof t.key!="string"||t.mode!=="form"&&t.mode!=="url")return[];let i=qe(t.requested_schema),n=new Set(Array.isArray(i.required)?i.required:[]),r=Object.entries(qe(i.properties)).map(([o,a])=>{let l=qe(a),c={request:t.key,name:o,label:String(l.title??o),description:ve(l.description)||void 0,required:n.has(o)};if(l.type==="boolean")return{...c,kind:"boolean"};if(l.type==="number")return{...c,kind:"number"};if(l.type==="integer")return{...c,kind:"integer"};if(l.type==="array")return{...c,kind:"multi",options:fc(qe(l.items))??[]};let h=fc(l);return h?{...c,kind:"select",options:h}:{...c,kind:"text"}});return[{key:t.key,mode:t.mode,message:ve(t.message),url:ve(t.url)||void 0,fields:r}]})}var mc=s=>s!==void 0&&s!==""&&!(Array.isArray(s)&&s.length===0);function xm(s,e){let t=Array.isArray(s.detail.action_requests)?s.detail.action_requests.map(qe):[],i=[ve(t[0]?.name),s.tool??""].find(a=>a.includes("."))??"",n=i.slice(0,i.indexOf(".")),r=n?e.find(a=>a.listing===n):void 0;if(!r)return;let o=qe(t[0]?.args??t[0]?.arguments);return{lab:r,machine:ve(o.instrument)||ve(o.machine)||void 0}}var hn=class{capturesViewportInput=!0;ctx;onAnswer;onClose;maxRows=()=>24;paint;mode="view";comment=new Te({prompt:""});editor=new Te({prompt:""});requests;values=new Map;opened=new Set;field=0;scroll=0;busy=!1;error="";_focused=!1;constructor(e,t){this.paint=e,this.ctx=t,this.requests=t.part.type==="mcp_input"?wm(t.part.detail):[];for(let i of this.requests)this.values.set(i.key,{});this.comment.onSubmit=i=>{this.send("reject",i)},this.comment.onEscape=()=>this.mode="view",this.editor.onSubmit=i=>this.saveField(i),this.editor.onEscape=()=>this.mode="view"}get focused(){return this._focused}set focused(e){this._focused=e,this.comment.focused=e&&this.mode==="comment",this.editor.focused=e&&this.mode==="edit"}get kind(){return this.ctx.part.type}invalidate(){}get slots(){return this.requests.flatMap(e=>e.mode==="url"?[{request:e}]:e.fields.map(t=>({request:e,field:t})))}saveField(e){let i=this.slots[this.field]?.field;if(!i)return;let n=this.values.get(i.request)??{},r=e;if(i.kind==="number"||i.kind==="integer")if(e.trim()==="")r=void 0;else{let o=Number(e);if(!Number.isFinite(o)||i.kind==="integer"&&!Number.isInteger(o)){this.error=`${i.label} takes ${i.kind==="integer"?"a whole number":"a number"}`;return}r=o}i.kind==="multi"&&(r=e.split(",").map(o=>o.trim()).filter(Boolean)),r===void 0||r===""?delete n[i.name]:n[i.name]=r,this.values.set(i.request,n),this.error="",this.mode="view"}activate(){let e=this.slots[this.field];if(!e)return;if(!e.field){this.opened.add(e.request.key);return}let t=e.field,i=this.values.get(t.request)??{};if(t.kind==="boolean"){i[t.name]=i[t.name]!==!0,this.values.set(t.request,i);return}if(t.kind==="select"&&t.options?.length){let r=t.options.findIndex(o=>o.value===i[t.name]);i[t.name]=t.options[(r+1)%t.options.length].value,this.values.set(t.request,i);return}let n=i[t.name];this.editor.setValue(n===void 0?"":Array.isArray(n)?n.join(", "):String(n)),this.mode="edit",this.focused=this._focused}body(){let e=this.ctx.part;return{interrupt_id:e.interruptId,tool_call_id:e.toolCallId,type:e.type}}async send(e,t=""){if(this.busy)return;let i=this.body();if(this.kind==="exit_plan_mode"&&(i.answers={approved:e==="approve"?"true":"false",feedback:t}),this.kind==="mcp_input"&&e==="approve"){let n=this.slots.find(o=>o.field?.required&&!mc(this.values.get(o.request.key)?.[o.field.name]));if(n?.field){this.error=`Fill ${n.field.label} first`;return}let r={};for(let o of this.requests)o.mode==="form"?r[o.key]={action:"accept",content:Object.fromEntries(Object.entries(this.values.get(o.key)??{}).filter(([,a])=>mc(a)))}:this.opened.has(o.key)&&(r[o.key]={action:"accept"});i.responses=r}this.busy=!0,this.error="";try{await this.onAnswer?.({decision:e,...t?{comment:t}:{},detail:i})}catch(n){this.error=n instanceof Error?n.message:String(n),this.mode="view"}finally{this.busy=!1}}handleInput(e){if(this.busy)return;if(this.mode==="comment"){this.comment.handleInput(e);return}if(this.mode==="edit"){this.editor.handleInput(e);return}if(e==="a"||e==="A"){if(this.ctx.record?.credential?.configured===!1){this.error=`Approving needs your own key for ${this.ctx.record.credential.provider}: add it in the app first`;return}this.send("approve");return}if(e==="r"||e==="R"){this.comment.setValue(""),this.mode="comment",this.focused=this._focused;return}if(S(e,T.escape)){this.onClose?.();return}let t=this.kind==="mcp_input";S(e,T.up)?t?this.field=Math.max(0,this.field-1):this.scroll=Math.max(0,this.scroll-1):S(e,T.down)?t?this.field=Math.min(Math.max(0,this.slots.length-1),this.field+1):this.scroll+=1:S(e,T.pageUp)?this.scroll=Math.max(0,this.scroll-10):S(e,T.pageDown)?this.scroll+=10:t&&(S(e,T.enter)||e===" ")&&this.activate()}title(){let e=this.ctx.part;return e.type==="mcp_input"?`${ve(e.detail.server)||"An MCP server"} asks for input`:e.type==="exit_plan_mode"?"A plan to confirm":"Approval"}lines(e){let t=this.paint,i=this.ctx.part,n=(u,d)=>M(`${t.dim(u.padEnd(9))}${d}`,e),r=[];if(r.push(...n("Agent",this.ctx.agent)),i.type==="mcp_input")return this.slots.forEach((u,d)=>{let p=d===this.field,f=p?t.tone("\u203A","brand"):" ";if(!u.field){(d===0||this.slots[d-1]?.request!==u.request)&&r.push("",...M(u.request.message,e)),r.push(...M(`${f} ${u.request.url??"(no address)"} ${this.opened.has(u.request.key)?t.tone("opened","ok"):t.dim("open it, then Enter")}`,e));return}(d===0||this.slots[d-1]?.request!==u.request)&&r.push("",...M(u.request.message,e));let g=u.field,b=this.values.get(g.request)?.[g.name],m=p&&this.mode==="edit"?"":b===void 0?t.dim(g.kind==="boolean"?"no":g.kind==="select"?`choose: ${g.options?.map(w=>w.label).join(", ")}`:"(empty)"):g.kind==="boolean"?b===!0?"yes":"no":g.kind==="select"?g.options?.find(w=>w.value===b)?.label??String(b):Array.isArray(b)?b.join(", "):String(b),y=`${g.label}${g.required?" *":""}`;if(p&&this.mode==="edit"){let w=this.editor.render(Math.max(4,e-x(y)-4))[0]??"";r.push(`${f} ${t.bold(y)}: ${w}`)}else r.push(...M(`${f} ${t.bold(y)}: ${m}`,e));p&&g.description&&r.push(...M(` ${t.dim(g.description)}`,e))}),this.slots.length||r.push("",t.dim("(the server asks for nothing to fill in)")),r;let o=Array.isArray(i.detail.action_requests)?i.detail.action_requests.map(qe):[],a=i.tool??ve(o[0]?.name);r.push(...n("Tool",t.bold(a||"a tool")));let l=xm(i,this.ctx.labs);l&&(r.push(...n("Lab",`${K(l.lab.name,l.lab.id)} (${l.lab.id})`)),l.machine&&r.push(...n("Machine",l.machine)));let c=ve(i.detail.message)||ve(o[0]?.description);if(c&&r.push(...n("Why",c)),i.type==="exit_plan_mode")r.push("",t.dim("Plan")),r.push(...M(ve(i.detail.plan),e));else if(o.length)for(let u of o){let d=u.args??u.arguments;r.push("",t.dim(o.length>1?`Arguments of ${ve(u.name)||"the call"}`:"Arguments")),r.push(...M(d===void 0?"(none)":JSON.stringify(d,null,2),e))}let h=this.ctx.record?.credential;return h?.configured===!1&&r.push("",...M(t.tone(`Approving needs your own key for ${h.provider}: add it in the app first.`,"needs"),e)),r}render(e){let t=Math.max(4,e-4),i=this.lines(t);this.mode==="comment"&&i.push("",`${this.paint.tone("Why reject? (optional)","needs")}`,this.comment.render(t)[0]??""),this.busy&&i.push("",this.paint.dim("Sending\u2026")),this.error&&i.push("",...M(this.paint.tone(this.error,"failed"),t));let n=Math.max(3,this.maxRows()-5);if(i.length>n){this.scroll=Math.min(this.scroll,i.length-n);let o=i.slice(this.scroll,this.scroll+n-1);o.push(this.paint.dim(`lines ${this.scroll+1}-${this.scroll+o.length} of ${i.length} \xB7 \u2191\u2193 PgUp PgDn scroll`)),i=o}else this.scroll=0;let r=this.mode==="comment"?"Enter rejects \xB7 Esc back":this.mode==="edit"?"Enter keeps the value \xB7 Esc back":this.kind==="mcp_input"?"\u2191\u2193 field \xB7 Enter edit or open \xB7 A send \xB7 R decline \xB7 Esc close (it keeps waiting)":"A approve \xB7 R reject \xB7 Esc close (the turn keeps waiting)";return De(this.paint,e,this.title(),i,r,"needs")}};var vm="Run on hardware",km="Run again",Yt=["credits","balance"],Xt=[{id:1,name:"S2048"},{id:4,name:"S1601"}],Sm="only the member's own sign-in compiles",Cm="source result or action preview was refused",$m=new Set(["result_expired","result_not_found"]),Am=s=>s.length>0&&!/[\x00-\x1f\x7f]/.test(s),Vr=class{value="";pasting=!1;get length(){return this.value.length}clear(){this.value="",this.pasting=!1}take(){let e=this.value.trim();return this.clear(),e}handle(e){let t=e;if(t.includes("\x1B[200~")&&(this.pasting=!0,t=t.replace("\x1B[200~","")),this.pasting){let i=t.indexOf("\x1B[201~"),n=i>=0?t.slice(0,i):t;return this.value+=n.replace(/[\x00-\x1f\x7f]/g,""),i>=0&&(this.pasting=!1),!0}return S(t,T.backspace)?(this.value=this.value.slice(0,-1),!0):S(t,T.ctrl("u"))?(this.value="",!0):Am(t)?(this.value+=t,!0):!1}render(e){return this.value?`${"\u2022".repeat(Math.min(this.value.length,Math.max(4,e-16)))} ${this.value.length} character${this.value.length===1?"":"s"}`:""}},un=class{capturesViewportInput=!0;opts;onClose;onSubmitted;requestRender=()=>{};maxRows=()=>24;focused=!1;paint;services;step="provider";loading="";error="";note="";settings;directory;credentials=new Map;offered=[];providerCursor=0;provider="";secret=new Vr;catalog;deviceCursor=0;target="";shots="";mode="auto";pool=[];readout=!0;point;fixedNotes=new Map;caps;qubitCursor=0;machine=1;count="1";postProcess=!1;payment=null;optionCursor=0;preview;compiling=!1;requestId="";shownAt=0;button="run";scroll=0;busy=!1;abort;hits=[];bodyTop=1;closed=!1;pending=new Set;constructor(e,t,i){this.paint=e,this.services=t,this.opts=i;let n=i.offer.candidate;n.kind!=="optimization"&&(this.shots=String(Tl(n)),n.kind==="energy"&&n.scan&&(this.point=i.rerun?.point!==void 0&&n.scan.points.some(r=>r.index===i.rerun.point)?i.rerun.point:n.scan.defaultPoint))}get optimization(){return this.opts.offer.candidate.kind==="optimization"}get circuit(){return this.opts.offer.candidate.kind==="distribution"}get qubits(){let e=this.opts.offer.candidate;return e.kind==="optimization"?0:e.qubits}nameOf(e){return Al(e,this.directory)}get action(){return Sr(this.opts.offer.actions).get(this.provider)??this.opts.offer.action}onWork;track(e){let t=e.finally(()=>{this.pending.delete(t),this.requestRender()});return this.pending.add(t),this.onWork?.(t.catch(()=>{})),t}async idle(){for(;this.pending.size;)await Promise.allSettled([...this.pending])}start(){this.loading="Reading your providers and keys\u2026",this.track(this.load())}async load(){try{if(this.optimization)this.settings=await this.services.settings().catch(()=>{});else{let[n,r]=await Promise.all([this.services.settings().catch(()=>{}),this.services.providers()]);this.settings=n,this.directory=r}this.offered=$l(this.opts.offer,this.directory,this.settings,this.opts.rerun?.provider),await Promise.all(this.offered.map(async n=>{try{this.credentials.set(n,await this.services.credential(n))}catch(r){this.credentials.set(n,r instanceof Error?r:new Error(String(r)))}}));let e=this.optimization?"isingq":Ge(this.opts.offer.action),t=this.opts.rerun?.provider??e??"",i=this.allowed(t)?this.offered.indexOf(t):this.offered.findIndex(n=>this.allowed(n));this.providerCursor=Math.max(0,i),this.loading="",this.offered.length||(this.error="no provider can run this result from here")}catch(e){this.loading="",this.error=yt(e)}}allowed(e){return!this.settings||$r(this.settings,e)}go(e){this.step=e,this.error="",this.scroll=0,e!=="key"&&this.secret.clear()}back(){switch(this.step){case"provider":this.close();return;case"key":case"device":this.note="",this.go("provider");return;case"options":this.optimization?this.go("provider"):this.go("device");return;case"qubits":this.go("options");return;case"preview":if(this.busy&&!this.compiling&&!this.abort)return;this.abort?.abort(),this.abort=void 0,this.busy=!1,this.compiling=!1,this.preview=void 0,this.go("options");return}}close(){this.closed||(this.closed=!0,this.abort?.abort(),this.secret.clear(),this.onClose?.())}chooseProvider(e){if(this.loading||this.busy)return;this.providerCursor=Math.max(0,this.offered.indexOf(e));let t=this.nameOf(e);if(!this.allowed(e)){this.error=`your organization has not enabled ${t}: ask its admin in the app`;return}let i=this.credentials.get(e);if(i instanceof Error||!i){this.error="",this.loading=`Reading whether a ${t} key is saved\u2026`,this.track(this.services.credential(e).then(n=>{this.credentials.set(e,n),this.loading=""},n=>{this.loading="",this.error=`could not read whether a ${t} key is saved: ${yt(n)}`}));return}if(e!==this.provider&&(this.provider=e,this.target="",this.pool=[],this.mode="auto",this.catalog=void 0),!i.configured){this.go("key");return}this.afterKey()}afterKey(){if(this.optimization){this.go("options"),this.optionCursor=this.optionRows().length-1;return}this.go("device"),this.loadCatalog(!1)}saveKey(){if(this.busy)return;if(!this.secret.length){this.error=`paste your ${this.nameOf(this.provider)} key first`;return}let e=this.secret.take(),t=this.provider,i=this.nameOf(t);this.busy=!0,this.error="",this.track(this.services.saveKey(t,e).then(n=>{this.busy=!1,this.credentials.set(t,n);let r=(n.masked_suffix??"").replace(/^[•*]+/,"");this.note=`Saved: your ${i} key${r?` ending ${r}`:""}, stored encrypted. Nothing was submitted.`,n.configured&&this.afterKey()},n=>{this.busy=!1,this.error=n instanceof Ei?n.message:`the key was not saved: ${yt(n)}`}))}loadCatalog(e){let t=this.provider;this.loading=e?"Asking the provider for its devices again\u2026":`Reading ${this.nameOf(t)}'s devices\u2026`,this.error="",this.track((async()=>{try{let i=await this.services.catalog(t,e),n=Date.now()+6e4;for(let a=qi(i);a!==!1&&Date.now()<n&&!this.closed&&this.provider===t;a=qi(i))this.catalog=i,this.requestRender(),await new Promise(l=>setTimeout(l,Math.min(a,3e3))),i=await this.services.catalog(t,!1);if(this.provider!==t)return;this.catalog=i;let o=Ar(i.data??[],this.qubits).findIndex(a=>a.target===this.target);this.deviceCursor=o>=0?o:0,i.configured?i.refresh.error&&!i.data&&(this.error=`the device list could not be read: ${i.refresh.error}`):this.error=`no ${this.nameOf(t)} key is saved`}catch(i){i instanceof Qe&&(i.code==="credential_missing"||i.code==="credential_invalid")?(this.credentials.delete(t),this.error=i.message):this.error=yt(i)}finally{this.loading=""}})())}get devices(){return Ar(this.catalog?.data??[],this.qubits)}get device(){return this.catalog?.data?.find(e=>e.target===this.target)}chooseDevice(e){if(!this.busy){if(this.deviceCursor=Math.max(0,this.devices.indexOf(e)),e.online===!1){this.error=`${e.target} is offline`;return}if(!Bs(e,this.qubits)){this.error=`${e.target} cannot hold ${this.qubits} connected qubits${typeof e.largest_connected_qubits=="number"?` (at most ${e.largest_connected_qubits})`:""}`;return}e.target!==this.target&&(this.target=e.target,this.pool=[],this.caps=void 0),this.go("options"),this.optionCursor=this.optionRows().length-1}}openQubits(){if(this.mode="physical_pool",this.go("qubits"),this.caps?.data?.target===this.target)return;this.caps=void 0;let e=this.target;this.loading=`Reading ${e}'s qubits\u2026`,this.track((async()=>{try{let t=await this.services.capabilities(this.provider,e),i=Date.now()+6e4;for(let n=qi(t);n!==!1&&Date.now()<i&&!this.closed&&this.target===e;n=qi(t))await new Promise(r=>setTimeout(r,Math.min(n,3e3))),t=await this.services.capabilities(this.provider,e);if(this.target!==e)return;this.caps=t,t.data?t.data.qubit_ids.every(n=>/^(0|[1-9][0-9]*)$/.test(n))||(this.error="this provider names its qubits in a way a pool cannot use: choose Automatic"):this.error=`${e}'s qubits could not be read${t.refresh.error?`: ${t.refresh.error}`:""}`}catch(t){this.error=yt(t)}finally{this.loading=""}})())}toggleQubit(e){let t=this.caps?.data;if(t){if(!Tr(e,this.pool,t.qubit_ids,t.couplings,this.qubits)){this.error=this.pool.length>=this.qubits&&!this.pool.includes(e)?`${this.qubits} qubits are chosen: remove one first`:`qubit ${e} is not next to the ones chosen (the pool stays connected)`;return}this.error="",this.pool=this.pool.includes(e)?this.pool.filter(i=>i!==e):[...this.pool,e]}}get shotCount(){return/^\d+$/.test(this.shots)?Number(this.shots):Number.NaN}correctionFixed(){return Cr.has(this.provider)||this.fixedNotes.has(this.provider)}runArguments(){if(this.optimization)return{solver_options:{computer_type_id:this.machine,calculate_count:Number(this.count),post_process:this.postProcess,use_credit:this.payment==="credits"}};let e=this.provider!=="logicqubit"?{provider:this.provider}:{};if(this.circuit)return{target:this.target,shots:this.shotCount,layout_mode:this.mode,qids:this.mode==="physical_pool"?this.pool.map(Number):[],...e};let t=this.opts.offer.candidate,i=t.kind==="energy"&&t.scan;return{target:this.target,shots:this.shotCount,readout_correction:this.correctionFixed()||this.readout,...i&&this.point!==void 0?{point:this.point}:{},...e}}notReady(){if(this.optimization){let e=Number(this.count);return!/^\d+$/.test(this.count)||e<1||e>1e4?"the calculation count is a whole number from 1 to 10000":this.payment?"":"choose how the run is paid: QuPai never chooses it for you"}if(!this.device)return"choose a device first";if(!Ai(this.device,this.qubits))return`${this.target} cannot take this run`;if(!Number.isSafeInteger(this.shotCount)||this.shotCount<1)return"the shots are a whole number above 0";if(this.circuit&&this.mode==="physical_pool"){let e=this.caps?.data;if(!e||!Il(this.pool,e,this.qubits))return`choose ${this.qubits} connected qubits by hand first, or Automatic`}return""}askPreview(){if(this.busy)return;let e=this.notReady();if(e){this.error=e;return}let t=new AbortController;this.abort=t,this.busy=!0,this.compiling=!1,this.preview=void 0,this.go("preview");let i=this.provider,n={source_turn_id:this.opts.turnId,source_tool_call_id:this.opts.offer.candidate.toolCallId,action_id:this.action.id,arguments:this.runArguments()};this.track(this.services.preview(n,()=>{this.compiling=!0,this.requestRender()},t.signal).then(r=>{if(!t.signal.aborted){if(Fs(r)){if(r.options.computer_type_id!==this.machine||r.machine.computer_type_id!==this.machine)throw new Error("the preview did not keep the machine you chose: preview again");if(r.options.use_credit!==(this.payment==="credits"))throw new Error("the preview did not keep how you chose to pay: preview again")}else{let o=Ir(r);o?.fixedOn&&this.fixedNotes.set(i,o.note)}this.preview=r,this.requestId=crypto.randomUUID(),this.shownAt=Date.now(),this.button="run",this.scroll=0}}).catch(r=>{t.signal.aborted||(this.preview=void 0,this.step="options",this.error=this.previewError(r),r instanceof D&&r.type==="urn:qupai:problem:credential-required"&&(this.credentials.delete(i),this.go("key"),this.error=`${this.nameOf(i)} needs your key again: paste it here`))}).finally(()=>{this.abort===t&&(this.abort=void 0),this.busy=!1,this.compiling=!1}))}previewError(e){if(e instanceof je)return e.errorType&&$m.has(e.errorType)?"This simulation result is no longer kept (results are kept for up to 7 days). Run the simulation again, then run it on hardware.":e.errorType==="sandbox_compile_timeout"?"The sandbox is still compiling this run after 10 minutes. Close this and try again later.":e.errorType==="sandbox_compile_failed"?`The sandbox could not compile this run: ${e.message}`:`The service refused this preview: ${e.message}`;if(e instanceof D){if(e.status===403&&e.detail.includes(Sm))return`This run is wider than the device service compiles itself, and only your own sign-in in the app starts the sandbox that compiles it (${e.detail}). Run it from the conversation in the web app: ${this.opts.link}`;if(!this.circuit&&e.type==="urn:qupai:problem:invalid-request"&&e.detail.includes(Cm))return"This result can't be run on hardware: it was probably computed before this action was offered. Run it again, then run the new result."}return yt(e)}submit(){let e=this.preview;if(!e||this.busy||Date.now()-this.shownAt<(this.opts.guardMs??500))return;this.busy=!0,this.error="";let t={source_turn_id:this.opts.turnId,action_id:this.action.id,preview_id:e.preview_id,request_id:this.requestId},i=this.summary(e);this.track(this.services.submit(t).then(n=>{this.busy=!1,this.onSubmitted?.({turn:n,summary:i}),this.close()},n=>{if(this.busy=!1,n instanceof D&&n.type==="urn:qupai:problem:credential-required"){this.credentials.delete(this.provider),this.preview=void 0,this.go("key"),this.error=`${this.nameOf(this.provider)} needs your key again: paste it here`;return}this.error=`not submitted: ${yt(n)}`}))}summary(e){if(Fs(e))return`isingq ${e.machine.name} \xB7 ${e.options.calculate_count} calculation${e.options.calculate_count===1?"":"s"}`;let t=this.nameOf(this.provider);return Ns(e)?`${e.target} (${t}) \xB7 ${e.variational.circuits} circuit${e.variational.circuits===1?"":"s"} \xD7 ${e.shots} shots`:`${e.target} (${t}) \xB7 ${e.shots} shots`}handleInput(e){if(this.step==="key"&&this.busy)return;if(this.step==="key"){if(S(e,T.enter)){this.saveKey();return}if(S(e,T.escape)){this.back();return}if(this.secret.handle(e)){this.error="";return}return}if(S(e,T.escape)){this.back();return}let t=S(e,T.up),i=S(e,T.down),n=S(e,T.enter);switch(this.step){case"provider":{t?this.providerCursor=Math.max(0,this.providerCursor-1):i?this.providerCursor=Math.min(Math.max(0,this.offered.length-1),this.providerCursor+1):n&&this.offered[this.providerCursor]&&this.chooseProvider(this.offered[this.providerCursor]);return}case"device":{let r=this.devices;t?this.deviceCursor=Math.max(0,this.deviceCursor-1):i?this.deviceCursor=Math.min(Math.max(0,r.length-1),this.deviceCursor+1):n&&r[this.deviceCursor]?this.chooseDevice(r[this.deviceCursor]):e==="r"&&!this.loading&&this.loadCatalog(!0);return}case"options":this.optionKey(e);return;case"qubits":{let r=this.caps?.data?.qubit_ids??[];t?this.qubitCursor=Math.max(0,this.qubitCursor-1):i?this.qubitCursor=Math.min(r.length,this.qubitCursor+1):(n||e===" ")&&(this.qubitCursor===r.length?this.go("options"):r[this.qubitCursor]&&this.toggleQubit(r[this.qubitCursor]));return}case"preview":{if(!this.preview)return;S(e,T.left)||S(e,T.right)||S(e,T.tab)?this.button=this.button==="run"?"change":"run":t?this.scroll=Math.max(0,this.scroll-1):i?this.scroll+=1:S(e,T.pageUp)?this.scroll=Math.max(0,this.scroll-10):S(e,T.pageDown)?this.scroll+=10:n&&(this.button==="change"?this.back():this.submit());return}}}optionKey(e){let t=this.optionRows();if(S(e,T.up)){this.optionCursor=Math.max(0,this.optionCursor-1);return}if(S(e,T.down)||S(e,T.tab)){this.optionCursor=Math.min(t.length-1,this.optionCursor+1);return}let i=t[this.optionCursor];if(!i)return;if(i.type==="number"){let r=i.key==="count"?"count":"shots";if(S(e,T.backspace)){this[r]=this[r].slice(0,-1),this.preview=void 0;return}if(/^\d+$/.test(e)){this[r]=(this[r]+e).replace(/^0+(?=\d)/,"").slice(0,7);return}S(e,T.enter)&&(this.optionCursor=Math.min(t.length-1,this.optionCursor+1));return}let n=S(e,T.left)?-1:S(e,T.right)||e===" "?1:S(e,T.enter)?0:null;n!==null&&i.act(n)}optionRows(){let e=this.paint,t=[];if(this.optimization){let n=Xt.find(r=>r.id===this.machine);return t.push({key:"machine",type:"choice",label:"Machine",value:Xt.map(r=>r.id===n.id?e.bold(`(\u2022) ${r.name}`):`( ) ${r.name}`).join(" "),act:r=>this.cycleMachine(r)}),t.push({key:"count",type:"number",label:"Calculations",value:this.count,act:()=>{}}),t.push({key:"post",type:"choice",label:"Post-process",value:this.postProcess?"[x] the provider's post processing":"[ ] the provider's post processing",act:()=>this.postProcess=!this.postProcess}),t.push({key:"payment",type:"choice",label:"Payment",value:Yt.map(r=>`${this.payment===r?"(\u2022)":"( )"} ${r==="credits"?"Compute credits":"Account balance"}`).join(" ")+(this.payment?"":e.tone(" (required)","needs")),act:r=>this.cyclePayment(r)}),t.push({key:"preview",type:"button",label:"",value:"Preview the run",act:()=>this.askPreview()}),t}let i=this.device;if(t.push({key:"device",type:"button",label:"Device",value:i?`${i.target} ${e.dim(bc(i))}`:e.dim("choose one"),act:()=>this.go("device")}),t.push({key:"shots",type:"number",label:this.circuit?"Shots":"Shots/circuit",value:this.shots,act:()=>{}}),this.circuit){let n=this.mode==="physical_pool",r=n?this.pool.length?` ${e.dim(`${this.pool.length} of ${this.qubits}: ${this.pool.join(", ")}`)}`:` ${e.dim("none chosen yet")}`:"";t.push({key:"qubits",type:"choice",label:"Qubits",value:`${n?"( ) Automatic (\u2022) By hand":"(\u2022) Automatic ( ) By hand"}${r}`,act:o=>{if(o===0||!n){this.openQubits();return}this.mode="auto"}})}else{let n=this.correctionFixed();t.push({key:"readout",type:"choice",label:"Readout fix",value:n||this.readout?`[x] readout correction${n?e.dim(" (always on here)"):""}`:"[ ] readout correction",act:()=>{n||(this.readout=!this.readout)}});let r=this.opts.offer.candidate;if(r.kind==="energy"&&r.scan){let o=r.scan.points.find(a=>a.index===this.point)??r.scan.points[0];t.push({key:"point",type:"choice",label:"Bond length",value:`\u2039 ${o.bondLength} \xC5 \xB7 ${Ri(o.minEnergy.toFixed(6))} Ha \u203A`,act:a=>this.cyclePoint(a||1)})}}return t.push({key:"preview",type:"button",label:"",value:this.circuit?"Preview the compilation":"Preview cost and placement",act:()=>this.askPreview()}),t}cycleMachine(e){let t=Xt.findIndex(i=>i.id===this.machine);this.machine=Xt[(t+(e||1)+Xt.length)%Xt.length].id}cyclePayment(e){let t=this.payment?Yt.indexOf(this.payment):-1;this.payment=Yt[((t+(e||1))%Yt.length+Yt.length)%Yt.length]}cyclePoint(e){let t=this.opts.offer.candidate;if(t.kind!=="energy"||!t.scan)return;let i=t.scan.points,n=Math.max(0,i.findIndex(r=>r.index===this.point));this.point=i[(n+e+i.length)%i.length].index}handleMouse(e){return e.type==="wheel"?(this.step==="preview"&&(this.scroll=Math.max(0,this.scroll+(e.wheelDelta??0))),{handled:!0,render:!0}):e.type!=="click"||e.button!=="left"?{handled:!0}:(this.buttonRow&&e.y===this.buttonRow.y?this.clickButton(e.x):this.hits[e.y]?.(),{handled:!0,render:!0})}invalidate(){}title(){return this.opts.offer.candidate.kind==="optimization"?"Run on isingq":this.opts.rerun?"Run on hardware again":"Run on hardware"}what(){let e=this.opts.offer.candidate;switch(e.kind){case"distribution":return`Sampled circuit \xB7 ${e.qubits} qubit${e.qubits===1?"":"s"} \xB7 simulated with ${e.shots} shots`;case"energy":return e.scan?`Bond-length scan \xB7 ${Ii(e.molecule.name)} \xB7 ${e.qubits} qubits`:e.molecule?`VQE energy \xB7 ${Ii(e.molecule.name)} ${e.molecule.bondLength} \xC5 \xB7 ${e.qubits} qubits`:`VQE energy \xB7 ${e.qubits} qubits`;case"maxcut":return`QAOA Max-Cut \xB7 ${e.qubits} nodes`;case"optimization":return`${e.problem.toUpperCase()} \xB7 ${e.numVariables} variable${e.numVariables===1?"":"s"} \xB7 local objective ${e.objective}`}}pays(e){return`The run is submitted with your own ${e} key, so ${e} counts it against your account there, on its terms. QuPai does not pay the provider for you.`}rows(e){let t=this.paint,i=[],n=(r="",o,a)=>{M(r,e).forEach((c,h)=>i.push({text:c,hit:o,focus:a&&h===0}))};switch(n(t.bold(this.what())),n(""),this.step){case"provider":{if(n(t.dim("1 Provider 2 Device and shots 3 Preview 4 Run")),n(""),this.loading)break;this.offered.forEach((r,o)=>{let a=o===this.providerCursor,l=this.credentials.get(r),c=this.allowed(r)?l instanceof Error?t.tone("could not read whether a key is saved","failed"):l?l.configured?t.tone(`key saved${l.masked_suffix?` (ending ${l.masked_suffix.replace(/^[•*]+/,"")})`:""}`,"ok"):t.tone("no key saved: you paste it next","needs"):t.dim("\u2026"):t.tone("not enabled by your organization","stopped"),h=this.nameOf(r);n(`${a?t.tone("\u203A","brand"):" "} ${a?t.bold(h.padEnd(18)):h.padEnd(18)} ${c}`,()=>this.chooseProvider(r),a)}),this.offered.length&&(n(""),n(t.dim(this.pays(this.nameOf(this.offered[this.providerCursor]??"")))));break}case"key":{let r=this.nameOf(this.provider),o=this.credentials.get(this.provider);n(`No ${r} key is saved for you. Paste it here: it is sealed for the platform on this computer, sent once, stored encrypted and shown only by its last characters. Nothing is written on this computer and nothing is submitted.`),o&&!(o instanceof Error)&&o.signup_url&&/^https:\/\//.test(o.signup_url)&&n(t.dim(`No key yet? Get one at ${o.signup_url}`)),n("");let a=this.busy?t.dim("Saving\u2026"):this.secret.render(e-16)||t.dim("(paste or type the key)");n(`${t.dim(`${r} key`.padEnd(14))} ${a}`,void 0,!0);break}case"device":{let r=this.nameOf(this.provider);if(this.note&&n(t.tone(this.note,"ok")),n(t.dim(`Devices of ${r} with your key${this.catalog?.fetched_at?`, read ${Tm(this.catalog.fetched_at)}${this.catalog.stale?" (stale: r reads them again)":""}`:""}:`)),n(""),this.loading&&!this.catalog?.data)break;let o=this.devices;!o.length&&!this.loading&&n(t.dim("No devices came back for your key.")),o.forEach((a,l)=>{let c=l===this.deviceCursor,h=Ai(a,this.qubits),u=a.online===!1||Bs(a,this.qubits)?"":`too small for ${this.qubits} connected qubits`,d=`${c?t.tone("\u203A","brand"):" "} ${J(c?t.bold(a.target):a.target,16)} ${bc(a)}${u?` \xB7 ${u}`:""}`;n(h?d:t.dim(d),()=>this.chooseDevice(a),c)}),this.provider==="baqis"&&n(t.dim(`Quafu-SQC runs shots in whole blocks of ${_i}.`)),this.provider==="originq"&&n(t.dim("Origin Quantum reports readout-corrected probabilities only, and bills machine time.")),this.provider==="tianyan"&&n(t.dim("Tianyan reports readout-corrected probabilities only and charges a task on one of its paid machines to your own Tianyan account (the preview says when a machine is paid). A task cannot be cancelled once it is sent."));break}case"options":{this.note&&this.optimization&&n(t.tone(this.note,"ok")),this.optimization&&n(t.dim("Machine types this integration supports; isingq checks availability and your access when the run is submitted. Submitted tasks cannot be cancelled through QuPai."));let r=this.optionRows();if(this.optionCursor=Math.min(this.optionCursor,r.length-1),r.forEach((o,a)=>{let l=a===this.optionCursor,c=l?t.tone("\u203A","brand"):" ";if(o.type==="button"){let u=o.label?`${t.dim(o.label.padEnd(14))}${o.value}`:l?t.inverse(` ${o.value} `):`[ ${o.value} ]`;o.label||n(""),n(`${c} ${u}`,()=>{this.optionCursor=a,o.act(0)},l);return}let h=o.type==="number"?`${l?t.inverse(` ${o.value||" "} `):`[ ${o.value} ]`}`:o.value;n(`${c} ${t.dim(o.label.padEnd(14))}${h}`,()=>{this.optionCursor=a,o.type!=="number"&&o.act(1)},l)}),n(""),!this.optimization){let o=this.opts.offer.candidate;this.circuit?n(t.dim(this.mode==="auto"?"Automatic: the compiler chooses the layout on the device.":`By hand: the compiler maps the circuit within the ${this.qubits} connected qubits you choose; the order you choose them in is not the mapping.`)):n(t.dim("The server places the circuits on connected qubits of the device; the preview shows which, and the cost.")),this.correctionFixed()&&n(t.dim(this.fixedNotes.get(this.provider)??`${this.nameOf(this.provider)} returns readout-corrected results only, so runs there are always sent with readout correction on.`)),this.provider==="baqis"&&Number.isSafeInteger(this.shotCount)&&this.shotCount%_i&&n(t.dim(`${this.shotCount} shots run as ${Math.ceil(this.shotCount/_i)*_i}.`)),o.kind!=="optimization"&&n(t.dim(this.pays(this.nameOf(this.provider))))}break}case"qubits":{let r=this.caps?.data;if(n(`Choose ${this.qubits} connected qubits of ${this.target}. The compiler maps the circuit within them; the order you choose them in is not the mapping.`),n(t.dim(`Chosen ${this.pool.length} of ${this.qubits}${this.pool.length?`: ${this.pool.join(", ")}`:""}`)),n(""),!r)break;r.qubit_ids.forEach((a,l)=>{let c=l===this.qubitCursor,h=this.pool.includes(a),u=Tr(a,this.pool,r.qubit_ids,r.couplings,this.qubits),d=h?"[x]":"[ ]",p=`${c?t.tone("\u203A","brand"):" "} ${h?t.tone(d,"brand"):d} ${J(a,5)} ${Rl(r,a)}`;n(u||h?p:t.dim(p),()=>{this.qubitCursor=l,this.toggleQubit(a)},c)});let o=this.qubitCursor===r.qubit_ids.length;n(""),n(`${o?t.tone("\u203A","brand"):" "} ${o?t.inverse(" Done "):"[ Done ]"}`,()=>this.go("options"),o);break}case"preview":{if(!this.preview){n(this.compiling?"Compiling in the sandbox\u2026":this.circuit?"Checking and compiling\u2026":this.optimization?"Preparing the preview\u2026":"Placing and estimating\u2026"),this.compiling&&n(t.dim("This run is wider than the device service compiles itself, so this conversation's sandbox compiles it for the device. That can take a minute or two. Nothing is sent to hardware."));break}for(let r of this.previewLines(this.preview))n(r);break}}return this.loading&&n(t.dim(this.loading)),this.error&&(n(""),n(t.tone(this.error,"failed"))),i}previewLines(e){let t=this.paint,i=[],n=(p,f)=>i.push(`${t.dim(p.padEnd(18))}${f}`);if(i.push(t.bold("Review this run: nothing has been sent yet")),i.push(""),Fs(e))return n("Machine",e.machine.name),n("Maximum variables",String(e.machine.max_variables)),n("Variables",String(e.baseline.num_variables)),n("Local objective",String(e.baseline.objective_value)),n("Calculations",String(e.options.calculate_count)),n("Post-processing",e.options.post_process?"yes":"no"),n("Payment",e.options.use_credit?"Compute credits":"Account balance"),n("Model SHA-256",e.baseline.model_hash),i.push(""),i.push(`${e.options.use_credit?"This run spends compute credits from your isingq account.":"This run is charged to the balance of your isingq account."} Run on hardware submits this exact preview, once. Hardware precision may affect the solution.`),i;let r=this.nameOf(this.provider),o=Ir(e)?.note??(Cr.has(this.provider)?`${r} returns readout-corrected results only, so runs there are always sent with readout correction on.`:void 0);if(Ns(e)){let p=e.variational;p.paid_machine===!0&&i.push(t.tone(`${e.target} is one of ${r}'s paid machines. ${r} charges each of these ${p.circuits} tasks to your own ${r} account, at its own price, which QuPai does not know. A task cannot be cancelled once it is sent.`,"needs"),""),i.push(t.dim(_m(e))),n("Device",`${e.target} (${r})`),n("Shots per circuit",String(e.shots)),n("Physical qubits",e.qids.join(", ")),n("Circuits",String(p.circuits)),n("Total shots",String(p.total_shots));let f=typeof p.estimated_cost_yuan=="number",g=f?Ws(p.estimated_cost_yuan):"";n("Estimated cost",f?p.billing_multiplier!==void 0&&p.billing_multiplier!==1?`about \xA5${g} (at the \xD7${p.billing_multiplier} billing multiplier)`:`\xA5${g}`:p.tasks!==void 0?`${p.tasks} task${p.tasks===1?"":"s"}`:p.machine_seconds_min!==void 0?`at least ${p.machine_seconds_min} s of machine time`:"\u2014"),n("CZ gates",p.cz_count===null?"\u2014":String(p.cz_count)),n("Circuit depth",p.depth===null?"\u2014":String(p.depth)),n("Est. fidelity",p.estimated_fidelity===void 0?"\u2014":p.estimated_fidelity.toFixed(3)),n("Readout fix",e.readout_correction?"on":"off"),p.cost_note&&!f&&i.push(t.dim(p.cost_note)),p.submission==="auto"&&p.batch_cost_yuan!==void 0&&i.push(t.dim(`A batch is tried first (about \xA5${Ws(p.batch_cost_yuan)}); if your subscription doesn't take batch tasks, the circuits are submitted one at a time, for at most \xA5${g}.`)),p.estimated_fidelity!==void 0&&p.estimated_fidelity<.5&&i.push(t.tone(`Estimated fidelity is only ${p.estimated_fidelity.toFixed(2)}, below 0.5: the result may be mostly noise. Try a shallower circuit or a smaller problem.`,"needs")),p.uncalibrated?.qubits.length&&i.push(t.dim(`No current calibration for qubits: ${p.uncalibrated.qubits.join(", ")}`)),p.uncalibrated?.couplers.length&&i.push(t.dim(`No current calibration for couplers: ${p.uncalibrated.couplers.map(([m,y])=>`${m}\u2013${y}`).join(", ")}`)),o&&i.push(t.dim(o));let b=Rr(e);return b&&i.push(b),i.push(""),i.push(e.mode==="sandbox"?`These ${p.circuits} circuit${p.circuits===1?" was":"s were"} compiled in this conversation's sandbox. Run on hardware submits them: the device service sends them as compiled, each once, and follows them; you can stop the run from the conversation.`:`Run on hardware submits ${p.circuits===1?"this circuit":`these ${p.circuits} circuits`} to the device as one hardware job.`),i.push(t.dim(this.pays(r))),i}let a=e;a.paid_machine===!0&&i.push(t.tone(`${a.target} is one of ${r}'s paid machines. ${r} charges this run to your own ${r} account, at its own price, which QuPai does not know. A task cannot be cancelled once it is sent.`,"needs"),"");let l=a.compilation;n("Device",`${a.target} (${r})`),n("Shots",String(a.shots)),typeof l.shots=="number"&&l.shots!==a.shots&&n("Shots run",String(l.shots)),n("Qubits",a.layout_mode==="physical_pool"?`chosen by hand: ${a.qids.join(", ")}`:"automatic compiler layout"),l.swap_count!=null&&n("SWAP gates added",String(l.swap_count));let c=l.qids??[];if(c.length?n("Layout",c.map((p,f)=>`q${f}\u2192${p}`).join(" ")):i.push(t.dim("The compiler did not report a logical-qubit layout.")),o&&i.push(t.dim(o)),a.mode==="sandbox"&&a.terms){let p=a.terms,f=p.estimated_cost_yuan!==void 0?`\xA5${Ws(p.estimated_cost_yuan)}`:p.tasks!==void 0?`${p.tasks} task${p.tasks===1?"":"s"}`:p.machine_seconds_min!==void 0?`at least ${p.machine_seconds_min} s of machine time`:"";n("Price",[f,p.cost_note??""].filter(Boolean).join(" \xB7 ")||"not reported by the provider")}else n("Price",`not reported by the provider: check it in your ${r} account`);let h=Rr(a);h&&i.push(h),i.push(""),i.push(t.dim(`Source circuit (logical qubits; ${a.baseline.result.num_qubits} qubits, ${a.baseline.result.shots} simulation shots):`));for(let p of a.baseline.input.code.split(`
|
|
114
|
+
`)||"(empty)")}return b.map(w=>_(w,e,""))}},jr=class{paint;part;waiting;constructor(e,t,i){this.paint=e,this.part=t,this.waiting=i}invalidate(){}render(e){let t=this.paint,i=this.part;if(i.type==="ask_user_question"){let o=[],a=Array.isArray(i.detail.questions)?i.detail.questions:[];for(let l of a)o.push(...M(`${t.tone("?","needs")} ${String(l.question??"")}`,e-2).map(h=>" "+h)),(Array.isArray(l.options)?l.options:[]).forEach((h,u)=>o.push(_(` ${u+1}. ${String(h.label??"")}${h.description?t.dim(` \u2014 ${String(h.description)}`):""}`,e,"")));return o.push(t.dim(" (answer it in your next message)")),o}let n=i.type==="mcp_input"?`${String(i.detail.server??"an MCP server")} asks for input`:i.type==="exit_plan_mode"?"a plan to confirm":`approval for ${i.tool??"a tool"}`,r=this.waiting()?t.tone("waits for you (Enter on an empty line shows it)","needs"):t.dim("answered");return[_(` ${t.tone("\u25C6","needs")} ${n} ${r}`,e,"")]}},Fi=class extends ee{answer;tools=[];paint;views=new Map;ending;onToggle;turnId;actions=()=>{};onRun;constructor(e,t,i={}){super(),this.paint=e,this.answer=t,this.turnId=i.turnId,i.actions&&(this.actions=i.actions),this.onRun=i.onRun,this.ending=new Gr(e,t),this.sync()}offers(){let e=this.actions();for(let t of this.tools)t.offer=Ns(t.part,this.answer,e)}sync(){let e=!1;for(let t of this.answer.parts){let i=this.views.get(t);i||(i=this.viewFor(t),this.views.set(t,i),this.removeChild(this.ending),this.addChild(i),e=!0),t.kind==="text"&&i instanceof Kt&&i.setText(t.text)}(e||!this.children.includes(this.ending))&&(this.removeChild(this.ending),this.addChild(this.ending)),this.offers();for(let t of this.children)t.invalidate()}viewFor(e){let t=this.paint;switch(e.kind){case"text":return new Kt(e.text,2,0,uc(t));case"tool":{let i=new Vr(t,e);return i.onToggle=()=>this.onToggle?.(),i.onAct=()=>{i.offer&&this.onRun?.(i.offer,i)},this.tools.push(i),i}case"input":return new ft(t,e.text);case"interrupt":return new jr(t,e,()=>this.answer.state==="awaiting_approval"&&this.answer.parts.at(-1)===e)}}},Gr=class{paint;answer;constructor(e,t){this.paint=e,this.answer=t}invalidate(){}render(e){let t=this.paint;switch(this.answer.state){case"aborted":return[_(` ${t.tone("stopped","stopped")}`,e,"")];case"error":return M(` ${t.tone("failed:","failed")} ${this.answer.error??""}`,e);default:return[]}}},ln=class{text="";tone="muted";paint;constructor(e){this.paint=e}set(e,t="muted"){this.text=e,this.tone=t}get value(){return this.text}clear(){this.text=""}invalidate(){}render(e){return this.text?M(this.paint.tone(this.text,this.tone),e):[]}},Sm={idle:["ready","muted"],writing:["writing\u2026","brand"],needs:["? needs you","needs"],stopped:["stopped","stopped"],failed:["! failed","failed"]},cn=class{paint;info;constructor(e,t){this.paint=e,this.info=t}invalidate(){}render(e){let t=this.paint,i=this.info(),[n,r]=Sm[i.state],o=i.unread?` ${t.tone(`${i.unread>99?"99+":i.unread} unread`,"needs")}`:"",a=`${t.wordmark()} ${t.tone(n,r)}${o}`,l=[mt(i.agent)+(i.place?` in ${i.place}`:""),i.org,mc(i.platform)].filter(Boolean).join(" \xB7 "),c=t.dim("? keys"),u=(i.update?[`Update available: ${i.update} \xB7 /update`,"/update"]:[]).find(b=>x(a)+x(b)+x(c)+6<=e),d=u?`${t.tone(u,"needs")} ${c}`:c,p=e-x(a)-x(d)-4,f=p>3?t.dim(_(l,p)):"",m=`${a} ${f}`;return[_(J(m,Math.max(0,e-x(d)))+d,e,"")]}},hn=class{paint;files;constructor(e,t){this.paint=e,this.files=t}invalidate(){}render(e){let t=this.files();if(!t.length)return[];let i=this.paint,n=t.map(o=>i.tone(`[${o.name} ${ce(o.size)}]`,"brand")),r=i.dim(t.length===1?"goes with your next message \xB7 Backspace removes it":"go with your next message \xB7 Backspace removes the last");return M(`${n.join(" ")} ${r}`,Math.max(1,e-1)).map(o=>` ${o}`)}};function De(s,e,t,i,n,r="brand"){let o=Math.max(4,e-4),a=d=>s.tone(d,r),l=` ${t} `,c=a("\u256D\u2500")+s.bold(_(l,o,""))+a("\u2500".repeat(Math.max(0,o-x(l)))+"\u2500\u256E"),h=i.map(d=>`${a("\u2502")} ${J(_(d,o,""),o)} ${a("\u2502")}`),u=n?[`${a("\u2502")} ${J(" ".repeat(o),o)} ${a("\u2502")}`,`${a("\u2502")} ${J(s.dim(_(n,o,"")),o)} ${a("\u2502")}`]:[];return[c,...h,...u,a(`\u2570${"\u2500".repeat(o+2)}\u256F`)]}var yc=s=>s.length>0&&!/[\x00-\x1f\x7f]/.test(s),gt=class{paint;title;items;list;empty;filter="";onPick;onCancel;capturesViewportInput=!0;constructor(e,t,i,n={}){this.paint=e,this.title=t,this.items=i,this.empty=n.empty??"nothing to choose",this.list=this.make(i),n.selected!==void 0&&n.selected>=0&&this.list.setSelectedIndex(n.selected)}make(e){let t=new Ve(e,12,rn(this.paint),{minPrimaryColumnWidth:20,maxPrimaryColumnWidth:44});return t.onSelect=i=>this.onPick?.(i.value),t.onCancel=()=>this.onCancel?.(),t}refilter(){let e=this.filter.toLowerCase().split(/\s+/).filter(Boolean),t=this.items.filter(i=>e.every(n=>`${i.label} ${i.description??""}`.toLowerCase().includes(n)));this.list=this.make(t)}invalidate(){this.list.invalidate()}handleInput(e){if(S(e,T.backspace)){this.filter=this.filter.slice(0,-1),this.refilter();return}if(yc(e)&&!(e===" "&&!this.filter)){this.filter+=e,this.refilter();return}this.list.handleInput(e)}render(e){let t=this.items.length?this.list.render(Math.max(10,e-4)):[this.paint.dim(this.empty)],i=this.filter?`${this.title} \xB7 ${this.filter}`:this.title;return De(this.paint,e,i,t,"\u2191\u2193 choose \xB7 Enter pick \xB7 type to filter \xB7 Esc close")}},Qt=class{paint;title;lines;scroll=0;scrolls=!1;onClose;maxRows=()=>1e3;constructor(e,t,i){this.paint=e,this.title=t,this.lines=i}invalidate(){}handleInput(e){if(this.scrolls){if(S(e,T.up))return void(this.scroll=Math.max(0,this.scroll-1));if(S(e,T.down))return void(this.scroll+=1);if(S(e,T.pageUp))return void(this.scroll=Math.max(0,this.scroll-10));if(S(e,T.pageDown))return void(this.scroll+=10)}this.onClose?.()}render(e){let t=Math.max(4,e-4),i=this.lines().flatMap(r=>M(r,t)),n=Math.max(3,this.maxRows()-4);if(this.scrolls=i.length>n,this.scrolls){this.scroll=Math.min(this.scroll,i.length-n+1);let r=i.slice(this.scroll,this.scroll+n-1);r.push(this.paint.dim(`lines ${this.scroll+1}-${this.scroll+r.length} of ${i.length} \xB7 \u2191\u2193 PgUp PgDn scroll`)),i=r}else this.scroll=0;return De(this.paint,e,this.title,i,this.scrolls?"any other key closes":"any key closes")}},te=class{capturesViewportInput=!0;paint;title;footer;empty;keys;free;items;list;note="";noteTone="muted";onPick;onKey;onCancel;constructor(e,t,i,n){this.paint=e,this.title=t,this.footer=n.footer,this.empty=n.empty??"nothing here",this.free=n.free??[],this.keys=[...n.keys??[],...this.free],this.items=i,this.list=this.make(i),n.selected!==void 0&&n.selected>=0&&this.list.setSelectedIndex(n.selected)}make(e){let t=new Ve(e,12,rn(this.paint),{minPrimaryColumnWidth:20,maxPrimaryColumnWidth:48});return t.onSelect=i=>this.onPick?.(i.value),t.onCancel=()=>this.onCancel?.(),t}get selected(){return this.list.getSelectedItem()?.value}setItems(e,t){let i=t??this.selected;this.items=e,this.list=this.make(e);let n=e.findIndex(r=>r.value===i);n>=0&&this.list.setSelectedIndex(n)}setTitle(e){this.title=e}say(e,t="muted"){this.note=e,this.noteTone=t}invalidate(){this.list.invalidate()}handleInput(e){let t=e.length===1?e.toLowerCase():"";if(t&&this.keys.includes(t)){let i=this.selected;(i!==void 0||this.free.includes(t))&&this.onKey?.(t,i??"");return}yc(e)&&e!==" "||this.list.handleInput(e)}render(e){let t=Math.max(4,e-4),i=this.items.length?this.list.render(Math.max(10,t)):[this.paint.dim(this.empty)];return this.note&&i.push("",...M(this.paint.tone(this.note,this.noteTone),t)),De(this.paint,e,this.title,i,this.footer)}},bt=class{capturesViewportInput=!0;paint;title;question;input=new Te({prompt:""});_focused=!1;error="";onAnswer;onCancel;constructor(e,t,i,n=""){this.paint=e,this.title=t,this.question=i,n&&this.input.handleInput(`\x1B[200~${n}\x1B[201~`),this.input.onSubmit=r=>this.onAnswer?.(r),this.input.onEscape=()=>this.onCancel?.()}get focused(){return this._focused}set focused(e){this._focused=e,this.input.focused=e}refuse(e){this.error=e}invalidate(){}handleInput(e){if(S(e,T.ctrl("c")))return void this.onCancel?.();this.error="",this.input.handleInput(e)}render(e){let t=Math.max(4,e-4),i=[...M(this.question,t),"",this.input.render(t)[0]??""];return this.error&&i.push("",...M(this.paint.tone(this.error,"failed"),t)),De(this.paint,e,this.title,i,"Enter answers \xB7 Esc cancels")}},un=class{capturesViewportInput=!0;paint;title;intro;editor;initial;_focused=!1;note="";noteTone="muted";warned=!1;busy=!1;onSave;onCancel;requestRender;constructor(e,t,i,n,r){this.paint=t,this.title=i,this.intro=n,this.initial=r,this.editor=new st(e,on(t),{paddingX:1}),this.editor.setText(r)}get focused(){return this._focused}set focused(e){this._focused=e,this.editor.focused=e}get text(){return this.editor.getExpandedText()}invalidate(){this.editor.invalidate()}handleInput(e){if(!this.busy){if(S(e,T.ctrl("s"))){this.busy=!0,this.note="Saving\u2026",this.noteTone="muted",(this.onSave?.(this.text)??Promise.resolve()).then(t=>{this.busy=!1,this.note=t||"",this.noteTone="failed",this.requestRender?.()},t=>{this.busy=!1,this.note=t instanceof Error?t.message:String(t),this.noteTone="failed",this.requestRender?.()});return}if(S(e,T.escape)){if(this.text.trim()!==this.initial.trim()&&!this.warned){this.warned=!0,this.note="Your changes are not saved: Esc again leaves them, Ctrl+S saves them",this.noteTone="needs";return}this.onCancel?.();return}this.warned=!1,this.note="",S(e,T.enter)?this.editor.handleInput(`
|
|
115
|
+
`):this.editor.handleInput(e)}}render(e){let t=Math.max(4,e-4),i=[...M(this.intro,t),"",...this.editor.render(t)];return this.note&&i.push(...M(this.paint.tone(this.note,this.noteTone),t)),De(this.paint,e,this.title,i,"Enter a new line \xB7 Ctrl+S save \xB7 Esc cancel")}},Ye=class{paint;question;onAnswer;constructor(e,t){this.paint=e,this.question=t}invalidate(){}handleInput(e){e==="y"||e==="Y"?this.onAnswer?.(!0):(e==="n"||e==="N"||S(e,T.escape)||S(e,T.ctrl("c")))&&this.onAnswer?.(!1)}render(e){return De(this.paint,e,"Confirm",M(this.question,Math.max(4,e-4)),"Y yes \xB7 N or Esc no","needs")}},qe=s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},ve=s=>typeof s=="string"?s:"";function gc(s){for(let e of["oneOf","anyOf"]){let t=s[e];if(Array.isArray(t))return t.map(qe).filter(i=>typeof i.const=="string").map(i=>({value:i.const,label:String(i.title??i.const)}))}if(Array.isArray(s.enum)){let e=Array.isArray(s.enumNames)?s.enumNames:[];return s.enum.map((t,i)=>({value:String(t),label:String(e[i]??t)}))}}function Cm(s){return(Array.isArray(s.requests)?s.requests:[]).map(qe).flatMap(t=>{if(typeof t.key!="string"||t.mode!=="form"&&t.mode!=="url")return[];let i=qe(t.requested_schema),n=new Set(Array.isArray(i.required)?i.required:[]),r=Object.entries(qe(i.properties)).map(([o,a])=>{let l=qe(a),c={request:t.key,name:o,label:String(l.title??o),description:ve(l.description)||void 0,required:n.has(o)};if(l.type==="boolean")return{...c,kind:"boolean"};if(l.type==="number")return{...c,kind:"number"};if(l.type==="integer")return{...c,kind:"integer"};if(l.type==="array")return{...c,kind:"multi",options:gc(qe(l.items))??[]};let h=gc(l);return h?{...c,kind:"select",options:h}:{...c,kind:"text"}});return[{key:t.key,mode:t.mode,message:ve(t.message),url:ve(t.url)||void 0,fields:r}]})}var bc=s=>s!==void 0&&s!==""&&!(Array.isArray(s)&&s.length===0);function $m(s,e){let t=Array.isArray(s.detail.action_requests)?s.detail.action_requests.map(qe):[],i=[ve(t[0]?.name),s.tool??""].find(a=>a.includes("."))??"",n=i.slice(0,i.indexOf(".")),r=n?e.find(a=>a.listing===n):void 0;if(!r)return;let o=qe(t[0]?.args??t[0]?.arguments);return{lab:r,machine:ve(o.instrument)||ve(o.machine)||void 0}}var dn=class{capturesViewportInput=!0;ctx;onAnswer;onClose;maxRows=()=>24;paint;mode="view";comment=new Te({prompt:""});editor=new Te({prompt:""});requests;values=new Map;opened=new Set;field=0;scroll=0;busy=!1;error="";_focused=!1;constructor(e,t){this.paint=e,this.ctx=t,this.requests=t.part.type==="mcp_input"?Cm(t.part.detail):[];for(let i of this.requests)this.values.set(i.key,{});this.comment.onSubmit=i=>{this.send("reject",i)},this.comment.onEscape=()=>this.mode="view",this.editor.onSubmit=i=>this.saveField(i),this.editor.onEscape=()=>this.mode="view"}get focused(){return this._focused}set focused(e){this._focused=e,this.comment.focused=e&&this.mode==="comment",this.editor.focused=e&&this.mode==="edit"}get kind(){return this.ctx.part.type}invalidate(){}get slots(){return this.requests.flatMap(e=>e.mode==="url"?[{request:e}]:e.fields.map(t=>({request:e,field:t})))}saveField(e){let i=this.slots[this.field]?.field;if(!i)return;let n=this.values.get(i.request)??{},r=e;if(i.kind==="number"||i.kind==="integer")if(e.trim()==="")r=void 0;else{let o=Number(e);if(!Number.isFinite(o)||i.kind==="integer"&&!Number.isInteger(o)){this.error=`${i.label} takes ${i.kind==="integer"?"a whole number":"a number"}`;return}r=o}i.kind==="multi"&&(r=e.split(",").map(o=>o.trim()).filter(Boolean)),r===void 0||r===""?delete n[i.name]:n[i.name]=r,this.values.set(i.request,n),this.error="",this.mode="view"}activate(){let e=this.slots[this.field];if(!e)return;if(!e.field){this.opened.add(e.request.key);return}let t=e.field,i=this.values.get(t.request)??{};if(t.kind==="boolean"){i[t.name]=i[t.name]!==!0,this.values.set(t.request,i);return}if(t.kind==="select"&&t.options?.length){let r=t.options.findIndex(o=>o.value===i[t.name]);i[t.name]=t.options[(r+1)%t.options.length].value,this.values.set(t.request,i);return}let n=i[t.name];this.editor.setValue(n===void 0?"":Array.isArray(n)?n.join(", "):String(n)),this.mode="edit",this.focused=this._focused}body(){let e=this.ctx.part;return{interrupt_id:e.interruptId,tool_call_id:e.toolCallId,type:e.type}}async send(e,t=""){if(this.busy)return;let i=this.body();if(this.kind==="exit_plan_mode"&&(i.answers={approved:e==="approve"?"true":"false",feedback:t}),this.kind==="mcp_input"&&e==="approve"){let n=this.slots.find(o=>o.field?.required&&!bc(this.values.get(o.request.key)?.[o.field.name]));if(n?.field){this.error=`Fill ${n.field.label} first`;return}let r={};for(let o of this.requests)o.mode==="form"?r[o.key]={action:"accept",content:Object.fromEntries(Object.entries(this.values.get(o.key)??{}).filter(([,a])=>bc(a)))}:this.opened.has(o.key)&&(r[o.key]={action:"accept"});i.responses=r}this.busy=!0,this.error="";try{await this.onAnswer?.({decision:e,...t?{comment:t}:{},detail:i})}catch(n){this.error=n instanceof Error?n.message:String(n),this.mode="view"}finally{this.busy=!1}}handleInput(e){if(this.busy)return;if(this.mode==="comment"){this.comment.handleInput(e);return}if(this.mode==="edit"){this.editor.handleInput(e);return}if(e==="a"||e==="A"){if(this.ctx.record?.credential?.configured===!1){this.error=`Approving needs your own key for ${this.ctx.record.credential.provider}: add it in the app first`;return}this.send("approve");return}if(e==="r"||e==="R"){this.comment.setValue(""),this.mode="comment",this.focused=this._focused;return}if(S(e,T.escape)){this.onClose?.();return}let t=this.kind==="mcp_input";S(e,T.up)?t?this.field=Math.max(0,this.field-1):this.scroll=Math.max(0,this.scroll-1):S(e,T.down)?t?this.field=Math.min(Math.max(0,this.slots.length-1),this.field+1):this.scroll+=1:S(e,T.pageUp)?this.scroll=Math.max(0,this.scroll-10):S(e,T.pageDown)?this.scroll+=10:t&&(S(e,T.enter)||e===" ")&&this.activate()}title(){let e=this.ctx.part;return e.type==="mcp_input"?`${ve(e.detail.server)||"An MCP server"} asks for input`:e.type==="exit_plan_mode"?"A plan to confirm":"Approval"}lines(e){let t=this.paint,i=this.ctx.part,n=(u,d)=>M(`${t.dim(u.padEnd(9))}${d}`,e),r=[];if(r.push(...n("Agent",this.ctx.agent)),i.type==="mcp_input")return this.slots.forEach((u,d)=>{let p=d===this.field,f=p?t.tone("\u203A","brand"):" ";if(!u.field){(d===0||this.slots[d-1]?.request!==u.request)&&r.push("",...M(u.request.message,e)),r.push(...M(`${f} ${u.request.url??"(no address)"} ${this.opened.has(u.request.key)?t.tone("opened","ok"):t.dim("open it, then Enter")}`,e));return}(d===0||this.slots[d-1]?.request!==u.request)&&r.push("",...M(u.request.message,e));let m=u.field,b=this.values.get(m.request)?.[m.name],g=p&&this.mode==="edit"?"":b===void 0?t.dim(m.kind==="boolean"?"no":m.kind==="select"?`choose: ${m.options?.map(w=>w.label).join(", ")}`:"(empty)"):m.kind==="boolean"?b===!0?"yes":"no":m.kind==="select"?m.options?.find(w=>w.value===b)?.label??String(b):Array.isArray(b)?b.join(", "):String(b),y=`${m.label}${m.required?" *":""}`;if(p&&this.mode==="edit"){let w=this.editor.render(Math.max(4,e-x(y)-4))[0]??"";r.push(`${f} ${t.bold(y)}: ${w}`)}else r.push(...M(`${f} ${t.bold(y)}: ${g}`,e));p&&m.description&&r.push(...M(` ${t.dim(m.description)}`,e))}),this.slots.length||r.push("",t.dim("(the server asks for nothing to fill in)")),r;let o=Array.isArray(i.detail.action_requests)?i.detail.action_requests.map(qe):[],a=i.tool??ve(o[0]?.name);r.push(...n("Tool",t.bold(a||"a tool")));let l=$m(i,this.ctx.labs);l&&(r.push(...n("Lab",`${U(l.lab.name,l.lab.id)} (${l.lab.id})`)),l.machine&&r.push(...n("Machine",l.machine)));let c=ve(i.detail.message)||ve(o[0]?.description);if(c&&r.push(...n("Why",c)),i.type==="exit_plan_mode")r.push("",t.dim("Plan")),r.push(...M(ve(i.detail.plan),e));else if(o.length)for(let u of o){let d=u.args??u.arguments;r.push("",t.dim(o.length>1?`Arguments of ${ve(u.name)||"the call"}`:"Arguments")),r.push(...M(d===void 0?"(none)":JSON.stringify(d,null,2),e))}let h=this.ctx.record?.credential;return h?.configured===!1&&r.push("",...M(t.tone(`Approving needs your own key for ${h.provider}: add it in the app first.`,"needs"),e)),r}render(e){let t=Math.max(4,e-4),i=this.lines(t);this.mode==="comment"&&i.push("",`${this.paint.tone("Why reject? (optional)","needs")}`,this.comment.render(t)[0]??""),this.busy&&i.push("",this.paint.dim("Sending\u2026")),this.error&&i.push("",...M(this.paint.tone(this.error,"failed"),t));let n=Math.max(3,this.maxRows()-5);if(i.length>n){this.scroll=Math.min(this.scroll,i.length-n);let o=i.slice(this.scroll,this.scroll+n-1);o.push(this.paint.dim(`lines ${this.scroll+1}-${this.scroll+o.length} of ${i.length} \xB7 \u2191\u2193 PgUp PgDn scroll`)),i=o}else this.scroll=0;let r=this.mode==="comment"?"Enter rejects \xB7 Esc back":this.mode==="edit"?"Enter keeps the value \xB7 Esc back":this.kind==="mcp_input"?"\u2191\u2193 field \xB7 Enter edit or open \xB7 A send \xB7 R decline \xB7 Esc close (it keeps waiting)":"A approve \xB7 R reject \xB7 Esc close (the turn keeps waiting)";return De(this.paint,e,this.title(),i,r,"needs")}};var Am="Run on hardware",Tm="Run again",Yt=["credits","balance"],Xt=[{id:1,name:"S2048"},{id:4,name:"S1601"}],_m="only the member's own sign-in compiles",Im="source result or action preview was refused",Pm=new Set(["result_expired","result_not_found"]),Rm=s=>s.length>0&&!/[\x00-\x1f\x7f]/.test(s),Qr=class{value="";pasting=!1;get length(){return this.value.length}clear(){this.value="",this.pasting=!1}take(){let e=this.value.trim();return this.clear(),e}handle(e){let t=e;if(t.includes("\x1B[200~")&&(this.pasting=!0,t=t.replace("\x1B[200~","")),this.pasting){let i=t.indexOf("\x1B[201~"),n=i>=0?t.slice(0,i):t;return this.value+=n.replace(/[\x00-\x1f\x7f]/g,""),i>=0&&(this.pasting=!1),!0}return S(t,T.backspace)?(this.value=this.value.slice(0,-1),!0):S(t,T.ctrl("u"))?(this.value="",!0):Rm(t)?(this.value+=t,!0):!1}render(e){return this.value?`${"\u2022".repeat(Math.min(this.value.length,Math.max(4,e-16)))} ${this.value.length} character${this.value.length===1?"":"s"}`:""}},pn=class{capturesViewportInput=!0;opts;onClose;onSubmitted;requestRender=()=>{};maxRows=()=>24;focused=!1;paint;services;step="provider";loading="";error="";note="";settings;directory;credentials=new Map;offered=[];providerCursor=0;provider="";secret=new Qr;catalog;deviceCursor=0;target="";shots="";mode="auto";pool=[];readout=!0;point;fixedNotes=new Map;caps;qubitCursor=0;machine=1;count="1";postProcess=!1;payment=null;optionCursor=0;preview;compiling=!1;requestId="";shownAt=0;button="run";scroll=0;busy=!1;abort;hits=[];bodyTop=1;closed=!1;pending=new Set;constructor(e,t,i){this.paint=e,this.services=t,this.opts=i;let n=i.offer.candidate;n.kind!=="optimization"&&(this.shots=String(Pl(n)),n.kind==="energy"&&n.scan&&(this.point=i.rerun?.point!==void 0&&n.scan.points.some(r=>r.index===i.rerun.point)?i.rerun.point:n.scan.defaultPoint))}get optimization(){return this.opts.offer.candidate.kind==="optimization"}get circuit(){return this.opts.offer.candidate.kind==="distribution"}get qubits(){let e=this.opts.offer.candidate;return e.kind==="optimization"?0:e.qubits}nameOf(e){return Il(e,this.directory)}get action(){return $r(this.opts.offer.actions).get(this.provider)??this.opts.offer.action}onWork;track(e){let t=e.finally(()=>{this.pending.delete(t),this.requestRender()});return this.pending.add(t),this.onWork?.(t.catch(()=>{})),t}async idle(){for(;this.pending.size;)await Promise.allSettled([...this.pending])}start(){this.loading="Reading your providers and keys\u2026",this.track(this.load())}async load(){try{if(this.optimization)this.settings=await this.services.settings().catch(()=>{});else{let[n,r]=await Promise.all([this.services.settings().catch(()=>{}),this.services.providers()]);this.settings=n,this.directory=r}this.offered=_l(this.opts.offer,this.directory,this.settings,this.opts.rerun?.provider),await Promise.all(this.offered.map(async n=>{try{this.credentials.set(n,await this.services.credential(n))}catch(r){this.credentials.set(n,r instanceof Error?r:new Error(String(r)))}}));let e=this.optimization?"isingq":Ge(this.opts.offer.action),t=this.opts.rerun?.provider??e??"",i=this.allowed(t)?this.offered.indexOf(t):this.offered.findIndex(n=>this.allowed(n));this.providerCursor=Math.max(0,i),this.loading="",this.offered.length||(this.error="no provider can run this result from here")}catch(e){this.loading="",this.error=yt(e)}}allowed(e){return!this.settings||Tr(this.settings,e)}go(e){this.step=e,this.error="",this.scroll=0,e!=="key"&&this.secret.clear()}back(){switch(this.step){case"provider":this.close();return;case"key":case"device":this.note="",this.go("provider");return;case"options":this.optimization?this.go("provider"):this.go("device");return;case"qubits":this.go("options");return;case"preview":if(this.busy&&!this.compiling&&!this.abort)return;this.abort?.abort(),this.abort=void 0,this.busy=!1,this.compiling=!1,this.preview=void 0,this.go("options");return}}close(){this.closed||(this.closed=!0,this.abort?.abort(),this.secret.clear(),this.onClose?.())}chooseProvider(e){if(this.loading||this.busy)return;this.providerCursor=Math.max(0,this.offered.indexOf(e));let t=this.nameOf(e);if(!this.allowed(e)){this.error=`your organization has not enabled ${t}: ask its admin in the app`;return}let i=this.credentials.get(e);if(i instanceof Error||!i){this.error="",this.loading=`Reading whether a ${t} key is saved\u2026`,this.track(this.services.credential(e).then(n=>{this.credentials.set(e,n),this.loading=""},n=>{this.loading="",this.error=`could not read whether a ${t} key is saved: ${yt(n)}`}));return}if(e!==this.provider&&(this.provider=e,this.target="",this.pool=[],this.mode="auto",this.catalog=void 0),!i.configured){this.go("key");return}this.afterKey()}afterKey(){if(this.optimization){this.go("options"),this.optionCursor=this.optionRows().length-1;return}this.go("device"),this.loadCatalog(!1)}saveKey(){if(this.busy)return;if(!this.secret.length){this.error=`paste your ${this.nameOf(this.provider)} key first`;return}let e=this.secret.take(),t=this.provider,i=this.nameOf(t);this.busy=!0,this.error="",this.track(this.services.saveKey(t,e).then(n=>{this.busy=!1,this.credentials.set(t,n);let r=(n.masked_suffix??"").replace(/^[•*]+/,"");this.note=`Saved: your ${i} key${r?` ending ${r}`:""}, stored encrypted. Nothing was submitted.`,n.configured&&this.afterKey()},n=>{this.busy=!1,this.error=n instanceof Li?n.message:`the key was not saved: ${yt(n)}`}))}loadCatalog(e){let t=this.provider;this.loading=e?"Asking the provider for its devices again\u2026":`Reading ${this.nameOf(t)}'s devices\u2026`,this.error="",this.track((async()=>{try{let i=await this.services.catalog(t,e),n=Date.now()+6e4;for(let a=Di(i);a!==!1&&Date.now()<n&&!this.closed&&this.provider===t;a=Di(i))this.catalog=i,this.requestRender(),await new Promise(l=>setTimeout(l,Math.min(a,3e3))),i=await this.services.catalog(t,!1);if(this.provider!==t)return;this.catalog=i;let o=_r(i.data??[],this.qubits).findIndex(a=>a.target===this.target);this.deviceCursor=o>=0?o:0,i.configured?i.refresh.error&&!i.data&&(this.error=`the device list could not be read: ${i.refresh.error}`):this.error=`no ${this.nameOf(t)} key is saved`}catch(i){i instanceof Qe&&(i.code==="credential_missing"||i.code==="credential_invalid")?(this.credentials.delete(t),this.error=i.message):this.error=yt(i)}finally{this.loading=""}})())}get devices(){return _r(this.catalog?.data??[],this.qubits)}get device(){return this.catalog?.data?.find(e=>e.target===this.target)}chooseDevice(e){if(!this.busy){if(this.deviceCursor=Math.max(0,this.devices.indexOf(e)),e.online===!1){this.error=`${e.target} is offline`;return}if(!Fs(e,this.qubits)){this.error=`${e.target} cannot hold ${this.qubits} connected qubits${typeof e.largest_connected_qubits=="number"?` (at most ${e.largest_connected_qubits})`:""}`;return}e.target!==this.target&&(this.target=e.target,this.pool=[],this.caps=void 0),this.go("options"),this.optionCursor=this.optionRows().length-1}}openQubits(){if(this.mode="physical_pool",this.go("qubits"),this.caps?.data?.target===this.target)return;this.caps=void 0;let e=this.target;this.loading=`Reading ${e}'s qubits\u2026`,this.track((async()=>{try{let t=await this.services.capabilities(this.provider,e),i=Date.now()+6e4;for(let n=Di(t);n!==!1&&Date.now()<i&&!this.closed&&this.target===e;n=Di(t))await new Promise(r=>setTimeout(r,Math.min(n,3e3))),t=await this.services.capabilities(this.provider,e);if(this.target!==e)return;this.caps=t,t.data?t.data.qubit_ids.every(n=>/^(0|[1-9][0-9]*)$/.test(n))||(this.error="this provider names its qubits in a way a pool cannot use: choose Automatic"):this.error=`${e}'s qubits could not be read${t.refresh.error?`: ${t.refresh.error}`:""}`}catch(t){this.error=yt(t)}finally{this.loading=""}})())}toggleQubit(e){let t=this.caps?.data;if(t){if(!Ir(e,this.pool,t.qubit_ids,t.couplings,this.qubits)){this.error=this.pool.length>=this.qubits&&!this.pool.includes(e)?`${this.qubits} qubits are chosen: remove one first`:`qubit ${e} is not next to the ones chosen (the pool stays connected)`;return}this.error="",this.pool=this.pool.includes(e)?this.pool.filter(i=>i!==e):[...this.pool,e]}}get shotCount(){return/^\d+$/.test(this.shots)?Number(this.shots):Number.NaN}correctionFixed(){return Ar.has(this.provider)||this.fixedNotes.has(this.provider)}runArguments(){if(this.optimization)return{solver_options:{computer_type_id:this.machine,calculate_count:Number(this.count),post_process:this.postProcess,use_credit:this.payment==="credits"}};let e=this.provider!=="logicqubit"?{provider:this.provider}:{};if(this.circuit)return{target:this.target,shots:this.shotCount,layout_mode:this.mode,qids:this.mode==="physical_pool"?this.pool.map(Number):[],...e};let t=this.opts.offer.candidate,i=t.kind==="energy"&&t.scan;return{target:this.target,shots:this.shotCount,readout_correction:this.correctionFixed()||this.readout,...i&&this.point!==void 0?{point:this.point}:{},...e}}notReady(){if(this.optimization){let e=Number(this.count);return!/^\d+$/.test(this.count)||e<1||e>1e4?"the calculation count is a whole number from 1 to 10000":this.payment?"":"choose how the run is paid: QuPai never chooses it for you"}if(!this.device)return"choose a device first";if(!Ti(this.device,this.qubits))return`${this.target} cannot take this run`;if(!Number.isSafeInteger(this.shotCount)||this.shotCount<1)return"the shots are a whole number above 0";if(this.circuit&&this.mode==="physical_pool"){let e=this.caps?.data;if(!e||!Ml(this.pool,e,this.qubits))return`choose ${this.qubits} connected qubits by hand first, or Automatic`}return""}askPreview(){if(this.busy)return;let e=this.notReady();if(e){this.error=e;return}let t=new AbortController;this.abort=t,this.busy=!0,this.compiling=!1,this.preview=void 0,this.go("preview");let i=this.provider,n={source_turn_id:this.opts.turnId,source_tool_call_id:this.opts.offer.candidate.toolCallId,action_id:this.action.id,arguments:this.runArguments()};this.track(this.services.preview(n,()=>{this.compiling=!0,this.requestRender()},t.signal).then(r=>{if(!t.signal.aborted){if(Us(r)){if(r.options.computer_type_id!==this.machine||r.machine.computer_type_id!==this.machine)throw new Error("the preview did not keep the machine you chose: preview again");if(r.options.use_credit!==(this.payment==="credits"))throw new Error("the preview did not keep how you chose to pay: preview again")}else{let o=Rr(r);o?.fixedOn&&this.fixedNotes.set(i,o.note)}this.preview=r,this.requestId=crypto.randomUUID(),this.shownAt=Date.now(),this.button="run",this.scroll=0}}).catch(r=>{t.signal.aborted||(this.preview=void 0,this.step="options",this.error=this.previewError(r),r instanceof D&&r.type==="urn:qupai:problem:credential-required"&&(this.credentials.delete(i),this.go("key"),this.error=`${this.nameOf(i)} needs your key again: paste it here`))}).finally(()=>{this.abort===t&&(this.abort=void 0),this.busy=!1,this.compiling=!1}))}previewError(e){if(e instanceof je)return e.errorType&&Pm.has(e.errorType)?"This simulation result is no longer kept (results are kept for up to 7 days). Run the simulation again, then run it on hardware.":e.errorType==="sandbox_compile_timeout"?"The sandbox is still compiling this run after 10 minutes. Close this and try again later.":e.errorType==="sandbox_compile_failed"?`The sandbox could not compile this run: ${e.message}`:`The service refused this preview: ${e.message}`;if(e instanceof D){if(e.status===403&&e.detail.includes(_m))return`This run is wider than the device service compiles itself, and only your own sign-in in the app starts the sandbox that compiles it (${e.detail}). Run it from the conversation in the web app: ${this.opts.link}`;if(!this.circuit&&e.type==="urn:qupai:problem:invalid-request"&&e.detail.includes(Im))return"This result can't be run on hardware: it was probably computed before this action was offered. Run it again, then run the new result."}return yt(e)}submit(){let e=this.preview;if(!e||this.busy||Date.now()-this.shownAt<(this.opts.guardMs??500))return;this.busy=!0,this.error="";let t={source_turn_id:this.opts.turnId,action_id:this.action.id,preview_id:e.preview_id,request_id:this.requestId},i=this.summary(e);this.track(this.services.submit(t).then(n=>{this.busy=!1,this.onSubmitted?.({turn:n,summary:i}),this.close()},n=>{if(this.busy=!1,n instanceof D&&n.type==="urn:qupai:problem:credential-required"){this.credentials.delete(this.provider),this.preview=void 0,this.go("key"),this.error=`${this.nameOf(this.provider)} needs your key again: paste it here`;return}this.error=`not submitted: ${yt(n)}`}))}summary(e){if(Us(e))return`isingq ${e.machine.name} \xB7 ${e.options.calculate_count} calculation${e.options.calculate_count===1?"":"s"}`;let t=this.nameOf(this.provider);return Ws(e)?`${e.target} (${t}) \xB7 ${e.variational.circuits} circuit${e.variational.circuits===1?"":"s"} \xD7 ${e.shots} shots`:`${e.target} (${t}) \xB7 ${e.shots} shots`}handleInput(e){if(this.step==="key"&&this.busy)return;if(this.step==="key"){if(S(e,T.enter)){this.saveKey();return}if(S(e,T.escape)){this.back();return}if(this.secret.handle(e)){this.error="";return}return}if(S(e,T.escape)){this.back();return}let t=S(e,T.up),i=S(e,T.down),n=S(e,T.enter);switch(this.step){case"provider":{t?this.providerCursor=Math.max(0,this.providerCursor-1):i?this.providerCursor=Math.min(Math.max(0,this.offered.length-1),this.providerCursor+1):n&&this.offered[this.providerCursor]&&this.chooseProvider(this.offered[this.providerCursor]);return}case"device":{let r=this.devices;t?this.deviceCursor=Math.max(0,this.deviceCursor-1):i?this.deviceCursor=Math.min(Math.max(0,r.length-1),this.deviceCursor+1):n&&r[this.deviceCursor]?this.chooseDevice(r[this.deviceCursor]):e==="r"&&!this.loading&&this.loadCatalog(!0);return}case"options":this.optionKey(e);return;case"qubits":{let r=this.caps?.data?.qubit_ids??[];t?this.qubitCursor=Math.max(0,this.qubitCursor-1):i?this.qubitCursor=Math.min(r.length,this.qubitCursor+1):(n||e===" ")&&(this.qubitCursor===r.length?this.go("options"):r[this.qubitCursor]&&this.toggleQubit(r[this.qubitCursor]));return}case"preview":{if(!this.preview)return;S(e,T.left)||S(e,T.right)||S(e,T.tab)?this.button=this.button==="run"?"change":"run":t?this.scroll=Math.max(0,this.scroll-1):i?this.scroll+=1:S(e,T.pageUp)?this.scroll=Math.max(0,this.scroll-10):S(e,T.pageDown)?this.scroll+=10:n&&(this.button==="change"?this.back():this.submit());return}}}optionKey(e){let t=this.optionRows();if(S(e,T.up)){this.optionCursor=Math.max(0,this.optionCursor-1);return}if(S(e,T.down)||S(e,T.tab)){this.optionCursor=Math.min(t.length-1,this.optionCursor+1);return}let i=t[this.optionCursor];if(!i)return;if(i.type==="number"){let r=i.key==="count"?"count":"shots";if(S(e,T.backspace)){this[r]=this[r].slice(0,-1),this.preview=void 0;return}if(/^\d+$/.test(e)){this[r]=(this[r]+e).replace(/^0+(?=\d)/,"").slice(0,7);return}S(e,T.enter)&&(this.optionCursor=Math.min(t.length-1,this.optionCursor+1));return}let n=S(e,T.left)?-1:S(e,T.right)||e===" "?1:S(e,T.enter)?0:null;n!==null&&i.act(n)}optionRows(){let e=this.paint,t=[];if(this.optimization){let n=Xt.find(r=>r.id===this.machine);return t.push({key:"machine",type:"choice",label:"Machine",value:Xt.map(r=>r.id===n.id?e.bold(`(\u2022) ${r.name}`):`( ) ${r.name}`).join(" "),act:r=>this.cycleMachine(r)}),t.push({key:"count",type:"number",label:"Calculations",value:this.count,act:()=>{}}),t.push({key:"post",type:"choice",label:"Post-process",value:this.postProcess?"[x] the provider's post processing":"[ ] the provider's post processing",act:()=>this.postProcess=!this.postProcess}),t.push({key:"payment",type:"choice",label:"Payment",value:Yt.map(r=>`${this.payment===r?"(\u2022)":"( )"} ${r==="credits"?"Compute credits":"Account balance"}`).join(" ")+(this.payment?"":e.tone(" (required)","needs")),act:r=>this.cyclePayment(r)}),t.push({key:"preview",type:"button",label:"",value:"Preview the run",act:()=>this.askPreview()}),t}let i=this.device;if(t.push({key:"device",type:"button",label:"Device",value:i?`${i.target} ${e.dim(wc(i))}`:e.dim("choose one"),act:()=>this.go("device")}),t.push({key:"shots",type:"number",label:this.circuit?"Shots":"Shots/circuit",value:this.shots,act:()=>{}}),this.circuit){let n=this.mode==="physical_pool",r=n?this.pool.length?` ${e.dim(`${this.pool.length} of ${this.qubits}: ${this.pool.join(", ")}`)}`:` ${e.dim("none chosen yet")}`:"";t.push({key:"qubits",type:"choice",label:"Qubits",value:`${n?"( ) Automatic (\u2022) By hand":"(\u2022) Automatic ( ) By hand"}${r}`,act:o=>{if(o===0||!n){this.openQubits();return}this.mode="auto"}})}else{let n=this.correctionFixed();t.push({key:"readout",type:"choice",label:"Readout fix",value:n||this.readout?`[x] readout correction${n?e.dim(" (always on here)"):""}`:"[ ] readout correction",act:()=>{n||(this.readout=!this.readout)}});let r=this.opts.offer.candidate;if(r.kind==="energy"&&r.scan){let o=r.scan.points.find(a=>a.index===this.point)??r.scan.points[0];t.push({key:"point",type:"choice",label:"Bond length",value:`\u2039 ${o.bondLength} \xC5 \xB7 ${Ri(o.minEnergy.toFixed(6))} Ha \u203A`,act:a=>this.cyclePoint(a||1)})}}return t.push({key:"preview",type:"button",label:"",value:this.circuit?"Preview the compilation":"Preview cost and placement",act:()=>this.askPreview()}),t}cycleMachine(e){let t=Xt.findIndex(i=>i.id===this.machine);this.machine=Xt[(t+(e||1)+Xt.length)%Xt.length].id}cyclePayment(e){let t=this.payment?Yt.indexOf(this.payment):-1;this.payment=Yt[((t+(e||1))%Yt.length+Yt.length)%Yt.length]}cyclePoint(e){let t=this.opts.offer.candidate;if(t.kind!=="energy"||!t.scan)return;let i=t.scan.points,n=Math.max(0,i.findIndex(r=>r.index===this.point));this.point=i[(n+e+i.length)%i.length].index}handleMouse(e){return e.type==="wheel"?(this.step==="preview"&&(this.scroll=Math.max(0,this.scroll+(e.wheelDelta??0))),{handled:!0,render:!0}):e.type!=="click"||e.button!=="left"?{handled:!0}:(this.buttonRow&&e.y===this.buttonRow.y?this.clickButton(e.x):this.hits[e.y]?.(),{handled:!0,render:!0})}invalidate(){}title(){return this.opts.offer.candidate.kind==="optimization"?"Run on isingq":this.opts.rerun?"Run on hardware again":"Run on hardware"}what(){let e=this.opts.offer.candidate;switch(e.kind){case"distribution":return`Sampled circuit \xB7 ${e.qubits} qubit${e.qubits===1?"":"s"} \xB7 simulated with ${e.shots} shots`;case"energy":return e.scan?`Bond-length scan \xB7 ${Pi(e.molecule.name)} \xB7 ${e.qubits} qubits`:e.molecule?`VQE energy \xB7 ${Pi(e.molecule.name)} ${e.molecule.bondLength} \xC5 \xB7 ${e.qubits} qubits`:`VQE energy \xB7 ${e.qubits} qubits`;case"maxcut":return`QAOA Max-Cut \xB7 ${e.qubits} nodes`;case"optimization":return`${e.problem.toUpperCase()} \xB7 ${e.numVariables} variable${e.numVariables===1?"":"s"} \xB7 local objective ${e.objective}`}}pays(e){return`The run is submitted with your own ${e} key, so ${e} counts it against your account there, on its terms. QuPai does not pay the provider for you.`}rows(e){let t=this.paint,i=[],n=(r="",o,a)=>{M(r,e).forEach((c,h)=>i.push({text:c,hit:o,focus:a&&h===0}))};switch(n(t.bold(this.what())),n(""),this.step){case"provider":{if(n(t.dim("1 Provider 2 Device and shots 3 Preview 4 Run")),n(""),this.loading)break;this.offered.forEach((r,o)=>{let a=o===this.providerCursor,l=this.credentials.get(r),c=this.allowed(r)?l instanceof Error?t.tone("could not read whether a key is saved","failed"):l?l.configured?t.tone(`key saved${l.masked_suffix?` (ending ${l.masked_suffix.replace(/^[•*]+/,"")})`:""}`,"ok"):t.tone("no key saved: you paste it next","needs"):t.dim("\u2026"):t.tone("not enabled by your organization","stopped"),h=this.nameOf(r);n(`${a?t.tone("\u203A","brand"):" "} ${a?t.bold(h.padEnd(18)):h.padEnd(18)} ${c}`,()=>this.chooseProvider(r),a)}),this.offered.length&&(n(""),n(t.dim(this.pays(this.nameOf(this.offered[this.providerCursor]??"")))));break}case"key":{let r=this.nameOf(this.provider),o=this.credentials.get(this.provider);n(`No ${r} key is saved for you. Paste it here: it is sealed for the platform on this computer, sent once, stored encrypted and shown only by its last characters. Nothing is written on this computer and nothing is submitted.`),o&&!(o instanceof Error)&&o.signup_url&&/^https:\/\//.test(o.signup_url)&&n(t.dim(`No key yet? Get one at ${o.signup_url}`)),n("");let a=this.busy?t.dim("Saving\u2026"):this.secret.render(e-16)||t.dim("(paste or type the key)");n(`${t.dim(`${r} key`.padEnd(14))} ${a}`,void 0,!0);break}case"device":{let r=this.nameOf(this.provider);if(this.note&&n(t.tone(this.note,"ok")),n(t.dim(`Devices of ${r} with your key${this.catalog?.fetched_at?`, read ${Mm(this.catalog.fetched_at)}${this.catalog.stale?" (stale: r reads them again)":""}`:""}:`)),n(""),this.loading&&!this.catalog?.data)break;let o=this.devices;!o.length&&!this.loading&&n(t.dim("No devices came back for your key.")),o.forEach((a,l)=>{let c=l===this.deviceCursor,h=Ti(a,this.qubits),u=a.online===!1||Fs(a,this.qubits)?"":`too small for ${this.qubits} connected qubits`,d=`${c?t.tone("\u203A","brand"):" "} ${J(c?t.bold(a.target):a.target,16)} ${wc(a)}${u?` \xB7 ${u}`:""}`;n(h?d:t.dim(d),()=>this.chooseDevice(a),c)}),this.provider==="baqis"&&n(t.dim(`Quafu-SQC runs shots in whole blocks of ${Ii}.`)),this.provider==="originq"&&n(t.dim("Origin Quantum reports readout-corrected probabilities only, and bills machine time.")),this.provider==="tianyan"&&n(t.dim("Tianyan reports readout-corrected probabilities only and charges a task on one of its paid machines to your own Tianyan account (the preview says when a machine is paid). A task cannot be cancelled once it is sent."));break}case"options":{this.note&&this.optimization&&n(t.tone(this.note,"ok")),this.optimization&&n(t.dim("Machine types this integration supports; isingq checks availability and your access when the run is submitted. Submitted tasks cannot be cancelled through QuPai."));let r=this.optionRows();if(this.optionCursor=Math.min(this.optionCursor,r.length-1),r.forEach((o,a)=>{let l=a===this.optionCursor,c=l?t.tone("\u203A","brand"):" ";if(o.type==="button"){let u=o.label?`${t.dim(o.label.padEnd(14))}${o.value}`:l?t.inverse(` ${o.value} `):`[ ${o.value} ]`;o.label||n(""),n(`${c} ${u}`,()=>{this.optionCursor=a,o.act(0)},l);return}let h=o.type==="number"?`${l?t.inverse(` ${o.value||" "} `):`[ ${o.value} ]`}`:o.value;n(`${c} ${t.dim(o.label.padEnd(14))}${h}`,()=>{this.optionCursor=a,o.type!=="number"&&o.act(1)},l)}),n(""),!this.optimization){let o=this.opts.offer.candidate;this.circuit?n(t.dim(this.mode==="auto"?"Automatic: the compiler chooses the layout on the device.":`By hand: the compiler maps the circuit within the ${this.qubits} connected qubits you choose; the order you choose them in is not the mapping.`)):n(t.dim("The server places the circuits on connected qubits of the device; the preview shows which, and the cost.")),this.correctionFixed()&&n(t.dim(this.fixedNotes.get(this.provider)??`${this.nameOf(this.provider)} returns readout-corrected results only, so runs there are always sent with readout correction on.`)),this.provider==="baqis"&&Number.isSafeInteger(this.shotCount)&&this.shotCount%Ii&&n(t.dim(`${this.shotCount} shots run as ${Math.ceil(this.shotCount/Ii)*Ii}.`)),o.kind!=="optimization"&&n(t.dim(this.pays(this.nameOf(this.provider))))}break}case"qubits":{let r=this.caps?.data;if(n(`Choose ${this.qubits} connected qubits of ${this.target}. The compiler maps the circuit within them; the order you choose them in is not the mapping.`),n(t.dim(`Chosen ${this.pool.length} of ${this.qubits}${this.pool.length?`: ${this.pool.join(", ")}`:""}`)),n(""),!r)break;r.qubit_ids.forEach((a,l)=>{let c=l===this.qubitCursor,h=this.pool.includes(a),u=Ir(a,this.pool,r.qubit_ids,r.couplings,this.qubits),d=h?"[x]":"[ ]",p=`${c?t.tone("\u203A","brand"):" "} ${h?t.tone(d,"brand"):d} ${J(a,5)} ${El(r,a)}`;n(u||h?p:t.dim(p),()=>{this.qubitCursor=l,this.toggleQubit(a)},c)});let o=this.qubitCursor===r.qubit_ids.length;n(""),n(`${o?t.tone("\u203A","brand"):" "} ${o?t.inverse(" Done "):"[ Done ]"}`,()=>this.go("options"),o);break}case"preview":{if(!this.preview){n(this.compiling?"Compiling in the sandbox\u2026":this.circuit?"Checking and compiling\u2026":this.optimization?"Preparing the preview\u2026":"Placing and estimating\u2026"),this.compiling&&n(t.dim("This run is wider than the device service compiles itself, so this conversation's sandbox compiles it for the device. That can take a minute or two. Nothing is sent to hardware."));break}for(let r of this.previewLines(this.preview))n(r);break}}return this.loading&&n(t.dim(this.loading)),this.error&&(n(""),n(t.tone(this.error,"failed"))),i}previewLines(e){let t=this.paint,i=[],n=(p,f)=>i.push(`${t.dim(p.padEnd(18))}${f}`);if(i.push(t.bold("Review this run: nothing has been sent yet")),i.push(""),Us(e))return n("Machine",e.machine.name),n("Maximum variables",String(e.machine.max_variables)),n("Variables",String(e.baseline.num_variables)),n("Local objective",String(e.baseline.objective_value)),n("Calculations",String(e.options.calculate_count)),n("Post-processing",e.options.post_process?"yes":"no"),n("Payment",e.options.use_credit?"Compute credits":"Account balance"),n("Model SHA-256",e.baseline.model_hash),i.push(""),i.push(`${e.options.use_credit?"This run spends compute credits from your isingq account.":"This run is charged to the balance of your isingq account."} Run on hardware submits this exact preview, once. Hardware precision may affect the solution.`),i;let r=this.nameOf(this.provider),o=Rr(e)?.note??(Ar.has(this.provider)?`${r} returns readout-corrected results only, so runs there are always sent with readout correction on.`:void 0);if(Ws(e)){let p=e.variational;p.paid_machine===!0&&i.push(t.tone(`${e.target} is one of ${r}'s paid machines. ${r} charges each of these ${p.circuits} tasks to your own ${r} account, at its own price, which QuPai does not know. A task cannot be cancelled once it is sent.`,"needs"),""),i.push(t.dim(Em(e))),n("Device",`${e.target} (${r})`),n("Shots per circuit",String(e.shots)),n("Physical qubits",e.qids.join(", ")),n("Circuits",String(p.circuits)),n("Total shots",String(p.total_shots));let f=typeof p.estimated_cost_yuan=="number",m=f?Ks(p.estimated_cost_yuan):"";n("Estimated cost",f?p.billing_multiplier!==void 0&&p.billing_multiplier!==1?`about \xA5${m} (at the \xD7${p.billing_multiplier} billing multiplier)`:`\xA5${m}`:p.tasks!==void 0?`${p.tasks} task${p.tasks===1?"":"s"}`:p.machine_seconds_min!==void 0?`at least ${p.machine_seconds_min} s of machine time`:"\u2014"),n("CZ gates",p.cz_count===null?"\u2014":String(p.cz_count)),n("Circuit depth",p.depth===null?"\u2014":String(p.depth)),n("Est. fidelity",p.estimated_fidelity===void 0?"\u2014":p.estimated_fidelity.toFixed(3)),n("Readout fix",e.readout_correction?"on":"off"),p.cost_note&&!f&&i.push(t.dim(p.cost_note)),p.submission==="auto"&&p.batch_cost_yuan!==void 0&&i.push(t.dim(`A batch is tried first (about \xA5${Ks(p.batch_cost_yuan)}); if your subscription doesn't take batch tasks, the circuits are submitted one at a time, for at most \xA5${m}.`)),p.estimated_fidelity!==void 0&&p.estimated_fidelity<.5&&i.push(t.tone(`Estimated fidelity is only ${p.estimated_fidelity.toFixed(2)}, below 0.5: the result may be mostly noise. Try a shallower circuit or a smaller problem.`,"needs")),p.uncalibrated?.qubits.length&&i.push(t.dim(`No current calibration for qubits: ${p.uncalibrated.qubits.join(", ")}`)),p.uncalibrated?.couplers.length&&i.push(t.dim(`No current calibration for couplers: ${p.uncalibrated.couplers.map(([g,y])=>`${g}\u2013${y}`).join(", ")}`)),o&&i.push(t.dim(o));let b=Mr(e);return b&&i.push(b),i.push(""),i.push(e.mode==="sandbox"?`These ${p.circuits} circuit${p.circuits===1?" was":"s were"} compiled in this conversation's sandbox. Run on hardware submits them: the device service sends them as compiled, each once, and follows them; you can stop the run from the conversation.`:`Run on hardware submits ${p.circuits===1?"this circuit":`these ${p.circuits} circuits`} to the device as one hardware job.`),i.push(t.dim(this.pays(r))),i}let a=e;a.paid_machine===!0&&i.push(t.tone(`${a.target} is one of ${r}'s paid machines. ${r} charges this run to your own ${r} account, at its own price, which QuPai does not know. A task cannot be cancelled once it is sent.`,"needs"),"");let l=a.compilation;n("Device",`${a.target} (${r})`),n("Shots",String(a.shots)),typeof l.shots=="number"&&l.shots!==a.shots&&n("Shots run",String(l.shots)),n("Qubits",a.layout_mode==="physical_pool"?`chosen by hand: ${a.qids.join(", ")}`:"automatic compiler layout"),l.swap_count!=null&&n("SWAP gates added",String(l.swap_count));let c=l.qids??[];if(c.length?n("Layout",c.map((p,f)=>`q${f}\u2192${p}`).join(" ")):i.push(t.dim("The compiler did not report a logical-qubit layout.")),o&&i.push(t.dim(o)),a.mode==="sandbox"&&a.terms){let p=a.terms,f=p.estimated_cost_yuan!==void 0?`\xA5${Ks(p.estimated_cost_yuan)}`:p.tasks!==void 0?`${p.tasks} task${p.tasks===1?"":"s"}`:p.machine_seconds_min!==void 0?`at least ${p.machine_seconds_min} s of machine time`:"";n("Price",[f,p.cost_note??""].filter(Boolean).join(" \xB7 ")||"not reported by the provider")}else n("Price",`not reported by the provider: check it in your ${r} account`);let h=Mr(a);h&&i.push(h),i.push(""),i.push(t.dim(`Source circuit (logical qubits; ${a.baseline.result.num_qubits} qubits, ${a.baseline.result.shots} simulation shots):`));for(let p of a.baseline.input.code.split(`
|
|
116
116
|
`))i.push(` ${p}`);let u=Object.entries(a.baseline.input.parameters??{});u.length&&i.push(t.dim("Bound parameters: ")+u.map(([p,f])=>`${p} = ${f}`).join(", "));let d=!l.compiled_python?.trim()&&l.compiled_program?.trim()?l.compiled_program:l.compiled_python;if(d?.trim()){i.push(""),i.push(t.dim(l.compiled_python?.trim()?"Compiled hardware circuit, as it is sent:":`Compiled program (${l.compiled_language??"the provider's"}), the exact program sent; the provider does not compile or remap it again:`));for(let p of d.split(`
|
|
117
|
-
`))i.push(` ${p}`)}return i.push(""),i.push(a.mode==="sandbox"?"This circuit was compiled in this conversation's sandbox. Run on hardware submits it for one hardware run: the device service sends it as compiled and follows it; you can stop the run from the conversation.":"Run on hardware submits this circuit, device, shot count and compiled layout for one hardware run."),i.push(t.dim(this.pays(r))),i}footer(){switch(this.step){case"provider":return"\u2191\u2193 choose \xB7 Enter continue \xB7 Esc close";case"key":return"paste the key \xB7 Enter save \xB7 Esc back";case"device":return"\u2191\u2193 choose \xB7 Enter pick \xB7 r read again \xB7 Esc back";case"options":return"\u2191\u2193 move \xB7 \u2190\u2192 Space change \xB7 digits for numbers \xB7 Enter on Preview \xB7 Esc back";case"qubits":return"\u2191\u2193 move \xB7 Space or Enter choose \xB7 Esc back";case"preview":return this.preview?"Enter on Run on hardware submits \xB7 \u2190\u2192 Change \xB7 \u2191\u2193 PgUp PgDn scroll \xB7 Esc back":"Esc back (stops waiting)"}}render(e){let t=Math.max(10,e-4),i=this.rows(t),n=Math.max(4,this.maxRows()-5-(this.step==="preview"&&this.preview?2:0)),r=0;if(i.length>n)if(this.step==="preview")this.scroll=Math.min(this.scroll,i.length-n),r=this.scroll;else{let l=i.findIndex(c=>c.focus);r=l<0?0:Math.min(Math.max(0,l-Math.floor(n/2)),i.length-n)}let o=i.slice(r,r+n),a=o.map(l=>l.text);if(this.hits=[],o.forEach((l,c)=>{l.hit&&(this.hits[this.bodyTop+c]=l.hit)}),i.length>n&&a.push(this.paint.dim(`lines ${r+1}-${r+o.length} of ${i.length}`)),this.step==="preview"&&this.preview){let l=this.busy?" Submitting\u2026 ":` ${vm} `,c=" Change ",h=(d,p)=>p?this.paint.inverse(this.paint.bold(d)):`[${d}]`;a.push("");let u=`${h(c,this.button==="change")} ${h(l,this.button==="run")}`;a.push(u),this.buttonRow={y:this.bodyTop+a.length-1,changeEnd:x(`[${c}]`)+1}}else this.buttonRow=void 0;return De(this.paint,e,this.title(),a.map(l=>_(l,t,"")),this.footer())}buttonRow;clickButton(e){this.buttonRow&&(e-2<this.buttonRow.changeEnd?this.back():(this.button="run",this.submit()))}};function yt(s){return s instanceof Error?s.message:String(s)}function bc(s){let e=Pl(s);return`${s.num_qubits??"?"} qubit${s.num_qubits===1?"":"s"} \xB7 ${e.state} \xB7 ${e.queue}`}function Tm(s){let e=Math.max(0,(Date.now()-Date.parse(s))/1e3);return Number.isFinite(e)?`${ht(Math.round(e))} ago`:"earlier"}function _m(s){let e=s.baseline;if(e.kind==="maxcut")return`QAOA Max-Cut \xB7 ${e.result.num_qubits} nodes`;let t=e.result.molecule;return t?`${e.point!==void 0?"Bond-length scan":"VQE"} \xB7 ${Ii(t.name)} ${t.bond_length} \xC5`:"VQE energy"}var Im=new Set(["submitted","running"]),Ni=s=>Im.has(s.status),Fi=class{paint;text;constructor(e,t){this.paint=e,this.text=t}invalidate(){}render(e){return["",...M(`${this.paint.tone("\u25B6","brand")} ${this.paint.bold(this.text)}`,e)]}},Wi=class{jobs=[];turnId;cards=[];paint;link;onRerun;canRerun=()=>!1;onToggle;constructor(e,t,i){this.paint=e,this.turnId=t,this.link=i}set(e){this.jobs=e;for(let t of e){if(Ni(t))continue;if(this.cards.some(n=>n.job.id===t.id)){this.cards.find(n=>n.job.id===t.id).job=t;continue}if(!Ks(t.detail)&&!Pi(t.detail)&&!jt(t.detail))continue;let i=new Ki(this.paint,t,this.link);i.onRerun=()=>this.onRerun?.(i.job),i.rerunnable=()=>this.canRerun(i.job),i.onToggle=()=>this.onToggle?.(),this.cards.push(i)}}get active(){return this.jobs.filter(Ni)}invalidate(){}handleMouse(e){let t=e.y-this.rowCount;for(let i of this.cards){let n=i.height;if(t>=0&&t<n)return i.handleMouse({...e,y:t});t-=n}}rowCount=0;render(e){let t=this.paint,i=[];for(let n of this.jobs){let r=Ni(n);if(this.cards.find(d=>d.job.id===n.id&&n.status==="succeeded"))continue;let a=r?t.tone("\u25CC","brand"):n.status==="succeeded"?t.tone("\u2713","ok"):n.status==="failed"?t.tone("\u2717","failed"):t.tone("\u25A0","stopped"),l=r&&n.cancel_requested?"stopping\u2026":n.status;i.push(_(` ${a} ${n.summary||n.tool||n.job_key} ${t.dim(`${n.kind} \xB7 ${l}`)}`,e,""));let c=n.detail,h=r&&n.kind==="hardware"?ql(c,Pi(c)?.variational.circuits??void 0):null;h&&i.push(...M(t.dim(` ${h}`),e));let u=c?.execution_warning;if(r&&typeof u=="string"&&u.trim()&&i.push(...M(t.dim(` ${u.trim()}`),e)),r&&n.kind==="hardware"&&!jt(c)&&!n.cancel_requested&&i.push(t.dim(" Esc on an empty line stops it")),!r&&n.status!=="succeeded"){let d=typeof c?.error=="string"?c.error:typeof c?.lost_reason=="string"?c.lost_reason:"";d&&i.push(...M(t.tone(` ${d}`,"failed"),e))}}this.rowCount=i.length;for(let n of this.cards)i.push(...n.render(e));return i}},Ki=class{job;selected=!1;expanded=!1;onRerun;onToggle;rerunnable=()=>!1;paint;link;lastHeight=0;buttonAt;constructor(e,t,i){this.paint=e,this.job=t,this.link=i}get height(){return this.lastHeight}act(){this.rerunnable()&&this.onRerun?.()}invalidate(){}handleMouse(e){if(!(e.type!=="click"||e.button!=="left")){if(e.y===1&&this.buttonAt&&e.x>=this.buttonAt.from&&e.x<this.buttonAt.to)return this.act(),{handled:!0};if(e.y===1)return this.expanded=!this.expanded,this.onToggle?.(),{handled:!0}}}render(e){let t=this.paint,i=[""],n=Math.max(20,e-4),r=this.rerunnable()?`[${km} v]`:"",o=u=>{let p=`${this.selected?t.tone("\u203A","brand"):" "} ${t.tone("\u25C6","brand")} ${t.bold(u)}`,f=e-x(r)-1,g=r?J(_(p,f,""),f)+" "+(this.selected?t.inverse(r):t.tone(r,"brand")):_(p,e,"");this.buttonAt=r?{from:f+1,to:f+1+x(r)}:void 0,i.push(g)},a=(u,d)=>i.push(...M(` ${t.dim(u.padEnd(20))}${d}`,e)),l=Ks(this.job.detail),c=Pi(this.job.detail),h=jt(this.job.detail);if(l){let u=l.hardware;if(o(`Hardware result \xB7 ${l.target}${u?.shots!=null?` \xB7 ${u.shots} sampled shots`:` \xB7 ${l.shots} requested shots`}`),i.push(t.dim(` ${l.layout_mode==="physical_pool"?`Physical pool: ${l.qids.join(", ")}`:"Automatic compiler layout"}`)),l.error&&!(u&&l.error===l.comparison_error)&&i.push(...M(t.tone(` ${l.error}`,"failed"),e)),typeof l.execution_warning=="string"&&l.execution_warning.trim()&&i.push(...M(t.dim(` ${l.execution_warning}`),e)),u){let{rows:d,more:p,comparable:f}=Bl(l);f&&l.comparison?i.push(` ${t.dim("TVD")} ${l.comparison.tvd.toFixed(6)} ${t.dim("classical fidelity")} ${l.comparison.fidelity.toFixed(6)}`):i.push(...M(t.dim(` ${u.bit_order==null?"The measurement bit order is unconfirmed, so the run is not compared with the simulation.":"This result cannot be compared with the simulation."} Hardware counts:`),e)),u.counts_kind==="readout_corrected_estimate"&&i.push(t.dim(" Readout correction is applied: the bars are the corrected probabilities."));let g=Math.min(24,Math.max(5,...d.map(m=>m.state.length))),b=Math.max(6,n-g-24);i.push(t.dim(` ${"outcome".padEnd(g)} ${f?"hardware / simulation":"hardware"}`));for(let m of d){let y=m.state.length>g?`${m.state.slice(0,g-1)}\u2026`:m.state.padEnd(g);i.push(_(` ${y} ${t.dim("hw ")} ${t.tone(J(ut(m.hardware,b),b),"brand")} ${Us(m.hardware).padStart(6)}`,e,"")),m.simulation!==void 0&&i.push(_(` ${" ".repeat(g)} ${t.dim("sim")} ${t.dim(J(ut(m.simulation,b),b))} ${Us(m.simulation).padStart(6)}`,e,""))}p&&i.push(t.dim(` ${p} more outcome${p===1?"":"s"}; the metrics use the complete distributions`))}}else if(c){let u=c.readout;o(`Hardware result \xB7 ${c.target} \xB7 ${c.variational.circuits} circuit${c.variational.circuits===1?"":"s"} \xD7 ${c.shots} shots`);let d=c.baseline,p=d.result.molecule;if(i.push(t.dim(` ${d.kind==="maxcut"?`QAOA Max-Cut \xB7 ${d.result.num_qubits} nodes`:p?`${d.point!==void 0?"Bond-length scan":"VQE"} \xB7 ${Ii(p.name)} ${p.bond_length} \xC5`:"VQE energy"}`)),c.serial&&(c.state==="submitted"||c.state==="running")&&c.serial.done<c.serial.total&&i.push(t.dim(` Submitting one at a time: circuit ${c.serial.done+1} of ${c.serial.total}`)),c.error&&c.error!==c.readout_error&&i.push(...M(t.tone(` ${c.error}`,"failed"),e)),!u&&c.readout_error&&i.push(...M(t.tone(` The run finished, but its readout could not be computed: ${c.readout_error}`,"failed"),e)),u&&"hardware_energy"in u){let f=!!(u.molecule??p),g=f?" Ha":"",b=v=>Ri(v.toFixed(6)),m=typeof u.exact_energy=="number"?u.exact_energy:void 0,y=typeof u.difference_mha=="number"?u.difference_mha:m!==void 0?(u.hardware_energy-m)*1e3:void 0;a("Hardware energy",`${b(u.hardware_energy)} \xB1 ${b(u.standard_error)}${g}`),a("Simulated (VQE)",`${b(u.simulated_energy)}${g}`),m!==void 0&&a("Exact energy",`${b(m)}${g}`),y!==void 0&&a("Difference from exact",f?`${Ri(y.toFixed(2))} \xB1 ${Ri((u.standard_error*1e3).toFixed(2))} mHa`:`${b(y/1e3)} \xB1 ${b(u.standard_error)}`);let w=m??u.simulated_energy,k=Math.max(Math.abs(u.hardware_energy-w),Math.abs(u.simulated_energy-w),1e-9),R=Math.max(6,n-40);i.push(t.dim(` distance from the ${m!==void 0?"exact":"simulated"} energy:`)),i.push(_(` ${t.dim("hw ")} ${t.tone(J(ut(Math.abs(u.hardware_energy-w)/k,R),R),"brand")} ${(Math.abs(u.hardware_energy-w)*1e3).toFixed(2)} mHa`,e,"")),m!==void 0&&i.push(_(` ${t.dim("sim")} ${t.dim(J(ut(Math.abs(u.simulated_energy-w)/k,R),R))} ${(Math.abs(u.simulated_energy-w)*1e3).toFixed(2)} mHa`,e,"")),f&&m!==void 0&&y!==void 0&&i.push(Math.abs(y)<=1.6?t.tone(" Within chemical accuracy (1.6 mHa)","ok"):t.tone(" Outside chemical accuracy (1.6 mHa)","needs")),i.push(t.dim(` ${u.readout_corrected?"Readout correction applied.":c.readout_correction?"Readout correction was requested but not applied.":"Readout correction off."}`))}if(u&&"max_cut"in u){let f=u.ideal,g=w=>typeof w=="number"?w.toFixed(3):"\u2014",b=w=>typeof w=="number"?Us(w):"\u2014";i.push(t.dim(` ${"".padEnd(22)}${"hardware".padStart(10)}${"ideal".padStart(10)}`)),i.push(` ${"Approximation ratio".padEnd(22)}${g(u.approximation_ratio).padStart(10)}${g(f.approximation_ratio).padStart(10)}`),i.push(` ${"P(optimal cut)".padEnd(22)}${b(u.p_optimal).padStart(10)}${b(f.p_optimal).padStart(10)}`),i.push(` ${"Expected cut".padEnd(22)}${String(Number(u.expected_cut.toFixed(4))).padStart(10)}${String(Number(f.expected_cut.toFixed(4))).padStart(10)}`);let m=Math.max(6,n-40),y=u.max_cut>0?u.max_cut:1;i.push(_(` ${t.dim("cut hw ")} ${t.tone(J(ut(u.expected_cut/y,m),m),"brand")} ${Number(u.expected_cut.toFixed(4))} of ${u.max_cut}`,e,"")),i.push(_(` ${t.dim("cut sim")} ${t.dim(J(ut(f.expected_cut/y,m),m))} ${Number(f.expected_cut.toFixed(4))} of ${u.max_cut}`,e,"")),a("Most frequent outcome",`${u.most_frequent.bits} \xB7 cut ${u.most_frequent.cut}`),a("Maximum cut",String(u.max_cut)),i.push(t.dim(` ${u.readout_corrected?"Readout correction applied.":c.readout_correction?"Readout correction was requested but not applied.":"Readout correction off."}`))}}else h&&(o(`isingq result${h.machine?` \xB7 ${h.machine.name}`:""}`),h.cloud_job_id&&a("Provider task",h.cloud_job_id),h.state==="submission_unknown"&&i.push(t.tone(" Submission is uncertain. Check your isingq account before starting another run.","needs")),h.hardware&&(a("Local objective",String(h.baseline.objective_value)),a("Hardware objective",String(h.hardware.objective_value)),h.comparison&&a("Hardware \u2212 local",String(h.comparison.objective_delta)),i.push(t.dim(" Both values are evaluated against the same original objective; for a minimization a negative difference is better."))),h.error&&i.push(...M(t.tone(` ${h.error}`,"failed"),e)),h.execution_warning&&i.push(...M(t.dim(` ${h.execution_warning}`),e)));return i.push(t.dim(` The full charts: ${this.link}`)),this.lastHeight=i.length,i.map(u=>_(u,e,""))}};import{statSync as Lm}from"node:fs";function Ne(s,e){return s===1?`1 ${e}`:`${s} ${e}s`}function Ui(s,e,t){let i=t?new URLSearchParams(t).toString():"";return`${s.replace(/\/+$/,"")}${e}${i?`?${i}`:""}`}var Rm=(s,e)=>Ui(s,`/chat/${encodeURIComponent(e)}`);function yc(s){let e=Math.max(0,Math.round(s));if(e<60)return`${e}s`;let t=Math.floor(e/86400),i=Math.floor(e%86400/3600),n=Math.floor(e%3600/60);return t?i?`${t}d ${i}h`:`${t}d`:i?n?`${i}h ${n}m`:`${i}h`:`${n}m`}function xc(s){return Xs(s.products).map(({product:e,agent:t})=>{let i=t.mine&&e.agents?.find(n=>n.id===t.mine.base)||t;return{product:e,agent:t,base:i,own:!!t.mine}})}var G=s=>K(s.agent.name,s.agent.id),jr=s=>s.own?s.agent.id:`${s.product.product_id}/${s.agent.id}`,vc=s=>s.products.some(e=>(e.agents??[]).some(t=>t.customizable!==void 0));function Gr(s,e,t){return vc(s)?(e.base.customizable??[]).includes(t):!0}function kc(s){let e=s.base.customizable??[];return e.length?e.join(", "):"nothing"}function Qr(s,e,t){return`${G(s)} does not let members ${e} (it needs ${t}; what it opens: ${kc(s)})`}var Be=(s,e)=>typeof s[e]=="string"?s[e]:"",Jt=(s,e)=>Array.isArray(s[e])?s[e].filter(t=>typeof t=="string"):[];function Pm(s,e){let t=s.instructions_private?"its own (kept private by its package)":`its own (${ce(Buffer.byteLength(s.instructions??""))})`,i=e.instructions_off===!0,n=Be(e,"instructions_replace"),r=Be(e,"instructions_append");return n&&i?`${t}; yours in their place are kept but off`:n?`yours in place of its own (${ce(Buffer.byteLength(n))})`:r&&i?`${t}; yours are kept but off`:r?`${t}, then yours (${ce(Buffer.byteLength(r))})`:s.organization_instructions?`${t}, then your organization's`:t}function wc(s,e,t){let i=s.map(n=>e.includes(n)?`${n} (off)`:n);return t&&i.push(`${t} from your library`),i.length?i.join(", "):"-"}function Mm(s,e){let t=Jt(e,"environments_off"),i=(s.environments??[]).filter(n=>!t.includes(n));for(let n of Jt(e,"environment_ids"))i.includes(n)||i.push(n);return i}var Em=(s,e,t)=>Ui(s,"/agent-settings",{agent:`${e}/${t}`});function Sc(s,e,t,i){let n=e.base,r=e.product,o=[];if(e.own){o.push(`Agent ${G(e)} (${e.agent.id}), yours`),o.push(`Built on ${r.product_id}/${n.id} (${K(n.name,n.id)})`);let c=K(e.agent.description??void 0);c&&o.push(`Description ${xe(c,200)}`)}else{o.push(`Agent ${G(e)} (${r.product_id}/${n.id})`);let c=K(n.description??void 0);c&&o.push(`Description ${xe(c,200)}`)}o.push(`Product ${r.product_id} ${r.version??""}${r.available?"":", unavailable"} (${K(r.name,r.product_id)})`.replace(/ {2,}\(/," (")),n.kind&&o.push(`Kind ${n.kind}`);let a=n.models?.default?`tier ${n.models.default}`:"the organization's default";n.models?.allowed?.length&&(a+=` (may use ${n.models.allowed.join(", ")})`),Be(t,"default_tier")&&(a+=`; yours: ${Be(t,"default_tier")}`),Be(t,"custom_provider_id")&&(a+=`; yours: your own endpoint ${Be(t,"custom_provider_id")}`),o.push(`Model ${a}`),o.push(`Instructions ${Pm(n,t)}`),o.push(`Skills ${wc((n.skills??[]).map(c=>c.id),Jt(t,"skills_off"),Jt(t,"skill_ids").length)}`),o.push(`Plugins ${wc((n.plugins??[]).map(c=>c.id),Jt(t,"plugins_off"),Jt(t,"plugin_ids").length)}`),n.tools?.length&&o.push(`Tools ${n.tools.map(c=>`${c.listing}${c.available===!1?" (not run here)":""}`).join(", ")}`);let l=Mm(n,t);if(l.length&&o.push(`Environments ${l.join(", ")}`),n.knowledge){let c="does not use your knowledge bases";n.knowledge.user&&(c=t.use_knowledge===!1?"may search your knowledge bases; you turned it off":"searches your knowledge bases"),o.push(`Knowledge ${c}`)}if(typeof n.max_tool_calls=="number"){let c=typeof t.max_tool_calls=="number"?`; yours: ${t.max_tool_calls}`:"";o.push(`Limits at most ${n.max_tool_calls} tool calls a turn${c}`)}return o.push(`You may change ${vc(s)?kc(e):"what the platform allows (it does not say)"} (turning things off, always)`),o.push(`In the app ${Em(i,r.product_id,e.agent.id)}`),o.push("",`Deeper changes (skills, plugins, environments, its own endpoint): qupai agent edit ${jr(e)}`),o}function Cc(s){let e=Be(s,"instructions_replace");return e?{mode:"replace",text:e}:{mode:"append",text:Be(s,"instructions_append")}}var $c={append:4e3,replace:16e3};function Ac(s,e,t){let i={...s};return delete i.instructions_off,delete i.instructions_append,delete i.instructions_replace,t?e==="replace"?(i.instructions_replace=t,{cust:i,done:"your instructions stand in place of its own"}):(i.instructions_append=t,{cust:i,done:"your instructions follow its own"}):{cust:i,done:"it runs with its own instructions"}}function Tc(s,e){let t=[];for(let n of e)for(let r of n.tiers??[])t.includes(r)||t.push(r);return(s.models?.allowed?.length?s.models.allowed:t).map(n=>({tier:n,models:e.filter(r=>(r.tiers??[]).includes(n))}))}function _c(s){let e=s.price&&(!s.price.currency||s.price.currency==="CNY")?`, ${re(s.price.input_per_mtok??0)} in / ${re(s.price.output_per_mtok??0)} out per M tokens`:"";return`${s.display_name||s.id}${s.display_name?` (${s.id})`:""}${e}`}function Ic(s,e,t){let i={...s};return t?(i.default_tier=t,delete i.custom_provider_id,delete i.custom_model,{cust:i,done:`its model is tier ${t}`}):(delete i.default_tier,{cust:i,done:`its model is its default${e.models?.default?` (tier ${e.models.default})`:""}`})}var Rc=s=>Be(s,"default_tier");var Yr=s=>Ui(s,"/agent-settings",{facet:"mcp"});function pn(s){return s.status==="needs_authorization"?"waiting for authorization":s.status}function Pc(s){let e=s.last_check_at?` \xB7 checked ${X(s.last_check_at)}${s.last_check_ok===!1?`: ${xe(s.last_check_detail||"failed",40)}`:""}`:"",t=s.plugin?` \xB7 from plugin ${s.plugin.name}`:"";return`${pn(s)} \xB7 ${s.auth_kind==="none"?"no sign-in":s.auth_kind} \xB7 ${Ne((s.tools??[]).length,"tool")}${e}${t} \xB7 ${s.url}`}function Xr(s){let e=(s.days??[]).join(", "),t;switch(s.type){case"daily":t=`daily at ${s.time}`;break;case"weekdays":t=`weekdays at ${s.time}`;break;case"weekly":t=`every ${e} at ${s.time}`;break;case"hourly":t=`every ${s.interval_hours??1} hours from ${s.time}${e?` on ${e}`:""}`;break;case"once":t=`once, on ${s.date??"?"} at ${s.time}`;break;default:t=`${s.type} at ${s.time}`}return`${t} (${s.tz})`}function Jr(s){return s.status==="auto_paused"?`paused after ${Ne(s.consecutive_failures??0,"failure")} in a row`:s.status}function Zr(s){return s.status==="active"&&s.next_run_at?`; next run ${X(s.next_run_at)}`:""}var dn=(s,e)=>Ui(s,`/goals/${encodeURIComponent(e)}`),Mc=s=>s.status==="done"||s.status==="halted";function Hi(s){let e=s.status.replaceAll("_"," ");return s.end_reason?`${e} (${s.end_reason.replaceAll("_"," ")})`:e}function Ec(s,e){let t=[`Goal ${s.title} (${s.id})`,`Status ${Hi(s)}`,`Objective ${s.objective}`,`Spent ${re(s.usage.spend_ucny)} of ${re(s.limits.spend_ucny)}`,`Time ${yc(s.usage.seconds)} of ${yc(s.limits.time_seconds)}`,`Rounds ${s.usage.rounds} of ${s.limits.rounds??100}`,`Hardware jobs ${s.usage.hardware_jobs} of ${s.limits.hardware_jobs??0}`];if(s.conclusion&&t.push(`Conclusion ${s.conclusion}`),t.push(`Conversation ${Rm(e,s.thread_id)}`,`In the app ${dn(e,s.id)}`),s.status==="awaiting_approval"&&t.push("",`It waits for your approval. Approve it in the app, where you see what it may spend: ${dn(e,s.id)}`),s.directives?.length){t.push("","Directives (every later round carries them)");for(let i of s.directives)t.push(` ${xe(i.text,200)}`)}if(s.rounds?.length){t.push("","Rounds");for(let i of s.rounds.slice(-10))t.push(` ${String(i.n).padStart(3)} ${i.reason}${i.stage?` (${i.stage})`:""} ${i.status} ${X(i.created_at)}`)}return t}var eo=(s,e)=>Ui(s,`/workspaces/${encodeURIComponent(e)}`);function to(s){return s.status==="open"&&s.expires_at?`open, until ${X(s.expires_at)}`:s.status}function Lc(s){return[to(s),`image ${s.image_id}`,s.has_snapshot?"saved state":"",s.subsystem?`kept for ${s.subsystem}${s.key?` ${s.key}`:""}`:"",s.last_error?`last error: ${xe(s.last_error,60)}`:""].filter(Boolean).join(" \xB7 ")}var Om=5*6e4,qm=3*6e4,Fe={width:"90%",minWidth:40,maxHeight:"80%"},Dm={width:"70%",minWidth:40},Bm={width:70,minWidth:30},he=s=>s instanceof Error?s.message:String(s),ie=(s,...e)=>s instanceof D&&e.includes(s.status),Ie=s=>s.detail.replace(/\.$/,""),Oc=s=>new Promise(e=>setTimeout(e,s)),fn=class{h;waiting=new Set;constructor(e){this.h=e}back(e,t,i,n="muted"){i!==void 0&&t.say(i,n),this.h.show(e,t,Fe)}tell(e,t,i="muted"){this.h.showing(e)?e.say(t,i):this.h.say(t,i),this.h.render()}failed(e,t){this.tell(e,he(t),"failed")}ask(e,t,i,n,r,o){let a=new bt(this.h.paint,i,n,r);a.onCancel=()=>this.back(e,t,"nothing was changed"),a.onAnswer=l=>o(l,a),this.h.show(`${e}-ask`,a,Dm)}confirm(e,t,i,n){let r=new Ye(this.h.paint,i);r.onAnswer=o=>{this.back(e,t,o?void 0:"nothing was changed"),o&&this.h.track(n())},this.h.show(`${e}-confirm`,r,Bm)}panel(e,t,i,n){let r=new Qt(this.h.paint,i,()=>n);r.maxRows=()=>Math.max(8,Math.floor(this.h.tui.terminal.rows*.85)),r.onClose=()=>this.back(e,t),this.h.show(`${e}-panel`,r,{width:"85%",minWidth:40,maxHeight:"85%"})}async agents(e){let t=this.h.dir();if(!t){this.h.say(this.h.loading()?"still asking the platform which agents you have":"the platform did not say which agents you have","needs");return}let i=xc(t),n=pt(t),r=u=>le(u.product.product_id,u.agent.id),o=this.h.agent(),a=o?le(o.productId,o.agentId):"",l=i.map(u=>{let d=n.find(f=>f.from==="product"&&le(f.productId,f.agentId)===r(u)),p=[r(u)===a?"in use":"",u.own?`yours, built on ${K(u.base.name,u.base.id)}`:u.base.kind??"general",K(u.product.name,u.product.product_id),d?.isDefault?"organization default":""];return{value:r(u),label:`${G(u)}${u.own?" (yours)":""}`,description:p.filter(Boolean).join(" \xB7 ")}}),c=new te(this.h.paint,"Your agents",l,{keys:["i","e","m","n","r","d"],footer:"Enter use \xB7 i show \xB7 e instructions \xB7 m model \xB7 n new \xB7 r rename \xB7 d delete \xB7 Esc",empty:"no agent is offered to you here",selected:l.findIndex(u=>u.value===(e?.select??a))});e&&c.say(e.text,e.tone);let h=u=>i.find(d=>r(d)===u);c.onCancel=()=>this.h.hide(),c.onPick=u=>{let d=h(u);if(!d)return;let p=n.find(f=>f.from==="product"&&le(f.productId,f.agentId)===u);if(p){this.h.hide(),this.h.useAgent(p);return}t.given&&!d.own?c.say(`you were given agents of your own: new conversations go to those; n makes one built on ${G(d)}`,"needs"):c.say(`${G(d)} is not offered for new conversations here: the tools it needs are not run here`,"needs"),this.h.render()},c.onKey=(u,d)=>{let p=h(d);p&&(u==="i"?this.h.track(this.showAgent(t,p,c)):u==="e"?this.h.track(this.editInstructions(t,p,c)):u==="m"?this.h.track(this.chooseModel(t,p,c)):u==="n"?this.newAgent(p,c):u==="r"?this.renameAgent(p,c):u==="d"&&this.deleteAgent(p,c),this.h.render())},this.h.show("agents",c,Fe)}async customization(e,t){try{return await this.h.client.customization(e.product.product_id,e.agent.id)}catch(i){this.tell(t,ie(i,404)?`${G(e)} is not there for you any more`:he(i),"failed");return}}async showAgent(e,t,i){let n=await this.customization(t,i);n&&this.panel("agents",i,G(t),Sc(e,t,n,this.h.web))}async editInstructions(e,t,i){let n=G(t),r=await this.customization(t,i);if(!r)return;let{mode:o,text:a}=Cc(r),l=o==="replace"?"instructions.replace":"instructions.append";if(!Gr(e,t,l)){this.tell(i,Qr(t,o==="replace"?"replace its instructions":"add instructions",l),"needs");return}let c=$c[o],h=o==="replace"?`Your instructions stand in place of ${n}'s own, at most ${c} bytes. Saving it empty goes back to its own.`:`Your instructions follow ${n}'s own${t.base.instructions_private?" (which its package keeps private)":""}, at most ${c} bytes. Saving it empty leaves its own alone. qupai agent edit ${jr(t)} -instructions FILE -replace puts yours in their place.`,u=new cn(this.h.tui,this.h.paint,`Your instructions for ${n}`,h,a);u.requestRender=()=>this.h.render(),u.onCancel=()=>this.back("agents",i,"nothing was changed"),u.onSave=d=>this.h.track((async()=>{let p=d.trim(),f=Buffer.byteLength(p);if(f>c)return`your instructions are ${f} bytes: at most ${c} here`;let g=Ac(r,o,p);try{await this.h.client.putCustomization(t.product.product_id,t.agent.id,g.cust)}catch(b){return ie(b,400)?`the platform did not take the change: ${Ie(b)}`:he(b)}this.back("agents",i,`Saved ${n}: ${g.done}.`)})()),this.h.show("agent-instructions",u,{width:"90%",minWidth:40,maxHeight:"90%"})}async chooseModel(e,t,i){let n=G(t);if(!Gr(e,t,"models.default")){this.tell(i,Qr(t,"choose its model","models.default"),"needs");return}let r=await this.customization(t,i);if(!r)return;let o;try{o=await this.h.client.models()}catch(d){this.failed(i,d);return}let a=Tc(t.base,o);if(!a.length){this.tell(i,"no models are offered to your organization here","needs");return}let l=Rc(r),c=t.base.models?.default,h=[{value:"",label:`its default${c?` (tier ${c})`:""}`,description:l?"":"in use"},...a.map(d=>({value:d.tier,label:`tier ${d.tier}`,description:`${d.tier===l?"in use \xB7 ":""}${d.models.length?d.models.map(_c).join("; "):"no model of your organization's is in this tier"}`}))],u=new gt(this.h.paint,`The model of ${n}`,h,{selected:h.findIndex(d=>d.value===l)});u.onCancel=()=>this.back("agents",i,"nothing was changed"),u.onPick=d=>{this.h.track((async()=>{let p=Ic(r,t.base,d);try{await this.h.client.putCustomization(t.product.product_id,t.agent.id,p.cust)}catch(f){this.back("agents",i,ie(f,400)?`the platform did not take the change to ${n}: ${Ie(f)}`:he(f),"failed");return}this.back("agents",i,`Saved ${n}: ${p.done}.`)})())},this.h.show("agent-model",u,Fe)}newAgent(e,t){let i=`${e.product.product_id}/${e.base.id}`;this.ask("agents",t,"A new agent of yours",`It is built on ${i}${e.own?` (as ${G(e)} is), without ${G(e)}'s changes`:""}; change it here or with qupai agent edit. Its name (at most 80 characters):`,"",(n,r)=>{let o=n.trim();if(!o||[...o].length>80){r.refuse("a name is 1 to 80 characters"),this.h.render();return}this.h.track((async()=>{let a;try{a=await this.h.client.createMyAgent(e.product.product_id,e.agent.id,o)}catch(l){r.refuse(ie(l,409)?`the platform made no agent: ${Ie(l)} (d deletes one of yours)`:he(l)),this.h.render();return}await this.h.reloadAgents().catch(()=>{}),await this.agents({text:`Created your agent "${a.name}" (${a.id}), built on ${a.product_id}/${a.base_agent_id}. Enter uses it.`,select:le(a.product_id,a.id)})})())})}renameAgent(e,t){if(!e.own){t.say(`${G(e)} is its product's: only your own agents are renamed (n makes one of yours)`,"needs");return}this.ask("agents",t,`Rename ${G(e)}`,"Its new name (at most 80 characters):",G(e),(i,n)=>{let r=i.trim();if(!r||[...r].length>80){n.refuse("a name is 1 to 80 characters"),this.h.render();return}this.h.track((async()=>{try{await this.h.client.renameMyAgent(e.agent.id,r)}catch(o){n.refuse(ie(o,404)?`${G(e)} is not there any more`:he(o)),this.h.render();return}await this.h.reloadAgents().catch(()=>{}),await this.agents({text:`Renamed it "${r}".`,select:le(e.product.product_id,e.agent.id)})})())})}deleteAgent(e,t){if(!e.own){t.say(`${G(e)} is its product's: only your own agents are deleted`,"needs");return}let i=G(e);this.confirm("agents",t,`Delete your agent "${i}" (${e.agent.id}) and its customization? Its conversations stay readable but take no new messages.`,async()=>{try{await this.h.client.deleteMyAgent(e.agent.id)}catch(n){this.failed(t,ie(n,404)?new Error(`${i} is not there any more`):n);return}await this.h.reloadAgents().catch(()=>{}),await this.agents({text:`Deleted your agent "${i}".`})})}async knowledge(){let e;try{e=await this.h.client.knowledgeBases()}catch(o){this.h.fail(o);return}let t=()=>e.map(o=>({value:o.id,label:o.name,description:`${Ne(o.document_count,"document")} \xB7 updated ${X(o.updated_at)}${o.description?` \xB7 ${xe(o.description,50)}`:""}`})),i=new te(this.h.paint,"Your knowledge bases",t(),{keys:["a","s","d"],free:["n"],footer:"Enter its documents \xB7 a add a file \xB7 s search \xB7 n new \xB7 d delete \xB7 Esc close",empty:"no knowledge bases yet: n makes one"}),n=async o=>{e=await this.h.client.knowledgeBases(),i.setItems(t(),o)},r=o=>e.find(a=>a.id===o);i.onCancel=()=>this.h.hide(),i.onPick=o=>{let a=r(o);a&&this.h.track(this.documents(a,i))},i.onKey=(o,a)=>{if(o==="n"){this.newKnowledgeBase(i,n);return}let l=r(a);l&&(o==="a"?this.addDocument(l,i,n):o==="s"?this.search(l,i):o==="d"&&this.confirm("kb",i,`Delete the knowledge base "${l.name}" with its ${Ne(l.document_count,"document")}? It cannot be undone.`,async()=>{try{await this.h.client.deleteKnowledgeBase(l.id),await n()}catch(c){this.failed(i,c);return}this.tell(i,`Deleted the knowledge base "${l.name}".`)}),this.h.render())},this.h.show("kb",i,Fe)}async documents(e,t){let i;try{i=await this.h.client.knowledgeDocuments(e.id)}catch(r){this.failed(t,r);return}let n=new te(this.h.paint,`${e.name}: documents`,i.map(r=>({value:r.id,label:r.name,description:`${ce(r.size_bytes)} \xB7 ${Ne(r.chunk_count,"passage")} \xB7 ${r.ingested_via==="agent"?"an agent wrote it":"uploaded"} \xB7 ${X(r.updated_at)}`})),{footer:"Esc back to your knowledge bases",empty:"no documents yet: a adds a file"});n.onCancel=()=>this.back("kb",t),n.onPick=()=>{n.say(`only its text passages are kept; qupai kb rm "${e.name}" <document> removes one`),this.h.render()},this.h.show("kb-docs",n,Fe)}addDocument(e,t,i){this.ask("kb",t,`Add a file to ${e.name}`,`A PDF, docx, txt or md file; only its text passages are kept, and a document of the same name is replaced. Its path, relative to ${this.h.shown(this.h.cwd)||"this directory"}:`,"",(n,r)=>{let o=n.trim();if(!o){r.refuse("type the file's path, or Esc"),this.h.render();return}let a=Gt(o,this.h.cwd);try{if(!Lm(a).isFile())throw new Error("not a file")}catch{r.refuse(`${this.h.shown(a)} is not a file here`),this.h.render();return}this.back("kb",t,`adding ${this.h.shown(a)} to ${e.name}\u2026`),this.h.track((async()=>{try{let l=await this.h.client.addKnowledgeDocument(e.id,a);await i(e.id),this.tell(t,`${l.document.name}: ${l.replaced?"replaced the document of the same name":"added"}, ${Ne(l.document.chunk_count,"passage")}.`)}catch(l){this.tell(t,ie(l,400,409)?`${this.h.shown(a)} was not added: ${Ie(l)}`:he(l),"failed")}})())})}search(e,t){this.ask("kb",t,`Search ${e.name}`,"The passages your agents would find (kb_search), best first. Search for:","",(i,n)=>{let r=i.trim();if(!r){n.refuse("type what to search for, or Esc"),this.h.render();return}this.h.track((async()=>{let o;try{o=await this.h.client.searchKnowledgeBase(e.id,r,5)}catch(l){n.refuse(he(l)),this.h.render();return}if(!o.length){this.back("kb",t,`nothing in ${e.name} matches "${r}"`,"needs");return}let a=o.flatMap((l,c)=>[...c?[""]:[],`${c+1}. ${l.document_name}, passage ${l.chunk_index} (score ${l.score.toFixed(3)})`,...l.text.trim().split(`
|
|
118
|
-
`).map(h=>` ${h}`)]);this.panel("kb",t,`${e.name}: "${xe(r,40)}"`,a)})())})}newKnowledgeBase(e,t){this.ask("kb",e,"A new knowledge base","Its name (at most 100 characters; each of yours has its own):","",(i,n)=>{let r=i.trim();if(!r||[...r].length>100){n.refuse("a name is 1 to 100 characters"),this.h.render();return}this.h.track((async()=>{let o;try{o=await this.h.client.createKnowledgeBase(r)}catch(a){n.refuse(ie(a,409)?`the platform made no knowledge base: ${Ie(a)} (a name is used once; you keep at most 50)`:he(a)),this.h.render();return}await t(o.id).catch(()=>{}),this.back("kb",e,`Created the knowledge base "${o.name}": a adds files to it.`)})())})}async connections(){let e;try{e=await this.h.client.connections()}catch(l){this.h.fail(l);return}let t=l=>l.display_name||l.name,i=()=>e.map(l=>({value:l.id,label:t(l),description:Pc(l)})),n=new te(this.h.paint,"Your connections",i(),{keys:["t","o","x","d"],footer:"Enter its tools \xB7 t test \xB7 o authorize \xB7 x switch on or off \xB7 d remove \xB7 Esc",empty:"no connections yet"});n.say("Adding one: qupai connection add <name> <url> (it asks for the server's secret where it is not shown)");let r=async()=>{e=await this.h.client.connections(),n.setItems(i())},o=l=>{e=e.map(c=>c.id===l.id?{...c,...l}:c),n.setItems(i())},a=l=>e.find(c=>c.id===l);n.onCancel=()=>this.h.hide(),n.onPick=l=>{let c=a(l);if(!c)return;let h=[`Connection ${t(c)} (${c.name}, ${c.id})`,`Address ${c.url}`,`Signs in by ${c.auth_kind==="none"?"nothing (open)":c.auth_kind}`,`Status ${pn(c)}`,...c.last_check_at?[`Last check ${X(c.last_check_at)}: ${c.last_check_ok?"answered":`failed${c.last_check_detail?` (${c.last_check_detail})`:""}`}`]:[],...c.plugin?[`From plugin ${c.plugin.name} (${c.plugin.server})`]:[],`In the app ${Yr(this.h.web)}`,"",(c.tools??[]).length?`Tools: ${(c.tools??[]).join(", ")}`:"No tools known yet: t tests it and lists them."];this.panel("connections",n,t(c),h)},n.onKey=(l,c)=>{let h=a(c);if(!h)return;let u=t(h);if(l==="t")n.say(`testing ${u}\u2026`),this.h.track((async()=>{try{let d=await this.h.client.testConnection(h.id);if(await r().catch(()=>{}),d.ok){let p=d.tools??[];this.tell(n,`${u} answers${d.latency_ms!==void 0?` (${d.latency_ms} ms)`:""}: ${Ne(p.length,"tool")}${p.length?`: ${p.slice(0,8).join(", ")}${p.length>8?", \u2026":""}`:""}`)}else this.tell(n,`${u} does not answer: ${d.detail||"no reason given"}${h.auth_kind==="oauth"?" (o signs in again)":""}`,"failed")}catch(d){this.failed(n,ie(d,404)?new Error(`the connection ${u} is not there any more`):d)}})());else if(l==="o")this.authorize(h,u,n,o);else if(l==="x"){if(h.status==="needs_authorization"){n.say(`${u} waits for authorization: o authorizes it`,"needs"),this.h.render();return}let d=h.status==="disabled";this.h.track(this.h.client.setConnectionEnabled(h.id,d).then(p=>{o(p),this.tell(n,`${u} is ${pn({...h,...p})}.`)},p=>this.failed(n,p)))}else l==="d"&&this.confirm("connections",n,`Remove the connection ${u} (${h.url}) and its secret? Agents lose its tools.`,async()=>{try{await this.h.client.deleteConnection(h.id),await r()}catch(d){this.failed(n,d);return}this.tell(n,`Removed the connection ${u}.`)});this.h.render()},this.h.show("connections",n,Fe)}authorize(e,t,i,n){if(e.auth_kind!=="oauth"){i.say(`${t} signs in by ${e.auth_kind==="none"?"nothing":e.auth_kind}, not OAuth: there is nothing to authorize (t tests it)`,"needs");return}if(this.waiting.has(e.id)){i.say(`already waiting for you to authorize ${t} in the browser`,"needs");return}this.waiting.add(e.id),this.h.track((async()=>{try{let r;try{r=await this.h.client.authorizeConnection(e.id,Yr(this.h.web))}catch(l){this.tell(i,ie(l,400)?`the platform could not start the authorization: ${Ie(l)}`:he(l),"failed");return}let o=this.h.openBrowser(r);this.tell(i,`${o?"The browser opened":"Open this in your browser"}: authorize ${t} there, then come back (the app waits up to 3 minutes). ${r}`,"needs");let a=Date.now()+qm;for(;!this.h.stopped()&&Date.now()<a;){await Oc(this.h.pollMs.authorize);let l;try{l=await this.h.client.connection(e.id)}catch{continue}if(l.status==="active"){n(l),this.tell(i,`${t} is authorized.`);return}}this.h.stopped()||this.tell(i,`${t} is not authorized yet: finish in the browser, then t tests it`,"needs")}finally{this.waiting.delete(e.id)}})())}async schedules(){let e;try{e=await this.h.client.schedules()}catch(r){this.h.fail(r);return}let t=()=>e.map(r=>({value:r.id,label:r.name,description:`${Jr(r)}${Zr(r)} \xB7 ${Xr(r.recurrence)}${r.last_run_at?` \xB7 last run ${X(r.last_run_at)}${r.last_run_status?` ${r.last_run_status}`:""}`:""}`})),i=new te(this.h.paint,"Your schedules",t(),{keys:["p","r","d"],footer:"Enter open its conversation \xB7 p pause or resume \xB7 r run now \xB7 d delete \xB7 Esc close",empty:"no schedules: qupai schedule new makes one"}),n=r=>e.find(o=>o.id===r);i.onCancel=()=>this.h.hide(),i.onPick=r=>{let o=n(r);o&&(this.h.hide(),this.h.track(this.h.openThread(o.thread_id)))},i.onKey=(r,o)=>{let a=n(o);if(a){if(r==="p"){if(a.status==="finished"){i.say(`"${a.name}" has finished (it ran once): qupai schedule new makes another`,"needs"),this.h.render();return}let l=a.status!=="active";this.h.track(this.h.client.setScheduleEnabled(a.id,l).then(c=>{e=e.map(u=>u.id===a.id?{...u,...c}:u),i.setItems(t());let h=n(a.id);this.tell(i,`"${a.name}" is ${Jr(h)}${Zr(h)}.`)},c=>this.tell(i,ie(c,400)?`the platform did not ${l?"resume":"pause"} "${a.name}": ${Ie(c)}`:he(c),"failed")))}else r==="r"?this.h.track(this.h.client.runScheduleNow(a.id).then(l=>this.tell(i,`Started a run of "${a.name}" (${l.status}) on its conversation: Enter opens it.`),l=>this.failed(i,l))):r==="d"&&this.confirm("schedules",i,`Delete the schedule "${a.name}" (${Xr(a.recurrence)})? Its conversation stays.`,async()=>{try{await this.h.client.deleteSchedule(a.id)}catch(l){this.failed(i,l);return}e=e.filter(l=>l.id!==a.id),i.setItems(t()),this.tell(i,`Deleted the schedule "${a.name}".`)});this.h.render()}},this.h.show("schedules",i,Fe)}async goals(){let e;try{e=await this.h.client.goals()}catch(l){this.h.fail(l);return}let t=()=>e.map(l=>({value:l.id,label:l.title||l.id,description:`${Hi(l)}${l.status==="awaiting_approval"?": approve it in the app":""} \xB7 spent ${re(l.usage.spend_ucny)} of ${re(l.limits.spend_ucny)} \xB7 ${X(l.created_at)}`})),i=new te(this.h.paint,"Your goals, newest first",t(),{keys:["p","s","w"],footer:"Enter show it \xB7 p pause or resume \xB7 s stop \xB7 w steer \xB7 Esc close",empty:"no goals: qupai goal new starts one (you approve it in the app)"}),n=e.filter(l=>l.status==="awaiting_approval").length;n&&i.say(`${Ne(n,"goal")} ${n===1?"waits":"wait"} for your approval: approve in the app (Enter shows its link); this app never approves a goal`,"needs");let r=l=>e.find(c=>c.id===l),o=l=>{e=e.map(c=>c.id===l.id?{...c,...l}:c),i.setItems(t())},a=(l,c)=>this.h.track(this.h.client.actOnGoal(l.id,c).then(h=>{o(h),this.tell(i,`The goal "${l.title}" is ${Hi({...l,...h})}.`)},h=>this.tell(i,ie(h,409)?`not possible now: ${Ie(h)}`:he(h),"failed")));i.onCancel=()=>this.h.hide(),i.onPick=l=>{let c=r(l);c&&this.h.track(this.h.client.goal(c.id).then(h=>this.panel("goals",i,c.title||c.id,Ec(h,this.h.web)),h=>this.failed(i,h)))},i.onKey=(l,c)=>{let h=r(c);if(!h)return;let u=Mc(h),d=`"${h.title}" waits for your approval: approve it in the app, ${dn(this.h.web,h.id)}`;l==="p"?h.status==="running"?a(h,"pause"):h.status==="paused"||h.status==="stalled"?a(h,"resume"):i.say(h.status==="awaiting_approval"?d:u?`"${h.title}" has ended`:`"${h.title}" is ${Hi(h)}: nothing to pause`,"needs"):l==="s"?u?i.say(`"${h.title}" has ended`,"needs"):this.confirm("goals",i,`Stop the goal "${h.title}" now? Its live round and jobs are cancelled, with no closing round.`,async()=>{await a(h,"halt")}):l==="w"&&(u?i.say(`"${h.title}" has ended: it takes no directives`,"needs"):this.steer(h,i)),this.h.render()},this.h.show("goals",i,Fe)}steer(e,t){this.ask("goals",t,`Steer ${e.title}`,"A directive every later round carries (at most 2000 characters):","",(i,n)=>{let r=i.trim();if(!r||[...r].length>2e3){n.refuse("a directive is 1 to 2000 characters"),this.h.render();return}this.h.track(this.h.client.steerGoal(e.id,r).then(o=>this.back("goals",t,`Every later round of "${e.title}" carries it (directive ${o.id}; qupai goal retire ${e.id} ${o.id} takes it back).`),o=>{n.refuse(ie(o,409)?`"${e.title}" has ended: it takes no directives`:he(o)),this.h.render()}))})}async workspaces(){let e;try{e=await this.h.client.workspaces()}catch(o){this.h.fail(o);return}let t=()=>e.map(o=>({value:o.id,label:o.name,description:Lc(o)})),i=new te(this.h.paint,"Your workspaces",t(),{keys:["s","o","d"],footer:"Enter its page \xB7 s start or stop \xB7 o open in the browser \xB7 d delete \xB7 Esc close",empty:"no workspaces: qupai workspace new makes one"}),n=o=>e.find(a=>a.id===o),r=o=>{e=e.map(a=>a.id===o.id?o:a),i.setItems(t())};i.onCancel=()=>this.h.hide(),i.onPick=o=>{let a=n(o);a&&(i.say(`"${a.name}" in the app: ${eo(this.h.web,a.id)} (o opens it)`),this.h.render())},i.onKey=(o,a)=>{let l=n(a);if(l){if(o==="s")this.startStop(l,i,r);else if(o==="o"){let c=eo(this.h.web,l.id);i.say(this.h.openBrowser(c)?`Opened "${l.name}" in the app: ${c}`:`The browser did not open: open ${c}`)}else o==="d"&&this.confirm("workspaces",i,`Delete the workspace "${l.name}" with its sandbox and saved state? It cannot be undone.`,async()=>{try{await this.h.client.deleteWorkspace(l.id)}catch(c){this.tell(i,this.workspaceRefusal(c,l),"failed");return}e=e.filter(c=>c.id!==l.id),i.setItems(t()),this.tell(i,`Deleted the workspace "${l.name}".`)});this.h.render()}},this.h.show("workspaces",i,Fe)}workspaceRefusal(e,t){return ie(e,404)?`the workspace "${t.name}" is not there any more`:ie(e,409,400)?`not possible now for "${t.name}": ${Ie(e)}`:ie(e,503)?`the platform's sandbox service does not answer: ${Ie(e)}`:he(e)}startStop(e,t,i){if(this.waiting.has(e.id)){t.say(`already waiting for "${e.name}"`,"needs");return}this.waiting.add(e.id),this.h.track((async()=>{try{let n=e,r;e.status==="idle"?(r="open",t.say(`starting "${e.name}"\u2026`),this.h.render(),n=await this.h.client.openWorkspace(e.id)):e.status==="open"?(r="idle",t.say(`saving and stopping "${e.name}"\u2026`),this.h.render(),n=await this.h.client.closeWorkspace(e.id)):(r=e.status==="starting"?"open":"idle",t.say(`"${e.name}" is ${e.status}: waiting for it\u2026`),this.h.render()),i(n);let o=Date.now()+Om;for(;n.status!==r;){if(this.h.stopped())return;if(n.last_error&&n.status==="idle"&&r==="open"){this.tell(t,`"${n.name}" did not start: ${n.last_error}`,"failed");return}if(Date.now()>o){this.tell(t,`"${n.name}" is still ${n.status} after 5 minutes: s waits for it again`,"needs");return}await Oc(this.h.pollMs.workspace),n=await this.h.client.workspace(e.id),i(n)}this.tell(t,`"${n.name}" is ${to(n)}${r==="open"?": o opens it":", its state saved"}.`)}catch(n){this.tell(t,this.workspaceRefusal(n,e),"failed")}finally{this.waiting.delete(e.id)}})())}};var Km=["project","calibration"],io=[{name:"new",description:"a new conversation with the agent in use"},{name:"agent",description:"choose an agent: your products' agents and your labs' own"},{name:"lab",description:"your labs: talk with a lab's agent, its status, ask for access"},{name:"threads",description:"continue one of your threads, newest first"},{name:"project",description:"your projects: start a conversation in one, save its files"},{name:"attach",description:"attach a file to your next message (/attach -clear removes them)"},{name:"files",description:"this conversation's files: save one here"},{name:"artifacts",description:"this conversation's artifacts: save one to a file"},{name:"notifications",description:"your notifications, newest first: open one, mark them read"},{name:"balance",description:"your balance and the last days' usage"},{name:"agents",description:"your agents: use one, its instructions and model, your own"},{name:"kb",description:"your knowledge bases: documents, add a file, search"},{name:"connections",description:"your MCP connections: test, authorize, switch on or off"},{name:"schedules",description:"your schedules: pause or resume, run now, delete"},{name:"goals",description:"your goals: show, pause or resume, stop, steer"},{name:"workspaces",description:"your workspaces: start or stop, open in the browser"},{name:"status",description:"who is signed in, where, and the agent in use"},{name:"help",description:"the commands and keys"},{name:"logout",description:"sign out (qupai logout) and quit"},{name:"quit",description:"leave the app"}],Nc=[["Enter","send the message (on an empty line: show a waiting approval again)"],["Shift+Enter","a new line (Alt+Enter or Ctrl+J where Shift+Enter does not reach the app)"],["/","commands, with completion (Tab or Enter)"],["Esc","stop a running turn or hardware run (it asks first); close a list or panel; in a dialog, go back"],["Backspace","on an empty line: remove the last file attached to the next message"],["Tab","on an empty line: move through the tool calls; Enter unfolds one, Esc returns"],["v","on a tool call or a result marked [Run on hardware v]: run it on hardware (a dialog; nothing is sent until you confirm)"],["PgUp PgDn","scroll the conversation (also the mouse wheel and the trackpad)"],["Ctrl+End","back to the newest output"],["A R","in an approval: approve, or reject with an optional comment (Esc closes it unanswered)"],["s r w","in /lab: the lab's status; ask QuPai staff for access (with a note); withdraw that request"],["a","in /notifications: mark them all read (Enter opens one and marks it read)"],["f","in /project: the project's files (Enter saves one, like /files)"],["i e m","in /agents: show it; your instructions for it (Ctrl+S saves them); its model"],["n r d","in /agents: a new agent of yours built on it; rename or delete one of yours"],["a s n d","in /kb: add a file; search; a new knowledge base; delete one"],["t o x d","in /connections: test; authorize (OAuth, in the browser); switch on or off; remove"],["p r d","in /schedules: pause or resume; run now; delete (Enter opens its conversation)"],["p s w","in /goals: pause or resume; stop; steer with a directive (Enter shows it)"],["s o d","in /workspaces: start or stop, waiting for it; open in the browser; delete"],["Ctrl+C","clear the line; on an empty line, quit (Ctrl+D too)"],["?","on an empty line: these keys"]],so=class{triggerCharacters=["/"];async getSuggestions(e,t,i){if(t!==0)return null;let n=(e[0]??"").slice(0,i),r=/^\s*\/(\S*)$/.exec(n);if(!r)return null;let o=(r[1]??"").toLowerCase(),a=io.filter(l=>l.name.startsWith(o)).map(l=>({value:l.name,label:`/${l.name}`,description:l.description}));return a.length?{items:a,prefix:`/${r[1]??""}`}:null}applyCompletion(e,t,i,n,r){let o=e[t]??"",a=i-r.length,l=`${o.slice(0,a)}/${n.value}${o.slice(i)}`,c=[...e];return c[t]=l,{lines:c,cursorLine:t,cursorCol:a+n.value.length+1}}},bn=class{tui;editor;notice;opts;client;paint;transcript=new ee;scroll;welcome;me;dir;agent;thread;threadAgent;loading=!0;following;last;answers=[];overlay;devices;runs=[];shownTurns=new Set;generation=0;approval;nav=-1;store;stopped=!1;pending=new Set;attachments=[];place;unread=0;bellOff=!1;bellTimer;labRequests=new Map;cwd;setup;constructor(e){this.opts=e,this.client=e.client,this.paint=e.paint,this.store=new Ys(e.client.signIn.handoff.choice_file),this.cwd=e.cwd??process.cwd(),this.devices=new Zs({platform:e.client,web:e.client.signIn.handoff.web,override:e.devicesUrl});let t=new $i(e.terminal,!1,void 0,{mouse:!0,scrollToEndIndicator:()=>this.paint.dim(" \u2193 newest ")});this.tui=t,this.welcome=new rn(e.paint,()=>this.welcomeInfo(),{image:e.image}),this.transcript.addChild(this.welcome),this.scroll=new lt(this.transcript,{follow:"end",primary:!0,overscroll:"chain",scrollbar:"auto"}),this.notice=new on(e.paint),this.editor=new st(t,nn(e.paint),{paddingX:1,autocompleteMaxVisible:8}),this.editor.setAutocompleteProvider(new so),this.editor.onSubmit=n=>this.submit(n);let i=new an(e.paint,()=>({state:this.markState(),agent:this.thread?this.threadAgent:this.place?.agent??this.agent,org:this.orgName(),platform:this.client.server,unread:this.unread,place:this.place?.title}));t.setLayoutRoot(new wi([{component:this.scroll,basis:0,grow:1,minSize:1},{component:this.notice,basis:"auto"},{component:new ln(e.paint,()=>this.attachments),basis:"auto"},{component:this.editor,basis:"auto",shrink:1,minSize:3},{component:i,basis:"auto"}])),t.setFocus(this.editor),t.addInputListener(n=>this.onKey(n)),this.setup=new fn({paint:e.paint,client:e.client,tui:t,web:e.client.signIn.handoff.web,cwd:this.cwd,pollMs:{workspace:e.workspacePollMs??2e3,authorize:e.authorizePollMs??1500},dir:()=>this.dir,loading:()=>this.loading,agent:()=>this.agent,show:(n,r,o)=>this.showOverlay(n,r,o),hide:()=>this.hideOverlay(),showing:n=>this.overlay?.component===n,say:(n,r)=>this.say(n,r),fail:n=>this.fail(n),track:n=>this.track(n),render:()=>this.render(),stopped:()=>this.stopped,shown:n=>this.shown(n),useAgent:n=>this.useAgent(n),reloadAgents:()=>this.reloadAgents(),openThread:n=>this.openThread(n),openBrowser:e.openBrowser??Um})}start(){this.tui.start(),this.track(this.load())}track(e){let t=e.finally(()=>this.pending.delete(t));return this.pending.add(t),t}async idle(){for(;this.pending.size;)await Promise.allSettled([...this.pending])}render(){this.stopped||this.tui.requestRender()}say(e,t="muted"){this.notice.set(e,t),this.render()}fail(e){let t=e instanceof D||e instanceof dt||e instanceof Error?e.message:String(e);this.say(t,"failed")}orgName(){let e=this.me;if(!e)return;let t=e.tenants?.find(i=>i.id===e.current_tenant_id);return t?.display_name||t?.slug||void 0}welcomeInfo(){let e=this.me;return{who:e?`${e.user.display_name}${e.user.email?` <${e.user.email}>`:""}`:void 0,org:this.orgName(),platform:this.client.server,agent:this.place?.agent??this.agent,place:this.place?.title,loading:this.loading}}markState(){let e=this.following?.answer??this.last;if(!e)return"idle";switch(e.state){case"running":return this.following?"writing":"idle";case"awaiting_approval":return"needs";case"aborted":return"stopped";case"error":return"failed";default:return"idle"}}async load(){try{let[e,t,i,n]=await Promise.all([this.client.me(),this.client.products(),this.client.myAgents(),this.client.labs().catch(()=>[])]);this.me=e,this.dir=Er(t,i,n);let r=this.opts.start??{};if(r.thread){this.loading=!1,await this.openThread(r.thread);return}if(r.lab){let o=Li(this.dir).find(a=>a.lab===r.lab);o?this.agent=o:this.say(`no lab ${r.lab} offers you its agent: /lab lists those that do`,"failed")}else if(r.product){let o=this.findProductAgent(r.product,r.agent);typeof o=="string"?this.say(o,"failed"):this.agent=o}this.agent||(this.agent=Lr(this.dir,this.store.get(this.client.server,e.user.id)),!this.agent&&!this.notice.value&&this.say("no agent is offered to you here: ask your organization's admin which products to enable","needs"))}catch(e){this.fail(e)}finally{this.loading=!1,this.render(),this.startBell()}}findProductAgent(e,t){let i=pt(this.dir).filter(o=>o.from==="product"&&o.productId===e),n=this.dir.products.find(o=>o.product_id===e);return n?n.available?t?i.find(o=>o.agentId===t)??n.agents?.filter(o=>o.id===t).map(o=>({productId:e,agentId:o.id,name:K(o.name,o.id),from:"product",isDefault:!1}))[0]??`${e} has no agent ${t} (its agents: ${(n.agents??[]).map(o=>o.id).join(", ")})`:(i[0]??(n.agents?.[0]&&{productId:e,agentId:n.agents[0].id,name:K(n.agents[0].name,n.agents[0].id),from:"product",isDefault:!1}))||`${e} has no agents`:`${e} is not available to you (no version resolves, or a permission is missing): ask your organization's admin`:`your organization runs no product ${e}: /agent lists what you can ask`}choiceFor(e,t){let i=this.dir?[...pt(this.dir),...Li(this.dir)].find(n=>n.productId===e&&n.agentId===t):void 0;return i||(t.startsWith("lab:")?{productId:e,agentId:t,name:t,from:"lab",lab:t.slice(4),isDefault:!1}:{productId:e,agentId:t,name:t,from:"product",isDefault:!1})}newConversation(){this.following?.abort.abort(),this.following=void 0,this.closeApproval(),this.thread=void 0,this.threadAgent=void 0,this.place=void 0,this.last=void 0,this.answers=[],this.runs=[],this.shownTurns=new Set,this.generation++,this.nav=-1,this.transcript.clear(),this.transcript.addChild(this.welcome),this.notice.clear(),this.render()}submit(e){let t=e.trim();if(!t){this.approval&&this.following?this.track(this.showApproval(this.approval.part,!0)):this.attachments.length&&this.say("type a message to go with the attached files","needs");return}let i=Fr(t,this.cwd);if(i){this.attach(i);return}if(this.editor.addToHistory(t),t.startsWith("/")){this.command(t);return}if(this.following){this.say("a turn is running: wait for its answer, or press Esc to stop it","needs");return}this.track(this.attachments.length||!this.thread&&this.place?this.send(t):this.ask(t))}async ask(e){if(this.notice.clear(),!this.thread){let i=this.agent;if(!i){this.say(this.loading?"still asking the platform which agents you have: try again in a moment":"no agent to ask: /agent chooses one","needs");return}try{this.thread=await this.client.createThread(i.productId,i.agentId),this.threadAgent=i}catch(n){this.fail(n);return}this.transcript.removeChild(this.welcome)}this.transcript.addChild(new ft(this.paint,e)),this.render();let t;try{t=(await this.client.submitTurn(this.thread.id,e)).id}catch(i){i instanceof D&&i.status===409?this.say("this thread has a turn that has not ended (it may wait for an approval): /threads opens it again","failed"):this.fail(i);return}await this.follow(t,0,Oi())}async send(e){this.notice.clear();let t=[...this.attachments],i=this.thread?void 0:this.place,n=this.thread?this.threadAgent:i?.agent??this.agent;if(!this.thread&&!n){this.say(this.loading?"still asking the platform which agents you have: try again in a moment":"no agent to ask: /agent chooses one","needs");return}let r=[];for(let u of t){this.say(`uploading ${u.name} (${ce(u.size)})\u2026`);try{r.push((await this.client.uploadFile(u.path)).id)}catch(d){let p=d instanceof D&&d.status===413?d.message:`uploading ${u.name}: ${d instanceof Error?d.message:String(d)}`;this.say(`${p} (nothing was sent; the files stay attached)`,"failed");return}}this.notice.clear();let o=!1;if(!this.thread){try{this.thread=i?await this.client.createThreadIn(n.productId,n.agentId,e,{app:i.app,key:i.key}):await this.client.createThread(n.productId,n.agentId),this.threadAgent=n,o=!0}catch(u){this.fail(u);return}this.transcript.removeChild(this.welcome)}let a=this.thread;this.attachments=[];let l=new ft(this.paint,e,t.map(u=>u.name));this.transcript.addChild(l),this.render();let c=async u=>{this.attachments=t,o?(await this.client.deleteThread(a.id).catch(()=>{}),this.newConversation(),this.place=i):this.transcript.removeChild(l),this.say(u,"failed")},h;try{h=await this.client.sendMessage(a.id,e,r)}catch(u){await c(u instanceof Error?u.message:String(u));return}if(h.status==="delivered"&&h.turn_id){await this.follow(h.turn_id,0,Oi());return}if(h.status==="failed"){await c(`the message started no turn: ${h.error||"the platform did not say why"}`);return}await this.client.withdrawMessage(a.id,h.id).catch(()=>{}),await c("this thread has a turn that has not ended (it may wait for an approval): /threads opens it again")}answerView(e,t){let i=new Bi(this.paint,e,{turnId:t,actions:()=>this.resultActions(),onRun:n=>this.openRun(n,t)});return i.onToggle=()=>this.render(),this.shownTurns.add(t),i}async follow(e,t,i){let n=this.answerView(i,e);this.transcript.addChild(n),this.answers.push(n);let r=new AbortController,o={turnId:e,answer:i,view:n,abort:r};this.following=o,this.last=i,this.render();let a=Js(i);a&&this.track(this.showApproval(a));let l=!1;try{for await(let c of this.client.follow(e,t,{signal:r.signal,onRetry:()=>{l=!0,this.say("the connection to the platform was lost: reconnecting\u2026","needs")}})){l&&(l=!1,this.notice.clear());let h=i.state;if(qr(i,c),n.sync(),c.event==="title"&&this.thread&&(this.thread.title=i.title),c.event==="interrupt"&&i.state==="awaiting_approval"){let u=Js(i);u&&this.track(this.showApproval(u))}h==="awaiting_approval"&&i.state!=="awaiting_approval"&&this.closeApproval(!0),this.render()}}catch(c){this.fail(c)}finally{this.following===o&&(this.following=void 0),i.state!=="awaiting_approval"&&this.closeApproval(),this.render(),this.track(this.readBell())}}async openThread(e){try{let[t,i]=await Promise.all([this.client.thread(e),this.client.threadTurns(e,20)]);this.newConversation(),this.thread={...t,id:t.id??e},this.threadAgent=this.choiceFor(t.product_id,t.agent_id),this.transcript.removeChild(this.welcome);let n=i.items??[];n.forEach((r,o)=>{let a=r.input??{};a.tool_action?this.transcript.addChild(new Fi(this.paint,"Run on hardware")):a.origin&&a.origin!=="member"?this.transcript.addChild(new ze(this.paint.dim(`\xB7 ${a.text||a.origin}`),0,1)):this.transcript.addChild(new ft(this.paint,a.text??"",(a.attachments??[]).map(u=>u.name)));let l=Dr(r.events??[],r.status);if(o===n.length-1&&(r.status==="running"||r.status==="admitted"||r.status==="awaiting_approval")){let u=this.follow(r.id,r.through_seq??0,l);a.tool_action?this.track(this.watchRun(this.addRun(r.id),u)):this.track(u);return}let h=this.answerView(l,r.id);this.transcript.addChild(h),this.answers.push(h),this.last=l,a.tool_action&&this.track(this.watchRun(this.addRun(r.id)))}),n.length||this.say("this thread has no turns yet: type a message to start one")}catch(t){t instanceof D&&(t.status===404||t.status===400)?this.say(`you have no thread ${e} here: /threads lists yours`,"failed"):this.fail(t)}this.render()}resultActions(){let e=this.thread?this.threadAgent:this.agent;return!e||!this.dir?[]:this.dir.products.find(n=>n.product_id===e.productId)?.agents?.find(n=>n.id===e.agentId)?.result_actions??[]}openRun(e,t,i){let n=this.thread;if(!n)return;if(this.following){this.say("a turn is running in this conversation: wait for it to end, then run the result on hardware","needs");return}let r=this.me,o=new un(this.paint,{settings:()=>this.client.settings(),providers:()=>this.devices.providers(),credential:a=>this.client.credential(a),saveKey:(a,l)=>r?this.client.saveCredential(a,{tenantId:r.current_tenant_id??"",userId:r.user.id},l):Promise.reject(new Error("the platform has not said who you are yet: try again in a moment")),catalog:(a,l)=>l?this.devices.refreshCatalog(a):this.devices.catalog(a),capabilities:(a,l)=>this.devices.capabilities(a,l),preview:(a,l,c)=>this.client.previewToolAction(n.id,a,{onCompiling:l,signal:c,pollMs:this.opts.previewPollMs}),submit:a=>this.client.submitToolAction(n.id,a)},{offer:e,threadId:n.id,turnId:t,link:`${this.client.signIn.handoff.web}/chat/${n.id}`,rerun:i,guardMs:this.opts.submitGuardMs});o.maxRows=()=>Math.max(10,Math.floor(this.tui.terminal.rows*.92)),o.requestRender=()=>this.render(),o.onWork=a=>this.track(a),o.onClose=()=>{this.overlay?.component===o&&this.hideOverlay()},o.onSubmitted=a=>this.track(this.followRun(a)),this.showOverlay("hardware",o,{width:"90%",minWidth:50,maxHeight:"92%"}),o.start()}get hardwareDialog(){return this.overlay?.kind==="hardware"?this.overlay.component:void 0}addRun(e){let t=new Wi(this.paint,e,`${this.client.signIn.handoff.web}/chat/${this.thread?.id??""}`);return t.onToggle=()=>this.render(),t.canRerun=i=>!!this.rerunOf(i),t.onRerun=i=>{let n=this.rerunOf(i);n&&this.openRun(n.offer,n.turnId,n.rerun)},this.transcript.addChild(t),this.runs.push(t),t}async followRun(e){this.notice.clear(),this.transcript.addChild(new Fi(this.paint,`Run on hardware: ${e.summary}`));let t=this.follow(e.turn.id,0,Oi());await this.watchRun(this.addRun(e.turn.id),t)}async watchRun(e,t){let i=this.generation,n=!t;t?.finally(()=>n=!0);let r=!1;for(let o=0;!this.stopped&&i===this.generation;o++){try{let a=await this.client.turnJobs(e.turnId);if(i!==this.generation)return;e.set(a),this.render();let l=a.some(Ni);if(r&&!l&&await this.afterRun(i),r=l,!l&&n&&o>0||!l&&n&&!t)return}catch(a){if(a instanceof D&&(a.status===404||a.status===403))return}await new Promise(a=>setTimeout(a,this.opts.jobPollMs??5e3))}}async afterRun(e){let t=this.thread;if(!(!t||this.following))try{let i=await this.client.threadTurns(t.id,3);if(e!==this.generation||this.following)return;let n=(i.items??[]).at(-1);if(!n||this.shownTurns.has(n.id)||!["running","admitted","awaiting_approval"].includes(n.status))return;let r=n.input??{};this.transcript.addChild(new ze(this.paint.dim(`\xB7 ${r.text||"the run ended: the agent reads its result"}`),0,1)),await this.follow(n.id,n.through_seq??0,Dr(n.events??[],n.status))}catch{}}rerunOf(e){let t=Dl(e.detail);if(!t||!["succeeded","failed","cancelled","lost"].includes(e.status))return null;let i=this.resultActions(),n=i.filter(l=>Ge(l)!==null&&l.submit_tool===e.tool);if(n.length!==1)return null;let r=this.answers.find(l=>l.turnId===t.turnId),o=r?.tools.find(l=>l.part.id===t.toolCallId);if(!r||!o)return null;let a=Ds(o.part,r.answer,i);return!a||a.candidate.kind==="optimization"?null:{offer:a,turnId:t.turnId,rerun:{provider:Ge(n[0]),point:t.point}}}stopRun(e,t){let i=new Ye(this.paint,`Stop this hardware run (${e.summary||e.tool})? A task the provider has already started may still finish there.`);i.onAnswer=n=>{this.hideOverlay(),n&&this.track(this.client.cancelJob(e.id).then(r=>{t.set(t.jobs.map(o=>o.id===r.id?r:o)),this.say("stopping the run\u2026")},r=>this.fail(r)))},this.showOverlay("confirm",i,{width:64,minWidth:30})}async showApproval(e,t=!1){let i=this.following;if(!i||this.approval?.part===e&&!t||(this.approval?.poll&&clearInterval(this.approval.poll),this.approval={part:e,dismissed:!1},t||await new Promise(l=>setTimeout(l,this.opts.approvalGraceMs??1e3)),this.following!==i||i.answer.state!=="awaiting_approval"||Js(i.answer)!==e))return;let n;try{let l=await this.client.approvals(i.turnId);if(n=l.find(c=>c.interrupt_seq===e.seq)??l.find(c=>!c.decision),n?.decision)return}catch{}if(this.following!==i||i.answer.state!=="awaiting_approval"||this.overlay?.kind==="approval")return;let r=(this.thread?this.threadAgent:this.agent)?.name??"the agent",o=new hn(this.paint,{agent:r,part:e,labs:this.dir?.labs??[],record:n});o.maxRows=()=>Math.max(8,this.tui.terminal.rows-4),o.onClose=()=>{this.approval&&(this.approval.dismissed=!0),this.hideOverlay(),this.say("the turn waits for your approval: Enter on an empty line shows it again","needs")},o.onAnswer=async l=>{try{await this.client.answerApproval(i.turnId,l)}catch(c){if(c instanceof D&&c.status===409){this.closeApproval(!0);return}throw c}this.closeApproval(),this.say(l.decision==="approve"?"approved: the turn goes on":"rejected: the agent is told","muted")},this.showOverlay("approval",o,{width:"80%",minWidth:40,maxHeight:"90%"});let a=setInterval(()=>{this.client.approvals(i.turnId).then(l=>{l.find(h=>h.interrupt_seq===e.seq)?.decision&&this.overlay?.component===o&&this.closeApproval(!0)},()=>{})},this.opts.approvalPollMs??3e3);a.unref?.(),this.approval.poll=a}closeApproval(e=!1){this.approval?.poll&&clearInterval(this.approval.poll);let t=this.overlay?.kind==="approval";t&&this.hideOverlay(),e&&(t||this.approval)&&this.say("the approval was answered: the turn goes on"),this.approval=void 0}showOverlay(e,t,i={width:"70%",minWidth:40,maxHeight:"80%"}){this.hideOverlay();let n=this.tui.showOverlay(t,i);this.overlay={handle:n,kind:e,component:t},this.render()}hideOverlay(){this.overlay&&(this.overlay.handle.hide(),this.overlay=void 0,this.tui.setFocus(this.editor),this.render())}get overlayKind(){return this.overlay?.kind}command(e){let[t=""]=e.slice(1).split(/\s+/),i=t.toLowerCase();switch(this.notice.clear(),i){case"new":this.newConversation();return;case"agent":this.pickAgent();return;case"lab":this.track(this.labList());return;case"threads":this.track(this.pickThread());return;case"project":case"projects":this.track(this.projectList());return;case"attach":this.attachCommand(e.slice(1+t.length));return;case"files":this.track(this.conversationFiles());return;case"artifacts":this.track(this.artifactList());return;case"notifications":this.track(this.notificationList());return;case"balance":this.track(this.balance());return;case"agents":this.track(this.setup.agents());return;case"kb":this.track(this.setup.knowledge());return;case"connections":this.track(this.setup.connections());return;case"schedules":this.track(this.setup.schedules());return;case"goals":this.track(this.setup.goals());return;case"workspaces":this.track(this.setup.workspaces());return;case"status":this.showOverlay("status",this.panel("Status",()=>this.statusLines()));return;case"help":this.showOverlay("help",this.panel("Help",()=>this.helpLines(),.85),{width:"90%",minWidth:40,maxHeight:"85%"});return;case"logout":this.quit(0,["logout"]);return;case"quit":case"exit":this.quit(0);return}let n=Hm(i,io.map(r=>r.name));this.say(`unknown command /${i}${n?`; did you mean /${n}?`:""} (/help lists them)`,"failed")}panel(e,t,i=.8){let n=new Qt(this.paint,e,t);return n.onClose=()=>this.hideOverlay(),n.maxRows=()=>Math.max(8,Math.floor(this.tui.terminal.rows*i)),n}statusLines(){let e=this.client.signIn.handoff,t={browser_key:"personal API key from the browser sign-in",pasted_key:"personal API key you pasted",env_key:"personal API key in QUPAI_API_KEY",device_sign_in:"sign-in at the identity provider"},i=this.me;return[`Platform ${e.server}`,...e.web&&e.web!==e.server?[`Web app ${e.web}`]:[],`Signed in as ${i?`${i.user.display_name}${i.user.email?` <${i.user.email}>`:""}`:"(asking)"}`,`Organization ${this.orgName()??"(none)"}`,`Sign-in ${t[e.kind]??(e.kind||"a key")}${e.renews?", renews itself":""}`,`Agent ${mt(this.agent)}`,...this.place?[`Project ${this.place.title} (${this.place.key})`]:[],...this.unread?[`Notifications ${this.unread} unread (/notifications)`]:[],...this.thread?[`Thread ${this.thread.id}${this.thread.title?` (${this.thread.title})`:""}`,` in the app ${e.web}/chat/${this.thread.id}`]:[]]}helpLines(){return["Commands:",...io.map(e=>` /${e.name.padEnd(15)}${e.description}`),"","Keys:",...Nc.map(([e,t])=>` ${e.padEnd(12)}${t}`),"","Approvals: when a turn waits for one, it opens over the conversation. Only A and R answer it.","Hardware: a result an agent's actions can run on hardware shows [Run on hardware v]. Tab to it and press v (or","click it): choose the provider, the device, the shots and the qubits, read the preview, then Run on hardware.","Files: /attach a path, or drop a file on the terminal (or paste its path): it shows above the composer and goes","with your next message. /files and /artifacts save what the conversation made into this directory.","The bell: the status line counts your unread notifications (read every minute and after each turn).","Credits: /balance shows them; top up in the app (the TUI takes no payments).","What you set up: /agents (e edits your instructions for one in the editor: Enter a new line, Ctrl+S saves), /kb,","/connections, /schedules, /goals and /workspaces. Adding a connection (its secret), a new schedule or goal, and an","agent's skills or environments are the qupai command's (qupai help lists them). A goal is approved in the app only."]}pickAgent(){if(!this.dir){this.say(this.loading?"still asking the platform which agents you have":"the platform did not say which agents you have","needs");return}let e=pt(this.dir),t=this.agent?le(this.agent.productId,this.agent.agentId):"",i=e.map((r,o)=>({value:String(o),label:r.name+(r.isDefault?" (organization default)":""),description:r.from==="lab"?`lab ${r.labName??r.lab}`:`${r.productName??r.productId}${le(r.productId,r.agentId)===t?" \xB7 in use":""}`})),n=new gt(this.paint,"Agent",i,{selected:e.findIndex(r=>le(r.productId,r.agentId)===t),empty:"no agent is offered to you here"});n.onCancel=()=>this.hideOverlay(),n.onPick=r=>{let o=e[Number(r)];this.hideOverlay(),o&&this.useAgent(o)},this.showOverlay("agent",n)}async reloadAgents(){let[e,t]=await Promise.all([this.client.products(),this.client.myAgents()]);this.dir=Er(e,t,this.dir?.labs??[]);let i=pt(this.dir),n=o=>o&&i.find(a=>a.productId===o.productId&&a.agentId===o.agentId);if(this.agent&&this.agent.from==="product"){let o=n(this.agent);if(o)this.agent=o;else{let a=this.agent;this.agent=Lr(this.dir,this.me?this.store.get(this.client.server,this.me.user.id):null),this.thread||this.say(`${a.name} is no longer there: new conversations go to ${mt(this.agent)}`,"needs")}}let r=n(this.threadAgent);r&&(this.threadAgent=r),this.render()}useAgent(e){this.agent=e,this.me&&this.store.set(this.client.server,this.me.user.id,Xl(e)),(this.thread||this.place)&&this.newConversation(),this.say(`new conversations go to ${mt(e)}`)}shown(e){let t=Wm(this.cwd,e);if(t&&!t.startsWith("..")&&!t.startsWith(Bc))return t;let i=Fm();return e.startsWith(i+Bc)?`~${e.slice(i.length)}`:e}attach(e){let t=[];for(let i of e){let n;try{n=Dc(i)}catch{this.say(`${this.shown(i)} is not there: nothing was attached`,"failed");return}if(n.isDirectory()){this.say(`${this.shown(i)} is a folder: attach files`,"failed");return}if(!(this.attachments.some(r=>r.path===i)||t.some(r=>r.path===i))){if(this.attachments.length+t.length>=Br){this.say(`at most ${Br} files go with a message`,"failed");break}t.push({path:i,name:mn(i),size:n.size})}}this.attachments=[...this.attachments,...t],t.length&&this.say(`attached ${t.map(i=>`${i.name} (${ce(i.size)})`).join(", ")}: ${t.length===1?"it goes":"they go"} with your next message`),this.render()}attachCommand(e){let t=Nr(e.trim());if(t.length===1&&(t[0]==="-clear"||t[0]==="--clear")){let i=this.attachments.length;this.attachments=[],this.say(i?`removed the ${i===1?"attached file":`${i} attached files`}`:"no files were attached");return}if(!t.length){this.say("/attach <path> attaches a file to your next message (or drop it on the terminal); /attach -clear removes them","needs");return}this.attach(t.map(i=>Gt(i,this.cwd)))}detachLast(){let e=this.attachments.at(-1);e&&(this.attachments=this.attachments.slice(0,-1),this.say(`removed ${e.name}`))}saveFile(e,t,i){let n=()=>this.track((async()=>{this.say(`saving ${i}\u2026`);try{let o=await this.client.download(e,t);this.say(`saved ${i} as ${this.shown(t)} (${ce(o)})`)}catch(o){o instanceof D&&o.status===404?this.say(`${i} is not there any more`,"failed"):this.fail(o)}})());if(!qc(t)){this.hideOverlay(),n();return}let r=new Ye(this.paint,`${this.shown(t)} is there already. Overwrite it with ${i}?`);r.onAnswer=o=>{this.hideOverlay(),o?n():this.say(`kept ${this.shown(t)}: nothing was saved`)},this.showOverlay("overwrite",r,{width:70,minWidth:30})}showFiles(e,t,i,n){let r=t.files.filter(l=>l.type!=="directory"),o=t.source==="snapshot"?" (from the last snapshot)":"",a=new te(this.paint,`${e}${o}`,r.map(l=>({value:l.path,label:l.path,description:`${ce(l.size)}${l.mtime?` \xB7 ${X(l.mtime)}`:""}`})),{footer:"\u2191\u2193 choose \xB7 Enter save it into this directory \xB7 Esc close",empty:t.source==="none"?n:"no files"});a.onCancel=()=>this.hideOverlay(),a.onPick=l=>this.saveFile(i(l),gn(this.cwd,mn(l)),mn(l)),this.showOverlay("files",a)}async conversationFiles(){let e=this.thread;if(!e){this.say("no conversation yet: its files are listed once it has started (/threads opens one)","needs");return}try{let t=await this.client.threadFiles(e.id);this.showFiles("This conversation's files",t,i=>Hl(e.id,i),"the conversation has no sandbox yet")}catch(t){this.fail(t)}}async artifactList(){let e=this.thread;if(!e){this.say("no conversation yet: its artifacts are listed once it has started (/threads opens one)","needs");return}let t;try{t=(await this.client.artifacts()).filter(n=>n.thread_id===e.id)}catch(n){this.fail(n);return}let i=new te(this.paint,"This conversation's artifacts",t.map(n=>({value:n.id,label:n.title||n.id,description:`version ${n.latest_version}${n.entry?` \xB7 ${n.entry.path} ${ce(n.entry.size)}`:""} \xB7 ${X(n.updated_at)}`})),{footer:"\u2191\u2193 choose \xB7 Enter save to a file \xB7 Esc close",empty:"this conversation has made no artifacts"});i.onCancel=()=>this.hideOverlay(),i.onPick=n=>{let r=t.find(o=>o.id===n);r&&this.track(this.saveArtifact(r))},this.showOverlay("artifacts",i)}async saveArtifact(e){let t=e.latest_version,i=e.entry?.path??"";if(!i)try{let a=(await this.client.artifact(e.id)).versions.reduce((l,c)=>!l||c.number>l.number?c:l,void 0);if(!a)throw new Error(`${e.title||e.id} has no version to save`);t=a.number,i=a.entry}catch(o){this.hideOverlay(),this.fail(o);return}let n=nc(e.title,i),r=new bt(this.paint,"Save the artifact",`Save "${e.title||e.id}" (version ${t}, ${mn(i)}) as a file, relative to ${this.shown(this.cwd)||"this directory"}:`,n);r.onCancel=()=>this.hideOverlay(),r.onAnswer=o=>{let a=o.trim();if(!a){r.refuse("type where to save it, or Esc"),this.render();return}let l=Gt(a,this.cwd);try{Dc(l).isDirectory()&&(l=gn(l,n))}catch{}if(!qc(gn(l,".."))){this.hideOverlay(),this.say(`there is no folder ${this.shown(gn(l,".."))}: nothing was saved`,"failed");return}this.saveFile(Vl(e.id,t,i),l,`"${e.title||e.id}"`)},this.showOverlay("save",r,{width:"70%",minWidth:40})}startBell(){this.stopped||this.bellTimer||(this.track(this.readBell()),this.bellTimer=setInterval(()=>this.track(this.readBell()),this.opts.bellPollMs??6e4),this.bellTimer.unref?.())}async readBell(){if(!(this.bellOff||this.stopped))try{let e=await this.client.notifications(1);this.unread=e.unread,this.render()}catch(e){e instanceof D&&(e.status===404||e.status===403)&&(this.bellOff=!0)}}notificationRow(e){let t=[Di(e.kind),e.summary?xe(e.summary,60):"",e.status?`(${e.status})`:""].filter(Boolean).join(" \xB7 ");return{value:e.id,label:`${e.read_at?" ":"\u2022"} ${xe(e.title||Di(e.kind),40)}`,description:`${t} \xB7 ${X(e.created_at)}`}}async notificationList(){let e;try{let n=await this.client.notifications(50);e=n.items??[],this.unread=n.unread}catch(n){n instanceof D&&n.status===404?this.say("this platform keeps no notifications","needs"):this.fail(n);return}let t=()=>`Notifications, newest first \xB7 ${this.unread} unread`,i=new te(this.paint,t(),e.map(n=>this.notificationRow(n)),{keys:["a"],footer:"\u2191\u2193 choose \xB7 Enter open it (marks it read) \xB7 a mark all read \xB7 Esc close",empty:"no notifications"});i.onCancel=()=>this.hideOverlay(),i.onKey=()=>{this.track(this.client.readNotifications().then(n=>{let r=new Date().toISOString();for(let o of e)o.read_at??=r;this.unread=n,i.setItems(e.map(o=>this.notificationRow(o))),i.setTitle(t()),i.say("all marked read"),this.render()},n=>{i.say(n instanceof Error?n.message:String(n),"failed"),this.render()}))},i.onPick=n=>{let r=e.find(o=>o.id===n);r&&this.openNotification(r)},this.showOverlay("notifications",i,{width:"90%",minWidth:40,maxHeight:"80%"})}openNotification(e){this.hideOverlay(),e.read_at||(e.read_at=new Date().toISOString(),this.unread=Math.max(0,this.unread-1),this.track(this.client.readNotifications([e.id]).then(i=>{this.unread=i,this.render()},()=>{})));let t=oc(e);t&&"thread"in t?this.thread?.id===t.thread?this.say(`${Di(e.kind)}: this conversation`):this.track(this.openThread(t.thread)):t&&"lab"in t?this.track(this.labStatus(t.lab)):this.say(`${Di(e.kind)}${e.summary?`: ${e.summary}`:""}`),this.render()}labRow(e){let t=e.agent?`agent ${K(e.agent.name,e.id)}`:"no agent for you";return{value:e.id,label:`${K(e.name,e.id)} (${e.id})`,description:`role ${en(e)} \xB7 ${e.status} \xB7 ${Wr(e.connection)} \xB7 ${t}`}}async labList(e){let t;try{t=await this.client.labs(),this.dir&&(this.dir.labs=t)}catch(r){this.fail(r);return}let i=e?.lab??(this.thread?this.threadAgent:this.agent)?.lab,n=new te(this.paint,"Your labs",t.map(r=>this.labRow(r)),{keys:["s","r","w"],footer:"Enter talk with its agent \xB7 s status \xB7 r ask for access \xB7 w withdraw it \xB7 Esc close",empty:"no lab is there for you",selected:t.findIndex(r=>r.id===i)});e&&n.say(e.text,e.tone),n.onCancel=()=>this.hideOverlay(),n.onPick=r=>{let o=t.find(l=>l.id===r);if(!o)return;let a=this.dir&&Li(this.dir).find(l=>l.lab===o.id);if(a){this.hideOverlay(),this.useAgent(a);return}tn(o)?o.status==="paused"?n.say(`${o.id} is paused: its agent is back when the lab is`,"needs"):n.say(`${o.id} offers your organization no agent`,"needs"):n.say(`you have no role on ${o.id}, so its agent is not yours to use: r asks QuPai staff for access`,"needs"),this.render()},n.onKey=(r,o)=>{let a=t.find(l=>l.id===o);a&&(r==="s"?this.track(this.labStatus(a.id)):r==="r"?this.askLabAccess(a,n):r==="w"&&this.track(this.withdrawLabAccess(a,n,t)),this.render())},this.showOverlay("lab",n,{width:"90%",minWidth:40,maxHeight:"80%"})}askLabAccess(e,t){if(tn(e)){t.say(`you hold a role on ${e.id} already (${en(e)})`,"needs");return}if(e.access_request==="pending"){t.say(`you have asked for ${e.id} already: QuPai staff answer it${this.labRequests.has(e.id)?" (w withdraws it)":""}`,"needs");return}let i=new bt(this.paint,`Ask for access to ${K(e.name,e.id)}`,"QuPai staff decide who uses a lab, and every staff member is told. A note for them (optional, at most 500 characters):");i.onCancel=()=>this.track(this.labList({text:"nothing was asked",lab:e.id})),i.onAnswer=n=>{let r=n.trim();if([...r].length>500){i.refuse(`the note is ${[...r].length} characters: at most 500`),this.render();return}this.hideOverlay(),this.track(this.client.requestLabAccess(e.id,r).then(o=>(this.labRequests.set(e.id,o.id),this.labList({text:`Asked QuPai staff for a role on ${e.id} (request ${o.id}). w withdraws it while the app is open: the platform gives the id only now.`,lab:e.id})),o=>{let a=o instanceof D&&o.status===409?`you hold a role on ${e.id} already, or have asked already: ${o.detail.replace(/\.$/,"")}`:o instanceof Error?o.message:String(o);return this.labList({text:a,tone:"failed",lab:e.id})}))},this.showOverlay("lab-request",i,{width:"70%",minWidth:40})}async withdrawLabAccess(e,t,i){let n=this.labRequests.get(e.id);if(!n){t.say(e.access_request==="pending"?`this app did not make that request, so it does not know its id: withdraw it on the lab's page in the app (${Kr(this.client.signIn.handoff.web,e.id)})`:`you have no open request for ${e.id}`,"needs");return}try{await this.client.withdrawLabAccess(e.id,n)}catch(r){r instanceof D&&r.status===404?(this.labRequests.delete(e.id),t.say(`${e.id} has no open request ${n} of yours (it may have been answered)`,"failed")):t.say(r instanceof Error?r.message:String(r),"failed"),this.render();return}this.labRequests.delete(e.id),e.access_request=null,t.setItems(i.map(r=>this.labRow(r))),t.say(`Withdrew your request for ${e.id}.`),this.render()}async labStatus(e){let t;try{t=await this.client.lab(e)}catch(o){o instanceof D&&o.status===404?this.say(`no lab ${e} is there for you (/lab lists yours)`,"failed"):this.fail(o);return}let i;if(!tn(t))i="you have no role on this lab: r in /lab asks QuPai staff for one";else if(t.status==="paused")i="the lab is paused";else try{i=await this.client.labMachines(t.id)}catch(o){o instanceof D&&o.status===503?i=`the lab does not answer (no lab PC is connected, or it is down): ${o.detail.replace(/\.$/,"")}`:o instanceof D&&o.status===409?i="the lab is paused":i=o instanceof Error?o.message:String(o)}let n=rc(t,i,this.client.signIn.handoff.web),r=this.panel(`${K(t.name,t.id)}: status`,()=>n,.85);this.showOverlay("lab-status",r,{width:"85%",minWidth:40,maxHeight:"85%"})}async projectList(){let e=[],t=0;for(let r of Km)try{let o=await this.client.places(r);t++;for(let a of o.items??[])e.push({app:a.app||r,key:a.key,title:a.title,updated:a.updated_at,declared:o.declared_by})}catch(o){if(o instanceof D&&(o.status===404||o.status===400||o.status===403&&o.type.endsWith(":feature-disabled")))continue;this.fail(o);return}if(!t){this.say("this platform offers you no projects (no package declares them, or your organization has the app turned off)","needs");return}let i=new te(this.paint,"Your projects",e.map(r=>({value:`${r.app}/${r.key}`,label:r.title||r.key,description:`${r.key} \xB7 ${r.app==="project"?"project":"calibration project"} \xB7 ${X(r.updated)}`})),{keys:["f"],footer:"\u2191\u2193 choose \xB7 Enter start a conversation in it \xB7 f its files \xB7 Esc close",empty:"no projects yet: make one in the app"}),n=r=>e.find(o=>`${o.app}/${o.key}`===r);i.onCancel=()=>this.hideOverlay(),i.onPick=r=>{let o=n(r);if(!o)return;let a=o.declared?.product_id&&o.declared.agent_id?this.choiceFor(o.declared.product_id,o.declared.agent_id):this.agent;if(!a){i.say("no agent to start it with: /agent chooses one","needs"),this.render();return}this.hideOverlay(),this.newConversation(),this.place={app:o.app,key:o.key,title:o.title||o.key,agent:a},this.say(`a new conversation in ${this.place.title} with ${mt(a)}: your first message starts it`)},i.onKey=(r,o)=>{let a=n(o);a&&this.track(this.client.placeFiles(a).then(l=>this.showFiles(`${a.title||a.key}: files`,l,c=>zl(a,c),"nothing is kept for the project yet"),l=>{i.say(l instanceof Error?l.message:String(l),"failed"),this.render()}))},this.showOverlay("project",i,{width:"80%",minWidth:40,maxHeight:"80%"})}async balance(){let t=sc(),[i,n]=await Promise.allSettled([this.client.billing(),this.client.usage(7,t)]);if(i.status==="rejected"){this.fail(i.reason);return}let r=i.value,o=`${this.client.signIn.handoff.web.replace(/\/+$/,"")}/credits`,a=[`Balance ${re(r.account.balance_ucny)}`,`Available ${re(r.account.available_ucny)} (${re(r.account.held_ucny)} held for running work)`,`Paid by ${r.payer==="tenant"?"your organization: its admin tops it up":"you"}`,`Top up in the app: ${o}`,""];if(n.status==="rejected")a.push(`Usage: ${n.reason instanceof Error?n.reason.message:String(n.reason)}`);else{let c=n.value;a.push(`The last 7 days (${c.tz}): ${re(c.spent_ucny)} spent, ${c.charges} ${c.charges===1?"charge":"charges"}`);let h=(c.days??[]).filter(u=>u.charges>0);for(let u of h)a.push(` ${u.day} ${re(u.spent_ucny).padStart(10)} ${u.charges} ${u.charges===1?"charge":"charges"}`);if((c.items??[]).length){a.push("","By model or tool");for(let u of c.items)a.push(` ${`${u.kind}${u.subject?` ${u.subject}`:""}`.padEnd(32)}${re(u.spent_ucny).padStart(10)} ${u.charges}`)}}let l=this.panel("Balance",()=>a,.85);this.showOverlay("balance",l,{width:"80%",minWidth:40,maxHeight:"85%"})}async pickThread(){let e;try{e=await this.client.threads(30)}catch(n){this.fail(n);return}let t=e.map(n=>({value:n.id,label:n.title||"(untitled)",description:`${n.updated_at?new Date(n.updated_at).toLocaleString():""} \xB7 ${n.product_id}/${n.agent_id}${n.activity==="needs_you"?" \xB7 needs you":n.activity==="running"?" \xB7 running":""}`})),i=new gt(this.paint,"Threads, newest first",t,{empty:"no threads yet"});i.onCancel=()=>this.hideOverlay(),i.onPick=n=>{this.hideOverlay(),this.track(this.openThread(n))},this.showOverlay("threads",i)}stopTurn(){let e=this.following;if(!e)return;let t=new Ye(this.paint,"Stop this turn? The agent stops where it is; what it did so far stays.");t.onAnswer=i=>{this.hideOverlay(),i&&this.track(this.client.cancelTurn(e.turnId).then(()=>this.say("stopping the turn\u2026"),n=>this.fail(n)))},this.showOverlay("confirm",t,{width:60,minWidth:30})}quit(e,t){if(this.stopped)return;this.bellTimer&&clearInterval(this.bellTimer),this.following?.abort.abort(),this.closeApproval(),this.hideOverlay(),this.stopped=!0;let i=new ee;if(this.thread){for(let r of this.transcript.children)r!==this.welcome&&i.addChild(r);i.addChild(new ze(this.paint.dim(`thread ${this.thread.id} \xB7 continue it with qupai chat -thread ${this.thread.id}`),0,1))}sr(this.tui)&&this.tui.setLayoutRoot(i),this.tui.stop();let n=e;t&&this.opts.runCommand&&(n=this.opts.runCommand(t)),this.client.signIn.close(),this.opts.onExit?.(n)}get tools(){return this.transcript.children.flatMap(e=>e instanceof Bi?e.tools:e instanceof Wi?e.cards:[])}setNav(e){let t=this.tools;for(let i of t)i.selected=!1;this.nav=e,e>=0&&t[e]&&(t[e].selected=!0),this.render()}onKey(e){if(this.overlay)return S(e,T.ctrl("c"))&&this.overlay.kind!=="approval"?(this.overlay.kind==="hardware"?this.overlay.component.close():this.hideOverlay(),{consume:!0}):void 0;if(e.startsWith("\x1B[200~")&&e.endsWith("\x1B[201~")){let i=Fr(e.slice(6,-6),this.cwd);if(i)return this.attach(i),{consume:!0}}let t=this.editor.getText()==="";if(S(e,T.backspace)&&t&&this.attachments.length&&this.nav<0)return this.detachLast(),{consume:!0};if(this.nav>=0){let i=this.tools;if(S(e,T.up))this.setNav(Math.max(0,this.nav-1));else if(S(e,T.down))this.setNav(Math.min(i.length-1,this.nav+1));else if(S(e,T.enter)||e===" "){let n=i[this.nav];n&&(n.expanded=!n.expanded),this.render()}else if(e==="v"||e==="V"){let n=i[this.nav],r=n instanceof Ki?n.rerunnable():!!n?.offer;n&&r?(this.setNav(-1),n.act()):this.say("nothing here runs on hardware: \u2191\u2193 to a line marked [Run on hardware v]","needs")}else if(S(e,T.escape)||S(e,T.tab)||S(e,T.ctrl("c")))this.setNav(-1);else if(S(e,T.pageUp)||S(e,T.pageDown))return;return{consume:!0}}if(S(e,T.ctrl("c")))return t?this.quit(0):this.editor.setText(""),this.render(),{consume:!0};if(S(e,T.ctrl("d"))&&t)return this.quit(0),{consume:!0};if(S(e,T.escape)&&this.following&&t)return this.stopTurn(),{consume:!0};if(S(e,T.escape)&&t)for(let i of this.runs){let n=i.active.find(r=>r.kind==="hardware"&&!r.cancel_requested&&!jt(r.detail));if(n)return this.stopRun(n,i),{consume:!0}}if(e==="?"&&t)return this.showOverlay("keys",this.panel("Keys",()=>Nc.map(([i,n])=>`${i.padEnd(12)}${n}`),.85),{width:"90%",minWidth:40,maxHeight:"85%"}),{consume:!0};if(S(e,T.tab)&&t&&this.tools.length)return this.setNav(this.tools.length-1),{consume:!0}}};function Um(s){let[e,t]=process.platform==="darwin"?["open",[s]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",s]]:["xdg-open",[s]];try{let i=Nm(e,t,{stdio:"ignore",detached:!0});return i.on("error",()=>{}),i.unref(),!0}catch{return!1}}function Hm(s,e){let t="",i=1/0;for(let n of e){let r=zm(s,n);r<i&&([t,i]=[n,r])}return t&&i<=Math.max(2,Math.floor(s.length/3))?t:""}function zm(s,e){let t=Array.from({length:e.length+1},(i,n)=>n);for(let i=1;i<=s.length;i++){let n=[i];for(let r=1;r<=e.length;r++)n[r]=Math.min(t[r]+1,n[r-1]+1,t[r-1]+(s[i-1]===e[r-1]?0:1));t=n}return t[e.length]}import{spawn as Vm}from"node:child_process";import{Socket as jm}from"node:net";var ke=class extends Error{exit;constructor(e,t=3){super(e),this.exit=t}};function Fc(s){let e;try{e=JSON.parse(s)}catch{throw new ke("the qupai command handed over no sign-in the app can read",1)}if(e.error)throw new ke(e.error,e.exit??3);if(!e.server||!e.token)throw new ke("the qupai command handed over no sign-in",1);return{server:e.server.replace(/\/+$/,""),web:(e.web||e.server).replace(/\/+$/,""),token:e.token,kind:e.kind??"",renews:e.renews===!0,choice_file:e.choice_file??""}}var no=class{buffer="";waiting=[];lines=[];ended=!1;constructor(e){e.setEncoding("utf8"),e.on("data",i=>{this.buffer+=i;let n;for(;(n=this.buffer.indexOf(`
|
|
119
|
-
`))>=0;){let r=this.buffer.slice(0,n);this.buffer=this.buffer.slice(n+1);let o=this.waiting.shift();o?o(r):this.lines.push(r)}});let t=()=>{this.ended=!0;for(let i of this.waiting.splice(0))i(null)};e.on("end",t),e.on("close",t),e.on("error",t)}next(){let e=this.lines.shift();return e!==void 0?Promise.resolve(e):this.ended?Promise.resolve(null):new Promise(t=>this.waiting.push(t))}};function
|
|
120
|
-
`),n()),close:()=>t.destroy()}}function
|
|
121
|
-
`)[0]??"";if(u){try{n(
|
|
117
|
+
`))i.push(` ${p}`)}return i.push(""),i.push(a.mode==="sandbox"?"This circuit was compiled in this conversation's sandbox. Run on hardware submits it for one hardware run: the device service sends it as compiled and follows it; you can stop the run from the conversation.":"Run on hardware submits this circuit, device, shot count and compiled layout for one hardware run."),i.push(t.dim(this.pays(r))),i}footer(){switch(this.step){case"provider":return"\u2191\u2193 choose \xB7 Enter continue \xB7 Esc close";case"key":return"paste the key \xB7 Enter save \xB7 Esc back";case"device":return"\u2191\u2193 choose \xB7 Enter pick \xB7 r read again \xB7 Esc back";case"options":return"\u2191\u2193 move \xB7 \u2190\u2192 Space change \xB7 digits for numbers \xB7 Enter on Preview \xB7 Esc back";case"qubits":return"\u2191\u2193 move \xB7 Space or Enter choose \xB7 Esc back";case"preview":return this.preview?"Enter on Run on hardware submits \xB7 \u2190\u2192 Change \xB7 \u2191\u2193 PgUp PgDn scroll \xB7 Esc back":"Esc back (stops waiting)"}}render(e){let t=Math.max(10,e-4),i=this.rows(t),n=Math.max(4,this.maxRows()-5-(this.step==="preview"&&this.preview?2:0)),r=0;if(i.length>n)if(this.step==="preview")this.scroll=Math.min(this.scroll,i.length-n),r=this.scroll;else{let l=i.findIndex(c=>c.focus);r=l<0?0:Math.min(Math.max(0,l-Math.floor(n/2)),i.length-n)}let o=i.slice(r,r+n),a=o.map(l=>l.text);if(this.hits=[],o.forEach((l,c)=>{l.hit&&(this.hits[this.bodyTop+c]=l.hit)}),i.length>n&&a.push(this.paint.dim(`lines ${r+1}-${r+o.length} of ${i.length}`)),this.step==="preview"&&this.preview){let l=this.busy?" Submitting\u2026 ":` ${Am} `,c=" Change ",h=(d,p)=>p?this.paint.inverse(this.paint.bold(d)):`[${d}]`;a.push("");let u=`${h(c,this.button==="change")} ${h(l,this.button==="run")}`;a.push(u),this.buttonRow={y:this.bodyTop+a.length-1,changeEnd:x(`[${c}]`)+1}}else this.buttonRow=void 0;return De(this.paint,e,this.title(),a.map(l=>_(l,t,"")),this.footer())}buttonRow;clickButton(e){this.buttonRow&&(e-2<this.buttonRow.changeEnd?this.back():(this.button="run",this.submit()))}};function yt(s){return s instanceof Error?s.message:String(s)}function wc(s){let e=Ll(s);return`${s.num_qubits??"?"} qubit${s.num_qubits===1?"":"s"} \xB7 ${e.state} \xB7 ${e.queue}`}function Mm(s){let e=Math.max(0,(Date.now()-Date.parse(s))/1e3);return Number.isFinite(e)?`${ht(Math.round(e))} ago`:"earlier"}function Em(s){let e=s.baseline;if(e.kind==="maxcut")return`QAOA Max-Cut \xB7 ${e.result.num_qubits} nodes`;let t=e.result.molecule;return t?`${e.point!==void 0?"Bond-length scan":"VQE"} \xB7 ${Pi(t.name)} ${t.bond_length} \xC5`:"VQE energy"}var Lm=new Set(["submitted","running"]),Wi=s=>Lm.has(s.status),Ui=class{paint;text;constructor(e,t){this.paint=e,this.text=t}invalidate(){}render(e){return["",...M(`${this.paint.tone("\u25B6","brand")} ${this.paint.bold(this.text)}`,e)]}},Ki=class{jobs=[];turnId;cards=[];paint;link;onRerun;canRerun=()=>!1;onToggle;constructor(e,t,i){this.paint=e,this.turnId=t,this.link=i}set(e){this.jobs=e;for(let t of e){if(Wi(t))continue;if(this.cards.some(n=>n.job.id===t.id)){this.cards.find(n=>n.job.id===t.id).job=t;continue}if(!Hs(t.detail)&&!Mi(t.detail)&&!jt(t.detail))continue;let i=new Hi(this.paint,t,this.link);i.onRerun=()=>this.onRerun?.(i.job),i.rerunnable=()=>this.canRerun(i.job),i.onToggle=()=>this.onToggle?.(),this.cards.push(i)}}get active(){return this.jobs.filter(Wi)}invalidate(){}handleMouse(e){let t=e.y-this.rowCount;for(let i of this.cards){let n=i.height;if(t>=0&&t<n)return i.handleMouse({...e,y:t});t-=n}}rowCount=0;render(e){let t=this.paint,i=[];for(let n of this.jobs){let r=Wi(n);if(this.cards.find(d=>d.job.id===n.id&&n.status==="succeeded"))continue;let a=r?t.tone("\u25CC","brand"):n.status==="succeeded"?t.tone("\u2713","ok"):n.status==="failed"?t.tone("\u2717","failed"):t.tone("\u25A0","stopped"),l=r&&n.cancel_requested?"stopping\u2026":n.status;i.push(_(` ${a} ${n.summary||n.tool||n.job_key} ${t.dim(`${n.kind} \xB7 ${l}`)}`,e,""));let c=n.detail,h=r&&n.kind==="hardware"?Nl(c,Mi(c)?.variational.circuits??void 0):null;h&&i.push(...M(t.dim(` ${h}`),e));let u=c?.execution_warning;if(r&&typeof u=="string"&&u.trim()&&i.push(...M(t.dim(` ${u.trim()}`),e)),r&&n.kind==="hardware"&&!jt(c)&&!n.cancel_requested&&i.push(t.dim(" Esc on an empty line stops it")),!r&&n.status!=="succeeded"){let d=typeof c?.error=="string"?c.error:typeof c?.lost_reason=="string"?c.lost_reason:"";d&&i.push(...M(t.tone(` ${d}`,"failed"),e))}}this.rowCount=i.length;for(let n of this.cards)i.push(...n.render(e));return i}},Hi=class{job;selected=!1;expanded=!1;onRerun;onToggle;rerunnable=()=>!1;paint;link;lastHeight=0;buttonAt;constructor(e,t,i){this.paint=e,this.job=t,this.link=i}get height(){return this.lastHeight}act(){this.rerunnable()&&this.onRerun?.()}invalidate(){}handleMouse(e){if(!(e.type!=="click"||e.button!=="left")){if(e.y===1&&this.buttonAt&&e.x>=this.buttonAt.from&&e.x<this.buttonAt.to)return this.act(),{handled:!0};if(e.y===1)return this.expanded=!this.expanded,this.onToggle?.(),{handled:!0}}}render(e){let t=this.paint,i=[""],n=Math.max(20,e-4),r=this.rerunnable()?`[${Tm} v]`:"",o=u=>{let p=`${this.selected?t.tone("\u203A","brand"):" "} ${t.tone("\u25C6","brand")} ${t.bold(u)}`,f=e-x(r)-1,m=r?J(_(p,f,""),f)+" "+(this.selected?t.inverse(r):t.tone(r,"brand")):_(p,e,"");this.buttonAt=r?{from:f+1,to:f+1+x(r)}:void 0,i.push(m)},a=(u,d)=>i.push(...M(` ${t.dim(u.padEnd(20))}${d}`,e)),l=Hs(this.job.detail),c=Mi(this.job.detail),h=jt(this.job.detail);if(l){let u=l.hardware;if(o(`Hardware result \xB7 ${l.target}${u?.shots!=null?` \xB7 ${u.shots} sampled shots`:` \xB7 ${l.shots} requested shots`}`),i.push(t.dim(` ${l.layout_mode==="physical_pool"?`Physical pool: ${l.qids.join(", ")}`:"Automatic compiler layout"}`)),l.error&&!(u&&l.error===l.comparison_error)&&i.push(...M(t.tone(` ${l.error}`,"failed"),e)),typeof l.execution_warning=="string"&&l.execution_warning.trim()&&i.push(...M(t.dim(` ${l.execution_warning}`),e)),u){let{rows:d,more:p,comparable:f}=Wl(l);f&&l.comparison?i.push(` ${t.dim("TVD")} ${l.comparison.tvd.toFixed(6)} ${t.dim("classical fidelity")} ${l.comparison.fidelity.toFixed(6)}`):i.push(...M(t.dim(` ${u.bit_order==null?"The measurement bit order is unconfirmed, so the run is not compared with the simulation.":"This result cannot be compared with the simulation."} Hardware counts:`),e)),u.counts_kind==="readout_corrected_estimate"&&i.push(t.dim(" Readout correction is applied: the bars are the corrected probabilities."));let m=Math.min(24,Math.max(5,...d.map(g=>g.state.length))),b=Math.max(6,n-m-24);i.push(t.dim(` ${"outcome".padEnd(m)} ${f?"hardware / simulation":"hardware"}`));for(let g of d){let y=g.state.length>m?`${g.state.slice(0,m-1)}\u2026`:g.state.padEnd(m);i.push(_(` ${y} ${t.dim("hw ")} ${t.tone(J(ut(g.hardware,b),b),"brand")} ${zs(g.hardware).padStart(6)}`,e,"")),g.simulation!==void 0&&i.push(_(` ${" ".repeat(m)} ${t.dim("sim")} ${t.dim(J(ut(g.simulation,b),b))} ${zs(g.simulation).padStart(6)}`,e,""))}p&&i.push(t.dim(` ${p} more outcome${p===1?"":"s"}; the metrics use the complete distributions`))}}else if(c){let u=c.readout;o(`Hardware result \xB7 ${c.target} \xB7 ${c.variational.circuits} circuit${c.variational.circuits===1?"":"s"} \xD7 ${c.shots} shots`);let d=c.baseline,p=d.result.molecule;if(i.push(t.dim(` ${d.kind==="maxcut"?`QAOA Max-Cut \xB7 ${d.result.num_qubits} nodes`:p?`${d.point!==void 0?"Bond-length scan":"VQE"} \xB7 ${Pi(p.name)} ${p.bond_length} \xC5`:"VQE energy"}`)),c.serial&&(c.state==="submitted"||c.state==="running")&&c.serial.done<c.serial.total&&i.push(t.dim(` Submitting one at a time: circuit ${c.serial.done+1} of ${c.serial.total}`)),c.error&&c.error!==c.readout_error&&i.push(...M(t.tone(` ${c.error}`,"failed"),e)),!u&&c.readout_error&&i.push(...M(t.tone(` The run finished, but its readout could not be computed: ${c.readout_error}`,"failed"),e)),u&&"hardware_energy"in u){let f=!!(u.molecule??p),m=f?" Ha":"",b=v=>Ri(v.toFixed(6)),g=typeof u.exact_energy=="number"?u.exact_energy:void 0,y=typeof u.difference_mha=="number"?u.difference_mha:g!==void 0?(u.hardware_energy-g)*1e3:void 0;a("Hardware energy",`${b(u.hardware_energy)} \xB1 ${b(u.standard_error)}${m}`),a("Simulated (VQE)",`${b(u.simulated_energy)}${m}`),g!==void 0&&a("Exact energy",`${b(g)}${m}`),y!==void 0&&a("Difference from exact",f?`${Ri(y.toFixed(2))} \xB1 ${Ri((u.standard_error*1e3).toFixed(2))} mHa`:`${b(y/1e3)} \xB1 ${b(u.standard_error)}`);let w=g??u.simulated_energy,k=Math.max(Math.abs(u.hardware_energy-w),Math.abs(u.simulated_energy-w),1e-9),P=Math.max(6,n-40);i.push(t.dim(` distance from the ${g!==void 0?"exact":"simulated"} energy:`)),i.push(_(` ${t.dim("hw ")} ${t.tone(J(ut(Math.abs(u.hardware_energy-w)/k,P),P),"brand")} ${(Math.abs(u.hardware_energy-w)*1e3).toFixed(2)} mHa`,e,"")),g!==void 0&&i.push(_(` ${t.dim("sim")} ${t.dim(J(ut(Math.abs(u.simulated_energy-w)/k,P),P))} ${(Math.abs(u.simulated_energy-w)*1e3).toFixed(2)} mHa`,e,"")),f&&g!==void 0&&y!==void 0&&i.push(Math.abs(y)<=1.6?t.tone(" Within chemical accuracy (1.6 mHa)","ok"):t.tone(" Outside chemical accuracy (1.6 mHa)","needs")),i.push(t.dim(` ${u.readout_corrected?"Readout correction applied.":c.readout_correction?"Readout correction was requested but not applied.":"Readout correction off."}`))}if(u&&"max_cut"in u){let f=u.ideal,m=w=>typeof w=="number"?w.toFixed(3):"\u2014",b=w=>typeof w=="number"?zs(w):"\u2014";i.push(t.dim(` ${"".padEnd(22)}${"hardware".padStart(10)}${"ideal".padStart(10)}`)),i.push(` ${"Approximation ratio".padEnd(22)}${m(u.approximation_ratio).padStart(10)}${m(f.approximation_ratio).padStart(10)}`),i.push(` ${"P(optimal cut)".padEnd(22)}${b(u.p_optimal).padStart(10)}${b(f.p_optimal).padStart(10)}`),i.push(` ${"Expected cut".padEnd(22)}${String(Number(u.expected_cut.toFixed(4))).padStart(10)}${String(Number(f.expected_cut.toFixed(4))).padStart(10)}`);let g=Math.max(6,n-40),y=u.max_cut>0?u.max_cut:1;i.push(_(` ${t.dim("cut hw ")} ${t.tone(J(ut(u.expected_cut/y,g),g),"brand")} ${Number(u.expected_cut.toFixed(4))} of ${u.max_cut}`,e,"")),i.push(_(` ${t.dim("cut sim")} ${t.dim(J(ut(f.expected_cut/y,g),g))} ${Number(f.expected_cut.toFixed(4))} of ${u.max_cut}`,e,"")),a("Most frequent outcome",`${u.most_frequent.bits} \xB7 cut ${u.most_frequent.cut}`),a("Maximum cut",String(u.max_cut)),i.push(t.dim(` ${u.readout_corrected?"Readout correction applied.":c.readout_correction?"Readout correction was requested but not applied.":"Readout correction off."}`))}}else h&&(o(`isingq result${h.machine?` \xB7 ${h.machine.name}`:""}`),h.cloud_job_id&&a("Provider task",h.cloud_job_id),h.state==="submission_unknown"&&i.push(t.tone(" Submission is uncertain. Check your isingq account before starting another run.","needs")),h.hardware&&(a("Local objective",String(h.baseline.objective_value)),a("Hardware objective",String(h.hardware.objective_value)),h.comparison&&a("Hardware \u2212 local",String(h.comparison.objective_delta)),i.push(t.dim(" Both values are evaluated against the same original objective; for a minimization a negative difference is better."))),h.error&&i.push(...M(t.tone(` ${h.error}`,"failed"),e)),h.execution_warning&&i.push(...M(t.dim(` ${h.execution_warning}`),e)));return i.push(t.dim(` The full charts: ${this.link}`)),this.lastHeight=i.length,i.map(u=>_(u,e,""))}};import{statSync as Nm}from"node:fs";function Ne(s,e){return s===1?`1 ${e}`:`${s} ${e}s`}function zi(s,e,t){let i=t?new URLSearchParams(t).toString():"";return`${s.replace(/\/+$/,"")}${e}${i?`?${i}`:""}`}var Om=(s,e)=>zi(s,`/chat/${encodeURIComponent(e)}`);function xc(s){let e=Math.max(0,Math.round(s));if(e<60)return`${e}s`;let t=Math.floor(e/86400),i=Math.floor(e%86400/3600),n=Math.floor(e%3600/60);return t?i?`${t}d ${i}h`:`${t}d`:i?n?`${i}h ${n}m`:`${i}h`:`${n}m`}function kc(s){return Zs(s.products).map(({product:e,agent:t})=>{let i=t.mine&&e.agents?.find(n=>n.id===t.mine.base)||t;return{product:e,agent:t,base:i,own:!!t.mine}})}var G=s=>U(s.agent.name,s.agent.id),Yr=s=>s.own?s.agent.id:`${s.product.product_id}/${s.agent.id}`,Sc=s=>s.products.some(e=>(e.agents??[]).some(t=>t.customizable!==void 0));function Xr(s,e,t){return Sc(s)?(e.base.customizable??[]).includes(t):!0}function Cc(s){let e=s.base.customizable??[];return e.length?e.join(", "):"nothing"}function Jr(s,e,t){return`${G(s)} does not let members ${e} (it needs ${t}; what it opens: ${Cc(s)})`}var Be=(s,e)=>typeof s[e]=="string"?s[e]:"",Jt=(s,e)=>Array.isArray(s[e])?s[e].filter(t=>typeof t=="string"):[];function qm(s,e){let t=s.instructions_private?"its own (kept private by its package)":`its own (${ce(Buffer.byteLength(s.instructions??""))})`,i=e.instructions_off===!0,n=Be(e,"instructions_replace"),r=Be(e,"instructions_append");return n&&i?`${t}; yours in their place are kept but off`:n?`yours in place of its own (${ce(Buffer.byteLength(n))})`:r&&i?`${t}; yours are kept but off`:r?`${t}, then yours (${ce(Buffer.byteLength(r))})`:s.organization_instructions?`${t}, then your organization's`:t}function vc(s,e,t){let i=s.map(n=>e.includes(n)?`${n} (off)`:n);return t&&i.push(`${t} from your library`),i.length?i.join(", "):"-"}function Dm(s,e){let t=Jt(e,"environments_off"),i=(s.environments??[]).filter(n=>!t.includes(n));for(let n of Jt(e,"environment_ids"))i.includes(n)||i.push(n);return i}var Bm=(s,e,t)=>zi(s,"/agent-settings",{agent:`${e}/${t}`});function $c(s,e,t,i){let n=e.base,r=e.product,o=[];if(e.own){o.push(`Agent ${G(e)} (${e.agent.id}), yours`),o.push(`Built on ${r.product_id}/${n.id} (${U(n.name,n.id)})`);let c=U(e.agent.description??void 0);c&&o.push(`Description ${xe(c,200)}`)}else{o.push(`Agent ${G(e)} (${r.product_id}/${n.id})`);let c=U(n.description??void 0);c&&o.push(`Description ${xe(c,200)}`)}o.push(`Product ${r.product_id} ${r.version??""}${r.available?"":", unavailable"} (${U(r.name,r.product_id)})`.replace(/ {2,}\(/," (")),n.kind&&o.push(`Kind ${n.kind}`);let a=n.models?.default?`tier ${n.models.default}`:"the organization's default";n.models?.allowed?.length&&(a+=` (may use ${n.models.allowed.join(", ")})`),Be(t,"default_tier")&&(a+=`; yours: ${Be(t,"default_tier")}`),Be(t,"custom_provider_id")&&(a+=`; yours: your own endpoint ${Be(t,"custom_provider_id")}`),o.push(`Model ${a}`),o.push(`Instructions ${qm(n,t)}`),o.push(`Skills ${vc((n.skills??[]).map(c=>c.id),Jt(t,"skills_off"),Jt(t,"skill_ids").length)}`),o.push(`Plugins ${vc((n.plugins??[]).map(c=>c.id),Jt(t,"plugins_off"),Jt(t,"plugin_ids").length)}`),n.tools?.length&&o.push(`Tools ${n.tools.map(c=>`${c.listing}${c.available===!1?" (not run here)":""}`).join(", ")}`);let l=Dm(n,t);if(l.length&&o.push(`Environments ${l.join(", ")}`),n.knowledge){let c="does not use your knowledge bases";n.knowledge.user&&(c=t.use_knowledge===!1?"may search your knowledge bases; you turned it off":"searches your knowledge bases"),o.push(`Knowledge ${c}`)}if(typeof n.max_tool_calls=="number"){let c=typeof t.max_tool_calls=="number"?`; yours: ${t.max_tool_calls}`:"";o.push(`Limits at most ${n.max_tool_calls} tool calls a turn${c}`)}return o.push(`You may change ${Sc(s)?Cc(e):"what the platform allows (it does not say)"} (turning things off, always)`),o.push(`In the app ${Bm(i,r.product_id,e.agent.id)}`),o.push("",`Deeper changes (skills, plugins, environments, its own endpoint): qupai agent edit ${Yr(e)}`),o}function Ac(s){let e=Be(s,"instructions_replace");return e?{mode:"replace",text:e}:{mode:"append",text:Be(s,"instructions_append")}}var Tc={append:4e3,replace:16e3};function _c(s,e,t){let i={...s};return delete i.instructions_off,delete i.instructions_append,delete i.instructions_replace,t?e==="replace"?(i.instructions_replace=t,{cust:i,done:"your instructions stand in place of its own"}):(i.instructions_append=t,{cust:i,done:"your instructions follow its own"}):{cust:i,done:"it runs with its own instructions"}}function Ic(s,e){let t=[];for(let n of e)for(let r of n.tiers??[])t.includes(r)||t.push(r);return(s.models?.allowed?.length?s.models.allowed:t).map(n=>({tier:n,models:e.filter(r=>(r.tiers??[]).includes(n))}))}function Pc(s){let e=s.price&&(!s.price.currency||s.price.currency==="CNY")?`, ${re(s.price.input_per_mtok??0)} in / ${re(s.price.output_per_mtok??0)} out per M tokens`:"";return`${s.display_name||s.id}${s.display_name?` (${s.id})`:""}${e}`}function Rc(s,e,t){let i={...s};return t?(i.default_tier=t,delete i.custom_provider_id,delete i.custom_model,{cust:i,done:`its model is tier ${t}`}):(delete i.default_tier,{cust:i,done:`its model is its default${e.models?.default?` (tier ${e.models.default})`:""}`})}var Mc=s=>Be(s,"default_tier");var Zr=s=>zi(s,"/agent-settings",{facet:"mcp"});function mn(s){return s.status==="needs_authorization"?"waiting for authorization":s.status}function Ec(s){let e=s.last_check_at?` \xB7 checked ${X(s.last_check_at)}${s.last_check_ok===!1?`: ${xe(s.last_check_detail||"failed",40)}`:""}`:"",t=s.plugin?` \xB7 from plugin ${s.plugin.name}`:"";return`${mn(s)} \xB7 ${s.auth_kind==="none"?"no sign-in":s.auth_kind} \xB7 ${Ne((s.tools??[]).length,"tool")}${e}${t} \xB7 ${s.url}`}function eo(s){let e=(s.days??[]).join(", "),t;switch(s.type){case"daily":t=`daily at ${s.time}`;break;case"weekdays":t=`weekdays at ${s.time}`;break;case"weekly":t=`every ${e} at ${s.time}`;break;case"hourly":t=`every ${s.interval_hours??1} hours from ${s.time}${e?` on ${e}`:""}`;break;case"once":t=`once, on ${s.date??"?"} at ${s.time}`;break;default:t=`${s.type} at ${s.time}`}return`${t} (${s.tz})`}function to(s){return s.status==="auto_paused"?`paused after ${Ne(s.consecutive_failures??0,"failure")} in a row`:s.status}function io(s){return s.status==="active"&&s.next_run_at?`; next run ${X(s.next_run_at)}`:""}var fn=(s,e)=>zi(s,`/goals/${encodeURIComponent(e)}`),Lc=s=>s.status==="done"||s.status==="halted";function Vi(s){let e=s.status.replaceAll("_"," ");return s.end_reason?`${e} (${s.end_reason.replaceAll("_"," ")})`:e}function Oc(s,e){let t=[`Goal ${s.title} (${s.id})`,`Status ${Vi(s)}`,`Objective ${s.objective}`,`Spent ${re(s.usage.spend_ucny)} of ${re(s.limits.spend_ucny)}`,`Time ${xc(s.usage.seconds)} of ${xc(s.limits.time_seconds)}`,`Rounds ${s.usage.rounds} of ${s.limits.rounds??100}`,`Hardware jobs ${s.usage.hardware_jobs} of ${s.limits.hardware_jobs??0}`];if(s.conclusion&&t.push(`Conclusion ${s.conclusion}`),t.push(`Conversation ${Om(e,s.thread_id)}`,`In the app ${fn(e,s.id)}`),s.status==="awaiting_approval"&&t.push("",`It waits for your approval. Approve it in the app, where you see what it may spend: ${fn(e,s.id)}`),s.directives?.length){t.push("","Directives (every later round carries them)");for(let i of s.directives)t.push(` ${xe(i.text,200)}`)}if(s.rounds?.length){t.push("","Rounds");for(let i of s.rounds.slice(-10))t.push(` ${String(i.n).padStart(3)} ${i.reason}${i.stage?` (${i.stage})`:""} ${i.status} ${X(i.created_at)}`)}return t}var so=(s,e)=>zi(s,`/workspaces/${encodeURIComponent(e)}`);function no(s){return s.status==="open"&&s.expires_at?`open, until ${X(s.expires_at)}`:s.status}function qc(s){return[no(s),`image ${s.image_id}`,s.has_snapshot?"saved state":"",s.subsystem?`kept for ${s.subsystem}${s.key?` ${s.key}`:""}`:"",s.last_error?`last error: ${xe(s.last_error,60)}`:""].filter(Boolean).join(" \xB7 ")}var Fm=5*6e4,Wm=3*6e4,Fe={width:"90%",minWidth:40,maxHeight:"80%"},Um={width:"70%",minWidth:40},Km={width:70,minWidth:30},he=s=>s instanceof Error?s.message:String(s),ie=(s,...e)=>s instanceof D&&e.includes(s.status),Ie=s=>s.detail.replace(/\.$/,""),Dc=s=>new Promise(e=>setTimeout(e,s)),gn=class{h;waiting=new Set;constructor(e){this.h=e}back(e,t,i,n="muted"){i!==void 0&&t.say(i,n),this.h.show(e,t,Fe)}tell(e,t,i="muted"){this.h.showing(e)?e.say(t,i):this.h.say(t,i),this.h.render()}failed(e,t){this.tell(e,he(t),"failed")}ask(e,t,i,n,r,o){let a=new bt(this.h.paint,i,n,r);a.onCancel=()=>this.back(e,t,"nothing was changed"),a.onAnswer=l=>o(l,a),this.h.show(`${e}-ask`,a,Um)}confirm(e,t,i,n){let r=new Ye(this.h.paint,i);r.onAnswer=o=>{this.back(e,t,o?void 0:"nothing was changed"),o&&this.h.track(n())},this.h.show(`${e}-confirm`,r,Km)}panel(e,t,i,n){let r=new Qt(this.h.paint,i,()=>n);r.maxRows=()=>Math.max(8,Math.floor(this.h.tui.terminal.rows*.85)),r.onClose=()=>this.back(e,t),this.h.show(`${e}-panel`,r,{width:"85%",minWidth:40,maxHeight:"85%"})}async agents(e){let t=this.h.dir();if(!t){this.h.say(this.h.loading()?"still asking the platform which agents you have":"the platform did not say which agents you have","needs");return}let i=kc(t),n=pt(t),r=u=>le(u.product.product_id,u.agent.id),o=this.h.agent(),a=o?le(o.productId,o.agentId):"",l=i.map(u=>{let d=n.find(f=>f.from==="product"&&le(f.productId,f.agentId)===r(u)),p=[r(u)===a?"in use":"",u.own?`yours, built on ${U(u.base.name,u.base.id)}`:u.base.kind??"general",U(u.product.name,u.product.product_id),d?.isDefault?"organization default":""];return{value:r(u),label:`${G(u)}${u.own?" (yours)":""}`,description:p.filter(Boolean).join(" \xB7 ")}}),c=new te(this.h.paint,"Your agents",l,{keys:["i","e","m","n","r","d"],footer:"Enter use \xB7 i show \xB7 e instructions \xB7 m model \xB7 n new \xB7 r rename \xB7 d delete \xB7 Esc",empty:"no agent is offered to you here",selected:l.findIndex(u=>u.value===(e?.select??a))});e&&c.say(e.text,e.tone);let h=u=>i.find(d=>r(d)===u);c.onCancel=()=>this.h.hide(),c.onPick=u=>{let d=h(u);if(!d)return;let p=n.find(f=>f.from==="product"&&le(f.productId,f.agentId)===u);if(p){this.h.hide(),this.h.useAgent(p);return}t.given&&!d.own?c.say(`you were given agents of your own: new conversations go to those; n makes one built on ${G(d)}`,"needs"):c.say(`${G(d)} is not offered for new conversations here: the tools it needs are not run here`,"needs"),this.h.render()},c.onKey=(u,d)=>{let p=h(d);p&&(u==="i"?this.h.track(this.showAgent(t,p,c)):u==="e"?this.h.track(this.editInstructions(t,p,c)):u==="m"?this.h.track(this.chooseModel(t,p,c)):u==="n"?this.newAgent(p,c):u==="r"?this.renameAgent(p,c):u==="d"&&this.deleteAgent(p,c),this.h.render())},this.h.show("agents",c,Fe)}async customization(e,t){try{return await this.h.client.customization(e.product.product_id,e.agent.id)}catch(i){this.tell(t,ie(i,404)?`${G(e)} is not there for you any more`:he(i),"failed");return}}async showAgent(e,t,i){let n=await this.customization(t,i);n&&this.panel("agents",i,G(t),$c(e,t,n,this.h.web))}async editInstructions(e,t,i){let n=G(t),r=await this.customization(t,i);if(!r)return;let{mode:o,text:a}=Ac(r),l=o==="replace"?"instructions.replace":"instructions.append";if(!Xr(e,t,l)){this.tell(i,Jr(t,o==="replace"?"replace its instructions":"add instructions",l),"needs");return}let c=Tc[o],h=o==="replace"?`Your instructions stand in place of ${n}'s own, at most ${c} bytes. Saving it empty goes back to its own.`:`Your instructions follow ${n}'s own${t.base.instructions_private?" (which its package keeps private)":""}, at most ${c} bytes. Saving it empty leaves its own alone. qupai agent edit ${Yr(t)} -instructions FILE -replace puts yours in their place.`,u=new un(this.h.tui,this.h.paint,`Your instructions for ${n}`,h,a);u.requestRender=()=>this.h.render(),u.onCancel=()=>this.back("agents",i,"nothing was changed"),u.onSave=d=>this.h.track((async()=>{let p=d.trim(),f=Buffer.byteLength(p);if(f>c)return`your instructions are ${f} bytes: at most ${c} here`;let m=_c(r,o,p);try{await this.h.client.putCustomization(t.product.product_id,t.agent.id,m.cust)}catch(b){return ie(b,400)?`the platform did not take the change: ${Ie(b)}`:he(b)}this.back("agents",i,`Saved ${n}: ${m.done}.`)})()),this.h.show("agent-instructions",u,{width:"90%",minWidth:40,maxHeight:"90%"})}async chooseModel(e,t,i){let n=G(t);if(!Xr(e,t,"models.default")){this.tell(i,Jr(t,"choose its model","models.default"),"needs");return}let r=await this.customization(t,i);if(!r)return;let o;try{o=await this.h.client.models()}catch(d){this.failed(i,d);return}let a=Ic(t.base,o);if(!a.length){this.tell(i,"no models are offered to your organization here","needs");return}let l=Mc(r),c=t.base.models?.default,h=[{value:"",label:`its default${c?` (tier ${c})`:""}`,description:l?"":"in use"},...a.map(d=>({value:d.tier,label:`tier ${d.tier}`,description:`${d.tier===l?"in use \xB7 ":""}${d.models.length?d.models.map(Pc).join("; "):"no model of your organization's is in this tier"}`}))],u=new gt(this.h.paint,`The model of ${n}`,h,{selected:h.findIndex(d=>d.value===l)});u.onCancel=()=>this.back("agents",i,"nothing was changed"),u.onPick=d=>{this.h.track((async()=>{let p=Rc(r,t.base,d);try{await this.h.client.putCustomization(t.product.product_id,t.agent.id,p.cust)}catch(f){this.back("agents",i,ie(f,400)?`the platform did not take the change to ${n}: ${Ie(f)}`:he(f),"failed");return}this.back("agents",i,`Saved ${n}: ${p.done}.`)})())},this.h.show("agent-model",u,Fe)}newAgent(e,t){let i=`${e.product.product_id}/${e.base.id}`;this.ask("agents",t,"A new agent of yours",`It is built on ${i}${e.own?` (as ${G(e)} is), without ${G(e)}'s changes`:""}; change it here or with qupai agent edit. Its name (at most 80 characters):`,"",(n,r)=>{let o=n.trim();if(!o||[...o].length>80){r.refuse("a name is 1 to 80 characters"),this.h.render();return}this.h.track((async()=>{let a;try{a=await this.h.client.createMyAgent(e.product.product_id,e.agent.id,o)}catch(l){r.refuse(ie(l,409)?`the platform made no agent: ${Ie(l)} (d deletes one of yours)`:he(l)),this.h.render();return}await this.h.reloadAgents().catch(()=>{}),await this.agents({text:`Created your agent "${a.name}" (${a.id}), built on ${a.product_id}/${a.base_agent_id}. Enter uses it.`,select:le(a.product_id,a.id)})})())})}renameAgent(e,t){if(!e.own){t.say(`${G(e)} is its product's: only your own agents are renamed (n makes one of yours)`,"needs");return}this.ask("agents",t,`Rename ${G(e)}`,"Its new name (at most 80 characters):",G(e),(i,n)=>{let r=i.trim();if(!r||[...r].length>80){n.refuse("a name is 1 to 80 characters"),this.h.render();return}this.h.track((async()=>{try{await this.h.client.renameMyAgent(e.agent.id,r)}catch(o){n.refuse(ie(o,404)?`${G(e)} is not there any more`:he(o)),this.h.render();return}await this.h.reloadAgents().catch(()=>{}),await this.agents({text:`Renamed it "${r}".`,select:le(e.product.product_id,e.agent.id)})})())})}deleteAgent(e,t){if(!e.own){t.say(`${G(e)} is its product's: only your own agents are deleted`,"needs");return}let i=G(e);this.confirm("agents",t,`Delete your agent "${i}" (${e.agent.id}) and its customization? Its conversations stay readable but take no new messages.`,async()=>{try{await this.h.client.deleteMyAgent(e.agent.id)}catch(n){this.failed(t,ie(n,404)?new Error(`${i} is not there any more`):n);return}await this.h.reloadAgents().catch(()=>{}),await this.agents({text:`Deleted your agent "${i}".`})})}async knowledge(){let e;try{e=await this.h.client.knowledgeBases()}catch(o){this.h.fail(o);return}let t=()=>e.map(o=>({value:o.id,label:o.name,description:`${Ne(o.document_count,"document")} \xB7 updated ${X(o.updated_at)}${o.description?` \xB7 ${xe(o.description,50)}`:""}`})),i=new te(this.h.paint,"Your knowledge bases",t(),{keys:["a","s","d"],free:["n"],footer:"Enter its documents \xB7 a add a file \xB7 s search \xB7 n new \xB7 d delete \xB7 Esc close",empty:"no knowledge bases yet: n makes one"}),n=async o=>{e=await this.h.client.knowledgeBases(),i.setItems(t(),o)},r=o=>e.find(a=>a.id===o);i.onCancel=()=>this.h.hide(),i.onPick=o=>{let a=r(o);a&&this.h.track(this.documents(a,i))},i.onKey=(o,a)=>{if(o==="n"){this.newKnowledgeBase(i,n);return}let l=r(a);l&&(o==="a"?this.addDocument(l,i,n):o==="s"?this.search(l,i):o==="d"&&this.confirm("kb",i,`Delete the knowledge base "${l.name}" with its ${Ne(l.document_count,"document")}? It cannot be undone.`,async()=>{try{await this.h.client.deleteKnowledgeBase(l.id),await n()}catch(c){this.failed(i,c);return}this.tell(i,`Deleted the knowledge base "${l.name}".`)}),this.h.render())},this.h.show("kb",i,Fe)}async documents(e,t){let i;try{i=await this.h.client.knowledgeDocuments(e.id)}catch(r){this.failed(t,r);return}let n=new te(this.h.paint,`${e.name}: documents`,i.map(r=>({value:r.id,label:r.name,description:`${ce(r.size_bytes)} \xB7 ${Ne(r.chunk_count,"passage")} \xB7 ${r.ingested_via==="agent"?"an agent wrote it":"uploaded"} \xB7 ${X(r.updated_at)}`})),{footer:"Esc back to your knowledge bases",empty:"no documents yet: a adds a file"});n.onCancel=()=>this.back("kb",t),n.onPick=()=>{n.say(`only its text passages are kept; qupai kb rm "${e.name}" <document> removes one`),this.h.render()},this.h.show("kb-docs",n,Fe)}addDocument(e,t,i){this.ask("kb",t,`Add a file to ${e.name}`,`A PDF, docx, txt or md file; only its text passages are kept, and a document of the same name is replaced. Its path, relative to ${this.h.shown(this.h.cwd)||"this directory"}:`,"",(n,r)=>{let o=n.trim();if(!o){r.refuse("type the file's path, or Esc"),this.h.render();return}let a=Gt(o,this.h.cwd);try{if(!Nm(a).isFile())throw new Error("not a file")}catch{r.refuse(`${this.h.shown(a)} is not a file here`),this.h.render();return}this.back("kb",t,`adding ${this.h.shown(a)} to ${e.name}\u2026`),this.h.track((async()=>{try{let l=await this.h.client.addKnowledgeDocument(e.id,a);await i(e.id),this.tell(t,`${l.document.name}: ${l.replaced?"replaced the document of the same name":"added"}, ${Ne(l.document.chunk_count,"passage")}.`)}catch(l){this.tell(t,ie(l,400,409)?`${this.h.shown(a)} was not added: ${Ie(l)}`:he(l),"failed")}})())})}search(e,t){this.ask("kb",t,`Search ${e.name}`,"The passages your agents would find (kb_search), best first. Search for:","",(i,n)=>{let r=i.trim();if(!r){n.refuse("type what to search for, or Esc"),this.h.render();return}this.h.track((async()=>{let o;try{o=await this.h.client.searchKnowledgeBase(e.id,r,5)}catch(l){n.refuse(he(l)),this.h.render();return}if(!o.length){this.back("kb",t,`nothing in ${e.name} matches "${r}"`,"needs");return}let a=o.flatMap((l,c)=>[...c?[""]:[],`${c+1}. ${l.document_name}, passage ${l.chunk_index} (score ${l.score.toFixed(3)})`,...l.text.trim().split(`
|
|
118
|
+
`).map(h=>` ${h}`)]);this.panel("kb",t,`${e.name}: "${xe(r,40)}"`,a)})())})}newKnowledgeBase(e,t){this.ask("kb",e,"A new knowledge base","Its name (at most 100 characters; each of yours has its own):","",(i,n)=>{let r=i.trim();if(!r||[...r].length>100){n.refuse("a name is 1 to 100 characters"),this.h.render();return}this.h.track((async()=>{let o;try{o=await this.h.client.createKnowledgeBase(r)}catch(a){n.refuse(ie(a,409)?`the platform made no knowledge base: ${Ie(a)} (a name is used once; you keep at most 50)`:he(a)),this.h.render();return}await t(o.id).catch(()=>{}),this.back("kb",e,`Created the knowledge base "${o.name}": a adds files to it.`)})())})}async connections(){let e;try{e=await this.h.client.connections()}catch(l){this.h.fail(l);return}let t=l=>l.display_name||l.name,i=()=>e.map(l=>({value:l.id,label:t(l),description:Ec(l)})),n=new te(this.h.paint,"Your connections",i(),{keys:["t","o","x","d"],footer:"Enter its tools \xB7 t test \xB7 o authorize \xB7 x switch on or off \xB7 d remove \xB7 Esc",empty:"no connections yet"});n.say("Adding one: qupai connection add <name> <url> (it asks for the server's secret where it is not shown)");let r=async()=>{e=await this.h.client.connections(),n.setItems(i())},o=l=>{e=e.map(c=>c.id===l.id?{...c,...l}:c),n.setItems(i())},a=l=>e.find(c=>c.id===l);n.onCancel=()=>this.h.hide(),n.onPick=l=>{let c=a(l);if(!c)return;let h=[`Connection ${t(c)} (${c.name}, ${c.id})`,`Address ${c.url}`,`Signs in by ${c.auth_kind==="none"?"nothing (open)":c.auth_kind}`,`Status ${mn(c)}`,...c.last_check_at?[`Last check ${X(c.last_check_at)}: ${c.last_check_ok?"answered":`failed${c.last_check_detail?` (${c.last_check_detail})`:""}`}`]:[],...c.plugin?[`From plugin ${c.plugin.name} (${c.plugin.server})`]:[],`In the app ${Zr(this.h.web)}`,"",(c.tools??[]).length?`Tools: ${(c.tools??[]).join(", ")}`:"No tools known yet: t tests it and lists them."];this.panel("connections",n,t(c),h)},n.onKey=(l,c)=>{let h=a(c);if(!h)return;let u=t(h);if(l==="t")n.say(`testing ${u}\u2026`),this.h.track((async()=>{try{let d=await this.h.client.testConnection(h.id);if(await r().catch(()=>{}),d.ok){let p=d.tools??[];this.tell(n,`${u} answers${d.latency_ms!==void 0?` (${d.latency_ms} ms)`:""}: ${Ne(p.length,"tool")}${p.length?`: ${p.slice(0,8).join(", ")}${p.length>8?", \u2026":""}`:""}`)}else this.tell(n,`${u} does not answer: ${d.detail||"no reason given"}${h.auth_kind==="oauth"?" (o signs in again)":""}`,"failed")}catch(d){this.failed(n,ie(d,404)?new Error(`the connection ${u} is not there any more`):d)}})());else if(l==="o")this.authorize(h,u,n,o);else if(l==="x"){if(h.status==="needs_authorization"){n.say(`${u} waits for authorization: o authorizes it`,"needs"),this.h.render();return}let d=h.status==="disabled";this.h.track(this.h.client.setConnectionEnabled(h.id,d).then(p=>{o(p),this.tell(n,`${u} is ${mn({...h,...p})}.`)},p=>this.failed(n,p)))}else l==="d"&&this.confirm("connections",n,`Remove the connection ${u} (${h.url}) and its secret? Agents lose its tools.`,async()=>{try{await this.h.client.deleteConnection(h.id),await r()}catch(d){this.failed(n,d);return}this.tell(n,`Removed the connection ${u}.`)});this.h.render()},this.h.show("connections",n,Fe)}authorize(e,t,i,n){if(e.auth_kind!=="oauth"){i.say(`${t} signs in by ${e.auth_kind==="none"?"nothing":e.auth_kind}, not OAuth: there is nothing to authorize (t tests it)`,"needs");return}if(this.waiting.has(e.id)){i.say(`already waiting for you to authorize ${t} in the browser`,"needs");return}this.waiting.add(e.id),this.h.track((async()=>{try{let r;try{r=await this.h.client.authorizeConnection(e.id,Zr(this.h.web))}catch(l){this.tell(i,ie(l,400)?`the platform could not start the authorization: ${Ie(l)}`:he(l),"failed");return}let o=this.h.openBrowser(r);this.tell(i,`${o?"The browser opened":"Open this in your browser"}: authorize ${t} there, then come back (the app waits up to 3 minutes). ${r}`,"needs");let a=Date.now()+Wm;for(;!this.h.stopped()&&Date.now()<a;){await Dc(this.h.pollMs.authorize);let l;try{l=await this.h.client.connection(e.id)}catch{continue}if(l.status==="active"){n(l),this.tell(i,`${t} is authorized.`);return}}this.h.stopped()||this.tell(i,`${t} is not authorized yet: finish in the browser, then t tests it`,"needs")}finally{this.waiting.delete(e.id)}})())}async schedules(){let e;try{e=await this.h.client.schedules()}catch(r){this.h.fail(r);return}let t=()=>e.map(r=>({value:r.id,label:r.name,description:`${to(r)}${io(r)} \xB7 ${eo(r.recurrence)}${r.last_run_at?` \xB7 last run ${X(r.last_run_at)}${r.last_run_status?` ${r.last_run_status}`:""}`:""}`})),i=new te(this.h.paint,"Your schedules",t(),{keys:["p","r","d"],footer:"Enter open its conversation \xB7 p pause or resume \xB7 r run now \xB7 d delete \xB7 Esc close",empty:"no schedules: qupai schedule new makes one"}),n=r=>e.find(o=>o.id===r);i.onCancel=()=>this.h.hide(),i.onPick=r=>{let o=n(r);o&&(this.h.hide(),this.h.track(this.h.openThread(o.thread_id)))},i.onKey=(r,o)=>{let a=n(o);if(a){if(r==="p"){if(a.status==="finished"){i.say(`"${a.name}" has finished (it ran once): qupai schedule new makes another`,"needs"),this.h.render();return}let l=a.status!=="active";this.h.track(this.h.client.setScheduleEnabled(a.id,l).then(c=>{e=e.map(u=>u.id===a.id?{...u,...c}:u),i.setItems(t());let h=n(a.id);this.tell(i,`"${a.name}" is ${to(h)}${io(h)}.`)},c=>this.tell(i,ie(c,400)?`the platform did not ${l?"resume":"pause"} "${a.name}": ${Ie(c)}`:he(c),"failed")))}else r==="r"?this.h.track(this.h.client.runScheduleNow(a.id).then(l=>this.tell(i,`Started a run of "${a.name}" (${l.status}) on its conversation: Enter opens it.`),l=>this.failed(i,l))):r==="d"&&this.confirm("schedules",i,`Delete the schedule "${a.name}" (${eo(a.recurrence)})? Its conversation stays.`,async()=>{try{await this.h.client.deleteSchedule(a.id)}catch(l){this.failed(i,l);return}e=e.filter(l=>l.id!==a.id),i.setItems(t()),this.tell(i,`Deleted the schedule "${a.name}".`)});this.h.render()}},this.h.show("schedules",i,Fe)}async goals(){let e;try{e=await this.h.client.goals()}catch(l){this.h.fail(l);return}let t=()=>e.map(l=>({value:l.id,label:l.title||l.id,description:`${Vi(l)}${l.status==="awaiting_approval"?": approve it in the app":""} \xB7 spent ${re(l.usage.spend_ucny)} of ${re(l.limits.spend_ucny)} \xB7 ${X(l.created_at)}`})),i=new te(this.h.paint,"Your goals, newest first",t(),{keys:["p","s","w"],footer:"Enter show it \xB7 p pause or resume \xB7 s stop \xB7 w steer \xB7 Esc close",empty:"no goals: qupai goal new starts one (you approve it in the app)"}),n=e.filter(l=>l.status==="awaiting_approval").length;n&&i.say(`${Ne(n,"goal")} ${n===1?"waits":"wait"} for your approval: approve in the app (Enter shows its link); this app never approves a goal`,"needs");let r=l=>e.find(c=>c.id===l),o=l=>{e=e.map(c=>c.id===l.id?{...c,...l}:c),i.setItems(t())},a=(l,c)=>this.h.track(this.h.client.actOnGoal(l.id,c).then(h=>{o(h),this.tell(i,`The goal "${l.title}" is ${Vi({...l,...h})}.`)},h=>this.tell(i,ie(h,409)?`not possible now: ${Ie(h)}`:he(h),"failed")));i.onCancel=()=>this.h.hide(),i.onPick=l=>{let c=r(l);c&&this.h.track(this.h.client.goal(c.id).then(h=>this.panel("goals",i,c.title||c.id,Oc(h,this.h.web)),h=>this.failed(i,h)))},i.onKey=(l,c)=>{let h=r(c);if(!h)return;let u=Lc(h),d=`"${h.title}" waits for your approval: approve it in the app, ${fn(this.h.web,h.id)}`;l==="p"?h.status==="running"?a(h,"pause"):h.status==="paused"||h.status==="stalled"?a(h,"resume"):i.say(h.status==="awaiting_approval"?d:u?`"${h.title}" has ended`:`"${h.title}" is ${Vi(h)}: nothing to pause`,"needs"):l==="s"?u?i.say(`"${h.title}" has ended`,"needs"):this.confirm("goals",i,`Stop the goal "${h.title}" now? Its live round and jobs are cancelled, with no closing round.`,async()=>{await a(h,"halt")}):l==="w"&&(u?i.say(`"${h.title}" has ended: it takes no directives`,"needs"):this.steer(h,i)),this.h.render()},this.h.show("goals",i,Fe)}steer(e,t){this.ask("goals",t,`Steer ${e.title}`,"A directive every later round carries (at most 2000 characters):","",(i,n)=>{let r=i.trim();if(!r||[...r].length>2e3){n.refuse("a directive is 1 to 2000 characters"),this.h.render();return}this.h.track(this.h.client.steerGoal(e.id,r).then(o=>this.back("goals",t,`Every later round of "${e.title}" carries it (directive ${o.id}; qupai goal retire ${e.id} ${o.id} takes it back).`),o=>{n.refuse(ie(o,409)?`"${e.title}" has ended: it takes no directives`:he(o)),this.h.render()}))})}async workspaces(){let e;try{e=await this.h.client.workspaces()}catch(o){this.h.fail(o);return}let t=()=>e.map(o=>({value:o.id,label:o.name,description:qc(o)})),i=new te(this.h.paint,"Your workspaces",t(),{keys:["s","o","d"],footer:"Enter its page \xB7 s start or stop \xB7 o open in the browser \xB7 d delete \xB7 Esc close",empty:"no workspaces: qupai workspace new makes one"}),n=o=>e.find(a=>a.id===o),r=o=>{e=e.map(a=>a.id===o.id?o:a),i.setItems(t())};i.onCancel=()=>this.h.hide(),i.onPick=o=>{let a=n(o);a&&(i.say(`"${a.name}" in the app: ${so(this.h.web,a.id)} (o opens it)`),this.h.render())},i.onKey=(o,a)=>{let l=n(a);if(l){if(o==="s")this.startStop(l,i,r);else if(o==="o"){let c=so(this.h.web,l.id);i.say(this.h.openBrowser(c)?`Opened "${l.name}" in the app: ${c}`:`The browser did not open: open ${c}`)}else o==="d"&&this.confirm("workspaces",i,`Delete the workspace "${l.name}" with its sandbox and saved state? It cannot be undone.`,async()=>{try{await this.h.client.deleteWorkspace(l.id)}catch(c){this.tell(i,this.workspaceRefusal(c,l),"failed");return}e=e.filter(c=>c.id!==l.id),i.setItems(t()),this.tell(i,`Deleted the workspace "${l.name}".`)});this.h.render()}},this.h.show("workspaces",i,Fe)}workspaceRefusal(e,t){return ie(e,404)?`the workspace "${t.name}" is not there any more`:ie(e,409,400)?`not possible now for "${t.name}": ${Ie(e)}`:ie(e,503)?`the platform's sandbox service does not answer: ${Ie(e)}`:he(e)}startStop(e,t,i){if(this.waiting.has(e.id)){t.say(`already waiting for "${e.name}"`,"needs");return}this.waiting.add(e.id),this.h.track((async()=>{try{let n=e,r;e.status==="idle"?(r="open",t.say(`starting "${e.name}"\u2026`),this.h.render(),n=await this.h.client.openWorkspace(e.id)):e.status==="open"?(r="idle",t.say(`saving and stopping "${e.name}"\u2026`),this.h.render(),n=await this.h.client.closeWorkspace(e.id)):(r=e.status==="starting"?"open":"idle",t.say(`"${e.name}" is ${e.status}: waiting for it\u2026`),this.h.render()),i(n);let o=Date.now()+Fm;for(;n.status!==r;){if(this.h.stopped())return;if(n.last_error&&n.status==="idle"&&r==="open"){this.tell(t,`"${n.name}" did not start: ${n.last_error}`,"failed");return}if(Date.now()>o){this.tell(t,`"${n.name}" is still ${n.status} after 5 minutes: s waits for it again`,"needs");return}await Dc(this.h.pollMs.workspace),n=await this.h.client.workspace(e.id),i(n)}this.tell(t,`"${n.name}" is ${no(n)}${r==="open"?": o opens it":", its state saved"}.`)}catch(n){this.tell(t,this.workspaceRefusal(n,e),"failed")}finally{this.waiting.delete(e.id)}})())}};var jm=["project","calibration"],ro=[{name:"new",description:"a new conversation with the agent in use"},{name:"agent",description:"choose an agent: your products' agents and your labs' own"},{name:"lab",description:"your labs: talk with a lab's agent, its status, ask for access"},{name:"threads",description:"continue one of your threads, newest first"},{name:"project",description:"your projects: start a conversation in one, save its files"},{name:"attach",description:"attach a file to your next message (/attach -clear removes them)"},{name:"files",description:"this conversation's files: save one here"},{name:"artifacts",description:"this conversation's artifacts: save one to a file"},{name:"notifications",description:"your notifications, newest first: open one, mark them read"},{name:"balance",description:"your balance and the last days' usage"},{name:"agents",description:"your agents: use one, its instructions and model, your own"},{name:"kb",description:"your knowledge bases: documents, add a file, search"},{name:"connections",description:"your MCP connections: test, authorize, switch on or off"},{name:"schedules",description:"your schedules: pause or resume, run now, delete"},{name:"goals",description:"your goals: show, pause or resume, stop, steer"},{name:"workspaces",description:"your workspaces: start or stop, open in the browser"},{name:"status",description:"who is signed in, where, and the agent in use"},{name:"help",description:"the commands and keys"},{name:"update",description:"install the newest qupai (qupai update) and quit"},{name:"logout",description:"sign out (qupai logout) and quit"},{name:"quit",description:"leave the app"}],Wc=[["Enter","send the message (on an empty line: show a waiting approval again)"],["Shift+Enter","a new line (Alt+Enter or Ctrl+J where Shift+Enter does not reach the app)"],["/","commands, with completion (Tab or Enter)"],["Esc","stop a running turn or hardware run (it asks first); close a list or panel; in a dialog, go back"],["Backspace","on an empty line: remove the last file attached to the next message"],["Tab","on an empty line: move through the tool calls; Enter unfolds one, Esc returns"],["v","on a tool call or a result marked [Run on hardware v]: run it on hardware (a dialog; nothing is sent until you confirm)"],["PgUp PgDn","scroll the conversation (also the mouse wheel and the trackpad)"],["Ctrl+End","back to the newest output"],["A R","in an approval: approve, or reject with an optional comment (Esc closes it unanswered)"],["s r w","in /lab: the lab's status; ask QuPai staff for access (with a note); withdraw that request"],["a","in /notifications: mark them all read (Enter opens one and marks it read)"],["f","in /project: the project's files (Enter saves one, like /files)"],["i e m","in /agents: show it; your instructions for it (Ctrl+S saves them); its model"],["n r d","in /agents: a new agent of yours built on it; rename or delete one of yours"],["a s n d","in /kb: add a file; search; a new knowledge base; delete one"],["t o x d","in /connections: test; authorize (OAuth, in the browser); switch on or off; remove"],["p r d","in /schedules: pause or resume; run now; delete (Enter opens its conversation)"],["p s w","in /goals: pause or resume; stop; steer with a directive (Enter shows it)"],["s o d","in /workspaces: start or stop, waiting for it; open in the browser; delete"],["Ctrl+C","clear the line; on an empty line, quit (Ctrl+D too)"],["?","on an empty line: these keys"]],oo=class{triggerCharacters=["/"];async getSuggestions(e,t,i){if(t!==0)return null;let n=(e[0]??"").slice(0,i),r=/^\s*\/(\S*)$/.exec(n);if(!r)return null;let o=(r[1]??"").toLowerCase(),a=ro.filter(l=>l.name.startsWith(o)).map(l=>({value:l.name,label:`/${l.name}`,description:l.description}));return a.length?{items:a,prefix:`/${r[1]??""}`}:null}applyCompletion(e,t,i,n,r){let o=e[t]??"",a=i-r.length,l=`${o.slice(0,a)}/${n.value}${o.slice(i)}`,c=[...e];return c[t]=l,{lines:c,cursorLine:t,cursorCol:a+n.value.length+1}}},wn=class{tui;editor;notice;opts;client;paint;transcript=new ee;scroll;welcome;me;dir;agent;thread;threadAgent;loading=!0;following;last;answers=[];overlay;devices;runs=[];shownTurns=new Set;generation=0;approval;nav=-1;store;stopped=!1;pending=new Set;attachments=[];place;unread=0;bellOff=!1;bellTimer;update;updateTimer;markTimer;labRequests=new Map;cwd;setup;constructor(e){this.opts=e,this.client=e.client,this.paint=e.paint,this.store=new Js(e.client.signIn.handoff.choice_file),this.cwd=e.cwd??process.cwd(),this.update=e.update??"",this.devices=new tn({platform:e.client,web:e.client.signIn.handoff.web,override:e.devicesUrl});let t=new Ai(e.terminal,!1,void 0,{mouse:!0,scrollToEndIndicator:()=>this.paint.dim(" \u2193 newest ")});this.tui=t,this.welcome=new an(e.paint,()=>this.welcomeInfo(),{image:e.image}),this.transcript.addChild(this.welcome),this.scroll=new lt(this.transcript,{follow:"end",primary:!0,overscroll:"chain",scrollbar:"auto"}),this.notice=new ln(e.paint),this.editor=new st(t,on(e.paint),{paddingX:1,autocompleteMaxVisible:8}),this.editor.setAutocompleteProvider(new oo),this.editor.onSubmit=n=>this.submit(n);let i=new cn(e.paint,()=>({state:this.markState(),agent:this.thread?this.threadAgent:this.place?.agent??this.agent,org:this.orgName(),platform:this.client.server,unread:this.unread,place:this.place?.title,update:this.update||void 0}));t.setLayoutRoot(new xi([{component:this.scroll,basis:0,grow:1,minSize:1},{component:this.notice,basis:"auto"},{component:new hn(e.paint,()=>this.attachments),basis:"auto"},{component:this.editor,basis:"auto",shrink:1,minSize:3},{component:i,basis:"auto"}])),t.setFocus(this.editor),t.addInputListener(n=>this.onKey(n)),this.setup=new gn({paint:e.paint,client:e.client,tui:t,web:e.client.signIn.handoff.web,cwd:this.cwd,pollMs:{workspace:e.workspacePollMs??2e3,authorize:e.authorizePollMs??1500},dir:()=>this.dir,loading:()=>this.loading,agent:()=>this.agent,show:(n,r,o)=>this.showOverlay(n,r,o),hide:()=>this.hideOverlay(),showing:n=>this.overlay?.component===n,say:(n,r)=>this.say(n,r),fail:n=>this.fail(n),track:n=>this.track(n),render:()=>this.render(),stopped:()=>this.stopped,shown:n=>this.shown(n),useAgent:n=>this.useAgent(n),reloadAgents:()=>this.reloadAgents(),openThread:n=>this.openThread(n),openBrowser:e.openBrowser??Gm})}start(){this.tui.start(),this.opts.motion&&this.welcome.draws&&this.drawMark(),this.track(this.load()),this.opts.checkUpdate&&(this.updateTimer=setInterval(()=>this.track(this.readUpdate()),this.opts.updatePollMs??120*6e4),this.updateTimer.unref?.())}drawMark(){let t=0;this.welcome.drawing=0,this.markTimer=setInterval(()=>{t++,t<Ni.length-1?this.welcome.drawing=t:this.loading&&t>=Ni.length-1+8?this.welcome.drawing=t=0:(this.welcome.drawing=void 0,this.loading||(clearInterval(this.markTimer),this.markTimer=void 0)),this.render()},this.opts.motionFrameMs??55),this.markTimer.unref?.()}async readUpdate(){let e=await this.opts.checkUpdate?.()??this.update;return e!==this.update&&(this.update=e,this.render()),e}async updateNow(){if(!this.opts.runCommand)return this.say("qupai update, from your shell, installs the newest qupai","needs");this.say("asking npm for the newest qupai\u2026");let e=await this.readUpdate();if(!this.stopped){if(!e)return this.say("npm has no newer qupai for you (qupai update -check, from your shell, says what it has)");this.quit(0,["update"])}}track(e){let t=e.finally(()=>this.pending.delete(t));return this.pending.add(t),t}async idle(){for(;this.pending.size;)await Promise.allSettled([...this.pending])}render(){this.stopped||this.tui.requestRender()}say(e,t="muted"){this.notice.set(e,t),this.render()}fail(e){let t=e instanceof D||e instanceof dt||e instanceof Error?e.message:String(e);this.say(t,"failed")}orgName(){let e=this.me;if(!e)return;let t=e.tenants?.find(i=>i.id===e.current_tenant_id);return t?.display_name||t?.slug||void 0}welcomeInfo(){let e=this.me;return{who:e?`${e.user.display_name}${e.user.email?` <${e.user.email}>`:""}`:void 0,org:this.orgName(),platform:this.client.server,agent:this.place?.agent??this.agent,place:this.place?.title,loading:this.loading}}markState(){let e=this.following?.answer??this.last;if(!e)return"idle";switch(e.state){case"running":return this.following?"writing":"idle";case"awaiting_approval":return"needs";case"aborted":return"stopped";case"error":return"failed";default:return"idle"}}async load(){try{let[e,t,i,n]=await Promise.all([this.client.me(),this.client.products(),this.client.myAgents(),this.client.labs().catch(()=>[])]);this.me=e,this.dir=Or(t,i,n);let r=this.opts.start??{};if(r.thread){this.loading=!1,await this.openThread(r.thread);return}if(r.lab){let o=Oi(this.dir).find(a=>a.lab===r.lab);o?this.agent=o:this.say(`no lab ${r.lab} offers you its agent: /lab lists those that do`,"failed")}else if(r.product){let o=this.findProductAgent(r.product,r.agent);typeof o=="string"?this.say(o,"failed"):this.agent=o}this.agent||(this.agent=qr(this.dir,this.store.get(this.client.server,e.user.id)),!this.agent&&!this.notice.value&&this.say("no agent is offered to you here: ask your organization's admin which products to enable","needs"))}catch(e){this.fail(e)}finally{this.loading=!1,this.render(),this.startBell()}}findProductAgent(e,t){let i=pt(this.dir).filter(o=>o.from==="product"&&o.productId===e),n=this.dir.products.find(o=>o.product_id===e);return n?n.available?t?i.find(o=>o.agentId===t)??n.agents?.filter(o=>o.id===t).map(o=>({productId:e,agentId:o.id,name:U(o.name,o.id),from:"product",isDefault:!1}))[0]??`${e} has no agent ${t} (its agents: ${(n.agents??[]).map(o=>o.id).join(", ")})`:(i[0]??(n.agents?.[0]&&{productId:e,agentId:n.agents[0].id,name:U(n.agents[0].name,n.agents[0].id),from:"product",isDefault:!1}))||`${e} has no agents`:`${e} is not available to you (no version resolves, or a permission is missing): ask your organization's admin`:`your organization runs no product ${e}: /agent lists what you can ask`}choiceFor(e,t){let i=this.dir?[...pt(this.dir),...Oi(this.dir)].find(n=>n.productId===e&&n.agentId===t):void 0;return i||(t.startsWith("lab:")?{productId:e,agentId:t,name:t,from:"lab",lab:t.slice(4),isDefault:!1}:{productId:e,agentId:t,name:t,from:"product",isDefault:!1})}newConversation(){this.following?.abort.abort(),this.following=void 0,this.closeApproval(),this.thread=void 0,this.threadAgent=void 0,this.place=void 0,this.last=void 0,this.answers=[],this.runs=[],this.shownTurns=new Set,this.generation++,this.nav=-1,this.transcript.clear(),this.transcript.addChild(this.welcome),this.notice.clear(),this.render()}submit(e){let t=e.trim();if(!t){this.approval&&this.following?this.track(this.showApproval(this.approval.part,!0)):this.attachments.length&&this.say("type a message to go with the attached files","needs");return}let i=Ur(t,this.cwd);if(i){this.attach(i);return}if(this.editor.addToHistory(t),t.startsWith("/")){this.command(t);return}if(this.following){this.say("a turn is running: wait for its answer, or press Esc to stop it","needs");return}this.track(this.attachments.length||!this.thread&&this.place?this.send(t):this.ask(t))}async ask(e){if(this.notice.clear(),!this.thread){let i=this.agent;if(!i){this.say(this.loading?"still asking the platform which agents you have: try again in a moment":"no agent to ask: /agent chooses one","needs");return}try{this.thread=await this.client.createThread(i.productId,i.agentId),this.threadAgent=i}catch(n){this.fail(n);return}this.transcript.removeChild(this.welcome)}this.transcript.addChild(new ft(this.paint,e)),this.render();let t;try{t=(await this.client.submitTurn(this.thread.id,e)).id}catch(i){i instanceof D&&i.status===409?this.say("this thread has a turn that has not ended (it may wait for an approval): /threads opens it again","failed"):this.fail(i);return}await this.follow(t,0,qi())}async send(e){this.notice.clear();let t=[...this.attachments],i=this.thread?void 0:this.place,n=this.thread?this.threadAgent:i?.agent??this.agent;if(!this.thread&&!n){this.say(this.loading?"still asking the platform which agents you have: try again in a moment":"no agent to ask: /agent chooses one","needs");return}let r=[];for(let u of t){this.say(`uploading ${u.name} (${ce(u.size)})\u2026`);try{r.push((await this.client.uploadFile(u.path)).id)}catch(d){let p=d instanceof D&&d.status===413?d.message:`uploading ${u.name}: ${d instanceof Error?d.message:String(d)}`;this.say(`${p} (nothing was sent; the files stay attached)`,"failed");return}}this.notice.clear();let o=!1;if(!this.thread){try{this.thread=i?await this.client.createThreadIn(n.productId,n.agentId,e,{app:i.app,key:i.key}):await this.client.createThread(n.productId,n.agentId),this.threadAgent=n,o=!0}catch(u){this.fail(u);return}this.transcript.removeChild(this.welcome)}let a=this.thread;this.attachments=[];let l=new ft(this.paint,e,t.map(u=>u.name));this.transcript.addChild(l),this.render();let c=async u=>{this.attachments=t,o?(await this.client.deleteThread(a.id).catch(()=>{}),this.newConversation(),this.place=i):this.transcript.removeChild(l),this.say(u,"failed")},h;try{h=await this.client.sendMessage(a.id,e,r)}catch(u){await c(u instanceof Error?u.message:String(u));return}if(h.status==="delivered"&&h.turn_id){await this.follow(h.turn_id,0,qi());return}if(h.status==="failed"){await c(`the message started no turn: ${h.error||"the platform did not say why"}`);return}await this.client.withdrawMessage(a.id,h.id).catch(()=>{}),await c("this thread has a turn that has not ended (it may wait for an approval): /threads opens it again")}answerView(e,t){let i=new Fi(this.paint,e,{turnId:t,actions:()=>this.resultActions(),onRun:n=>this.openRun(n,t)});return i.onToggle=()=>this.render(),this.shownTurns.add(t),i}async follow(e,t,i){let n=this.answerView(i,e);this.transcript.addChild(n),this.answers.push(n);let r=new AbortController,o={turnId:e,answer:i,view:n,abort:r};this.following=o,this.last=i,this.render();let a=en(i);a&&this.track(this.showApproval(a));let l=!1;try{for await(let c of this.client.follow(e,t,{signal:r.signal,onRetry:()=>{l=!0,this.say("the connection to the platform was lost: reconnecting\u2026","needs")}})){l&&(l=!1,this.notice.clear());let h=i.state;if(Br(i,c),n.sync(),c.event==="title"&&this.thread&&(this.thread.title=i.title),c.event==="interrupt"&&i.state==="awaiting_approval"){let u=en(i);u&&this.track(this.showApproval(u))}h==="awaiting_approval"&&i.state!=="awaiting_approval"&&this.closeApproval(!0),this.render()}}catch(c){this.fail(c)}finally{this.following===o&&(this.following=void 0),i.state!=="awaiting_approval"&&this.closeApproval(),this.render(),this.track(this.readBell())}}async openThread(e){try{let[t,i]=await Promise.all([this.client.thread(e),this.client.threadTurns(e,20)]);this.newConversation(),this.thread={...t,id:t.id??e},this.threadAgent=this.choiceFor(t.product_id,t.agent_id),this.transcript.removeChild(this.welcome);let n=i.items??[];n.forEach((r,o)=>{let a=r.input??{};a.tool_action?this.transcript.addChild(new Ui(this.paint,"Run on hardware")):a.origin&&a.origin!=="member"?this.transcript.addChild(new ze(this.paint.dim(`\xB7 ${a.text||a.origin}`),0,1)):this.transcript.addChild(new ft(this.paint,a.text??"",(a.attachments??[]).map(u=>u.name)));let l=Nr(r.events??[],r.status);if(o===n.length-1&&(r.status==="running"||r.status==="admitted"||r.status==="awaiting_approval")){let u=this.follow(r.id,r.through_seq??0,l);a.tool_action?this.track(this.watchRun(this.addRun(r.id),u)):this.track(u);return}let h=this.answerView(l,r.id);this.transcript.addChild(h),this.answers.push(h),this.last=l,a.tool_action&&this.track(this.watchRun(this.addRun(r.id)))}),n.length||this.say("this thread has no turns yet: type a message to start one")}catch(t){t instanceof D&&(t.status===404||t.status===400)?this.say(`you have no thread ${e} here: /threads lists yours`,"failed"):this.fail(t)}this.render()}resultActions(){let e=this.thread?this.threadAgent:this.agent;return!e||!this.dir?[]:this.dir.products.find(n=>n.product_id===e.productId)?.agents?.find(n=>n.id===e.agentId)?.result_actions??[]}openRun(e,t,i){let n=this.thread;if(!n)return;if(this.following){this.say("a turn is running in this conversation: wait for it to end, then run the result on hardware","needs");return}let r=this.me,o=new pn(this.paint,{settings:()=>this.client.settings(),providers:()=>this.devices.providers(),credential:a=>this.client.credential(a),saveKey:(a,l)=>r?this.client.saveCredential(a,{tenantId:r.current_tenant_id??"",userId:r.user.id},l):Promise.reject(new Error("the platform has not said who you are yet: try again in a moment")),catalog:(a,l)=>l?this.devices.refreshCatalog(a):this.devices.catalog(a),capabilities:(a,l)=>this.devices.capabilities(a,l),preview:(a,l,c)=>this.client.previewToolAction(n.id,a,{onCompiling:l,signal:c,pollMs:this.opts.previewPollMs}),submit:a=>this.client.submitToolAction(n.id,a)},{offer:e,threadId:n.id,turnId:t,link:`${this.client.signIn.handoff.web}/chat/${n.id}`,rerun:i,guardMs:this.opts.submitGuardMs});o.maxRows=()=>Math.max(10,Math.floor(this.tui.terminal.rows*.92)),o.requestRender=()=>this.render(),o.onWork=a=>this.track(a),o.onClose=()=>{this.overlay?.component===o&&this.hideOverlay()},o.onSubmitted=a=>this.track(this.followRun(a)),this.showOverlay("hardware",o,{width:"90%",minWidth:50,maxHeight:"92%"}),o.start()}get hardwareDialog(){return this.overlay?.kind==="hardware"?this.overlay.component:void 0}addRun(e){let t=new Ki(this.paint,e,`${this.client.signIn.handoff.web}/chat/${this.thread?.id??""}`);return t.onToggle=()=>this.render(),t.canRerun=i=>!!this.rerunOf(i),t.onRerun=i=>{let n=this.rerunOf(i);n&&this.openRun(n.offer,n.turnId,n.rerun)},this.transcript.addChild(t),this.runs.push(t),t}async followRun(e){this.notice.clear(),this.transcript.addChild(new Ui(this.paint,`Run on hardware: ${e.summary}`));let t=this.follow(e.turn.id,0,qi());await this.watchRun(this.addRun(e.turn.id),t)}async watchRun(e,t){let i=this.generation,n=!t;t?.finally(()=>n=!0);let r=!1;for(let o=0;!this.stopped&&i===this.generation;o++){try{let a=await this.client.turnJobs(e.turnId);if(i!==this.generation)return;e.set(a),this.render();let l=a.some(Wi);if(r&&!l&&await this.afterRun(i),r=l,!l&&n&&o>0||!l&&n&&!t)return}catch(a){if(a instanceof D&&(a.status===404||a.status===403))return}await new Promise(a=>setTimeout(a,this.opts.jobPollMs??5e3))}}async afterRun(e){let t=this.thread;if(!(!t||this.following))try{let i=await this.client.threadTurns(t.id,3);if(e!==this.generation||this.following)return;let n=(i.items??[]).at(-1);if(!n||this.shownTurns.has(n.id)||!["running","admitted","awaiting_approval"].includes(n.status))return;let r=n.input??{};this.transcript.addChild(new ze(this.paint.dim(`\xB7 ${r.text||"the run ended: the agent reads its result"}`),0,1)),await this.follow(n.id,n.through_seq??0,Nr(n.events??[],n.status))}catch{}}rerunOf(e){let t=Fl(e.detail);if(!t||!["succeeded","failed","cancelled","lost"].includes(e.status))return null;let i=this.resultActions(),n=i.filter(l=>Ge(l)!==null&&l.submit_tool===e.tool);if(n.length!==1)return null;let r=this.answers.find(l=>l.turnId===t.turnId),o=r?.tools.find(l=>l.part.id===t.toolCallId);if(!r||!o)return null;let a=Ns(o.part,r.answer,i);return!a||a.candidate.kind==="optimization"?null:{offer:a,turnId:t.turnId,rerun:{provider:Ge(n[0]),point:t.point}}}stopRun(e,t){let i=new Ye(this.paint,`Stop this hardware run (${e.summary||e.tool})? A task the provider has already started may still finish there.`);i.onAnswer=n=>{this.hideOverlay(),n&&this.track(this.client.cancelJob(e.id).then(r=>{t.set(t.jobs.map(o=>o.id===r.id?r:o)),this.say("stopping the run\u2026")},r=>this.fail(r)))},this.showOverlay("confirm",i,{width:64,minWidth:30})}async showApproval(e,t=!1){let i=this.following;if(!i||this.approval?.part===e&&!t||(this.approval?.poll&&clearInterval(this.approval.poll),this.approval={part:e,dismissed:!1},t||await new Promise(l=>setTimeout(l,this.opts.approvalGraceMs??1e3)),this.following!==i||i.answer.state!=="awaiting_approval"||en(i.answer)!==e))return;let n;try{let l=await this.client.approvals(i.turnId);if(n=l.find(c=>c.interrupt_seq===e.seq)??l.find(c=>!c.decision),n?.decision)return}catch{}if(this.following!==i||i.answer.state!=="awaiting_approval"||this.overlay?.kind==="approval")return;let r=(this.thread?this.threadAgent:this.agent)?.name??"the agent",o=new dn(this.paint,{agent:r,part:e,labs:this.dir?.labs??[],record:n});o.maxRows=()=>Math.max(8,this.tui.terminal.rows-4),o.onClose=()=>{this.approval&&(this.approval.dismissed=!0),this.hideOverlay(),this.say("the turn waits for your approval: Enter on an empty line shows it again","needs")},o.onAnswer=async l=>{try{await this.client.answerApproval(i.turnId,l)}catch(c){if(c instanceof D&&c.status===409){this.closeApproval(!0);return}throw c}this.closeApproval(),this.say(l.decision==="approve"?"approved: the turn goes on":"rejected: the agent is told","muted")},this.showOverlay("approval",o,{width:"80%",minWidth:40,maxHeight:"90%"});let a=setInterval(()=>{this.client.approvals(i.turnId).then(l=>{l.find(h=>h.interrupt_seq===e.seq)?.decision&&this.overlay?.component===o&&this.closeApproval(!0)},()=>{})},this.opts.approvalPollMs??3e3);a.unref?.(),this.approval.poll=a}closeApproval(e=!1){this.approval?.poll&&clearInterval(this.approval.poll);let t=this.overlay?.kind==="approval";t&&this.hideOverlay(),e&&(t||this.approval)&&this.say("the approval was answered: the turn goes on"),this.approval=void 0}showOverlay(e,t,i={width:"70%",minWidth:40,maxHeight:"80%"}){this.hideOverlay();let n=this.tui.showOverlay(t,i);this.overlay={handle:n,kind:e,component:t},this.render()}hideOverlay(){this.overlay&&(this.overlay.handle.hide(),this.overlay=void 0,this.tui.setFocus(this.editor),this.render())}get overlayKind(){return this.overlay?.kind}command(e){let[t=""]=e.slice(1).split(/\s+/),i=t.toLowerCase();switch(this.notice.clear(),i){case"new":this.newConversation();return;case"agent":this.pickAgent();return;case"lab":this.track(this.labList());return;case"threads":this.track(this.pickThread());return;case"project":case"projects":this.track(this.projectList());return;case"attach":this.attachCommand(e.slice(1+t.length));return;case"files":this.track(this.conversationFiles());return;case"artifacts":this.track(this.artifactList());return;case"notifications":this.track(this.notificationList());return;case"balance":this.track(this.balance());return;case"agents":this.track(this.setup.agents());return;case"kb":this.track(this.setup.knowledge());return;case"connections":this.track(this.setup.connections());return;case"schedules":this.track(this.setup.schedules());return;case"goals":this.track(this.setup.goals());return;case"workspaces":this.track(this.setup.workspaces());return;case"status":this.showOverlay("status",this.panel("Status",()=>this.statusLines()));return;case"help":this.showOverlay("help",this.panel("Help",()=>this.helpLines(),.85),{width:"90%",minWidth:40,maxHeight:"85%"});return;case"update":this.track(this.updateNow());return;case"logout":this.quit(0,["logout"]);return;case"quit":case"exit":this.quit(0);return}let n=Qm(i,ro.map(r=>r.name));this.say(`unknown command /${i}${n?`; did you mean /${n}?`:""} (/help lists them)`,"failed")}panel(e,t,i=.8){let n=new Qt(this.paint,e,t);return n.onClose=()=>this.hideOverlay(),n.maxRows=()=>Math.max(8,Math.floor(this.tui.terminal.rows*i)),n}statusLines(){let e=this.client.signIn.handoff,t={browser_key:"personal API key from the browser sign-in",pasted_key:"personal API key you pasted",env_key:"personal API key in QUPAI_API_KEY",device_sign_in:"sign-in at the identity provider"},i=this.me;return[`Platform ${e.server}`,...e.web&&e.web!==e.server?[`Web app ${e.web}`]:[],`Signed in as ${i?`${i.user.display_name}${i.user.email?` <${i.user.email}>`:""}`:"(asking)"}`,`Organization ${this.orgName()??"(none)"}`,`Sign-in ${t[e.kind]??(e.kind||"a key")}${e.renews?", renews itself":""}`,`Agent ${mt(this.agent)}`,...this.place?[`Project ${this.place.title} (${this.place.key})`]:[],...this.unread?[`Notifications ${this.unread} unread (/notifications)`]:[],...this.thread?[`Thread ${this.thread.id}${this.thread.title?` (${this.thread.title})`:""}`,` in the app ${e.web}/chat/${this.thread.id}`]:[]]}helpLines(){return["Commands:",...ro.map(e=>` /${e.name.padEnd(15)}${e.description}`),"","Keys:",...Wc.map(([e,t])=>` ${e.padEnd(12)}${t}`),"","Approvals: when a turn waits for one, it opens over the conversation. Only A and R answer it.","Hardware: a result an agent's actions can run on hardware shows [Run on hardware v]. Tab to it and press v (or","click it): choose the provider, the device, the shots and the qubits, read the preview, then Run on hardware.","Files: /attach a path, or drop a file on the terminal (or paste its path): it shows above the composer and goes","with your next message. /files and /artifacts save what the conversation made into this directory.","The bell: the status line counts your unread notifications (read every minute and after each turn).","Credits: /balance shows them; top up in the app (the TUI takes no payments).","What you set up: /agents (e edits your instructions for one in the editor: Enter a new line, Ctrl+S saves), /kb,","/connections, /schedules, /goals and /workspaces. Adding a connection (its secret), a new schedule or goal, and an","agent's skills or environments are the qupai command's (qupai help lists them). A goal is approved in the app only."]}pickAgent(){if(!this.dir){this.say(this.loading?"still asking the platform which agents you have":"the platform did not say which agents you have","needs");return}let e=pt(this.dir),t=this.agent?le(this.agent.productId,this.agent.agentId):"",i=e.map((r,o)=>({value:String(o),label:r.name+(r.isDefault?" (organization default)":""),description:r.from==="lab"?`lab ${r.labName??r.lab}`:`${r.productName??r.productId}${le(r.productId,r.agentId)===t?" \xB7 in use":""}`})),n=new gt(this.paint,"Agent",i,{selected:e.findIndex(r=>le(r.productId,r.agentId)===t),empty:"no agent is offered to you here"});n.onCancel=()=>this.hideOverlay(),n.onPick=r=>{let o=e[Number(r)];this.hideOverlay(),o&&this.useAgent(o)},this.showOverlay("agent",n)}async reloadAgents(){let[e,t]=await Promise.all([this.client.products(),this.client.myAgents()]);this.dir=Or(e,t,this.dir?.labs??[]);let i=pt(this.dir),n=o=>o&&i.find(a=>a.productId===o.productId&&a.agentId===o.agentId);if(this.agent&&this.agent.from==="product"){let o=n(this.agent);if(o)this.agent=o;else{let a=this.agent;this.agent=qr(this.dir,this.me?this.store.get(this.client.server,this.me.user.id):null),this.thread||this.say(`${a.name} is no longer there: new conversations go to ${mt(this.agent)}`,"needs")}}let r=n(this.threadAgent);r&&(this.threadAgent=r),this.render()}useAgent(e){this.agent=e,this.me&&this.store.set(this.client.server,this.me.user.id,ec(e)),(this.thread||this.place)&&this.newConversation(),this.say(`new conversations go to ${mt(e)}`)}shown(e){let t=Vm(this.cwd,e);if(t&&!t.startsWith("..")&&!t.startsWith(Fc))return t;let i=zm();return e.startsWith(i+Fc)?`~${e.slice(i.length)}`:e}attach(e){let t=[];for(let i of e){let n;try{n=Nc(i)}catch{this.say(`${this.shown(i)} is not there: nothing was attached`,"failed");return}if(n.isDirectory()){this.say(`${this.shown(i)} is a folder: attach files`,"failed");return}if(!(this.attachments.some(r=>r.path===i)||t.some(r=>r.path===i))){if(this.attachments.length+t.length>=Fr){this.say(`at most ${Fr} files go with a message`,"failed");break}t.push({path:i,name:bn(i),size:n.size})}}this.attachments=[...this.attachments,...t],t.length&&this.say(`attached ${t.map(i=>`${i.name} (${ce(i.size)})`).join(", ")}: ${t.length===1?"it goes":"they go"} with your next message`),this.render()}attachCommand(e){let t=Wr(e.trim());if(t.length===1&&(t[0]==="-clear"||t[0]==="--clear")){let i=this.attachments.length;this.attachments=[],this.say(i?`removed the ${i===1?"attached file":`${i} attached files`}`:"no files were attached");return}if(!t.length){this.say("/attach <path> attaches a file to your next message (or drop it on the terminal); /attach -clear removes them","needs");return}this.attach(t.map(i=>Gt(i,this.cwd)))}detachLast(){let e=this.attachments.at(-1);e&&(this.attachments=this.attachments.slice(0,-1),this.say(`removed ${e.name}`))}saveFile(e,t,i){let n=()=>this.track((async()=>{this.say(`saving ${i}\u2026`);try{let o=await this.client.download(e,t);this.say(`saved ${i} as ${this.shown(t)} (${ce(o)})`)}catch(o){o instanceof D&&o.status===404?this.say(`${i} is not there any more`,"failed"):this.fail(o)}})());if(!Bc(t)){this.hideOverlay(),n();return}let r=new Ye(this.paint,`${this.shown(t)} is there already. Overwrite it with ${i}?`);r.onAnswer=o=>{this.hideOverlay(),o?n():this.say(`kept ${this.shown(t)}: nothing was saved`)},this.showOverlay("overwrite",r,{width:70,minWidth:30})}showFiles(e,t,i,n){let r=t.files.filter(l=>l.type!=="directory"),o=t.source==="snapshot"?" (from the last snapshot)":"",a=new te(this.paint,`${e}${o}`,r.map(l=>({value:l.path,label:l.path,description:`${ce(l.size)}${l.mtime?` \xB7 ${X(l.mtime)}`:""}`})),{footer:"\u2191\u2193 choose \xB7 Enter save it into this directory \xB7 Esc close",empty:t.source==="none"?n:"no files"});a.onCancel=()=>this.hideOverlay(),a.onPick=l=>this.saveFile(i(l),yn(this.cwd,bn(l)),bn(l)),this.showOverlay("files",a)}async conversationFiles(){let e=this.thread;if(!e){this.say("no conversation yet: its files are listed once it has started (/threads opens one)","needs");return}try{let t=await this.client.threadFiles(e.id);this.showFiles("This conversation's files",t,i=>jl(e.id,i),"the conversation has no sandbox yet")}catch(t){this.fail(t)}}async artifactList(){let e=this.thread;if(!e){this.say("no conversation yet: its artifacts are listed once it has started (/threads opens one)","needs");return}let t;try{t=(await this.client.artifacts()).filter(n=>n.thread_id===e.id)}catch(n){this.fail(n);return}let i=new te(this.paint,"This conversation's artifacts",t.map(n=>({value:n.id,label:n.title||n.id,description:`version ${n.latest_version}${n.entry?` \xB7 ${n.entry.path} ${ce(n.entry.size)}`:""} \xB7 ${X(n.updated_at)}`})),{footer:"\u2191\u2193 choose \xB7 Enter save to a file \xB7 Esc close",empty:"this conversation has made no artifacts"});i.onCancel=()=>this.hideOverlay(),i.onPick=n=>{let r=t.find(o=>o.id===n);r&&this.track(this.saveArtifact(r))},this.showOverlay("artifacts",i)}async saveArtifact(e){let t=e.latest_version,i=e.entry?.path??"";if(!i)try{let a=(await this.client.artifact(e.id)).versions.reduce((l,c)=>!l||c.number>l.number?c:l,void 0);if(!a)throw new Error(`${e.title||e.id} has no version to save`);t=a.number,i=a.entry}catch(o){this.hideOverlay(),this.fail(o);return}let n=ac(e.title,i),r=new bt(this.paint,"Save the artifact",`Save "${e.title||e.id}" (version ${t}, ${bn(i)}) as a file, relative to ${this.shown(this.cwd)||"this directory"}:`,n);r.onCancel=()=>this.hideOverlay(),r.onAnswer=o=>{let a=o.trim();if(!a){r.refuse("type where to save it, or Esc"),this.render();return}let l=Gt(a,this.cwd);try{Nc(l).isDirectory()&&(l=yn(l,n))}catch{}if(!Bc(yn(l,".."))){this.hideOverlay(),this.say(`there is no folder ${this.shown(yn(l,".."))}: nothing was saved`,"failed");return}this.saveFile(Ql(e.id,t,i),l,`"${e.title||e.id}"`)},this.showOverlay("save",r,{width:"70%",minWidth:40})}startBell(){this.stopped||this.bellTimer||(this.track(this.readBell()),this.bellTimer=setInterval(()=>this.track(this.readBell()),this.opts.bellPollMs??6e4),this.bellTimer.unref?.())}async readBell(){if(!(this.bellOff||this.stopped))try{let e=await this.client.notifications(1);this.unread=e.unread,this.render()}catch(e){e instanceof D&&(e.status===404||e.status===403)&&(this.bellOff=!0)}}notificationRow(e){let t=[Bi(e.kind),e.summary?xe(e.summary,60):"",e.status?`(${e.status})`:""].filter(Boolean).join(" \xB7 ");return{value:e.id,label:`${e.read_at?" ":"\u2022"} ${xe(e.title||Bi(e.kind),40)}`,description:`${t} \xB7 ${X(e.created_at)}`}}async notificationList(){let e;try{let n=await this.client.notifications(50);e=n.items??[],this.unread=n.unread}catch(n){n instanceof D&&n.status===404?this.say("this platform keeps no notifications","needs"):this.fail(n);return}let t=()=>`Notifications, newest first \xB7 ${this.unread} unread`,i=new te(this.paint,t(),e.map(n=>this.notificationRow(n)),{keys:["a"],footer:"\u2191\u2193 choose \xB7 Enter open it (marks it read) \xB7 a mark all read \xB7 Esc close",empty:"no notifications"});i.onCancel=()=>this.hideOverlay(),i.onKey=()=>{this.track(this.client.readNotifications().then(n=>{let r=new Date().toISOString();for(let o of e)o.read_at??=r;this.unread=n,i.setItems(e.map(o=>this.notificationRow(o))),i.setTitle(t()),i.say("all marked read"),this.render()},n=>{i.say(n instanceof Error?n.message:String(n),"failed"),this.render()}))},i.onPick=n=>{let r=e.find(o=>o.id===n);r&&this.openNotification(r)},this.showOverlay("notifications",i,{width:"90%",minWidth:40,maxHeight:"80%"})}openNotification(e){this.hideOverlay(),e.read_at||(e.read_at=new Date().toISOString(),this.unread=Math.max(0,this.unread-1),this.track(this.client.readNotifications([e.id]).then(i=>{this.unread=i,this.render()},()=>{})));let t=cc(e);t&&"thread"in t?this.thread?.id===t.thread?this.say(`${Bi(e.kind)}: this conversation`):this.track(this.openThread(t.thread)):t&&"lab"in t?this.track(this.labStatus(t.lab)):this.say(`${Bi(e.kind)}${e.summary?`: ${e.summary}`:""}`),this.render()}labRow(e){let t=e.agent?`agent ${U(e.agent.name,e.id)}`:"no agent for you";return{value:e.id,label:`${U(e.name,e.id)} (${e.id})`,description:`role ${sn(e)} \xB7 ${e.status} \xB7 ${Kr(e.connection)} \xB7 ${t}`}}async labList(e){let t;try{t=await this.client.labs(),this.dir&&(this.dir.labs=t)}catch(r){this.fail(r);return}let i=e?.lab??(this.thread?this.threadAgent:this.agent)?.lab,n=new te(this.paint,"Your labs",t.map(r=>this.labRow(r)),{keys:["s","r","w"],footer:"Enter talk with its agent \xB7 s status \xB7 r ask for access \xB7 w withdraw it \xB7 Esc close",empty:"no lab is there for you",selected:t.findIndex(r=>r.id===i)});e&&n.say(e.text,e.tone),n.onCancel=()=>this.hideOverlay(),n.onPick=r=>{let o=t.find(l=>l.id===r);if(!o)return;let a=this.dir&&Oi(this.dir).find(l=>l.lab===o.id);if(a){this.hideOverlay(),this.useAgent(a);return}nn(o)?o.status==="paused"?n.say(`${o.id} is paused: its agent is back when the lab is`,"needs"):n.say(`${o.id} offers your organization no agent`,"needs"):n.say(`you have no role on ${o.id}, so its agent is not yours to use: r asks QuPai staff for access`,"needs"),this.render()},n.onKey=(r,o)=>{let a=t.find(l=>l.id===o);a&&(r==="s"?this.track(this.labStatus(a.id)):r==="r"?this.askLabAccess(a,n):r==="w"&&this.track(this.withdrawLabAccess(a,n,t)),this.render())},this.showOverlay("lab",n,{width:"90%",minWidth:40,maxHeight:"80%"})}askLabAccess(e,t){if(nn(e)){t.say(`you hold a role on ${e.id} already (${sn(e)})`,"needs");return}if(e.access_request==="pending"){t.say(`you have asked for ${e.id} already: QuPai staff answer it${this.labRequests.has(e.id)?" (w withdraws it)":""}`,"needs");return}let i=new bt(this.paint,`Ask for access to ${U(e.name,e.id)}`,"QuPai staff decide who uses a lab, and every staff member is told. A note for them (optional, at most 500 characters):");i.onCancel=()=>this.track(this.labList({text:"nothing was asked",lab:e.id})),i.onAnswer=n=>{let r=n.trim();if([...r].length>500){i.refuse(`the note is ${[...r].length} characters: at most 500`),this.render();return}this.hideOverlay(),this.track(this.client.requestLabAccess(e.id,r).then(o=>(this.labRequests.set(e.id,o.id),this.labList({text:`Asked QuPai staff for a role on ${e.id} (request ${o.id}). w withdraws it while the app is open: the platform gives the id only now.`,lab:e.id})),o=>{let a=o instanceof D&&o.status===409?`you hold a role on ${e.id} already, or have asked already: ${o.detail.replace(/\.$/,"")}`:o instanceof Error?o.message:String(o);return this.labList({text:a,tone:"failed",lab:e.id})}))},this.showOverlay("lab-request",i,{width:"70%",minWidth:40})}async withdrawLabAccess(e,t,i){let n=this.labRequests.get(e.id);if(!n){t.say(e.access_request==="pending"?`this app did not make that request, so it does not know its id: withdraw it on the lab's page in the app (${Hr(this.client.signIn.handoff.web,e.id)})`:`you have no open request for ${e.id}`,"needs");return}try{await this.client.withdrawLabAccess(e.id,n)}catch(r){r instanceof D&&r.status===404?(this.labRequests.delete(e.id),t.say(`${e.id} has no open request ${n} of yours (it may have been answered)`,"failed")):t.say(r instanceof Error?r.message:String(r),"failed"),this.render();return}this.labRequests.delete(e.id),e.access_request=null,t.setItems(i.map(r=>this.labRow(r))),t.say(`Withdrew your request for ${e.id}.`),this.render()}async labStatus(e){let t;try{t=await this.client.lab(e)}catch(o){o instanceof D&&o.status===404?this.say(`no lab ${e} is there for you (/lab lists yours)`,"failed"):this.fail(o);return}let i;if(!nn(t))i="you have no role on this lab: r in /lab asks QuPai staff for one";else if(t.status==="paused")i="the lab is paused";else try{i=await this.client.labMachines(t.id)}catch(o){o instanceof D&&o.status===503?i=`the lab does not answer (no lab PC is connected, or it is down): ${o.detail.replace(/\.$/,"")}`:o instanceof D&&o.status===409?i="the lab is paused":i=o instanceof Error?o.message:String(o)}let n=lc(t,i,this.client.signIn.handoff.web),r=this.panel(`${U(t.name,t.id)}: status`,()=>n,.85);this.showOverlay("lab-status",r,{width:"85%",minWidth:40,maxHeight:"85%"})}async projectList(){let e=[],t=0;for(let r of jm)try{let o=await this.client.places(r);t++;for(let a of o.items??[])e.push({app:a.app||r,key:a.key,title:a.title,updated:a.updated_at,declared:o.declared_by})}catch(o){if(o instanceof D&&(o.status===404||o.status===400||o.status===403&&o.type.endsWith(":feature-disabled")))continue;this.fail(o);return}if(!t){this.say("this platform offers you no projects (no package declares them, or your organization has the app turned off)","needs");return}let i=new te(this.paint,"Your projects",e.map(r=>({value:`${r.app}/${r.key}`,label:r.title||r.key,description:`${r.key} \xB7 ${r.app==="project"?"project":"calibration project"} \xB7 ${X(r.updated)}`})),{keys:["f"],footer:"\u2191\u2193 choose \xB7 Enter start a conversation in it \xB7 f its files \xB7 Esc close",empty:"no projects yet: make one in the app"}),n=r=>e.find(o=>`${o.app}/${o.key}`===r);i.onCancel=()=>this.hideOverlay(),i.onPick=r=>{let o=n(r);if(!o)return;let a=o.declared?.product_id&&o.declared.agent_id?this.choiceFor(o.declared.product_id,o.declared.agent_id):this.agent;if(!a){i.say("no agent to start it with: /agent chooses one","needs"),this.render();return}this.hideOverlay(),this.newConversation(),this.place={app:o.app,key:o.key,title:o.title||o.key,agent:a},this.say(`a new conversation in ${this.place.title} with ${mt(a)}: your first message starts it`)},i.onKey=(r,o)=>{let a=n(o);a&&this.track(this.client.placeFiles(a).then(l=>this.showFiles(`${a.title||a.key}: files`,l,c=>Gl(a,c),"nothing is kept for the project yet"),l=>{i.say(l instanceof Error?l.message:String(l),"failed"),this.render()}))},this.showOverlay("project",i,{width:"80%",minWidth:40,maxHeight:"80%"})}async balance(){let t=oc(),[i,n]=await Promise.allSettled([this.client.billing(),this.client.usage(7,t)]);if(i.status==="rejected"){this.fail(i.reason);return}let r=i.value,o=`${this.client.signIn.handoff.web.replace(/\/+$/,"")}/credits`,a=[`Balance ${re(r.account.balance_ucny)}`,`Available ${re(r.account.available_ucny)} (${re(r.account.held_ucny)} held for running work)`,`Paid by ${r.payer==="tenant"?"your organization: its admin tops it up":"you"}`,`Top up in the app: ${o}`,""];if(n.status==="rejected")a.push(`Usage: ${n.reason instanceof Error?n.reason.message:String(n.reason)}`);else{let c=n.value;a.push(`The last 7 days (${c.tz}): ${re(c.spent_ucny)} spent, ${c.charges} ${c.charges===1?"charge":"charges"}`);let h=(c.days??[]).filter(u=>u.charges>0);for(let u of h)a.push(` ${u.day} ${re(u.spent_ucny).padStart(10)} ${u.charges} ${u.charges===1?"charge":"charges"}`);if((c.items??[]).length){a.push("","By model or tool");for(let u of c.items)a.push(` ${`${u.kind}${u.subject?` ${u.subject}`:""}`.padEnd(32)}${re(u.spent_ucny).padStart(10)} ${u.charges}`)}}let l=this.panel("Balance",()=>a,.85);this.showOverlay("balance",l,{width:"80%",minWidth:40,maxHeight:"85%"})}async pickThread(){let e;try{e=await this.client.threads(30)}catch(n){this.fail(n);return}let t=e.map(n=>({value:n.id,label:n.title||"(untitled)",description:`${n.updated_at?new Date(n.updated_at).toLocaleString():""} \xB7 ${n.product_id}/${n.agent_id}${n.activity==="needs_you"?" \xB7 needs you":n.activity==="running"?" \xB7 running":""}`})),i=new gt(this.paint,"Threads, newest first",t,{empty:"no threads yet"});i.onCancel=()=>this.hideOverlay(),i.onPick=n=>{this.hideOverlay(),this.track(this.openThread(n))},this.showOverlay("threads",i)}stopTurn(){let e=this.following;if(!e)return;let t=new Ye(this.paint,"Stop this turn? The agent stops where it is; what it did so far stays.");t.onAnswer=i=>{this.hideOverlay(),i&&this.track(this.client.cancelTurn(e.turnId).then(()=>this.say("stopping the turn\u2026"),n=>this.fail(n)))},this.showOverlay("confirm",t,{width:60,minWidth:30})}quit(e,t){if(this.stopped)return;this.bellTimer&&clearInterval(this.bellTimer),this.updateTimer&&clearInterval(this.updateTimer),this.markTimer&&clearInterval(this.markTimer),this.following?.abort.abort(),this.closeApproval(),this.hideOverlay(),this.stopped=!0;let i=new ee;if(this.thread){for(let r of this.transcript.children)r!==this.welcome&&i.addChild(r);i.addChild(new ze(this.paint.dim(`thread ${this.thread.id} \xB7 continue it with qupai chat -thread ${this.thread.id}`),0,1))}rr(this.tui)&&this.tui.setLayoutRoot(i),this.tui.stop();let n=e;t&&this.opts.runCommand&&(n=this.opts.runCommand(t)),this.client.signIn.close(),this.opts.onExit?.(n)}get tools(){return this.transcript.children.flatMap(e=>e instanceof Fi?e.tools:e instanceof Ki?e.cards:[])}setNav(e){let t=this.tools;for(let i of t)i.selected=!1;this.nav=e,e>=0&&t[e]&&(t[e].selected=!0),this.render()}onKey(e){if(this.overlay)return S(e,T.ctrl("c"))&&this.overlay.kind!=="approval"?(this.overlay.kind==="hardware"?this.overlay.component.close():this.hideOverlay(),{consume:!0}):void 0;if(e.startsWith("\x1B[200~")&&e.endsWith("\x1B[201~")){let i=Ur(e.slice(6,-6),this.cwd);if(i)return this.attach(i),{consume:!0}}let t=this.editor.getText()==="";if(S(e,T.backspace)&&t&&this.attachments.length&&this.nav<0)return this.detachLast(),{consume:!0};if(this.nav>=0){let i=this.tools;if(S(e,T.up))this.setNav(Math.max(0,this.nav-1));else if(S(e,T.down))this.setNav(Math.min(i.length-1,this.nav+1));else if(S(e,T.enter)||e===" "){let n=i[this.nav];n&&(n.expanded=!n.expanded),this.render()}else if(e==="v"||e==="V"){let n=i[this.nav],r=n instanceof Hi?n.rerunnable():!!n?.offer;n&&r?(this.setNav(-1),n.act()):this.say("nothing here runs on hardware: \u2191\u2193 to a line marked [Run on hardware v]","needs")}else if(S(e,T.escape)||S(e,T.tab)||S(e,T.ctrl("c")))this.setNav(-1);else if(S(e,T.pageUp)||S(e,T.pageDown))return;return{consume:!0}}if(S(e,T.ctrl("c")))return t?this.quit(0):this.editor.setText(""),this.render(),{consume:!0};if(S(e,T.ctrl("d"))&&t)return this.quit(0),{consume:!0};if(S(e,T.escape)&&this.following&&t)return this.stopTurn(),{consume:!0};if(S(e,T.escape)&&t)for(let i of this.runs){let n=i.active.find(r=>r.kind==="hardware"&&!r.cancel_requested&&!jt(r.detail));if(n)return this.stopRun(n,i),{consume:!0}}if(e==="?"&&t)return this.showOverlay("keys",this.panel("Keys",()=>Wc.map(([i,n])=>`${i.padEnd(12)}${n}`),.85),{width:"90%",minWidth:40,maxHeight:"85%"}),{consume:!0};if(S(e,T.tab)&&t&&this.tools.length)return this.setNav(this.tools.length-1),{consume:!0}}};function Gm(s){let[e,t]=process.platform==="darwin"?["open",[s]]:process.platform==="win32"?["rundll32",["url.dll,FileProtocolHandler",s]]:["xdg-open",[s]];try{let i=Hm(e,t,{stdio:"ignore",detached:!0});return i.on("error",()=>{}),i.unref(),!0}catch{return!1}}function Qm(s,e){let t="",i=1/0;for(let n of e){let r=Ym(s,n);r<i&&([t,i]=[n,r])}return t&&i<=Math.max(2,Math.floor(s.length/3))?t:""}function Ym(s,e){let t=Array.from({length:e.length+1},(i,n)=>n);for(let i=1;i<=s.length;i++){let n=[i];for(let r=1;r<=e.length;r++)n[r]=Math.min(t[r]+1,n[r-1]+1,t[r-1]+(s[i-1]===e[r-1]?0:1));t=n}return t[e.length]}import{spawn as Xm}from"node:child_process";import{Socket as Jm}from"node:net";var ke=class extends Error{exit;constructor(e,t=3){super(e),this.exit=t}};function Uc(s){let e;try{e=JSON.parse(s)}catch{throw new ke("the qupai command handed over no sign-in the app can read",1)}if(e.error)throw new ke(e.error,e.exit??3);if(!e.server||!e.token)throw new ke("the qupai command handed over no sign-in",1);return{server:e.server.replace(/\/+$/,""),web:(e.web||e.server).replace(/\/+$/,""),token:e.token,kind:e.kind??"",renews:e.renews===!0,choice_file:e.choice_file??""}}var ao=class{buffer="";waiting=[];lines=[];ended=!1;constructor(e){e.setEncoding("utf8"),e.on("data",i=>{this.buffer+=i;let n;for(;(n=this.buffer.indexOf(`
|
|
119
|
+
`))>=0;){let r=this.buffer.slice(0,n);this.buffer=this.buffer.slice(n+1);let o=this.waiting.shift();o?o(r):this.lines.push(r)}});let t=()=>{this.ended=!0;for(let i of this.waiting.splice(0))i(null)};e.on("end",t),e.on("close",t),e.on("error",t)}next(){let e=this.lines.shift();return e!==void 0?Promise.resolve(e):this.ended?Promise.resolve(null):new Promise(t=>this.waiting.push(t))}};function Zm(s=3,e){let t=e??new Jm({fd:s,readable:!0,writable:!0}),i=new ao(t),n=async()=>{let r=await i.next();if(r===null)throw new ke("the qupai command closed the sign-in hand-off",1);return Uc(r)};return{first:n,renew:async()=>(t.write(`{"op":"renew"}
|
|
120
|
+
`),n()),close:()=>t.destroy()}}function eg(s,e){let t=i=>new Promise((n,r)=>{let o=["tui-handoff","-server",e,...i?["-renew"]:[]],a=Xm(s,o,{stdio:["ignore","pipe","pipe"],windowsHide:!0}),l="",c="";a.stdout.setEncoding("utf8").on("data",h=>l+=h),a.stderr.setEncoding("utf8").on("data",h=>c+=h),a.on("error",h=>r(new ke(`the qupai command could not hand over the sign-in: ${h.message}`,1))),a.on("close",h=>{let u=l.split(`
|
|
121
|
+
`)[0]??"";if(u){try{n(Uc(u))}catch(d){r(d)}return}r(new ke(c.trim().replace(/^qupai: /,"")||`the qupai command handed over no sign-in (exit ${h})`,h??1))})});return{first:()=>t(!1),renew:()=>t(!0),close:()=>{}}}function Kc(s=process.env){switch(s.QUPAI_TUI_HANDOFF){case"fd":return Zm(3);case"exec":if(!s.QUPAI_TUI_COMMAND||!s.QUPAI_TUI_SERVER)throw new ke("QUPAI_TUI_COMMAND and QUPAI_TUI_SERVER name no command to ask",2);return eg(s.QUPAI_TUI_COMMAND,s.QUPAI_TUI_SERVER)}throw new ke("start the full-screen app with the qupai command (qupai, or qupai chat)",2)}var xn=class{current;renewing=null;source;constructor(e,t){this.current=e,this.source=t}get handoff(){return this.current}token(){return this.current.token}async renew(e){if(this.current.token!==e)return!0;this.renewing??=this.source.renew().finally(()=>this.renewing=null);let t=await this.renewing;return this.current=t,t.token!==e}close(){this.source.close()}};var Hc={update:20,later:21,skip:22,interrupt:130},Zt=["update","later","skip"];function tg(s,e,t){switch(s){case"update":return`Update now ${t.dim(`(runs ${e.command})`)}`;case"later":return`Later ${t.dim("(asks again tomorrow)")}`;case"skip":return`Skip this version ${t.dim(`(quiet until one after ${e.latest})`)}`}}function ig(s,e,t){let i=Zt.map((n,r)=>{let o=`${r+1}. ${tg(n,s,t)}`;return r===e?`${t.tone("\u203A","brand")} ${t.bold(o)}`:` ${o}`});return["",` ${t.tone(t.bold(`Update available: qupai ${s.current} \u2192 ${s.latest}`),"needs")}`,"",...i,"",` ${t.dim("\u2191\u2193 or 1-3 to choose \xB7 Enter to confirm \xB7 Esc for later")}`,""]}function sg(s,e){switch(s){case"":return{choice:"interrupt"};case"\r":case`
|
|
122
|
+
`:return{choice:Zt[e]};case"\x1B":case"":case"q":return{choice:"later"};case"\x1B[A":case"\x1BOA":case"k":return{selected:(e+Zt.length-1)%Zt.length};case"\x1B[B":case"\x1BOB":case"j":case" ":return{selected:(e+1)%Zt.length};case"1":case"2":case"3":return{choice:Zt[Number(s)-1]}}return{selected:e}}function zc(s,e){let{input:t,output:i,paint:n}=e,r=0,o=0,a=()=>o?`\x1B[${o}A\r\x1B[J`:"",l=()=>{let c=ig(s,r,n);i.write(`${a()}${c.join(`\r
|
|
123
|
+
`)}\r
|
|
124
|
+
`),o=c.length};return new Promise(c=>{let h=u=>{let d=sg(u,r);if("selected"in d){d.selected!==r&&(r=d.selected,l());return}t.off("data",h),t.setRawMode?.(!1),t.pause(),i.write(`${a()}\x1B[?25h`),c(d.choice)};t.setRawMode?.(!0),t.setEncoding("utf8"),t.resume(),i.write("\x1B[?25l"),l(),t.on("data",h)})}function Vc(s){if(s[0]!=="-update-prompt")return;let e={};for(let t=1;t+1<s.length;t+=2)e[s[t].replace(/^--?/,"")]=s[t+1];if(!(!e.current||!e.latest||!e.command))return{current:e.current,latest:e.latest,command:e.command}}var lo=[22,19];function og(s=process.versions.node){let[e=0,t=0]=s.split(".").map(Number);return e>lo[0]||e===lo[0]&&t>=lo[1]}function ag(s){let e={};for(let t=0;t<s.length;t++){let i=s[t]?.replace(/^--?/,""),n=s[t+1];(i==="product"||i==="agent"||i==="lab"||i==="thread")&&n!==void 0&&(e[i]=n,t++)}return e}function lg(s){return new Promise(e=>{ng(s,["update","-check","-json"],{timeout:2e4,windowsHide:!0},(t,i)=>{if(t)return e("");try{let n=JSON.parse(i);e(n.update_available&&!n.skipped&&n.latest?n.latest:"")}catch{e("")}})})}async function cg(){if(process.argv[2]==="-update-prompt"){let t=Vc(process.argv.slice(2));return!t||!process.stdin.isTTY||!process.stdout.isTTY?0:Hc[await zc(t,{input:process.stdin,output:process.stdout,paint:zr()})]}if(!og())return process.stderr.write(`qupai: the full-screen app needs Node.js 22.19 or later; this is Node.js ${process.versions.node}
|
|
122
125
|
`),2;if(!process.stdin.isTTY||!process.stdout.isTTY)return process.stderr.write(`qupai: the full-screen app opens only on a terminal
|
|
123
|
-
`),2;let s;try{let t=
|
|
124
|
-
`),t instanceof ke?t.exit:1}let e=process.env.QUPAI_TUI_COMMAND;return new Promise(t=>{let i=new
|
|
125
|
-
`),process.exit(1)});export{
|
|
126
|
+
`),2;let s;try{let t=Kc();s=new xn(await t.first(),t)}catch(t){return process.stderr.write(`qupai: ${t instanceof Error?t.message:String(t)}
|
|
127
|
+
`),t instanceof ke?t.exit:1}let e=process.env.QUPAI_TUI_COMMAND;return new Promise(t=>{let i=new wn({terminal:new Si,client:new Xs({signIn:s}),paint:zr(),start:ag(process.argv.slice(2)),devicesUrl:process.env.QUPAI_DEVICES_URL,motion:!process.env.QUPAI_NO_MOTION,update:process.env.QUPAI_TUI_UPDATE||void 0,checkUpdate:e&&process.env.QUPAI_TUI_UPDATE_CHECK?()=>lg(e):void 0,runCommand:e?n=>rg(e,n,{stdio:"inherit"}).status??1:void 0,onExit:t});for(let n of["SIGTERM","SIGHUP"])process.on(n,()=>i.quit(n==="SIGTERM"?143:129));i.start()})}cg().then(s=>process.exit(s),s=>{process.stderr.write(`qupai: the full-screen app failed: ${s instanceof Error?s.stack??s.message:String(s)}
|
|
128
|
+
`),process.exit(1)});export{lo as MIN_NODE,lg as askForUpdate,og as nodeIsRecentEnough,ag as parseArgs};
|