@evandu/super-pi 0.1.111 → 0.1.113
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.super-pi-check-inputs.json +2 -2
- package/dist/client/.super-pi-client-sources.json +8 -7
- package/dist/client/assets/{CodeMirrorEditor-CaF1aTpR.js → CodeMirrorEditor-moFTk5SE.js} +2 -2
- package/dist/client/assets/{dist-aC6cFQVF.js → dist-BR4s0dNg.js} +1 -1
- package/dist/client/assets/{dist-Bl_iPEld.js → dist-BUuPRG15.js} +1 -1
- package/dist/client/assets/{dist-CPo4IuhO.js → dist-Bds_PUYK.js} +1 -1
- package/dist/client/assets/{dist-BydrWuS9.js → dist-BsO40qxQ.js} +1 -1
- package/dist/client/assets/{dist-jDX3NY00.js → dist-CCYnr6ul.js} +1 -1
- package/dist/client/assets/{dist-f78PQc3f.js → dist-CL65aMXY.js} +1 -1
- package/dist/client/assets/{dist-BjrDHYro.js → dist-D9m04q-s.js} +1 -1
- package/dist/client/assets/{dist-o-3gMx5l.js → dist-DIfmMr8s.js} +1 -1
- package/dist/client/assets/{dist-CJHSsi_2.js → dist-DPDGd2jl.js} +1 -1
- package/dist/client/assets/{dist-C9gmrpfb.js → dist-DPvy57Ph.js} +1 -1
- package/dist/client/assets/{dist-CKziNS6e.js → dist-DQjJMys5.js} +1 -1
- package/dist/client/assets/{dist-CbkXScEJ.js → dist-Dnr5BxAi.js} +1 -1
- package/dist/client/assets/{dist-C2JgfsQ0.js → dist-DrbUrVWB.js} +1 -1
- package/dist/client/assets/{dist-BG1mkRxC.js → dist-DuWhzonJ.js} +1 -1
- package/dist/client/assets/{dist-DnwnynHW.js → dist-TgNJUr7p.js} +1 -1
- package/dist/client/assets/{dist-Bv-QAejS.js → dist-rhPxFuD1.js} +1 -1
- package/dist/client/assets/{index-CME3BwBz.js → index-BixdV7aQ.js} +23 -23
- package/dist/client/assets/index-CGXMw9LP.css +1 -0
- package/dist/client/index.html +2 -2
- package/dist/server/application/run-service.d.ts +7 -0
- package/dist/server/application/run-service.js +16 -0
- package/dist/server/file-name-index.d.ts +144 -0
- package/dist/server/file-name-index.js +324 -0
- package/dist/server/http-server.js +112 -3
- package/dist/server/index.js +10 -0
- package/dist/server/server-context.d.ts +9 -0
- package/dist/server/skills.d.ts +23 -0
- package/dist/server/skills.js +171 -0
- package/dist/server/types.d.ts +7 -0
- package/package.json +3 -1
- package/scripts/patch-brace-expansion.mjs +1 -1
- package/dist/client/assets/index-CauO59H-.css +0 -1
|
@@ -42,12 +42,12 @@ https://github.com/highlightjs/highlight.js/issues/2277`),i=e,r=t),n===void 0&&(
|
|
|
42
42
|
`))});continue}if(e.includes(`|`)&&r+1<t.length&&Op.test(t[r+1])&&t[r+1].includes(`-`)){let i=Ip(e),a=Ip(t[r+1]).map(Lp),o=[];for(r+=2;r<t.length&&t[r].trim()&&t[r].includes(`|`);)o.push(Rp(Ip(t[r]),i.length).map(e=>xp(e))),r+=1;n.push({type:`table`,head:i.map(e=>xp(e)),align:a,rows:o});continue}if(Tp.test(e)||Ep.test(e)){let e=Fp(t,r);n.push(e.node),r=e.next;continue}let s=[];for(;r<t.length&&t[r].trim()&&!Pp(t[r]);)s.push(t[r]),r+=1;s.length||(s.push(t[r]),r+=1),n.push({type:`paragraph`,children:xp(s.join(`
|
|
43
43
|
`))})}return n}function Pp(e){return Sp.test(e)||Cp.test(e)||wp.test(e)||Dp.test(e)||Tp.test(e)||Ep.test(e)||/^\s*\$\$/.test(e)}function Fp(e,t){let n=Ep.test(e[t]),r=n?Ep.exec(e[t]):Tp.exec(e[t]),i=r[1].length,a=[],o=t;for(;o<e.length;){let t=Tp.exec(e[o]),r=Ep.exec(e[o]),s=n?r:t;if(!s)break;let c=s[1].length;if(c<i)break;let l=[s[s.length-1]];for(o+=1;o<e.length;){let n=e[o];if(!n.trim()){let t=e[o+1]??``;if(!t.trim()||t.search(/\S/)<=c)break;l.push(``),o+=1;continue}let i=n.search(/\S/);if(i===0&&t||i===0&&r)break;if(i>c)l.push(n.slice(Math.min(i,c+2))),o+=1;else if(i===c){if(Pp(n))break;l.push(n),o+=1}else break}a.push(Np(l.join(`
|
|
44
44
|
`)))}return{node:{type:`list`,ordered:n,start:n?Number(r[2]):1,items:a},next:o}}function Ip(e){let t=e.trim();t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&!t.endsWith(`\\|`)&&(t=t.slice(0,-1));let n=[],r=``;for(let e=0;e<t.length;e+=1)t[e]===`\\`&&t[e+1]===`|`?(r+=`|`,e+=1):t[e]===`|`?(n.push(r.trim()),r=``):r+=t[e];return n.push(r.trim()),n}function Lp(e){let t=e.startsWith(`:`),n=e.endsWith(`:`);return t&&n?`center`:n?`right`:t?`left`:null}function Rp(e,t){let n=e.slice(0,t);for(;n.length<t;)n.push(``);return n}var zp={alpha:`α`,beta:`β`,gamma:`γ`,delta:`δ`,epsilon:`ε`,varepsilon:`ε`,zeta:`ζ`,eta:`η`,theta:`θ`,vartheta:`ϑ`,iota:`ι`,kappa:`κ`,lambda:`λ`,mu:`μ`,nu:`ν`,xi:`ξ`,pi:`π`,varpi:`ϖ`,rho:`ρ`,varrho:`ϱ`,sigma:`σ`,varsigma:`ς`,tau:`τ`,upsilon:`υ`,phi:`φ`,varphi:`ϕ`,chi:`χ`,psi:`ψ`,omega:`ω`,Gamma:`Γ`,Delta:`Δ`,Theta:`Θ`,Lambda:`Λ`,Xi:`Ξ`,Pi:`Π`,Sigma:`Σ`,Upsilon:`Υ`,Phi:`Φ`,Psi:`Ψ`,Omega:`Ω`},Bp={times:`×`,div:`÷`,pm:`±`,mp:`∓`,cdot:`·`,ast:`∗`,star:`⋆`,circ:`∘`,bullet:`∙`,leq:`≤`,le:`≤`,geq:`≥`,ge:`≥`,neq:`≠`,ne:`≠`,approx:`≈`,sim:`∼`,simeq:`≃`,equiv:`≡`,propto:`∝`,ll:`≪`,gg:`≫`,in:`∈`,notin:`∉`,ni:`∋`,subset:`⊂`,subseteq:`⊆`,supset:`⊃`,supseteq:`⊇`,cup:`∪`,cap:`∩`,setminus:`∖`,emptyset:`∅`,varnothing:`∅`,aleph:`ℵ`,hbar:`ℏ`,ell:`ℓ`,Re:`ℜ`,Im:`ℑ`,sum:`∑`,prod:`∏`,coprod:`∐`,int:`∫`,iint:`∬`,iiint:`∭`,oint:`∮`,bigcup:`⋃`,bigcap:`⋂`,to:`→`,rightarrow:`→`,leftarrow:`←`,gets:`←`,leftrightarrow:`↔`,Rightarrow:`⇒`,Leftarrow:`⇐`,Leftrightarrow:`⇔`,mapsto:`↦`,longrightarrow:`⟶`,longleftarrow:`⟵`,uparrow:`↑`,downarrow:`↓`,ldots:`…`,cdots:`⋯`,vdots:`⋮`,ddots:`⋱`,dots:`…`,therefore:`∴`,because:`∵`,angle:`∠`,triangle:`△`,perp:`⊥`,parallel:`∥`,degree:`°`,prime:`′`,lbrace:`{`,rbrace:`}`,lbrack:`[`,rbrack:`]`,langle:`⟨`,rangle:`⟩`,lfloor:`⌊`,rfloor:`⌋`,lceil:`⌈`,rceil:`⌉`,vert:`|`,Vert:`‖`,backslash:`\\`,oplus:`⊕`,ominus:`⊖`,otimes:`⊗`,oslash:`⊘`,odot:`⊙`,dagger:`†`,ddagger:`‡`,quad:` `,qquad:` `,thinspace:` `,enspace:` `,negthinspace:``},Vp=new Set(`arcsin.arccos.arctan.sinh.cosh.tanh.cot.sec.csc.sin.cos.tan.log.ln.lg.exp.lim.limsup.liminf.max.min.det.dim.ker.deg.gcd.hom.arg.Pr.sup.inf`.split(`.`)),Hp={C:`ℂ`,H:`ℍ`,N:`ℕ`,P:`ℙ`,Q:`ℚ`,R:`ℝ`,Z:`ℤ`},Up={B:`ℬ`,E:`ℰ`,F:`ℱ`,H:`ℋ`,I:`ℐ`,L:`ℒ`,M:`ℳ`,R:`ℛ`,e:`ℯ`,g:`ℊ`,o:`ℴ`},Wp={mathbb:e=>Hp[e]??e.toUpperCase(),mathcal:e=>Up[e]??e.toUpperCase(),mathscr:e=>Up[e]??e.toUpperCase()},Gp=new Set([`left`,`right`,`big`,`Big`,`bigg`,`Bigg`,`bigl`,`bigr`,`Bigl`,`Bigr`,`biggl`,`biggr`,`Biggl`,`Biggr`,`middle`,`displaystyle`,`textstyle`,`scriptstyle`,`limits`,`nolimits`,`nonumber`,`notag`,`label`]),Kp={hat:`^`,widehat:`^`,bar:`‾`,overline:`‾`,tilde:`~`,widetilde:`~`,vec:`→`,dot:`·`,ddot:`··`,check:`ˇ`,breve:`˘`,acute:`´`,grave:"`"},qp=new Set([`(`,`)`,`[`,`]`,`|`,`/`,`<`,`>`]),Jp=new Set([`pmatrix`,`bmatrix`,`Bmatrix`,`vmatrix`,`Vmatrix`,`matrix`,`array`,`cases`,`aligned`,`align`,`alignat`,`split`,`gather`,`gathered`,`equation`,`smallmatrix`,`dcases`,`subarray`]);function Yp(e){let t=[],n=``,r=()=>{n&&=(t.push(...$p(n)),``)},i=e=>{r(),t.push(e)};for(let a=0;a<e.length;){let o=e[a];if(o===`\\`){let t=a,r=/^\\([a-zA-Z]+|.)/.exec(e.slice(a));if(!r){n+=o,a+=1;continue}let s=r[1];if(a+=r[0].length,s===`\\`){i({type:`math-row-break`});continue}if(s===`{`||s===`}`){n+=s;continue}if(s===`,`||s===`;`||s===`:`||s===`!`||s===`&`)continue;if(s===`%`){for(;a<e.length&&e[a]!==`
|
|
45
|
-
`;)a+=1;continue}if(Gp.has(s))continue;if(s===`begin`){let n=up(e,a),r=n.content,o=`\\end{${r}}`,s=e.indexOf(o,n.next),c=s===-1?e.length:s+o.length;i({type:`math-unsupported`,value:e.slice(t,c),reason:`\\begin{${r}} 不支持`}),a=c;continue}if(s===`frac`||s===`dfrac`||s===`tfrac`||s===`cfrac`){let t=Zp(e,a),n=Zp(e,t.next);a=n.next,i({type:`math-fraction`,numerator:Yp(t.content),denominator:Yp(n.content)});continue}if(s===`sqrt`){let t,n=a;if(e[n]===`[`){let r=Xp(e,n);t=Yp(r.content),n=r.next}let r=Zp(e,n);a=r.next,i({type:`math-root`,...t?{index:t}:{},radicand:Yp(r.content)});continue}if(s===`text`||s===`mathrm`||s===`textrm`||s===`mathbf`||s===`mathit`||s===`mathsf`||s===`mathtt`||s===`operatorname`||s===`textbf`){let t=up(e,a);a=t.next,i({type:`math-text`,value:t.content});continue}if(s in Wp){let t=Zp(e,a);a=t.next;let n=Wp[s];i({type:`math-text`,value:[...t.content].map(n).join(``)});continue}if(s in Kp){let t=Zp(e,a);a=t.next,i({type:`math-text`,value:`${em(Yp(t.content))}${Kp[s]}`});continue}if(s in zp){i({type:`math-identifier`,value:zp[s]});continue}if(s in Bp){let e=Bp[s];/^\d/.test(e)?i({type:`math-number`,value:e}):/^[A-Za-z]/.test(e)?i({type:`math-text`,value:e}):i({type:`math-operator`,value:e});continue}if(Vp.has(s)){i({type:`math-function`,value:s});continue}if(Jp.has(s))continue;i({type:`math-unsupported`,value:`\\${s}`,reason:`\\${s} 不支持`})}else if(o===`{`){let n=up(e,a);t.push(...Yp(n.content)),a=n.next}else if(o===`}`||o===`&`||o===`$`)a+=1;else if(o===`^`||o===`_`){r();let n=Zp(e,a+1);a=n.next,Qp(t,o===`^`?`sup`:`sub`,Yp(n.content))}else qp.has(o)?(i({type:`math-text`,value:o}),a+=1):(n+=o,a+=1)}return r(),t}function Xp(e,t){let n=e.indexOf(`]`,t+1);return n===-1?{content:``,next:e.length}:{content:e.slice(t+1,n),next:n+1}}function Zp(e,t){let n=e[t];if(n===void 0)return{content:``,next:t};if(n===`{`)return up(e,t);let r=/^\\[a-zA-Z]+/.exec(e.slice(t));return r?{content:r[0],next:t+r[0].length}:{content:n,next:t+1}}function Qp(e,t,n){let r=e.pop();if(r){if(r.type===`math-script`)t===`sub`&&!r.sub?e.push({...r,sub:n}):t===`sup`&&!r.sup?e.push({...r,sup:n}):e.push(r);else if(r.type===`math-identifier`||r.type===`math-text`){let i=[...r.value],a=i.pop()??``;i.length&&e.push({type:r.type,value:i.join(``)}),e.push({type:`math-script`,base:[{type:`math-identifier`,value:a}],...t===`sub`?{sub:n}:{sup:n}})}else e.push({type:`math-script`,base:[r],...t===`sub`?{sub:n}:{sup:n}})}}function $p(e){let t=[],n=0;for(;n<e.length;){let r=e.slice(n),i=/^\d+(?:\.\d+)?/.exec(r);if(i){t.push({type:`math-number`,value:i[0]}),n+=i[0].length;continue}let a=/^[A-Za-z]+/.exec(r);if(a){t.push(Vp.has(a[0])?{type:`math-function`,value:a[0]}:{type:`math-identifier`,value:a[0]}),n+=a[0].length;continue}let o=/^[,;:!.'’|()\-+=<>/*]+/.exec(r);o?(t.push({type:`math-operator`,value:o[0]}),n+=o[0].length):(t.push({type:`math-text`,value:r[0]}),n+=1)}return t.reduce((e,t)=>{let n=e[e.length-1];return n?.type===`math-operator`&&t.type===`math-operator`?n.value+=t.value:e.push({...t}),e},[])}function em(e){return e.map(e=>{switch(e.type){case`math-text`:case`math-number`:case`math-identifier`:case`math-operator`:case`math-function`:return e.value;case`math-script`:return`${em(e.base)}${e.sub?`_{${em(e.sub)}}`:``}${e.sup?`^{${em(e.sup)}}`:``}`;case`math-fraction`:return`\\frac{${em(e.numerator)}}{${em(e.denominator)}}`;case`math-root`:return`\\sqrt{${em(e.radicand)}}`;case`math-row-break`:return`\\\\`;case`math-unsupported`:return e.value;default:return``}}).join(``)}function tm({source:e}){let t=(0,z.useMemo)(()=>Np(e),[e]);return(0,B.jsx)(`div`,{className:`md`,"data-md":`1`,children:t.map((e,t)=>im(e,t))})}function nm({source:e}){let t=(0,z.useMemo)(()=>xp(e),[e]);return(0,B.jsx)(`span`,{className:`md md-inline`,children:t.map((e,t)=>om(e,t))})}function rm(e){return np(e).map((e,t)=>e.kind===`plain`?(0,B.jsx)(`span`,{children:e.text},t):(0,B.jsx)(`span`,{className:`code-token-${e.kind}`,children:e.text},t))}function im(e,t){switch(e.type){case`paragraph`:return(0,B.jsx)(`p`,{className:`md-p`,children:e.children.map((e,t)=>om(e,t))},t);case`heading`:{let n=`h${Math.min(6,Math.max(1,e.level))}`;return(0,B.jsx)(n,{className:`md-h md-h${e.level}`,children:e.children.map((e,t)=>om(e,t))},t)}case`code-block`:return(0,B.jsx)(`pre`,{className:`md-pre`,"data-md-lang":e.lang||void 0,children:(0,B.jsx)(`code`,{className:`md-code`,children:rm(e.value)})},t);case`list`:{let n=e.items.map((e,t)=>(0,B.jsx)(`li`,{className:`md-li`,children:e.map((e,t)=>im(e,t))},t));return e.ordered?(0,B.jsx)(`ol`,{className:`md-ol`,start:e.start>1?e.start:void 0,children:n},t):(0,B.jsx)(`ul`,{className:`md-ul`,children:n},t)}case`blockquote`:return(0,B.jsx)(`blockquote`,{className:`md-quote`,children:e.children.map((e,t)=>im(e,t))},t);case`rule`:return(0,B.jsx)(`hr`,{className:`md-rule`},t);case`table`:return(0,B.jsx)(`div`,{className:`md-table-wrap`,children:(0,B.jsxs)(`table`,{className:`md-table`,children:[(0,B.jsx)(`thead`,{children:(0,B.jsx)(`tr`,{children:e.head.map((t,n)=>(0,B.jsx)(`th`,{style:am(e.align[n]),children:t.map((e,t)=>om(e,t))},n))})}),(0,B.jsx)(`tbody`,{children:e.rows.map((t,n)=>(0,B.jsx)(`tr`,{children:t.map((t,n)=>(0,B.jsx)(`td`,{style:am(e.align[n]),children:t.map((e,t)=>om(e,t))},n))},n))})]})},t);case`math-block`:return(0,B.jsx)(sm,{source:e.source},t);default:return null}}var am=e=>e?{textAlign:e}:void 0;function om(e,t){switch(e.type){case`text`:return(0,B.jsx)(z.Fragment,{children:e.value},t);case`code`:return(0,B.jsx)(`code`,{className:`md-code-inline`,children:e.value},t);case`strong`:return(0,B.jsx)(`strong`,{className:`md-strong`,children:e.children.map((e,t)=>om(e,t))},t);case`em`:return(0,B.jsx)(`em`,{className:`md-em`,children:e.children.map((e,t)=>om(e,t))},t);case`del`:return(0,B.jsx)(`del`,{className:`md-del`,children:e.children.map((e,t)=>om(e,t))},t);case`break`:return(0,B.jsx)(`br`,{className:`md-break`},t);case`math`:return(0,B.jsx)(cm,{source:e.source},t);case`link`:{let n=op(e.href);return n?(0,B.jsx)(`a`,{className:`md-link`,href:n,title:e.title,target:`_blank`,rel:`noopener noreferrer nofollow`,children:e.children.map((e,t)=>om(e,t))},t):(0,B.jsx)(z.Fragment,{children:e.children.map((e,t)=>om(e,t))},t)}default:return null}}function sm({source:e}){let t=(0,z.useMemo)(()=>Yp(e),[e]);return(0,B.jsx)(`div`,{className:`md-math md-math-block`,"data-md-math":`block`,"data-md-math-source":e,children:t.map((e,t)=>lm(e,t))})}function cm({source:e}){let t=(0,z.useMemo)(()=>Yp(e),[e]);return(0,B.jsx)(`span`,{className:`md-math md-math-inline`,"data-md-math":`inline`,"data-md-math-source":e,children:t.map((e,t)=>lm(e,t))})}function lm(e,t){switch(e.type){case`math-text`:return(0,B.jsx)(`span`,{className:`md-m-text`,children:e.value},t);case`math-number`:return(0,B.jsx)(`span`,{className:`md-m-number`,children:e.value},t);case`math-identifier`:return(0,B.jsx)(`i`,{className:`md-m-var`,children:e.value},t);case`math-operator`:return(0,B.jsx)(`span`,{className:`md-m-op`,children:e.value},t);case`math-function`:return(0,B.jsx)(`span`,{className:`md-m-fn`,children:e.value},t);case`math-row-break`:return(0,B.jsx)(`br`,{className:`md-m-rowbreak`},t);case`math-unsupported`:return(0,B.jsx)(`span`,{className:`md-m-unsupported`,"data-md-math-unsupported":`1`,title:e.reason,children:e.value},t);case`math-script`:return(0,B.jsxs)(`span`,{className:`md-m-script`,children:[(0,B.jsx)(`span`,{className:`md-m-base`,children:e.base.map((e,t)=>lm(e,t))}),e.sup&&(0,B.jsx)(`sup`,{className:`md-m-sup`,children:e.sup.map((e,t)=>lm(e,t))}),e.sub&&(0,B.jsx)(`sub`,{className:`md-m-sub`,children:e.sub.map((e,t)=>lm(e,t))})]},t);case`math-fraction`:return(0,B.jsxs)(`span`,{className:`md-m-frac`,children:[(0,B.jsx)(`span`,{className:`md-m-num`,children:e.numerator.map((e,t)=>lm(e,t))}),(0,B.jsx)(`span`,{className:`md-m-den`,children:e.denominator.map((e,t)=>lm(e,t))})]},t);case`math-root`:return(0,B.jsxs)(`span`,{className:`md-m-root`,children:[(0,B.jsx)(`span`,{className:`md-m-radical`,children:`√`}),e.index&&(0,B.jsx)(`sup`,{className:`md-m-index`,children:e.index.map((e,t)=>lm(e,t))}),(0,B.jsx)(`span`,{className:`md-m-body`,children:e.radicand.map((e,t)=>lm(e,t))})]},t);default:return null}}var um=[[`help`,`Show help`],[`model`,`Choose model`],[`settings`,`Open settings`],[`clear`,`Clear session`],[`compact`,`Compact context`],[`reload`,`Reload agents`],[`new`,`New session`],[`fork`,`Fork session`],[`resume`,`Resume session`],[`stop`,`Stop run`],[`skill`,`Workspace skill`]].map(([e,t])=>({id:e,label:`/${e} — ${t}`,description:t})),dm=e=>e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLowerCase();function fm(e,t){let n=dm(t.trim());return e.examples?.find(t=>dm(t).includes(n)&&t!==e.id)??e.id}function pm(e,t){let n=dm(t.trim());return n?e.filter(e=>dm(e.id).includes(n)||dm(e.label).includes(n)||e.examples?.some(e=>dm(e).includes(n))):e}function mm({query:e,anchorRect:t,command:n,workspaceId:r,onSelect:i,onClose:a}){let[o,s]=(0,z.useState)(0),[c,l]=(0,z.useState)(um),u=(0,z.useRef)(null),d=(0,z.useRef)([]);(0,z.useEffect)(()=>{let e=!1;if(r)return fetch(`/api/memory?workspaceId=${encodeURIComponent(r)}`).then(e=>e.ok?e.json():void 0).then(t=>{if(e||!t?.entries?.skills)return;let n=t.entries.skills.map(e=>{let t=e.content.split(/\r?\n/,1)[0].replace(/^#+\s*/,``).trim()||`unnamed-skill`,n=t.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff]+/g,`-`).replace(/^-|-$/g,``)||`unnamed-skill`;return{id:`skill:${n}`,label:t,description:`Workspace skill`,examples:[`skill:${n}`]}});l([...um.filter(e=>e.id!==`skill`),...n])}).catch(()=>{}),()=>{e=!0}},[r]);let f=pm([{id:`start`,label:`start — 打开浏览器`,description:`在浏览器中打开 Super Pi 控制台`,action:()=>n({type:`super_pi.start`})},{id:`restart`,label:`restart — 重启 Super Pi 服务`,description:`停掉并重新启动服务,加载磁盘上的新代码`,action:()=>n({type:`super_pi.restart`})},{id:`update`,label:`update — 更新 Super Pi`,description:`运行 npm install -g @evandu/super-pi 然后重启`,action:()=>n({type:`super_pi.update`})},...c],e),p=f.length===0?-1:Math.min(Math.max(o,0),f.length-1),m=e=>s(t=>f.length?Math.min(Math.max(t+e,0),f.length-1):0);(0,z.useEffect)(()=>{let e=e=>{u.current?.contains(e.target)||a()};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[a]),(0,z.useEffect)(()=>{s(0)},[e]),(0,z.useLayoutEffect)(()=>{p>=0&&d.current[p]?.scrollIntoView({block:`nearest`})},[p]);let h={position:`fixed`,left:Math.max(8,Math.min(t.left,window.innerWidth-360)),bottom:Math.max(8,window.innerHeight-t.top+6),zIndex:200};return(0,B.jsx)(`div`,{ref:u,className:`slash-menu`,style:h,role:`listbox`,"aria-label":`斜杠命令`,onKeyDown:e=>{if(e.key===`Escape`)e.preventDefault(),a();else if(e.key===`ArrowDown`)e.preventDefault(),m(1);else if(e.key===`ArrowUp`)e.preventDefault(),m(-1);else if(e.key===`Home`)e.preventDefault(),s(0);else if(e.key===`End`)e.preventDefault(),s(f.length-1);else if(e.key===`Enter`){e.preventDefault();let t=f[p];if(!t)return;t.action?(t.action(),a()):i(t)}},children:f.length===0?(0,B.jsxs)(`div`,{className:`slash-menu-empty`,children:[`没有匹配「`,e,`」的命令`]}):f.map((e,t)=>(0,B.jsxs)(`button`,{ref:e=>{d.current[t]=e},type:`button`,role:`option`,"aria-selected":t===p,className:`slash-menu-item${t===p?` selected`:``}`,"data-slash-command":e.id,onClick:()=>{e.action?(e.action(),a()):i(e)},onMouseEnter:()=>s(t),children:[(0,B.jsxs)(`span`,{className:`slash-menu-item-id`,children:[`/`,e.id]}),(0,B.jsx)(`span`,{className:`slash-menu-item-sep`,"aria-hidden":`true`,children:` — `}),(0,B.jsx)(`span`,{className:`slash-menu-item-label`,children:e.label}),e.examples?.length?(0,B.jsx)(`span`,{className:`slash-menu-item-examples`,children:e.examples.slice(0,2).join(` · `)}):null]},e.id))})}function hm(){}hm.prototype={diff:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.callback;typeof n==`function`&&(r=n,n={}),this.options=n;var i=this;function a(e){return r?(setTimeout(function(){r(void 0,e)},0),!0):e}e=this.castInput(e),t=this.castInput(t),e=this.removeEmpty(this.tokenize(e)),t=this.removeEmpty(this.tokenize(t));var o=t.length,s=e.length,c=1,l=o+s;n.maxEditLength&&(l=Math.min(l,n.maxEditLength));var u=n.timeout??1/0,d=Date.now()+u,f=[{oldPos:-1,lastComponent:void 0}],p=this.extractCommon(f[0],t,e,0);if(f[0].oldPos+1>=s&&p+1>=o)return a([{value:this.join(t),count:t.length}]);var m=-1/0,h=1/0;function g(){for(var n=Math.max(m,-c);n<=Math.min(h,c);n+=2){var r=void 0,l=f[n-1],u=f[n+1];l&&(f[n-1]=void 0);var d=!1;if(u){var g=u.oldPos-n;d=u&&0<=g&&g<o}var _=l&&l.oldPos+1<s;if(!d&&!_)f[n]=void 0;else{if(r=!_||d&&l.oldPos+1<u.oldPos?i.addToPath(u,!0,void 0,0):i.addToPath(l,void 0,!0,1),p=i.extractCommon(r,t,e,n),r.oldPos+1>=s&&p+1>=o)return a(gm(i,r.lastComponent,t,e,i.useLongestToken));f[n]=r,r.oldPos+1>=s&&(h=Math.min(h,n-1)),p+1>=o&&(m=Math.max(m,n+1))}}c++}if(r)(function e(){setTimeout(function(){if(c>l||Date.now()>d)return r();g()||e()},0)})();else for(;c<=l&&Date.now()<=d;){var _=g();if(_)return _}},addToPath:function(e,t,n,r){var i=e.lastComponent;return i&&i.added===t&&i.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:i.count+1,added:t,removed:n,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:i}}},extractCommon:function(e,t,n,r){for(var i=t.length,a=n.length,o=e.oldPos,s=o-r,c=0;s+1<i&&o+1<a&&this.equals(t[s+1],n[o+1]);)s++,o++,c++;return c&&(e.lastComponent={count:c,previousComponent:e.lastComponent}),e.oldPos=o,s},equals:function(e,t){return this.options.comparator?this.options.comparator(e,t):e===t||this.options.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t},castInput:function(e){return e},tokenize:function(e){return e.split(``)},join:function(e){return e.join(``)}};function gm(e,t,n,r,i){for(var a=[],o;t;)a.push(t),o=t.previousComponent,delete t.previousComponent,t=o;a.reverse();for(var s=0,c=a.length,l=0,u=0;s<c;s++){var d=a[s];if(!d.removed){if(!d.added&&i){var f=n.slice(l,l+d.count);f=f.map(function(e,t){var n=r[u+t];return n.length>e.length?n:e}),d.value=e.join(f)}else d.value=e.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}else if(d.value=e.join(r.slice(u,u+d.count)),u+=d.count,s&&a[s-1].added){var p=a[s-1];a[s-1]=a[s],a[s]=p}}var m=a[c-1];return c>1&&typeof m.value==`string`&&(m.added||m.removed)&&e.equals(``,m.value)&&(a[c-2].value+=m.value,a.pop()),a}new hm;var _m=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,vm=/\S/,ym=new hm;ym.equals=function(e,t){return this.options.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||this.options.ignoreWhitespace&&!vm.test(e)&&!vm.test(t)},ym.tokenize=function(e){for(var t=e.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),n=0;n<t.length-1;n++)!t[n+1]&&t[n+2]&&_m.test(t[n])&&_m.test(t[n+2])&&(t[n]+=t[n+2],t.splice(n+1,2),n--);return t};var bm=new hm;bm.tokenize=function(e){this.options.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
45
|
+
`;)a+=1;continue}if(Gp.has(s))continue;if(s===`begin`){let n=up(e,a),r=n.content,o=`\\end{${r}}`,s=e.indexOf(o,n.next),c=s===-1?e.length:s+o.length;i({type:`math-unsupported`,value:e.slice(t,c),reason:`\\begin{${r}} 不支持`}),a=c;continue}if(s===`frac`||s===`dfrac`||s===`tfrac`||s===`cfrac`){let t=Zp(e,a),n=Zp(e,t.next);a=n.next,i({type:`math-fraction`,numerator:Yp(t.content),denominator:Yp(n.content)});continue}if(s===`sqrt`){let t,n=a;if(e[n]===`[`){let r=Xp(e,n);t=Yp(r.content),n=r.next}let r=Zp(e,n);a=r.next,i({type:`math-root`,...t?{index:t}:{},radicand:Yp(r.content)});continue}if(s===`text`||s===`mathrm`||s===`textrm`||s===`mathbf`||s===`mathit`||s===`mathsf`||s===`mathtt`||s===`operatorname`||s===`textbf`){let t=up(e,a);a=t.next,i({type:`math-text`,value:t.content});continue}if(s in Wp){let t=Zp(e,a);a=t.next;let n=Wp[s];i({type:`math-text`,value:[...t.content].map(n).join(``)});continue}if(s in Kp){let t=Zp(e,a);a=t.next,i({type:`math-text`,value:`${em(Yp(t.content))}${Kp[s]}`});continue}if(s in zp){i({type:`math-identifier`,value:zp[s]});continue}if(s in Bp){let e=Bp[s];/^\d/.test(e)?i({type:`math-number`,value:e}):/^[A-Za-z]/.test(e)?i({type:`math-text`,value:e}):i({type:`math-operator`,value:e});continue}if(Vp.has(s)){i({type:`math-function`,value:s});continue}if(Jp.has(s))continue;i({type:`math-unsupported`,value:`\\${s}`,reason:`\\${s} 不支持`})}else if(o===`{`){let n=up(e,a);t.push(...Yp(n.content)),a=n.next}else if(o===`}`||o===`&`||o===`$`)a+=1;else if(o===`^`||o===`_`){r();let n=Zp(e,a+1);a=n.next,Qp(t,o===`^`?`sup`:`sub`,Yp(n.content))}else qp.has(o)?(i({type:`math-text`,value:o}),a+=1):(n+=o,a+=1)}return r(),t}function Xp(e,t){let n=e.indexOf(`]`,t+1);return n===-1?{content:``,next:e.length}:{content:e.slice(t+1,n),next:n+1}}function Zp(e,t){let n=e[t];if(n===void 0)return{content:``,next:t};if(n===`{`)return up(e,t);let r=/^\\[a-zA-Z]+/.exec(e.slice(t));return r?{content:r[0],next:t+r[0].length}:{content:n,next:t+1}}function Qp(e,t,n){let r=e.pop();if(r){if(r.type===`math-script`)t===`sub`&&!r.sub?e.push({...r,sub:n}):t===`sup`&&!r.sup?e.push({...r,sup:n}):e.push(r);else if(r.type===`math-identifier`||r.type===`math-text`){let i=[...r.value],a=i.pop()??``;i.length&&e.push({type:r.type,value:i.join(``)}),e.push({type:`math-script`,base:[{type:`math-identifier`,value:a}],...t===`sub`?{sub:n}:{sup:n}})}else e.push({type:`math-script`,base:[r],...t===`sub`?{sub:n}:{sup:n}})}}function $p(e){let t=[],n=0;for(;n<e.length;){let r=e.slice(n),i=/^\d+(?:\.\d+)?/.exec(r);if(i){t.push({type:`math-number`,value:i[0]}),n+=i[0].length;continue}let a=/^[A-Za-z]+/.exec(r);if(a){t.push(Vp.has(a[0])?{type:`math-function`,value:a[0]}:{type:`math-identifier`,value:a[0]}),n+=a[0].length;continue}let o=/^[,;:!.'’|()\-+=<>/*]+/.exec(r);o?(t.push({type:`math-operator`,value:o[0]}),n+=o[0].length):(t.push({type:`math-text`,value:r[0]}),n+=1)}return t.reduce((e,t)=>{let n=e[e.length-1];return n?.type===`math-operator`&&t.type===`math-operator`?n.value+=t.value:e.push({...t}),e},[])}function em(e){return e.map(e=>{switch(e.type){case`math-text`:case`math-number`:case`math-identifier`:case`math-operator`:case`math-function`:return e.value;case`math-script`:return`${em(e.base)}${e.sub?`_{${em(e.sub)}}`:``}${e.sup?`^{${em(e.sup)}}`:``}`;case`math-fraction`:return`\\frac{${em(e.numerator)}}{${em(e.denominator)}}`;case`math-root`:return`\\sqrt{${em(e.radicand)}}`;case`math-row-break`:return`\\\\`;case`math-unsupported`:return e.value;default:return``}}).join(``)}function tm({source:e}){let t=(0,z.useMemo)(()=>Np(e),[e]);return(0,B.jsx)(`div`,{className:`md`,"data-md":`1`,children:t.map((e,t)=>im(e,t))})}function nm({source:e}){let t=(0,z.useMemo)(()=>xp(e),[e]);return(0,B.jsx)(`span`,{className:`md md-inline`,children:t.map((e,t)=>om(e,t))})}function rm(e){return np(e).map((e,t)=>e.kind===`plain`?(0,B.jsx)(`span`,{children:e.text},t):(0,B.jsx)(`span`,{className:`code-token-${e.kind}`,children:e.text},t))}function im(e,t){switch(e.type){case`paragraph`:return(0,B.jsx)(`p`,{className:`md-p`,children:e.children.map((e,t)=>om(e,t))},t);case`heading`:{let n=`h${Math.min(6,Math.max(1,e.level))}`;return(0,B.jsx)(n,{className:`md-h md-h${e.level}`,children:e.children.map((e,t)=>om(e,t))},t)}case`code-block`:return(0,B.jsx)(`pre`,{className:`md-pre`,"data-md-lang":e.lang||void 0,children:(0,B.jsx)(`code`,{className:`md-code`,children:rm(e.value)})},t);case`list`:{let n=e.items.map((e,t)=>(0,B.jsx)(`li`,{className:`md-li`,children:e.map((e,t)=>im(e,t))},t));return e.ordered?(0,B.jsx)(`ol`,{className:`md-ol`,start:e.start>1?e.start:void 0,children:n},t):(0,B.jsx)(`ul`,{className:`md-ul`,children:n},t)}case`blockquote`:return(0,B.jsx)(`blockquote`,{className:`md-quote`,children:e.children.map((e,t)=>im(e,t))},t);case`rule`:return(0,B.jsx)(`hr`,{className:`md-rule`},t);case`table`:return(0,B.jsx)(`div`,{className:`md-table-wrap`,children:(0,B.jsxs)(`table`,{className:`md-table`,children:[(0,B.jsx)(`thead`,{children:(0,B.jsx)(`tr`,{children:e.head.map((t,n)=>(0,B.jsx)(`th`,{style:am(e.align[n]),children:t.map((e,t)=>om(e,t))},n))})}),(0,B.jsx)(`tbody`,{children:e.rows.map((t,n)=>(0,B.jsx)(`tr`,{children:t.map((t,n)=>(0,B.jsx)(`td`,{style:am(e.align[n]),children:t.map((e,t)=>om(e,t))},n))},n))})]})},t);case`math-block`:return(0,B.jsx)(sm,{source:e.source},t);default:return null}}var am=e=>e?{textAlign:e}:void 0;function om(e,t){switch(e.type){case`text`:return(0,B.jsx)(z.Fragment,{children:e.value},t);case`code`:return(0,B.jsx)(`code`,{className:`md-code-inline`,children:e.value},t);case`strong`:return(0,B.jsx)(`strong`,{className:`md-strong`,children:e.children.map((e,t)=>om(e,t))},t);case`em`:return(0,B.jsx)(`em`,{className:`md-em`,children:e.children.map((e,t)=>om(e,t))},t);case`del`:return(0,B.jsx)(`del`,{className:`md-del`,children:e.children.map((e,t)=>om(e,t))},t);case`break`:return(0,B.jsx)(`br`,{className:`md-break`},t);case`math`:return(0,B.jsx)(cm,{source:e.source},t);case`link`:{let n=op(e.href);return n?(0,B.jsx)(`a`,{className:`md-link`,href:n,title:e.title,target:`_blank`,rel:`noopener noreferrer nofollow`,children:e.children.map((e,t)=>om(e,t))},t):(0,B.jsx)(z.Fragment,{children:e.children.map((e,t)=>om(e,t))},t)}default:return null}}function sm({source:e}){let t=(0,z.useMemo)(()=>Yp(e),[e]);return(0,B.jsx)(`div`,{className:`md-math md-math-block`,"data-md-math":`block`,"data-md-math-source":e,children:t.map((e,t)=>lm(e,t))})}function cm({source:e}){let t=(0,z.useMemo)(()=>Yp(e),[e]);return(0,B.jsx)(`span`,{className:`md-math md-math-inline`,"data-md-math":`inline`,"data-md-math-source":e,children:t.map((e,t)=>lm(e,t))})}function lm(e,t){switch(e.type){case`math-text`:return(0,B.jsx)(`span`,{className:`md-m-text`,children:e.value},t);case`math-number`:return(0,B.jsx)(`span`,{className:`md-m-number`,children:e.value},t);case`math-identifier`:return(0,B.jsx)(`i`,{className:`md-m-var`,children:e.value},t);case`math-operator`:return(0,B.jsx)(`span`,{className:`md-m-op`,children:e.value},t);case`math-function`:return(0,B.jsx)(`span`,{className:`md-m-fn`,children:e.value},t);case`math-row-break`:return(0,B.jsx)(`br`,{className:`md-m-rowbreak`},t);case`math-unsupported`:return(0,B.jsx)(`span`,{className:`md-m-unsupported`,"data-md-math-unsupported":`1`,title:e.reason,children:e.value},t);case`math-script`:return(0,B.jsxs)(`span`,{className:`md-m-script`,children:[(0,B.jsx)(`span`,{className:`md-m-base`,children:e.base.map((e,t)=>lm(e,t))}),e.sup&&(0,B.jsx)(`sup`,{className:`md-m-sup`,children:e.sup.map((e,t)=>lm(e,t))}),e.sub&&(0,B.jsx)(`sub`,{className:`md-m-sub`,children:e.sub.map((e,t)=>lm(e,t))})]},t);case`math-fraction`:return(0,B.jsxs)(`span`,{className:`md-m-frac`,children:[(0,B.jsx)(`span`,{className:`md-m-num`,children:e.numerator.map((e,t)=>lm(e,t))}),(0,B.jsx)(`span`,{className:`md-m-den`,children:e.denominator.map((e,t)=>lm(e,t))})]},t);case`math-root`:return(0,B.jsxs)(`span`,{className:`md-m-root`,children:[(0,B.jsx)(`span`,{className:`md-m-radical`,children:`√`}),e.index&&(0,B.jsx)(`sup`,{className:`md-m-index`,children:e.index.map((e,t)=>lm(e,t))}),(0,B.jsx)(`span`,{className:`md-m-body`,children:e.radicand.map((e,t)=>lm(e,t))})]},t);default:return null}}var um=[[`help`,`Show help`],[`model`,`Choose model`],[`settings`,`Open settings`],[`clear`,`Clear session`],[`compact`,`Compact context`],[`reload`,`Reload agents`],[`new`,`New session`],[`fork`,`Fork session`],[`resume`,`Resume session`],[`stop`,`Stop run`],[`skill`,`Workspace skill`]].map(([e,t])=>({id:e,label:`/${e} — ${t}`,description:t})),dm=e=>e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLowerCase();function fm(e,t){let n=dm(t.trim());return e.examples?.find(t=>dm(t).includes(n)&&t!==e.id)??e.id}function pm(e,t){let n=dm(t.trim());return n?e.filter(e=>dm(e.id).includes(n)||dm(e.label).includes(n)||e.examples?.some(e=>dm(e).includes(n))):e}function mm({query:e,anchorRect:t,command:n,workspaceId:r,onSelect:i,onClose:a}){let[o,s]=(0,z.useState)(0),[c,l]=(0,z.useState)(um),u=(0,z.useRef)(null),d=(0,z.useRef)([]);(0,z.useEffect)(()=>{let e=!1,t=r?`/api/skills?workspaceId=${encodeURIComponent(r)}`:`/api/skills`;return fetch(t).then(e=>e.ok?e.json():void 0).then(t=>{if(e||!Array.isArray(t?.skills))return;let n=t.skills.map(e=>{let t=e.id?.startsWith(`skill:`)?e.id:`skill:${e.name}`,n=e.description?.trim()||(e.scope===`workspace`?`工作区技能`:`技能`);return{id:t,label:n,description:n,examples:[t]}});l([...um.filter(e=>e.id!==`skill`),...n])}).catch(()=>{}),()=>{e=!0}},[r]);let f=pm([{id:`start`,label:`start — 打开浏览器`,description:`在浏览器中打开 Super Pi 控制台`,action:()=>n({type:`super_pi.start`})},{id:`restart`,label:`restart — 重启 Super Pi 服务`,description:`停掉并重新启动服务,加载磁盘上的新代码`,action:()=>n({type:`super_pi.restart`})},{id:`update`,label:`update — 更新 Super Pi`,description:`运行 npm install -g @evandu/super-pi 然后重启`,action:()=>n({type:`super_pi.update`})},...c],e),p=f.length===0?-1:Math.min(Math.max(o,0),f.length-1),m=e=>s(t=>f.length?Math.min(Math.max(t+e,0),f.length-1):0);(0,z.useEffect)(()=>{let e=e=>{u.current?.contains(e.target)||a()};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[a]),(0,z.useEffect)(()=>{s(0)},[e]),(0,z.useLayoutEffect)(()=>{p>=0&&d.current[p]?.scrollIntoView({block:`nearest`})},[p]);let h={position:`fixed`,left:Math.max(8,Math.min(t.left,window.innerWidth-360)),bottom:Math.max(8,window.innerHeight-t.top+6),zIndex:200};return(0,B.jsx)(`div`,{ref:u,className:`slash-menu`,style:h,role:`listbox`,"aria-label":`斜杠命令`,onKeyDown:e=>{if(e.key===`Escape`)e.preventDefault(),a();else if(e.key===`ArrowDown`)e.preventDefault(),m(1);else if(e.key===`ArrowUp`)e.preventDefault(),m(-1);else if(e.key===`Home`)e.preventDefault(),s(0);else if(e.key===`End`)e.preventDefault(),s(f.length-1);else if(e.key===`Enter`){e.preventDefault();let t=f[p];if(!t)return;t.action?(t.action(),a()):i(t)}},children:f.length===0?(0,B.jsxs)(`div`,{className:`slash-menu-empty`,children:[`没有匹配「`,e,`」的命令`]}):f.map((e,t)=>(0,B.jsxs)(`button`,{ref:e=>{d.current[t]=e},type:`button`,role:`option`,"aria-selected":t===p,className:`slash-menu-item${t===p?` selected`:``}`,"data-slash-command":e.id,onClick:()=>{e.action?(e.action(),a()):i(e)},onMouseEnter:()=>s(t),children:[(0,B.jsxs)(`span`,{className:`slash-menu-item-id`,children:[`/`,e.id]}),(0,B.jsx)(`span`,{className:`slash-menu-item-sep`,"aria-hidden":`true`,children:` — `}),(0,B.jsx)(`span`,{className:`slash-menu-item-label`,children:e.label}),e.examples?.length?(0,B.jsx)(`span`,{className:`slash-menu-item-examples`,children:e.examples.slice(0,2).join(` · `)}):null]},e.id))})}function hm(){}hm.prototype={diff:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.callback;typeof n==`function`&&(r=n,n={}),this.options=n;var i=this;function a(e){return r?(setTimeout(function(){r(void 0,e)},0),!0):e}e=this.castInput(e),t=this.castInput(t),e=this.removeEmpty(this.tokenize(e)),t=this.removeEmpty(this.tokenize(t));var o=t.length,s=e.length,c=1,l=o+s;n.maxEditLength&&(l=Math.min(l,n.maxEditLength));var u=n.timeout??1/0,d=Date.now()+u,f=[{oldPos:-1,lastComponent:void 0}],p=this.extractCommon(f[0],t,e,0);if(f[0].oldPos+1>=s&&p+1>=o)return a([{value:this.join(t),count:t.length}]);var m=-1/0,h=1/0;function g(){for(var n=Math.max(m,-c);n<=Math.min(h,c);n+=2){var r=void 0,l=f[n-1],u=f[n+1];l&&(f[n-1]=void 0);var d=!1;if(u){var g=u.oldPos-n;d=u&&0<=g&&g<o}var _=l&&l.oldPos+1<s;if(!d&&!_)f[n]=void 0;else{if(r=!_||d&&l.oldPos+1<u.oldPos?i.addToPath(u,!0,void 0,0):i.addToPath(l,void 0,!0,1),p=i.extractCommon(r,t,e,n),r.oldPos+1>=s&&p+1>=o)return a(gm(i,r.lastComponent,t,e,i.useLongestToken));f[n]=r,r.oldPos+1>=s&&(h=Math.min(h,n-1)),p+1>=o&&(m=Math.max(m,n+1))}}c++}if(r)(function e(){setTimeout(function(){if(c>l||Date.now()>d)return r();g()||e()},0)})();else for(;c<=l&&Date.now()<=d;){var _=g();if(_)return _}},addToPath:function(e,t,n,r){var i=e.lastComponent;return i&&i.added===t&&i.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:i.count+1,added:t,removed:n,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:i}}},extractCommon:function(e,t,n,r){for(var i=t.length,a=n.length,o=e.oldPos,s=o-r,c=0;s+1<i&&o+1<a&&this.equals(t[s+1],n[o+1]);)s++,o++,c++;return c&&(e.lastComponent={count:c,previousComponent:e.lastComponent}),e.oldPos=o,s},equals:function(e,t){return this.options.comparator?this.options.comparator(e,t):e===t||this.options.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t},castInput:function(e){return e},tokenize:function(e){return e.split(``)},join:function(e){return e.join(``)}};function gm(e,t,n,r,i){for(var a=[],o;t;)a.push(t),o=t.previousComponent,delete t.previousComponent,t=o;a.reverse();for(var s=0,c=a.length,l=0,u=0;s<c;s++){var d=a[s];if(!d.removed){if(!d.added&&i){var f=n.slice(l,l+d.count);f=f.map(function(e,t){var n=r[u+t];return n.length>e.length?n:e}),d.value=e.join(f)}else d.value=e.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}else if(d.value=e.join(r.slice(u,u+d.count)),u+=d.count,s&&a[s-1].added){var p=a[s-1];a[s-1]=a[s],a[s]=p}}var m=a[c-1];return c>1&&typeof m.value==`string`&&(m.added||m.removed)&&e.equals(``,m.value)&&(a[c-2].value+=m.value,a.pop()),a}new hm;var _m=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,vm=/\S/,ym=new hm;ym.equals=function(e,t){return this.options.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||this.options.ignoreWhitespace&&!vm.test(e)&&!vm.test(t)},ym.tokenize=function(e){for(var t=e.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),n=0;n<t.length-1;n++)!t[n+1]&&t[n+2]&&_m.test(t[n])&&_m.test(t[n+2])&&(t[n]+=t[n+2],t.splice(n+1,2),n--);return t};var bm=new hm;bm.tokenize=function(e){this.options.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
46
46
|
`));var t=[],n=e.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var r=0;r<n.length;r++){var i=n[r];r%2&&!this.options.newlineIsToken?t[t.length-1]+=i:(this.options.ignoreWhitespace&&(i=i.trim()),t.push(i))}return t};function xm(e,t,n){return bm.diff(e,t,n)}var Sm=new hm;Sm.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var Cm=new hm;Cm.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function wm(e){"@babel/helpers - typeof";return wm=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},wm(e)}var Tm=Object.prototype.toString,Em=new hm;Em.useLongestToken=!0,Em.tokenize=bm.tokenize,Em.castInput=function(e){var t=this.options,n=t.undefinedReplacement,r=t.stringifyReplacer,i=r===void 0?function(e,t){return t===void 0?n:t}:r;return typeof e==`string`?e:JSON.stringify(Dm(e,null,null,i),i,` `)},Em.equals=function(e,t){return hm.prototype.equals.call(Em,e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`))};function Dm(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i,e));for(var a=0;a<t.length;a+=1)if(t[a]===e)return n[a];var o;if(Tm.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=Dm(e[a],t,n,r,i);return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),wm(e)===`object`&&e!==null){t.push(e),o={},n.push(o);var s=[],c;for(c in e)e.hasOwnProperty(c)&&s.push(c);for(s.sort(),a=0;a<s.length;a+=1)c=s[a],o[c]=Dm(e[c],t,n,r,c);t.pop(),n.pop()}else o=e;return o}var Om=new hm;Om.tokenize=function(e){return e.slice()},Om.join=Om.removeEmpty=function(e){return e};function km(e,t){let n=xm(e??``,t??``),r=[],i=0,a=0,o=1,s=1;for(let e of n){let t=e.value.split(`
|
|
47
|
-
`),n=t.length>0&&t[t.length-1]===``;n&&t.pop();for(let c=0;c<t.length;c+=1){let l=t[c],u=c===t.length-1&&!n;e.added?(r.push({kind:`added`,text:l,newLine:s,noNewline:u}),s+=1,i+=1):e.removed?(r.push({kind:`removed`,text:l,oldLine:o,noNewline:u}),o+=1,a+=1):(r.push({kind:`same`,text:l,oldLine:o,newLine:s,noNewline:u}),o+=1,s+=1)}}return{lines:r,added:i,removed:a,identical:i===0&&a===0}}function Am(e,t=3){let n=new Set;e.lines.forEach((r,i)=>{if(r.kind!==`same`)for(let r=-t;r<=t;r+=1){let t=i+r;t>=0&&t<e.lines.length&&n.add(t)}});let r=[],i=0,a=!1;return e.lines.forEach((e,t)=>{n.has(t)?(a&&=(r.push({kind:`fold`,text:`⋯ 省略未改动的行`}),!1),r.push(e)):a||(a=!0,i+=1)}),a&&r.push({kind:`fold`,text:`⋯ 省略未改动的行`}),{lines:r,folded:i}}function jm(e){return Array.isArray?Array.isArray(e):Vm(e)===`[object Array]`}function Mm(e){if(typeof e==`string`)return e;if(typeof e==`bigint`)return e.toString();let t=e+``;return t==`0`&&1/e==-1/0?`-0`:t}function Nm(e){return e==null?``:Mm(e)}function Pm(e){return typeof e==`string`}function Fm(e){return typeof e==`number`}function Im(e){return e===!0||e===!1||Rm(e)&&Vm(e)==`[object Boolean]`}function Lm(e){return typeof e==`object`}function Rm(e){return Lm(e)&&e!==null}function zm(e){return e!=null}function Bm(e){return!e.trim().length}function Vm(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:Object.prototype.toString.call(e)}var Hm=`Incorrect 'index' type`,Um=`Invalid doc index: must be a non-negative integer within the bounds of the docs array`,Wm=e=>`Invalid value for key ${e}`,Gm=e=>`Pattern length exceeds max of ${e}.`,Km=e=>`Missing ${e} property in key`,qm=e=>`Property 'weight' in key '${e}' must be a positive integer`,Jm=`Fuse.match does not support useTokenSearch: token search requires corpus-level statistics (df, fieldCount) that a one-off string comparison does not have. Use new Fuse(...).search(...) instead.`,Ym=Object.prototype.hasOwnProperty,Xm=class{constructor(e){this._keys=[],this._keyMap={};let t=0;e.forEach(e=>{let n=Zm(e);this._keys.push(n),this._keyMap[n.id]=n,t+=n.weight}),this._keys.forEach(e=>{e.weight/=t})}get(e){return this._keyMap[e]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};function Zm(e){let t=null,n=null,r=null,i=1,a=null;if(Pm(e)||jm(e))r=e,t=Qm(e),n=$m(e);else{if(!Ym.call(e,`name`))throw Error(Km(`name`));let o=e.name;if(r=o,Ym.call(e,`weight`)&&e.weight!==void 0&&(i=e.weight,i<=0))throw Error(qm($m(o)));t=Qm(o),n=$m(o),a=e.getFn??null}return{path:t,id:n,weight:i,src:r,getFn:a}}function Qm(e){return jm(e)?e:e.split(`.`)}function $m(e){return jm(e)?e.join(`.`):e}function eh(e,t){let n=[],r=!1,i=(e,t,a,o)=>{if(zm(e)){if(!t[a])n.push(o===void 0?e:{v:e,i:o});else{let s=e[t[a]];if(!zm(s))return;if(a===t.length-1&&(Pm(s)||Fm(s)||Im(s)||typeof s==`bigint`))n.push(o===void 0?Nm(s):{v:Nm(s),i:o});else if(jm(s)){r=!0;for(let e=0,n=s.length;e<n;e+=1)i(s[e],t,a+1,e)}else t.length&&i(s,t,a+1,o)}}};return i(e,Pm(t)?t.split(`.`):t,0),r?n:n[0]}var th={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},nh={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(e,t)=>e.score===t.score?e.idx<t.idx?-1:1:e.score<t.score?-1:1},rh={location:0,threshold:.6,distance:100},ih={useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:`any`,getFn:eh,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1},Y=Object.freeze({...nh,...th,...rh,...ih});function ah(e){return e>=9&&e<=13||e===32||e===160}function oh(e=1,t=3){let n=new Map,r=10**t;return{get(t){let i=0,a=!1;for(let e=0;e<t.length;e++)ah(t.charCodeAt(e))?a=!1:a||=(i++,!0);if(i===0&&(i=1),n.has(i))return n.get(i);let o=Math.round(r/i**(.5*e))/r;return n.set(i,o),o},clear(){n.clear()}}}var sh=class{constructor({getFn:e=Y.getFn,fieldNormWeight:t=Y.fieldNormWeight}={}){this.norm=oh(t,3),this.getFn=e,this.isCreated=!1,this.docs=[],this.keys=[],this._keysMap={},this.setIndexRecords()}setSources(e=[]){this.docs=e}setIndexRecords(e=[]){this.records=e}setKeys(e=[]){this.keys=e,this._keysMap={},e.forEach((e,t)=>{this._keysMap[e.id]=t})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;let e=this.docs.length;this.records=Array(e);let t=0;if(Pm(this.docs[0]))for(let n=0;n<e;n++){let e=this._createStringRecord(this.docs[n],n);e&&(this.records[t++]=e)}else for(let n=0;n<e;n++)this.records[t++]=this._createObjectRecord(this.docs[n],n);this.records.length=t,this.norm.clear()}add(e,t){if(!Number.isInteger(t)||t<0)throw Error(Um);if(Pm(e)){let n=this._createStringRecord(e,t);return n&&this.records.push(n),n}let n=this._createObjectRecord(e,t);return this.records.push(n),n}removeAt(e){if(!Number.isInteger(e)||e<0)throw Error(Um);for(let t=0,n=this.records.length;t<n;t+=1)if(this.records[t].i===e){this.records.splice(t,1);break}for(let t=0,n=this.records.length;t<n;t+=1)this.records[t].i>e&&--this.records[t].i}removeAll(e){let t=new Set;for(let n of e)Number.isInteger(n)&&n>=0&&t.add(n);if(t.size===0)return;this.records=this.records.filter(e=>!t.has(e.i));let n=Array.from(t).sort((e,t)=>e-t);for(let e of this.records){let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i]<e.i?t=i+1:r=i}e.i-=t}}getValueForItemAtKeyId(e,t){return e[this._keysMap[t]]}size(){return this.records.length}_createStringRecord(e,t){return!zm(e)||Bm(e)?null:{v:e,i:t,n:this.norm.get(e)}}_createObjectRecord(e,t){let n={i:t,$:{}};for(let t=0,r=this.keys.length;t<r;t++){let r=this.keys[t],i=r.getFn?r.getFn(e):this.getFn(e,r.path);if(zm(i)){if(jm(i)){let e=[];for(let t=0,n=i.length;t<n;t+=1){let n=i[t];if(zm(n)){if(Pm(n)){if(!Bm(n)){let r={v:n,i:t,n:this.norm.get(n)};e.push(r)}}else if(zm(n.v)){let t=Pm(n.v)?n.v:Nm(n.v);if(!Bm(t)){let r={v:t,i:n.i,n:this.norm.get(t)};e.push(r)}}}}n.$[t]=e}else if(Pm(i)&&!Bm(i)){let e={v:i,n:this.norm.get(i)};n.$[t]=e}}}return n}toJSON(){return{keys:this.keys.map(({getFn:e,...t})=>t),records:this.records}}};function ch(e,t,{getFn:n=Y.getFn,fieldNormWeight:r=Y.fieldNormWeight}={}){let i=new sh({getFn:n,fieldNormWeight:r});return i.setKeys(e.map(Zm)),i.setSources(t),i.create(),i}function lh(e,{getFn:t=Y.getFn,fieldNormWeight:n=Y.fieldNormWeight}={}){let{keys:r,records:i}=e,a=new sh({getFn:t,fieldNormWeight:n});return a.setKeys(r),a.setIndexRecords(i),a}function uh(e=[],t=Y.minMatchCharLength){let n=[],r=-1,i=-1,a=0;for(let o=e.length;a<o;a+=1){let o=e[a];o&&r===-1?r=a:!o&&r!==-1&&(i=a-1,i-r+1>=t&&n.push([r,i]),r=-1)}return e[a-1]&&a-r>=t&&n.push([r,a-1]),n}function dh(e,t,n,{location:r=Y.location,distance:i=Y.distance,threshold:a=Y.threshold,findAllMatches:o=Y.findAllMatches,minMatchCharLength:s=Y.minMatchCharLength,includeMatches:c=Y.includeMatches,ignoreLocation:l=Y.ignoreLocation}={}){if(t.length>32)throw Error(Gm(32));let u=t.length,d=e.length,f=Math.max(0,Math.min(r,d)),p=a,m=f,h=(e,t)=>{let n=e/u;if(l)return n;let r=Math.abs(f-t);return i?n+r/i:r?1:n},g=s>1||c,_=g?Array(d):[],v;for(;(v=e.indexOf(t,m))>-1;){let e=h(0,v);if(p=Math.min(e,p),m=v+u,g){let e=0;for(;e<u;)_[v+e]=1,e+=1}}m=-1;let y=[],b=1,x=0,S=u+d,C=1<<u-1;for(let t=0;t<u;t+=1){let r=0,i=S;for(;r<i;)h(t,f+i)<=p?r=i:S=i,i=Math.floor((S-r)/2+r);S=i;let a=Math.max(1,f-i+1),s=o?d:Math.min(f+i,d)+u,c=Array(s+2);c[s+1]=(1<<t)-1;for(let r=s;r>=a;--r){let i=r-1,o=n[e[i]];if(c[r]=(c[r+1]<<1|1)&o,t&&(c[r]|=(y[r+1]|y[r])<<1|1|y[r+1]),c[r]&C&&(b=h(t,i),b<=p)){if(p=b,m=i,x=t,m<=f)break;a=Math.max(1,2*f-m)}}if(h(t+1,f)>p)break;y=c}if(g&&m>=0){let t=Math.min(d-1,m+u-1+x);for(let r=m;r<=t;r+=1)n[e[r]]&&(_[r]=1)}let w={isMatch:m>=0,score:Math.max(.001,b)};if(g){let e=uh(_,s);e.length?c&&(w.indices=e):w.isMatch=!1}return w}function fh(e){let t={};for(let n=0,r=e.length;n<r;n+=1){let i=e.charAt(n);t[i]=(t[i]||0)|1<<r-n-1}return t}function ph(e){if(e.length<=1)return e;e.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let t=[e[0]];for(let n=1,r=e.length;n<r;n+=1){let r=t[t.length-1],i=e[n];i[0]<=r[1]+1?r[1]=Math.max(r[1],i[1]):t.push(i)}return t}var mh={ł:`l`,Ł:`L`,đ:`d`,Đ:`D`,ø:`o`,Ø:`O`,ħ:`h`,Ħ:`H`,ŧ:`t`,Ŧ:`T`,ı:`i`,ß:`ss`},hh=RegExp(`[`+Object.keys(mh).join(``)+`]`,`g`),gh=typeof String.prototype.normalize==`function`?e=>e.normalize(`NFD`).replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,``).replace(hh,e=>mh[e]):e=>e,_h=class{constructor(e,{location:t=Y.location,threshold:n=Y.threshold,distance:r=Y.distance,includeMatches:i=Y.includeMatches,findAllMatches:a=Y.findAllMatches,minMatchCharLength:o=Y.minMatchCharLength,isCaseSensitive:s=Y.isCaseSensitive,ignoreDiacritics:c=Y.ignoreDiacritics,ignoreLocation:l=Y.ignoreLocation}={}){if(this.options={location:t,threshold:n,distance:r,includeMatches:i,findAllMatches:a,minMatchCharLength:o,isCaseSensitive:s,ignoreDiacritics:c,ignoreLocation:l},e=s?e:e.toLowerCase(),e=c?gh(e):e,this.pattern=e,this.chunks=[],!this.pattern.length)return;let u=(e,t)=>{this.chunks.push({pattern:e,alphabet:fh(e),startIndex:t})},d=this.pattern.length;if(d>32){let e=0,t=d%32,n=d-t;for(;e<n;)u(this.pattern.substr(e,32),e),e+=32;if(t){let e=d-32;u(this.pattern.substr(e),e)}}else u(this.pattern,0)}searchIn(e){let{isCaseSensitive:t,ignoreDiacritics:n,includeMatches:r}=this.options;if(e=t?e:e.toLowerCase(),e=n?gh(e):e,this.pattern===e){if(e.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};let t={isMatch:!0,score:0};return r&&(t.indices=[[0,e.length-1]]),t}let{location:i,distance:a,threshold:o,findAllMatches:s,minMatchCharLength:c,ignoreLocation:l}=this.options,u=[],d=0,f=!1;this.chunks.forEach(({pattern:t,alphabet:n,startIndex:p})=>{let{isMatch:m,score:h,indices:g}=dh(e,t,n,{location:i+p,distance:a,threshold:o,findAllMatches:s,minMatchCharLength:c,includeMatches:r,ignoreLocation:l});m&&(f=!0),d+=h,m&&g&&u.push(...g)});let p={isMatch:f,score:f?d/this.chunks.length:1};return f&&r&&(p.indices=ph(u)),p}},vh=new Set([`fuzzy`,`include`]);function yh(e){return e.startsWith(`inverse`)}var bh=[{type:`exact`,multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:e=>({type:`exact`,search(t){let n=t===e;return{isMatch:n,score:+!n,indices:[0,e.length-1]}}})},{type:`include`,multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:e=>({type:`include`,search(t){let n=0,r,i=[],a=e.length;for(;(r=t.indexOf(e,n))>-1;)n=r+a,i.push([r,n-1]);let o=!!i.length;return{isMatch:o,score:+!o,indices:i}}})},{type:`prefix-exact`,multiRegex:/^\^"(.*)"$/,singleRegex:/^\^(.*)$/,create:e=>({type:`prefix-exact`,search(t){let n=t.startsWith(e);return{isMatch:n,score:+!n,indices:[0,e.length-1]}}})},{type:`inverse-prefix-exact`,multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:e=>({type:`inverse-prefix-exact`,search(t){let n=!t.startsWith(e);return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`inverse-suffix-exact`,multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:e=>({type:`inverse-suffix-exact`,search(t){let n=!t.endsWith(e);return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`suffix-exact`,multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:e=>({type:`suffix-exact`,search(t){let n=t.endsWith(e);return{isMatch:n,score:+!n,indices:[t.length-e.length,t.length-1]}}})},{type:`inverse-exact`,multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:e=>({type:`inverse-exact`,search(t){let n=t.indexOf(e)===-1;return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`fuzzy`,multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(e,t={})=>{let n=new _h(e,{location:t.location??Y.location,threshold:t.threshold??Y.threshold,distance:t.distance??Y.distance,includeMatches:t.includeMatches??Y.includeMatches,findAllMatches:t.findAllMatches??Y.findAllMatches,minMatchCharLength:t.minMatchCharLength??Y.minMatchCharLength,isCaseSensitive:t.isCaseSensitive??Y.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics??Y.ignoreDiacritics,ignoreLocation:t.ignoreLocation??Y.ignoreLocation});return{type:`fuzzy`,search(e){return n.searchIn(e)}}}}],xh=bh.length,Sh=`\0`,Ch=`|`;function wh(e){let t=[],n=e.length,r=0;for(;r<n;){for(;r<n&&e[r]===` `;)r++;if(r>=n)break;let i=r;for(;i<n&&e[i]!==` `&&e[i]!==`"`;)i++;if(i<n&&e[i]===`"`){for(i++;i<n;){if(e[i]===`"`){let t=i+1;if(t>=n||e[t]===` `){i++;break}if(e[t]===`$`&&(t+1>=n||e[t+1]===` `)){i+=2;break}}i++}t.push(e.substring(r,i)),r=i}else{for(;i<n&&e[i]!==` `;)i++;t.push(e.substring(r,i)),r=i}}return t}function Th(e,t){let n=e.match(t);return n?n[1]:null}function Eh(e,t={}){return e.replace(/\\\|/g,Sh).split(Ch).map(e=>{let n=wh(e.replace(/\u0000/g,`|`).trim()).filter(e=>e&&!!e.trim()),r=[];for(let e=0,i=n.length;e<i;e+=1){let i=n[e],a=!1,o=-1;for(;!a&&++o<xh;){let e=bh[o],n=Th(i,e.multiRegex);n&&(r.push(e.create(n,t)),a=!0)}if(!a)for(o=-1;++o<xh;){let e=bh[o],n=Th(i,e.singleRegex);if(n){r.push(e.create(n,t));break}}}return r})}var Dh=class{constructor(e,{isCaseSensitive:t=Y.isCaseSensitive,ignoreDiacritics:n=Y.ignoreDiacritics,includeMatches:r=Y.includeMatches,minMatchCharLength:i=Y.minMatchCharLength,ignoreLocation:a=Y.ignoreLocation,findAllMatches:o=Y.findAllMatches,location:s=Y.location,threshold:c=Y.threshold,distance:l=Y.distance}={}){this.query=null,this.options={isCaseSensitive:t,ignoreDiacritics:n,includeMatches:r,minMatchCharLength:i,findAllMatches:o,ignoreLocation:a,location:s,threshold:c,distance:l},e=t?e:e.toLowerCase(),e=n?gh(e):e,this.pattern=e,this.query=Eh(this.pattern,this.options)}static condition(e,t){return t.useExtendedSearch}searchIn(e){let t=this.query;if(!t)return{isMatch:!1,score:1};let{includeMatches:n,isCaseSensitive:r,ignoreDiacritics:i}=this.options;e=r?e:e.toLowerCase(),e=i?gh(e):e;let a=0,o=[],s=0,c=!1;for(let r=0,i=t.length;r<i;r+=1){let i=t[r];o.length=0,a=0,c=!1;for(let t=0,r=i.length;t<r;t+=1){let r=i[t],{isMatch:l,indices:u,score:d}=r.search(e);if(l)a+=1,s+=d,yh(r.type)&&(c=!0),n&&(vh.has(r.type)?o.push(...u):o.push(u));else{s=0,a=0,o.length=0,c=!1;break}}if(a){let e={isMatch:!0,score:s/a};return c&&(e.hasInverse=!0),n&&(e.indices=ph(o)),e}}return{isMatch:!1,score:1}}},Oh=[];function kh(...e){Oh.push(...e)}function Ah(e,t){for(let n=0,r=Oh.length;n<r;n+=1){let r=Oh[n];if(r.condition(e,t))return new r(e,t)}return new _h(e,t)}var jh={AND:`$and`,OR:`$or`},Mh={PATH:`$path`,PATTERN:`$val`},Nh=e=>!!(e[jh.AND]||e[jh.OR]),Ph=e=>!!e[Mh.PATH],Fh=e=>!jm(e)&&Lm(e)&&!Nh(e),Ih=e=>({[jh.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function Lh(e,t,{auto:n=!0}={}){let r=e=>{if(Pm(e)){let r={keyId:null,pattern:e};return n&&(r.searcher=Ah(e,t)),r}let i=Object.keys(e),a=Ph(e);if(!a&&i.length>1&&!Nh(e))return r(Ih(e));if(Fh(e)){let r=a?e[Mh.PATH]:i[0],o=a?e[Mh.PATTERN]:e[r];if(!Pm(o))throw Error(Wm(r));let s={keyId:$m(r),pattern:o};return n&&(s.searcher=Ah(o,t)),s}let o={children:[],operator:i[0]};return i.forEach(t=>{let n=e[t];jm(n)&&n.forEach(e=>{o.children.push(r(e))})}),o};return Nh(e)||(e=Ih(e)),r(e)}function Rh(e,{ignoreFieldNorm:t=Y.ignoreFieldNorm}){let n=1;return e.forEach(({key:e,norm:r,score:i})=>{let a=e?e.weight:null;n*=(i===0&&a?2**-52:i)**+((a||1)*(t?1:r))}),n}function zh(e,{ignoreFieldNorm:t=Y.ignoreFieldNorm}){e.forEach(e=>{e.score=Rh(e.matches,{ignoreFieldNorm:t})})}var Bh=class{constructor(e,t){this.limit=e,this.heap=[],this.comparator=t}get size(){return this.heap.length}insert(e){this.size<this.limit?(this.heap.push(e),this._bubbleUp(this.size-1)):this.comparator(e,this.heap[0])<0&&(this.heap[0]=e,this._sinkDown(0))}extractSorted(){return this.heap.sort(this.comparator)}_bubbleUp(e){let t=this.heap;for(;e>0;){let n=e-1>>1;if(this.comparator(t[e],t[n])<=0)break;let r=t[e];t[e]=t[n],t[n]=r,e=n}}_sinkDown(e){let t=this.heap,n=t.length,r=e;do{e=r;let i=2*e+1,a=2*e+2;if(i<n&&this.comparator(t[i],t[r])>0&&(r=i),a<n&&this.comparator(t[a],t[r])>0&&(r=a),r!==e){let n=t[e];t[e]=t[r],t[r]=n}}while(r!==e)}};function Vh(e){let t=[];return e.matches.forEach(e=>{if(!zm(e.indices)||!e.indices.length)return;let n={indices:e.indices,value:e.value};e.key&&(n.key=e.key.id),e.idx>-1&&(n.refIndex=e.idx),t.push(n)}),t}function Hh(e,t,{includeMatches:n=Y.includeMatches,includeScore:r=Y.includeScore}={}){return e.map(e=>{let{idx:i}=e,a={item:t[i],refIndex:i};return n&&(a.matches=Vh(e)),r&&(a.score=e.score),a})}var Uh=/[\p{L}\p{M}\p{N}_]+/gu,Wh=new WeakSet;function Gh(e){Wh.has(e)||(Wh.add(e),console.warn(`[Fuse] tokenize regex ${e} lacks the global flag; only the first match per text will be returned. Add the 'g' flag.`))}function Kh(e){if(typeof e==`function`){let t=!1;return n=>{let r=e(n);if(!t&&(t=!0,!Array.isArray(r)||r.some(e=>typeof e!=`string`)))throw Error(`[Fuse] tokenize function must return string[]; received ${Array.isArray(r)?`array containing non-strings`:typeof r}.`);return r}}return e instanceof RegExp?(e.global||Gh(e),t=>t.match(e)||[]):e=>e.match(Uh)||[]}function qh({isCaseSensitive:e=!1,ignoreDiacritics:t=!1,tokenize:n}={}){let r=Kh(n);return{tokenize(n){return e||(n=n.toLowerCase()),t&&(n=gh(n)),r(n)}}}var Jh=class{static condition(e,t){return t.useTokenSearch}constructor(e,t){this.options=t,this.analyzer=qh({isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,tokenize:t.tokenize});let n=this.analyzer.tokenize(e),{df:r,fieldCount:i}=t._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(let e of n){this.termSearchers.push(new _h(e,{location:t.location,threshold:t.threshold,distance:t.distance,includeMatches:t.includeMatches,findAllMatches:t.findAllMatches,minMatchCharLength:t.minMatchCharLength,isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,ignoreLocation:!0}));let n=r.get(e)||0,a=Math.log(1+(i-n+.5)/(n+.5));this.idfWeights.push(a)}this.combineAll=t.tokenMatch===`all`,this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(e){if(!this.termSearchers.length)return{isMatch:!1,score:1};let t=[],n=0,r=0,i=0,a=0,o=this.combineAll&&!this.useMask?new Set:null;for(let s=0;s<this.termSearchers.length;s++){let c=this.termSearchers[s].searchIn(e),l=this.idfWeights[s];r+=l,c.isMatch&&(i++,n+=l*(1-c.score),c.indices&&t.push(...c.indices),this.combineAll&&(this.useMask?a|=1<<s:o.add(s)))}if(i===0)return{isMatch:!1,score:1};let s=r>0?1-n/r:0,c={isMatch:!0,score:Math.max(.001,s)};return this.options.includeMatches&&t.length&&(c.indices=ph(t)),this.combineAll&&(this.useMask?c.matchedMask=a:c.matchedTerms=o,c.termCount=this.numTerms),c}};function Yh(e,t,n,r){let i=r.tokenize(t);if(!i.length)return;e.fieldCount++,e.docFieldCount.set(n,(e.docFieldCount.get(n)||0)+1);let a=new Set(i),o=e.docTermFieldHits.get(n);o||(o=new Map,e.docTermFieldHits.set(n,o));for(let t of a)o.set(t,(o.get(t)||0)+1),e.df.set(t,(e.df.get(t)||0)+1)}function Xh(e,t,n,r){let{i,v:a,$:o}=t;if(a!==void 0)Yh(e,a,i,r);else if(o)for(let t=0;t<n;t++){let n=o[t];if(n){if(Array.isArray(n))for(let t of n)Yh(e,t.v,i,r);else Yh(e,n.v,i,r)}}}function Zh(e,t,n){let r={fieldCount:0,df:new Map,docFieldCount:new Map,docTermFieldHits:new Map};for(let i of e)Xh(r,i,t,n);return r}function Qh(e,t,n,r){Xh(e,t,n,r)}function $h(e,t){let n=e.docFieldCount.get(t);if(n===void 0)return;e.fieldCount-=n,e.docFieldCount.delete(t);let r=e.docTermFieldHits.get(t);if(r){for(let[t,n]of r){let r=(e.df.get(t)||0)-n;r<=0?e.df.delete(t):e.df.set(t,r)}e.docTermFieldHits.delete(t)}}function eg(e,t){if(t.length===0)return;let n=Array.from(new Set(t)).sort((e,t)=>e-t);for(let t of n)$h(e,t);let r=e=>{let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i]<e?t=i+1:r=i}return e-t},i=n[0],a=new Map;for(let[t,n]of e.docFieldCount)a.set(t>i?r(t):t,n);e.docFieldCount=a;let o=new Map;for(let[t,n]of e.docTermFieldHits)o.set(t>i?r(t):t,n);e.docTermFieldHits=o}var tg=class{constructor(e,t,n){this.options={...Y,...t},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new Xm(this.options.keys),this._docs=e,this._myIndex=null,this._invertedIndex=null,this.setCollection(e,n),this._lastQuery=null,this._lastSearcher=null}_getSearcher(e){if(this._lastQuery===e)return this._lastSearcher;let t=Ah(e,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=e,this._lastSearcher=t,t}setCollection(e,t){if(this._docs=e,t&&!(t instanceof sh))throw Error(Hm);if(this._myIndex=t||ch(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){let e=qh({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=Zh(this._myIndex.records,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}add(e){if(!zm(e))return;this._docs.push(e);let t=this._myIndex.add(e,this._docs.length-1);if(this._invertedIndex&&t){let e=qh({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});Qh(this._invertedIndex,t,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}remove(e=()=>!1){let t=[],n=[];for(let r=0,i=this._docs.length;r<i;r+=1)e(this._docs[r],r)&&(t.push(this._docs[r]),n.push(r));if(n.length){this._invertedIndex&&eg(this._invertedIndex,n);let e=new Set(n);this._docs=this._docs.filter((t,n)=>!e.has(n)),this._myIndex.removeAll(n),this._invalidateSearcherCache()}return t}removeAt(e){if(!Number.isInteger(e)||e<0||e>=this._docs.length)throw Error(Um);this._invertedIndex&&eg(this._invertedIndex,[e]);let t=this._docs.splice(e,1)[0];return this._myIndex.removeAt(e),this._invalidateSearcherCache(),t}_invalidateSearcherCache(){this._lastQuery=null,this._lastSearcher=null}getIndex(){return this._myIndex}_normalizedKeys(){return this._myIndex.keys.map(e=>this._keyStore.get(e.id)||e)}search(e,t){let{limit:n=-1}=t||{},{includeMatches:r,includeScore:i,shouldSort:a,sortFn:o,ignoreFieldNorm:s}=this.options;if(Pm(e)&&!e.trim()){let e=this._docs.map((e,t)=>({item:e,refIndex:t}));return Fm(n)&&n>-1&&(e=e.slice(0,n)),e}let c=a&&Fm(n)&&n>0&&Pm(e),l=o,u=(e,t)=>l(e,t)||e.idx-t.idx,d;if(c){let t=new Bh(n,u);Pm(this._docs[0])?this._searchStringList(e,{heap:t,ignoreFieldNorm:s}):this._searchObjectList(e,{heap:t,ignoreFieldNorm:s}),d=t.extractSorted()}else d=Pm(e)?Pm(this._docs[0])?this._searchStringList(e):this._searchObjectList(e):this._searchLogical(e),zh(d,{ignoreFieldNorm:s}),a&&d.sort(Pm(e)?u:l),Fm(n)&&n>-1&&(d=d.slice(0,n));return Hh(d,this._docs,{includeMatches:r,includeScore:i})}_searchStringList(e,{heap:t,ignoreFieldNorm:n}={}){let r=this._getSearcher(e),i=this.options.useTokenSearch&&this.options.tokenMatch===`all`,{records:a}=this._myIndex,o=t?null:[];return a.forEach(({v:e,i:a,n:s})=>{if(!zm(e))return;let c=r.searchIn(e);if(c.isMatch){let r={score:c.score,value:e,norm:s,indices:c.indices};i&&(r.matchedMask=c.matchedMask,r.matchedTerms=c.matchedTerms,r.termCount=c.termCount);let l=[r];if(!i||this._coversAllTokens(l)){let r={item:e,idx:a,matches:l};t?(r.score=Rh(r.matches,{ignoreFieldNorm:n}),t.insert(r)):o.push(r)}}}),o}_searchLogical(e){let t=Lh(e,this.options),n=this._normalizedKeys(),r=(e,t,i)=>{if(!(`children`in e)){let{keyId:r,searcher:a}=e,o;return r===null?(o=[],n.forEach((e,n)=>{o.push(...this._findMatches({key:e,value:t[n],searcher:a}))})):o=this._findMatches({key:this._keyStore.get(r),value:this._myIndex.getValueForItemAtKeyId(t,r),searcher:a}),o&&o.length?[{idx:i,item:t,matches:o}]:[]}let{children:a,operator:o}=e,s=[];for(let e=0,n=a.length;e<n;e+=1){let n=a[e],c=r(n,t,i);if(c.length)s.push(...c);else if(o===jh.AND)return[]}return s},i=this._myIndex.records,a=new Map,o=[];return i.forEach(({$:e,i:n})=>{if(zm(e)){let i=r(t,e,n);i.length&&(a.has(n)||(a.set(n,{idx:n,item:e,matches:[]}),o.push(a.get(n))),i.forEach(({matches:e})=>{a.get(n).matches.push(...e)}))}}),o}_searchObjectList(e,{heap:t,ignoreFieldNorm:n}={}){let r=this._getSearcher(e),i=this.options.useTokenSearch&&this.options.tokenMatch===`all`,{records:a}=this._myIndex,o=this._normalizedKeys(),s=t?null:[];return a.forEach(({$:e,i:a})=>{if(!zm(e))return;let c=[],l=!1,u=!1;if(o.forEach((t,n)=>{let i=this._findMatches({key:t,value:e[n],searcher:r});i.length?(c.push(...i),i[0].hasInverse&&(u=!0)):l=!0}),!(u&&l)&&c.length&&(!i||this._coversAllTokens(c))){let r={idx:a,item:e,matches:c};t?(r.score=Rh(r.matches,{ignoreFieldNorm:n}),t.insert(r)):s.push(r)}}),s}_findMatches({key:e,value:t,searcher:n}){if(!zm(t))return[];let r=[];if(jm(t))t.forEach(({v:t,i,n:a})=>{if(!zm(t))return;let o=n.searchIn(t);if(o.isMatch){let n={score:o.score,key:e,value:t,idx:i,norm:a,indices:o.indices,hasInverse:o.hasInverse};o.termCount!==void 0&&(n.matchedMask=o.matchedMask,n.matchedTerms=o.matchedTerms,n.termCount=o.termCount),r.push(n)}});else{let{v:i,n:a}=t,o=n.searchIn(i);if(o.isMatch){let t={score:o.score,key:e,value:i,norm:a,indices:o.indices,hasInverse:o.hasInverse};o.termCount!==void 0&&(t.matchedMask=o.matchedMask,t.matchedTerms=o.matchedTerms,t.termCount=o.termCount),r.push(t)}}return r}_coversAllTokens(e){let t=e.length?e[0].termCount:void 0;if(t===void 0)return!0;if(t<=31){let n=0;for(let t=0;t<e.length;t++)n|=e[t].matchedMask||0;return n===2**t-1}let n=new Set;for(let t=0;t<e.length;t++){let r=e[t].matchedTerms;if(r)for(let e of r)n.add(e)}return n.size===t}};tg.version=`7.5.0`,tg.createIndex=ch,tg.parseIndex=lh,tg.config=Y,tg.match=function(e,t,n){if(n&&n.useTokenSearch)throw Error(Jm);return Ah(e,{...Y,...n}).searchIn(t)},tg.parseQuery=Lh,kh(Dh),kh(Jh),tg.use=function(...e){e.forEach(e=>kh(e))};var ng=tg,rg=`modulepreload`,ig=function(e){return`/`+e},ag={},og=function(e){return e.pathname.endsWith(`.css`)},sg=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},cg=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=ig(t,n);let r=s(t),i=og(r);return sg(ag,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:rg,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},lg=4e3,ug=(0,z.lazy)(()=>cg(()=>import(`./CodeMirrorEditor-CaF1aTpR.js`).then(e=>({default:e.CodeMirrorEditor})),[])),dg=class extends Error{status;body;constructor(e,t){super(t.error||`HTTP ${e}`),this.status=e,this.body=t,this.name=`ApiError`}},fg=15e3,pg=e=>new dg(408,{error:`请求超时:${fg/1e3} 秒内服务端没有响应`,code:`timeout`,details:{path:e}});async function mg(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),fg);try{let r=await fetch(e,{...t,signal:n.signal}),i;try{i=await r.json()}catch{i=void 0}if(!r.ok)throw new dg(r.status,i??{error:`HTTP ${r.status}`});return i}catch(t){throw n.signal.aborted?pg(e):t}finally{clearTimeout(r)}}var hg=e=>e instanceof dg?e:new dg(0,{error:e instanceof Error?e.message:`读取失败`}),gg=e=>encodeURIComponent(e),_g=(e,t)=>`/api/files?workspaceId=${gg(e)}&path=${gg(t)}`,vg=(e,t)=>`/api/file?workspaceId=${gg(e)}&path=${gg(t)}`,yg=(e,t)=>`/api/file?workspaceId=${gg(e)}&path=${gg(t)}&meta=1`,bg=(e,t)=>`/api/files?workspaceId=${gg(e)}&q=${gg(t)}`,xg=e=>e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(1)} MB`,Sg=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?``:new Date(e).toLocaleTimeString(`zh-CN`,{hour:`2-digit`,minute:`2-digit`})};function Cg({workspaceId:e,entryPath:t,name:n,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:u,depth:d}){let f=r[t],p=i.has(t);return(0,z.useEffect)(()=>{p&&f===void 0&&o(t)},[p,t,f,o]),(0,B.jsxs)(`li`,{className:`file-node`,"data-file-dir":t,"data-file-dir-changed":c.has(t)?`1`:`0`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`file-row file-row-dir`,"data-file-dir-toggle":t,"aria-expanded":p,style:{paddingLeft:`${8+d*13}px`},title:c.has(t)?`${t} 里有 agent 改过的文件`:t,onClick:()=>a(t),children:[(0,B.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`,children:p?`▾`:`▸`}),(0,B.jsx)(`span`,{className:`file-name`,children:n}),c.has(t)&&(0,B.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-dir-changed-badge":t,title:`里面有 agent 改过的文件`,children:`✎`})]}),p&&(0,B.jsx)(`ul`,{className:`file-children`,children:f===void 0?(0,B.jsx)(`li`,{className:`file-row-loading`,"data-file-loading":t,children:`读取中…`}):`error`in f?(0,B.jsx)(`li`,{className:`file-row-error`,"data-file-error":t,children:f.error.message}):f.entries.length===0?(0,B.jsx)(`li`,{className:`file-row-empty`,"data-file-empty":t,children:`空目录`}):(0,B.jsxs)(B.Fragment,{children:[f.truncated&&(0,B.jsx)(`li`,{className:`file-row-empty`,"data-file-truncated":t,children:`条目过多,只显示前一部分`}),f.entries.map(t=>t.kind===`directory`?(0,B.jsx)(Cg,{workspaceId:e,entryPath:t.path,name:t.name,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:u,depth:d+1},t.path):(0,B.jsx)(wg,{entry:t,depth:d+1,openPaths:s,changedPaths:l,onOpen:u},t.path))]})})]})}function wg({entry:e,depth:t,openPaths:n,changedPaths:r,onOpen:i}){if(e.kind===`symlink`)return(0,B.jsx)(`li`,{className:`file-node`,"data-file-entry":e.path,"data-file-outside":e.path,children:(0,B.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,disabled:!0,title:`${e.path} 是一个指向 workspace 之外的符号链接,不能打开`,style:{paddingLeft:`${8+t*13}px`},children:[(0,B.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,B.jsx)(`span`,{className:`file-name`,children:e.name}),(0,B.jsx)(`span`,{className:`file-badge`,"data-file-outside-badge":`1`,children:`外部链接`})]})});let a=n.has(e.path),o=r.has(e.path);return(0,B.jsx)(`li`,{className:`file-node`,"data-file-entry":e.path,"data-file-row-open":a?`1`:`0`,"data-file-row-changed":o?`1`:`0`,children:(0,B.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-open":e.path,disabled:!e.text,title:e.text?o?`${e.path}(agent 改过这个文件,点击查看改动)`:a?`${e.path}(已经打开,点击切换到它)`:e.path:`${e.name} 是二进制文件,无法以文本打开`,style:{paddingLeft:`${8+t*13}px`},onClick:()=>i(e),children:[(0,B.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,B.jsx)(`span`,{className:`file-name`,children:e.name}),a&&(0,B.jsx)(`span`,{className:`file-open-mark`,"data-file-open-mark":e.path,title:`已经打开`,"aria-label":`已经打开`,children:`●`}),o&&(0,B.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-changed":e.path,title:`agent 改过这个文件`,children:`✎ 已改`}),!e.text&&(0,B.jsx)(`span`,{className:`file-badge`,"data-file-binary":`1`,"aria-label":`不支持的文件类型`,children:`不支持`})]})})}function Tg({file:e,state:t,message:n,external:r,jumpToLine:i,onChange:a,onSave:o,onReload:s,onOverwrite:c}){let[l,u]=(0,z.useState)(!0),d=(0,z.useRef)(null);(0,z.useEffect)(()=>{i&&u(!1)},[e.path,i]),(0,z.useEffect)(()=>{let e=d.current;if(!i||!e)return;let t=Math.min(i.line,e.value.split(`
|
|
47
|
+
`),n=t.length>0&&t[t.length-1]===``;n&&t.pop();for(let c=0;c<t.length;c+=1){let l=t[c],u=c===t.length-1&&!n;e.added?(r.push({kind:`added`,text:l,newLine:s,noNewline:u}),s+=1,i+=1):e.removed?(r.push({kind:`removed`,text:l,oldLine:o,noNewline:u}),o+=1,a+=1):(r.push({kind:`same`,text:l,oldLine:o,newLine:s,noNewline:u}),o+=1,s+=1)}}return{lines:r,added:i,removed:a,identical:i===0&&a===0}}function Am(e,t=3){let n=new Set;e.lines.forEach((r,i)=>{if(r.kind!==`same`)for(let r=-t;r<=t;r+=1){let t=i+r;t>=0&&t<e.lines.length&&n.add(t)}});let r=[],i=0,a=!1;return e.lines.forEach((e,t)=>{n.has(t)?(a&&=(r.push({kind:`fold`,text:`⋯ 省略未改动的行`}),!1),r.push(e)):a||(a=!0,i+=1)}),a&&r.push({kind:`fold`,text:`⋯ 省略未改动的行`}),{lines:r,folded:i}}function jm(e){return Array.isArray?Array.isArray(e):Vm(e)===`[object Array]`}function Mm(e){if(typeof e==`string`)return e;if(typeof e==`bigint`)return e.toString();let t=e+``;return t==`0`&&1/e==-1/0?`-0`:t}function Nm(e){return e==null?``:Mm(e)}function Pm(e){return typeof e==`string`}function Fm(e){return typeof e==`number`}function Im(e){return e===!0||e===!1||Rm(e)&&Vm(e)==`[object Boolean]`}function Lm(e){return typeof e==`object`}function Rm(e){return Lm(e)&&e!==null}function zm(e){return e!=null}function Bm(e){return!e.trim().length}function Vm(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:Object.prototype.toString.call(e)}var Hm=`Incorrect 'index' type`,Um=`Invalid doc index: must be a non-negative integer within the bounds of the docs array`,Wm=e=>`Invalid value for key ${e}`,Gm=e=>`Pattern length exceeds max of ${e}.`,Km=e=>`Missing ${e} property in key`,qm=e=>`Property 'weight' in key '${e}' must be a positive integer`,Jm=`Fuse.match does not support useTokenSearch: token search requires corpus-level statistics (df, fieldCount) that a one-off string comparison does not have. Use new Fuse(...).search(...) instead.`,Ym=Object.prototype.hasOwnProperty,Xm=class{constructor(e){this._keys=[],this._keyMap={};let t=0;e.forEach(e=>{let n=Zm(e);this._keys.push(n),this._keyMap[n.id]=n,t+=n.weight}),this._keys.forEach(e=>{e.weight/=t})}get(e){return this._keyMap[e]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};function Zm(e){let t=null,n=null,r=null,i=1,a=null;if(Pm(e)||jm(e))r=e,t=Qm(e),n=$m(e);else{if(!Ym.call(e,`name`))throw Error(Km(`name`));let o=e.name;if(r=o,Ym.call(e,`weight`)&&e.weight!==void 0&&(i=e.weight,i<=0))throw Error(qm($m(o)));t=Qm(o),n=$m(o),a=e.getFn??null}return{path:t,id:n,weight:i,src:r,getFn:a}}function Qm(e){return jm(e)?e:e.split(`.`)}function $m(e){return jm(e)?e.join(`.`):e}function eh(e,t){let n=[],r=!1,i=(e,t,a,o)=>{if(zm(e)){if(!t[a])n.push(o===void 0?e:{v:e,i:o});else{let s=e[t[a]];if(!zm(s))return;if(a===t.length-1&&(Pm(s)||Fm(s)||Im(s)||typeof s==`bigint`))n.push(o===void 0?Nm(s):{v:Nm(s),i:o});else if(jm(s)){r=!0;for(let e=0,n=s.length;e<n;e+=1)i(s[e],t,a+1,e)}else t.length&&i(s,t,a+1,o)}}};return i(e,Pm(t)?t.split(`.`):t,0),r?n:n[0]}var th={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},nh={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(e,t)=>e.score===t.score?e.idx<t.idx?-1:1:e.score<t.score?-1:1},rh={location:0,threshold:.6,distance:100},ih={useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:`any`,getFn:eh,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1},Y=Object.freeze({...nh,...th,...rh,...ih});function ah(e){return e>=9&&e<=13||e===32||e===160}function oh(e=1,t=3){let n=new Map,r=10**t;return{get(t){let i=0,a=!1;for(let e=0;e<t.length;e++)ah(t.charCodeAt(e))?a=!1:a||=(i++,!0);if(i===0&&(i=1),n.has(i))return n.get(i);let o=Math.round(r/i**(.5*e))/r;return n.set(i,o),o},clear(){n.clear()}}}var sh=class{constructor({getFn:e=Y.getFn,fieldNormWeight:t=Y.fieldNormWeight}={}){this.norm=oh(t,3),this.getFn=e,this.isCreated=!1,this.docs=[],this.keys=[],this._keysMap={},this.setIndexRecords()}setSources(e=[]){this.docs=e}setIndexRecords(e=[]){this.records=e}setKeys(e=[]){this.keys=e,this._keysMap={},e.forEach((e,t)=>{this._keysMap[e.id]=t})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;let e=this.docs.length;this.records=Array(e);let t=0;if(Pm(this.docs[0]))for(let n=0;n<e;n++){let e=this._createStringRecord(this.docs[n],n);e&&(this.records[t++]=e)}else for(let n=0;n<e;n++)this.records[t++]=this._createObjectRecord(this.docs[n],n);this.records.length=t,this.norm.clear()}add(e,t){if(!Number.isInteger(t)||t<0)throw Error(Um);if(Pm(e)){let n=this._createStringRecord(e,t);return n&&this.records.push(n),n}let n=this._createObjectRecord(e,t);return this.records.push(n),n}removeAt(e){if(!Number.isInteger(e)||e<0)throw Error(Um);for(let t=0,n=this.records.length;t<n;t+=1)if(this.records[t].i===e){this.records.splice(t,1);break}for(let t=0,n=this.records.length;t<n;t+=1)this.records[t].i>e&&--this.records[t].i}removeAll(e){let t=new Set;for(let n of e)Number.isInteger(n)&&n>=0&&t.add(n);if(t.size===0)return;this.records=this.records.filter(e=>!t.has(e.i));let n=Array.from(t).sort((e,t)=>e-t);for(let e of this.records){let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i]<e.i?t=i+1:r=i}e.i-=t}}getValueForItemAtKeyId(e,t){return e[this._keysMap[t]]}size(){return this.records.length}_createStringRecord(e,t){return!zm(e)||Bm(e)?null:{v:e,i:t,n:this.norm.get(e)}}_createObjectRecord(e,t){let n={i:t,$:{}};for(let t=0,r=this.keys.length;t<r;t++){let r=this.keys[t],i=r.getFn?r.getFn(e):this.getFn(e,r.path);if(zm(i)){if(jm(i)){let e=[];for(let t=0,n=i.length;t<n;t+=1){let n=i[t];if(zm(n)){if(Pm(n)){if(!Bm(n)){let r={v:n,i:t,n:this.norm.get(n)};e.push(r)}}else if(zm(n.v)){let t=Pm(n.v)?n.v:Nm(n.v);if(!Bm(t)){let r={v:t,i:n.i,n:this.norm.get(t)};e.push(r)}}}}n.$[t]=e}else if(Pm(i)&&!Bm(i)){let e={v:i,n:this.norm.get(i)};n.$[t]=e}}}return n}toJSON(){return{keys:this.keys.map(({getFn:e,...t})=>t),records:this.records}}};function ch(e,t,{getFn:n=Y.getFn,fieldNormWeight:r=Y.fieldNormWeight}={}){let i=new sh({getFn:n,fieldNormWeight:r});return i.setKeys(e.map(Zm)),i.setSources(t),i.create(),i}function lh(e,{getFn:t=Y.getFn,fieldNormWeight:n=Y.fieldNormWeight}={}){let{keys:r,records:i}=e,a=new sh({getFn:t,fieldNormWeight:n});return a.setKeys(r),a.setIndexRecords(i),a}function uh(e=[],t=Y.minMatchCharLength){let n=[],r=-1,i=-1,a=0;for(let o=e.length;a<o;a+=1){let o=e[a];o&&r===-1?r=a:!o&&r!==-1&&(i=a-1,i-r+1>=t&&n.push([r,i]),r=-1)}return e[a-1]&&a-r>=t&&n.push([r,a-1]),n}function dh(e,t,n,{location:r=Y.location,distance:i=Y.distance,threshold:a=Y.threshold,findAllMatches:o=Y.findAllMatches,minMatchCharLength:s=Y.minMatchCharLength,includeMatches:c=Y.includeMatches,ignoreLocation:l=Y.ignoreLocation}={}){if(t.length>32)throw Error(Gm(32));let u=t.length,d=e.length,f=Math.max(0,Math.min(r,d)),p=a,m=f,h=(e,t)=>{let n=e/u;if(l)return n;let r=Math.abs(f-t);return i?n+r/i:r?1:n},g=s>1||c,_=g?Array(d):[],v;for(;(v=e.indexOf(t,m))>-1;){let e=h(0,v);if(p=Math.min(e,p),m=v+u,g){let e=0;for(;e<u;)_[v+e]=1,e+=1}}m=-1;let y=[],b=1,x=0,S=u+d,C=1<<u-1;for(let t=0;t<u;t+=1){let r=0,i=S;for(;r<i;)h(t,f+i)<=p?r=i:S=i,i=Math.floor((S-r)/2+r);S=i;let a=Math.max(1,f-i+1),s=o?d:Math.min(f+i,d)+u,c=Array(s+2);c[s+1]=(1<<t)-1;for(let r=s;r>=a;--r){let i=r-1,o=n[e[i]];if(c[r]=(c[r+1]<<1|1)&o,t&&(c[r]|=(y[r+1]|y[r])<<1|1|y[r+1]),c[r]&C&&(b=h(t,i),b<=p)){if(p=b,m=i,x=t,m<=f)break;a=Math.max(1,2*f-m)}}if(h(t+1,f)>p)break;y=c}if(g&&m>=0){let t=Math.min(d-1,m+u-1+x);for(let r=m;r<=t;r+=1)n[e[r]]&&(_[r]=1)}let w={isMatch:m>=0,score:Math.max(.001,b)};if(g){let e=uh(_,s);e.length?c&&(w.indices=e):w.isMatch=!1}return w}function fh(e){let t={};for(let n=0,r=e.length;n<r;n+=1){let i=e.charAt(n);t[i]=(t[i]||0)|1<<r-n-1}return t}function ph(e){if(e.length<=1)return e;e.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let t=[e[0]];for(let n=1,r=e.length;n<r;n+=1){let r=t[t.length-1],i=e[n];i[0]<=r[1]+1?r[1]=Math.max(r[1],i[1]):t.push(i)}return t}var mh={ł:`l`,Ł:`L`,đ:`d`,Đ:`D`,ø:`o`,Ø:`O`,ħ:`h`,Ħ:`H`,ŧ:`t`,Ŧ:`T`,ı:`i`,ß:`ss`},hh=RegExp(`[`+Object.keys(mh).join(``)+`]`,`g`),gh=typeof String.prototype.normalize==`function`?e=>e.normalize(`NFD`).replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,``).replace(hh,e=>mh[e]):e=>e,_h=class{constructor(e,{location:t=Y.location,threshold:n=Y.threshold,distance:r=Y.distance,includeMatches:i=Y.includeMatches,findAllMatches:a=Y.findAllMatches,minMatchCharLength:o=Y.minMatchCharLength,isCaseSensitive:s=Y.isCaseSensitive,ignoreDiacritics:c=Y.ignoreDiacritics,ignoreLocation:l=Y.ignoreLocation}={}){if(this.options={location:t,threshold:n,distance:r,includeMatches:i,findAllMatches:a,minMatchCharLength:o,isCaseSensitive:s,ignoreDiacritics:c,ignoreLocation:l},e=s?e:e.toLowerCase(),e=c?gh(e):e,this.pattern=e,this.chunks=[],!this.pattern.length)return;let u=(e,t)=>{this.chunks.push({pattern:e,alphabet:fh(e),startIndex:t})},d=this.pattern.length;if(d>32){let e=0,t=d%32,n=d-t;for(;e<n;)u(this.pattern.substr(e,32),e),e+=32;if(t){let e=d-32;u(this.pattern.substr(e),e)}}else u(this.pattern,0)}searchIn(e){let{isCaseSensitive:t,ignoreDiacritics:n,includeMatches:r}=this.options;if(e=t?e:e.toLowerCase(),e=n?gh(e):e,this.pattern===e){if(e.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};let t={isMatch:!0,score:0};return r&&(t.indices=[[0,e.length-1]]),t}let{location:i,distance:a,threshold:o,findAllMatches:s,minMatchCharLength:c,ignoreLocation:l}=this.options,u=[],d=0,f=!1;this.chunks.forEach(({pattern:t,alphabet:n,startIndex:p})=>{let{isMatch:m,score:h,indices:g}=dh(e,t,n,{location:i+p,distance:a,threshold:o,findAllMatches:s,minMatchCharLength:c,includeMatches:r,ignoreLocation:l});m&&(f=!0),d+=h,m&&g&&u.push(...g)});let p={isMatch:f,score:f?d/this.chunks.length:1};return f&&r&&(p.indices=ph(u)),p}},vh=new Set([`fuzzy`,`include`]);function yh(e){return e.startsWith(`inverse`)}var bh=[{type:`exact`,multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:e=>({type:`exact`,search(t){let n=t===e;return{isMatch:n,score:+!n,indices:[0,e.length-1]}}})},{type:`include`,multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:e=>({type:`include`,search(t){let n=0,r,i=[],a=e.length;for(;(r=t.indexOf(e,n))>-1;)n=r+a,i.push([r,n-1]);let o=!!i.length;return{isMatch:o,score:+!o,indices:i}}})},{type:`prefix-exact`,multiRegex:/^\^"(.*)"$/,singleRegex:/^\^(.*)$/,create:e=>({type:`prefix-exact`,search(t){let n=t.startsWith(e);return{isMatch:n,score:+!n,indices:[0,e.length-1]}}})},{type:`inverse-prefix-exact`,multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:e=>({type:`inverse-prefix-exact`,search(t){let n=!t.startsWith(e);return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`inverse-suffix-exact`,multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:e=>({type:`inverse-suffix-exact`,search(t){let n=!t.endsWith(e);return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`suffix-exact`,multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:e=>({type:`suffix-exact`,search(t){let n=t.endsWith(e);return{isMatch:n,score:+!n,indices:[t.length-e.length,t.length-1]}}})},{type:`inverse-exact`,multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:e=>({type:`inverse-exact`,search(t){let n=t.indexOf(e)===-1;return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`fuzzy`,multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(e,t={})=>{let n=new _h(e,{location:t.location??Y.location,threshold:t.threshold??Y.threshold,distance:t.distance??Y.distance,includeMatches:t.includeMatches??Y.includeMatches,findAllMatches:t.findAllMatches??Y.findAllMatches,minMatchCharLength:t.minMatchCharLength??Y.minMatchCharLength,isCaseSensitive:t.isCaseSensitive??Y.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics??Y.ignoreDiacritics,ignoreLocation:t.ignoreLocation??Y.ignoreLocation});return{type:`fuzzy`,search(e){return n.searchIn(e)}}}}],xh=bh.length,Sh=`\0`,Ch=`|`;function wh(e){let t=[],n=e.length,r=0;for(;r<n;){for(;r<n&&e[r]===` `;)r++;if(r>=n)break;let i=r;for(;i<n&&e[i]!==` `&&e[i]!==`"`;)i++;if(i<n&&e[i]===`"`){for(i++;i<n;){if(e[i]===`"`){let t=i+1;if(t>=n||e[t]===` `){i++;break}if(e[t]===`$`&&(t+1>=n||e[t+1]===` `)){i+=2;break}}i++}t.push(e.substring(r,i)),r=i}else{for(;i<n&&e[i]!==` `;)i++;t.push(e.substring(r,i)),r=i}}return t}function Th(e,t){let n=e.match(t);return n?n[1]:null}function Eh(e,t={}){return e.replace(/\\\|/g,Sh).split(Ch).map(e=>{let n=wh(e.replace(/\u0000/g,`|`).trim()).filter(e=>e&&!!e.trim()),r=[];for(let e=0,i=n.length;e<i;e+=1){let i=n[e],a=!1,o=-1;for(;!a&&++o<xh;){let e=bh[o],n=Th(i,e.multiRegex);n&&(r.push(e.create(n,t)),a=!0)}if(!a)for(o=-1;++o<xh;){let e=bh[o],n=Th(i,e.singleRegex);if(n){r.push(e.create(n,t));break}}}return r})}var Dh=class{constructor(e,{isCaseSensitive:t=Y.isCaseSensitive,ignoreDiacritics:n=Y.ignoreDiacritics,includeMatches:r=Y.includeMatches,minMatchCharLength:i=Y.minMatchCharLength,ignoreLocation:a=Y.ignoreLocation,findAllMatches:o=Y.findAllMatches,location:s=Y.location,threshold:c=Y.threshold,distance:l=Y.distance}={}){this.query=null,this.options={isCaseSensitive:t,ignoreDiacritics:n,includeMatches:r,minMatchCharLength:i,findAllMatches:o,ignoreLocation:a,location:s,threshold:c,distance:l},e=t?e:e.toLowerCase(),e=n?gh(e):e,this.pattern=e,this.query=Eh(this.pattern,this.options)}static condition(e,t){return t.useExtendedSearch}searchIn(e){let t=this.query;if(!t)return{isMatch:!1,score:1};let{includeMatches:n,isCaseSensitive:r,ignoreDiacritics:i}=this.options;e=r?e:e.toLowerCase(),e=i?gh(e):e;let a=0,o=[],s=0,c=!1;for(let r=0,i=t.length;r<i;r+=1){let i=t[r];o.length=0,a=0,c=!1;for(let t=0,r=i.length;t<r;t+=1){let r=i[t],{isMatch:l,indices:u,score:d}=r.search(e);if(l)a+=1,s+=d,yh(r.type)&&(c=!0),n&&(vh.has(r.type)?o.push(...u):o.push(u));else{s=0,a=0,o.length=0,c=!1;break}}if(a){let e={isMatch:!0,score:s/a};return c&&(e.hasInverse=!0),n&&(e.indices=ph(o)),e}}return{isMatch:!1,score:1}}},Oh=[];function kh(...e){Oh.push(...e)}function Ah(e,t){for(let n=0,r=Oh.length;n<r;n+=1){let r=Oh[n];if(r.condition(e,t))return new r(e,t)}return new _h(e,t)}var jh={AND:`$and`,OR:`$or`},Mh={PATH:`$path`,PATTERN:`$val`},Nh=e=>!!(e[jh.AND]||e[jh.OR]),Ph=e=>!!e[Mh.PATH],Fh=e=>!jm(e)&&Lm(e)&&!Nh(e),Ih=e=>({[jh.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function Lh(e,t,{auto:n=!0}={}){let r=e=>{if(Pm(e)){let r={keyId:null,pattern:e};return n&&(r.searcher=Ah(e,t)),r}let i=Object.keys(e),a=Ph(e);if(!a&&i.length>1&&!Nh(e))return r(Ih(e));if(Fh(e)){let r=a?e[Mh.PATH]:i[0],o=a?e[Mh.PATTERN]:e[r];if(!Pm(o))throw Error(Wm(r));let s={keyId:$m(r),pattern:o};return n&&(s.searcher=Ah(o,t)),s}let o={children:[],operator:i[0]};return i.forEach(t=>{let n=e[t];jm(n)&&n.forEach(e=>{o.children.push(r(e))})}),o};return Nh(e)||(e=Ih(e)),r(e)}function Rh(e,{ignoreFieldNorm:t=Y.ignoreFieldNorm}){let n=1;return e.forEach(({key:e,norm:r,score:i})=>{let a=e?e.weight:null;n*=(i===0&&a?2**-52:i)**+((a||1)*(t?1:r))}),n}function zh(e,{ignoreFieldNorm:t=Y.ignoreFieldNorm}){e.forEach(e=>{e.score=Rh(e.matches,{ignoreFieldNorm:t})})}var Bh=class{constructor(e,t){this.limit=e,this.heap=[],this.comparator=t}get size(){return this.heap.length}insert(e){this.size<this.limit?(this.heap.push(e),this._bubbleUp(this.size-1)):this.comparator(e,this.heap[0])<0&&(this.heap[0]=e,this._sinkDown(0))}extractSorted(){return this.heap.sort(this.comparator)}_bubbleUp(e){let t=this.heap;for(;e>0;){let n=e-1>>1;if(this.comparator(t[e],t[n])<=0)break;let r=t[e];t[e]=t[n],t[n]=r,e=n}}_sinkDown(e){let t=this.heap,n=t.length,r=e;do{e=r;let i=2*e+1,a=2*e+2;if(i<n&&this.comparator(t[i],t[r])>0&&(r=i),a<n&&this.comparator(t[a],t[r])>0&&(r=a),r!==e){let n=t[e];t[e]=t[r],t[r]=n}}while(r!==e)}};function Vh(e){let t=[];return e.matches.forEach(e=>{if(!zm(e.indices)||!e.indices.length)return;let n={indices:e.indices,value:e.value};e.key&&(n.key=e.key.id),e.idx>-1&&(n.refIndex=e.idx),t.push(n)}),t}function Hh(e,t,{includeMatches:n=Y.includeMatches,includeScore:r=Y.includeScore}={}){return e.map(e=>{let{idx:i}=e,a={item:t[i],refIndex:i};return n&&(a.matches=Vh(e)),r&&(a.score=e.score),a})}var Uh=/[\p{L}\p{M}\p{N}_]+/gu,Wh=new WeakSet;function Gh(e){Wh.has(e)||(Wh.add(e),console.warn(`[Fuse] tokenize regex ${e} lacks the global flag; only the first match per text will be returned. Add the 'g' flag.`))}function Kh(e){if(typeof e==`function`){let t=!1;return n=>{let r=e(n);if(!t&&(t=!0,!Array.isArray(r)||r.some(e=>typeof e!=`string`)))throw Error(`[Fuse] tokenize function must return string[]; received ${Array.isArray(r)?`array containing non-strings`:typeof r}.`);return r}}return e instanceof RegExp?(e.global||Gh(e),t=>t.match(e)||[]):e=>e.match(Uh)||[]}function qh({isCaseSensitive:e=!1,ignoreDiacritics:t=!1,tokenize:n}={}){let r=Kh(n);return{tokenize(n){return e||(n=n.toLowerCase()),t&&(n=gh(n)),r(n)}}}var Jh=class{static condition(e,t){return t.useTokenSearch}constructor(e,t){this.options=t,this.analyzer=qh({isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,tokenize:t.tokenize});let n=this.analyzer.tokenize(e),{df:r,fieldCount:i}=t._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(let e of n){this.termSearchers.push(new _h(e,{location:t.location,threshold:t.threshold,distance:t.distance,includeMatches:t.includeMatches,findAllMatches:t.findAllMatches,minMatchCharLength:t.minMatchCharLength,isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,ignoreLocation:!0}));let n=r.get(e)||0,a=Math.log(1+(i-n+.5)/(n+.5));this.idfWeights.push(a)}this.combineAll=t.tokenMatch===`all`,this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(e){if(!this.termSearchers.length)return{isMatch:!1,score:1};let t=[],n=0,r=0,i=0,a=0,o=this.combineAll&&!this.useMask?new Set:null;for(let s=0;s<this.termSearchers.length;s++){let c=this.termSearchers[s].searchIn(e),l=this.idfWeights[s];r+=l,c.isMatch&&(i++,n+=l*(1-c.score),c.indices&&t.push(...c.indices),this.combineAll&&(this.useMask?a|=1<<s:o.add(s)))}if(i===0)return{isMatch:!1,score:1};let s=r>0?1-n/r:0,c={isMatch:!0,score:Math.max(.001,s)};return this.options.includeMatches&&t.length&&(c.indices=ph(t)),this.combineAll&&(this.useMask?c.matchedMask=a:c.matchedTerms=o,c.termCount=this.numTerms),c}};function Yh(e,t,n,r){let i=r.tokenize(t);if(!i.length)return;e.fieldCount++,e.docFieldCount.set(n,(e.docFieldCount.get(n)||0)+1);let a=new Set(i),o=e.docTermFieldHits.get(n);o||(o=new Map,e.docTermFieldHits.set(n,o));for(let t of a)o.set(t,(o.get(t)||0)+1),e.df.set(t,(e.df.get(t)||0)+1)}function Xh(e,t,n,r){let{i,v:a,$:o}=t;if(a!==void 0)Yh(e,a,i,r);else if(o)for(let t=0;t<n;t++){let n=o[t];if(n){if(Array.isArray(n))for(let t of n)Yh(e,t.v,i,r);else Yh(e,n.v,i,r)}}}function Zh(e,t,n){let r={fieldCount:0,df:new Map,docFieldCount:new Map,docTermFieldHits:new Map};for(let i of e)Xh(r,i,t,n);return r}function Qh(e,t,n,r){Xh(e,t,n,r)}function $h(e,t){let n=e.docFieldCount.get(t);if(n===void 0)return;e.fieldCount-=n,e.docFieldCount.delete(t);let r=e.docTermFieldHits.get(t);if(r){for(let[t,n]of r){let r=(e.df.get(t)||0)-n;r<=0?e.df.delete(t):e.df.set(t,r)}e.docTermFieldHits.delete(t)}}function eg(e,t){if(t.length===0)return;let n=Array.from(new Set(t)).sort((e,t)=>e-t);for(let t of n)$h(e,t);let r=e=>{let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i]<e?t=i+1:r=i}return e-t},i=n[0],a=new Map;for(let[t,n]of e.docFieldCount)a.set(t>i?r(t):t,n);e.docFieldCount=a;let o=new Map;for(let[t,n]of e.docTermFieldHits)o.set(t>i?r(t):t,n);e.docTermFieldHits=o}var tg=class{constructor(e,t,n){this.options={...Y,...t},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new Xm(this.options.keys),this._docs=e,this._myIndex=null,this._invertedIndex=null,this.setCollection(e,n),this._lastQuery=null,this._lastSearcher=null}_getSearcher(e){if(this._lastQuery===e)return this._lastSearcher;let t=Ah(e,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=e,this._lastSearcher=t,t}setCollection(e,t){if(this._docs=e,t&&!(t instanceof sh))throw Error(Hm);if(this._myIndex=t||ch(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){let e=qh({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=Zh(this._myIndex.records,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}add(e){if(!zm(e))return;this._docs.push(e);let t=this._myIndex.add(e,this._docs.length-1);if(this._invertedIndex&&t){let e=qh({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});Qh(this._invertedIndex,t,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}remove(e=()=>!1){let t=[],n=[];for(let r=0,i=this._docs.length;r<i;r+=1)e(this._docs[r],r)&&(t.push(this._docs[r]),n.push(r));if(n.length){this._invertedIndex&&eg(this._invertedIndex,n);let e=new Set(n);this._docs=this._docs.filter((t,n)=>!e.has(n)),this._myIndex.removeAll(n),this._invalidateSearcherCache()}return t}removeAt(e){if(!Number.isInteger(e)||e<0||e>=this._docs.length)throw Error(Um);this._invertedIndex&&eg(this._invertedIndex,[e]);let t=this._docs.splice(e,1)[0];return this._myIndex.removeAt(e),this._invalidateSearcherCache(),t}_invalidateSearcherCache(){this._lastQuery=null,this._lastSearcher=null}getIndex(){return this._myIndex}_normalizedKeys(){return this._myIndex.keys.map(e=>this._keyStore.get(e.id)||e)}search(e,t){let{limit:n=-1}=t||{},{includeMatches:r,includeScore:i,shouldSort:a,sortFn:o,ignoreFieldNorm:s}=this.options;if(Pm(e)&&!e.trim()){let e=this._docs.map((e,t)=>({item:e,refIndex:t}));return Fm(n)&&n>-1&&(e=e.slice(0,n)),e}let c=a&&Fm(n)&&n>0&&Pm(e),l=o,u=(e,t)=>l(e,t)||e.idx-t.idx,d;if(c){let t=new Bh(n,u);Pm(this._docs[0])?this._searchStringList(e,{heap:t,ignoreFieldNorm:s}):this._searchObjectList(e,{heap:t,ignoreFieldNorm:s}),d=t.extractSorted()}else d=Pm(e)?Pm(this._docs[0])?this._searchStringList(e):this._searchObjectList(e):this._searchLogical(e),zh(d,{ignoreFieldNorm:s}),a&&d.sort(Pm(e)?u:l),Fm(n)&&n>-1&&(d=d.slice(0,n));return Hh(d,this._docs,{includeMatches:r,includeScore:i})}_searchStringList(e,{heap:t,ignoreFieldNorm:n}={}){let r=this._getSearcher(e),i=this.options.useTokenSearch&&this.options.tokenMatch===`all`,{records:a}=this._myIndex,o=t?null:[];return a.forEach(({v:e,i:a,n:s})=>{if(!zm(e))return;let c=r.searchIn(e);if(c.isMatch){let r={score:c.score,value:e,norm:s,indices:c.indices};i&&(r.matchedMask=c.matchedMask,r.matchedTerms=c.matchedTerms,r.termCount=c.termCount);let l=[r];if(!i||this._coversAllTokens(l)){let r={item:e,idx:a,matches:l};t?(r.score=Rh(r.matches,{ignoreFieldNorm:n}),t.insert(r)):o.push(r)}}}),o}_searchLogical(e){let t=Lh(e,this.options),n=this._normalizedKeys(),r=(e,t,i)=>{if(!(`children`in e)){let{keyId:r,searcher:a}=e,o;return r===null?(o=[],n.forEach((e,n)=>{o.push(...this._findMatches({key:e,value:t[n],searcher:a}))})):o=this._findMatches({key:this._keyStore.get(r),value:this._myIndex.getValueForItemAtKeyId(t,r),searcher:a}),o&&o.length?[{idx:i,item:t,matches:o}]:[]}let{children:a,operator:o}=e,s=[];for(let e=0,n=a.length;e<n;e+=1){let n=a[e],c=r(n,t,i);if(c.length)s.push(...c);else if(o===jh.AND)return[]}return s},i=this._myIndex.records,a=new Map,o=[];return i.forEach(({$:e,i:n})=>{if(zm(e)){let i=r(t,e,n);i.length&&(a.has(n)||(a.set(n,{idx:n,item:e,matches:[]}),o.push(a.get(n))),i.forEach(({matches:e})=>{a.get(n).matches.push(...e)}))}}),o}_searchObjectList(e,{heap:t,ignoreFieldNorm:n}={}){let r=this._getSearcher(e),i=this.options.useTokenSearch&&this.options.tokenMatch===`all`,{records:a}=this._myIndex,o=this._normalizedKeys(),s=t?null:[];return a.forEach(({$:e,i:a})=>{if(!zm(e))return;let c=[],l=!1,u=!1;if(o.forEach((t,n)=>{let i=this._findMatches({key:t,value:e[n],searcher:r});i.length?(c.push(...i),i[0].hasInverse&&(u=!0)):l=!0}),!(u&&l)&&c.length&&(!i||this._coversAllTokens(c))){let r={idx:a,item:e,matches:c};t?(r.score=Rh(r.matches,{ignoreFieldNorm:n}),t.insert(r)):s.push(r)}}),s}_findMatches({key:e,value:t,searcher:n}){if(!zm(t))return[];let r=[];if(jm(t))t.forEach(({v:t,i,n:a})=>{if(!zm(t))return;let o=n.searchIn(t);if(o.isMatch){let n={score:o.score,key:e,value:t,idx:i,norm:a,indices:o.indices,hasInverse:o.hasInverse};o.termCount!==void 0&&(n.matchedMask=o.matchedMask,n.matchedTerms=o.matchedTerms,n.termCount=o.termCount),r.push(n)}});else{let{v:i,n:a}=t,o=n.searchIn(i);if(o.isMatch){let t={score:o.score,key:e,value:i,norm:a,indices:o.indices,hasInverse:o.hasInverse};o.termCount!==void 0&&(t.matchedMask=o.matchedMask,t.matchedTerms=o.matchedTerms,t.termCount=o.termCount),r.push(t)}}return r}_coversAllTokens(e){let t=e.length?e[0].termCount:void 0;if(t===void 0)return!0;if(t<=31){let n=0;for(let t=0;t<e.length;t++)n|=e[t].matchedMask||0;return n===2**t-1}let n=new Set;for(let t=0;t<e.length;t++){let r=e[t].matchedTerms;if(r)for(let e of r)n.add(e)}return n.size===t}};tg.version=`7.5.0`,tg.createIndex=ch,tg.parseIndex=lh,tg.config=Y,tg.match=function(e,t,n){if(n&&n.useTokenSearch)throw Error(Jm);return Ah(e,{...Y,...n}).searchIn(t)},tg.parseQuery=Lh,kh(Dh),kh(Jh),tg.use=function(...e){e.forEach(e=>kh(e))};var ng=tg;function rg(e){let t=e.slice(e.lastIndexOf(`/`)+1),n=t.lastIndexOf(`.`);return n<=0?``:t.slice(n+1).toLowerCase()}var ig={ts:`code`,tsx:`code`,js:`code`,jsx:`code`,mjs:`code`,cjs:`code`,mts:`code`,cts:`code`,py:`code`,rb:`code`,go:`code`,rs:`code`,java:`code`,kt:`code`,kts:`code`,scala:`code`,c:`code`,h:`code`,cc:`code`,cpp:`code`,hpp:`code`,cs:`code`,swift:`code`,m:`code`,mm:`code`,php:`code`,pl:`code`,pm:`code`,lua:`code`,r:`code`,jl:`code`,ex:`code`,exs:`code`,erl:`code`,hs:`code`,dart:`code`,nim:`code`,zig:`code`,vue:`code`,svelte:`code`,astro:`code`,sh:`code`,bash:`code`,zsh:`code`,fish:`code`,ps1:`code`,bat:`code`,cmd:`code`,sql:`code`,graphql:`code`,gql:`code`,proto:`code`,tf:`code`,tfvars:`code`,hcl:`code`,sol:`code`,md:`markup`,mdx:`markup`,markdown:`markup`,txt:`markup`,text:`markup`,rst:`markup`,adoc:`markup`,org:`markup`,yaml:`config`,yml:`config`,toml:`config`,ini:`config`,cfg:`config`,conf:`config`,xml:`config`,env:`config`,properties:`config`,gitignore:`config`,editorconfig:`config`,eslintrc:`config`,prettierrc:`config`,css:`style`,scss:`style`,sass:`style`,less:`style`,stylus:`style`,pcss:`style`,postcss:`style`,png:`image`,jpg:`image`,jpeg:`image`,gif:`image`,bmp:`image`,webp:`image`,avif:`image`,ico:`image`,svg:`image`,tif:`image`,tiff:`image`,heic:`image`,psd:`image`,ai:`image`,json:`data`,jsonc:`data`,json5:`data`,csv:`data`,tsv:`data`,parquet:`data`,db:`data`,sqlite:`data`,sqlite3:`data`,ndjson:`data`,zip:`archive`,tar:`archive`,gz:`archive`,tgz:`archive`,bz2:`archive`,xz:`archive`,"7z":`archive`,rar:`archive`,zst:`archive`,jar:`archive`,war:`archive`,whl:`archive`,woff:`font`,woff2:`font`,ttf:`font`,otf:`font`,eot:`font`,exe:`binary`,dll:`binary`,so:`binary`,dylib:`binary`,bin:`binary`,o:`binary`,obj:`binary`,a:`binary`,lib:`binary`,class:`binary`,node:`binary`,pyc:`binary`,pyo:`binary`,pack:`binary`,idx:`binary`,iso:`binary`,dmg:`binary`,msi:`binary`,apk:`binary`,deb:`binary`,rpm:`binary`,pdf:`binary`,doc:`binary`,docx:`binary`,xls:`binary`,xlsx:`binary`,ppt:`binary`,pptx:`binary`,odt:`binary`,ods:`binary`,odp:`binary`,wasm:`binary`},ag={dockerfile:`config`,containerfile:`config`,makefile:`code`,cmakelists:`code`,rakefile:`code`,gemfile:`config`,procfile:`config`,license:`markup`,licence:`markup`,notice:`markup`,readme:`markup`,changelog:`markup`,authors:`markup`,contributing:`markup`,".gitignore":`config`,".gitattributes":`config`,".gitmodules":`config`,".npmrc":`config`,".nvmrc":`config`,".env":`config`};function og(e){let t=ag[e.slice(e.lastIndexOf(`/`)+1).toLowerCase()];if(t)return t;let n=rg(e);return n?ig[n]??`generic`:`generic`}var sg={code:[`M6 4.5 2.5 8 6 11.5`,`M10 4.5 13.5 8 10 11.5`,`M9.2 3.5 6.8 12.5`],markup:[`M4 2.5h5l3 3v8a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-10a1 1 0 0 1 1-1z`,`M9 2.5v3h3`,`M5.5 8.5h5`,`M5.5 11h3.5`],config:[`M8 10.2a2.2 2.2 0 1 0 0-4.4 2.2 2.2 0 0 0 0 4.4z`,`M8 1.8v1.6`,`M8 12.6v1.6`,`M1.8 8h1.6`,`M12.6 8h1.6`,`M3.6 3.6l1.1 1.1`,`M11.3 11.3l1.1 1.1`,`M12.4 3.6l-1.1 1.1`,`M4.7 11.3l-1.1 1.1`],style:[`M8 13.5a5.5 5.5 0 1 1 0-11c3 0 5.5 2 5.5 4.5 0 1.4-1.1 2.2-2.3 2.2h-1c-.9 0-1.6.7-1.6 1.5 0 .4.2.7.4 1 .2.3.4.6.4 1a1.3 1.3 0 0 1-1.4.8z`,`M5.6 6.8h.01`,`M8.4 5.2h.01`,`M11 6.9h.01`],image:[`M2.5 4.5a1 1 0 0 1 1-1h9a1 1 0 0 1 1 1v7a1 1 0 0 1-1 1h-9a1 1 0 0 1-1-1v-7z`,`M2.5 10.5 6 7.5l2.5 2 2-1.5 3 2.5`,`M5.8 6.4h.01`],data:[`M2.5 3.5h11v9h-11z`,`M2.5 8h11`,`M8 3.5v9`],archive:[`M2.5 5.5h11v8h-11z`,`M1.5 2.5h13v3h-13z`,`M6.8 8.5h2.4`],font:[`M3.5 13 8 3l4.5 10`,`M5.4 9.6h5.2`],binary:[`M2.5 4.5h11v7h-11z`,`M5 7h.01`,`M8 7h.01`,`M11 7h.01`,`M5 9.5h.01`,`M8 9.5h.01`],generic:[`M4 2.5h5l3 3v8a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-10a1 1 0 0 1 1-1z`,`M9 2.5v3h3`],folder:[`M2.5 4.5a1 1 0 0 1 1-1h3l1.5 2h4.5a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1h-9a1 1 0 0 1-1-1v-8z`],"folder-open":[`M2.5 12.5v-8a1 1 0 0 1 1-1h3l1.5 2h4.5a1 1 0 0 1 1 1v1`,`M2.5 12.5 4.6 6.8a1 1 0 0 1 .95-.7h8.1a.6.6 0 0 1 .55.85L12.9 12.5a1 1 0 0 1-.95.7H3.5a1 1 0 0 1-1-1z`]};function cg({path:e,category:t,size:n=14}){let r=t??og(e??``),i=sg[r]??sg.generic;return(0,B.jsx)(`svg`,{className:`file-icon file-icon-${r}`,"data-file-icon":r,width:n,height:n,viewBox:`0 0 16 16`,fill:`none`,stroke:`currentColor`,strokeWidth:1.5,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,focusable:`false`,children:i.map((e,t)=>(0,B.jsx)(`path`,{d:e},t))})}var lg=`modulepreload`,ug=function(e){return`/`+e},dg={},fg=function(e){return e.pathname.endsWith(`.css`)},pg=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},mg=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=ug(t,n);let r=s(t),i=fg(r);return pg(dg,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:lg,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},hg=4e3,gg=(0,z.lazy)(()=>mg(()=>import(`./CodeMirrorEditor-moFTk5SE.js`).then(e=>({default:e.CodeMirrorEditor})),[])),_g=class extends Error{status;body;constructor(e,t){super(t.error||`HTTP ${e}`),this.status=e,this.body=t,this.name=`ApiError`}},vg=15e3,yg=e=>new _g(408,{error:`请求超时:${vg/1e3} 秒内服务端没有响应`,code:`timeout`,details:{path:e}});async function bg(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),vg);try{let r=await fetch(e,{...t,signal:n.signal}),i;try{i=await r.json()}catch{i=void 0}if(!r.ok)throw new _g(r.status,i??{error:`HTTP ${r.status}`});return i}catch(t){throw n.signal.aborted?yg(e):t}finally{clearTimeout(r)}}var xg=e=>e instanceof _g?e:new _g(0,{error:e instanceof Error?e.message:`读取失败`}),Sg=e=>encodeURIComponent(e),Cg=(e,t)=>`/api/files?workspaceId=${Sg(e)}&path=${Sg(t)}`,wg=(e,t)=>`/api/file?workspaceId=${Sg(e)}&path=${Sg(t)}`,Tg=(e,t)=>`/api/file?workspaceId=${Sg(e)}&path=${Sg(t)}&meta=1`,Eg=(e,t)=>`/api/files?workspaceId=${Sg(e)}&q=${Sg(t)}`,Dg=e=>e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(1)} MB`,Og=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?``:new Date(e).toLocaleTimeString(`zh-CN`,{hour:`2-digit`,minute:`2-digit`})};function kg({workspaceId:e,entryPath:t,name:n,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:u,depth:d}){let f=r[t],p=i.has(t);return(0,z.useEffect)(()=>{p&&f===void 0&&o(t)},[p,t,f,o]),(0,B.jsxs)(`li`,{className:`file-node`,"data-file-dir":t,"data-file-dir-changed":c.has(t)?`1`:`0`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`file-row file-row-dir`,"data-file-dir-toggle":t,"aria-expanded":p,style:{paddingLeft:`${8+d*13}px`},title:c.has(t)?`${t} 里有 agent 改过的文件`:t,onClick:()=>a(t),children:[(0,B.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`,children:p?`▾`:`▸`}),(0,B.jsx)(cg,{category:`folder`}),(0,B.jsx)(`span`,{className:`file-name`,children:n}),c.has(t)&&(0,B.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-dir-changed-badge":t,title:`里面有 agent 改过的文件`,children:`✎`})]}),p&&(0,B.jsx)(`ul`,{className:`file-children`,children:f===void 0?(0,B.jsx)(`li`,{className:`file-row-loading`,"data-file-loading":t,children:`读取中…`}):`error`in f?(0,B.jsx)(`li`,{className:`file-row-error`,"data-file-error":t,children:f.error.message}):f.entries.length===0?(0,B.jsx)(`li`,{className:`file-row-empty`,"data-file-empty":t,children:`空目录`}):(0,B.jsxs)(B.Fragment,{children:[f.truncated&&(0,B.jsx)(`li`,{className:`file-row-empty`,"data-file-truncated":t,children:`条目过多,只显示前一部分`}),f.entries.map(t=>t.kind===`directory`?(0,B.jsx)(kg,{workspaceId:e,entryPath:t.path,name:t.name,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:u,depth:d+1},t.path):(0,B.jsx)(Ag,{entry:t,depth:d+1,openPaths:s,changedPaths:l,onOpen:u},t.path))]})})]})}function Ag({entry:e,depth:t,openPaths:n,changedPaths:r,onOpen:i}){if(e.kind===`symlink`)return(0,B.jsx)(`li`,{className:`file-node`,"data-file-entry":e.path,"data-file-outside":e.path,children:(0,B.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,disabled:!0,title:`${e.path} 是一个指向 workspace 之外的符号链接,不能打开`,style:{paddingLeft:`${8+t*13}px`},children:[(0,B.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,B.jsx)(`span`,{className:`file-name`,children:e.name}),(0,B.jsx)(`span`,{className:`file-badge`,"data-file-outside-badge":`1`,children:`外部链接`})]})});let a=n.has(e.path),o=r.has(e.path);return(0,B.jsx)(`li`,{className:`file-node`,"data-file-entry":e.path,"data-file-row-open":a?`1`:`0`,"data-file-row-changed":o?`1`:`0`,children:(0,B.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-open":e.path,disabled:!e.text,title:e.text?o?`${e.path}(agent 改过这个文件,点击查看改动)`:a?`${e.path}(已经打开,点击切换到它)`:e.path:`${e.name} 是二进制文件,无法以文本打开`,style:{paddingLeft:`${8+t*13}px`},onClick:()=>i(e),children:[(0,B.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,B.jsx)(cg,{path:e.path}),(0,B.jsx)(`span`,{className:`file-name`,children:e.name}),a&&(0,B.jsx)(`span`,{className:`file-open-mark`,"data-file-open-mark":e.path,title:`已经打开`,"aria-label":`已经打开`,children:`●`}),o&&(0,B.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-changed":e.path,title:`agent 改过这个文件`,children:`✎ 已改`}),!e.text&&(0,B.jsx)(`span`,{className:`file-badge`,"data-file-binary":`1`,"aria-label":`不支持的文件类型`,children:`不支持`})]})})}function jg({file:e,state:t,message:n,external:r,jumpToLine:i,onChange:a,onSave:o,onReload:s,onOverwrite:c}){let[l,u]=(0,z.useState)(!0),d=(0,z.useRef)(null);(0,z.useEffect)(()=>{i&&u(!1)},[e.path,i]),(0,z.useEffect)(()=>{let e=d.current;if(!i||!e)return;let t=Math.min(i.line,e.value.split(`
|
|
48
48
|
`).length),n=e.value.split(`
|
|
49
|
-
`),r=n.slice(0,t-1).reduce((e,t)=>e+t.length+1,0);e.focus(),e.setSelectionRange(r,r+n[t-1].length);let a=parseFloat(getComputedStyle(e).lineHeight);e.scrollTop=Math.max(0,(t-1)*a-e.clientHeight/2),e.scrollLeft=0;let o=e.previousElementSibling;o instanceof HTMLElement&&(o.scrollTop=e.scrollTop,o.scrollLeft=0)},[e.path,i,l]);let f=/\.md$/i.test(e.path);return(0,B.jsxs)(`div`,{className:`file-editor`,"data-file-editor":e.path,"data-save-state":t,children:[(0,B.jsxs)(`div`,{className:`file-editor-head`,children:[(0,B.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path}),(0,B.jsxs)(`span`,{className:`file-editor-flags`,children:[f&&(0,B.jsx)(`button`,{type:`button`,className:`file-preview-toggle`,onClick:()=>u(e=>!e),children:l?`原文`:`预览`}),e.dirty&&(0,B.jsx)(`span`,{className:`file-dirty`,"data-file-dirty":`1`,children:`未保存`}),(0,B.jsx)(`button`,{type:`button`,className:`file-save`,"data-file-save":e.path,onClick:o,disabled:t===`saving`,children:t===`saving`?`保存中…`:`保存`})]})]}),r&&t!==`conflict`&&(0,B.jsxs)(`div`,{className:`file-conflict`,"data-file-external":e.path,role:`alert`,children:[(0,B.jsx)(`p`,{children:`这个文件在磁盘上已经被改过了,你的修改还没有覆盖它。`}),(0,B.jsxs)(`div`,{className:`file-conflict-actions`,children:[(0,B.jsx)(`button`,{type:`button`,"data-file-reload":e.path,onClick:s,children:`丢掉我的修改,读磁盘版本`}),(0,B.jsx)(`button`,{type:`button`,"data-file-overwrite":e.path,onClick:c,children:`仍然覆盖磁盘`})]})]}),t===`conflict`&&(0,B.jsxs)(`div`,{className:`file-conflict`,"data-file-conflict":e.path,role:`alert`,children:[(0,B.jsx)(`p`,{children:`保存被拒绝:这个文件在磁盘上已经被改过了,覆盖会丢掉对方的改动。`}),(0,B.jsxs)(`div`,{className:`file-conflict-actions`,children:[(0,B.jsx)(`button`,{type:`button`,"data-file-reload":e.path,onClick:s,children:`丢掉我的修改,读磁盘版本`}),(0,B.jsx)(`button`,{type:`button`,"data-file-overwrite":e.path,onClick:c,children:`仍然覆盖磁盘`})]})]}),n&&t!==`conflict`&&!r&&(0,B.jsx)(`p`,{className:`file-editor-message file-message-${t}`,"data-file-message":t,role:`status`,children:n}),f&&l?(0,B.jsx)(`div`,{className:`file-markdown-preview`,"data-file-preview":`markdown`,children:(0,B.jsx)(tm,{source:e.content})}):(0,B.jsx)(z.Suspense,{fallback:(0,B.jsx)(`div`,{className:`file-cm-wrap`,"data-file-text":e.path,"data-file-content":e.content,"data-file-selection":`0,0`,"data-file-editor-ready":`0`,children:(0,B.jsx)(`span`,{className:`file-cm-status`,"data-file-editor-loading":`1`,children:`⌛ 正在加载编辑器…`})}),children:(0,B.jsx)(ug,{path:e.path,value:e.content,onChange:a,jumpToLine:i,onSave:o})})]})}function Eg({line:e}){if(e.kind===`fold`)return(0,B.jsx)(`div`,{className:`file-diff-line file-diff-fold`,"data-diff-kind":`fold`,children:e.text});let t=e.kind===`added`?`+`:e.kind===`removed`?`-`:` `;return(0,B.jsxs)(`div`,{className:`file-diff-line file-diff-${e.kind}`,"data-diff-kind":e.kind,"data-diff-no-newline":e.noNewline?`1`:void 0,children:[(0,B.jsx)(`span`,{className:`file-diff-mark`,"aria-hidden":`true`,children:t}),(0,B.jsx)(`span`,{className:`file-diff-number`,"aria-hidden":`true`,children:e.oldLine??``}),(0,B.jsx)(`span`,{className:`file-diff-number`,"aria-hidden":`true`,children:e.newLine??``}),(0,B.jsx)(`span`,{className:`file-diff-text`,children:e.text}),e.noNewline&&(0,B.jsx)(`span`,{className:`file-diff-no-newline`,title:`这个版本的末尾没有换行`,children:`(末尾无换行)`})]})}function Dg({diff:e,loading:t,error:n,bufferContent:r,mode:i,onMode:a}){if(t)return(0,B.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`loading`,children:(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-diff-loading":`1`,children:`正在读取差异…`})});if(n)return(0,B.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`error`,children:(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-diff-error":`1`,children:n})});if(!e)return(0,B.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`empty`,children:(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-diff-empty":`1`,children:`没有选中的差异。`})});let o=typeof r==`string`,s=i===`buffer`&&o,c=s?e.after:e.before,l=s?r:e.after,u=s?`我未保存的修改`:e.label,d=s?`buffer`:e.baseline,f=o&&e.baseline!==`none`?(0,B.jsxs)(`span`,{className:`file-diff-switch`,"data-file-diff-switch":`1`,children:[(0,B.jsx)(`button`,{type:`button`,className:`file-diff-switch-btn${s?``:` file-diff-switch-active`}`,"data-file-diff-base":`server`,"aria-pressed":!s,onClick:()=>a(`server`),children:`agent 的改动`}),(0,B.jsx)(`button`,{type:`button`,className:`file-diff-switch-btn${s?` file-diff-switch-active`:``}`,"data-file-diff-base":`buffer`,"aria-pressed":s,onClick:()=>a(`buffer`),children:`我的修改`})]}):null;if(d===`none`)return(0,B.jsxs)(`div`,{className:`file-diff`,"data-file-diff-state":`none`,"data-file-diff-baseline":d,children:[(0,B.jsxs)(`div`,{className:`file-editor-head`,children:[(0,B.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path}),(0,B.jsx)(`span`,{className:`file-editor-flags`,children:f})]}),(0,B.jsx)(`p`,{className:`file-diff-nobaseline`,"data-file-diff-nobaseline":`1`,children:u})]});let p=km(c,l),m=Am(p);return(0,B.jsxs)(`div`,{className:`file-diff`,"data-file-diff-state":`ready`,"data-file-diff-baseline":d,"data-file-diff-added":p.added,"data-file-diff-removed":p.removed,children:[(0,B.jsxs)(`div`,{className:`file-editor-head`,children:[(0,B.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path}),(0,B.jsxs)(`span`,{className:`file-editor-flags`,children:[f,(0,B.jsx)(`span`,{className:`file-diff-baseline`,"data-file-diff-label":`1`,children:u}),(0,B.jsxs)(`span`,{className:`file-diff-count`,"data-file-diff-count":`1`,children:[`+`,p.added,` / -`,p.removed]})]})]}),e.beforeUnknown&&!s&&(0,B.jsx)(`p`,{className:`file-diff-warning`,"data-file-diff-before-unknown":`1`,role:`status`,children:`读不到改动前的版本(文件太大或无法读取),这里只显示现在的内容。`}),e.before===null&&!e.beforeUnknown&&!s&&(0,B.jsx)(`p`,{className:`file-diff-warning`,"data-file-diff-is-new":`1`,role:`status`,children:`这个文件是新建的,下面是它的全部内容。`}),p.identical?(0,B.jsx)(`p`,{className:`file-diff-nobaseline`,"data-file-diff-identical":`1`,children:`两个版本没有区别。`}):(0,B.jsx)(`div`,{className:`file-diff-body`,"data-file-diff-body":`1`,children:m.lines.map((e,t)=>(0,B.jsx)(Eg,{line:e},t))})]})}function Og({error:e}){let t=e.body.code,n=typeof e.body.details?.path==`string`?e.body.details.path:``,r=t===`workspace_missing`?`missing`:t===`timeout`?`timeout`:`failed`;return(0,B.jsxs)(`div`,{className:`rail-empty file-problem`,"data-file-root-error":`1`,"data-file-error-kind":r,role:`alert`,children:[r===`missing`&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`工作区路径不存在,无法读取文件。`}),(0,B.jsx)(`p`,{className:`file-problem-hint`,children:`请确认这个路径是写错了,还是目录被移动或删除了:`}),(0,B.jsx)(`code`,{className:`file-problem-path`,"data-file-error-path":`1`,children:n||e.message})]}),r===`timeout`&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`读取超时,服务端没有回应。`}),(0,B.jsxs)(`p`,{className:`file-problem-hint`,children:[`已经等了 `,fg/1e3,` 秒。如果这个工作区在网络盘上,请检查它是否已连接,然后点上面的 ↻ 重试。`]})]}),r===`failed`&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`读取失败。`}),(0,B.jsx)(`p`,{className:`file-problem-hint`,children:e.message})]})]})}function kg(e){let[t,n]=(0,z.useState)([]),[r,i]=(0,z.useState)(),[a,o]=(0,z.useState)(``),[s,c]=(0,z.useState)({}),[l,u]=(0,z.useState)({}),[d,f]=(0,z.useState)({}),[p,m]=(0,z.useState)(()=>new Set),[h,g]=(0,z.useState)(``),[_,v]=(0,z.useState)(null),[y,b]=(0,z.useState)(!1),[x,S]=(0,z.useState)([]),[C,w]=(0,z.useState)(!1),[T,E]=(0,z.useState)([]),D=(0,z.useCallback)((e,t)=>S(n=>{let r=new Map(n.map(e=>[e.path,e]));for(let t of e)r.set(t.path,t);for(let e of t)r.delete(e);return[...r.values()]}),[]),O=(0,z.useCallback)((e,t)=>{w(e),E(t)},[]);(0,z.useEffect)(()=>{if(S([]),w(!1),E([]),!e)return;let t=!0;return fetch(`/api/files/index?workspaceId=${encodeURIComponent(e)}`).then(e=>e.json()).then(e=>{t&&(D(e.changed??[],e.removed??[]),w(e.complete===!0),E(e.skipped??[]))}).catch(()=>void 0),()=>{t=!1}},[e,D]);let[k,A]=(0,z.useState)({});(0,z.useEffect)(()=>{if(n([]),i(void 0),o(``),c({}),u({}),f({}),m(new Set),v(null),g(``),b(!1),!e)return;let t=!0;return mg(_g(e,``)).then(e=>{t&&f({"":e})}).catch(e=>{t&&f({"":{error:hg(e)}})}),()=>{t=!1}},[e]);let ee=(0,z.useRef)(void 0),[j,M]=(0,z.useState)(void 0);(0,z.useEffect)(()=>{if(!e||ee.current===e)return;ee.current=e;let t=jg()[e];t&&(t.expanded.length&&m(new Set(t.expanded)),t.open.length&&(async()=>{for(let e of t.open)await re({path:e,name:e.split(`/`).pop()??e,text:!0});t.active&&(i(t.active),M(t.active))})())},[e]),(0,z.useEffect)(()=>{if(!e)return;let n=setTimeout(()=>{let n=jg();n[e]={open:t.map(e=>e.path),expanded:[...p],...r?{active:r}:{}},Mg(n)},400);return()=>{clearTimeout(n)}},[e,t,p,r]);let N=(0,z.useCallback)(t=>{e&&mg(_g(e,t)).then(e=>{f(n=>({...n,[t]:e}))}).catch(e=>{f(n=>({...n,[t]:{error:hg(e)}}))})},[e]),te=(0,z.useCallback)(e=>{m(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ne=(0,z.useCallback)(()=>{e&&(f({}),m(new Set),mg(_g(e,``)).then(e=>{f({"":e})}).catch(e=>{f({"":{error:hg(e)}})}))},[e]);(0,z.useEffect)(()=>{let t=h.trim();if(!e||!t){v(null),b(!1);return}let n=!0;b(!0);let r=setTimeout(()=>{mg(bg(e,t)).then(e=>{n&&(v(e),b(!1))}).catch(e=>{n&&(v({mode:`search`,query:t,hits:[],truncated:!1,skipped:[]}),b(!1),o(`搜索失败:${e instanceof Error?e.message:`未知错误`}`))})},220);return()=>{n=!1,clearTimeout(r)}},[h,e]);let re=(0,z.useCallback)(async r=>{if(e){if(r.text===!1)o(`「${r.name}」不支持以文本打开(二进制文件)。`);else if(t.some(e=>e.path===r.path))i(r.path);else{o(``);try{let t=await mg(vg(e,r.path));n(e=>e.some(e=>e.path===r.path)?e:[...e,{path:t.path,name:r.name,content:t.content,etag:t.meta.etag,dirty:!1}]),i(t.path),u(e=>({...e,[t.path]:!1}))}catch(e){o(`打不开「${r.name}」:${e instanceof Error?e.message:`未知错误`}`)}}}},[e,t]),ie=(0,z.useCallback)(e=>{n(t=>{let n=t.find(t=>t.path===e);if(n?.dirty&&!window.confirm(`「${n.name}」有未保存的修改,关掉就丢了。仍然关闭?`))return t;let a=t.findIndex(t=>t.path===e),o=t.filter(t=>t.path!==e);return e===r&&i(o.length===0?void 0:o[Math.min(a,o.length-1)]?.path),o})},[r]),ae=(0,z.useCallback)((e,t)=>{n(n=>n.map(n=>n.path===e?{...n,content:t,dirty:!0}:n))},[]);(0,z.useEffect)(()=>{if(!e||t.length===0)return;let n=!0,r=t.map(e=>e.path),i=setInterval(()=>{for(let i of r)mg(yg(e,i)).then(e=>{if(!n)return;let r=t.find(e=>e.path===i);r&&e.etag!==r.etag&&u(e=>({...e,[i]:!0}))}).catch(()=>{})},lg);return()=>{n=!1,clearInterval(i)}},[e,t]);let oe=(0,z.useCallback)(async(r,i)=>{if(!e)return;let a=t.find(e=>e.path===r);if(!a)return;c(e=>({...e,[r]:{state:`saving`,message:``}}));let o=a.etag;if(i)try{o=(await mg(yg(e,r))).etag}catch(e){c(t=>({...t,[r]:{state:`error`,message:`无法读取磁盘上的最新版本:${e instanceof Error?e.message:`未知错误`}`}}));return}try{let t=await mg(vg(e,r),{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({path:r,content:a.content,baseEtag:o})});n(e=>e.map(e=>e.path===r?{...e,etag:t.meta.etag,dirty:!1}:e)),u(e=>({...e,[r]:!1})),c(e=>({...e,[r]:{state:`saved`,message:`已保存 ${Sg(t.meta.modifiedAt)}`}}))}catch(e){let t=e instanceof dg&&e.body.code===`stale`;c(n=>({...n,[r]:{state:t?`conflict`:`error`,message:e instanceof Error?e.message:`保存失败`}})),t&&u(e=>({...e,[r]:!0}))}},[e,t]),se=(0,z.useCallback)(async t=>{if(e)try{let r=await mg(vg(e,t));n(e=>e.map(e=>e.path===t?{...e,content:r.content,etag:r.meta.etag,dirty:!1}:e)),u(e=>({...e,[t]:!1})),c(e=>({...e,[t]:{state:`saved`,message:`已重新载入磁盘版本`}}))}catch(e){c(n=>({...n,[t]:{state:`error`,message:e instanceof Error?e.message:`重新载入失败`}}))}},[e]),ce=t.find(e=>e.path===r),le=(0,z.useMemo)(()=>t.map(e=>({id:e.path,label:e.name,title:e.path,closable:!0,badge:e.dirty?(0,B.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[t]),ue=(0,z.useMemo)(()=>new Set(t.map(e=>e.path)),[t]),de=(0,z.useCallback)((e,t,n)=>{A(r=>({...r,[e]:{changes:t,dropped:n}}))},[]),fe=e?k[e]:void 0,pe=fe?.changes??[],me=fe?.dropped??0;return{open:t,activePath:r,active:ce,tabItems:le,openPaths:ue,notice:a,setNotice:o,saves:s,external:l,openFile:re,setActivePath:i,closeFile:ie,updateBuffer:ae,save:oe,reload:se,listings:d,expanded:p,toggleDirectory:te,loadDirectory:N,refreshTree:ne,query:h,setQuery:g,hits:_,searching:y,changed:pe,changedPaths:(0,z.useMemo)(()=>new Set(pe.map(e=>e.path)),[pe]),changedDirs:(0,z.useMemo)(()=>{let e=new Set;for(let t of pe){let n=t.path.split(`/`);for(let t=1;t<n.length;t++)e.add(n.slice(0,t).join(`/`))}return e},[pe]),changedDropped:me,setChangedFor:de,index:x,indexComplete:C,indexSkipped:T,setIndex:D,setIndexStatus:O,restoredActive:j}}var Ag=`super-pi.file-workbench.v1`;function jg(){try{if(typeof window>`u`)return{};let e=JSON.parse(window.localStorage.getItem(`super-pi.file-workbench.v1`)??`null`);if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e)){if(!r||typeof r!=`object`)continue;let e=r;t[n]={open:Array.isArray(e.open)?e.open.filter(e=>typeof e==`string`):[],expanded:Array.isArray(e.expanded)?e.expanded.filter(e=>typeof e==`string`):[],...typeof e.active==`string`?{active:e.active}:{}}}return t}catch{return{}}}function Mg(e){try{typeof window<`u`&&window.localStorage.setItem(Ag,JSON.stringify(e))}catch{}}function Ng({workspaceId:e,files:t,onOpenFile:n,onOpenChanged:r}){let{open:i,openPaths:a,notice:o,setNotice:s,openFile:c,listings:l,expanded:u,toggleDirectory:d,loadDirectory:f,refreshTree:p,query:m,setQuery:h,hits:g,searching:_,changed:v,changedPaths:y,changedDirs:b,changedDropped:x}=t,S=(0,z.useCallback)(e=>{n?n(e):c(e)},[n,c]),C=l[``],w=m.trim(),T=(0,z.useMemo)(()=>w?_||!g?(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-searching":`1`,children:`搜索中…`}):g.hits.length===0?(0,B.jsxs)(`p`,{className:`rail-empty`,"data-file-search-empty":`1`,children:[`没有匹配「`,w,`」的文件。`]}):(0,B.jsxs)(B.Fragment,{children:[g.truncated&&(0,B.jsx)(`p`,{className:`file-search-note`,"data-file-search-partial":`1`,children:`结果不完整:搜索有上限,只列出了一部分。`}),g.skipped.length>0&&(0,B.jsxs)(`p`,{className:`file-search-note`,"data-file-search-skipped":`1`,children:[`已跳过 `,g.skipped.length,` 个目录(node_modules、.git 等)。`]}),(0,B.jsx)(`ul`,{className:`file-list`,children:g.hits.map(e=>(0,B.jsx)(`li`,{children:(0,B.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-hit":e.path,"data-file-hit-open":a.has(e.path)?`1`:`0`,onClick:()=>S({path:e.path,name:e.name,text:!0}),children:[(0,B.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,B.jsx)(`span`,{className:`file-name`,children:e.name}),a.has(e.path)&&(0,B.jsx)(`span`,{className:`file-open-mark`,"data-file-open-mark":e.path,title:`已经打开`,"aria-label":`已经打开`,children:`●`}),(0,B.jsx)(`span`,{className:`file-badge-path`,children:e.directory||`/`})]})},e.path))})]}):e?C===void 0?(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-root-loading":`1`,children:`读取工作区…`}):`error`in C?(0,B.jsx)(Og,{error:C.error}):(0,B.jsxs)(B.Fragment,{children:[C.truncated&&(0,B.jsx)(`p`,{className:`file-search-note`,"data-file-truncated-root":`1`,children:`条目过多,只显示前一部分。`}),C.entries.length===0?(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-root-empty":`1`,children:`这个工作区是空的,没有文件也没有子目录。`}):(0,B.jsx)(`ul`,{className:`file-list`,children:C.entries.map(t=>t.kind===`directory`?(0,B.jsx)(Cg,{workspaceId:e,entryPath:t.path,name:t.name,listings:l,expanded:u,toggle:d,loadDirectory:f,openPaths:a,changedDirs:b,changedPaths:y,onOpen:e=>S(e),depth:0},t.path):(0,B.jsx)(wg,{entry:t,depth:0,openPaths:a,changedPaths:y,onOpen:e=>S(e)},t.path))})]}):(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-no-workspace":`1`,children:`先在左侧选一个工作区,这里会显示它的文件。`}),[w,_,g,e,C,l,u,d,f,S,a,b,y]);return(0,B.jsxs)(`div`,{className:`files-panel`,"data-files-panel":`1`,"data-files-open-count":i.length,"data-files-changed-count":v.length,children:[(0,B.jsxs)(`div`,{className:`files-search`,children:[(0,B.jsx)(`input`,{type:`search`,className:`files-search-input`,"data-file-search-input":`1`,value:m,placeholder:`按文件名搜索…`,"aria-label":`按文件名搜索`,onChange:e=>h(e.target.value)}),(0,B.jsx)(`button`,{type:`button`,className:`files-refresh`,"data-file-refresh":`1`,title:`重新读取目录`,"aria-label":`重新读取目录`,disabled:!e,onClick:()=>p(),children:`↻`})]}),v.length>0&&(0,B.jsxs)(`div`,{className:`files-changed`,"data-file-changed-list":`1`,children:[(0,B.jsxs)(`p`,{className:`files-changed-head`,"data-file-changed-head":`1`,children:[`agent 改了 `,v.length,` 个文件`]}),x>0&&(0,B.jsxs)(`p`,{className:`file-search-note`,"data-file-changed-dropped":`1`,children:[`还有 `,x,` 个改动没有记录(超过保留上限)。`]}),(0,B.jsx)(`ul`,{className:`file-list`,children:v.map(e=>(0,B.jsx)(`li`,{children:(0,B.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-changed-open":e.path,title:`${e.path}(点击查看改动)`,onClick:()=>r?.(e.path),children:[(0,B.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,B.jsx)(`span`,{className:`file-name`,children:e.path.split(`/`).pop()}),(0,B.jsx)(`span`,{className:`file-badge-path`,children:e.path.split(`/`).slice(0,-1).join(`/`)||`/`}),(0,B.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-changed-kind":e.path,children:e.baseline===null&&!e.baselineUnknown?`新建`:`已改`})]})},e.path))})]}),o&&(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-notice":`1`,children:o}),(0,B.jsx)(`div`,{className:`files-tree`,"data-file-tree":w?`search`:`browse`,children:T}),i.length===0&&(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-none-open":`1`,children:`点一个文本文件,它会在上面的标签栏开一个标签,正文显示在中间主画面。`}),i.length>0&&(0,B.jsxs)(`p`,{className:`files-hint`,"data-file-open-hint":`1`,children:[`已打开 `,i.length,` 个文件,正文显示在中间主画面;点上面的标签切换,点这里的行切换。`]}),(0,B.jsxs)(`p`,{className:`files-footnote`,"data-files-footnote":`1`,children:[`只支持纯文本(md / 代码),二进制文件不会打开。写入只允许覆盖已存在的文件,不新建,不删除。`,i.length>0&&` 当前打开 ${i.length} 个文件,占 ${xg(i.reduce((e,t)=>e+t.content.length,0))}。`]})]})}function Pg({workspaceId:e,onOpen:t,onClose:n}){let[r,i]=(0,z.useState)(``),[a,o]=(0,z.useState)(null),[s,c]=(0,z.useState)(``),[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(0),p=(0,z.useRef)(null),m=(0,z.useRef)(null);(0,z.useEffect)(()=>{p.current?.focus()},[]),(0,z.useEffect)(()=>{m.current?.scrollIntoView({block:`nearest`})},[d]),(0,z.useEffect)(()=>{let t=r.trim();if(o(null),c(``),f(0),!e||!t){u(!1);return}let n=!0;u(!0);let i=setTimeout(()=>{mg(`/api/files/search?workspaceId=${gg(e)}&q=${gg(t)}`).then(e=>{n&&(o(e),u(!1))}).catch(e=>{n&&(c(e instanceof Error?e.message:`未知错误`),u(!1))})},220);return()=>{n=!1,clearTimeout(i)}},[r,e]);let h=e=>{e&&(t(e),n())},g=a?.truncated||a?.complete===!1,_={index:`索引未完整`,size:`文件超过 512KB`,depth:`目录超过 12 层`,time:`搜索超过 10 秒`,results:`达到 500 条上限`,output:`SDK 输出达到上限`,line:`长行已截断`,unreadable:`部分文件无法读取`};return(0,B.jsx)(`div`,{className:`quick-open-backdrop`,"data-content-search":`1`,role:`presentation`,onMouseDown:n,children:(0,B.jsxs)(`div`,{className:`quick-open content-search`,role:`dialog`,"aria-modal":`true`,"aria-label":`内容搜索`,onMouseDown:e=>e.stopPropagation(),children:[(0,B.jsx)(`input`,{ref:p,className:`quick-open-input`,"data-content-search-input":`1`,value:r,maxLength:256,placeholder:`内容搜索(区分大小写,按字面匹配)`,"aria-label":`内容搜索`,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Escape`?(e.preventDefault(),n()):e.key===`ArrowDown`?(e.preventDefault(),f(e=>Math.min(e+1,Math.max(0,(a?.hits.length??0)-1)))):e.key===`ArrowUp`?(e.preventDefault(),f(e=>Math.max(0,e-1))):e.key===`Enter`&&(e.preventDefault(),h(a?.hits[d]))}}),(0,B.jsxs)(`p`,{className:`quick-open-status`,role:`status`,"data-content-search-status":s?`error`:l?`searching`:g?`partial`:`complete`,children:[s?`✕ 搜索失败:`+s:l?`… 搜索中`:e?g?`⚠ 结果不完整`:a?`✓ 搜索完成`:`○ 输入要搜索的内容`:`○ 请先选择工作区`,a?` · ${a.hits.length} 条命中`:``,` · Esc 关闭`]}),g&&(0,B.jsxs)(`p`,{className:`quick-open-status`,"data-content-search-partial":`1`,children:[`⚠ 结果不完整:`,a?.reasons.map(e=>_[e]??e).join(`;`)]}),a&&a.skipped.length>0&&(0,B.jsxs)(`details`,{className:`quick-open-status`,"data-content-search-skipped":`1`,children:[(0,B.jsxs)(`summary`,{children:[`↷ 已跳过 `,a.skipped.length,` 个文件或目录`]}),(0,B.jsx)(`p`,{className:`content-search-skipped-paths`,children:a.skipped.join(`
|
|
50
|
-
`)})]}),a&&!l&&a.hits.length===0&&(0,B.jsx)(`p`,{className:`quick-open-status`,"data-content-search-empty":`1`,children:`○ 没有匹配的行`}),(0,B.jsx)(`ul`,{className:`quick-open-results content-search-results`,role:`listbox`,children:a?.hits.map((e,t)=>(0,B.jsx)(`li`,{children:(0,B.jsxs)(`button`,{ref:t===d?m:void 0,type:`button`,"data-content-search-result":`${e.path}:${e.line}`,className:`quick-open-result content-search-result${d===t?` quick-open-result-active`:``}`,"aria-selected":d===t,onMouseEnter:()=>f(t),onClick:()=>h(e),children:[(0,B.jsxs)(`span`,{children:[e.path,`:`,e.line]}),(0,B.jsx)(`small`,{title:e.text,children:e.text})]})},`${e.path}:${e.line}`))})]})})}function Fg({entries:e,complete:t,skipped:n,onOpen:r,onClose:i}){let[a,o]=(0,z.useState)(``),[s,c]=(0,z.useState)(0),l=(0,z.useRef)(null),u=(0,z.useMemo)(()=>e.filter(e=>e.kind===`file`&&e.text!==!1),[e]),d=(0,z.useMemo)(()=>a.trim()?new ng(u,{keys:[`path`],threshold:.38,ignoreLocation:!0}).search(a).slice(0,20).map(e=>e.item):u.slice(0,20),[u,a]);(0,z.useEffect)(()=>{l.current?.focus(),c(0)},[a]);let f=(0,z.useCallback)(e=>{e&&(r({path:e.path,name:e.path.split(`/`).pop()??e.path,text:e.text}),i())},[r,i]);return(0,B.jsx)(`div`,{className:`quick-open-backdrop`,"data-quick-open":`1`,role:`presentation`,onMouseDown:i,children:(0,B.jsxs)(`div`,{className:`quick-open`,role:`dialog`,"aria-modal":`true`,"aria-label":`Quick Open`,onMouseDown:e=>e.stopPropagation(),children:[(0,B.jsx)(`input`,{ref:l,className:`quick-open-input`,"data-quick-open-input":`1`,value:a,placeholder:`Quick Open: type a file path`,"aria-label":`Quick Open file path`,onChange:e=>o(e.target.value),onKeyDown:e=>{e.key===`Escape`?(e.preventDefault(),i()):e.key===`ArrowDown`?(e.preventDefault(),c(e=>Math.min(e+1,Math.max(0,d.length-1)))):e.key===`ArrowUp`?(e.preventDefault(),c(e=>Math.max(e-1,0))):e.key===`Enter`&&(e.preventDefault(),f(d[s]))}}),(0,B.jsxs)(`p`,{className:`quick-open-status`,"data-quick-open-status":t?`complete`:`partial`,children:[t?`✓ 索引完整`:`⚠ 索引不完整`,` · `,u.length,` 个文件 · Esc 关闭`]}),n.length>0&&(0,B.jsxs)(`p`,{className:`quick-open-status`,"data-quick-open-skipped":`1`,title:n.join(`, `),children:[`↷ 已跳过:`,n.join(`, `)]}),(0,B.jsx)(`ul`,{className:`quick-open-results`,role:`listbox`,children:d.map((e,t)=>(0,B.jsx)(`li`,{children:(0,B.jsxs)(`button`,{type:`button`,"data-quick-open-result":e.path,className:t===s?`quick-open-result quick-open-result-active`:`quick-open-result`,"aria-selected":t===s,onMouseEnter:()=>c(t),onClick:()=>f(e),children:[(0,B.jsx)(`span`,{children:e.path.split(`/`).pop()}),(0,B.jsx)(`small`,{children:e.path})]})},e.path))})]})})}function Ig(e,t,n=88,r=200){let i=Math.max(0,Math.floor(e));if(!Number.isFinite(t)||t<=0)return{perRow:Math.max(1,i),width:n};if(i===0)return{perRow:1,width:n};if(i===1)return{perRow:1,width:Math.min(r,t)};let a=t/i;if(a>=n)return{perRow:i,width:Math.min(a,r)};for(let e=2;e<=i;e+=1){let a=Math.ceil(i/e),o=t/a;if(o>=n)return{perRow:a,width:Math.min(o,r)}}return{perRow:1,width:n}}function Lg(e,t){let n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r}function Rg(e,t,n=88,r=200){let[i,a]=(0,z.useState)(()=>Ig(e,0,n,r)),[o,s]=(0,z.useState)(null),c=(0,z.useCallback)(()=>{let i=Ig(e,t,n,r);s({count:e,containerWidth:t}),a(e=>e.perRow===i.perRow&&e.width===i.width?e:i)},[e,t,n,r]),l=(0,z.useRef)(t);(0,z.useEffect)(()=>{t<=0||l.current!==t&&(l.current=t,c())},[t,c]);let u=(0,z.useRef)(null);return(0,z.useEffect)(()=>{let t=u.current;u.current=e,t!==null&&e>t&&c()},[e,c]),{layout:i,frozen:o!==null&&o.count!==e,recompute:c}}function zg({tabs:e,activeId:t,onSelect:n,onClose:r,ariaLabel:i,minWidth:a=88,maxWidth:o=200,prefix:s=`workspace-tab`,idPrefix:c=s,className:l}){let u=(0,z.useRef)(null),[d,f]=(0,z.useState)(0),{layout:p,frozen:m,recompute:h}=Rg(e.length,d,a,o);(0,z.useLayoutEffect)(()=>{let e=u.current;if(!e||typeof ResizeObserver>`u`)return;let t=()=>{let t=e.clientWidth;t>0&&f(t)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let g=Lg(e,p.perRow),_=(e,t)=>t===void 0?{}:{[`data-${s}-${e}`]:t},v=e.filter(e=>e.kind===`file`).length,y=e.filter(e=>e.kind===`session`||!e.kind).length,b=t=>({[`data-${t}-strip`]:`1`,...m?{[`data-${t}-frozen`]:`1`}:{},[`data-${t}-count`]:t===`file-tab`?v:t===`session-tab`?y:e.length,[`data-${t}-min`]:a,[`data-${t}-max`]:o,[`data-${t}-per-row`]:p.perRow,[`data-${t}-width`]:Math.round(p.width*100)/100}),x=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&h()},S=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&h()};(0,z.useEffect)(()=>{if(!m)return;let e=u.current;if(!e)return;let t=t=>{let n=e.getBoundingClientRect();t.clientX>=n.left&&t.clientX<=n.right&&t.clientY>=n.top&&t.clientY<=n.bottom||h()};return document.addEventListener(`mousemove`,t,!0),()=>document.removeEventListener(`mousemove`,t,!0)},[m,h]);let C=[`${s}-strip`,`workspace-tab-strip`,`session-tab-strip`,`file-tab-strip`,l].filter(Boolean).join(` `);return(0,B.jsx)(`div`,{ref:u,className:C,role:`tablist`,"aria-label":i??`工作区标签页`,..._(`strip`,`1`),...b(`workspace-tab`),...b(`session-tab`),...b(`file-tab`),style:{"--tab-w":`${p.width}px`},onMouseEnter:x,onMouseLeave:S,children:g.map((i,a)=>(0,B.jsx)(`div`,{className:`${s}-row workspace-tab-row session-tab-row file-tab-row`,role:`presentation`,..._(`row`,a),children:i.map(i=>{let a=i.id===t||i.rawId!==void 0&&i.rawId===t,o=i.title??i.label,l=i.kind,u=i.rawId??i.id,d=e.findIndex(e=>e.id===i.id),f=[s,a?`${s}-active`:``,`workspace-tab`,a?`workspace-tab-active`:``,l?`${l}-tab`:``,l&&a?`${l}-tab-active`:``].filter(Boolean).join(` `);return(0,B.jsxs)(`div`,{role:`tab`,id:`${c}-${i.id}`,"aria-selected":a,"aria-controls":`${c}-panel-${i.id}`,tabIndex:a?0:-1,className:f,..._(`id`,u),..._(`index`,d),...a?_(`active`,`1`):{},..._(`closable`,i.closable===!1?`0`:`1`),...l?{"data-tab-kind":l}:{},...l===`session`||!l?{"data-session-tab-id":u,"data-session-tab-index":d,...a?{"data-session-tab-active":`1`}:{},"data-session-tab-closable":i.closable===!1?`0`:`1`}:{},...l===`file`?{"data-file-tab-id":u,"data-file-tab-index":d,...a?{"data-file-tab-active":`1`}:{},"data-file-tab-closable":i.closable===!1?`0`:`1`}:{},title:o,style:{width:p.width,boxSizing:`border-box`},onClick:()=>n?.(i.id),onAuxClick:e=>{e.button===1&&(e.preventDefault(),e.stopPropagation(),i.closable!==!1&&r&&r(i.id))},onMouseDown:e=>{e.button===1&&e.preventDefault()},onKeyDown:t=>{if(t.key!==`ArrowLeft`&&t.key!==`ArrowRight`)return;t.preventDefault();let r=t.key===`ArrowRight`?1:-1,a=e[(e.findIndex(e=>e.id===i.id)+r+e.length)%e.length];a&&n?.(a.id)},children:[i.icon&&(0,B.jsx)(`span`,{className:`${s}-icon workspace-tab-icon`,children:i.icon}),i.badge,(0,B.jsx)(`span`,{className:`${s}-label workspace-tab-label ${l?`${l}-tab-label`:``}`,..._(`label`,u),...l===`session`||!l?{"data-session-tab-label":u}:{},...l===`file`?{"data-file-tab-label":u}:{},children:i.label}),i.closable!==!1&&r&&(0,B.jsx)(`button`,{type:`button`,className:`${s}-close workspace-tab-close ${l?`${l}-tab-close`:``}`,..._(`close`,u),...l===`session`||!l?{"data-session-tab-close":u}:{},...l===`file`?{"data-file-tab-close":u}:{},onClick:e=>{e.stopPropagation(),r(i.id)},title:`关闭 ${o}`,"aria-label":`关闭 ${o}`,children:`×`})]},i.id)})},`row_${a}`))})}var Bg={pending:`未开始`,running:`运行中`,completed:`已完成`,failed:`失败`,skipped:`已跳过`,stopped:`已停止`},Vg={running:`运行中`,completed:`全部完成`,failed:`中途失败`,stopped:`已停止`},Hg={pending:`○`,running:`◐`,completed:`✓`,failed:`✕`,skipped:`→`,stopped:`■`},Ug={stop:`失败即停`,skip:`失败跳过`,"retry:1":`失败重试 1 次`,"retry:2":`失败重试 2 次`,"retry:3":`失败重试 3 次`};function Wg(e){let t=Math.max(0,Math.round(e/1e3)),n=t%60,r=Math.floor(t/60)%60,i=Math.floor(t/3600),a=e=>String(e).padStart(2,`0`);return i>0?`${i}h ${a(r)}:${a(n)}`:`${r}:${a(n)}`}function Gg(e){let t=e.status===`running`,[n,r]=(0,z.useState)(0);(0,z.useEffect)(()=>{if(!t)return;r(Date.now());let e=window.setInterval(()=>r(Date.now()),200);return()=>window.clearInterval(e)},[t,e.startedAt]);let i=Date.parse(e.startedAt);if(Number.isFinite(i)){if(!t){let t=Date.parse(e.finishedAt??``);return Number.isFinite(t)?t-i:void 0}return n>0?n-i:void 0}}function Kg({step:e,names:t}){let n=e.attempts.length,r=e.attempts[n-1],i=t.get(e.agentId)||e.agentId,a=e.label?.trim()||i;return(0,B.jsxs)(`li`,{className:`workflow-step workflow-step-${e.status}`,"data-workflow-step":e.index+1,"data-workflow-step-status":e.status,"data-workflow-step-agent":e.agentId,"data-workflow-step-attempts":n,children:[(0,B.jsx)(`span`,{className:`workflow-step-mark`,"aria-hidden":`true`,children:Hg[e.status]}),(0,B.jsxs)(`span`,{className:`workflow-step-n`,"data-workflow-step-n":e.index+1,children:[`第 `,e.index+1,` 步`]}),(0,B.jsx)(`strong`,{className:`workflow-step-name`,"data-workflow-step-name":e.index+1,children:a}),(0,B.jsx)(`span`,{className:`workflow-step-agent`,"data-workflow-step-agent-name":e.index+1,children:i}),n>1&&(0,B.jsxs)(`span`,{className:`workflow-step-tries`,"data-workflow-step-retried":e.index+1,children:[`尝试 `,n,` 次`]}),(0,B.jsx)(`span`,{className:`workflow-step-status`,"data-workflow-step-status-text":e.index+1,children:Bg[e.status]}),e.status===`failed`&&r?.error&&(0,B.jsx)(`span`,{className:`workflow-step-why`,"data-workflow-step-error":e.index+1,children:r.error})]})}function qg({workflow:e,names:t,onStop:n,stopping:r}){let i=e.status===`running`,a=Gg(e),o=e.steps.filter(e=>e.status===`completed`||e.status===`skipped`).length;return(0,B.jsxs)(`article`,{className:`workflow-card workflow-${e.status}`,"data-workflow-card":e.id,"data-workflow-status":e.status,"data-workflow-steps":e.steps.length,"data-workflow-current":e.currentIndex+1,children:[(0,B.jsxs)(`div`,{className:`workflow-head`,children:[(0,B.jsx)(`span`,{className:`workflow-badge`,children:`编排`}),(0,B.jsx)(`strong`,{className:`workflow-summary`,"data-workflow-summary":e.id,children:e.summary}),(0,B.jsxs)(`span`,{className:`workflow-progress`,"data-workflow-progress":e.id,children:[o,`/`,e.steps.length]}),(0,B.jsx)(`span`,{className:`workflow-status`,"data-workflow-status-text":e.id,children:Vg[e.status]??e.status}),(0,B.jsx)(`span`,{className:`workflow-policy`,"data-workflow-policy":e.onFailure,children:Ug[e.onFailure]??e.onFailure}),a!==void 0&&(0,B.jsxs)(`span`,{className:`workflow-clock`,"data-workflow-elapsed":e.id,children:[i?`已运行 `:`用时 `,Wg(a)]}),i&&(0,B.jsx)(`button`,{type:`button`,className:`workflow-stop`,"data-workflow-stop":e.id,disabled:r,onClick:n,children:`停止`})]}),(0,B.jsx)(`ol`,{className:`workflow-steps`,"data-workflow-step-count":e.steps.length,children:e.steps.map(e=>(0,B.jsx)(Kg,{step:e,names:t},e.index))})]})}var Jg=[{id:`agents`,label:`智能体与创建`,icon:`🤖`,title:`Agent 智能体系统与创建指南`,description:`了解 Super Pi 的角色设定机制,以及如何一步步创建你自己的自定义 Agent。`},{id:`workspace`,label:`工作区与会话`,icon:`🗂️`,title:`工作区与多会话管理`,description:`高效管理本地代码仓库、独立会话标签页与多模态图文输入。`},{id:`subagents`,label:`子任务与编排`,icon:`⚡`,title:`子智能体委托与顺序编排使用指南`,description:`让主 Agent 安排分工、交接结果,并查看进度、处理失败与停止任务。`},{id:`model-policy`,label:`模型使用规则`,icon:`🔒`,title:`模型过滤规则(按工作区限制可用模型)`,description:`用正则规则限定哪些工作区只能用哪些模型,防止敏感代码被发到不该用的模型上。`},{id:`memory`,label:`主动记忆`,icon:`🧠`,title:`主动记忆与技能经验`,description:`让 Super Pi 在得到明确证据后保存长期事实、用户偏好和可复用工作方法。`},{id:`knowledge`,label:`知识库`,icon:`📚`,title:`工作区知识库`,description:`导入规范与设计文档,让 Agent 检索原文作答,而不是凭记忆编造。`},{id:`tools`,label:`侧边栏工具`,icon:`🧩`,title:`全局工具:开发、导出与导入`,description:`让 Agent 写一个工具,用一个文件分享给别人,导入前先看清它会做什么。`},{id:`cli`,label:`指令与快捷键`,icon:`⌨️`,title:`Pi 终端命令与键盘快捷操作`,description:`利用 Pi 终端斜杠指令控制服务生命周期,掌握常用快捷键提升效率。`},{id:`themes`,label:`外观与主题`,icon:`🎨`,title:`界面主题与个性化显示`,description:`内置 4 款专业高对比度主题,针对不同环境提供舒适体验。`}];function Yg({onClose:e}){let[t,n]=(0,z.useState)(`agents`);(0,z.useEffect)(()=>{let t=t=>{t.key===`Escape`&&!t.defaultPrevented&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let r=Jg.find(e=>e.id===t)??Jg[0];return(0,B.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,B.jsxs)(`div`,{className:`picker settings-window help-window`,"data-help-window":`1`,onClick:e=>e.stopPropagation(),role:`dialog`,"aria-modal":`true`,"aria-labelledby":`help-window-title`,children:[(0,B.jsxs)(`div`,{className:`settings-window-head help-window-head`,children:[(0,B.jsxs)(`div`,{className:`help-head-title`,children:[(0,B.jsx)(`h2`,{id:`help-window-title`,children:`使用指南与帮助`}),(0,B.jsx)(`span`,{className:`help-badge`,children:`v0.1.x`})]}),(0,B.jsx)(`button`,{type:`button`,className:`help-close-button`,"aria-label":`关闭指南`,onClick:e,children:`✕`})]}),(0,B.jsxs)(`div`,{className:`settings-window-body help-window-body`,children:[(0,B.jsxs)(`nav`,{className:`settings-nav help-nav`,role:`tablist`,"aria-orientation":`vertical`,"aria-label":`使用指南分类`,children:[(0,B.jsx)(`div`,{className:`settings-nav-label`,children:`目录`}),Jg.map(e=>(0,B.jsxs)(`button`,{type:`button`,id:`help-tab-${e.id}`,className:`settings-category help-category`,role:`tab`,"aria-selected":e.id===r.id,"aria-controls":`help-panel`,tabIndex:e.id===r.id?0:-1,onClick:()=>n(e.id),children:[(0,B.jsx)(`span`,{className:`help-tab-icon`,"aria-hidden":`true`,children:e.icon}),(0,B.jsx)(`span`,{children:e.label})]},e.id))]}),(0,B.jsxs)(`div`,{id:`help-panel`,className:`settings-panel help-panel`,role:`tabpanel`,"aria-labelledby":`help-tab-${r.id}`,children:[(0,B.jsxs)(`div`,{className:`help-panel-header`,children:[(0,B.jsx)(`h3`,{className:`help-panel-title`,children:r.title}),(0,B.jsx)(`p`,{className:`help-panel-desc`,children:r.description})]}),(0,B.jsxs)(`div`,{className:`help-panel-content`,children:[r.id===`agents`&&(0,B.jsx)(Qg,{}),r.id===`workspace`&&(0,B.jsx)($g,{}),r.id===`subagents`&&(0,B.jsx)(t_,{}),r.id===`model-policy`&&(0,B.jsx)(e_,{}),r.id===`memory`&&(0,B.jsx)(Xg,{}),r.id===`knowledge`&&(0,B.jsx)(Zg,{}),r.id===`tools`&&(0,B.jsx)(n_,{}),r.id===`cli`&&(0,B.jsx)(r_,{}),r.id===`themes`&&(0,B.jsx)(i_,{})]}),(0,B.jsx)(`div`,{className:`picker-actions help-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e,children:`关闭`})})]})]})]})})}function Xg(){return(0,B.jsxs)(`div`,{className:`help-section-group`,children:[(0,B.jsxs)(`div`,{className:`help-card highlight`,children:[(0,B.jsx)(`h4`,{children:`🧠 它会记住什么?`}),(0,B.jsx)(`p`,{children:`用户档案保存跨工作区的长期偏好;工作区事实保存环境与项目约定;技能保存已经验证过的步骤、命令和坑。临时结果、秘密和未验证的失败不会保存。`})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`主动保存与后台复盘`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[`主 Agent 可以使用 `,(0,B.jsx)(`code`,{children:`memory`}),` 和 `,(0,B.jsx)(`code`,{children:`skill_manage`}),` 工具主动保存;说“记住了”本身不会写入。`]}),(0,B.jsx)(`li`,{children:`每隔若干回合,系统会在独立会话中复盘最近证据。复盘不能读写工作区文件、执行命令或派发任务。`}),(0,B.jsx)(`li`,{children:`读取记忆和历史只返回带来源的参考数据,不能把记忆中的文字当作新的指令。`})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`权限与审批`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsx)(`li`,{children:`子 Agent 可以读取相关记忆,但没有写入权限。`}),(0,B.jsx)(`li`,{children:`后台复盘新增记忆可以直接保存;修改或删除旧条目会进入设置中的待审批列表。`}),(0,B.jsx)(`li`,{children:`在“设置 → 主动记忆”可以开关功能、调整复盘间隔、编辑条目和批准提案。`})]})]})]})}function Zg(){return(0,B.jsxs)(`div`,{className:`help-section-group`,children:[(0,B.jsxs)(`div`,{className:`help-card highlight`,children:[(0,B.jsx)(`h4`,{children:`📚 它解决什么问题?`}),(0,B.jsx)(`p`,{children:`Agent 默认靠训练时的记忆回答项目里的问题。知识库让你把规范、设计稿、会议纪要导入工作区,Agent 在回答前检索这些文档的原文片段,而不是凭印象编造。它与“主动记忆”不同:记忆是 Agent 自己沉淀的事实和技能,知识库只有你能写入。`})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`怎么用`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsx)(`li`,{children:`在“设置 → 知识库”里点“浏览工作区文件…”,在弹出的浏览器里挑一个 Markdown 或文本文件,挑完即导入。也可以直接粘贴正文,或手动填写相对路径。`}),(0,B.jsx)(`li`,{children:`同一个文件内容改了再导入就是更新,不会留下旧版本;同样的内容换个标题再导入也不会变成两篇。`}),(0,B.jsx)(`li`,{children:`面板里的“试检索”会用和 Agent 相同的检索器回答,方便你在交给 Agent 之前先确认它找得到。`}),(0,B.jsxs)(`li`,{children:[`从下一条消息开始生效。Agent 使用 `,(0,B.jsx)(`code`,{children:`knowledge_search`}),` 检索,只拿得到片段和来源,拿不到整篇文档。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`语义检索是内置的`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[`关键词检索始终可用。语义检索让“撤销购买”也能找到写着“取消订单”的段落,它靠一个`,(0,B.jsx)(`strong`,{children:`随安装包一起分发`}),`的中文模型在本机运行,不需要额外下载、不需要联网、也不会把文档发到任何服务。`]}),(0,B.jsxs)(`li`,{children:[`第一次检索时加载模型(约一秒),之后一直可用。设 `,(0,B.jsx)(`code`,{children:`SUPER_PI_KNOWLEDGE_EMBEDDINGS=0`}),` 可以彻底关闭语义检索,只保留关键词检索。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`它不知道的事`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsx)(`li`,{children:`知识库只会检索它有的东西。文档里没写的,它检索出来也不会有——所以导入什么,直接决定它能回答什么。`}),(0,B.jsx)(`li`,{children:`语义检索总会返回“最接近的那一段”,即使这一段其实并不回答问题。检索结果带一个分数,低分意味着这可能只是最像的一条,Agent 会被要求先核对再使用。`}),(0,B.jsx)(`li`,{children:`Agent 对知识库只读,不能写入或删除;导入和删除只有你能做。`})]})]})]})}function Qg(){return(0,B.jsxs)(`div`,{className:`help-section-group`,children:[(0,B.jsxs)(`div`,{className:`help-card highlight`,children:[(0,B.jsx)(`h4`,{children:`💡 Agent 是什么?`}),(0,B.jsxs)(`p`,{children:[`在 Super Pi 中,`,(0,B.jsx)(`strong`,{children:`Agent(智能体)`}),` 是一套独立的「角色提示词设定与能力配置」。 通过切换 Agent,模型将扮演专精工程师、系统架构师、代码审查员或规划专家等不同角色,遵循指定的原则来协助你完成任务。`]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`📁 Agent 文件存放在哪里?`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`内置 Agent 目录:`}),`项目根目录下的 `,(0,B.jsx)(`code`,{children:`agents/`}),` 文件夹,例如 `,(0,B.jsx)(`code`,{children:`agents/coder.md`}),`、`,(0,B.jsx)(`code`,{children:`agents/planner.md`}),`、`,(0,B.jsx)(`code`,{children:`agents/reviewer.md`}),` 等。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`用户自定义持久化目录:`}),`用户主目录下的 `,(0,B.jsx)(`code`,{children:`~/.super-pi/agents/`}),`,放入此目录的文件在所有项目和更新中均持久有效。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`🚀 如何创建一个全新的自定义 Agent?`}),(0,B.jsxs)(`div`,{className:`help-steps`,children:[(0,B.jsxs)(`div`,{className:`help-step`,children:[(0,B.jsx)(`span`,{className:`step-num`,children:`1`}),(0,B.jsxs)(`div`,{className:`step-body`,children:[(0,B.jsx)(`strong`,{children:`创建 Markdown 文件`}),(0,B.jsxs)(`p`,{children:[`在 `,(0,B.jsx)(`code`,{children:`agents/`}),` 或 `,(0,B.jsx)(`code`,{children:`~/.super-pi/agents/`}),` 目录下新建文件,例如 `,(0,B.jsx)(`code`,{children:`architect.md`}),`。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-step`,children:[(0,B.jsx)(`span`,{className:`step-num`,children:`2`}),(0,B.jsxs)(`div`,{className:`step-body`,children:[(0,B.jsx)(`strong`,{children:`编写元数据与系统提示词`}),(0,B.jsx)(`p`,{children:`文件开头使用 YAML Frontmatter 声明名称和描述,正文编写设定提示词:`}),(0,B.jsx)(`pre`,{className:`help-code-block`,children:(0,B.jsx)(`code`,{children:`---
|
|
49
|
+
`),r=n.slice(0,t-1).reduce((e,t)=>e+t.length+1,0);e.focus(),e.setSelectionRange(r,r+n[t-1].length);let a=parseFloat(getComputedStyle(e).lineHeight);e.scrollTop=Math.max(0,(t-1)*a-e.clientHeight/2),e.scrollLeft=0;let o=e.previousElementSibling;o instanceof HTMLElement&&(o.scrollTop=e.scrollTop,o.scrollLeft=0)},[e.path,i,l]);let f=/\.md$/i.test(e.path);return(0,B.jsxs)(`div`,{className:`file-editor`,"data-file-editor":e.path,"data-save-state":t,children:[(0,B.jsxs)(`div`,{className:`file-editor-head`,children:[(0,B.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path}),(0,B.jsxs)(`span`,{className:`file-editor-flags`,children:[f&&(0,B.jsx)(`button`,{type:`button`,className:`file-preview-toggle`,onClick:()=>u(e=>!e),children:l?`原文`:`预览`}),e.dirty&&(0,B.jsx)(`span`,{className:`file-dirty`,"data-file-dirty":`1`,children:`未保存`}),(0,B.jsx)(`button`,{type:`button`,className:`file-save`,"data-file-save":e.path,onClick:o,disabled:t===`saving`,children:t===`saving`?`保存中…`:`保存`})]})]}),r&&t!==`conflict`&&(0,B.jsxs)(`div`,{className:`file-conflict`,"data-file-external":e.path,role:`alert`,children:[(0,B.jsx)(`p`,{children:`这个文件在磁盘上已经被改过了,你的修改还没有覆盖它。`}),(0,B.jsxs)(`div`,{className:`file-conflict-actions`,children:[(0,B.jsx)(`button`,{type:`button`,"data-file-reload":e.path,onClick:s,children:`丢掉我的修改,读磁盘版本`}),(0,B.jsx)(`button`,{type:`button`,"data-file-overwrite":e.path,onClick:c,children:`仍然覆盖磁盘`})]})]}),t===`conflict`&&(0,B.jsxs)(`div`,{className:`file-conflict`,"data-file-conflict":e.path,role:`alert`,children:[(0,B.jsx)(`p`,{children:`保存被拒绝:这个文件在磁盘上已经被改过了,覆盖会丢掉对方的改动。`}),(0,B.jsxs)(`div`,{className:`file-conflict-actions`,children:[(0,B.jsx)(`button`,{type:`button`,"data-file-reload":e.path,onClick:s,children:`丢掉我的修改,读磁盘版本`}),(0,B.jsx)(`button`,{type:`button`,"data-file-overwrite":e.path,onClick:c,children:`仍然覆盖磁盘`})]})]}),n&&t!==`conflict`&&!r&&(0,B.jsx)(`p`,{className:`file-editor-message file-message-${t}`,"data-file-message":t,role:`status`,children:n}),f&&l?(0,B.jsx)(`div`,{className:`file-markdown-preview`,"data-file-preview":`markdown`,children:(0,B.jsx)(tm,{source:e.content})}):(0,B.jsx)(z.Suspense,{fallback:(0,B.jsx)(`div`,{className:`file-cm-wrap`,"data-file-text":e.path,"data-file-content":e.content,"data-file-selection":`0,0`,"data-file-editor-ready":`0`,children:(0,B.jsx)(`span`,{className:`file-cm-status`,"data-file-editor-loading":`1`,children:`⌛ 正在加载编辑器…`})}),children:(0,B.jsx)(gg,{path:e.path,value:e.content,onChange:a,jumpToLine:i,onSave:o})})]})}function Mg({line:e}){if(e.kind===`fold`)return(0,B.jsx)(`div`,{className:`file-diff-line file-diff-fold`,"data-diff-kind":`fold`,children:e.text});let t=e.kind===`added`?`+`:e.kind===`removed`?`-`:` `;return(0,B.jsxs)(`div`,{className:`file-diff-line file-diff-${e.kind}`,"data-diff-kind":e.kind,"data-diff-no-newline":e.noNewline?`1`:void 0,children:[(0,B.jsx)(`span`,{className:`file-diff-mark`,"aria-hidden":`true`,children:t}),(0,B.jsx)(`span`,{className:`file-diff-number`,"aria-hidden":`true`,children:e.oldLine??``}),(0,B.jsx)(`span`,{className:`file-diff-number`,"aria-hidden":`true`,children:e.newLine??``}),(0,B.jsx)(`span`,{className:`file-diff-text`,children:e.text}),e.noNewline&&(0,B.jsx)(`span`,{className:`file-diff-no-newline`,title:`这个版本的末尾没有换行`,children:`(末尾无换行)`})]})}function Ng({diff:e,loading:t,error:n,bufferContent:r,mode:i,onMode:a}){if(t)return(0,B.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`loading`,children:(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-diff-loading":`1`,children:`正在读取差异…`})});if(n)return(0,B.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`error`,children:(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-diff-error":`1`,children:n})});if(!e)return(0,B.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`empty`,children:(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-diff-empty":`1`,children:`没有选中的差异。`})});let o=typeof r==`string`,s=i===`buffer`&&o,c=s?e.after:e.before,l=s?r:e.after,u=s?`我未保存的修改`:e.label,d=s?`buffer`:e.baseline,f=o&&e.baseline!==`none`?(0,B.jsxs)(`span`,{className:`file-diff-switch`,"data-file-diff-switch":`1`,children:[(0,B.jsx)(`button`,{type:`button`,className:`file-diff-switch-btn${s?``:` file-diff-switch-active`}`,"data-file-diff-base":`server`,"aria-pressed":!s,onClick:()=>a(`server`),children:`agent 的改动`}),(0,B.jsx)(`button`,{type:`button`,className:`file-diff-switch-btn${s?` file-diff-switch-active`:``}`,"data-file-diff-base":`buffer`,"aria-pressed":s,onClick:()=>a(`buffer`),children:`我的修改`})]}):null;if(d===`none`)return(0,B.jsxs)(`div`,{className:`file-diff`,"data-file-diff-state":`none`,"data-file-diff-baseline":d,children:[(0,B.jsxs)(`div`,{className:`file-editor-head`,children:[(0,B.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path}),(0,B.jsx)(`span`,{className:`file-editor-flags`,children:f})]}),(0,B.jsx)(`p`,{className:`file-diff-nobaseline`,"data-file-diff-nobaseline":`1`,children:u})]});let p=km(c,l),m=Am(p);return(0,B.jsxs)(`div`,{className:`file-diff`,"data-file-diff-state":`ready`,"data-file-diff-baseline":d,"data-file-diff-added":p.added,"data-file-diff-removed":p.removed,children:[(0,B.jsxs)(`div`,{className:`file-editor-head`,children:[(0,B.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path}),(0,B.jsxs)(`span`,{className:`file-editor-flags`,children:[f,(0,B.jsx)(`span`,{className:`file-diff-baseline`,"data-file-diff-label":`1`,children:u}),(0,B.jsxs)(`span`,{className:`file-diff-count`,"data-file-diff-count":`1`,children:[`+`,p.added,` / -`,p.removed]})]})]}),e.beforeUnknown&&!s&&(0,B.jsx)(`p`,{className:`file-diff-warning`,"data-file-diff-before-unknown":`1`,role:`status`,children:`读不到改动前的版本(文件太大或无法读取),这里只显示现在的内容。`}),e.before===null&&!e.beforeUnknown&&!s&&(0,B.jsx)(`p`,{className:`file-diff-warning`,"data-file-diff-is-new":`1`,role:`status`,children:`这个文件是新建的,下面是它的全部内容。`}),p.identical?(0,B.jsx)(`p`,{className:`file-diff-nobaseline`,"data-file-diff-identical":`1`,children:`两个版本没有区别。`}):(0,B.jsx)(`div`,{className:`file-diff-body`,"data-file-diff-body":`1`,children:m.lines.map((e,t)=>(0,B.jsx)(Mg,{line:e},t))})]})}function Pg({error:e}){let t=e.body.code,n=typeof e.body.details?.path==`string`?e.body.details.path:``,r=t===`workspace_missing`?`missing`:t===`timeout`?`timeout`:`failed`;return(0,B.jsxs)(`div`,{className:`rail-empty file-problem`,"data-file-root-error":`1`,"data-file-error-kind":r,role:`alert`,children:[r===`missing`&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`工作区路径不存在,无法读取文件。`}),(0,B.jsx)(`p`,{className:`file-problem-hint`,children:`请确认这个路径是写错了,还是目录被移动或删除了:`}),(0,B.jsx)(`code`,{className:`file-problem-path`,"data-file-error-path":`1`,children:n||e.message})]}),r===`timeout`&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`读取超时,服务端没有回应。`}),(0,B.jsxs)(`p`,{className:`file-problem-hint`,children:[`已经等了 `,vg/1e3,` 秒。如果这个工作区在网络盘上,请检查它是否已连接,然后点上面的 ↻ 重试。`]})]}),r===`failed`&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`读取失败。`}),(0,B.jsx)(`p`,{className:`file-problem-hint`,children:e.message})]})]})}function Fg(e){let[t,n]=(0,z.useState)([]),[r,i]=(0,z.useState)(),[a,o]=(0,z.useState)(``),[s,c]=(0,z.useState)({}),[l,u]=(0,z.useState)({}),[d,f]=(0,z.useState)({}),[p,m]=(0,z.useState)(()=>new Set),[h,g]=(0,z.useState)(``),[_,v]=(0,z.useState)(null),[y,b]=(0,z.useState)(!1),[x,S]=(0,z.useState)([]),[C,w]=(0,z.useState)(!1),[T,E]=(0,z.useState)([]),D=(0,z.useCallback)((e,t)=>S(n=>{let r=new Map(n.map(e=>[e.path,e]));for(let t of e)r.set(t.path,t);for(let e of t)r.delete(e);return[...r.values()]}),[]),O=(0,z.useCallback)((e,t)=>{w(e),E(t)},[]);(0,z.useEffect)(()=>{if(S([]),w(!1),E([]),!e)return;let t=!0;return fetch(`/api/files/index?workspaceId=${encodeURIComponent(e)}`).then(e=>e.json()).then(e=>{t&&(D(e.changed??[],e.removed??[]),w(e.complete===!0),E(e.skipped??[]))}).catch(()=>void 0),()=>{t=!1}},[e,D]);let[k,A]=(0,z.useState)({});(0,z.useEffect)(()=>{if(n([]),i(void 0),o(``),c({}),u({}),f({}),m(new Set),v(null),g(``),b(!1),!e)return;let t=!0;return bg(Cg(e,``)).then(e=>{t&&f({"":e})}).catch(e=>{t&&f({"":{error:xg(e)}})}),()=>{t=!1}},[e]);let ee=(0,z.useRef)(void 0),[j,M]=(0,z.useState)(void 0);(0,z.useEffect)(()=>{if(!e||ee.current===e)return;ee.current=e;let t=Lg()[e];t&&(t.expanded.length&&m(new Set(t.expanded)),t.open.length&&(async()=>{for(let e of t.open)await re({path:e,name:e.split(`/`).pop()??e,text:!0});t.active&&(i(t.active),M(t.active))})())},[e]),(0,z.useEffect)(()=>{if(!e)return;let n=setTimeout(()=>{let n=Lg();n[e]={open:t.map(e=>e.path),expanded:[...p],...r?{active:r}:{}},Rg(n)},400);return()=>{clearTimeout(n)}},[e,t,p,r]);let N=(0,z.useCallback)(t=>{e&&bg(Cg(e,t)).then(e=>{f(n=>({...n,[t]:e}))}).catch(e=>{f(n=>({...n,[t]:{error:xg(e)}}))})},[e]),te=(0,z.useCallback)(e=>{m(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ne=(0,z.useCallback)(()=>{e&&(f({}),m(new Set),bg(Cg(e,``)).then(e=>{f({"":e})}).catch(e=>{f({"":{error:xg(e)}})}))},[e]);(0,z.useEffect)(()=>{let t=h.trim();if(!e||!t){v(null),b(!1);return}let n=!0;b(!0);let r=setTimeout(()=>{bg(Eg(e,t)).then(e=>{n&&(v(e),b(!1))}).catch(e=>{n&&(v({mode:`search`,query:t,hits:[],total:0,indexed:!1}),b(!1),o(`搜索失败:${e instanceof Error?e.message:`未知错误`}`))})},80);return()=>{n=!1,clearTimeout(r)}},[h,e]);let re=(0,z.useCallback)(async r=>{if(e){if(r.text===!1)o(`「${r.name}」不支持以文本打开(二进制文件)。`);else if(t.some(e=>e.path===r.path))i(r.path);else{o(``);try{let t=await bg(wg(e,r.path));n(e=>e.some(e=>e.path===r.path)?e:[...e,{path:t.path,name:r.name,content:t.content,etag:t.meta.etag,dirty:!1}]),i(t.path),u(e=>({...e,[t.path]:!1}))}catch(e){o(`打不开「${r.name}」:${e instanceof Error?e.message:`未知错误`}`)}}}},[e,t]),ie=(0,z.useCallback)(e=>{n(t=>{let n=t.find(t=>t.path===e);if(n?.dirty&&!window.confirm(`「${n.name}」有未保存的修改,关掉就丢了。仍然关闭?`))return t;let a=t.findIndex(t=>t.path===e),o=t.filter(t=>t.path!==e);return e===r&&i(o.length===0?void 0:o[Math.min(a,o.length-1)]?.path),o})},[r]),ae=(0,z.useCallback)((e,t)=>{n(n=>n.map(n=>n.path===e?{...n,content:t,dirty:!0}:n))},[]);(0,z.useEffect)(()=>{if(!e||t.length===0)return;let n=!0,r=t.map(e=>e.path),i=setInterval(()=>{for(let i of r)bg(Tg(e,i)).then(e=>{if(!n)return;let r=t.find(e=>e.path===i);r&&e.etag!==r.etag&&u(e=>({...e,[i]:!0}))}).catch(()=>{})},hg);return()=>{n=!1,clearInterval(i)}},[e,t]);let oe=(0,z.useCallback)(async(r,i)=>{if(!e)return;let a=t.find(e=>e.path===r);if(!a)return;c(e=>({...e,[r]:{state:`saving`,message:``}}));let o=a.etag;if(i)try{o=(await bg(Tg(e,r))).etag}catch(e){c(t=>({...t,[r]:{state:`error`,message:`无法读取磁盘上的最新版本:${e instanceof Error?e.message:`未知错误`}`}}));return}try{let t=await bg(wg(e,r),{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({path:r,content:a.content,baseEtag:o})});n(e=>e.map(e=>e.path===r?{...e,etag:t.meta.etag,dirty:!1}:e)),u(e=>({...e,[r]:!1})),c(e=>({...e,[r]:{state:`saved`,message:`已保存 ${Og(t.meta.modifiedAt)}`}}))}catch(e){let t=e instanceof _g&&e.body.code===`stale`;c(n=>({...n,[r]:{state:t?`conflict`:`error`,message:e instanceof Error?e.message:`保存失败`}})),t&&u(e=>({...e,[r]:!0}))}},[e,t]),se=(0,z.useCallback)(async t=>{if(e)try{let r=await bg(wg(e,t));n(e=>e.map(e=>e.path===t?{...e,content:r.content,etag:r.meta.etag,dirty:!1}:e)),u(e=>({...e,[t]:!1})),c(e=>({...e,[t]:{state:`saved`,message:`已重新载入磁盘版本`}}))}catch(e){c(n=>({...n,[t]:{state:`error`,message:e instanceof Error?e.message:`重新载入失败`}}))}},[e]),ce=t.find(e=>e.path===r),le=(0,z.useMemo)(()=>t.map(e=>({id:e.path,label:e.name,title:e.path,closable:!0,badge:e.dirty?(0,B.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[t]),ue=(0,z.useMemo)(()=>new Set(t.map(e=>e.path)),[t]),de=(0,z.useCallback)((e,t,n)=>{A(r=>({...r,[e]:{changes:t,dropped:n}}))},[]),fe=e?k[e]:void 0,pe=fe?.changes??[],me=fe?.dropped??0;return{open:t,activePath:r,active:ce,tabItems:le,openPaths:ue,notice:a,setNotice:o,saves:s,external:l,openFile:re,setActivePath:i,closeFile:ie,updateBuffer:ae,save:oe,reload:se,listings:d,expanded:p,toggleDirectory:te,loadDirectory:N,refreshTree:ne,query:h,setQuery:g,hits:_,searching:y,changed:pe,changedPaths:(0,z.useMemo)(()=>new Set(pe.map(e=>e.path)),[pe]),changedDirs:(0,z.useMemo)(()=>{let e=new Set;for(let t of pe){let n=t.path.split(`/`);for(let t=1;t<n.length;t++)e.add(n.slice(0,t).join(`/`))}return e},[pe]),changedDropped:me,setChangedFor:de,index:x,indexComplete:C,indexSkipped:T,setIndex:D,setIndexStatus:O,restoredActive:j}}var Ig=`super-pi.file-workbench.v1`;function Lg(){try{if(typeof window>`u`)return{};let e=JSON.parse(window.localStorage.getItem(`super-pi.file-workbench.v1`)??`null`);if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e)){if(!r||typeof r!=`object`)continue;let e=r;t[n]={open:Array.isArray(e.open)?e.open.filter(e=>typeof e==`string`):[],expanded:Array.isArray(e.expanded)?e.expanded.filter(e=>typeof e==`string`):[],...typeof e.active==`string`?{active:e.active}:{}}}return t}catch{return{}}}function Rg(e){try{typeof window<`u`&&window.localStorage.setItem(Ig,JSON.stringify(e))}catch{}}function zg({workspaceId:e,files:t,onOpenFile:n,onOpenChanged:r}){let{open:i,openPaths:a,notice:o,setNotice:s,openFile:c,listings:l,expanded:u,toggleDirectory:d,loadDirectory:f,refreshTree:p,query:m,setQuery:h,hits:g,searching:_,changed:v,changedPaths:y,changedDirs:b,changedDropped:x}=t,S=(0,z.useCallback)(e=>{n?n(e):c(e)},[n,c]),C=l[``],w=m.trim(),T=(0,z.useRef)(null),E=(0,z.useCallback)(e=>{let t=T.current;if(!t)return;let n=e.target?.closest(`.file-row`);if(!n)return;let r=[...t.querySelectorAll(`.file-row`)],i=r.indexOf(n);if(i<0)return;let a=e=>{let t=Math.max(0,Math.min(r.length-1,e));r[t]?.focus()};if(e.key===`ArrowDown`)e.preventDefault(),a(i+1);else if(e.key===`ArrowUp`)e.preventDefault(),a(i-1);else if(e.key===`Home`)e.preventDefault(),a(0);else if(e.key===`End`)e.preventDefault(),a(r.length-1);else if(e.key===`ArrowRight`){let t=n.getAttribute(`data-file-dir-toggle`);t&&n.getAttribute(`aria-expanded`)===`false`&&(e.preventDefault(),d(t))}else if(e.key===`ArrowLeft`){let r=n.getAttribute(`data-file-dir-toggle`);if(r&&n.getAttribute(`aria-expanded`)===`true`){e.preventDefault(),d(r);return}let i=n.getAttribute(`data-file-open`)??n.getAttribute(`data-file-hit`);if(i){e.preventDefault();let n=i.lastIndexOf(`/`),r=n<0?``:i.slice(0,n);(r?t.querySelector(`[data-file-dir-toggle="${CSS.escape(r)}"]`):null)?.focus()}}},[d]),[D,O]=(0,z.useState)(200);(0,z.useEffect)(()=>{O(200)},[w,e]);let k=(0,z.useRef)(null);(0,z.useEffect)(()=>{if(w===``)return;let e=k.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&O(e=>e>=(g?.hits.length??0)?e:e+200)},{rootMargin:`200px`});return t.observe(e),()=>t.disconnect()},[w,g]);let A=(0,z.useMemo)(()=>{if(w){if(_||!g)return(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-searching":`1`,children:`搜索中…`});if(g.hits.length===0)return(0,B.jsxs)(`p`,{className:`rail-empty`,"data-file-search-empty":`1`,children:[`没有匹配「`,w,`」的文件。`]});let e=g.hits.slice(0,D),t=[],n=new Map;for(let r of e){let e=n.get(r.directory);if(e)e.push(r);else{let e=[r];n.set(r.directory,e),t.push({directory:r.directory,hits:e})}}return(0,B.jsxs)(B.Fragment,{children:[t.map(e=>(0,B.jsxs)(`section`,{className:`file-group`,"data-file-search-group":e.directory,children:[(0,B.jsxs)(`h3`,{className:`file-group-head`,"data-file-search-group-head":e.directory,children:[(0,B.jsx)(`span`,{className:`file-group-name`,children:e.directory||`/`}),(0,B.jsx)(`span`,{className:`file-group-count`,children:e.hits.length})]}),(0,B.jsx)(`ul`,{className:`file-list`,children:e.hits.map(e=>(0,B.jsx)(`li`,{children:(0,B.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-hit":e.path,"data-file-hit-open":a.has(e.path)?`1`:`0`,onClick:()=>S({path:e.path,name:e.name,text:!0}),children:[(0,B.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,B.jsx)(cg,{path:e.path}),(0,B.jsx)(`span`,{className:`file-name`,children:e.name}),a.has(e.path)&&(0,B.jsx)(`span`,{className:`file-open-mark`,"data-file-open-mark":e.path,title:`已经打开`,"aria-label":`已经打开`,children:`●`})]})},e.path))})]},e.directory||`/`)),e.length<g.hits.length&&(0,B.jsx)(`div`,{ref:k,className:`file-sentinel`,"data-file-search-more":`1`,children:`正在载入更多…`})]})}return e?C===void 0?(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-root-loading":`1`,children:`读取工作区…`}):`error`in C?(0,B.jsx)(Pg,{error:C.error}):(0,B.jsxs)(B.Fragment,{children:[C.truncated&&(0,B.jsx)(`p`,{className:`file-search-note`,"data-file-truncated-root":`1`,children:`条目过多,只显示前一部分。`}),C.entries.length===0?(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-root-empty":`1`,children:`这个工作区是空的,没有文件也没有子目录。`}):(0,B.jsx)(`ul`,{className:`file-list`,children:C.entries.map(t=>t.kind===`directory`?(0,B.jsx)(kg,{workspaceId:e,entryPath:t.path,name:t.name,listings:l,expanded:u,toggle:d,loadDirectory:f,openPaths:a,changedDirs:b,changedPaths:y,onOpen:e=>S(e),depth:0},t.path):(0,B.jsx)(Ag,{entry:t,depth:0,openPaths:a,changedPaths:y,onOpen:e=>S(e)},t.path))})]}):(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-no-workspace":`1`,children:`先在左侧选一个工作区,这里会显示它的文件。`})},[w,_,g,D,e,C,l,u,d,f,S,a,b,y]);return(0,B.jsxs)(`div`,{className:`files-panel`,"data-files-panel":`1`,"data-files-open-count":i.length,"data-files-changed-count":v.length,ref:T,onKeyDown:E,children:[(0,B.jsxs)(`div`,{className:`files-search`,children:[(0,B.jsx)(`span`,{className:`files-search-icon`,"aria-hidden":`true`,children:(0,B.jsxs)(`svg`,{viewBox:`0 0 16 16`,width:`13`,height:`13`,fill:`none`,stroke:`currentColor`,strokeWidth:1.6,strokeLinecap:`round`,children:[(0,B.jsx)(`circle`,{cx:`7`,cy:`7`,r:`4.6`}),(0,B.jsx)(`path`,{d:`M10.4 10.4 14 14`})]})}),(0,B.jsx)(`input`,{type:`search`,className:`files-search-input`,"data-file-search-input":`1`,value:m,placeholder:`按文件名搜索…`,"aria-label":`按文件名搜索`,onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),h(``))},onChange:e=>h(e.target.value)}),(0,B.jsx)(`button`,{type:`button`,className:`files-refresh`,"data-file-refresh":`1`,title:`重新读取目录`,"aria-label":`重新读取目录`,disabled:!e,onClick:()=>p(),children:`↻`})]}),w&&g&&!_&&(0,B.jsxs)(`p`,{className:`files-count`,"data-file-search-count":`1`,role:`status`,children:[(0,B.jsx)(`b`,{children:g.total.toLocaleString(`zh-CN`)}),` 个结果`,g.indexed===!1&&(0,B.jsx)(`span`,{className:`files-count-note`,"data-file-search-indexing":`1`,children:`正在建立索引…`})]}),v.length>0&&(0,B.jsxs)(`div`,{className:`files-changed`,"data-file-changed-list":`1`,children:[(0,B.jsxs)(`p`,{className:`files-changed-head`,"data-file-changed-head":`1`,children:[`agent 改了 `,v.length,` 个文件`]}),x>0&&(0,B.jsxs)(`p`,{className:`file-search-note`,"data-file-changed-dropped":`1`,children:[`还有 `,x,` 个改动没有记录(超过保留上限)。`]}),(0,B.jsx)(`ul`,{className:`file-list`,children:v.map(e=>(0,B.jsx)(`li`,{children:(0,B.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-changed-open":e.path,title:`${e.path}(点击查看改动)`,onClick:()=>r?.(e.path),children:[(0,B.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,B.jsx)(cg,{path:e.path}),(0,B.jsx)(`span`,{className:`file-name`,children:e.path.split(`/`).pop()}),(0,B.jsx)(`span`,{className:`file-badge-path`,children:e.path.split(`/`).slice(0,-1).join(`/`)||`/`}),(0,B.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-changed-kind":e.path,children:e.baseline===null&&!e.baselineUnknown?`新建`:`已改`})]})},e.path))})]}),o&&(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-notice":`1`,children:o}),(0,B.jsx)(`div`,{className:`files-tree`,"data-file-tree":w?`search`:`browse`,children:A}),i.length===0&&(0,B.jsx)(`p`,{className:`rail-empty`,"data-file-none-open":`1`,children:`点一个文本文件,它会在上面的标签栏开一个标签,正文显示在中间主画面。`}),i.length>0&&(0,B.jsxs)(`p`,{className:`files-hint`,"data-file-open-hint":`1`,children:[`已打开 `,i.length,` 个文件,正文显示在中间主画面;点上面的标签切换,点这里的行切换。`]}),(0,B.jsxs)(`p`,{className:`files-footnote`,"data-files-footnote":`1`,children:[`只支持纯文本(md / 代码),二进制文件不会打开。写入只允许覆盖已存在的文件,不新建,不删除。`,i.length>0&&` 当前打开 ${i.length} 个文件,占 ${Dg(i.reduce((e,t)=>e+t.content.length,0))}。`]})]})}function Bg({workspaceId:e,onOpen:t,onClose:n}){let[r,i]=(0,z.useState)(``),[a,o]=(0,z.useState)(null),[s,c]=(0,z.useState)(``),[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(0),p=(0,z.useRef)(null),m=(0,z.useRef)(null);(0,z.useEffect)(()=>{p.current?.focus()},[]),(0,z.useEffect)(()=>{m.current?.scrollIntoView({block:`nearest`})},[d]),(0,z.useEffect)(()=>{let t=r.trim();if(o(null),c(``),f(0),!e||!t){u(!1);return}let n=!0;u(!0);let i=setTimeout(()=>{bg(`/api/files/search?workspaceId=${Sg(e)}&q=${Sg(t)}`).then(e=>{n&&(o(e),u(!1))}).catch(e=>{n&&(c(e instanceof Error?e.message:`未知错误`),u(!1))})},220);return()=>{n=!1,clearTimeout(i)}},[r,e]);let h=e=>{e&&(t(e),n())},g=a?.truncated||a?.complete===!1,_={index:`索引未完整`,size:`文件超过 512KB`,depth:`目录超过 12 层`,time:`搜索超过 10 秒`,results:`达到 500 条上限`,output:`SDK 输出达到上限`,line:`长行已截断`,unreadable:`部分文件无法读取`};return(0,B.jsx)(`div`,{className:`quick-open-backdrop`,"data-content-search":`1`,role:`presentation`,onMouseDown:n,children:(0,B.jsxs)(`div`,{className:`quick-open content-search`,role:`dialog`,"aria-modal":`true`,"aria-label":`内容搜索`,onMouseDown:e=>e.stopPropagation(),children:[(0,B.jsx)(`input`,{ref:p,className:`quick-open-input`,"data-content-search-input":`1`,value:r,maxLength:256,placeholder:`内容搜索(区分大小写,按字面匹配)`,"aria-label":`内容搜索`,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Escape`?(e.preventDefault(),n()):e.key===`ArrowDown`?(e.preventDefault(),f(e=>Math.min(e+1,Math.max(0,(a?.hits.length??0)-1)))):e.key===`ArrowUp`?(e.preventDefault(),f(e=>Math.max(0,e-1))):e.key===`Enter`&&(e.preventDefault(),h(a?.hits[d]))}}),(0,B.jsxs)(`p`,{className:`quick-open-status`,role:`status`,"data-content-search-status":s?`error`:l?`searching`:g?`partial`:`complete`,children:[s?`✕ 搜索失败:`+s:l?`… 搜索中`:e?g?`⚠ 结果不完整`:a?`✓ 搜索完成`:`○ 输入要搜索的内容`:`○ 请先选择工作区`,a?` · ${a.hits.length} 条命中`:``,` · Esc 关闭`]}),g&&(0,B.jsxs)(`p`,{className:`quick-open-status`,"data-content-search-partial":`1`,children:[`⚠ 结果不完整:`,a?.reasons.map(e=>_[e]??e).join(`;`)]}),a&&a.skipped.length>0&&(0,B.jsxs)(`details`,{className:`quick-open-status`,"data-content-search-skipped":`1`,children:[(0,B.jsxs)(`summary`,{children:[`↷ 已跳过 `,a.skipped.length,` 个文件或目录`]}),(0,B.jsx)(`p`,{className:`content-search-skipped-paths`,children:a.skipped.join(`
|
|
50
|
+
`)})]}),a&&!l&&a.hits.length===0&&(0,B.jsx)(`p`,{className:`quick-open-status`,"data-content-search-empty":`1`,children:`○ 没有匹配的行`}),(0,B.jsx)(`ul`,{className:`quick-open-results content-search-results`,role:`listbox`,children:a?.hits.map((e,t)=>(0,B.jsx)(`li`,{children:(0,B.jsxs)(`button`,{ref:t===d?m:void 0,type:`button`,"data-content-search-result":`${e.path}:${e.line}`,className:`quick-open-result content-search-result${d===t?` quick-open-result-active`:``}`,"aria-selected":d===t,onMouseEnter:()=>f(t),onClick:()=>h(e),children:[(0,B.jsxs)(`span`,{children:[e.path,`:`,e.line]}),(0,B.jsx)(`small`,{title:e.text,children:e.text})]})},`${e.path}:${e.line}`))})]})})}function Vg({entries:e,complete:t,skipped:n,onOpen:r,onClose:i}){let[a,o]=(0,z.useState)(``),[s,c]=(0,z.useState)(0),l=(0,z.useRef)(null),u=(0,z.useMemo)(()=>e.filter(e=>e.kind===`file`&&e.text!==!1),[e]),d=(0,z.useMemo)(()=>a.trim()?new ng(u,{keys:[`path`],threshold:.38,ignoreLocation:!0}).search(a).slice(0,20).map(e=>e.item):u.slice(0,20),[u,a]);(0,z.useEffect)(()=>{l.current?.focus(),c(0)},[a]);let f=(0,z.useCallback)(e=>{e&&(r({path:e.path,name:e.path.split(`/`).pop()??e.path,text:e.text}),i())},[r,i]);return(0,B.jsx)(`div`,{className:`quick-open-backdrop`,"data-quick-open":`1`,role:`presentation`,onMouseDown:i,children:(0,B.jsxs)(`div`,{className:`quick-open`,role:`dialog`,"aria-modal":`true`,"aria-label":`Quick Open`,onMouseDown:e=>e.stopPropagation(),children:[(0,B.jsx)(`input`,{ref:l,className:`quick-open-input`,"data-quick-open-input":`1`,value:a,placeholder:`Quick Open: type a file path`,"aria-label":`Quick Open file path`,onChange:e=>o(e.target.value),onKeyDown:e=>{e.key===`Escape`?(e.preventDefault(),i()):e.key===`ArrowDown`?(e.preventDefault(),c(e=>Math.min(e+1,Math.max(0,d.length-1)))):e.key===`ArrowUp`?(e.preventDefault(),c(e=>Math.max(e-1,0))):e.key===`Enter`&&(e.preventDefault(),f(d[s]))}}),(0,B.jsxs)(`p`,{className:`quick-open-status`,"data-quick-open-status":t?`complete`:`partial`,children:[t?`✓ 索引完整`:`⚠ 索引不完整`,` · `,u.length,` 个文件 · Esc 关闭`]}),n.length>0&&(0,B.jsxs)(`p`,{className:`quick-open-status`,"data-quick-open-skipped":`1`,title:n.join(`, `),children:[`↷ 已跳过:`,n.join(`, `)]}),(0,B.jsx)(`ul`,{className:`quick-open-results`,role:`listbox`,children:d.map((e,t)=>(0,B.jsx)(`li`,{children:(0,B.jsxs)(`button`,{type:`button`,"data-quick-open-result":e.path,className:t===s?`quick-open-result quick-open-result-active`:`quick-open-result`,"aria-selected":t===s,onMouseEnter:()=>c(t),onClick:()=>f(e),children:[(0,B.jsx)(`span`,{children:e.path.split(`/`).pop()}),(0,B.jsx)(`small`,{children:e.path})]})},e.path))})]})})}function Hg(e,t,n=88,r=200){let i=Math.max(0,Math.floor(e));if(!Number.isFinite(t)||t<=0)return{perRow:Math.max(1,i),width:n};if(i===0)return{perRow:1,width:n};if(i===1)return{perRow:1,width:Math.min(r,t)};let a=t/i;if(a>=n)return{perRow:i,width:Math.min(a,r)};for(let e=2;e<=i;e+=1){let a=Math.ceil(i/e),o=t/a;if(o>=n)return{perRow:a,width:Math.min(o,r)}}return{perRow:1,width:n}}function Ug(e,t){let n=Math.max(1,Math.floor(t)),r=[];for(let t=0;t<e.length;t+=n)r.push(e.slice(t,t+n));return r}function Wg(e,t,n=88,r=200){let[i,a]=(0,z.useState)(()=>Hg(e,0,n,r)),[o,s]=(0,z.useState)(null),c=(0,z.useCallback)(()=>{let i=Hg(e,t,n,r);s({count:e,containerWidth:t}),a(e=>e.perRow===i.perRow&&e.width===i.width?e:i)},[e,t,n,r]),l=(0,z.useRef)(t);(0,z.useEffect)(()=>{t<=0||l.current!==t&&(l.current=t,c())},[t,c]);let u=(0,z.useRef)(null);return(0,z.useEffect)(()=>{let t=u.current;u.current=e,t!==null&&e>t&&c()},[e,c]),{layout:i,frozen:o!==null&&o.count!==e,recompute:c}}function Gg({tabs:e,activeId:t,onSelect:n,onClose:r,ariaLabel:i,minWidth:a=88,maxWidth:o=200,prefix:s=`workspace-tab`,idPrefix:c=s,className:l}){let u=(0,z.useRef)(null),[d,f]=(0,z.useState)(0),{layout:p,frozen:m,recompute:h}=Wg(e.length,d,a,o);(0,z.useLayoutEffect)(()=>{let e=u.current;if(!e||typeof ResizeObserver>`u`)return;let t=()=>{let t=e.clientWidth;t>0&&f(t)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let g=Ug(e,p.perRow),_=(e,t)=>t===void 0?{}:{[`data-${s}-${e}`]:t},v=e.filter(e=>e.kind===`file`).length,y=e.filter(e=>e.kind===`session`||!e.kind).length,b=t=>({[`data-${t}-strip`]:`1`,...m?{[`data-${t}-frozen`]:`1`}:{},[`data-${t}-count`]:t===`file-tab`?v:t===`session-tab`?y:e.length,[`data-${t}-min`]:a,[`data-${t}-max`]:o,[`data-${t}-per-row`]:p.perRow,[`data-${t}-width`]:Math.round(p.width*100)/100}),x=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&h()},S=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&h()};(0,z.useEffect)(()=>{if(!m)return;let e=u.current;if(!e)return;let t=t=>{let n=e.getBoundingClientRect();t.clientX>=n.left&&t.clientX<=n.right&&t.clientY>=n.top&&t.clientY<=n.bottom||h()};return document.addEventListener(`mousemove`,t,!0),()=>document.removeEventListener(`mousemove`,t,!0)},[m,h]);let C=[`${s}-strip`,`workspace-tab-strip`,`session-tab-strip`,`file-tab-strip`,l].filter(Boolean).join(` `);return(0,B.jsx)(`div`,{ref:u,className:C,role:`tablist`,"aria-label":i??`工作区标签页`,..._(`strip`,`1`),...b(`workspace-tab`),...b(`session-tab`),...b(`file-tab`),style:{"--tab-w":`${p.width}px`},onMouseEnter:x,onMouseLeave:S,children:g.map((i,a)=>(0,B.jsx)(`div`,{className:`${s}-row workspace-tab-row session-tab-row file-tab-row`,role:`presentation`,..._(`row`,a),children:i.map(i=>{let a=i.id===t||i.rawId!==void 0&&i.rawId===t,o=i.title??i.label,l=i.kind,u=i.rawId??i.id,d=e.findIndex(e=>e.id===i.id),f=[s,a?`${s}-active`:``,`workspace-tab`,a?`workspace-tab-active`:``,l?`${l}-tab`:``,l&&a?`${l}-tab-active`:``].filter(Boolean).join(` `);return(0,B.jsxs)(`div`,{role:`tab`,id:`${c}-${i.id}`,"aria-selected":a,"aria-controls":`${c}-panel-${i.id}`,tabIndex:a?0:-1,className:f,..._(`id`,u),..._(`index`,d),...a?_(`active`,`1`):{},..._(`closable`,i.closable===!1?`0`:`1`),...l?{"data-tab-kind":l}:{},...l===`session`||!l?{"data-session-tab-id":u,"data-session-tab-index":d,...a?{"data-session-tab-active":`1`}:{},"data-session-tab-closable":i.closable===!1?`0`:`1`}:{},...l===`file`?{"data-file-tab-id":u,"data-file-tab-index":d,...a?{"data-file-tab-active":`1`}:{},"data-file-tab-closable":i.closable===!1?`0`:`1`}:{},title:o,style:{width:p.width,boxSizing:`border-box`},onClick:()=>n?.(i.id),onAuxClick:e=>{e.button===1&&(e.preventDefault(),e.stopPropagation(),i.closable!==!1&&r&&r(i.id))},onMouseDown:e=>{e.button===1&&e.preventDefault()},onKeyDown:t=>{if(t.key!==`ArrowLeft`&&t.key!==`ArrowRight`)return;t.preventDefault();let r=t.key===`ArrowRight`?1:-1,a=e[(e.findIndex(e=>e.id===i.id)+r+e.length)%e.length];a&&n?.(a.id)},children:[i.icon&&(0,B.jsx)(`span`,{className:`${s}-icon workspace-tab-icon`,children:i.icon}),i.badge,(0,B.jsx)(`span`,{className:`${s}-label workspace-tab-label ${l?`${l}-tab-label`:``}`,..._(`label`,u),...l===`session`||!l?{"data-session-tab-label":u}:{},...l===`file`?{"data-file-tab-label":u}:{},children:i.label}),i.closable!==!1&&r&&(0,B.jsx)(`button`,{type:`button`,className:`${s}-close workspace-tab-close ${l?`${l}-tab-close`:``}`,..._(`close`,u),...l===`session`||!l?{"data-session-tab-close":u}:{},...l===`file`?{"data-file-tab-close":u}:{},onClick:e=>{e.stopPropagation(),r(i.id)},title:`关闭 ${o}`,"aria-label":`关闭 ${o}`,children:`×`})]},i.id)})},`row_${a}`))})}var Kg={pending:`未开始`,running:`运行中`,completed:`已完成`,failed:`失败`,skipped:`已跳过`,stopped:`已停止`},qg={running:`运行中`,completed:`全部完成`,failed:`中途失败`,stopped:`已停止`},Jg={pending:`○`,running:`◐`,completed:`✓`,failed:`✕`,skipped:`→`,stopped:`■`},Yg={stop:`失败即停`,skip:`失败跳过`,"retry:1":`失败重试 1 次`,"retry:2":`失败重试 2 次`,"retry:3":`失败重试 3 次`};function Xg(e){let t=Math.max(0,Math.round(e/1e3)),n=t%60,r=Math.floor(t/60)%60,i=Math.floor(t/3600),a=e=>String(e).padStart(2,`0`);return i>0?`${i}h ${a(r)}:${a(n)}`:`${r}:${a(n)}`}function Zg(e){let t=e.status===`running`,[n,r]=(0,z.useState)(0);(0,z.useEffect)(()=>{if(!t)return;r(Date.now());let e=window.setInterval(()=>r(Date.now()),200);return()=>window.clearInterval(e)},[t,e.startedAt]);let i=Date.parse(e.startedAt);if(Number.isFinite(i)){if(!t){let t=Date.parse(e.finishedAt??``);return Number.isFinite(t)?t-i:void 0}return n>0?n-i:void 0}}function Qg({step:e,names:t}){let n=e.attempts.length,r=e.attempts[n-1],i=t.get(e.agentId)||e.agentId,a=e.label?.trim()||i;return(0,B.jsxs)(`li`,{className:`workflow-step workflow-step-${e.status}`,"data-workflow-step":e.index+1,"data-workflow-step-status":e.status,"data-workflow-step-agent":e.agentId,"data-workflow-step-attempts":n,children:[(0,B.jsx)(`span`,{className:`workflow-step-mark`,"aria-hidden":`true`,children:Jg[e.status]}),(0,B.jsxs)(`span`,{className:`workflow-step-n`,"data-workflow-step-n":e.index+1,children:[`第 `,e.index+1,` 步`]}),(0,B.jsx)(`strong`,{className:`workflow-step-name`,"data-workflow-step-name":e.index+1,children:a}),(0,B.jsx)(`span`,{className:`workflow-step-agent`,"data-workflow-step-agent-name":e.index+1,children:i}),n>1&&(0,B.jsxs)(`span`,{className:`workflow-step-tries`,"data-workflow-step-retried":e.index+1,children:[`尝试 `,n,` 次`]}),(0,B.jsx)(`span`,{className:`workflow-step-status`,"data-workflow-step-status-text":e.index+1,children:Kg[e.status]}),e.status===`failed`&&r?.error&&(0,B.jsx)(`span`,{className:`workflow-step-why`,"data-workflow-step-error":e.index+1,children:r.error})]})}function $g({workflow:e,names:t,onStop:n,stopping:r}){let i=e.status===`running`,a=Zg(e),o=e.steps.filter(e=>e.status===`completed`||e.status===`skipped`).length;return(0,B.jsxs)(`article`,{className:`workflow-card workflow-${e.status}`,"data-workflow-card":e.id,"data-workflow-status":e.status,"data-workflow-steps":e.steps.length,"data-workflow-current":e.currentIndex+1,children:[(0,B.jsxs)(`div`,{className:`workflow-head`,children:[(0,B.jsx)(`span`,{className:`workflow-badge`,children:`编排`}),(0,B.jsx)(`strong`,{className:`workflow-summary`,"data-workflow-summary":e.id,children:e.summary}),(0,B.jsxs)(`span`,{className:`workflow-progress`,"data-workflow-progress":e.id,children:[o,`/`,e.steps.length]}),(0,B.jsx)(`span`,{className:`workflow-status`,"data-workflow-status-text":e.id,children:qg[e.status]??e.status}),(0,B.jsx)(`span`,{className:`workflow-policy`,"data-workflow-policy":e.onFailure,children:Yg[e.onFailure]??e.onFailure}),a!==void 0&&(0,B.jsxs)(`span`,{className:`workflow-clock`,"data-workflow-elapsed":e.id,children:[i?`已运行 `:`用时 `,Xg(a)]}),i&&(0,B.jsx)(`button`,{type:`button`,className:`workflow-stop`,"data-workflow-stop":e.id,disabled:r,onClick:n,children:`停止`})]}),(0,B.jsx)(`ol`,{className:`workflow-steps`,"data-workflow-step-count":e.steps.length,children:e.steps.map(e=>(0,B.jsx)(Qg,{step:e,names:t},e.index))})]})}var e_=[{id:`agents`,label:`智能体与创建`,icon:`🤖`,title:`Agent 智能体系统与创建指南`,description:`了解 Super Pi 的角色设定机制,以及如何一步步创建你自己的自定义 Agent。`},{id:`workspace`,label:`工作区与会话`,icon:`🗂️`,title:`工作区与多会话管理`,description:`高效管理本地代码仓库、独立会话标签页与多模态图文输入。`},{id:`subagents`,label:`子任务与编排`,icon:`⚡`,title:`子智能体委托与顺序编排使用指南`,description:`让主 Agent 安排分工、交接结果,并查看进度、处理失败与停止任务。`},{id:`model-policy`,label:`模型使用规则`,icon:`🔒`,title:`模型过滤规则(按工作区限制可用模型)`,description:`用正则规则限定哪些工作区只能用哪些模型,防止敏感代码被发到不该用的模型上。`},{id:`memory`,label:`主动记忆`,icon:`🧠`,title:`主动记忆与技能经验`,description:`让 Super Pi 在得到明确证据后保存长期事实、用户偏好和可复用工作方法。`},{id:`knowledge`,label:`知识库`,icon:`📚`,title:`工作区知识库`,description:`导入规范与设计文档,让 Agent 检索原文作答,而不是凭记忆编造。`},{id:`tools`,label:`侧边栏工具`,icon:`🧩`,title:`全局工具:开发、导出与导入`,description:`让 Agent 写一个工具,用一个文件分享给别人,导入前先看清它会做什么。`},{id:`cli`,label:`指令与快捷键`,icon:`⌨️`,title:`Pi 终端命令与键盘快捷操作`,description:`利用 Pi 终端斜杠指令控制服务生命周期,掌握常用快捷键提升效率。`},{id:`themes`,label:`外观与主题`,icon:`🎨`,title:`界面主题与个性化显示`,description:`内置 4 款专业高对比度主题,针对不同环境提供舒适体验。`}];function t_({onClose:e}){let[t,n]=(0,z.useState)(`agents`);(0,z.useEffect)(()=>{let t=t=>{t.key===`Escape`&&!t.defaultPrevented&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let r=e_.find(e=>e.id===t)??e_[0];return(0,B.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,B.jsxs)(`div`,{className:`picker settings-window help-window`,"data-help-window":`1`,onClick:e=>e.stopPropagation(),role:`dialog`,"aria-modal":`true`,"aria-labelledby":`help-window-title`,children:[(0,B.jsxs)(`div`,{className:`settings-window-head help-window-head`,children:[(0,B.jsxs)(`div`,{className:`help-head-title`,children:[(0,B.jsx)(`h2`,{id:`help-window-title`,children:`使用指南与帮助`}),(0,B.jsx)(`span`,{className:`help-badge`,children:`v0.1.x`})]}),(0,B.jsx)(`button`,{type:`button`,className:`help-close-button`,"aria-label":`关闭指南`,onClick:e,children:`✕`})]}),(0,B.jsxs)(`div`,{className:`settings-window-body help-window-body`,children:[(0,B.jsxs)(`nav`,{className:`settings-nav help-nav`,role:`tablist`,"aria-orientation":`vertical`,"aria-label":`使用指南分类`,children:[(0,B.jsx)(`div`,{className:`settings-nav-label`,children:`目录`}),e_.map(e=>(0,B.jsxs)(`button`,{type:`button`,id:`help-tab-${e.id}`,className:`settings-category help-category`,role:`tab`,"aria-selected":e.id===r.id,"aria-controls":`help-panel`,tabIndex:e.id===r.id?0:-1,onClick:()=>n(e.id),children:[(0,B.jsx)(`span`,{className:`help-tab-icon`,"aria-hidden":`true`,children:e.icon}),(0,B.jsx)(`span`,{children:e.label})]},e.id))]}),(0,B.jsxs)(`div`,{id:`help-panel`,className:`settings-panel help-panel`,role:`tabpanel`,"aria-labelledby":`help-tab-${r.id}`,children:[(0,B.jsxs)(`div`,{className:`help-panel-header`,children:[(0,B.jsx)(`h3`,{className:`help-panel-title`,children:r.title}),(0,B.jsx)(`p`,{className:`help-panel-desc`,children:r.description})]}),(0,B.jsxs)(`div`,{className:`help-panel-content`,children:[r.id===`agents`&&(0,B.jsx)(i_,{}),r.id===`workspace`&&(0,B.jsx)(a_,{}),r.id===`subagents`&&(0,B.jsx)(s_,{}),r.id===`model-policy`&&(0,B.jsx)(o_,{}),r.id===`memory`&&(0,B.jsx)(n_,{}),r.id===`knowledge`&&(0,B.jsx)(r_,{}),r.id===`tools`&&(0,B.jsx)(c_,{}),r.id===`cli`&&(0,B.jsx)(l_,{}),r.id===`themes`&&(0,B.jsx)(u_,{})]}),(0,B.jsx)(`div`,{className:`picker-actions help-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e,children:`关闭`})})]})]})]})})}function n_(){return(0,B.jsxs)(`div`,{className:`help-section-group`,children:[(0,B.jsxs)(`div`,{className:`help-card highlight`,children:[(0,B.jsx)(`h4`,{children:`🧠 它会记住什么?`}),(0,B.jsx)(`p`,{children:`用户档案保存跨工作区的长期偏好;工作区事实保存环境与项目约定;技能保存已经验证过的步骤、命令和坑。临时结果、秘密和未验证的失败不会保存。`})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`主动保存与后台复盘`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[`主 Agent 可以使用 `,(0,B.jsx)(`code`,{children:`memory`}),` 和 `,(0,B.jsx)(`code`,{children:`skill_manage`}),` 工具主动保存;说“记住了”本身不会写入。`]}),(0,B.jsx)(`li`,{children:`每隔若干回合,系统会在独立会话中复盘最近证据。复盘不能读写工作区文件、执行命令或派发任务。`}),(0,B.jsx)(`li`,{children:`读取记忆和历史只返回带来源的参考数据,不能把记忆中的文字当作新的指令。`})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`权限与审批`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsx)(`li`,{children:`子 Agent 可以读取相关记忆,但没有写入权限。`}),(0,B.jsx)(`li`,{children:`后台复盘新增记忆可以直接保存;修改或删除旧条目会进入设置中的待审批列表。`}),(0,B.jsx)(`li`,{children:`在“设置 → 主动记忆”可以开关功能、调整复盘间隔、编辑条目和批准提案。`})]})]})]})}function r_(){return(0,B.jsxs)(`div`,{className:`help-section-group`,children:[(0,B.jsxs)(`div`,{className:`help-card highlight`,children:[(0,B.jsx)(`h4`,{children:`📚 它解决什么问题?`}),(0,B.jsx)(`p`,{children:`Agent 默认靠训练时的记忆回答项目里的问题。知识库让你把规范、设计稿、会议纪要导入工作区,Agent 在回答前检索这些文档的原文片段,而不是凭印象编造。它与“主动记忆”不同:记忆是 Agent 自己沉淀的事实和技能,知识库只有你能写入。`})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`怎么用`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsx)(`li`,{children:`在“设置 → 知识库”里点“浏览工作区文件…”,在弹出的浏览器里挑一个 Markdown 或文本文件,挑完即导入。也可以直接粘贴正文,或手动填写相对路径。`}),(0,B.jsx)(`li`,{children:`同一个文件内容改了再导入就是更新,不会留下旧版本;同样的内容换个标题再导入也不会变成两篇。`}),(0,B.jsx)(`li`,{children:`面板里的“试检索”会用和 Agent 相同的检索器回答,方便你在交给 Agent 之前先确认它找得到。`}),(0,B.jsxs)(`li`,{children:[`从下一条消息开始生效。Agent 使用 `,(0,B.jsx)(`code`,{children:`knowledge_search`}),` 检索,只拿得到片段和来源,拿不到整篇文档。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`语义检索是内置的`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[`关键词检索始终可用。语义检索让“撤销购买”也能找到写着“取消订单”的段落,它靠一个`,(0,B.jsx)(`strong`,{children:`随安装包一起分发`}),`的中文模型在本机运行,不需要额外下载、不需要联网、也不会把文档发到任何服务。`]}),(0,B.jsxs)(`li`,{children:[`第一次检索时加载模型(约一秒),之后一直可用。设 `,(0,B.jsx)(`code`,{children:`SUPER_PI_KNOWLEDGE_EMBEDDINGS=0`}),` 可以彻底关闭语义检索,只保留关键词检索。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`它不知道的事`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsx)(`li`,{children:`知识库只会检索它有的东西。文档里没写的,它检索出来也不会有——所以导入什么,直接决定它能回答什么。`}),(0,B.jsx)(`li`,{children:`语义检索总会返回“最接近的那一段”,即使这一段其实并不回答问题。检索结果带一个分数,低分意味着这可能只是最像的一条,Agent 会被要求先核对再使用。`}),(0,B.jsx)(`li`,{children:`Agent 对知识库只读,不能写入或删除;导入和删除只有你能做。`})]})]})]})}function i_(){return(0,B.jsxs)(`div`,{className:`help-section-group`,children:[(0,B.jsxs)(`div`,{className:`help-card highlight`,children:[(0,B.jsx)(`h4`,{children:`💡 Agent 是什么?`}),(0,B.jsxs)(`p`,{children:[`在 Super Pi 中,`,(0,B.jsx)(`strong`,{children:`Agent(智能体)`}),` 是一套独立的「角色提示词设定与能力配置」。 通过切换 Agent,模型将扮演专精工程师、系统架构师、代码审查员或规划专家等不同角色,遵循指定的原则来协助你完成任务。`]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`📁 Agent 文件存放在哪里?`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`内置 Agent 目录:`}),`项目根目录下的 `,(0,B.jsx)(`code`,{children:`agents/`}),` 文件夹,例如 `,(0,B.jsx)(`code`,{children:`agents/coder.md`}),`、`,(0,B.jsx)(`code`,{children:`agents/planner.md`}),`、`,(0,B.jsx)(`code`,{children:`agents/reviewer.md`}),` 等。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`用户自定义持久化目录:`}),`用户主目录下的 `,(0,B.jsx)(`code`,{children:`~/.super-pi/agents/`}),`,放入此目录的文件在所有项目和更新中均持久有效。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`🚀 如何创建一个全新的自定义 Agent?`}),(0,B.jsxs)(`div`,{className:`help-steps`,children:[(0,B.jsxs)(`div`,{className:`help-step`,children:[(0,B.jsx)(`span`,{className:`step-num`,children:`1`}),(0,B.jsxs)(`div`,{className:`step-body`,children:[(0,B.jsx)(`strong`,{children:`创建 Markdown 文件`}),(0,B.jsxs)(`p`,{children:[`在 `,(0,B.jsx)(`code`,{children:`agents/`}),` 或 `,(0,B.jsx)(`code`,{children:`~/.super-pi/agents/`}),` 目录下新建文件,例如 `,(0,B.jsx)(`code`,{children:`architect.md`}),`。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-step`,children:[(0,B.jsx)(`span`,{className:`step-num`,children:`2`}),(0,B.jsxs)(`div`,{className:`step-body`,children:[(0,B.jsx)(`strong`,{children:`编写元数据与系统提示词`}),(0,B.jsx)(`p`,{children:`文件开头使用 YAML Frontmatter 声明名称和描述,正文编写设定提示词:`}),(0,B.jsx)(`pre`,{className:`help-code-block`,children:(0,B.jsx)(`code`,{children:`---
|
|
51
51
|
name: 系统架构师
|
|
52
52
|
description: 专注于系统架构拆解、模块解耦与技术选型分析
|
|
53
53
|
---
|
|
@@ -56,12 +56,12 @@ description: 专注于系统架构拆解、模块解耦与技术选型分析
|
|
|
56
56
|
在回答技术方案或重构建议时,请遵循以下原则:
|
|
57
57
|
1. 始终优先保障系统模块边界清晰与职责单一;
|
|
58
58
|
2. 提出方案时提供利弊分析(Trade-offs)与选型依据;
|
|
59
|
-
3. 输出高内聚、低耦合的设计图表与步骤。`})})]})]}),(0,B.jsxs)(`div`,{className:`help-step`,children:[(0,B.jsx)(`span`,{className:`step-num`,children:`3`}),(0,B.jsxs)(`div`,{className:`step-body`,children:[(0,B.jsx)(`strong`,{children:`在工作区中直接选择使用`}),(0,B.jsxs)(`p`,{children:[`文件保存后,刷新页面或点击左侧工作区标题旁的 `,(0,B.jsx)(`strong`,{children:`⚙ 设置`}),` 按钮, 在「默认 Agent」下拉菜单中就能直接看到新加入的「系统架构师」!`]})]})]})]})]})]})}function
|
|
59
|
+
3. 输出高内聚、低耦合的设计图表与步骤。`})})]})]}),(0,B.jsxs)(`div`,{className:`help-step`,children:[(0,B.jsx)(`span`,{className:`step-num`,children:`3`}),(0,B.jsxs)(`div`,{className:`step-body`,children:[(0,B.jsx)(`strong`,{children:`在工作区中直接选择使用`}),(0,B.jsxs)(`p`,{children:[`文件保存后,刷新页面或点击左侧工作区标题旁的 `,(0,B.jsx)(`strong`,{children:`⚙ 设置`}),` 按钮, 在「默认 Agent」下拉菜单中就能直接看到新加入的「系统架构师」!`]})]})]})]})]})]})}function a_(){return(0,B.jsxs)(`div`,{className:`help-section-group`,children:[(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`🗂️ 工作区(Workspace)管理`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`绑定真实目录:`}),`每个工作区对应本地机器的一个具体项目路径。代码操作与工具调用均以该路径为上下文根目录。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`独立偏好配置:`}),`点击工作区标题右侧的 `,(0,B.jsx)(`strong`,{children:`⚙ 齿轮图标`}),`,可为该工作区单独配置其专属的「默认 Agent」、「默认模型」与「思考深度等级」。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`多工作区折叠:`}),`点击工作区名称即可折叠或展开会话列表,界面清爽高效。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`💬 多会话与标签页(Tabs)`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`顶部标签页流转:`}),`打开的会话会作为标签页显示在消息区顶部,方便在不同任务与思路之间瞬间切换。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`会话归档:`}),`不再活跃的会话可以归档,归档列表独立折叠收纳在底部,随时可还原。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`图文多模态输入:`}),`在模型选择器中带有「图文」标签的模型(如 Claude 3.7 / GPT-4o 等),支持在输入框直接上传或拖拽图片,协同分析 UI 与架构图。`]})]})]})]})}function o_(){return(0,B.jsxs)(`div`,{className:`help-section-group`,children:[(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`🔒 它解决什么问题`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`按工作区限定可用模型:`}),`一条规则 =「工作区名匹配某个正则」时,这个工作区的会话`,(0,B.jsx)(`strong`,{children:`只允许`}),`使用模型名匹配另一个正则的模型。例如「名称含 `,(0,B.jsx)(`code`,{children:`sensitive`}),` 的工作区,只能用名称含 `,(0,B.jsx)(`code`,{children:`internal`}),` 的模型」。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`为什么要按工作区而不是按会话:`}),`敏感程度取决于代码在哪儿,而不是取决于是哪一次提问。规则写在工作区上,新增工作区自动受管,不会因为新开了个会话就绕过去。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`不是纯界面限制:`}),`模型下拉里只会列出允许的模型;但即使绕过界面(第二个标签页、过期窗口、手写指令),`,(0,B.jsx)(`strong`,{children:`服务端也会拒绝运行`}),`并说明是哪个工作区命中了哪条规则。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`⚙️ 怎么配置`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`位置:`}),`左侧栏 `,(0,B.jsx)(`strong`,{children:`⚙ 设置 → 模型过滤`}),`,全局生效,对所有工作区统一管理。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`两条正则各管一件事:`}),`左边匹配`,(0,B.jsx)(`strong`,{children:`工作区名称`}),`(不区分大小写),右边匹配`,(0,B.jsx)(`strong`,{children:`模型名称`}),`(同时匹配模型显示名和 `,(0,B.jsx)(`code`,{children:`provider/modelId`}),`,任一命中即算允许)。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`多条规则同时命中时取交集:`}),`一个模型必须被`,(0,B.jsx)(`strong`,{children:`每一条`}),`命中的规则都允许,才算允许。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`正则写错不会拖垮服务:`}),`填表时当场校验,写错立刻标红并阻止保存;万一有非法规则进了配置,服务端会跳过它并在日志里说明,`,(0,B.jsx)(`strong`,{children:`不会`}),`被当成「全部禁止」。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`没有规则 = 不过滤:`}),`不配置任何规则时行为和以前完全一样。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`🛡️ 到底拦住了哪些路径`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`模型下拉列表:`}),`被禁用的模型根本不会出现在选择器里。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`切换模型 / 选 Agent / 改工作区默认模型:`}),`都会在服务端校验,违规直接拒绝,不会静默换成别的模型。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`Agent 自己声明的模型:`}),`在 `,(0,B.jsx)(`code`,{children:`agents/*.md`}),` 里写死的 `,(0,B.jsx)(`code`,{children:`model:`}),` 同样受约束——选一个声明了禁用模型的 Agent 会被拒绝,而不是偷偷按那个模型跑。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`子智能体(Sub-agent):`}),`派发子任务时使用的模型,`,(0,B.jsx)(`strong`,{children:`包括从父 Agent 继承下来的那个`}),`,一样按会话所属工作区校验。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`已有会话复查:`}),`会话配好之后你才新增规则的话,下次真正开始跑之前会重新校验一次。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`跟随 Pi 默认的情况:`}),`会话没有显式选模型时,Pi 会用它自己的全局默认模型。这个默认模型`,(0,B.jsx)(`strong`,{children:`同样会被检查`}),`——如果它正好被规则禁用,运行会被拒绝。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`💡 怎么写正则`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`大小写不敏感:`}),(0,B.jsx)(`code`,{children:`/sensitive/i`}),` 和 `,(0,B.jsx)(`code`,{children:`/SENSITIVE/i`}),` 效果一样,不用在小写和大写之间纠结。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`常用写法:`}),(0,B.jsx)(`code`,{children:`/敏感|sensitive/i`}),` 匹配多个关键词;`,(0,B.jsx)(`code`,{children:`/^客户-/i`}),` 只匹配以「客户-」开头的;`,(0,B.jsx)(`code`,{children:`/internal|private/i`}),` 匹配任一即可。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`模型名两种写法都认:`}),`规则右边写 `,(0,B.jsx)(`code`,{children:`internal`}),` 能匹配显示名为「Internal」的模型,写 `,(0,B.jsx)(`code`,{children:`minimax-cn/internal`}),` 也能精确匹配同一个模型。`]})]})]})]})}function s_(){return(0,B.jsxs)(`div`,{className:`help-section-group`,children:[(0,B.jsxs)(`div`,{className:`help-card`,"data-help-workflow":`start`,children:[(0,B.jsx)(`h4`,{children:`如何开始一次编排`}),(0,B.jsxs)(`p`,{children:[`选择工作区和主 Agent,在消息框里说明目标、希望参与的子 Agent、执行顺序和验收条件。主 Agent 会使用 `,(0,B.jsx)(`code`,{children:`workflow`}),` 工具提交计划;你不需要手写 JSON,也没有需要点击的“启动编排”按钮。`]}),(0,B.jsxs)(`p`,{children:[`先在设置的“智能体”分类确认这些角色已被发现。主 Agent 使用 `,(0,B.jsx)(`code`,{children:`mode: primary`}),`,参与步骤的角色使用 `,(0,B.jsx)(`code`,{children:`mode: subagent`}),`;指令中的角色 ID 对应定义文件名(不带 .md)。主 Agent 的工具权限需要允许 `,(0,B.jsx)(`code`,{children:`workflow`}),`,单独委托则需要允许 `,(0,B.jsx)(`code`,{children:`task`}),`。`]}),(0,B.jsx)(`pre`,{className:`help-code-block`,children:(0,B.jsx)(`code`,{children:`请修复这个工作区的登录失败问题,用 workflow 顺序编排:
|
|
60
60
|
1. scout:定位原因,输出相关文件、复现步骤和修复建议。
|
|
61
61
|
2. coder:根据 scout 的结果实现修复,不修改无关代码。
|
|
62
62
|
3. verifier:根据修复结果运行测试,检查回归并给出结论。
|
|
63
63
|
运行失败时最多重试 1 次,仍失败就停止。
|
|
64
|
-
最后由你汇总修改、测试结果和剩余问题。`})}),(0,B.jsx)(`p`,{children:`上例使用内置角色;自定义角色请换成你实际配置的 ID。若主 Agent 没有调用编排工具,可明确补充“请调用 workflow 工具执行,而不是只列计划”。`})]}),(0,B.jsxs)(`div`,{className:`help-card`,"data-help-workflow":`choices`,children:[(0,B.jsx)(`h4`,{children:`选择单独委托、后台任务还是顺序编排`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`单独委托(task):`}),`适合一两个子任务,或需要主 Agent 看完结果再决定下一步。直接说“让 scout 先调查,拿到结果后再决定怎么修”。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`顺序编排(workflow):`}),`适合多个有依赖的步骤,例如调查 → 实现 → 验证。步骤依次执行,每个子 Agent 从新上下文开始,服务端自动把前序产出交给后续步骤。一次调用会等待整个计划结束,再把结果交回主 Agent。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`后台任务:`}),`适合互不依赖的工作。可说“并行委托两个独立调查任务,使用 task 的 background 模式”;它们完成后会回传结果,不保证执行顺序。`]})]}),(0,B.jsx)(`p`,{children:`当前 workflow 不支持条件分支、步骤并行或自动回跳。若验证发现问题,可让主 Agent 阅读结论后安排新一轮修复与验证。`})]}),(0,B.jsxs)(`div`,{className:`help-card`,"data-help-workflow":`progress`,children:[(0,B.jsx)(`h4`,{children:`查看进度、处理失败与停止`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`进度:`}),`对话正文会出现编排卡片,显示完整步骤、当前步骤、状态和尝试次数。各步骤的子 Agent 卡片显示输出和工具活动;刷新页面后仍可查看已保存记录。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`失败策略:`}),`默认 `,(0,B.jsx)(`code`,{children:`stop`}),` 在步骤运行失败后停止;`,(0,B.jsx)(`code`,{children:`retry:N`}),` 最多追加 N 次尝试,并携带上次失败证据;`,(0,B.jsx)(`code`,{children:`skip`}),` 跳过失败步骤并告知后续角色输入缺失。可以用自然语言要求主 Agent 选择策略。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`验证结论:`}),`步骤“已完成”表示子进程正常结束,不代表它的报告说“验证通过”。主 Agent 需要阅读报告再判断是否达到验收条件。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`停止:`}),`编排卡片的“停止”会取消当前子任务并阻止后续步骤;停止主任务也会停止其编排。点击后显示“停止中”,实际取消确认后才显示停止状态。停止当前步骤的子 Agent 也会终止该计划。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`继续:`}),`停止或服务重启后不会自动续跑。已完成的输出仍保留;请让主 Agent 根据这些记录重新安排剩余步骤,先检查已有修改,避免重复执行。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`⚡ 子任务分工与委托机制`}),(0,B.jsxs)(`p`,{children:[`当面对复杂工程任务时,Super Pi 支持通过 `,(0,B.jsx)(`code`,{children:`task`}),` 工具将子任务派发给专精子智能体。`]}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`Scout(侦察兵):`}),`负责快速穿透仓库搜寻相关文件与代码位置。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`Coder(编码专家):`}),`专注于高精度实现与代码变更。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`Verifier(验证官):`}),`负责运行自动化测试与编译校验,确保修改零回归。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`📊 右侧抽屉栏(Right Rail)`}),(0,B.jsx)(`p`,{children:`右侧边栏集成了三大核心实时监控面板:`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`任务清单(Task List):`}),`跟踪长任务规划执行进度与各步骤完成状态。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`后台任务(Tasks):`}),`实时追踪并发子任务的祖先链路、状态流转与执行产物。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`文件工作台(Files):`}),`免切窗口直接浏览、检索与阅读当前工作区的文件内容。`]})]})]})]})}function
|
|
64
|
+
最后由你汇总修改、测试结果和剩余问题。`})}),(0,B.jsx)(`p`,{children:`上例使用内置角色;自定义角色请换成你实际配置的 ID。若主 Agent 没有调用编排工具,可明确补充“请调用 workflow 工具执行,而不是只列计划”。`})]}),(0,B.jsxs)(`div`,{className:`help-card`,"data-help-workflow":`choices`,children:[(0,B.jsx)(`h4`,{children:`选择单独委托、后台任务还是顺序编排`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`单独委托(task):`}),`适合一两个子任务,或需要主 Agent 看完结果再决定下一步。直接说“让 scout 先调查,拿到结果后再决定怎么修”。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`顺序编排(workflow):`}),`适合多个有依赖的步骤,例如调查 → 实现 → 验证。步骤依次执行,每个子 Agent 从新上下文开始,服务端自动把前序产出交给后续步骤。一次调用会等待整个计划结束,再把结果交回主 Agent。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`后台任务:`}),`适合互不依赖的工作。可说“并行委托两个独立调查任务,使用 task 的 background 模式”;它们完成后会回传结果,不保证执行顺序。`]})]}),(0,B.jsx)(`p`,{children:`当前 workflow 不支持条件分支、步骤并行或自动回跳。若验证发现问题,可让主 Agent 阅读结论后安排新一轮修复与验证。`})]}),(0,B.jsxs)(`div`,{className:`help-card`,"data-help-workflow":`progress`,children:[(0,B.jsx)(`h4`,{children:`查看进度、处理失败与停止`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`进度:`}),`对话正文会出现编排卡片,显示完整步骤、当前步骤、状态和尝试次数。各步骤的子 Agent 卡片显示输出和工具活动;刷新页面后仍可查看已保存记录。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`失败策略:`}),`默认 `,(0,B.jsx)(`code`,{children:`stop`}),` 在步骤运行失败后停止;`,(0,B.jsx)(`code`,{children:`retry:N`}),` 最多追加 N 次尝试,并携带上次失败证据;`,(0,B.jsx)(`code`,{children:`skip`}),` 跳过失败步骤并告知后续角色输入缺失。可以用自然语言要求主 Agent 选择策略。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`验证结论:`}),`步骤“已完成”表示子进程正常结束,不代表它的报告说“验证通过”。主 Agent 需要阅读报告再判断是否达到验收条件。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`停止:`}),`编排卡片的“停止”会取消当前子任务并阻止后续步骤;停止主任务也会停止其编排。点击后显示“停止中”,实际取消确认后才显示停止状态。停止当前步骤的子 Agent 也会终止该计划。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`继续:`}),`停止或服务重启后不会自动续跑。已完成的输出仍保留;请让主 Agent 根据这些记录重新安排剩余步骤,先检查已有修改,避免重复执行。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`⚡ 子任务分工与委托机制`}),(0,B.jsxs)(`p`,{children:[`当面对复杂工程任务时,Super Pi 支持通过 `,(0,B.jsx)(`code`,{children:`task`}),` 工具将子任务派发给专精子智能体。`]}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`Scout(侦察兵):`}),`负责快速穿透仓库搜寻相关文件与代码位置。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`Coder(编码专家):`}),`专注于高精度实现与代码变更。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`Verifier(验证官):`}),`负责运行自动化测试与编译校验,确保修改零回归。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`📊 右侧抽屉栏(Right Rail)`}),(0,B.jsx)(`p`,{children:`右侧边栏集成了三大核心实时监控面板:`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`任务清单(Task List):`}),`跟踪长任务规划执行进度与各步骤完成状态。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`后台任务(Tasks):`}),`实时追踪并发子任务的祖先链路、状态流转与执行产物。`]}),(0,B.jsxs)(`li`,{children:[(0,B.jsx)(`strong`,{children:`文件工作台(Files):`}),`免切窗口直接浏览、检索与阅读当前工作区的文件内容。`]})]})]})]})}function c_(){return(0,B.jsxs)(`div`,{className:`help-section-group`,children:[(0,B.jsxs)(`div`,{className:`help-card highlight`,children:[(0,B.jsx)(`h4`,{children:`🧩 工具是全局的`}),(0,B.jsxs)(`p`,{children:[`工具不属于某一个工作区,写好之后在每个工作区的“工具”Tab 里都能用。工具由 Agent 通过内置的 `,(0,B.jsx)(`code`,{children:`tool_register`}),` 一次性提交完整文件(index.html、JS/CSS,需要时再加 .py);你也可以在“工具设置”里复制那段提示词,直接让当前 Agent 写一个。`]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`本地计算怎么跑`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[`工具页面里加载 `,(0,B.jsx)(`code`,{children:`./super-pi-tool.js`}),`,用 `,(0,B.jsx)(`code`,{children:`SuperPiTool.run(params)`}),`、`,(0,B.jsx)(`code`,{children:`get`}),`、`,(0,B.jsx)(`code`,{children:`wait`}),`、`,(0,B.jsx)(`code`,{children:`cancel`}),` 操作自己的 Python 任务。这些都是绑定本工具身份的相对接口,不要自己猜 id、不要调用 `,(0,B.jsx)(`code`,{children:`/api/exec`}),`。`]}),(0,B.jsxs)(`li`,{children:[`脚本参数以 JSON 从 stdin 传入,stdout 必须只输出一个 JSON 对象;页面通过 `,(0,B.jsx)(`code`,{children:`./api/runs/<id>`}),` 查看状态和日志。`]}),(0,B.jsxs)(`li`,{children:[`第三方 Python 包写进 `,(0,B.jsx)(`code`,{children:`environment.requires`}),`,并且必须钉死成 `,(0,B.jsx)(`code`,{children:`pkg==version`}),`;没钉死的会被拒绝并告诉你哪一个。它们装进`,(0,B.jsx)(`strong`,{children:`这个工具自己的虚拟环境`}),`,第一次真正运行时自动安装,装包过程就是这次运行的日志。`]}),(0,B.jsx)(`li`,{children:`环境对不上时不会拦住你运行,只会在工具列表里标出来。工具设置里的“环境就绪 / 缺少可用的 Python / 与导出方环境不一致”说的是事实,不是保证。`})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`🤖 工具可以问模型`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[`需要摘要、改写、抽取、分类时调用 `,(0,B.jsx)(`code`,{children:`SuperPiTool.llmText({ prompt, system })`}),`(或 `,(0,B.jsx)(`code`,{children:`llm`}),` + `,(0,B.jsx)(`code`,{children:`llmWait`}),` 两步、可取消),不用自己写客户端,也不用自己保管密钥——凭据和模型选择都在 Super Pi 这边。`]}),(0,B.jsxs)(`li`,{children:[`这是`,(0,B.jsx)(`strong`,{children:`补全,不是 Agent`}),`:回答问题的那个模型没有工具、拿不到你的文件、也读不到会话历史。`]}),(0,B.jsxs)(`li`,{children:[`必须显式授权:工具注册时声明 `,(0,B.jsx)(`code`,{children:`permissions: { llm: true }`}),`,否则服务端直接拒绝。这条授权会随工具文件一起分享,所以对方在导入之前就能看到“这个工具可以调用模型”,导入之后工具列表里也一直标着。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`📤 导出与导入`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[`两个入口都在`,(0,B.jsx)(`strong`,{children:`工具设置`}),`里:上面一节列出已安装的全局工具(带环境状态),可以逐个导出;下面一节从文件导入。`]}),(0,B.jsxs)(`li`,{children:[`导出得到一个 `,(0,B.jsx)(`code`,{children:`xxx.super-pi-tool.json`}),`,文件名可以改(缺后缀会自动补上)。这个文件就是工具本身,可以直接发给别人。`]}),(0,B.jsxs)(`li`,{children:[`导入是`,(0,B.jsx)(`strong`,{children:`两步`}),`:先选文件,审阅卡会告诉你这个包里有哪些文件、含不含 Python 脚本、运行它要装什么、要哪些模型权限。你可以展开“查看文件”把每个文件读完——包括对方那个 `,(0,B.jsx)(`code`,{children:`.py`}),` 的原文——再决定要不要导入。`]}),(0,B.jsxs)(`li`,{children:[`如果 slug 和本机已有的工具重了,卡片上会多一个改名框;不改名(点取消)就是`,(0,B.jsx)(`strong`,{children:`不导入`}),`,不会悄悄换个名字装上。`]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`⚠️ 导入一个工具,等于接受一段代码`}),(0,B.jsxs)(`ul`,{className:`help-list`,children:[(0,B.jsxs)(`li`,{children:[`工具页面跑在不带 `,(0,B.jsx)(`code`,{children:`allow-same-origin`}),` 的 iframe 里,拿不到本站的登录态和 localStorage,也连不上外网。`]}),(0,B.jsxs)(`li`,{children:[`但 Python 那一侧`,(0,B.jsx)(`strong`,{children:`没有沙箱`}),`:脚本是以你的身份在你的机器上执行的,能读你的文件、能联网。所以含 Python 脚本的工具,审阅卡会明确写出这一点。`]}),(0,B.jsx)(`li`,{children:`工具里也没有作者署名和校验和——没有可信第三方,一个假的“已验证”标记比没有更糟。工具文件本身、加上你能读到的原文,就是全部依据。`}),(0,B.jsx)(`li`,{children:`删除工具会连同它的虚拟环境一起删掉。`})]})]})]})}function l_(){return(0,B.jsxs)(`div`,{className:`help-section-group`,children:[(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`⌨️ Pi 终端斜杠指令`}),(0,B.jsx)(`p`,{children:`在安装了 Super Pi 扩展的 Pi 终端会话内,支持以下指令:`}),(0,B.jsxs)(`div`,{className:`help-command-table`,children:[(0,B.jsxs)(`div`,{className:`cmd-row`,children:[(0,B.jsx)(`code`,{children:`/super_pi`}),(0,B.jsx)(`span`,{children:`后台守护启动 Super Pi 服务(端口 3080)并自动在默认浏览器中打开`})]}),(0,B.jsxs)(`div`,{className:`cmd-row`,children:[(0,B.jsx)(`code`,{children:`/super_pi restart`}),(0,B.jsx)(`span`,{children:`重启后台 Super Pi Web 控制平面服务`})]}),(0,B.jsxs)(`div`,{className:`cmd-row`,children:[(0,B.jsx)(`code`,{children:`/super_pi stop`}),(0,B.jsx)(`span`,{children:`安全停止后台常驻的 Super Pi 服务`})]})]})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`📦 扩展包安装与更新`}),(0,B.jsx)(`pre`,{className:`help-code-block`,children:(0,B.jsx)(`code`,{children:`# 在 Pi 中一键安装 Super Pi 扩展
|
|
65
65
|
pi install npm:@evandu/super-pi
|
|
66
66
|
|
|
67
67
|
# 检查已安装插件列表
|
|
@@ -71,29 +71,29 @@ pi list
|
|
|
71
71
|
pi update npm:@evandu/super-pi
|
|
72
72
|
|
|
73
73
|
# 独立启动(无需 Pi 环境)
|
|
74
|
-
npx @evandu/super-pi`})})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`🎯 键盘快捷键`}),(0,B.jsxs)(`div`,{className:`help-command-table`,children:[(0,B.jsxs)(`div`,{className:`cmd-row`,children:[(0,B.jsx)(`code`,{children:`Enter`}),(0,B.jsx)(`span`,{children:`发送对话消息`})]}),(0,B.jsxs)(`div`,{className:`cmd-row`,children:[(0,B.jsx)(`code`,{children:`Shift + Enter`}),(0,B.jsx)(`span`,{children:`输入框内换行`})]}),(0,B.jsxs)(`div`,{className:`cmd-row`,children:[(0,B.jsx)(`code`,{children:`Esc`}),(0,B.jsx)(`span`,{children:`快速关闭当前顶层弹窗(使用指南、设置、工作区选择器等)`})]})]})]})]})}function
|
|
75
|
-
已验证的步骤、命令和注意事项`:`输入长期有效的事实或偏好`,value:u,onChange:e=>d(e.target.value)}),(0,B.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!u.trim(),onClick:async()=>{await g({action:`write`,operation:{target:c,action:f?`replace`:`add`,id:f,content:u}})&&(p(void 0),d(``))},children:[`保存`,f?`修改`:`新条目`]}),f&&(0,B.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,onClick:()=>{p(void 0),d(``)},children:`取消编辑`})]})]})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsxs)(`h4`,{className:`settings-section-title`,children:[`待审批提案(共 `,n.pending.length,` 个)`]}),n.pending.length===0?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`暂无待审批提案。`}):(0,B.jsx)(`div`,{className:`settings-dirs-list`,children:n.pending.map(e=>(0,B.jsxs)(`article`,{"data-memory-proposal":e.id,className:`settings-proposal-card`,children:[(0,B.jsxs)(`div`,{className:`settings-proposal-header`,children:[(0,B.jsx)(`span`,{className:`settings-proposal-badge`,children:e.operation.target}),(0,B.jsx)(`span`,{className:`settings-proposal-action`,children:e.operation.action})]}),e.previous&&(0,B.jsxs)(`pre`,{className:`settings-proposal-diff old`,children:[`原内容:`,e.previous]}),(0,B.jsx)(`pre`,{className:`settings-proposal-diff new`,children:e.operation.content}),(0,B.jsxs)(`div`,{className:`settings-proposal-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-rule-edit-btn`,onClick:()=>void g({action:`approve`,proposalId:e.id}),children:`批准`}),(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,onClick:()=>void g({action:`discard`,proposalId:e.id}),children:`拒绝`})]})]},e.id))})]})]}),t&&(0,B.jsx)(`div`,{className:`picker-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:t,children:`完成`})})]}):(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`请先在主界面选择工作区以管理其专属记忆与技能。`})}function o_({workspaceId:e,onClose:t,onPick:n}){let[r,i]=(0,z.useState)(),[a,o]=(0,z.useState)(!1),[s,c]=(0,z.useState)(``),[l,u]=(0,z.useState)(``),[d,f]=(0,z.useState)(),p=(0,z.useRef)(0);async function m(t){let n=++p.current;o(!0),c(``);try{let r=await fetch(`/api/files?workspaceId=${encodeURIComponent(e)}${t?`&path=${encodeURIComponent(t)}`:``}`),a=await r.json();if(!r.ok)throw Error(a.error??`HTTP ${r.status}`);if(n!==p.current)return;i(a),f(void 0)}catch(e){n===p.current&&c(String(e instanceof Error?e.message:e))}finally{n===p.current&&o(!1)}}(0,z.useEffect)(()=>{m()},[e]),(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.isComposing&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]);let h=l.trim().toLocaleLowerCase(),g=(0,z.useMemo)(()=>(r?.entries??[]).filter(e=>e.kind===`directory`||e.kind===`file`&&e.text&&!e.outside),[r]),_=h?g.filter(e=>e.name.toLocaleLowerCase().includes(h)):g;return(0,B.jsx)(`div`,{className:`overlay`,onClick:t,children:(0,B.jsxs)(`div`,{className:`picker knowledge-picker`,"data-knowledge-picker":`1`,onClick:e=>e.stopPropagation(),role:`dialog`,"aria-modal":`true`,"aria-label":`选择要导入的文档`,children:[(0,B.jsx)(`h2`,{children:`选择要导入的文档`}),(0,B.jsxs)(`div`,{className:`picker-path-bar`,children:[(0,B.jsx)(`input`,{"aria-label":`按文件名过滤`,className:`picker-path-input`,placeholder:`按文件名过滤…`,value:l,onChange:e=>u(e.target.value)}),(0,B.jsx)(`button`,{type:`button`,className:`picker-up-btn`,disabled:!r||r.parent===null||a,onClick:()=>void m(r?.parent??void 0),"aria-label":`上一级`,children:`↑`})]}),(0,B.jsx)(`div`,{className:`picker-status`,"data-knowledge-picker-path":r?.path??``,children:r?r.path||`工作区根目录`:`读取中…`}),s&&(0,B.jsx)(`div`,{className:`picker-error`,role:`alert`,children:s}),(0,B.jsx)(`div`,{className:`picker-list`,"data-knowledge-picker-list":_.length,children:_.length===0?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:h?`没有匹配的文件。`:`这个目录里没有可导入的文本文件。`}):_.map(e=>e.kind===`directory`?(0,B.jsxs)(`button`,{type:`button`,className:`picker-dir`,"data-knowledge-picker-dir":e.path,onClick:()=>void m(e.path),children:[`📁 `,e.name]},e.path):(0,B.jsxs)(`button`,{type:`button`,className:`picker-dir`,"data-knowledge-picker-file":e.path,"aria-pressed":d===e.path,onClick:()=>f(e.path),onDoubleClick:()=>n(e.path),children:[`📄 `,e.name]},e.path))}),(0,B.jsxs)(`div`,{className:`picker-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:t,children:`取消`}),(0,B.jsx)(`button`,{type:`button`,className:`picker-ok`,disabled:!d,"data-knowledge-picker-ok":d??``,onClick:()=>{d&&n(d)},children:`导入这个文档`})]})]})})}function s_({workspaceId:e,onClose:t}){let[n,r]=(0,z.useState)(),[i,a]=(0,z.useState)(``),[o,s]=(0,z.useState)(!1),[c,l]=(0,z.useState)(``),[u,d]=(0,z.useState)(``),[f,p]=(0,z.useState)(``),[m,h]=(0,z.useState)(``),[g,_]=(0,z.useState)(!1),v=(0,z.useRef)(e);v.current=e;let y=(0,z.useRef)(0);async function b(t){if(!e)return;let n=++y.current;s(!0),a(``);try{let i=await fetch(`/api/knowledge?workspaceId=${encodeURIComponent(e)}`,{method:t?`POST`:`GET`,headers:{"Content-Type":`application/json`},...t?{body:JSON.stringify(t)}:{}}),a=await i.json();if(!i.ok)throw Error(a.error);return v.current!==e||n!==y.current?!1:(r(a),!0)}catch(t){return v.current===e&&n===y.current&&a(String(t)),!1}finally{v.current===e&&n===y.current&&s(!1)}}if((0,z.useEffect)(()=>{r(void 0),l(``),d(``),p(``),h(``),b()},[e]),!e)return(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`请先在主界面选择工作区以管理它的知识库。`});let x=n?.documents??[],S=x.reduce((e,t)=>e+t.characters,0),C=n?.semantic,w=C?C.enabled?C.error?`不可用:${C.error};已退回关键词检索`:C.ready?`已就绪,已索引 ${C.indexed} 个片段`:C.bundled===!1?`随包分发的模型缺失;已退回关键词检索`:`首次检索时加载本地模型,之后一直可用`:`已关闭(SUPER_PI_KNOWLEDGE_EMBEDDINGS=0)`:`未启用`;return(0,B.jsxs)(`section`,{"data-knowledge-panel":`1`,className:`settings-panel-container`,children:[(0,B.jsx)(`div`,{className:`settings-agents-header`,children:(0,B.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,B.jsx)(`strong`,{children:`项目自己的文档。`}),` 浏览工作区里的规范、设计稿、会议纪要导入进来,Agent 就能在回答前检索原文,而不是凭记忆编造。文档按当前工作区隔离,检索结果只回传片段而不回传全文。关键词检索始终可用;语义检索能在用词不同的情况下找到片段,但代价是首次使用要下载一个本地模型。`]})}),(0,B.jsxs)(`div`,{className:`settings-dir-info`,"data-knowledge-semantic":C?C.error?`unavailable`:C.ready?`ready`:`loading`:`off`,children:[`语义检索:`,w]}),i&&(0,B.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,children:i}),n&&(0,B.jsxs)(`fieldset`,{disabled:o,className:`settings-memory-fieldset`,children:[(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsxs)(`h4`,{className:`settings-section-title`,children:[`从工作区文件导入(`,x.length,` 篇,共 `,S,` 字符)`]}),(0,B.jsxs)(`div`,{className:`settings-add-dir-form`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-knowledge-browse":`1`,onClick:()=>_(!0),children:`浏览工作区文件…`}),(0,B.jsx)(`span`,{className:`settings-dir-info`,children:`在工作区里挑选一个 Markdown 或文本文件`})]}),(0,B.jsxs)(`div`,{className:`settings-add-dir-form`,style:{marginTop:8},children:[(0,B.jsx)(`input`,{"aria-label":`文档路径`,className:`settings-dir-input`,placeholder:`或直接填写相对路径,例如 docs/design.md`,value:c,onChange:e=>l(e.target.value)}),(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!c.trim(),onClick:async()=>{await b({action:`add`,path:c})&&l(``)},children:`导入`})]}),(0,B.jsxs)(`div`,{className:`settings-memory-editor`,style:{marginTop:12},children:[(0,B.jsx)(`h5`,{className:`settings-memory-editor-title`,children:`或者直接粘贴正文`}),(0,B.jsx)(`input`,{"aria-label":`文档标题`,className:`settings-dir-input`,placeholder:`标题(留空则取正文首行)`,value:u,onChange:e=>d(e.target.value)}),(0,B.jsx)(`textarea`,{"aria-label":`文档正文`,className:`settings-memory-textarea`,placeholder:`以 # 开头的标题会成为检索结果里的段落归属`,value:f,onChange:e=>p(e.target.value)}),(0,B.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!f.trim(),onClick:async()=>{await b({action:`add`,title:u,text:f})&&(d(``),p(``))},children:`保存文档`}),(0,B.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,onClick:()=>{d(``),p(``)},children:`清空`})]})]})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`已导入文档`}),x.length===0?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`还没有文档。导入后,下一条消息起 Agent 就能检索到它们。`}):(0,B.jsx)(`div`,{className:`settings-dirs-list`,children:x.map(e=>(0,B.jsxs)(`article`,{"data-knowledge-document":e.id,className:`settings-memory-card`,children:[(0,B.jsxs)(`div`,{className:`settings-dir-row`,children:[(0,B.jsx)(`span`,{className:`settings-dir-tag`,children:e.format||`txt`}),(0,B.jsx)(`span`,{className:`settings-dir-path`,children:e.title}),(0,B.jsxs)(`span`,{className:`settings-dir-count`,children:[e.characters,` 字符`]})]}),(0,B.jsx)(`div`,{className:`settings-dir-info`,children:e.source}),(0,B.jsx)(`div`,{className:`settings-memory-card-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,onClick:()=>void b({action:`remove`,documentId:e.id}),children:`删除`})})]},e.id))})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`试检索`}),(0,B.jsxs)(`div`,{className:`settings-add-dir-form`,children:[(0,B.jsx)(`input`,{"aria-label":`检索词`,className:`settings-dir-input`,placeholder:`用和提问时相同的措辞试试`,value:m,onChange:e=>h(e.target.value),onKeyDown:e=>{e.key===`Enter`&&m.trim()&&b({action:`search`,query:m})}}),(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!m.trim(),onClick:()=>void b({action:`search`,query:m}),children:`检索`})]}),m.trim()&&(n?.hits?.length===0?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`没有命中。知识库确实没有这段内容——Agent 也会得到同样的空结果。`}):(0,B.jsx)(`div`,{className:`settings-memory-entries-list`,children:(n?.hits??[]).map(e=>(0,B.jsxs)(`article`,{"data-knowledge-hit":`${e.documentId}#${e.chunk}`,className:`settings-memory-card`,children:[(0,B.jsxs)(`div`,{className:`settings-dir-row`,children:[(0,B.jsx)(`span`,{className:`settings-dir-tag`,children:e.title}),(0,B.jsxs)(`span`,{className:`settings-dir-count`,children:[`score `,e.score]})]}),e.heading&&(0,B.jsx)(`div`,{className:`settings-dir-info`,children:e.heading}),(0,B.jsx)(`pre`,{className:`settings-memory-content`,children:e.text})]},`${e.documentId}#${e.chunk}`))}))]})]}),t&&(0,B.jsx)(`div`,{className:`picker-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:t,children:`完成`})}),g&&(0,B.jsx)(o_,{workspaceId:e,onClose:()=>_(!1),onPick:async e=>{_(!1),await b({action:`add`,path:e})&&l(``)}})]})}var c_=[{kind:`calculator`,name:`计算器`,glyph:`∑`,blurb:`算术表达式,四则运算与乘方。除零会明确报错。`},{kind:`timestamp`,name:`时间戳`,glyph:`◷`,blurb:`Unix 时间戳与日期互转,本地计算,不联网。`}],l_=[{id:`preset_calculator`,kind:`calculator`,name:`计算器`,glyph:`∑`}],u_=40,d_=2048,f_=`super-pi:tools:v1`;function p_(e){return typeof e==`string`?e.replace(/\s+/g,` `).trim().slice(0,u_):``}function m_(e){let t=e.trim();if(!t)return{ok:!1,reason:`请填写网址。`};if(t.length>d_)return{ok:!1,reason:`网址太长了,请控制在 ${d_} 个字符以内。`};let n=op(t);return n?{ok:!0,url:n}:{ok:!1,reason:`这个网址不是允许的协议。只支持 http / https / mailto 开头的网址。`}}function h_(e){if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}if(!Array.isArray(t))return[];let n=[],r=new Set;for(let e of t){if(n.length>=32)break;if(typeof e!=`object`||!e)continue;let t=e,i=t.kind;if(typeof i!=`string`||i!==`calculator`&&i!==`timestamp`&&i!==`link`)continue;let a=p_(t.name);if(!a)continue;let o=typeof t.glyph==`string`&&t.glyph.trim()?t.glyph.trim().slice(0,4):``;if(!o)continue;let s=typeof t.id==`string`&&t.id.trim()?t.id.trim().slice(0,64):``;if(s&&!r.has(s)){if(i===`link`){let e=op(typeof t.url==`string`?t.url:``);if(!e)continue;r.add(s),n.push({id:s,kind:`link`,name:a,glyph:o,url:e})}else r.add(s),n.push({id:s,kind:i,name:a,glyph:o})}}return n}function g_(e){return JSON.stringify(e.map(e=>e.kind===`link`?{...e}:{id:e.id,kind:e.kind,name:e.name,glyph:e.glyph}))}function __(){let e=typeof globalThis<`u`?globalThis.crypto:void 0;return typeof e?.randomUUID==`function`?e.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}function v_(e,t){let n=e===`link`?`link`:`preset_${e}`,r=__().replace(/-/g,``).slice(0,8),i=`${n}_${r}`,a=1;for(;t.includes(i);)i=`${n}_${r}_${a}`,a+=1;return i}function y_(e,t){if(e.some(e=>e.kind===t))return e.slice();let n=c_.find(e=>e.kind===t);return n?[...e,{id:v_(t,e.map(e=>e.id)),kind:t,name:n.name,glyph:n.glyph}]:e.slice()}function b_(e,t){return e.filter(e=>e.id!==t)}var x_=e=>({ok:!1,reason:e}),S_=`除数不能为 0:除以零没有结果,请换一个非零的除数。`,C_=new Set([`/`,`%`]),w_=e=>e!==void 0&&e>=`0`&&e<=`9`,T_=e=>e!==void 0&&/\s/.test(e);function E_(e){for(;T_(e.source[e.at]);)e.at+=1}function D_(e){let t=e.at,n=0;for(;w_(e.source[e.at]);)e.at+=1,n+=1;if(e.source[e.at]===`.`)for(e.at+=1;w_(e.source[e.at]);)e.at+=1,n+=1;if(!n)return e.at=t,x_(`「${e.source[t]}」不是有效的数字。`);let r=Number(e.source.slice(t,e.at));return Number.isFinite(r)?{ok:!0,value:r}:x_(`数字太长了,无法表示。`)}function O_(e){E_(e);let t=e.source[e.at];if(t===void 0)return x_(`算式不完整:末尾还缺一个数字或右括号。`);if(t===`(`){e.at+=1;let t=M_(e);return t.ok?(E_(e),e.source[e.at]===`)`?(e.at+=1,t):x_(`括号不匹配:少了一个右括号「)」。`)):t}return w_(t)||t===`.`?D_(e):x_(`无法识别的字符「${t}」。`)}function k_(e){let t=O_(e);if(!t.ok||(E_(e),e.source[e.at]!==`^`))return t;e.at+=1;let n=A_(e);if(!n.ok)return n;let r=t.value**n.value;return Number.isFinite(r)?{ok:!0,value:r}:x_(`结果超出了可计算的数值范围。`)}function A_(e){E_(e);let t=e.source[e.at];if(t!==`+`&&t!==`-`)return k_(e);e.at+=1;let n=A_(e);if(!n.ok)return n;let r=t===`-`?-n.value:n.value;return Number.isFinite(r)?{ok:!0,value:r}:x_(`结果超出了可计算的数值范围。`)}function j_(e){let t=A_(e);if(!t.ok)return t;for(;;){E_(e);let n=e.source[e.at];if(n!==`*`&&!C_.has(n))return t;e.at+=1;let r=A_(e);if(!r.ok)return r;if(C_.has(n)&&r.value===0)return x_(S_);let i=n===`*`?t.value*r.value:n===`%`?t.value%r.value:t.value/r.value;if(!Number.isFinite(i))return x_(`结果超出了可计算的数值范围。`);t={ok:!0,value:i}}}function M_(e){let t=j_(e);if(!t.ok)return t;for(;;){E_(e);let n=e.source[e.at];if(n!==`+`&&n!==`-`)return t;e.at+=1;let r=j_(e);if(!r.ok)return r;let i=n===`+`?t.value+r.value:t.value-r.value;if(!Number.isFinite(i))return x_(`结果超出了可计算的数值范围。`);t={ok:!0,value:i}}}function N_(e){let t=e.trim();if(!t)return x_(`请输入算式。`);if(t.length>200)return x_(`算式太长了,请控制在 200 个字符以内。`);let n={source:t,at:0},r=M_(n);return r.ok?(E_(n),n.at===t.length?Number.isFinite(r.value)?r:x_(`结果不是有限数字。`):x_(`「${t[n.at]}」后面的内容无法识别,请检查是否漏了运算符。`)):r}function P_(e){return String(!Number.isFinite(e)||Number.isInteger(e)&&Math.abs(e)<1e21?e:Number(e.toPrecision(12)))}function F_(e){let t=e.trim();if(!t)return{ok:!1,reason:`请输入时间戳或日期。`};if(/^-?\d+$/.test(t)){let e=Number(t);if(!Number.isFinite(e))return{ok:!1,reason:`这个数字太大,无法表示。`};let n=t.replace(`-`,``).length<=11?e*1e3:e;return!Number.isFinite(n)||Math.abs(n)>864e13?{ok:!1,reason:`这个时间戳超出了日期能表示的范围。`}:{ok:!0,ms:n}}let n=Date.parse(t);return Number.isNaN(n)?{ok:!1,reason:`看不懂这个日期。试试 1757000000、2026-10-08 或 2026-10-08T09:00:00。`}:{ok:!0,ms:n}}var I_=e=>String(Math.abs(e)).padStart(2,`0`);function L_(e){let t=new Date(e);return Number.isNaN(t.getTime())?null:{local:`${t.getFullYear()}-${I_(t.getMonth()+1)}-${I_(t.getDate())} ${I_(t.getHours())}:${I_(t.getMinutes())}:${I_(t.getSeconds())}`,iso:t.toISOString(),seconds:String(Math.floor(e/1e3)),milliseconds:String(e)}}var R_=e=>e.nativeEvent.isComposing||e.keyCode===229,z_=`super-pi.theme`,B_=[{id:`dracula`,name:`Dracula`,blurb:`紫调暗色,饱满对比,适合夜间专注。`},{id:`monokai`,name:`Monokai`,blurb:`暖调暗色,橙红点缀,经典编辑器风格。`},{id:`solarized-light`,name:`Solarized Light`,blurb:`暖黄米色调,柔和护眼,适合长时间阅读。`},{id:`github-light`,name:`GitHub Light`,blurb:`冷调浅色,中性清晰,日常办公首选。`}],V_=`dracula`,H_=e=>typeof e==`string`&&B_.some(t=>t.id===e);function U_(){try{let e=window.localStorage.getItem(z_);if(!e)return V_;let t=JSON.parse(e),n=typeof t==`string`?t:t?.id;return H_(n)?n:V_}catch{return V_}}function W_(e){document.documentElement.setAttribute(`data-theme`,e);try{window.localStorage.setItem(z_,JSON.stringify({id:e,version:1}))}catch{}}function G_(){let[e,t]=(0,z.useState)(V_);return(0,z.useEffect)(()=>{t(U_());let e=e=>{if(e.key===`super-pi.theme`&&e.newValue)try{let n=JSON.parse(e.newValue),r=typeof n==`string`?n:n?.id;H_(r)&&(document.documentElement.setAttribute(`data-theme`,r),t(r))}catch{}};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),{theme:e,setTheme:(0,z.useCallback)(e=>{W_(e),t(e)},[])}}function K_({theme:e,onChooseTheme:t,onClose:n}){let r=B_.find(t=>t.id===e);return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`div`,{className:`settings-scope`,children:`主题只影响这台设备的显示,不改变任何内容;切换立即生效。`}),B_.length===0?(0,B.jsx)(`div`,{className:`theme-empty`,"data-theme-empty":`1`,children:`没有可用的主题。界面将继续使用默认配色,你可以在主题文件恢复后重试。`}):(0,B.jsx)(`div`,{className:`theme-options`,role:`radiogroup`,"aria-label":`主题`,children:B_.map(n=>{let r=n.id===e;return(0,B.jsxs)(`button`,{type:`button`,className:`theme-option`,role:`radio`,"aria-checked":r,"aria-pressed":r,"data-theme-option":n.id,"data-theme-current":r?`1`:`0`,onClick:()=>t(n.id),children:[(0,B.jsx)(`span`,{className:`theme-preview-strip`,"data-preview":n.id,"aria-hidden":`true`}),(0,B.jsxs)(`span`,{className:`theme-option-name`,children:[n.name,r&&(0,B.jsx)(`span`,{className:`theme-option-current`,children:`当前 ✓`})]}),(0,B.jsx)(`span`,{className:`theme-option-blurb`,children:n.blurb})]},n.id)})}),(0,B.jsx)(`div`,{className:`picker-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,"data-theme-close":`1`,onClick:n,children:`完成`})}),(0,B.jsxs)(`div`,{className:`settings-scope theme-current-line`,children:[`当前:`,r?`${r.name}(${r.id})`:`默认`]})]})}function q_({userNickname:e,onSetUserNickname:t,onClose:n}){return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`div`,{className:`settings-scope`,children:`昵称会显示在消息时间戳旁和头像上,替代默认的「你」。留空恢复默认。`}),(0,B.jsxs)(`div`,{className:`general-nickname`,children:[(0,B.jsx)(`label`,{className:`general-nickname-label`,htmlFor:`general-nickname-input`,children:`昵称`}),(0,B.jsx)(`input`,{id:`general-nickname-input`,type:`text`,className:`general-nickname-input`,"data-general-nickname":`1`,maxLength:24,placeholder:`你`,value:e??``,onChange:e=>t?.(e.target.value)}),(0,B.jsx)(`span`,{className:`general-nickname-hint`,"data-general-nickname-preview":`1`,title:`当前显示`,children:e?.trim()?`将显示为:${e.trim()}`:`将显示为:你`})]}),(0,B.jsx)(`div`,{className:`picker-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:n,children:`完成`})})]})}function J_({context:e}){let[t,n]=(0,z.useState)(``),[r,i]=(0,z.useState)(``),[a,o]=(0,z.useState)(!1),s=e.agentCatalog,c=e.subagentCatalog,l=s?.agents??[],u=c?.agents??[],d=[...l,...u],f=[...s?.problems??[],...c?.problems??[]],p=[...new Set([...s?.directories??(s?.directory?[s.directory]:[]),...e.customAgentDirs??[]])],m=e.customAgentDirs??[],h=r=>{if(r.preventDefault(),e.pendingSettings)return;let a=t.trim();a&&(m.includes(a)?i(`该路径已存在于自定义目录列表中`):(e.onSetCustomAgentDirs?.([...m,a]),n(``),i(``)))},g=t=>{let n=m.filter(e=>e!==t);e.onSetCustomAgentDirs?.(n)};return(0,B.jsxs)(`div`,{className:`settings-agents-container`,children:[(0,B.jsxs)(`div`,{className:`settings-agents-header`,children:[(0,B.jsx)(`p`,{className:`settings-agents-desc`,children:`Super Pi 支持多目录发现智能体。系统会按优先级自上而下合并扫描目录;若存在同名配置,高优先级目录的文件将覆盖低优先级目录。`}),(0,B.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,onClick:()=>{o(!0),e.onRescanAgents?.(),setTimeout(()=>o(!1),600)},disabled:a,title:`重新扫描所有目录中的智能体定义文件`,children:a?`正在扫描…`:`🔄 立即重新扫描`})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`发现路径清单(按优先级自高到低)`}),(0,B.jsx)(`div`,{className:`settings-dirs-list`,children:p.length===0?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`暂无活跃的发现路径`}):p.map((t,n)=>{let r=m.includes(t),i=t.includes(`.super_pi`)||t.includes(`.super-pi`)||t.includes(`.pi`),a=!r&&!i,o=d.filter(e=>e.sourceDir===t).length;return(0,B.jsxs)(`div`,{className:`settings-dir-row`,children:[(0,B.jsxs)(`div`,{className:`settings-dir-info`,children:[(0,B.jsxs)(`span`,{className:`settings-dir-priority`,children:[`#`,n+1]}),(0,B.jsx)(`span`,{className:`settings-dir-path`,title:t,children:t}),(0,B.jsx)(`span`,{className:`settings-dir-tag`,children:r?`自定义`:i?`用户全局`:a?`内置`:`环境`}),(0,B.jsxs)(`span`,{className:`settings-dir-count`,children:[`(发现 `,o,` 个智能体)`]})]}),r&&(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,disabled:e.pendingSettings,onClick:()=>g(t),title:`移除此自定义扫描路径`,children:`移除`})]},t)})})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`添加自定义路径`}),(0,B.jsxs)(`form`,{onSubmit:h,className:`settings-add-dir-form`,children:[(0,B.jsx)(`input`,{type:`text`,className:`settings-dir-input`,value:t,onChange:e=>{n(e.target.value),r&&i(``)},onKeyDown:e=>{e.key===`Enter`&&R_(e)&&e.preventDefault()},placeholder:`输入本地目录绝对路径或 ~/ 开头路径,如 D:\\agents 或 ~/.super_pi/agents`}),(0,B.jsx)(`button`,{type:`submit`,className:`settings-dir-add-btn`,disabled:e.pendingSettings||!t.trim(),children:`添加目录`})]}),r&&(0,B.jsx)(`div`,{className:`settings-dir-error`,children:r})]}),f.length>0&&(0,B.jsxs)(`section`,{className:`settings-section settings-problems-section`,children:[(0,B.jsxs)(`h4`,{className:`settings-problems-title`,children:[`⚠️ 发现 `,f.length,` 个文件解析问题`]}),(0,B.jsx)(`div`,{className:`settings-problems-list`,children:f.map((e,t)=>(0,B.jsxs)(`div`,{className:`settings-problem-row`,children:[(0,B.jsx)(`span`,{className:`settings-problem-file`,children:e.file}),`: `,e.message]},t))})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsxs)(`h4`,{className:`settings-section-title`,children:[`已发现的智能体(共 `,d.length,` 个)`]}),d.length===0?(0,B.jsxs)(`div`,{className:`settings-empty-hint`,children:[`当前未发现任何智能体。请在上述目录中添加 `,(0,B.jsx)(`code`,{children:`.md`}),` 文件(需包含 YAML frontmatter)。`]}):(0,B.jsx)(`div`,{className:`settings-agent-grid`,children:d.map(e=>(0,B.jsxs)(`div`,{className:`settings-agent-card`,children:[(0,B.jsxs)(`div`,{className:`settings-agent-card-header`,children:[(0,B.jsx)(`span`,{className:`settings-agent-name`,children:e.name}),(0,B.jsxs)(`span`,{className:`settings-agent-id`,children:[`(`,e.id,`)`]}),(0,B.jsx)(`span`,{className:`settings-agent-mode-badge ${e.mode}`,children:e.mode===`primary`?`主智能体`:`子智能体`})]}),e.sourceDir&&(0,B.jsxs)(`div`,{className:`settings-agent-source`,title:e.sourceDir,children:[`来源:`,e.sourceDir]}),e.description&&(0,B.jsx)(`div`,{className:`settings-agent-desc`,children:e.description}),(0,B.jsxs)(`div`,{className:`settings-agent-footer`,children:[(0,B.jsx)(`span`,{className:`settings-agent-tools`,children:e.toolSummary}),e.model&&(0,B.jsxs)(`span`,{className:`settings-agent-model`,children:[e.model.provider,`/`,e.model.modelId]})]})]},`${e.sourceDir}-${e.id}`))})]}),(0,B.jsx)(`div`,{className:`picker-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}function Y_(e){return(0,B.jsx)(J_,{context:e})}function X_({context:e}){let[t,n]=(0,z.useState)(``),[r,i]=(0,z.useState)(``),[a,o]=(0,z.useState)(),s=e=>{try{return new RegExp(e,`i`),!1}catch{return!0}},c=s(t),l=s(r),u=e.modelFilterRules??[];return(0,B.jsxs)(`section`,{"data-model-rules":`1`,className:`settings-panel-container`,children:[(0,B.jsx)(`div`,{className:`settings-agents-header`,children:(0,B.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,B.jsx)(`strong`,{children:`按工作区约束可用模型。`}),`当工作区名称匹配指定正则表达式时,会话中仅可选择符合模型正则的模型(匹配模型名称或 `,(0,B.jsx)(`code`,{children:`provider/modelId`}),`)。多条命中规则必须全部满足。`]})}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsxs)(`h4`,{className:`settings-section-title`,children:[`已配置的过滤规则(共 `,u.length,` 条)`]}),u.length===0?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`暂无模型过滤规则。所有工作区默认可使用全部已配置模型。`}):(0,B.jsx)(`div`,{className:`settings-dirs-list`,children:u.map(t=>{let r=a===t.id;return(0,B.jsxs)(`div`,{className:`settings-rule-card ${r?`editing`:``}`,children:[(0,B.jsx)(`div`,{className:`settings-rule-info`,children:(0,B.jsxs)(`div`,{className:`settings-rule-patterns`,children:[(0,B.jsxs)(`span`,{className:`settings-rule-pill`,children:[(0,B.jsx)(`span`,{className:`settings-rule-pill-tag`,children:`工作区`}),(0,B.jsx)(`code`,{className:`settings-rule-code`,title:t.workspacePattern,children:t.workspacePattern})]}),(0,B.jsx)(`span`,{className:`settings-rule-arrow`,"aria-hidden":`true`,children:`→`}),(0,B.jsxs)(`span`,{className:`settings-rule-pill`,children:[(0,B.jsx)(`span`,{className:`settings-rule-pill-tag`,children:`允许模型`}),(0,B.jsx)(`code`,{className:`settings-rule-code`,title:t.modelPattern,children:t.modelPattern})]})]})}),(0,B.jsxs)(`div`,{className:`settings-rule-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-rule-edit-btn`,onClick:()=>{o(t.id),n(t.workspacePattern),i(t.modelPattern)},children:r?`编辑中`:`编辑`}),(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,onClick:()=>{a===t.id&&(o(void 0),n(``),i(``)),e.onSetModelRules?.(u.filter(e=>e.id!==t.id))},children:`删除`})]})]},t.id)})})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:a?`编辑过滤规则`:`添加新规则`}),(0,B.jsxs)(`fieldset`,{disabled:e.pendingSettings,className:`model-rules-fields settings-rule-fieldset`,children:[(0,B.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`工作区名正则表达式`}),(0,B.jsx)(`input`,{type:`text`,"data-rule-workspace":`1`,className:`settings-dir-input`,value:t,"aria-invalid":c,placeholder:`如 ^proj- 或 my-workspace`,onChange:e=>n(e.target.value)})]}),(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`允许的模型名正则表达式`}),(0,B.jsx)(`input`,{type:`text`,"data-rule-model":`1`,className:`settings-dir-input`,value:r,"aria-invalid":l,placeholder:`如 anthropic/.* 或 gpt-4o|claude`,onChange:e=>i(e.target.value)})]})]}),(c||l)&&(0,B.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,children:`⚠️ 正则表达式语法不合法,请检查后修正。`}),(0,B.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,B.jsx)(`button`,{type:`button`,"data-rule-save":`1`,className:`settings-dir-add-btn`,disabled:!t.trim()||!r.trim()||c||l,onClick:()=>{let s={id:a??__(),workspacePattern:t.trim(),modelPattern:r.trim()};e.onSetModelRules?.([...u.filter(e=>e.id!==s.id),s]),n(``),i(``),o(void 0)},children:a?`保存修改`:`添加规则`}),a&&(0,B.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,onClick:()=>{o(void 0),n(``),i(``)},children:`取消编辑`})]})]})]}),(0,B.jsx)(`div`,{className:`picker-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}function Z_({context:e}){let t=e.providers??[],n=e.providerApis??[],[r,i]=(0,z.useState)({kind:`add`}),[a,o]=(0,z.useState)(``),[s,c]=(0,z.useState)(``),[l,u]=(0,z.useState)(``),[d,f]=(0,z.useState)(``),[p,m]=(0,z.useState)(``),[h,g]=(0,z.useState)(!1),[_,v]=(0,z.useState)(``),[y,b]=(0,z.useState)(``),[x,S]=(0,z.useState)(!1),[C,w]=(0,z.useState)(!1),[T,E]=(0,z.useState)(``),[D,O]=(0,z.useState)(``),[k,A]=(0,z.useState)(!0),[ee,j]=(0,z.useState)(!0),M=r.kind===`add`?void 0:t.find(e=>e.id===r.providerId),N=(0,z.useRef)(!1),te=()=>{N.current=!0},ne=(0,z.useRef)(!1);(0,z.useEffect)(()=>{ne.current&&(ne.current=!1,!N.current&&re())},[t]);let re=()=>{i({kind:`add`}),N.current=!1,o(``),c(``),u(``),f(n[0]??`openai-completions`),m(``),g(!1),v(``),b(``),S(!1),w(!1),E(``),O(``),A(!0),j(!0)},ie=e=>{o(e.id),c(e.name===e.id?``:e.name),u(e.baseUrl),f(e.api),m(``),g(!1)},ae=e=>{v(e?.id??``),b(!e||e.name===e.id?``:e.name),S(e?.reasoning??!1),w(e?.imageInput??!1),E(e?String(e.contextWindow):``),O(e?String(e.maxTokens):``),A(!0),j(!0)},oe=e=>{let n=t.find(t=>t.id===e);n&&(te(),i({kind:`addModel`,providerId:e}),ie(n),ae(void 0))},se=(e,n)=>{let r=t.find(t=>t.id===e),a=r?.models.find(e=>e.id===n);r&&a&&(te(),i({kind:`editModel`,providerId:e,modelId:n}),ie(r),ae(a))},ce=a.trim()&&l.trim()&&d.trim()&&_.trim()&&!e.pendingSettings;return(0,B.jsxs)(`section`,{className:`settings-section`,"data-settings-providers":`1`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`自定义供应商与模型`}),(0,B.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,B.jsx)(`strong`,{children:`不用再手改 Pi 的模型配置文件。`}),`这里填的供应商会写进 Pi 自己的配置(`,(0,B.jsx)(`code`,{children:`models.json`}),` 放定义、`,(0,B.jsx)(`code`,{children:`auth.json`}),` 放 key), 所以 Super Pi 的会话、终端里的 `,(0,B.jsx)(`code`,{children:`pi`}),` 都能用上它。Pi 配置文件里你自己写的其它条目不会被动到。`]}),t.length>0&&(0,B.jsx)(`div`,{className:`settings-provider-list`,children:t.map(t=>(0,B.jsxs)(`div`,{className:`settings-provider-card`,"data-provider-row":t.id,children:[(0,B.jsxs)(`div`,{className:`settings-provider-head`,children:[(0,B.jsx)(`span`,{className:`settings-provider-id`,children:t.id}),t.name!==t.id&&(0,B.jsx)(`span`,{className:`settings-provider-name`,children:t.name}),t.hasKey&&(0,B.jsx)(`span`,{className:`settings-provider-badge`,children:`已设置 key`})]}),(0,B.jsxs)(`div`,{className:`settings-provider-meta`,children:[t.baseUrl,` · `,t.api]}),(0,B.jsx)(`div`,{className:`settings-provider-models`,children:t.models.map(n=>(0,B.jsxs)(`div`,{className:`settings-provider-model-row`,"data-model-row":`${t.id}:${n.id}`,children:[(0,B.jsx)(`span`,{className:`settings-provider-model`,children:n.name}),(0,B.jsx)(`code`,{className:`settings-provider-model-id`,children:n.id}),(0,B.jsxs)(`div`,{className:`settings-provider-model-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-provider-link`,"data-model-edit":`${t.id}:${n.id}`,onClick:()=>se(t.id,n.id),children:`编辑`}),(0,B.jsx)(`button`,{type:`button`,className:`settings-provider-link danger`,"data-model-delete":`${t.id}:${n.id}`,onClick:()=>e.onRemoveProviderModel?.(t.id,n.id),children:`删除`})]})]},n.id))}),(0,B.jsxs)(`div`,{className:`settings-provider-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-provider-add-model":t.id,onClick:()=>oe(t.id),children:`添加模型`}),(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-provider-delete":t.id,onClick:()=>e.onRemoveProvider?.(t.id),children:`删除供应商`})]})]},t.id))}),(0,B.jsxs)(`h4`,{className:`settings-section-title`,children:[r.kind===`add`&&`添加供应商与模型`,r.kind===`addModel`&&`为供应商「${r.providerId}」添加模型`,r.kind===`editModel`&&`编辑模型「${r.modelId}」`]}),r.kind!==`add`&&(0,B.jsxs)(`p`,{className:`settings-agents-desc`,"data-provider-shared-note":`1`,children:[`上面这些是这个供应商下`,(0,B.jsx)(`b`,{children:`所有模型共用`}),`的(地址、API 类型、key)。改动会同时影响它下面的每个模型。`]}),(0,B.jsxs)(`div`,{className:`settings-provider-form`,onChange:te,children:[(0,B.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`供应商 id`}),(0,B.jsx)(`input`,{type:`text`,"data-provider-id":`1`,className:`settings-dir-input`,value:a,placeholder:`如 my-proxy`,readOnly:r.kind!==`add`,onChange:e=>o(e.target.value)})]}),(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`显示名称`}),(0,B.jsx)(`input`,{type:`text`,"data-provider-name":`1`,className:`settings-dir-input`,value:s,placeholder:`如 公司中转`,onChange:e=>c(e.target.value)})]})]}),(0,B.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`API 地址`}),(0,B.jsx)(`input`,{type:`text`,"data-provider-base-url":`1`,className:`settings-dir-input`,value:l,placeholder:`如 https://api.example.com/v1`,onChange:e=>u(e.target.value)})]}),(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`API 类型`}),(0,B.jsx)(`select`,{"data-provider-api":`1`,className:`settings-model-select`,value:d,onChange:e=>f(e.target.value),children:(n.length?n:[`openai-completions`]).map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))})]})]}),(0,B.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`API key`}),(0,B.jsx)(`input`,{type:`password`,"data-provider-api-key":`1`,className:`settings-dir-input`,value:p,autoComplete:`off`,placeholder:M?.hasKey?`已设置,留空表示不修改`:`如 sk-...`,onChange:e=>m(e.target.value)})]}),(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`模型 id`}),(0,B.jsx)(`input`,{type:`text`,"data-model-id":`1`,className:`settings-dir-input`,value:_,placeholder:`如 gpt-4o`,onChange:e=>v(e.target.value)})]})]}),(0,B.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`模型显示名`}),(0,B.jsx)(`input`,{type:`text`,"data-model-name":`1`,className:`settings-dir-input`,value:y,placeholder:`留空则用模型 id`,onChange:e=>b(e.target.value)})]}),(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`上下文窗口 / 最大输出`}),(0,B.jsxs)(`div`,{className:`settings-provider-numbers`,children:[(0,B.jsx)(`input`,{type:`number`,"data-model-context-window":`1`,className:`settings-dir-input`,value:T,placeholder:`128000`,onChange:e=>E(e.target.value)}),(0,B.jsx)(`input`,{type:`number`,"data-model-max-tokens":`1`,className:`settings-dir-input`,value:D,placeholder:`16384`,onChange:e=>O(e.target.value)})]})]})]}),(0,B.jsxs)(`div`,{className:`settings-provider-switches`,children:[(0,B.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,B.jsx)(`input`,{type:`checkbox`,"data-model-reasoning":`1`,checked:x,onChange:e=>S(e.target.checked)}),`推理模型`]}),(0,B.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,B.jsx)(`input`,{type:`checkbox`,"data-model-image-input":`1`,checked:C,onChange:e=>w(e.target.checked)}),`支持图片输入`]}),(0,B.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,B.jsx)(`input`,{type:`checkbox`,"data-model-developer-role":`1`,checked:k,onChange:e=>A(e.target.checked)}),`支持 developer 角色`]}),(0,B.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,B.jsx)(`input`,{type:`checkbox`,"data-model-reasoning-effort":`1`,checked:ee,onChange:e=>j(e.target.checked)}),`支持 reasoning_effort`]}),M?.hasKey&&(0,B.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,B.jsx)(`input`,{type:`checkbox`,"data-provider-clear-key":`1`,checked:h,onChange:e=>g(e.target.checked)}),`清除已保存的 key`]})]}),(0,B.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,B.jsx)(`button`,{type:`button`,"data-provider-save":`1`,className:`settings-dir-add-btn`,disabled:!ce,onClick:()=>{ne.current=!0,N.current=!1,e.onSetProvider?.({id:a.trim(),...s.trim()?{name:s.trim()}:{},baseUrl:l.trim(),api:d.trim(),...p.trim()?{apiKey:p.trim()}:{},...h?{clearKey:!0}:{},models:[{id:_.trim(),...y.trim()?{name:y.trim()}:{},...x?{reasoning:!0}:{},...C?{imageInput:!0}:{},...T.trim()?{contextWindow:Number(T)}:{},...D.trim()?{maxTokens:Number(D)}:{},...k?{}:{supportsDeveloperRole:!1},...ee?{}:{supportsReasoningEffort:!1}}]})},children:r.kind===`add`?`添加`:r.kind===`addModel`?`添加模型`:`保存修改`}),r.kind!==`add`&&(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-provider-cancel":`1`,onClick:re,children:`取消`})]})]})]})}function Q_({context:e}){let t=e.modelCatalog,n=e.defaultModel,r=t?.models??[],i=r.reduce((e,t)=>e.includes(t.provider)?e:[...e,t.provider],[]),a=n?`${n.provider}/${n.modelId}`:``,[o,s]=(0,z.useState)(n?.provider??``),[c,l]=(0,z.useState)(n?.modelId??``),u=(0,z.useRef)(void 0);(0,z.useEffect)(()=>{u.current!==a&&(u.current=a,s(n?.provider??``),l(n?.modelId??``))},[a,n]);let d=n&&!i.includes(n.provider)?[...i,n.provider]:i,f=d.includes(o)?o:d[0]??``,p=r.filter(e=>e.provider===f),m=n&&n.provider===f&&!p.some(e=>e.modelId===n.modelId)?[...p,{provider:n.provider,modelId:n.modelId,label:n.label}]:p,h=m.some(e=>e.modelId===c)?c:m[0]?.modelId??``,g=!n||r.some(e=>e.provider===n.provider&&e.modelId===n.modelId),_=f&&h?`${f}/${h}`:``,v=_!==a,y=!t,b=t?.source===`unavailable`,x=e=>{s(e);let t=r.filter(t=>t.provider===e);l(e=>t.some(t=>t.modelId===e)?e:t[0]?.modelId??``)};return(0,B.jsxs)(`section`,{"data-settings-model":`1`,className:`settings-panel-container`,children:[(0,B.jsx)(`div`,{className:`settings-agents-header`,children:(0,B.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,B.jsx)(`strong`,{children:`设置新建会话的默认模型。`}),`这里的选择对所有工作区生效,但优先级低于工作区自己的默认模型;两者都没有时,跟随 Pi 的默认模型。 默认值只在会话创建时复制一次,之后改这里不会改动已经存在的会话。`]})}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`当前默认模型`}),(0,B.jsx)(`div`,{className:`settings-model-current`,"data-model-current":`1`,children:n?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`span`,{className:`settings-model-current-name`,children:n.label}),(0,B.jsxs)(`code`,{className:`settings-model-current-pair`,children:[n.provider,`/`,n.modelId]})]}):(0,B.jsx)(`span`,{className:`settings-model-current-none`,children:`跟随 Pi 默认模型`})}),n&&!g&&(0,B.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,children:`⚠️ Pi 当前不再提供这个模型,新会话会改用 Pi 的默认模型。`})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`修改默认模型`}),y?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`正在读取 Pi 的模型列表…`}):b?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`无法读取 Pi 的模型列表,暂时不能设置默认模型。`}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`settings-model-grid`,children:[(0,B.jsxs)(`label`,{className:`settings-model-group`,children:[(0,B.jsx)(`span`,{className:`settings-model-label`,children:`供应商`}),(0,B.jsx)(`select`,{"data-model-provider":`1`,className:`settings-model-select`,value:f,disabled:e.pendingSettings||d.length===0,onChange:e=>x(e.target.value),children:d.map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))})]}),(0,B.jsxs)(`label`,{className:`settings-model-group`,children:[(0,B.jsx)(`span`,{className:`settings-model-label`,children:`模型`}),(0,B.jsx)(`select`,{"data-model-select":`1`,className:`settings-model-select`,value:h,disabled:e.pendingSettings||m.length===0,onChange:e=>l(e.target.value),children:m.map(e=>(0,B.jsx)(`option`,{value:e.modelId,children:e.label},e.modelId))})]})]}),(0,B.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,B.jsx)(`button`,{type:`button`,"data-model-save":`1`,className:`settings-dir-add-btn`,disabled:!v||e.pendingSettings||!_,onClick:()=>{let t=r.find(e=>e.provider===f&&e.modelId===h);t&&e.onSetDefaultModel?.({provider:t.provider,modelId:t.modelId,label:t.label})},children:`保存默认模型`}),(0,B.jsx)(`button`,{type:`button`,"data-model-clear":`1`,className:`settings-dir-cancel-btn`,disabled:!n||e.pendingSettings,onClick:()=>e.onSetDefaultModel?.(null),children:`清除默认模型`})]})]})]}),(0,B.jsx)(Z_,{context:e}),(0,B.jsx)(`div`,{className:`picker-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}var $_=[{id:`appearance`,label:`外观`,render:K_},{id:`general`,label:`通用`,render:q_},{id:`memory`,label:`主动记忆`,render:e=>(0,B.jsx)(a_,{workspaceId:e.workspaceId,onClose:e.onClose})},{id:`knowledge`,label:`知识库`,render:e=>(0,B.jsx)(s_,{workspaceId:e.workspaceId,onClose:e.onClose})},{id:`agents`,label:`智能体`,render:Y_},{id:`model`,label:`模型`,render:e=>(0,B.jsx)(Q_,{context:e})},{id:`model-rules`,label:`模型过滤`,render:e=>(0,B.jsx)(X_,{context:e})}],ev=$_[0]?.id;function tv({workspaceId:e,theme:t,onChooseTheme:n,onClose:r,agentCatalog:i,subagentCatalog:a,modelFilterRules:o,onSetModelRules:s,defaultModel:c,modelCatalog:l,onSetDefaultModel:u,providers:d,providerApis:f,onSetProvider:p,onRemoveProvider:m,onRemoveProviderModel:h,customAgentDirs:g,pendingSettings:_,onSetCustomAgentDirs:v,onRescanAgents:y,userNickname:b,onSetUserNickname:x}){let[S,C]=(0,z.useState)(ev);(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.defaultPrevented&&r()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r]);let w=$_.find(e=>e.id===S)??$_[0];return(0,B.jsx)(`div`,{className:`overlay`,onClick:r,children:(0,B.jsxs)(`div`,{className:`picker settings-window`,"data-theme-dialog":`1`,"data-settings-window":`1`,onClick:e=>e.stopPropagation(),children:[(0,B.jsx)(`div`,{className:`settings-window-head`,children:(0,B.jsx)(`h2`,{children:`设置`})}),(0,B.jsxs)(`div`,{className:`settings-window-body`,children:[(0,B.jsxs)(`nav`,{className:`settings-nav`,role:`tablist`,"aria-orientation":`vertical`,"aria-label":`设置分类`,"data-settings-nav":`1`,children:[(0,B.jsx)(`div`,{className:`settings-nav-label`,children:`分类`}),$_.map(e=>(0,B.jsx)(`button`,{type:`button`,id:`settings-tab-${e.id}`,className:`settings-category`,role:`tab`,"aria-selected":e.id===w?.id,"aria-controls":`settings-panel`,tabIndex:e.id===w?.id?0:-1,"data-settings-category":e.id,onClick:()=>C(e.id),children:e.label},e.id))]}),w&&(0,B.jsxs)(`div`,{className:`settings-panel`,id:`settings-panel`,role:`tabpanel`,"aria-labelledby":`settings-tab-${w.id}`,"data-settings-panel":w.id,children:[(0,B.jsx)(`h3`,{className:`settings-panel-title`,"data-settings-panel-title":w.id,children:w.label}),w.render({workspaceId:e,theme:t,onChooseTheme:n,onClose:r,agentCatalog:i,subagentCatalog:a,modelFilterRules:o,onSetModelRules:s,defaultModel:c,modelCatalog:l,onSetDefaultModel:u,providers:d,providerApis:f,onSetProvider:p,onRemoveProvider:m,onRemoveProviderModel:h,customAgentDirs:g,pendingSettings:_,onSetCustomAgentDirs:v,onRescanAgents:y,userNickname:b,onSetUserNickname:x})]})]})]})})}var nv=Object.defineProperty,rv=Object.getOwnPropertyDescriptor,iv=(e,t)=>{for(var n in t)nv(e,n,{get:t[n],enumerable:!0})},av=(e,t,n,r)=>{for(var i=r>1?void 0:r?rv(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&nv(t,n,i),i},X=(e,t)=>(n,r)=>t(n,r,e),ov=`Terminal input`,sv={get:()=>ov,set:e=>ov=e},cv=`Too much output to announce, navigate to rows manually to read`,lv={get:()=>cv,set:e=>cv=e};function uv(e){return e.replace(/\r?\n/g,`\r`)}function dv(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function fv(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function pv(e,t,n,r){e.stopPropagation(),e.clipboardData&&mv(e.clipboardData.getData(`text/plain`),t,n,r)}function mv(e,t,n,r){e=uv(e),e=dv(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function hv(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function gv(e,t,n,r,i){hv(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function _v(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function vv(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var yv=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o)}else i!==65279&&(t[r++]=i)}return r}},bv=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128||(c=(i&31)<<6|a&63,c<128)){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},xv=``,Sv=` `,Cv=class e{constructor(){this.fg=0,this.bg=0,this.extended=new wv}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},wv=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},Tv=class e extends Cv{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new wv,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?_v(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Ev=`di$target`,Dv=`di$dependencies`,Ov=new Map;function kv(e){return e[Dv]||[]}function Av(e){if(Ov.has(e))return Ov.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);jv(t,e,r)};return t._id=e,Ov.set(e,t),t}function jv(e,t,n){t[Ev]===t?t[Dv].push({id:e,index:n}):(t[Dv]=[{id:e,index:n}],t[Ev]=t)}var Mv=Av(`BufferService`),Nv=Av(`CoreMouseService`),Pv=Av(`CoreService`),Fv=Av(`CharsetService`),Iv=Av(`InstantiationService`),Lv=Av(`LogService`),Rv=Av(`OptionsService`),zv=Av(`OscLinkService`),Bv=Av(`UnicodeService`),Vv=Av(`DecorationService`),Hv=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new Tv,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(c!==-1||n.hasContent(t)){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId){if(c===-1){c=t,s=a.extended.urlId;continue}l=a.extended.urlId!==s}else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):Uv(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};Hv=av([X(0,Mv),X(1,Rv),X(2,zv)],Hv);function Uv(e,t){if(confirm(`Do you want to navigate to ${t}?
|
|
74
|
+
npx @evandu/super-pi`})})]}),(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`🎯 键盘快捷键`}),(0,B.jsxs)(`div`,{className:`help-command-table`,children:[(0,B.jsxs)(`div`,{className:`cmd-row`,children:[(0,B.jsx)(`code`,{children:`Enter`}),(0,B.jsx)(`span`,{children:`发送对话消息`})]}),(0,B.jsxs)(`div`,{className:`cmd-row`,children:[(0,B.jsx)(`code`,{children:`Shift + Enter`}),(0,B.jsx)(`span`,{children:`输入框内换行`})]}),(0,B.jsxs)(`div`,{className:`cmd-row`,children:[(0,B.jsx)(`code`,{children:`Esc`}),(0,B.jsx)(`span`,{children:`快速关闭当前顶层弹窗(使用指南、设置、工作区选择器等)`})]})]})]})]})}function u_(){return(0,B.jsx)(`div`,{className:`help-section-group`,children:(0,B.jsxs)(`div`,{className:`help-card`,children:[(0,B.jsx)(`h4`,{children:`🎨 4 款主题,来自 VSCode 流行主题`}),(0,B.jsxs)(`div`,{className:`help-theme-list`,children:[(0,B.jsxs)(`div`,{className:`help-theme-item`,children:[(0,B.jsx)(`strong`,{children:`🟣 Dracula`}),(0,B.jsx)(`p`,{children:`紫调暗色,饱满对比,适合夜间专注编程。`})]}),(0,B.jsxs)(`div`,{className:`help-theme-item`,children:[(0,B.jsx)(`strong`,{children:`🟠 Monokai`}),(0,B.jsx)(`p`,{children:`暖调暗色,橙红点缀,经典编辑器风格。`})]}),(0,B.jsxs)(`div`,{className:`help-theme-item`,children:[(0,B.jsx)(`strong`,{children:`🟡 Solarized Light`}),(0,B.jsx)(`p`,{children:`暖黄米色调,柔和护眼,适合长时间阅读。`})]}),(0,B.jsxs)(`div`,{className:`help-theme-item`,children:[(0,B.jsx)(`strong`,{children:`🔵 GitHub Light`}),(0,B.jsx)(`p`,{children:`冷调浅色,中性清晰,日常办公首选。`})]})]}),(0,B.jsxs)(`p`,{className:`help-hint`,children:[`可在左侧栏底部的 `,(0,B.jsx)(`strong`,{children:`⚙ 设置`}),` 中一键切换主题,设置会自动持久化保存在本地。`]})]})})}function d_({workspaceId:e,onClose:t}){let[n,r]=(0,z.useState)(),[i,a]=(0,z.useState)(``),[o,s]=(0,z.useState)(!1),[c,l]=(0,z.useState)(`memory`),[u,d]=(0,z.useState)(``),[f,p]=(0,z.useState)(),m=(0,z.useRef)(e);m.current=e;let h=(0,z.useRef)(0);async function g(t){if(!e)return;let n=++h.current;s(!0),a(``);try{let i=await fetch(`/api/memory?workspaceId=${encodeURIComponent(e)}`,{method:t?`POST`:`GET`,headers:{"Content-Type":`application/json`},...t?{body:JSON.stringify(t)}:{}}),a=await i.json();if(!i.ok)throw Error(a.error);return m.current!==e||n!==h.current?!1:(r(a),!0)}catch(t){return m.current===e&&n===h.current&&a(String(t)),!1}finally{m.current===e&&n===h.current&&s(!1)}}return(0,z.useEffect)(()=>{r(void 0),p(void 0),d(``),g()},[e]),e?(0,B.jsxs)(`section`,{"data-memory-panel":`1`,className:`settings-panel-container`,children:[(0,B.jsx)(`div`,{className:`settings-agents-header`,children:(0,B.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,B.jsx)(`strong`,{children:`长期知识与经验复盘。`}),` 用户档案跨工作区共享;工作区事实、技能和历史召回按当前工作区隔离。后台复盘不会静默删除旧记忆。`]})}),i&&(0,B.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,children:i}),n&&(0,B.jsxs)(`fieldset`,{disabled:o,className:`settings-memory-fieldset`,children:[(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`主动记忆机制配置`}),(0,B.jsxs)(`div`,{className:`settings-memory-switches`,children:[(0,B.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,B.jsx)(`input`,{type:`checkbox`,checked:n.settings.enabled,onChange:e=>void g({action:`configure`,settings:{...n.settings,enabled:e.target.checked}})}),`启用主动记忆`]}),(0,B.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,B.jsx)(`input`,{type:`checkbox`,checked:n.settings.writeApproval,onChange:e=>void g({action:`configure`,settings:{...n.settings,writeApproval:e.target.checked}})}),`Agent 写入均需审批`]})]}),(0,B.jsxs)(`div`,{className:`settings-memory-interval-row`,style:{marginTop:10},children:[(0,B.jsxs)(`label`,{className:`settings-memory-interval-label`,children:[`复盘间隔(用户回合,0 为关闭):`,(0,B.jsx)(`input`,{"aria-label":`复盘间隔`,type:`number`,min:`0`,className:`settings-dir-input settings-interval-input`,value:n.settings.reviewInterval,onChange:e=>r({...n,settings:{...n.settings,reviewInterval:Number(e.target.value)}})})]}),(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,onClick:()=>void g({action:`configure`,settings:n.settings}),children:`保存间隔`})]})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsxs)(`div`,{className:`settings-memory-category-header`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`记忆条目管理`}),(0,B.jsxs)(`select`,{"aria-label":`记忆类别`,className:`settings-memory-select`,value:c,onChange:e=>{l(e.target.value),p(void 0),d(``)},children:[(0,B.jsx)(`option`,{value:`user`,children:`用户档案(全局共享)`}),(0,B.jsx)(`option`,{value:`memory`,children:`工作区事实(当前工作区)`}),(0,B.jsx)(`option`,{value:`skills`,children:`技能与经验(当前工作区)`})]})]}),(n.entries[c]??[]).length===0?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`当前类别暂无条目。在下方输入内容即可添加。`}):(0,B.jsx)(`div`,{className:`settings-memory-entries-list`,children:(n.entries[c]??[]).map(e=>(0,B.jsxs)(`article`,{"data-memory-entry":e.id,className:`settings-memory-card`,children:[(0,B.jsx)(`pre`,{className:`settings-memory-content`,children:e.content}),(0,B.jsxs)(`div`,{className:`settings-memory-card-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-rule-edit-btn`,onClick:()=>{p(e.id),d(e.content)},children:`编辑`}),(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,onClick:()=>void g({action:`write`,operation:{target:c,action:`remove`,id:e.id}}),children:`删除`})]})]},e.id))}),(0,B.jsxs)(`div`,{className:`settings-memory-editor`,style:{marginTop:12},children:[(0,B.jsx)(`h5`,{className:`settings-memory-editor-title`,children:f?`编辑条目`:`添加新条目`}),(0,B.jsx)(`textarea`,{"aria-label":`记忆内容`,className:`settings-memory-textarea`,placeholder:c===`skills`?`# 技能名称
|
|
75
|
+
已验证的步骤、命令和注意事项`:`输入长期有效的事实或偏好`,value:u,onChange:e=>d(e.target.value)}),(0,B.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!u.trim(),onClick:async()=>{await g({action:`write`,operation:{target:c,action:f?`replace`:`add`,id:f,content:u}})&&(p(void 0),d(``))},children:[`保存`,f?`修改`:`新条目`]}),f&&(0,B.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,onClick:()=>{p(void 0),d(``)},children:`取消编辑`})]})]})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsxs)(`h4`,{className:`settings-section-title`,children:[`待审批提案(共 `,n.pending.length,` 个)`]}),n.pending.length===0?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`暂无待审批提案。`}):(0,B.jsx)(`div`,{className:`settings-dirs-list`,children:n.pending.map(e=>(0,B.jsxs)(`article`,{"data-memory-proposal":e.id,className:`settings-proposal-card`,children:[(0,B.jsxs)(`div`,{className:`settings-proposal-header`,children:[(0,B.jsx)(`span`,{className:`settings-proposal-badge`,children:e.operation.target}),(0,B.jsx)(`span`,{className:`settings-proposal-action`,children:e.operation.action})]}),e.previous&&(0,B.jsxs)(`pre`,{className:`settings-proposal-diff old`,children:[`原内容:`,e.previous]}),(0,B.jsx)(`pre`,{className:`settings-proposal-diff new`,children:e.operation.content}),(0,B.jsxs)(`div`,{className:`settings-proposal-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-rule-edit-btn`,onClick:()=>void g({action:`approve`,proposalId:e.id}),children:`批准`}),(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,onClick:()=>void g({action:`discard`,proposalId:e.id}),children:`拒绝`})]})]},e.id))})]})]}),t&&(0,B.jsx)(`div`,{className:`picker-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:t,children:`完成`})})]}):(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`请先在主界面选择工作区以管理其专属记忆与技能。`})}function f_({workspaceId:e,onClose:t,onPick:n}){let[r,i]=(0,z.useState)(),[a,o]=(0,z.useState)(!1),[s,c]=(0,z.useState)(``),[l,u]=(0,z.useState)(``),[d,f]=(0,z.useState)(),p=(0,z.useRef)(0);async function m(t){let n=++p.current;o(!0),c(``);try{let r=await fetch(`/api/files?workspaceId=${encodeURIComponent(e)}${t?`&path=${encodeURIComponent(t)}`:``}`),a=await r.json();if(!r.ok)throw Error(a.error??`HTTP ${r.status}`);if(n!==p.current)return;i(a),f(void 0)}catch(e){n===p.current&&c(String(e instanceof Error?e.message:e))}finally{n===p.current&&o(!1)}}(0,z.useEffect)(()=>{m()},[e]),(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.isComposing&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]);let h=l.trim().toLocaleLowerCase(),g=(0,z.useMemo)(()=>(r?.entries??[]).filter(e=>e.kind===`directory`||e.kind===`file`&&e.text&&!e.outside),[r]),_=h?g.filter(e=>e.name.toLocaleLowerCase().includes(h)):g;return(0,B.jsx)(`div`,{className:`overlay`,onClick:t,children:(0,B.jsxs)(`div`,{className:`picker knowledge-picker`,"data-knowledge-picker":`1`,onClick:e=>e.stopPropagation(),role:`dialog`,"aria-modal":`true`,"aria-label":`选择要导入的文档`,children:[(0,B.jsx)(`h2`,{children:`选择要导入的文档`}),(0,B.jsxs)(`div`,{className:`picker-path-bar`,children:[(0,B.jsx)(`input`,{"aria-label":`按文件名过滤`,className:`picker-path-input`,placeholder:`按文件名过滤…`,value:l,onChange:e=>u(e.target.value)}),(0,B.jsx)(`button`,{type:`button`,className:`picker-up-btn`,disabled:!r||r.parent===null||a,onClick:()=>void m(r?.parent??void 0),"aria-label":`上一级`,children:`↑`})]}),(0,B.jsx)(`div`,{className:`picker-status`,"data-knowledge-picker-path":r?.path??``,children:r?r.path||`工作区根目录`:`读取中…`}),s&&(0,B.jsx)(`div`,{className:`picker-error`,role:`alert`,children:s}),(0,B.jsx)(`div`,{className:`picker-list`,"data-knowledge-picker-list":_.length,children:_.length===0?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:h?`没有匹配的文件。`:`这个目录里没有可导入的文本文件。`}):_.map(e=>e.kind===`directory`?(0,B.jsxs)(`button`,{type:`button`,className:`picker-dir`,"data-knowledge-picker-dir":e.path,onClick:()=>void m(e.path),children:[`📁 `,e.name]},e.path):(0,B.jsxs)(`button`,{type:`button`,className:`picker-dir`,"data-knowledge-picker-file":e.path,"aria-pressed":d===e.path,onClick:()=>f(e.path),onDoubleClick:()=>n(e.path),children:[`📄 `,e.name]},e.path))}),(0,B.jsxs)(`div`,{className:`picker-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:t,children:`取消`}),(0,B.jsx)(`button`,{type:`button`,className:`picker-ok`,disabled:!d,"data-knowledge-picker-ok":d??``,onClick:()=>{d&&n(d)},children:`导入这个文档`})]})]})})}function p_({workspaceId:e,onClose:t}){let[n,r]=(0,z.useState)(),[i,a]=(0,z.useState)(``),[o,s]=(0,z.useState)(!1),[c,l]=(0,z.useState)(``),[u,d]=(0,z.useState)(``),[f,p]=(0,z.useState)(``),[m,h]=(0,z.useState)(``),[g,_]=(0,z.useState)(!1),v=(0,z.useRef)(e);v.current=e;let y=(0,z.useRef)(0);async function b(t){if(!e)return;let n=++y.current;s(!0),a(``);try{let i=await fetch(`/api/knowledge?workspaceId=${encodeURIComponent(e)}`,{method:t?`POST`:`GET`,headers:{"Content-Type":`application/json`},...t?{body:JSON.stringify(t)}:{}}),a=await i.json();if(!i.ok)throw Error(a.error);return v.current!==e||n!==y.current?!1:(r(a),!0)}catch(t){return v.current===e&&n===y.current&&a(String(t)),!1}finally{v.current===e&&n===y.current&&s(!1)}}if((0,z.useEffect)(()=>{r(void 0),l(``),d(``),p(``),h(``),b()},[e]),!e)return(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`请先在主界面选择工作区以管理它的知识库。`});let x=n?.documents??[],S=x.reduce((e,t)=>e+t.characters,0),C=n?.semantic,w=C?C.enabled?C.error?`不可用:${C.error};已退回关键词检索`:C.ready?`已就绪,已索引 ${C.indexed} 个片段`:C.bundled===!1?`随包分发的模型缺失;已退回关键词检索`:`首次检索时加载本地模型,之后一直可用`:`已关闭(SUPER_PI_KNOWLEDGE_EMBEDDINGS=0)`:`未启用`;return(0,B.jsxs)(`section`,{"data-knowledge-panel":`1`,className:`settings-panel-container`,children:[(0,B.jsx)(`div`,{className:`settings-agents-header`,children:(0,B.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,B.jsx)(`strong`,{children:`项目自己的文档。`}),` 浏览工作区里的规范、设计稿、会议纪要导入进来,Agent 就能在回答前检索原文,而不是凭记忆编造。文档按当前工作区隔离,检索结果只回传片段而不回传全文。关键词检索始终可用;语义检索能在用词不同的情况下找到片段,但代价是首次使用要下载一个本地模型。`]})}),(0,B.jsxs)(`div`,{className:`settings-dir-info`,"data-knowledge-semantic":C?C.error?`unavailable`:C.ready?`ready`:`loading`:`off`,children:[`语义检索:`,w]}),i&&(0,B.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,children:i}),n&&(0,B.jsxs)(`fieldset`,{disabled:o,className:`settings-memory-fieldset`,children:[(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsxs)(`h4`,{className:`settings-section-title`,children:[`从工作区文件导入(`,x.length,` 篇,共 `,S,` 字符)`]}),(0,B.jsxs)(`div`,{className:`settings-add-dir-form`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-knowledge-browse":`1`,onClick:()=>_(!0),children:`浏览工作区文件…`}),(0,B.jsx)(`span`,{className:`settings-dir-info`,children:`在工作区里挑选一个 Markdown 或文本文件`})]}),(0,B.jsxs)(`div`,{className:`settings-add-dir-form`,style:{marginTop:8},children:[(0,B.jsx)(`input`,{"aria-label":`文档路径`,className:`settings-dir-input`,placeholder:`或直接填写相对路径,例如 docs/design.md`,value:c,onChange:e=>l(e.target.value)}),(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!c.trim(),onClick:async()=>{await b({action:`add`,path:c})&&l(``)},children:`导入`})]}),(0,B.jsxs)(`div`,{className:`settings-memory-editor`,style:{marginTop:12},children:[(0,B.jsx)(`h5`,{className:`settings-memory-editor-title`,children:`或者直接粘贴正文`}),(0,B.jsx)(`input`,{"aria-label":`文档标题`,className:`settings-dir-input`,placeholder:`标题(留空则取正文首行)`,value:u,onChange:e=>d(e.target.value)}),(0,B.jsx)(`textarea`,{"aria-label":`文档正文`,className:`settings-memory-textarea`,placeholder:`以 # 开头的标题会成为检索结果里的段落归属`,value:f,onChange:e=>p(e.target.value)}),(0,B.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!f.trim(),onClick:async()=>{await b({action:`add`,title:u,text:f})&&(d(``),p(``))},children:`保存文档`}),(0,B.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,onClick:()=>{d(``),p(``)},children:`清空`})]})]})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`已导入文档`}),x.length===0?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`还没有文档。导入后,下一条消息起 Agent 就能检索到它们。`}):(0,B.jsx)(`div`,{className:`settings-dirs-list`,children:x.map(e=>(0,B.jsxs)(`article`,{"data-knowledge-document":e.id,className:`settings-memory-card`,children:[(0,B.jsxs)(`div`,{className:`settings-dir-row`,children:[(0,B.jsx)(`span`,{className:`settings-dir-tag`,children:e.format||`txt`}),(0,B.jsx)(`span`,{className:`settings-dir-path`,children:e.title}),(0,B.jsxs)(`span`,{className:`settings-dir-count`,children:[e.characters,` 字符`]})]}),(0,B.jsx)(`div`,{className:`settings-dir-info`,children:e.source}),(0,B.jsx)(`div`,{className:`settings-memory-card-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,onClick:()=>void b({action:`remove`,documentId:e.id}),children:`删除`})})]},e.id))})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`试检索`}),(0,B.jsxs)(`div`,{className:`settings-add-dir-form`,children:[(0,B.jsx)(`input`,{"aria-label":`检索词`,className:`settings-dir-input`,placeholder:`用和提问时相同的措辞试试`,value:m,onChange:e=>h(e.target.value),onKeyDown:e=>{e.key===`Enter`&&m.trim()&&b({action:`search`,query:m})}}),(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,disabled:!m.trim(),onClick:()=>void b({action:`search`,query:m}),children:`检索`})]}),m.trim()&&(n?.hits?.length===0?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`没有命中。知识库确实没有这段内容——Agent 也会得到同样的空结果。`}):(0,B.jsx)(`div`,{className:`settings-memory-entries-list`,children:(n?.hits??[]).map(e=>(0,B.jsxs)(`article`,{"data-knowledge-hit":`${e.documentId}#${e.chunk}`,className:`settings-memory-card`,children:[(0,B.jsxs)(`div`,{className:`settings-dir-row`,children:[(0,B.jsx)(`span`,{className:`settings-dir-tag`,children:e.title}),(0,B.jsxs)(`span`,{className:`settings-dir-count`,children:[`score `,e.score]})]}),e.heading&&(0,B.jsx)(`div`,{className:`settings-dir-info`,children:e.heading}),(0,B.jsx)(`pre`,{className:`settings-memory-content`,children:e.text})]},`${e.documentId}#${e.chunk}`))}))]})]}),t&&(0,B.jsx)(`div`,{className:`picker-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:t,children:`完成`})}),g&&(0,B.jsx)(f_,{workspaceId:e,onClose:()=>_(!1),onPick:async e=>{_(!1),await b({action:`add`,path:e})&&l(``)}})]})}var m_=[{kind:`calculator`,name:`计算器`,glyph:`∑`,blurb:`算术表达式,四则运算与乘方。除零会明确报错。`},{kind:`timestamp`,name:`时间戳`,glyph:`◷`,blurb:`Unix 时间戳与日期互转,本地计算,不联网。`}],h_=[{id:`preset_calculator`,kind:`calculator`,name:`计算器`,glyph:`∑`}],g_=40,__=2048,v_=`super-pi:tools:v1`;function y_(e){return typeof e==`string`?e.replace(/\s+/g,` `).trim().slice(0,g_):``}function b_(e){let t=e.trim();if(!t)return{ok:!1,reason:`请填写网址。`};if(t.length>__)return{ok:!1,reason:`网址太长了,请控制在 ${__} 个字符以内。`};let n=op(t);return n?{ok:!0,url:n}:{ok:!1,reason:`这个网址不是允许的协议。只支持 http / https / mailto 开头的网址。`}}function x_(e){if(!e)return[];let t;try{t=JSON.parse(e)}catch{return[]}if(!Array.isArray(t))return[];let n=[],r=new Set;for(let e of t){if(n.length>=32)break;if(typeof e!=`object`||!e)continue;let t=e,i=t.kind;if(typeof i!=`string`||i!==`calculator`&&i!==`timestamp`&&i!==`link`)continue;let a=y_(t.name);if(!a)continue;let o=typeof t.glyph==`string`&&t.glyph.trim()?t.glyph.trim().slice(0,4):``;if(!o)continue;let s=typeof t.id==`string`&&t.id.trim()?t.id.trim().slice(0,64):``;if(s&&!r.has(s)){if(i===`link`){let e=op(typeof t.url==`string`?t.url:``);if(!e)continue;r.add(s),n.push({id:s,kind:`link`,name:a,glyph:o,url:e})}else r.add(s),n.push({id:s,kind:i,name:a,glyph:o})}}return n}function S_(e){return JSON.stringify(e.map(e=>e.kind===`link`?{...e}:{id:e.id,kind:e.kind,name:e.name,glyph:e.glyph}))}function C_(){let e=typeof globalThis<`u`?globalThis.crypto:void 0;return typeof e?.randomUUID==`function`?e.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}function w_(e,t){let n=e===`link`?`link`:`preset_${e}`,r=C_().replace(/-/g,``).slice(0,8),i=`${n}_${r}`,a=1;for(;t.includes(i);)i=`${n}_${r}_${a}`,a+=1;return i}function T_(e,t){if(e.some(e=>e.kind===t))return e.slice();let n=m_.find(e=>e.kind===t);return n?[...e,{id:w_(t,e.map(e=>e.id)),kind:t,name:n.name,glyph:n.glyph}]:e.slice()}function E_(e,t){return e.filter(e=>e.id!==t)}var D_=e=>({ok:!1,reason:e}),O_=`除数不能为 0:除以零没有结果,请换一个非零的除数。`,k_=new Set([`/`,`%`]),A_=e=>e!==void 0&&e>=`0`&&e<=`9`,j_=e=>e!==void 0&&/\s/.test(e);function M_(e){for(;j_(e.source[e.at]);)e.at+=1}function N_(e){let t=e.at,n=0;for(;A_(e.source[e.at]);)e.at+=1,n+=1;if(e.source[e.at]===`.`)for(e.at+=1;A_(e.source[e.at]);)e.at+=1,n+=1;if(!n)return e.at=t,D_(`「${e.source[t]}」不是有效的数字。`);let r=Number(e.source.slice(t,e.at));return Number.isFinite(r)?{ok:!0,value:r}:D_(`数字太长了,无法表示。`)}function P_(e){M_(e);let t=e.source[e.at];if(t===void 0)return D_(`算式不完整:末尾还缺一个数字或右括号。`);if(t===`(`){e.at+=1;let t=R_(e);return t.ok?(M_(e),e.source[e.at]===`)`?(e.at+=1,t):D_(`括号不匹配:少了一个右括号「)」。`)):t}return A_(t)||t===`.`?N_(e):D_(`无法识别的字符「${t}」。`)}function F_(e){let t=P_(e);if(!t.ok||(M_(e),e.source[e.at]!==`^`))return t;e.at+=1;let n=I_(e);if(!n.ok)return n;let r=t.value**n.value;return Number.isFinite(r)?{ok:!0,value:r}:D_(`结果超出了可计算的数值范围。`)}function I_(e){M_(e);let t=e.source[e.at];if(t!==`+`&&t!==`-`)return F_(e);e.at+=1;let n=I_(e);if(!n.ok)return n;let r=t===`-`?-n.value:n.value;return Number.isFinite(r)?{ok:!0,value:r}:D_(`结果超出了可计算的数值范围。`)}function L_(e){let t=I_(e);if(!t.ok)return t;for(;;){M_(e);let n=e.source[e.at];if(n!==`*`&&!k_.has(n))return t;e.at+=1;let r=I_(e);if(!r.ok)return r;if(k_.has(n)&&r.value===0)return D_(O_);let i=n===`*`?t.value*r.value:n===`%`?t.value%r.value:t.value/r.value;if(!Number.isFinite(i))return D_(`结果超出了可计算的数值范围。`);t={ok:!0,value:i}}}function R_(e){let t=L_(e);if(!t.ok)return t;for(;;){M_(e);let n=e.source[e.at];if(n!==`+`&&n!==`-`)return t;e.at+=1;let r=L_(e);if(!r.ok)return r;let i=n===`+`?t.value+r.value:t.value-r.value;if(!Number.isFinite(i))return D_(`结果超出了可计算的数值范围。`);t={ok:!0,value:i}}}function z_(e){let t=e.trim();if(!t)return D_(`请输入算式。`);if(t.length>200)return D_(`算式太长了,请控制在 200 个字符以内。`);let n={source:t,at:0},r=R_(n);return r.ok?(M_(n),n.at===t.length?Number.isFinite(r.value)?r:D_(`结果不是有限数字。`):D_(`「${t[n.at]}」后面的内容无法识别,请检查是否漏了运算符。`)):r}function B_(e){return String(!Number.isFinite(e)||Number.isInteger(e)&&Math.abs(e)<1e21?e:Number(e.toPrecision(12)))}function V_(e){let t=e.trim();if(!t)return{ok:!1,reason:`请输入时间戳或日期。`};if(/^-?\d+$/.test(t)){let e=Number(t);if(!Number.isFinite(e))return{ok:!1,reason:`这个数字太大,无法表示。`};let n=t.replace(`-`,``).length<=11?e*1e3:e;return!Number.isFinite(n)||Math.abs(n)>864e13?{ok:!1,reason:`这个时间戳超出了日期能表示的范围。`}:{ok:!0,ms:n}}let n=Date.parse(t);return Number.isNaN(n)?{ok:!1,reason:`看不懂这个日期。试试 1757000000、2026-10-08 或 2026-10-08T09:00:00。`}:{ok:!0,ms:n}}var H_=e=>String(Math.abs(e)).padStart(2,`0`);function U_(e){let t=new Date(e);return Number.isNaN(t.getTime())?null:{local:`${t.getFullYear()}-${H_(t.getMonth()+1)}-${H_(t.getDate())} ${H_(t.getHours())}:${H_(t.getMinutes())}:${H_(t.getSeconds())}`,iso:t.toISOString(),seconds:String(Math.floor(e/1e3)),milliseconds:String(e)}}var W_=e=>e.nativeEvent.isComposing||e.keyCode===229,G_=`super-pi.theme`,K_=[{id:`dracula`,name:`Dracula`,blurb:`紫调暗色,饱满对比,适合夜间专注。`},{id:`monokai`,name:`Monokai`,blurb:`暖调暗色,橙红点缀,经典编辑器风格。`},{id:`solarized-light`,name:`Solarized Light`,blurb:`暖黄米色调,柔和护眼,适合长时间阅读。`},{id:`github-light`,name:`GitHub Light`,blurb:`冷调浅色,中性清晰,日常办公首选。`}],q_=`dracula`,J_=e=>typeof e==`string`&&K_.some(t=>t.id===e);function Y_(){try{let e=window.localStorage.getItem(G_);if(!e)return q_;let t=JSON.parse(e),n=typeof t==`string`?t:t?.id;return J_(n)?n:q_}catch{return q_}}function X_(e){document.documentElement.setAttribute(`data-theme`,e);try{window.localStorage.setItem(G_,JSON.stringify({id:e,version:1}))}catch{}}function Z_(){let[e,t]=(0,z.useState)(q_);return(0,z.useEffect)(()=>{t(Y_());let e=e=>{if(e.key===`super-pi.theme`&&e.newValue)try{let n=JSON.parse(e.newValue),r=typeof n==`string`?n:n?.id;J_(r)&&(document.documentElement.setAttribute(`data-theme`,r),t(r))}catch{}};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),{theme:e,setTheme:(0,z.useCallback)(e=>{X_(e),t(e)},[])}}function Q_({theme:e,onChooseTheme:t,onClose:n}){let r=K_.find(t=>t.id===e);return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`div`,{className:`settings-scope`,children:`主题只影响这台设备的显示,不改变任何内容;切换立即生效。`}),K_.length===0?(0,B.jsx)(`div`,{className:`theme-empty`,"data-theme-empty":`1`,children:`没有可用的主题。界面将继续使用默认配色,你可以在主题文件恢复后重试。`}):(0,B.jsx)(`div`,{className:`theme-options`,role:`radiogroup`,"aria-label":`主题`,children:K_.map(n=>{let r=n.id===e;return(0,B.jsxs)(`button`,{type:`button`,className:`theme-option`,role:`radio`,"aria-checked":r,"aria-pressed":r,"data-theme-option":n.id,"data-theme-current":r?`1`:`0`,onClick:()=>t(n.id),children:[(0,B.jsx)(`span`,{className:`theme-preview-strip`,"data-preview":n.id,"aria-hidden":`true`}),(0,B.jsxs)(`span`,{className:`theme-option-name`,children:[n.name,r&&(0,B.jsx)(`span`,{className:`theme-option-current`,children:`当前 ✓`})]}),(0,B.jsx)(`span`,{className:`theme-option-blurb`,children:n.blurb})]},n.id)})}),(0,B.jsx)(`div`,{className:`picker-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,"data-theme-close":`1`,onClick:n,children:`完成`})}),(0,B.jsxs)(`div`,{className:`settings-scope theme-current-line`,children:[`当前:`,r?`${r.name}(${r.id})`:`默认`]})]})}function $_({userNickname:e,onSetUserNickname:t,onClose:n}){return(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`div`,{className:`settings-scope`,children:`昵称会显示在消息时间戳旁和头像上,替代默认的「你」。留空恢复默认。`}),(0,B.jsxs)(`div`,{className:`general-nickname`,children:[(0,B.jsx)(`label`,{className:`general-nickname-label`,htmlFor:`general-nickname-input`,children:`昵称`}),(0,B.jsx)(`input`,{id:`general-nickname-input`,type:`text`,className:`general-nickname-input`,"data-general-nickname":`1`,maxLength:24,placeholder:`你`,value:e??``,onChange:e=>t?.(e.target.value)}),(0,B.jsx)(`span`,{className:`general-nickname-hint`,"data-general-nickname-preview":`1`,title:`当前显示`,children:e?.trim()?`将显示为:${e.trim()}`:`将显示为:你`})]}),(0,B.jsx)(`div`,{className:`picker-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:n,children:`完成`})})]})}function ev({context:e}){let[t,n]=(0,z.useState)(``),[r,i]=(0,z.useState)(``),[a,o]=(0,z.useState)(!1),s=e.agentCatalog,c=e.subagentCatalog,l=s?.agents??[],u=c?.agents??[],d=[...l,...u],f=[...s?.problems??[],...c?.problems??[]],p=[...new Set([...s?.directories??(s?.directory?[s.directory]:[]),...e.customAgentDirs??[]])],m=e.customAgentDirs??[],h=r=>{if(r.preventDefault(),e.pendingSettings)return;let a=t.trim();a&&(m.includes(a)?i(`该路径已存在于自定义目录列表中`):(e.onSetCustomAgentDirs?.([...m,a]),n(``),i(``)))},g=t=>{let n=m.filter(e=>e!==t);e.onSetCustomAgentDirs?.(n)};return(0,B.jsxs)(`div`,{className:`settings-agents-container`,children:[(0,B.jsxs)(`div`,{className:`settings-agents-header`,children:[(0,B.jsx)(`p`,{className:`settings-agents-desc`,children:`Super Pi 支持多目录发现智能体。系统会按优先级自上而下合并扫描目录;若存在同名配置,高优先级目录的文件将覆盖低优先级目录。`}),(0,B.jsx)(`button`,{type:`button`,className:`settings-agent-rescan-btn`,onClick:()=>{o(!0),e.onRescanAgents?.(),setTimeout(()=>o(!1),600)},disabled:a,title:`重新扫描所有目录中的智能体定义文件`,children:a?`正在扫描…`:`🔄 立即重新扫描`})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`发现路径清单(按优先级自高到低)`}),(0,B.jsx)(`div`,{className:`settings-dirs-list`,children:p.length===0?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`暂无活跃的发现路径`}):p.map((t,n)=>{let r=m.includes(t),i=t.includes(`.super_pi`)||t.includes(`.super-pi`)||t.includes(`.pi`),a=!r&&!i,o=d.filter(e=>e.sourceDir===t).length;return(0,B.jsxs)(`div`,{className:`settings-dir-row`,children:[(0,B.jsxs)(`div`,{className:`settings-dir-info`,children:[(0,B.jsxs)(`span`,{className:`settings-dir-priority`,children:[`#`,n+1]}),(0,B.jsx)(`span`,{className:`settings-dir-path`,title:t,children:t}),(0,B.jsx)(`span`,{className:`settings-dir-tag`,children:r?`自定义`:i?`用户全局`:a?`内置`:`环境`}),(0,B.jsxs)(`span`,{className:`settings-dir-count`,children:[`(发现 `,o,` 个智能体)`]})]}),r&&(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,disabled:e.pendingSettings,onClick:()=>g(t),title:`移除此自定义扫描路径`,children:`移除`})]},t)})})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`添加自定义路径`}),(0,B.jsxs)(`form`,{onSubmit:h,className:`settings-add-dir-form`,children:[(0,B.jsx)(`input`,{type:`text`,className:`settings-dir-input`,value:t,onChange:e=>{n(e.target.value),r&&i(``)},onKeyDown:e=>{e.key===`Enter`&&W_(e)&&e.preventDefault()},placeholder:`输入本地目录绝对路径或 ~/ 开头路径,如 D:\\agents 或 ~/.super_pi/agents`}),(0,B.jsx)(`button`,{type:`submit`,className:`settings-dir-add-btn`,disabled:e.pendingSettings||!t.trim(),children:`添加目录`})]}),r&&(0,B.jsx)(`div`,{className:`settings-dir-error`,children:r})]}),f.length>0&&(0,B.jsxs)(`section`,{className:`settings-section settings-problems-section`,children:[(0,B.jsxs)(`h4`,{className:`settings-problems-title`,children:[`⚠️ 发现 `,f.length,` 个文件解析问题`]}),(0,B.jsx)(`div`,{className:`settings-problems-list`,children:f.map((e,t)=>(0,B.jsxs)(`div`,{className:`settings-problem-row`,children:[(0,B.jsx)(`span`,{className:`settings-problem-file`,children:e.file}),`: `,e.message]},t))})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsxs)(`h4`,{className:`settings-section-title`,children:[`已发现的智能体(共 `,d.length,` 个)`]}),d.length===0?(0,B.jsxs)(`div`,{className:`settings-empty-hint`,children:[`当前未发现任何智能体。请在上述目录中添加 `,(0,B.jsx)(`code`,{children:`.md`}),` 文件(需包含 YAML frontmatter)。`]}):(0,B.jsx)(`div`,{className:`settings-agent-grid`,children:d.map(e=>(0,B.jsxs)(`div`,{className:`settings-agent-card`,children:[(0,B.jsxs)(`div`,{className:`settings-agent-card-header`,children:[(0,B.jsx)(`span`,{className:`settings-agent-name`,children:e.name}),(0,B.jsxs)(`span`,{className:`settings-agent-id`,children:[`(`,e.id,`)`]}),(0,B.jsx)(`span`,{className:`settings-agent-mode-badge ${e.mode}`,children:e.mode===`primary`?`主智能体`:`子智能体`})]}),e.sourceDir&&(0,B.jsxs)(`div`,{className:`settings-agent-source`,title:e.sourceDir,children:[`来源:`,e.sourceDir]}),e.description&&(0,B.jsx)(`div`,{className:`settings-agent-desc`,children:e.description}),(0,B.jsxs)(`div`,{className:`settings-agent-footer`,children:[(0,B.jsx)(`span`,{className:`settings-agent-tools`,children:e.toolSummary}),e.model&&(0,B.jsxs)(`span`,{className:`settings-agent-model`,children:[e.model.provider,`/`,e.model.modelId]})]})]},`${e.sourceDir}-${e.id}`))})]}),(0,B.jsx)(`div`,{className:`picker-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}function tv(e){return(0,B.jsx)(ev,{context:e})}function nv({context:e}){let[t,n]=(0,z.useState)(``),[r,i]=(0,z.useState)(``),[a,o]=(0,z.useState)(),s=e=>{try{return new RegExp(e,`i`),!1}catch{return!0}},c=s(t),l=s(r),u=e.modelFilterRules??[];return(0,B.jsxs)(`section`,{"data-model-rules":`1`,className:`settings-panel-container`,children:[(0,B.jsx)(`div`,{className:`settings-agents-header`,children:(0,B.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,B.jsx)(`strong`,{children:`按工作区约束可用模型。`}),`当工作区名称匹配指定正则表达式时,会话中仅可选择符合模型正则的模型(匹配模型名称或 `,(0,B.jsx)(`code`,{children:`provider/modelId`}),`)。多条命中规则必须全部满足。`]})}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsxs)(`h4`,{className:`settings-section-title`,children:[`已配置的过滤规则(共 `,u.length,` 条)`]}),u.length===0?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`暂无模型过滤规则。所有工作区默认可使用全部已配置模型。`}):(0,B.jsx)(`div`,{className:`settings-dirs-list`,children:u.map(t=>{let r=a===t.id;return(0,B.jsxs)(`div`,{className:`settings-rule-card ${r?`editing`:``}`,children:[(0,B.jsx)(`div`,{className:`settings-rule-info`,children:(0,B.jsxs)(`div`,{className:`settings-rule-patterns`,children:[(0,B.jsxs)(`span`,{className:`settings-rule-pill`,children:[(0,B.jsx)(`span`,{className:`settings-rule-pill-tag`,children:`工作区`}),(0,B.jsx)(`code`,{className:`settings-rule-code`,title:t.workspacePattern,children:t.workspacePattern})]}),(0,B.jsx)(`span`,{className:`settings-rule-arrow`,"aria-hidden":`true`,children:`→`}),(0,B.jsxs)(`span`,{className:`settings-rule-pill`,children:[(0,B.jsx)(`span`,{className:`settings-rule-pill-tag`,children:`允许模型`}),(0,B.jsx)(`code`,{className:`settings-rule-code`,title:t.modelPattern,children:t.modelPattern})]})]})}),(0,B.jsxs)(`div`,{className:`settings-rule-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-rule-edit-btn`,onClick:()=>{o(t.id),n(t.workspacePattern),i(t.modelPattern)},children:r?`编辑中`:`编辑`}),(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-remove-btn`,onClick:()=>{a===t.id&&(o(void 0),n(``),i(``)),e.onSetModelRules?.(u.filter(e=>e.id!==t.id))},children:`删除`})]})]},t.id)})})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:a?`编辑过滤规则`:`添加新规则`}),(0,B.jsxs)(`fieldset`,{disabled:e.pendingSettings,className:`model-rules-fields settings-rule-fieldset`,children:[(0,B.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`工作区名正则表达式`}),(0,B.jsx)(`input`,{type:`text`,"data-rule-workspace":`1`,className:`settings-dir-input`,value:t,"aria-invalid":c,placeholder:`如 ^proj- 或 my-workspace`,onChange:e=>n(e.target.value)})]}),(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`允许的模型名正则表达式`}),(0,B.jsx)(`input`,{type:`text`,"data-rule-model":`1`,className:`settings-dir-input`,value:r,"aria-invalid":l,placeholder:`如 anthropic/.* 或 gpt-4o|claude`,onChange:e=>i(e.target.value)})]})]}),(c||l)&&(0,B.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,children:`⚠️ 正则表达式语法不合法,请检查后修正。`}),(0,B.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,B.jsx)(`button`,{type:`button`,"data-rule-save":`1`,className:`settings-dir-add-btn`,disabled:!t.trim()||!r.trim()||c||l,onClick:()=>{let s={id:a??C_(),workspacePattern:t.trim(),modelPattern:r.trim()};e.onSetModelRules?.([...u.filter(e=>e.id!==s.id),s]),n(``),i(``),o(void 0)},children:a?`保存修改`:`添加规则`}),a&&(0,B.jsx)(`button`,{type:`button`,className:`settings-rule-cancel-btn`,onClick:()=>{o(void 0),n(``),i(``)},children:`取消编辑`})]})]})]}),(0,B.jsx)(`div`,{className:`picker-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}function rv({context:e}){let t=e.providers??[],n=e.providerApis??[],[r,i]=(0,z.useState)({kind:`add`}),[a,o]=(0,z.useState)(``),[s,c]=(0,z.useState)(``),[l,u]=(0,z.useState)(``),[d,f]=(0,z.useState)(``),[p,m]=(0,z.useState)(``),[h,g]=(0,z.useState)(!1),[_,v]=(0,z.useState)(``),[y,b]=(0,z.useState)(``),[x,S]=(0,z.useState)(!1),[C,w]=(0,z.useState)(!1),[T,E]=(0,z.useState)(``),[D,O]=(0,z.useState)(``),[k,A]=(0,z.useState)(!0),[ee,j]=(0,z.useState)(!0),M=r.kind===`add`?void 0:t.find(e=>e.id===r.providerId),N=(0,z.useRef)(!1),te=()=>{N.current=!0},ne=(0,z.useRef)(!1);(0,z.useEffect)(()=>{ne.current&&(ne.current=!1,!N.current&&re())},[t]);let re=()=>{i({kind:`add`}),N.current=!1,o(``),c(``),u(``),f(n[0]??`openai-completions`),m(``),g(!1),v(``),b(``),S(!1),w(!1),E(``),O(``),A(!0),j(!0)},ie=e=>{o(e.id),c(e.name===e.id?``:e.name),u(e.baseUrl),f(e.api),m(``),g(!1)},ae=e=>{v(e?.id??``),b(!e||e.name===e.id?``:e.name),S(e?.reasoning??!1),w(e?.imageInput??!1),E(e?String(e.contextWindow):``),O(e?String(e.maxTokens):``),A(!0),j(!0)},oe=e=>{let n=t.find(t=>t.id===e);n&&(te(),i({kind:`addModel`,providerId:e}),ie(n),ae(void 0))},se=(e,n)=>{let r=t.find(t=>t.id===e),a=r?.models.find(e=>e.id===n);r&&a&&(te(),i({kind:`editModel`,providerId:e,modelId:n}),ie(r),ae(a))},ce=a.trim()&&l.trim()&&d.trim()&&_.trim()&&!e.pendingSettings;return(0,B.jsxs)(`section`,{className:`settings-section`,"data-settings-providers":`1`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`自定义供应商与模型`}),(0,B.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,B.jsx)(`strong`,{children:`不用再手改 Pi 的模型配置文件。`}),`这里填的供应商会写进 Pi 自己的配置(`,(0,B.jsx)(`code`,{children:`models.json`}),` 放定义、`,(0,B.jsx)(`code`,{children:`auth.json`}),` 放 key), 所以 Super Pi 的会话、终端里的 `,(0,B.jsx)(`code`,{children:`pi`}),` 都能用上它。Pi 配置文件里你自己写的其它条目不会被动到。`]}),t.length>0&&(0,B.jsx)(`div`,{className:`settings-provider-list`,children:t.map(t=>(0,B.jsxs)(`div`,{className:`settings-provider-card`,"data-provider-row":t.id,children:[(0,B.jsxs)(`div`,{className:`settings-provider-head`,children:[(0,B.jsx)(`span`,{className:`settings-provider-id`,children:t.id}),t.name!==t.id&&(0,B.jsx)(`span`,{className:`settings-provider-name`,children:t.name}),t.hasKey&&(0,B.jsx)(`span`,{className:`settings-provider-badge`,children:`已设置 key`})]}),(0,B.jsxs)(`div`,{className:`settings-provider-meta`,children:[t.baseUrl,` · `,t.api]}),(0,B.jsx)(`div`,{className:`settings-provider-models`,children:t.models.map(n=>(0,B.jsxs)(`div`,{className:`settings-provider-model-row`,"data-model-row":`${t.id}:${n.id}`,children:[(0,B.jsx)(`span`,{className:`settings-provider-model`,children:n.name}),(0,B.jsx)(`code`,{className:`settings-provider-model-id`,children:n.id}),(0,B.jsxs)(`div`,{className:`settings-provider-model-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-provider-link`,"data-model-edit":`${t.id}:${n.id}`,onClick:()=>se(t.id,n.id),children:`编辑`}),(0,B.jsx)(`button`,{type:`button`,className:`settings-provider-link danger`,"data-model-delete":`${t.id}:${n.id}`,onClick:()=>e.onRemoveProviderModel?.(t.id,n.id),children:`删除`})]})]},n.id))}),(0,B.jsxs)(`div`,{className:`settings-provider-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-add-btn`,"data-provider-add-model":t.id,onClick:()=>oe(t.id),children:`添加模型`}),(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-provider-delete":t.id,onClick:()=>e.onRemoveProvider?.(t.id),children:`删除供应商`})]})]},t.id))}),(0,B.jsxs)(`h4`,{className:`settings-section-title`,children:[r.kind===`add`&&`添加供应商与模型`,r.kind===`addModel`&&`为供应商「${r.providerId}」添加模型`,r.kind===`editModel`&&`编辑模型「${r.modelId}」`]}),r.kind!==`add`&&(0,B.jsxs)(`p`,{className:`settings-agents-desc`,"data-provider-shared-note":`1`,children:[`上面这些是这个供应商下`,(0,B.jsx)(`b`,{children:`所有模型共用`}),`的(地址、API 类型、key)。改动会同时影响它下面的每个模型。`]}),(0,B.jsxs)(`div`,{className:`settings-provider-form`,onChange:te,children:[(0,B.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`供应商 id`}),(0,B.jsx)(`input`,{type:`text`,"data-provider-id":`1`,className:`settings-dir-input`,value:a,placeholder:`如 my-proxy`,readOnly:r.kind!==`add`,onChange:e=>o(e.target.value)})]}),(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`显示名称`}),(0,B.jsx)(`input`,{type:`text`,"data-provider-name":`1`,className:`settings-dir-input`,value:s,placeholder:`如 公司中转`,onChange:e=>c(e.target.value)})]})]}),(0,B.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`API 地址`}),(0,B.jsx)(`input`,{type:`text`,"data-provider-base-url":`1`,className:`settings-dir-input`,value:l,placeholder:`如 https://api.example.com/v1`,onChange:e=>u(e.target.value)})]}),(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`API 类型`}),(0,B.jsx)(`select`,{"data-provider-api":`1`,className:`settings-model-select`,value:d,onChange:e=>f(e.target.value),children:(n.length?n:[`openai-completions`]).map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))})]})]}),(0,B.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`API key`}),(0,B.jsx)(`input`,{type:`password`,"data-provider-api-key":`1`,className:`settings-dir-input`,value:p,autoComplete:`off`,placeholder:M?.hasKey?`已设置,留空表示不修改`:`如 sk-...`,onChange:e=>m(e.target.value)})]}),(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`模型 id`}),(0,B.jsx)(`input`,{type:`text`,"data-model-id":`1`,className:`settings-dir-input`,value:_,placeholder:`如 gpt-4o`,onChange:e=>v(e.target.value)})]})]}),(0,B.jsxs)(`div`,{className:`settings-rule-form-grid`,children:[(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`模型显示名`}),(0,B.jsx)(`input`,{type:`text`,"data-model-name":`1`,className:`settings-dir-input`,value:y,placeholder:`留空则用模型 id`,onChange:e=>b(e.target.value)})]}),(0,B.jsxs)(`label`,{className:`settings-rule-input-group`,children:[(0,B.jsx)(`span`,{className:`settings-rule-label-text`,children:`上下文窗口 / 最大输出`}),(0,B.jsxs)(`div`,{className:`settings-provider-numbers`,children:[(0,B.jsx)(`input`,{type:`number`,"data-model-context-window":`1`,className:`settings-dir-input`,value:T,placeholder:`128000`,onChange:e=>E(e.target.value)}),(0,B.jsx)(`input`,{type:`number`,"data-model-max-tokens":`1`,className:`settings-dir-input`,value:D,placeholder:`16384`,onChange:e=>O(e.target.value)})]})]})]}),(0,B.jsxs)(`div`,{className:`settings-provider-switches`,children:[(0,B.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,B.jsx)(`input`,{type:`checkbox`,"data-model-reasoning":`1`,checked:x,onChange:e=>S(e.target.checked)}),`推理模型`]}),(0,B.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,B.jsx)(`input`,{type:`checkbox`,"data-model-image-input":`1`,checked:C,onChange:e=>w(e.target.checked)}),`支持图片输入`]}),(0,B.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,B.jsx)(`input`,{type:`checkbox`,"data-model-developer-role":`1`,checked:k,onChange:e=>A(e.target.checked)}),`支持 developer 角色`]}),(0,B.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,B.jsx)(`input`,{type:`checkbox`,"data-model-reasoning-effort":`1`,checked:ee,onChange:e=>j(e.target.checked)}),`支持 reasoning_effort`]}),M?.hasKey&&(0,B.jsxs)(`label`,{className:`settings-checkbox-label`,children:[(0,B.jsx)(`input`,{type:`checkbox`,"data-provider-clear-key":`1`,checked:h,onChange:e=>g(e.target.checked)}),`清除已保存的 key`]})]}),(0,B.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,B.jsx)(`button`,{type:`button`,"data-provider-save":`1`,className:`settings-dir-add-btn`,disabled:!ce,onClick:()=>{ne.current=!0,N.current=!1,e.onSetProvider?.({id:a.trim(),...s.trim()?{name:s.trim()}:{},baseUrl:l.trim(),api:d.trim(),...p.trim()?{apiKey:p.trim()}:{},...h?{clearKey:!0}:{},models:[{id:_.trim(),...y.trim()?{name:y.trim()}:{},...x?{reasoning:!0}:{},...C?{imageInput:!0}:{},...T.trim()?{contextWindow:Number(T)}:{},...D.trim()?{maxTokens:Number(D)}:{},...k?{}:{supportsDeveloperRole:!1},...ee?{}:{supportsReasoningEffort:!1}}]})},children:r.kind===`add`?`添加`:r.kind===`addModel`?`添加模型`:`保存修改`}),r.kind!==`add`&&(0,B.jsx)(`button`,{type:`button`,className:`settings-dir-cancel-btn`,"data-provider-cancel":`1`,onClick:re,children:`取消`})]})]})]})}function iv({context:e}){let t=e.modelCatalog,n=e.defaultModel,r=t?.models??[],i=r.reduce((e,t)=>e.includes(t.provider)?e:[...e,t.provider],[]),a=n?`${n.provider}/${n.modelId}`:``,[o,s]=(0,z.useState)(n?.provider??``),[c,l]=(0,z.useState)(n?.modelId??``),u=(0,z.useRef)(void 0);(0,z.useEffect)(()=>{u.current!==a&&(u.current=a,s(n?.provider??``),l(n?.modelId??``))},[a,n]);let d=n&&!i.includes(n.provider)?[...i,n.provider]:i,f=d.includes(o)?o:d[0]??``,p=r.filter(e=>e.provider===f),m=n&&n.provider===f&&!p.some(e=>e.modelId===n.modelId)?[...p,{provider:n.provider,modelId:n.modelId,label:n.label}]:p,h=m.some(e=>e.modelId===c)?c:m[0]?.modelId??``,g=!n||r.some(e=>e.provider===n.provider&&e.modelId===n.modelId),_=f&&h?`${f}/${h}`:``,v=_!==a,y=!t,b=t?.source===`unavailable`,x=e=>{s(e);let t=r.filter(t=>t.provider===e);l(e=>t.some(t=>t.modelId===e)?e:t[0]?.modelId??``)};return(0,B.jsxs)(`section`,{"data-settings-model":`1`,className:`settings-panel-container`,children:[(0,B.jsx)(`div`,{className:`settings-agents-header`,children:(0,B.jsxs)(`p`,{className:`settings-agents-desc`,children:[(0,B.jsx)(`strong`,{children:`设置新建会话的默认模型。`}),`这里的选择对所有工作区生效,但优先级低于工作区自己的默认模型;两者都没有时,跟随 Pi 的默认模型。 默认值只在会话创建时复制一次,之后改这里不会改动已经存在的会话。`]})}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`当前默认模型`}),(0,B.jsx)(`div`,{className:`settings-model-current`,"data-model-current":`1`,children:n?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`span`,{className:`settings-model-current-name`,children:n.label}),(0,B.jsxs)(`code`,{className:`settings-model-current-pair`,children:[n.provider,`/`,n.modelId]})]}):(0,B.jsx)(`span`,{className:`settings-model-current-none`,children:`跟随 Pi 默认模型`})}),n&&!g&&(0,B.jsx)(`div`,{className:`settings-dir-error`,role:`alert`,children:`⚠️ Pi 当前不再提供这个模型,新会话会改用 Pi 的默认模型。`})]}),(0,B.jsxs)(`section`,{className:`settings-section`,children:[(0,B.jsx)(`h4`,{className:`settings-section-title`,children:`修改默认模型`}),y?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`正在读取 Pi 的模型列表…`}):b?(0,B.jsx)(`div`,{className:`settings-empty-hint`,children:`无法读取 Pi 的模型列表,暂时不能设置默认模型。`}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`settings-model-grid`,children:[(0,B.jsxs)(`label`,{className:`settings-model-group`,children:[(0,B.jsx)(`span`,{className:`settings-model-label`,children:`供应商`}),(0,B.jsx)(`select`,{"data-model-provider":`1`,className:`settings-model-select`,value:f,disabled:e.pendingSettings||d.length===0,onChange:e=>x(e.target.value),children:d.map(e=>(0,B.jsx)(`option`,{value:e,children:e},e))})]}),(0,B.jsxs)(`label`,{className:`settings-model-group`,children:[(0,B.jsx)(`span`,{className:`settings-model-label`,children:`模型`}),(0,B.jsx)(`select`,{"data-model-select":`1`,className:`settings-model-select`,value:h,disabled:e.pendingSettings||m.length===0,onChange:e=>l(e.target.value),children:m.map(e=>(0,B.jsx)(`option`,{value:e.modelId,children:e.label},e.modelId))})]})]}),(0,B.jsxs)(`div`,{className:`settings-rule-form-buttons`,children:[(0,B.jsx)(`button`,{type:`button`,"data-model-save":`1`,className:`settings-dir-add-btn`,disabled:!v||e.pendingSettings||!_,onClick:()=>{let t=r.find(e=>e.provider===f&&e.modelId===h);t&&e.onSetDefaultModel?.({provider:t.provider,modelId:t.modelId,label:t.label})},children:`保存默认模型`}),(0,B.jsx)(`button`,{type:`button`,"data-model-clear":`1`,className:`settings-dir-cancel-btn`,disabled:!n||e.pendingSettings,onClick:()=>e.onSetDefaultModel?.(null),children:`清除默认模型`})]})]})]}),(0,B.jsx)(rv,{context:e}),(0,B.jsx)(`div`,{className:`picker-actions`,children:(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e.onClose,children:`完成`})})]})}var av=[{id:`appearance`,label:`外观`,render:Q_},{id:`general`,label:`通用`,render:$_},{id:`memory`,label:`主动记忆`,render:e=>(0,B.jsx)(d_,{workspaceId:e.workspaceId,onClose:e.onClose})},{id:`knowledge`,label:`知识库`,render:e=>(0,B.jsx)(p_,{workspaceId:e.workspaceId,onClose:e.onClose})},{id:`agents`,label:`智能体`,render:tv},{id:`model`,label:`模型`,render:e=>(0,B.jsx)(iv,{context:e})},{id:`model-rules`,label:`模型过滤`,render:e=>(0,B.jsx)(nv,{context:e})}],ov=av[0]?.id;function sv({workspaceId:e,theme:t,onChooseTheme:n,onClose:r,agentCatalog:i,subagentCatalog:a,modelFilterRules:o,onSetModelRules:s,defaultModel:c,modelCatalog:l,onSetDefaultModel:u,providers:d,providerApis:f,onSetProvider:p,onRemoveProvider:m,onRemoveProviderModel:h,customAgentDirs:g,pendingSettings:_,onSetCustomAgentDirs:v,onRescanAgents:y,userNickname:b,onSetUserNickname:x}){let[S,C]=(0,z.useState)(ov);(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.defaultPrevented&&r()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r]);let w=av.find(e=>e.id===S)??av[0];return(0,B.jsx)(`div`,{className:`overlay`,onClick:r,children:(0,B.jsxs)(`div`,{className:`picker settings-window`,"data-theme-dialog":`1`,"data-settings-window":`1`,onClick:e=>e.stopPropagation(),children:[(0,B.jsx)(`div`,{className:`settings-window-head`,children:(0,B.jsx)(`h2`,{children:`设置`})}),(0,B.jsxs)(`div`,{className:`settings-window-body`,children:[(0,B.jsxs)(`nav`,{className:`settings-nav`,role:`tablist`,"aria-orientation":`vertical`,"aria-label":`设置分类`,"data-settings-nav":`1`,children:[(0,B.jsx)(`div`,{className:`settings-nav-label`,children:`分类`}),av.map(e=>(0,B.jsx)(`button`,{type:`button`,id:`settings-tab-${e.id}`,className:`settings-category`,role:`tab`,"aria-selected":e.id===w?.id,"aria-controls":`settings-panel`,tabIndex:e.id===w?.id?0:-1,"data-settings-category":e.id,onClick:()=>C(e.id),children:e.label},e.id))]}),w&&(0,B.jsxs)(`div`,{className:`settings-panel`,id:`settings-panel`,role:`tabpanel`,"aria-labelledby":`settings-tab-${w.id}`,"data-settings-panel":w.id,children:[(0,B.jsx)(`h3`,{className:`settings-panel-title`,"data-settings-panel-title":w.id,children:w.label}),w.render({workspaceId:e,theme:t,onChooseTheme:n,onClose:r,agentCatalog:i,subagentCatalog:a,modelFilterRules:o,onSetModelRules:s,defaultModel:c,modelCatalog:l,onSetDefaultModel:u,providers:d,providerApis:f,onSetProvider:p,onRemoveProvider:m,onRemoveProviderModel:h,customAgentDirs:g,pendingSettings:_,onSetCustomAgentDirs:v,onRescanAgents:y,userNickname:b,onSetUserNickname:x})]})]})]})})}var cv=Object.defineProperty,lv=Object.getOwnPropertyDescriptor,uv=(e,t)=>{for(var n in t)cv(e,n,{get:t[n],enumerable:!0})},dv=(e,t,n,r)=>{for(var i=r>1?void 0:r?lv(t,n):t,a=e.length-1,o;a>=0;a--)(o=e[a])&&(i=(r?o(t,n,i):o(i))||i);return r&&i&&cv(t,n,i),i},X=(e,t)=>(n,r)=>t(n,r,e),fv=`Terminal input`,pv={get:()=>fv,set:e=>fv=e},mv=`Too much output to announce, navigate to rows manually to read`,hv={get:()=>mv,set:e=>mv=e};function gv(e){return e.replace(/\r?\n/g,`\r`)}function _v(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function vv(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()}function yv(e,t,n,r){e.stopPropagation(),e.clipboardData&&bv(e.clipboardData.getData(`text/plain`),t,n,r)}function bv(e,t,n,r){e=gv(e),e=_v(e,n.decPrivateModes.bracketedPasteMode&&r.rawOptions.ignoreBracketedPasteMode!==!0),n.triggerDataEvent(e,!0),t.value=``}function xv(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}function Sv(e,t,n,r,i){xv(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}function Cv(e){return e>65535?(e-=65536,String.fromCharCode((e>>10)+55296)+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)}function wv(e,t=0,n=e.length){let r=``;for(let i=t;i<n;++i){let t=e[i];t>65535?(t-=65536,r+=String.fromCharCode((t>>10)+55296)+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r}var Tv=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=(this._interim-55296)*1024+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a<n;++a){let i=e.charCodeAt(a);if(55296<=i&&i<=56319){if(++a>=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=(i-55296)*1024+o-56320+65536:(t[r++]=i,t[r++]=o)}else i!==65279&&(t[r++]=i)}return r}},Ev=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i,a,o,s,c=0,l=0;if(this.interim[0]){let i=!1,a=this.interim[0];a&=(a&224)==192?31:(a&240)==224?15:7;let o=0,s;for(;(s=this.interim[++o]&63)&&o<4;)a<<=6,a|=s;let c=(this.interim[0]&224)==192?2:(this.interim[0]&240)==224?3:4,u=c-o;for(;l<u;){if(l>=n)return 0;if(s=e[l++],(s&192)!=128){l--,i=!0;break}this.interim[o++]=s,a<<=6,a|=s&63}i||(c===2?a<128?l--:t[r++]=a:c===3?a<2048||a>=55296&&a<=57343||a===65279||(t[r++]=a):a<65536||a>1114111||(t[r++]=a)),this.interim.fill(0)}let u=n-4,d=l;for(;d<n;){for(;d<u&&!((i=e[d])&128)&&!((a=e[d+1])&128)&&!((o=e[d+2])&128)&&!((s=e[d+3])&128);)t[r++]=i,t[r++]=a,t[r++]=o,t[r++]=s,d+=4;if(i=e[d++],i<128)t[r++]=i;else if((i&224)==192){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128||(c=(i&31)<<6|a&63,c<128)){d--;continue}t[r++]=c}else if((i&240)==224){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(c=(i&15)<<12|(a&63)<<6|o&63,c<2048||c>=55296&&c<=57343||c===65279)continue;t[r++]=c}else if((i&248)==240){if(d>=n)return this.interim[0]=i,r;if(a=e[d++],(a&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,r;if(o=e[d++],(o&192)!=128){d--;continue}if(d>=n)return this.interim[0]=i,this.interim[1]=a,this.interim[2]=o,r;if(s=e[d++],(s&192)!=128){d--;continue}if(c=(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63,c<65536||c>1114111)continue;t[r++]=c}}return r}},Dv=``,Ov=` `,kv=class e{constructor(){this.fg=0,this.bg=0,this.extended=new Av}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let t=new e;return t.fg=this.fg,t.bg=this.bg,t.extended=this.extended.clone(),t}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)==50331648}isBgRGB(){return(this.bg&50331648)==50331648}isFgPalette(){return(this.fg&50331648)==16777216||(this.fg&50331648)==33554432}isBgPalette(){return(this.bg&50331648)==16777216||(this.bg&50331648)==33554432}isFgDefault(){return!(this.fg&50331648)}isBgDefault(){return!(this.bg&50331648)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:case 33554432:return this.fg&255;case 50331648:return this.fg&16777215;default:return-1}}getBgColor(){switch(this.bg&50331648){case 16777216:case 33554432:return this.bg&255;case 50331648:return this.bg&16777215;default:return-1}}hasExtendedAttrs(){return this.bg&268435456}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(this.bg&268435456&&~this.extended.underlineColor)switch(this.extended.underlineColor&50331648){case 16777216:case 33554432:return this.extended.underlineColor&255;case 50331648:return this.extended.underlineColor&16777215;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return this.bg&268435456&&~this.extended.underlineColor?this.extended.underlineColor&50331648:this.getFgColorMode()}isUnderlineColorRGB(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return this.bg&268435456&&~this.extended.underlineColor?(this.extended.underlineColor&50331648)==16777216||(this.extended.underlineColor&50331648)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return this.bg&268435456&&~this.extended.underlineColor?!(this.extended.underlineColor&50331648):this.isFgDefault()}getUnderlineStyle(){return this.fg&268435456?this.bg&268435456?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}},Av=class e{constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}get ext(){return this._urlId?this._ext&-469762049|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(this._ext&469762048)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return this._ext&67108863}set underlineColor(e){this._ext&=-67108864,this._ext|=e&67108863}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(this._ext&3758096384)>>29;return e<0?e^4294967288:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}clone(){return new e(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}},jv=class e extends kv{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new Av,this.combinedData=``}static fromCharData(t){let n=new e;return n.setFromCharData(t),n}isCombined(){return this.content&2097152}getWidth(){return this.content>>22}getChars(){return this.content&2097152?this.combinedData:this.content&2097151?Cv(this.content&2097151):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):this.content&2097151}setFromCharData(e){this.fg=e[0],this.bg=0;let t=!1;if(e[1].length>2)t=!0;else if(e[1].length===2){let n=e[1].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[1].charCodeAt(1);56320<=r&&r<=57343?this.content=(n-55296)*1024+r-56320+65536|e[2]<<22:t=!0}else t=!0}else this.content=e[1].charCodeAt(0)|e[2]<<22;t&&(this.combinedData=e[1],this.content=2097152|e[2]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},Mv=`di$target`,Nv=`di$dependencies`,Pv=new Map;function Fv(e){return e[Nv]||[]}function Iv(e){if(Pv.has(e))return Pv.get(e);let t=function(e,n,r){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);Lv(t,e,r)};return t._id=e,Pv.set(e,t),t}function Lv(e,t,n){t[Mv]===t?t[Nv].push({id:e,index:n}):(t[Nv]=[{id:e,index:n}],t[Mv]=t)}var Rv=Iv(`BufferService`),zv=Iv(`CoreMouseService`),Bv=Iv(`CoreService`),Vv=Iv(`CharsetService`),Hv=Iv(`InstantiationService`),Uv=Iv(`LogService`),Wv=Iv(`OptionsService`),Gv=Iv(`OscLinkService`),Kv=Iv(`UnicodeService`),qv=Iv(`DecorationService`),Jv=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n){t(void 0);return}let r=[],i=this._optionsService.rawOptions.linkHandler,a=new jv,o=n.getTrimmedLength(),s=-1,c=-1,l=!1;for(let t=0;t<o;t++)if(c!==-1||n.hasContent(t)){if(n.loadCell(t,a),a.hasExtendedAttrs()&&a.extended.urlId){if(c===-1){c=t,s=a.extended.urlId;continue}l=a.extended.urlId!==s}else c!==-1&&(l=!0);if(l||c!==-1&&t===o-1){let n=this._oscLinkService.getLinkData(s)?.uri;if(n){let a={start:{x:c+1,y:e},end:{x:t+ +(!l&&t===o-1),y:e}},s=!1;if(!i?.allowNonHttpProtocols)try{let e=new URL(n);[`http:`,`https:`].includes(e.protocol)||(s=!0)}catch{s=!0}s||r.push({text:n,range:a,activate:(e,t)=>i?i.activate(e,t,a):Yv(e,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}l=!1,a.hasExtendedAttrs()&&a.extended.urlId?(c=t,s=a.extended.urlId):(c=-1,s=-1)}}t(r)}};Jv=dv([X(0,Rv),X(1,Wv),X(2,Gv)],Jv);function Yv(e,t){if(confirm(`Do you want to navigate to ${t}?
|
|
76
76
|
|
|
77
|
-
WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var
|
|
77
|
+
WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}var Xv=Iv(`CharSizeService`),Zv=Iv(`CoreBrowserService`),Qv=Iv(`MouseService`),$v=Iv(`RenderService`),ey=Iv(`SelectionService`),ty=Iv(`CharacterJoinerService`),ny=Iv(`ThemeService`),ry=Iv(`LinkProviderService`),iy=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?uy.isErrorNoTelemetry(e)?new uy(e.message+`
|
|
78
78
|
|
|
79
79
|
`+e.stack):Error(e.message+`
|
|
80
80
|
|
|
81
|
-
`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function $v(e){ty(e)||Qv.onUnexpectedError(e)}var ey=`Canceled`;function ty(e){return e instanceof ny||e instanceof Error&&e.name===ey&&e.message===ey}var ny=class extends Error{constructor(){super(ey),this.name=this.message}};function ry(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var iy=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},ay=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function oy(e,t=0){return e[e.length-(1+t)]}var sy;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(sy||={});var cy=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||sy.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};cy.empty=new cy(e=>{});function ly(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var uy;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function y(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=y})(uy||={});var dy=null;function fy(e){return dy?.trackDisposable(e),e}function py(e){dy?.markAsDisposed(e)}function my(e,t){dy?.setParent(e,t)}function hy(e){return dy?.markAsSingleton(e),e}function gy(e){if(uy.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function _y(...e){return vy(()=>gy(e))}function vy(e){let t=fy({dispose:ly(()=>{py(t),e()})});return t}var yy=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,fy(this)}dispose(){this._isDisposed||(py(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{gy(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return my(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),my(e,null))}};yy.DISABLE_DISPOSED_WARNING=!1;var by=yy,xy=class{constructor(){this._store=new by,fy(this),my(this._store,this)}dispose(){py(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};xy.None=Object.freeze({dispose(){}});var Sy=class{constructor(){this._isDisposed=!1,fy(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&my(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,py(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&my(e,null),e}},Cy=typeof window==`object`?window:globalThis,wy=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};wy.Undefined=new wy(void 0);var Ty=wy,Ey=class{constructor(){this._first=Ty.Undefined,this._last=Ty.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===Ty.Undefined}clear(){let e=this._first;for(;e!==Ty.Undefined;){let t=e.next;e.prev=Ty.Undefined,e.next=Ty.Undefined,e=t}this._first=Ty.Undefined,this._last=Ty.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new Ty(e);if(this._first===Ty.Undefined)this._first=n,this._last=n;else if(t){let e=this._last;this._last=n,n.prev=e,e.next=n}else{let e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==Ty.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==Ty.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==Ty.Undefined&&e.next!==Ty.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===Ty.Undefined&&e.next===Ty.Undefined?(this._first=Ty.Undefined,this._last=Ty.Undefined):e.next===Ty.Undefined?(this._last=this._last.prev,this._last.next=Ty.Undefined):e.prev===Ty.Undefined&&(this._first=this._first.next,this._first.prev=Ty.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==Ty.Undefined;)yield e.element,e=e.next}},Dy=globalThis.performance&&typeof globalThis.performance.now==`function`,Oy=class e{static create(t){return new e(t)}constructor(e){this._now=Dy&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},ky;(e=>{e.None=()=>xy.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(_y(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new Z({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new Z({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new Z({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new Z({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=y;function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new Z({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=b;function x(e){return new Promise(t=>n(e)(t))}e.toPromise=x;function S(e){let t=new Z;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=S;function C(e,t){return e(e=>t.fire(e))}e.forward=C;function w(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=w;class T{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new Z(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function E(e,t){return new T(e,t).emitter.event}e.fromObservable=E;function D(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof by?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=D})(ky||={});var Ay=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new Oy,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};Ay.all=new Set,Ay._idPool=0;var jy=Ay,My=-1,Ny=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t<n)return;this._stacks||=new Map;let r=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,r+1),--this._warnCountdown,this._warnCountdown<=0){this._warnCountdown=n*.5;let[e,r]=this.getMostFrequentStack(),i=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${r}):`;console.warn(i),console.warn(e);let a=new Iy(i,e);this._errorHandler(a)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t<r)&&(e=[n,r],t=r);return e}};Ny._idPool=1;var Py=Ny,Fy=class e{constructor(e){this.value=e}static create(){return new e(Error().stack??``)}print(){console.warn(this.value.split(`
|
|
81
|
+
`+e.stack):e},0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach(t=>{t(e)})}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function ay(e){sy(e)||iy.onUnexpectedError(e)}var oy=`Canceled`;function sy(e){return e instanceof cy||e instanceof Error&&e.name===oy&&e.message===oy}var cy=class extends Error{constructor(){super(oy),this.name=this.message}};function ly(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)}var uy=class e extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(t){if(t instanceof e)return t;let n=new e;return n.message=t.message,n.stack=t.stack,n}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}},dy=class e extends Error{constructor(t){super(t||`An unexpected bug occurred.`),Object.setPrototypeOf(this,e.prototype)}};function fy(e,t=0){return e[e.length-(1+t)]}var py;(e=>{function t(e){return e<0}e.isLessThan=t;function n(e){return e<=0}e.isLessThanOrEqual=n;function r(e){return e>0}e.isGreaterThan=r;function i(e){return e===0}e.isNeitherLessOrGreaterThan=i,e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(py||={});var my=class e{constructor(e){this.iterate=e}forEach(e){this.iterate(t=>(e(t),!0))}toArray(){let e=[];return this.iterate(t=>(e.push(t),!0)),e}filter(t){return new e(e=>this.iterate(n=>!t(n)||e(n)))}map(t){return new e(e=>this.iterate(n=>e(t(n))))}some(e){let t=!1;return this.iterate(n=>(t=e(n),!t)),t}findFirst(e){let t;return this.iterate(n=>!e(n)||(t=n,!1)),t}findLast(e){let t;return this.iterate(n=>(e(n)&&(t=n),!0)),t}findLastMaxBy(e){let t,n=!0;return this.iterate(r=>((n||py.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0)),t}};my.empty=new my(e=>{});function hy(e,t){let n=this,r=!1,i;return function(){if(r)return i;if(r=!0,t)try{i=e.apply(n,arguments)}finally{t()}else i=e.apply(n,arguments);return i}}var gy;(e=>{function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function r(){return n}e.empty=r;function*i(e){yield e}e.single=i;function a(e){return t(e)?e:i(e)}e.wrap=a;function o(e){return e||n}e.from=o;function*s(e){for(let t=e.length-1;t>=0;t--)yield e[t]}e.reverse=s;function c(e){return!e||e[Symbol.iterator]().next().done===!0}e.isEmpty=c;function l(e){return e[Symbol.iterator]().next().value}e.first=l;function u(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1}e.some=u;function d(e,t){for(let n of e)if(t(n))return n}e.find=d;function*f(e,t){for(let n of e)t(n)&&(yield n)}e.filter=f;function*p(e,t){let n=0;for(let r of e)yield t(r,n++)}e.map=p;function*m(e,t){let n=0;for(let r of e)yield*t(r,n++)}e.flatMap=m;function*h(...e){for(let t of e)yield*t}e.concat=h;function g(e,t,n){let r=n;for(let n of e)r=t(r,n);return r}e.reduce=g;function*_(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]}e.slice=_;function v(t,n=1/0){let r=[];if(n===0)return[r,t];let i=t[Symbol.iterator]();for(let t=0;t<n;t++){let t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator](){return i}}]}e.consume=v;async function y(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}e.asyncToArray=y})(gy||={});var _y=null;function vy(e){return _y?.trackDisposable(e),e}function yy(e){_y?.markAsDisposed(e)}function by(e,t){_y?.setParent(e,t)}function xy(e){return _y?.markAsSingleton(e),e}function Sy(e){if(gy.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function Cy(...e){return wy(()=>Sy(e))}function wy(e){let t=vy({dispose:hy(()=>{yy(t),e()})});return t}var Ty=class e{constructor(){this._toDispose=new Set,this._isDisposed=!1,vy(this)}dispose(){this._isDisposed||(yy(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Sy(this._toDispose)}finally{this._toDispose.clear()}}add(t){if(!t)return t;if(t===this)throw Error(`Cannot register a disposable on itself!`);return by(t,this),this._isDisposed?e.DISABLE_DISPOSED_WARNING||console.warn(Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`).stack):this._toDispose.add(t),t}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),by(e,null))}};Ty.DISABLE_DISPOSED_WARNING=!1;var Ey=Ty,Dy=class{constructor(){this._store=new Ey,vy(this),by(this._store,this)}dispose(){yy(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}};Dy.None=Object.freeze({dispose(){}});var Oy=class{constructor(){this._isDisposed=!1,vy(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&by(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,yy(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&by(e,null),e}},ky=typeof window==`object`?window:globalThis,Ay=class e{constructor(t){this.element=t,this.next=e.Undefined,this.prev=e.Undefined}};Ay.Undefined=new Ay(void 0);var jy=Ay,My=class{constructor(){this._first=jy.Undefined,this._last=jy.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===jy.Undefined}clear(){let e=this._first;for(;e!==jy.Undefined;){let t=e.next;e.prev=jy.Undefined,e.next=jy.Undefined,e=t}this._first=jy.Undefined,this._last=jy.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let n=new jy(e);if(this._first===jy.Undefined)this._first=n,this._last=n;else if(t){let e=this._last;this._last=n,n.prev=e,e.next=n}else{let e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==jy.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==jy.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==jy.Undefined&&e.next!==jy.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===jy.Undefined&&e.next===jy.Undefined?(this._first=jy.Undefined,this._last=jy.Undefined):e.next===jy.Undefined?(this._last=this._last.prev,this._last.next=jy.Undefined):e.prev===jy.Undefined&&(this._first=this._first.next,this._first.prev=jy.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==jy.Undefined;)yield e.element,e=e.next}},Ny=globalThis.performance&&typeof globalThis.performance.now==`function`,Py=class e{static create(t){return new e(t)}constructor(e){this._now=Ny&&e===!1?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}},Fy;(e=>{e.None=()=>Dy.None;function t(e,t){return d(e,()=>{},0,void 0,!0,void 0,t)}e.defer=t;function n(e){return(t,n=null,r)=>{let i=!1,a;return a=e(e=>{if(!i)return a?a.dispose():i=!0,t.call(n,e)},null,r),i&&a.dispose(),a}}e.once=n;function r(e,t,n){return l((n,r=null,i)=>e(e=>n.call(r,t(e)),null,i),n)}e.map=r;function i(e,t,n){return l((n,r=null,i)=>e(e=>{t(e),n.call(r,e)},null,i),n)}e.forEach=i;function a(e,t,n){return l((n,r=null,i)=>e(e=>t(e)&&n.call(r,e),null,i),n)}e.filter=a;function o(e){return e}e.signal=o;function s(...e){return(t,n=null,r)=>u(Cy(...e.map(e=>e(e=>t.call(n,e)))),r)}e.any=s;function c(e,t,n,i){let a=n;return r(e,e=>(a=t(a,e),a),i)}e.reduce=c;function l(e,t){let n,r=new Z({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function u(e,t){return t instanceof Array?t.push(e):t&&t.add(e),e}function d(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u=0,d,f=new Z({leakWarningThreshold:a,onWillAddFirstListener(){s=e(e=>{u++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),d=()=>{let e=c;c=void 0,l=void 0,(!r||u>1)&&f.fire(e),u=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(d,n)):l===void 0&&(l=0,queueMicrotask(d))})},onWillRemoveListener(){i&&u>0&&d?.()},onDidRemoveLastListener(){d=void 0,s.dispose()}});return o?.add(f),f.event}e.debounce=d;function f(t,n=0,r){return e.debounce(t,(e,t)=>e?(e.push(t),e):[t],n,void 0,!0,void 0,r)}e.accumulate=f;function p(e,t=(e,t)=>e===t,n){let r=!0,i;return a(e,e=>{let n=r||!t(e,i);return r=!1,i=e,n},n)}e.latch=p;function m(t,n,r){return[e.filter(t,n,r),e.filter(t,e=>!n(e),r)]}e.split=m;function h(e,t=!1,n=[],r){let i=n.slice(),a=e(e=>{i?i.push(e):s.fire(e)});r&&r.add(a);let o=()=>{i?.forEach(e=>s.fire(e)),i=null},s=new Z({onWillAddFirstListener(){a||(a=e(e=>s.fire(e)),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event}e.buffer=h;function g(e,t){return(n,r,i)=>{let a=t(new v);return e(function(e){let t=a.evaluate(e);t!==_&&n.call(r,t)},void 0,i)}}e.chain=g;let _=Symbol(`HaltChainable`);class v{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push(t=>(e(t),t)),this}filter(e){return this.steps.push(t=>e(t)?t:_),this}reduce(e,t){let n=t;return this.steps.push(t=>(n=e(n,t),n)),this}latch(e=(e,t)=>e===t){let t=!0,n;return this.steps.push(r=>{let i=t||!e(r,n);return t=!1,n=r,i?r:_}),this}evaluate(e){for(let t of this.steps)if(e=t(e),e===_)break;return e}}function y(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new Z({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event}e.fromNodeEventEmitter=y;function b(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new Z({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event}e.fromDOMEventEmitter=b;function x(e){return new Promise(t=>n(e)(t))}e.toPromise=x;function S(e){let t=new Z;return e.then(e=>{t.fire(e)},()=>{t.fire(void 0)}).finally(()=>{t.dispose()}),t.event}e.fromPromise=S;function C(e,t){return e(e=>t.fire(e))}e.forward=C;function w(e,t,n){return t(n),e(e=>t(e))}e.runAndSubscribe=w;class T{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new Z(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}function E(e,t){return new T(e,t).emitter.event}e.fromObservable=E;function D(e){return(t,n,r)=>{let i=0,a=!1,o={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),a&&(a=!1,t.call(n)))},handlePossibleChange(){},handleChange(){a=!0}};e.addObserver(o),e.reportChanges();let s={dispose(){e.removeObserver(o)}};return r instanceof Ey?r.add(s):Array.isArray(r)&&r.push(s),s}}e.fromObservableLight=D})(Fy||={});var Iy=class e{constructor(t){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${t}_${e._idPool++}`,e.all.add(this)}start(e){this._stopWatch=new Py,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}};Iy.all=new Set,Iy._idPool=0;var Ly=Iy,Ry=-1,zy=class e{constructor(t,n,r=(e._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=t,this.threshold=n,this.name=r,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t<n)return;this._stacks||=new Map;let r=this._stacks.get(e.value)||0;if(this._stacks.set(e.value,r+1),--this._warnCountdown,this._warnCountdown<=0){this._warnCountdown=n*.5;let[e,r]=this.getMostFrequentStack(),i=`[${this.name}] potential listener LEAK detected, having ${t} listeners already. MOST frequent listener (${r}):`;console.warn(i),console.warn(e);let a=new Hy(i,e);this._errorHandler(a)}return()=>{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t<r)&&(e=[n,r],t=r);return e}};zy._idPool=1;var By=zy,Vy=class e{constructor(e){this.value=e}static create(){return new e(Error().stack??``)}print(){console.warn(this.value.split(`
|
|
82
82
|
`).slice(2).join(`
|
|
83
|
-
`))}},Iy=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},Ly=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},Ry=0,zy=class{constructor(e){this.value=e,this.id=Ry++}},By=2,Z=class{constructor(e){this._size=0,this._options=e,this._leakageMon=My>0||this._options?.leakWarningThreshold?new Py(e?.onListenerError??$v,this._options?.leakWarningThreshold??My):void 0,this._perfMon=this._options?._profName?new jy(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new Ly(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||$v)(n),xy.None}if(this._disposed)return xy.None;t&&(e=e.bind(t));let r=new zy(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=Fy.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof zy?(this._deliveryQueue??=new Vy,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=vy(()=>{i?.(),this._removeListener(r)});return n instanceof by?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*By<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||$v;if(!n)e.value(t);else try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners){if(this._listeners instanceof zy)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}}this._perfMon?.stop()}hasListeners(){return this._size>0}},Vy=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Hy=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Z,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Z,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};Hy.INSTANCE=new Hy;var Uy=Hy;function Wy(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}Uy.INSTANCE.onDidChangeZoomLevel;function Gy(e){return Uy.INSTANCE.getZoomFactor(e)}Uy.INSTANCE.onDidChangeFullscreen;var Ky=typeof navigator==`object`?navigator.userAgent:``,qy=Ky.indexOf(`Firefox`)>=0,Jy=Ky.indexOf(`AppleWebKit`)>=0,Yy=Ky.indexOf(`Chrome`)>=0,Xy=!Yy&&Ky.indexOf(`Safari`)>=0;Ky.indexOf(`Electron/`),Ky.indexOf(`Android`);var Zy=!1;if(typeof Cy.matchMedia==`function`){let e=Cy.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=Cy.matchMedia(`(display-mode: fullscreen)`);Zy=e.matches,Wy(Cy,e,({matches:e})=>{Zy&&t.matches||(Zy=e)})}function Qy(){return Zy}var $y=`en`,eb=!1,tb=!1,nb=!1,rb=!1,ib=!1,ab=$y,ob,sb=globalThis,cb;typeof sb.vscode<`u`&&typeof sb.vscode.process<`u`?cb=sb.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(cb=process);var lb=typeof cb?.versions?.electron==`string`&&cb?.type===`renderer`;if(typeof cb==`object`){eb=cb.platform===`win32`,tb=cb.platform===`darwin`,nb=cb.platform===`linux`,nb&&cb.env.SNAP&&cb.env.SNAP_REVISION,cb.env.CI||cb.env.BUILD_ARTIFACTSTAGINGDIRECTORY,ab=$y;let e=cb.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,ab=t.resolvedLanguage||$y,t.languagePack?.translationsConfigFile}catch{}rb=!0}else typeof navigator==`object`&&!lb?(ob=navigator.userAgent,eb=ob.indexOf(`Windows`)>=0,tb=ob.indexOf(`Macintosh`)>=0,(ob.indexOf(`Macintosh`)>=0||ob.indexOf(`iPad`)>=0||ob.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,nb=ob.indexOf(`Linux`)>=0,ob?.indexOf(`Mobi`),ib=!0,ab=globalThis._VSCODE_NLS_LANGUAGE||$y,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var ub=eb,db=tb,fb=nb,pb=rb;ib&&typeof sb.importScripts==`function`&&sb.origin;var mb=ob,hb=ab,gb;(e=>{function t(){return hb}e.value=t;function n(){return hb.length===2?hb===`en`:hb.length>=3&&hb[0]===`e`&&hb[1]===`n`&&hb[2]===`-`}e.isDefaultVariant=n;function r(){return hb===`en`}e.isDefault=r})(gb||={});var _b=typeof sb.postMessage==`function`&&!sb.importScripts;(()=>{if(_b){let e=[];sb.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n<r;n++){let r=e[n];if(r.id===t.data.vscodeScheduleAsyncWork){e.splice(n,1),r.callback();return}}});let t=0;return n=>{let r=++t;e.push({id:r,callback:n}),sb.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var vb=!!(mb&&mb.indexOf(`Chrome`)>=0);mb&&mb.indexOf(`Firefox`),!vb&&mb&&mb.indexOf(`Safari`),mb&&mb.indexOf(`Edg/`),mb&&mb.indexOf(`Android`);var yb=typeof navigator==`object`?navigator:{};pb||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||yb&&yb.clipboard&&yb.clipboard.writeText,pb||yb&&yb.clipboard&&yb.clipboard.readText,pb||Qy()||yb.keyboard,`ontouchstart`in Cy||yb.maxTouchPoints,Cy.PointerEvent&&(`ontouchstart`in Cy||navigator.maxTouchPoints);var bb=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},xb=new bb,Sb=new bb,Cb=new bb,wb=Array(230),Tb;(e=>{function t(e){return xb.keyCodeToStr(e)}e.toString=t;function n(e){return xb.strToKeyCode(e)}e.fromString=n;function r(e){return Sb.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return Cb.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return Sb.strToKeyCode(e)||Cb.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return xb.keyCodeToStr(e)}e.toElectronAccelerator=o})(Tb||={});var Eb=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new Db([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Db=class{constructor(e){if(e.length===0)throw ry(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t<n;t++)t!==0&&(e+=`;`),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function Ob(e){if(e.charCode){let t=String.fromCharCode(e.charCode).toUpperCase();return Tb.fromString(t)}let t=e.keyCode;if(t===3)return 7;if(qy)switch(t){case 59:return 85;case 60:if(fb)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(db)return 57}else if(Jy&&(db&&t===93||!db&&t===92))return 57;return wb[t]||0}var kb=db?256:2048,Ab=512,jb=1024,Mb=db?2048:256,Nb=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.(`AltGraph`),this.keyCode=Ob(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=kb),this.altKey&&(t|=Ab),this.shiftKey&&(t|=jb),this.metaKey&&(t|=Mb),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new Eb(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},Pb=new WeakMap;function Fb(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,n=e.parent.location;if(t.origin!==`null`&&n.origin!==`null`&&t.origin!==n.origin)return null}catch{return null}return e.parent}var Ib=class{static getSameOriginWindowChain(e){let t=Pb.get(e);if(!t){t=[],Pb.set(e,t);let n=e,r;do r=Fb(n),r?t.push({window:new WeakRef(n),iframeElement:n.frameElement||null}):t.push({window:new WeakRef(n),iframeElement:null}),n=r;while(n)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let n=0,r=0,i=this.getSameOriginWindowChain(e);for(let e of i){let i=e.window.deref();if(n+=i?.scrollY??0,r+=i?.scrollX??0,i===t||!e.iframeElement)break;let a=e.iframeElement.getBoundingClientRect();n+=a.top,r+=a.left}return{top:n,left:r}}},Lb=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type===`dblclick`&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX==`number`?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let n=Ib.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=n.left,this.posy-=n.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},Rb=class{constructor(e,t=0,n=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=n,this.deltaX=t;let r=!1;if(Yy){let e=navigator.userAgent.match(/Chrome\/(\d+)/);r=(e?parseInt(e[1]):123)<=122}if(e){let t=e,n=e,i=e.view?.devicePixelRatio||1;if(typeof t.wheelDeltaY<`u`)this.deltaY=r?t.wheelDeltaY/(120*i):t.wheelDeltaY/120;else if(typeof n.VERTICAL_AXIS<`u`&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type===`wheel`){let t=e;this.deltaY=t.deltaMode===t.DOM_DELTA_LINE?qy&&!db?-e.deltaY/3:-e.deltaY:-e.deltaY/40}if(typeof t.wheelDeltaX<`u`)this.deltaX=Xy&&ub?-(t.wheelDeltaX/120):r?t.wheelDeltaX/(120*i):t.wheelDeltaX/120;else if(typeof n.HORIZONTAL_AXIS<`u`&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type===`wheel`){let t=e;this.deltaX=t.deltaMode===t.DOM_DELTA_LINE?qy&&!db?-e.deltaX/3:-e.deltaX:-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(this.deltaY=r?e.wheelDelta/(120*i):e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},zb=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),Bb;(e=>{function t(t){return t===e.None||t===e.Cancelled||t instanceof Vb?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:ky.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:zb})})(Bb||={});var Vb=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?zb:(this._emitter||=new Z,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},Hb=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new ay(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new ay(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},Ub=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new ay(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=vy(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var Wb;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(Wb||={});var Gb=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new Z,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(this._state===1)return{done:!0,value:void 0};await ky.toPromise(this._onStateChanged.event)}while(1)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};Gb.EMPTY=Gb.fromArray([]);function Kb(e){return qb(e,0)}function qb(e,t){switch(typeof e){case`object`:return e===null?Jb(349,t):Array.isArray(e)?Zb(e,t):Qb(e,t);case`string`:return Xb(e,t);case`boolean`:return Yb(e,t);case`number`:return Jb(e,t);case`undefined`:return Jb(937,t);default:return Jb(617,t)}}function Jb(e,t){return(t<<5)-t+e|0}function Yb(e,t){return Jb(e?433:863,t)}function Xb(e,t){t=Jb(149417,t);for(let n=0,r=e.length;n<r;n++)t=Jb(e.charCodeAt(n),t);return t}function Zb(e,t){return t=Jb(104579,t),e.reduce((e,t)=>qb(t,e),t)}function Qb(e,t){return t=Jb(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=Xb(n,t),qb(e[n],t)),t)}var{registerWindow:$b,getWindow:ex,getDocument:tx,getWindows:nx,getWindowsCount:rx,getWindowId:ix,getWindowById:ax,hasWindow:ox,onDidRegisterWindow:sx,onWillUnregisterWindow:cx,onDidUnregisterWindow:lx}=function(){let e=new Map,t={window:Cy,disposables:new by};e.set(Cy.vscodeWindowId,t);let n=new Z,r=new Z,i=new Z;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return xy.None;let a=new by,o={window:t,disposables:a.add(new by)};return e.set(t.vscodeWindowId,o),a.add(vy(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(Q(t,yx.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:Cy},getDocument(e){return ex(e).document}}}(),ux=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function Q(e,t,n,r){return new ux(e,t,n,r)}function dx(e,t){return function(n){return t(new Lb(e,n))}}function fx(e){return function(t){return e(new Nb(t))}}var px=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=dx(ex(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=fx(n)),Q(e,t,i,r)},mx,hx=class extends Ub{constructor(e){super(),this.defaultTarget=e&&ex(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},gx=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){$v(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(gx.sort),a.shift().execute();r.set(i,!1)};mx=(t,r,a=0)=>{let o=ix(t),s=new gx(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var _x=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};_x.None=new _x(0,0);function vx(e){let t=e.getBoundingClientRect(),n=ex(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=Kb(n),a=r.get(i);if(a)a.users+=1;else{let o=new Z,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(vy(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var yx={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:Jy?`webkitAnimationStart`:`animationstart`,ANIMATION_END:Jy?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:Jy?`webkitAnimationIteration`:`animationiteration`},bx=class{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=xx(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=xx(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=xx(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=xx(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=xx(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=xx(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=xx(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=xx(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=xx(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=xx(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=xx(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=xx(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=xx(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=xx(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function xx(e){return typeof e==`number`?`${e}px`:e}function Sx(e){return new bx(e)}var Cx=class{constructor(){this._hooks=new by,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add(vy(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=ex(e)}this._hooks.add(Q(a,yx.POINTER_MOVE,e=>{e.buttons===n?(e.preventDefault(),this._pointerMoveCallback(e)):this.stopMonitoring(!0)})),this._hooks.add(Q(a,yx.POINTER_UP,e=>this.stopMonitoring(!0)))}};function wx(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var Tx;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(Tx||={});var Ex=class e extends xy{constructor(){super(),this.dispatched=!1,this.targets=new Ey,this.ignoreTargets=new Ey,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(ky.runAndSubscribe(sx,({window:e,disposables:t})=>{t.add(Q(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add(Q(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add(Q(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:Cy,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=hy(new e),vy(e.INSTANCE.targets.push(t))):xy.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=hy(new e),vy(e.INSTANCE.ignoreTargets.push(t))):xy.None}static isTouchDevice(){return`ontouchstart`in Cy||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n<r;n++){let r=e.targetTouches.item(n);this.activeTouches[r.identifier]={id:r.identifier,initialTarget:r.target,initialTimeStamp:t,initialPageX:r.pageX,initialPageY:r.pageY,rollingTimestamps:[t],rollingPageX:[r.pageX],rollingPageY:[r.pageY]};let i=this.newGestureEvent(Tx.Start,r.target);i.pageX=r.pageX,i.pageY=r.pageY,this.dispatchEvent(i)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}onTouchEnd(t,n){let r=Date.now(),i=Object.keys(this.activeTouches).length;for(let a=0,o=n.changedTouches.length;a<o;a++){let o=n.changedTouches.item(a);if(!this.activeTouches.hasOwnProperty(String(o.identifier))){console.warn(`move of an UNKNOWN touch`,o);continue}let s=this.activeTouches[o.identifier],c=Date.now()-s.initialTimeStamp;if(c<e.HOLD_DELAY&&Math.abs(s.initialPageX-oy(s.rollingPageX))<30&&Math.abs(s.initialPageY-oy(s.rollingPageY))<30){let e=this.newGestureEvent(Tx.Tap,s.initialTarget);e.pageX=oy(s.rollingPageX),e.pageY=oy(s.rollingPageY),this.dispatchEvent(e)}else if(c>=e.HOLD_DELAY&&Math.abs(s.initialPageX-oy(s.rollingPageX))<30&&Math.abs(s.initialPageY-oy(s.rollingPageY))<30){let e=this.newGestureEvent(Tx.Contextmenu,s.initialTarget);e.pageX=oy(s.rollingPageX),e.pageY=oy(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=oy(s.rollingPageX),n=oy(s.rollingPageY),i=oy(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(Tx.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===Tx.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===Tx.Change||t.type===Tx.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=mx(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(Tx.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n<r;n++){let r=e.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(r.identifier))){console.warn(`end of an UNKNOWN touch`,r);continue}let i=this.activeTouches[r.identifier],a=this.newGestureEvent(Tx.Change,i.initialTarget);a.translationX=r.pageX-oy(i.rollingPageX),a.translationY=r.pageY-oy(i.rollingPageY),a.pageX=r.pageX,a.pageY=r.pageY,this.dispatchEvent(a),i.rollingPageX.length>3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};Ex.SCROLL_FRICTION=-.005,Ex.HOLD_DELAY=700,Ex.CLEAR_TAP_COUNT_TIME=400,av([wx],Ex,`isTouchDevice`,1);var Dx=Ex,Ox=class extends xy{onclick(e,t){this._register(Q(e,yx.CLICK,n=>t(new Lb(ex(e),n))))}onmousedown(e,t){this._register(Q(e,yx.MOUSE_DOWN,n=>t(new Lb(ex(e),n))))}onmouseover(e,t){this._register(Q(e,yx.MOUSE_OVER,n=>t(new Lb(ex(e),n))))}onmouseleave(e,t){this._register(Q(e,yx.MOUSE_LEAVE,n=>t(new Lb(ex(e),n))))}onkeydown(e,t){this._register(Q(e,yx.KEY_DOWN,e=>t(new Nb(e))))}onkeyup(e,t){this._register(Q(e,yx.KEY_UP,e=>t(new Nb(e))))}oninput(e,t){this._register(Q(e,yx.INPUT,t))}onblur(e,t){this._register(Q(e,yx.BLUR,t))}onfocus(e,t){this._register(Q(e,yx.FOCUS,t))}onchange(e,t){this._register(Q(e,yx.CHANGE,t))}ignoreGesture(e){return Dx.ignoreTarget(e)}},kx=11,Ax=class extends Ox{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,typeof e.top<`u`&&(this.bgDomNode.style.top=`0px`),typeof e.left<`u`&&(this.bgDomNode.style.left=`0px`),typeof e.bottom<`u`&&(this.bgDomNode.style.bottom=`0px`),typeof e.right<`u`&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=kx+`px`,this.domNode.style.height=kx+`px`,typeof e.top<`u`&&(this.domNode.style.top=e.top+`px`),typeof e.left<`u`&&(this.domNode.style.left=e.left+`px`),typeof e.bottom<`u`&&(this.domNode.style.bottom=e.bottom+`px`),typeof e.right<`u`&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new Cx),this._register(px(this.bgDomNode,yx.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(px(this.domNode,yx.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new hx),this._pointerdownScheduleRepeatTimer=this._register(new Hb)}_arrowPointerDown(e){e.target&&e.target instanceof Element&&(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,ex(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},jx=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<`u`?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<`u`?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},Mx=class extends xy{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new jx(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new Ix(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=Ix.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},Nx=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function Px(e,t){let n=t-e;return function(t){return e+n*Rx(t)}}function Fx(e,t,n){return function(r){return r<n?e(r/n):t((r-n)/(1-n))}}var Ix=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.duration=r,this.startTime=n,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,n){if(Math.abs(e-t)>2.5*n){let r,i;return e<t?(r=e+.75*n,i=t-.75*n):(r=e-.75*n,i=t+.75*n),Fx(Px(e,r),Px(i,t),.33)}return Px(e,t)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(e){this.to=e.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(e){let t=(e-this.startTime)/this.duration;return t<1?new Nx(this.scrollLeft(t),this.scrollTop(t),!1):new Nx(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,n,r){return e.start(t,n,r)}static start(t,n,r){r+=10;let i=Date.now()-10;return new e(t,n,i,r)}};function Lx(e){return e**3}function Rx(e){return 1-Lx(1-e)}var zx=class extends xy{constructor(e,t,n){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=n,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new Hb)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3||this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){this._isNeeded?this._shouldBeVisible?this._reveal():this._hide(!0):this._hide(!1)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},Bx=140,Vx=class extends Ox{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new zx(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new Cx),this._shouldRender=!0,this.domNode=Sx(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register(Q(this.domNode.domNode,yx.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new Ax(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=Sx(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Q(this.slider.domNode,yx.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=vx(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(ub&&a>Bx){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},Hx=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t<this._computedSliderPosition?n-=this._visibleSize:n+=this._visibleSize,n}getDesiredScrollPositionFromDelta(e){if(!this._computedIsNeeded)return 0;let t=this._computedSliderPosition+e;return Math.round(t/this._computedSliderRatio)}},Ux=class extends Vx{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new Hx(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,r.width,r.scrollWidth,i.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:`horizontal`,scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},Wx=class extends Vx{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new Hx(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,r.height,r.scrollHeight,i.scrollTop),visibility:t.vertical,extraScrollbarClassName:`vertical`,scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},Gx=500,Kx=50,qx=!0,Jx=class{constructor(e,t,n){this.timestamp=e,this.deltaX=t,this.deltaY=n,this.score=0}},Yx=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let e=1,t=0,n=1,r=this._rear;do{let i=r===this._front?e:2**-n;if(e-=i,t+=this._memory[r].score*i,r===this._front)break;r=(this._capacity+r-1)%this._capacity,n++}while(1);return t<=.5}acceptStandardWheelEvent(e){if(Yy){let t=Gy(ex(e.browserEvent));this.accept(Date.now(),e.deltaX*t,e.deltaY*t)}else this.accept(Date.now(),e.deltaX,e.deltaY)}accept(e,t,n){let r=null,i=new Jx(e,t,n);this._front===-1&&this._rear===-1?(this._memory[0]=i,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=i),i.score=this._computeScore(i,r)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};Yx.INSTANCE=new Yx;var Xx=Yx,Zx=class extends Ox{constructor(e,t,n){super(),this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new Z),this.onWillScroll=this._onWillScroll.event,this._options=$x(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new Wx(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new Ux(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Sx(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Sx(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Sx(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new Hb),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=gy(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,db&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){typeof e.handleMouseWheel<`u`&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<`u`&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<`u`&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<`u`&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<`u`&&(this._options.horizontal=e.horizontal),typeof e.vertical<`u`&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<`u`&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<`u`&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<`u`&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new Rb(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=gy(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(Q(this._listenOnDomNode,yx.MOUSE_WHEEL,e=>{this._onMouseWheel(new Rb(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=Xx.INSTANCE;qx&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!db&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=Kx*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=Kx*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(qx&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),Gx)}},Qx=class extends Zx{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function $x(e){let t={lazyRender:typeof e.lazyRender<`u`&&e.lazyRender,className:typeof e.className<`u`?e.className:``,useShadows:typeof e.useShadows<`u`?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<`u`?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<`u`&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<`u`&&e.scrollYToX,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<`u`?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<`u`?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<`u`?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<`u`?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<`u`?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<`u`?e.listenOnDomNode:null,horizontal:typeof e.horizontal<`u`?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<`u`?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<`u`&&e.horizontalHasArrows,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,db&&(t.className+=` mac`),t}var eS=class extends xy{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new Z),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new Mx({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>mx(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new Qx(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(ky.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(vy(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register(vy(()=>this._styleElement.remove())),this._register(ky.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(`
|
|
84
|
-
`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};eS=av([X(2,Mv),X(3,Gv),X(4,Nv),X(5,Xv),X(6,Rv),X(7,qv)],eS);var tS=class extends xy{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(vy(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};tS=av([X(1,Mv),X(2,Gv),X(3,Vv),X(4,qv)],tS);var nS=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},rS={full:0,left:0,center:0,right:0},iS={full:0,left:0,center:0,right:0},aS={full:0,left:0,center:0,right:0},oS=class extends xy{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new nS,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(vy(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw Error(`Ctx cannot be null`);this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);iS.full=this._canvas.width,iS.left=e,iS.center=t,iS.right=e,this._refreshDrawHeightConstants(),aS.full=1,aS.left=1,aS.center=1+iS.left,aS.right=1+iS.left+iS.center}_refreshDrawHeightConstants(){rS.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);rS.left=t,rS.center=t,rS.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*rS.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*rS.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*rS.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*rS.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(aS[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-rS[e.position||`full`]/2),iS[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+rS[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};oS=av([X(2,Mv),X(3,Vv),X(4,qv),X(5,Rv),X(6,Xv),X(7,Gv)],oS);var $;(e=>(e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
|
|
85
|
-
`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))($||={});var sS;(e=>(e.PAD=``,e.HOP=``,e.BPH=``,e.NBH=``,e.IND=``,e.NEL=`
`,e.SSA=``,e.ESA=``,e.HTS=``,e.HTJ=``,e.VTS=``,e.PLD=``,e.PLU=``,e.RI=``,e.SS2=``,e.SS3=``,e.DCS=``,e.PU1=``,e.PU2=``,e.STS=``,e.CCH=``,e.MW=``,e.SPA=``,e.EPA=``,e.SOS=``,e.SGCI=``,e.SCI=``,e.CSI=``,e.ST=``,e.OSC=``,e.PM=``,e.APC=``))(sS||={});var cS;(e=>e.ST=`${$.ESC}\\`)(cS||={});var lS=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${$.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};lS=av([X(2,Mv),X(3,Rv),X(4,Pv),X(5,qv)],lS);var uS=0,dS=0,fS=0,pS=0,mS={css:`#00000000`,rgba:0},hS;(e=>{function t(e,t,n,r){return r===void 0?`#${bS(e)}${bS(t)}${bS(n)}`:`#${bS(e)}${bS(t)}${bS(n)}${bS(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(hS||={});var gS;(e=>{function t(e,t){if(pS=(t.rgba&255)/255,pS===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return uS=a+Math.round((n-a)*pS),dS=o+Math.round((r-o)*pS),fS=s+Math.round((i-s)*pS),{css:hS.toCss(uS,dS,fS),rgba:hS.toRgba(uS,dS,fS)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=yS.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return hS.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[uS,dS,fS]=yS.toChannels(t),{css:hS.toCss(uS,dS,fS),rgba:t}}e.opaque=i;function a(e,t){return pS=Math.round(t*255),[uS,dS,fS]=yS.toChannels(e.rgba),{css:hS.toCss(uS,dS,fS,pS),rgba:hS.toRgba(uS,dS,fS,pS)}}e.opacity=a;function o(e,t){return pS=e.rgba&255,a(e,pS*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(gS||={});var _S;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return uS=parseInt(e.slice(1,2).repeat(2),16),dS=parseInt(e.slice(2,3).repeat(2),16),fS=parseInt(e.slice(3,4).repeat(2),16),hS.toColor(uS,dS,fS);case 5:return uS=parseInt(e.slice(1,2).repeat(2),16),dS=parseInt(e.slice(2,3).repeat(2),16),fS=parseInt(e.slice(3,4).repeat(2),16),pS=parseInt(e.slice(4,5).repeat(2),16),hS.toColor(uS,dS,fS,pS);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return uS=parseInt(r[1]),dS=parseInt(r[2]),fS=parseInt(r[3]),pS=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),hS.toColor(uS,dS,fS,pS);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[uS,dS,fS,pS]=t.getImageData(0,0,1,1).data,pS!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:hS.toRgba(uS,dS,fS,pS),css:e}}e.toColor=r})(_S||={});var vS;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(vS||={});var yS;(e=>{function t(e,t){if(pS=(t&255)/255,pS===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return uS=a+Math.round((n-a)*pS),dS=o+Math.round((r-o)*pS),fS=s+Math.round((i-s)*pS),hS.toRgba(uS,dS,fS)}e.blend=t;function n(e,t,n){let a=vS.relativeLuminance(e>>8),o=vS.relativeLuminance(t>>8);if(xS(a,o)<n){if(o<a){let o=r(e,t,n),s=xS(a,vS.relativeLuminance(o>>8));if(s<n){let r=i(e,t,n);return s>xS(a,vS.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=xS(a,vS.relativeLuminance(s>>8));if(c<n){let i=r(e,t,n);return c>xS(a,vS.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=xS(vS.relativeLuminance2(o,s,c),vS.relativeLuminance2(r,i,a));for(;l<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=xS(vS.relativeLuminance2(o,s,c),vS.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=xS(vS.relativeLuminance2(o,s,c),vS.relativeLuminance2(r,i,a));for(;l<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil((255-o)*.1)),s=Math.min(255,s+Math.ceil((255-s)*.1)),c=Math.min(255,c+Math.ceil((255-c)*.1)),l=xS(vS.relativeLuminance2(o,s,c),vS.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(yS||={});function bS(e){let t=e.toString(16);return t.length<2?`0`+t:t}function xS(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var SS=class extends Cv{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},CS=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new Tv}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let n=[],r=t.translateToString(!0),i=0,a=0,o=0,s=t.getFg(0),c=t.getBg(0);for(let e=0;e<t.getTrimmedLength();e++)if(t.loadCell(e,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==s||this._workCell.bg!==c){if(e-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}i=e,o=a,s=this._workCell.fg,c=this._workCell.bg}a+=this._workCell.getChars().length||Sv.length}if(this._bufferService.cols-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}return n}_getJoinedRanges(e,t,n,r,i){let a=e.substring(t,n),o=[];try{o=this._characterJoiners[0].handler(a)}catch(e){console.error(e)}for(let e=1;e<this._characterJoiners.length;e++)try{let t=this._characterJoiners[e].handler(a);for(let e=0;e<t.length;e++)CS._mergeRanges(o,t[e])}catch(e){console.error(e)}return this._stringRangesToCellRanges(o,r,i),o}_stringRangesToCellRanges(e,t,n){let r=0,i=!1,a=0,o=e[r];if(o){for(let s=n;s<this._bufferService.cols;s++){let n=t.getWidth(s),c=t.getString(s).length||Sv.length;if(n!==0){if(!i&&o[0]<=a&&(o[0]=s,i=!0),o[1]<=a){if(o[1]=s,o=e[++r],!o)break;o[0]<=a?(o[0]=s,i=!0):i=!1}a+=c}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){if(t[1]<=i[0])return e[r-1][1]=t[1],e;if(t[1]<=i[1])return e[r-1][1]=Math.max(t[1],i[1]),e.splice(r,1),e;e.splice(r,1),r--}else{if(t[1]<=i[0])return e.splice(r,0,t),e;if(t[1]<=i[1])return i[0]=Math.min(t[0],i[0]),e;t[0]<i[1]&&(i[0]=Math.min(t[0],i[0]),n=!0);continue}}return n?e[e.length-1][1]=t[1]:e.push(t),e}};CS=av([X(0,Mv)],CS);function wS(e){return 57508<=e&&e<=57558}function TS(e){return 9472<=e&&e<=9631}function ES(e){return wS(e)||TS(e)}function DS(){return{css:{canvas:OS(),cell:OS()},device:{canvas:OS(),cell:OS(),char:{width:0,height:0,left:0,top:0}}}}function OS(){return{width:0,height:0}}var kS=class{constructor(e,t,n,r,i,a,o){this._document=e,this._characterJoinerService=t,this._optionsService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._themeService=o,this._workCell=new Tv,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,n){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=n}createRow(e,t,n,r,i,a,o,s,c,l,u){let d=[],f=this._characterJoinerService.getJoinedCharacters(t),p=this._themeService.colors,m=e.getNoBgTrimmedLength();n&&m<a+1&&(m=a+1);let h,g=0,_=``,v=0,y=0,b=0,x=0,S=!1,C=0,w=!1,T=0,E=0,D=[],O=l!==-1&&u!==-1;for(let k=0;k<m;k++){e.loadCell(k,this._workCell);let m=this._workCell.getWidth();if(m===0)continue;let A=!1,ee=k>=E,j=k,M=this._workCell;if(f.length>0&&k===f[0][0]&&ee){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v<r[1];v++)ee&&=i===this._isCellInSelection(v,t);ee&&=!n||a<r[0]||a>=r[1],ee?(A=!0,M=new SS(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),j=r[1]-1,m=M.getWidth()):E=r[1]}let N=this._isCellInSelection(k,t),te=n&&k===a,ne=O&&k>=l&&k<=u,re=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{re=!0});let ie=M.getChars()||Sv;if(ie===` `&&(M.isUnderline()||M.isOverline())&&(ie=`\xA0`),T=m*s-c.get(ie,M.isBold(),M.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(N&&w||!N&&!w&&M.bg===y)&&(N&&w&&p.selectionForeground||M.fg===b)&&M.extended.ext===x&&ne===S&&T===C&&!te&&!A&&!re&&ee){M.isInvisible()?_+=Sv:_+=ie,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(y=M.bg,b=M.fg,x=M.extended.ext,S=ne,C=T,w=N,A&&a>=k&&a<=j&&(a=k),!this._coreService.isCursorHidden&&te&&this._coreService.isCursorInitialized){if(D.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&D.push(`xterm-cursor-blink`),D.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:D.push(`xterm-cursor-outline`);break;case`block`:D.push(`xterm-cursor-block`);break;case`bar`:D.push(`xterm-cursor-bar`);break;case`underline`:D.push(`xterm-cursor-underline`)}}if(M.isBold()&&D.push(`xterm-bold`),M.isItalic()&&D.push(`xterm-italic`),M.isDim()&&D.push(`xterm-dim`),_=M.isInvisible()?Sv:M.getChars()||Sv,M.isUnderline()&&(D.push(`xterm-underline-${M.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!M.isUnderlineColorDefault())){if(M.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${Cv.toColorRGB(M.getUnderlineColor()).join(`,`)})`;else{let e=M.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&M.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}}M.isOverline()&&(D.push(`xterm-overline`),_===` `&&(_=`\xA0`)),M.isStrikethrough()&&D.push(`xterm-strikethrough`),ne&&(h.style.textDecoration=`underline`);let ae=M.getFgColor(),oe=M.getFgColorMode(),se=M.getBgColor(),ce=M.getBgColorMode(),le=!!M.isInverse();if(le){let e=ae;ae=se,se=e;let t=oe;oe=ce,ce=t}let ue,de,fe=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{e.options.layer!==`top`&&fe||(e.backgroundColorRGB&&(ce=50331648,se=e.backgroundColorRGB.rgba>>8&16777215,ue=e.backgroundColorRGB),e.foregroundColorRGB&&(oe=50331648,ae=e.foregroundColorRGB.rgba>>8&16777215,de=e.foregroundColorRGB),fe=e.options.layer===`top`)}),!fe&&N&&(ue=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,se=ue.rgba>>8&16777215,ce=50331648,fe=!0,p.selectionForeground&&(oe=50331648,ae=p.selectionForeground.rgba>>8&16777215,de=p.selectionForeground)),fe&&D.push(`xterm-decoration-top`);let pe;switch(ce){case 16777216:case 33554432:pe=p.ansi[se],D.push(`xterm-bg-${se}`);break;case 50331648:pe=hS.toColor(se>>16,se>>8&255,se&255),this._addStyle(h,`background-color:#${AS((se>>>0).toString(16),`0`,6)}`);break;default:le?(pe=p.foreground,D.push(`xterm-bg-257`)):pe=p.background}switch(ue||M.isDim()&&(ue=gS.multiplyOpacity(pe,.5)),oe){case 16777216:case 33554432:M.isBold()&&ae<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(ae+=8),this._applyMinimumContrast(h,pe,p.ansi[ae],M,ue,void 0)||D.push(`xterm-fg-${ae}`);break;case 50331648:let e=hS.toColor(ae>>16&255,ae>>8&255,ae&255);this._applyMinimumContrast(h,pe,e,M,ue,de)||this._addStyle(h,`color:#${AS(ae.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,pe,p.foreground,M,ue,de)||le&&D.push(`xterm-fg-257`)}D.length&&=(h.className=D.join(` `),0),!te&&!A&&!re&&ee?g++:h.textContent=_,T!==this.defaultSpacing&&(h.style.letterSpacing=`${T}px`),d.push(h),k=j}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||ES(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=gS.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e<r[0]&&t<=r[1]:e<n[0]&&t>=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t<r[1]||n[1]===r[1]&&t===n[1]&&e>=n[0]&&e<r[0]||n[1]<r[1]&&t===r[1]&&e<r[0]||n[1]<r[1]&&t===n[1]&&e>=n[0]}};kS=av([X(1,Yv),X(2,Rv),X(3,Gv),X(4,Pv),X(5,Vv),X(6,Xv)],kS);function AS(e,t,n){for(;e.length<n;)e=t+e;return e}var jS=class{constructor(e,t){this._flat=new Float32Array(256),this._font=``,this._fontSize=0,this._weight=`normal`,this._weightBold=`bold`,this._measureElements=[],this._container=e.createElement(`div`),this._container.classList.add(`xterm-width-cache-measure-container`),this._container.setAttribute(`aria-hidden`,`true`),this._container.style.whiteSpace=`pre`,this._container.style.fontKerning=`none`;let n=e.createElement(`span`);n.classList.add(`xterm-char-measure-element`);let r=e.createElement(`span`);r.classList.add(`xterm-char-measure-element`),r.style.fontWeight=`bold`;let i=e.createElement(`span`);i.classList.add(`xterm-char-measure-element`),i.style.fontStyle=`italic`;let a=e.createElement(`span`);a.classList.add(`xterm-char-measure-element`),a.style.fontWeight=`bold`,a.style.fontStyle=`italic`,this._measureElements=[n,r,i,a],this._container.appendChild(n),this._container.appendChild(r),this._container.appendChild(i),this._container.appendChild(a),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,n,r){e===this._font&&t===this._fontSize&&n===this._weight&&r===this._weightBold||(this._font=e,this._fontSize=t,this._weight=n,this._weightBold=r,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${n}`,this._measureElements[1].style.fontWeight=`${r}`,this._measureElements[2].style.fontWeight=`${n}`,this._measureElements[3].style.fontWeight=`${r}`,this.clear())}get(e,t,n){let r=0;if(!t&&!n&&e.length===1&&(r=e.charCodeAt(0))<256){if(this._flat[r]!==-9999)return this._flat[r];let t=this._measure(e,0);return t>0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},MS=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);s>=e.rows||c<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0])}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function NS(){return new MS}var PS=`xterm-dom-renderer-owner-`,FS=`xterm-rows`,IS=`xterm-fg-`,LS=`xterm-bg-`,RS=`xterm-focus`,zS=`xterm-selection`,BS=1,VS=class extends xy{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=BS++,this._rowElements=[],this._selectionRenderModel=NS(),this.onRequestRedraw=this._register(new Z).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(FS),this._rowContainer.style.lineHeight=`normal`,this._rowContainer.setAttribute(`aria-hidden`,`true`),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(`div`),this._selectionContainer.classList.add(zS),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=DS(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(kS,document),this._element.classList.add(PS+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(vy(()=>{this._element.classList.remove(PS+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new jS(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${FS} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${FS} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${FS} .xterm-dim { color: ${gS.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${FS}.${RS} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${FS}.${RS} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${FS}.${RS} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${FS} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${FS} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${FS} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${FS} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${FS} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${zS} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${zS} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${zS} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${IS}${n} { color: ${r.css}; }${this._terminalSelector} .${IS}${n}.xterm-dim { color: ${gS.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${LS}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${IS}257 { color: ${gS.opaque(e.background).css}; }${this._terminalSelector} .${IS}257.xterm-dim { color: ${gS.multiplyOpacity(gS.opaque(e.background),.5).css}; }${this._terminalSelector} .${LS}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(RS),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(RS),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${PS}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};VS=av([X(7,Iv),X(8,Wv),X(9,Rv),X(10,Mv),X(11,Pv),X(12,Gv),X(13,Xv)],VS);var HS=class extends xy{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new Z),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new GS(this._optionsService))}catch{this._measureStrategy=this._register(new WS(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};HS=av([X(2,Rv)],HS);var US=class extends xy{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},WS=class extends US{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},GS=class extends US{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},KS=class extends xy{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new qS(this._window)),this._onDprChange=this._register(new Z),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new Z),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(ky.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Q(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(Q(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},qS=class extends xy{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Sy),this._onDprChange=this._register(new Z),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(vy(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Q(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},JS=class extends xy{constructor(){super(),this.linkProviders=[],this._register(vy(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function YS(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function XS(e,t,n,r,i,a,o,s,c){if(!a)return;let l=YS(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var ZS=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return XS(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=YS(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};ZS=av([X(0,qv),X(1,Wv)],ZS);var QS=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},$S={};iv($S,{getSafariVersion:()=>oC,isChromeOS:()=>fC,isFirefox:()=>rC,isIpad:()=>cC,isIphone:()=>lC,isLegacyEdge:()=>iC,isLinux:()=>dC,isMac:()=>sC,isNode:()=>eC,isSafari:()=>aC,isWindows:()=>uC});var eC=typeof process<`u`&&`title`in process,tC=eC?`node`:navigator.userAgent,nC=eC?`node`:navigator.platform,rC=tC.includes(`Firefox`),iC=tC.includes(`Edge`),aC=/^((?!chrome|android).)*safari/i.test(tC);function oC(){if(!aC)return 0;let e=tC.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var sC=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(nC),cC=nC===`iPad`,lC=nC===`iPhone`,uC=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(nC),dC=nC.indexOf(`Linux`)>=0,fC=/\bCrOS\b/.test(tC),pC=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},mC=class extends pC{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},hC=class extends pC{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},gC=!eC&&`requestIdleCallback`in window?hC:mC,_C=class{constructor(){this._queue=new gC}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},vC=class extends xy{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new Sy),this._pausedResizeTask=new _C,this._observerDisposable=this._register(new Sy),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new Z),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new Z),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new Z),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new Z),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new QS((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new yC(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(vy(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=vy(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};vC=av([X(2,Rv),X(3,Wv),X(4,Pv),X(5,Vv),X(6,Mv),X(7,Gv),X(8,Xv)],vC);var yC=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function bC(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return CC(i,a,e,t,n,r)+wC(a,t,n,r)+TC(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,MC(Math.abs(i-e),jC(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return MC(SC(a>t?e:i,n)+(s-1)*n.cols+1+xC(a>t?i:e,n),jC(o,r))}function xC(e,t){return e-1}function SC(e,t){return t.cols-e}function CC(e,t,n,r,i,a){return wC(t,r,i,a).length===0?``:MC(AC(e,t,e,t-DC(t,i),!1,i).length,jC(`D`,a))}function wC(e,t,n,r){let i=e-DC(e,n),a=t-DC(t,n);return MC(Math.abs(i-a)-EC(e,t,n),jC(kC(e,t),r))}function TC(e,t,n,r,i,a){let o;o=wC(t,r,i,a).length>0?r-DC(r,i):t;let s=r,c=OC(e,t,n,r,i,a);return MC(AC(e,o,n,s,c===`C`,i).length,jC(c,a))}function EC(e,t,n){let r=0,i=e-DC(e,n),a=t-DC(t,n);for(let o=0;o<Math.abs(i-a);o++){let a=kC(e,t)===`A`?-1:1;n.buffer.lines.get(i+a*o)?.isWrapped&&r++}return r}function DC(e,t){let n=0,r=t.buffer.lines.get(e),i=r?.isWrapped;for(;i&&e>=0&&e<t.rows;)n++,r=t.buffer.lines.get(--e),i=r?.isWrapped;return n}function OC(e,t,n,r,i,a){let o;return o=wC(n,r,i,a).length>0?r-DC(r,i):t,e<n&&o<=r||e>=n&&o<r?`C`:`D`}function kC(e,t){return e>t?`A`:`B`}function AC(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&s<a.buffer.lines.length;)o+=i?1:-1,i&&o>a.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function jC(e,t){let n=t?`O`:`[`;return $.ESC+n+e}function MC(e,t){e=Math.floor(e);let n=``;for(let r=0;r<e;r++)n+=t;return n}var NC=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function PC(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var FC=50,IC=15,LC=50,RC=500,zC=RegExp(`\xA0`,`g`),BC=class extends xy{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new Tv,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new Z),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new Z),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new Z),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new Z),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new NC(this._bufferService),this._activeSelectionMode=0,this._register(vy(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]<t[0]?e[0]:t[0],a=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let e=n.translateBufferLineToString(o,!0,i,a);r.push(e)}}else{let i=e[1]===t[1]?t[0]:void 0;r.push(n.translateBufferLineToString(e[1],!0,e[0],i));for(let i=e[1]+1;i<=t[1]-1;i++){let e=n.lines.get(i),t=n.translateBufferLineToString(i,!0);e?.isWrapped?r[r.length-1]+=t:r.push(t)}if(e[1]!==t[1]){let e=n.lines.get(t[1]),i=n.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?r[r.length-1]+=i:r.push(i)}}return r.map(e=>e.replace(zC,` `)).join(uC?`\r
|
|
83
|
+
`))}},Hy=class extends Error{constructor(e,t){super(e),this.name=`ListenerLeakError`,this.stack=t}},Uy=class extends Error{constructor(e,t){super(e),this.name=`ListenerRefusalError`,this.stack=t}},Wy=0,Gy=class{constructor(e){this.value=e,this.id=Wy++}},Ky=2,Z=class{constructor(e){this._size=0,this._options=e,this._leakageMon=Ry>0||this._options?.leakWarningThreshold?new By(e?.onListenerError??ay,this._options?.leakWarningThreshold??Ry):void 0,this._perfMon=this._options?._profName?new Ly(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new Uy(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||ay)(n),Dy.None}if(this._disposed)return Dy.None;t&&(e=e.bind(t));let r=new Gy(e),i;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=Vy.create(),i=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof Gy?(this._deliveryQueue??=new qy,this._listeners=[this._listeners,r]):this._listeners.push(r):(this._options?.onWillAddFirstListener?.(this),this._listeners=r,this._options?.onDidAddFirstListener?.(this)),this._size++;let a=wy(()=>{i?.(),this._removeListener(r)});return n instanceof Ey?n.add(a):Array.isArray(n)&&n.push(a),a},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1){this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),this._size=0;return}let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(this._size*Ky<=t.length){let e=0;for(let n=0;n<t.length;n++)t[n]?t[e++]=t[n]:r&&(this._deliveryQueue.end--,e<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=e}}_deliver(e,t){if(!e)return;let n=this._options?.onListenerError||ay;if(!n)e.value(t);else try{e.value(t)}catch(e){n(e)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){if(this._deliveryQueue?.current&&(this._deliverQueue(this._deliveryQueue),this._perfMon?.stop()),this._perfMon?.start(this._size),this._listeners){if(this._listeners instanceof Gy)this._deliver(this._listeners,e);else{let t=this._deliveryQueue;t.enqueue(this,e,this._listeners.length),this._deliverQueue(t)}}this._perfMon?.stop()}hasListeners(){return this._size>0}},qy=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Jy=class{constructor(){this.mapWindowIdToZoomLevel=new Map,this._onDidChangeZoomLevel=new Z,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=new Map,this._onDidChangeFullscreen=new Z,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};Jy.INSTANCE=new Jy;var Yy=Jy;function Xy(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}Yy.INSTANCE.onDidChangeZoomLevel;function Zy(e){return Yy.INSTANCE.getZoomFactor(e)}Yy.INSTANCE.onDidChangeFullscreen;var Qy=typeof navigator==`object`?navigator.userAgent:``,$y=Qy.indexOf(`Firefox`)>=0,eb=Qy.indexOf(`AppleWebKit`)>=0,tb=Qy.indexOf(`Chrome`)>=0,nb=!tb&&Qy.indexOf(`Safari`)>=0;Qy.indexOf(`Electron/`),Qy.indexOf(`Android`);var rb=!1;if(typeof ky.matchMedia==`function`){let e=ky.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=ky.matchMedia(`(display-mode: fullscreen)`);rb=e.matches,Xy(ky,e,({matches:e})=>{rb&&t.matches||(rb=e)})}function ib(){return rb}var ab=`en`,ob=!1,sb=!1,cb=!1,lb=!1,ub=!1,db=ab,fb,pb=globalThis,mb;typeof pb.vscode<`u`&&typeof pb.vscode.process<`u`?mb=pb.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(mb=process);var hb=typeof mb?.versions?.electron==`string`&&mb?.type===`renderer`;if(typeof mb==`object`){ob=mb.platform===`win32`,sb=mb.platform===`darwin`,cb=mb.platform===`linux`,cb&&mb.env.SNAP&&mb.env.SNAP_REVISION,mb.env.CI||mb.env.BUILD_ARTIFACTSTAGINGDIRECTORY,db=ab;let e=mb.env.VSCODE_NLS_CONFIG;if(e)try{let t=JSON.parse(e);t.userLocale,t.osLocale,db=t.resolvedLanguage||ab,t.languagePack?.translationsConfigFile}catch{}lb=!0}else typeof navigator==`object`&&!hb?(fb=navigator.userAgent,ob=fb.indexOf(`Windows`)>=0,sb=fb.indexOf(`Macintosh`)>=0,(fb.indexOf(`Macintosh`)>=0||fb.indexOf(`iPad`)>=0||fb.indexOf(`iPhone`)>=0)&&navigator.maxTouchPoints&&navigator.maxTouchPoints,cb=fb.indexOf(`Linux`)>=0,fb?.indexOf(`Mobi`),ub=!0,db=globalThis._VSCODE_NLS_LANGUAGE||ab,navigator.language.toLowerCase()):console.error(`Unable to resolve platform.`);var gb=ob,_b=sb,vb=cb,yb=lb;ub&&typeof pb.importScripts==`function`&&pb.origin;var bb=fb,xb=db,Sb;(e=>{function t(){return xb}e.value=t;function n(){return xb.length===2?xb===`en`:xb.length>=3&&xb[0]===`e`&&xb[1]===`n`&&xb[2]===`-`}e.isDefaultVariant=n;function r(){return xb===`en`}e.isDefault=r})(Sb||={});var Cb=typeof pb.postMessage==`function`&&!pb.importScripts;(()=>{if(Cb){let e=[];pb.addEventListener(`message`,t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n<r;n++){let r=e[n];if(r.id===t.data.vscodeScheduleAsyncWork){e.splice(n,1),r.callback();return}}});let t=0;return n=>{let r=++t;e.push({id:r,callback:n}),pb.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})();var wb=!!(bb&&bb.indexOf(`Chrome`)>=0);bb&&bb.indexOf(`Firefox`),!wb&&bb&&bb.indexOf(`Safari`),bb&&bb.indexOf(`Edg/`),bb&&bb.indexOf(`Android`);var Tb=typeof navigator==`object`?navigator:{};yb||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||Tb&&Tb.clipboard&&Tb.clipboard.writeText,yb||Tb&&Tb.clipboard&&Tb.clipboard.readText,yb||ib()||Tb.keyboard,`ontouchstart`in ky||Tb.maxTouchPoints,ky.PointerEvent&&(`ontouchstart`in ky||navigator.maxTouchPoints);var Eb=class{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}},Db=new Eb,Ob=new Eb,kb=new Eb,Ab=Array(230),jb;(e=>{function t(e){return Db.keyCodeToStr(e)}e.toString=t;function n(e){return Db.strToKeyCode(e)}e.fromString=n;function r(e){return Ob.keyCodeToStr(e)}e.toUserSettingsUS=r;function i(e){return kb.keyCodeToStr(e)}e.toUserSettingsGeneral=i;function a(e){return Ob.strToKeyCode(e)||kb.strToKeyCode(e)}e.fromUserSettings=a;function o(e){if(e>=98&&e<=113)return null;switch(e){case 16:return`Up`;case 18:return`Down`;case 15:return`Left`;case 17:return`Right`}return Db.keyCodeToStr(e)}e.toElectronAccelerator=o})(jb||={});var Mb=class e{constructor(e,t,n,r,i){this.ctrlKey=e,this.shiftKey=t,this.altKey=n,this.metaKey=r,this.keyCode=i}equals(t){return t instanceof e&&this.ctrlKey===t.ctrlKey&&this.shiftKey===t.shiftKey&&this.altKey===t.altKey&&this.metaKey===t.metaKey&&this.keyCode===t.keyCode}getHashCode(){return`K${this.ctrlKey?`1`:`0`}${this.shiftKey?`1`:`0`}${this.altKey?`1`:`0`}${this.metaKey?`1`:`0`}${this.keyCode}`}isModifierKey(){return this.keyCode===0||this.keyCode===5||this.keyCode===57||this.keyCode===6||this.keyCode===4}toKeybinding(){return new Nb([this])}isDuplicateModifierCase(){return this.ctrlKey&&this.keyCode===5||this.shiftKey&&this.keyCode===4||this.altKey&&this.keyCode===6||this.metaKey&&this.keyCode===57}},Nb=class{constructor(e){if(e.length===0)throw ly(`chords`);this.chords=e}getHashCode(){let e=``;for(let t=0,n=this.chords.length;t<n;t++)t!==0&&(e+=`;`),e+=this.chords[t].getHashCode();return e}equals(e){if(e===null||this.chords.length!==e.chords.length)return!1;for(let t=0;t<this.chords.length;t++)if(!this.chords[t].equals(e.chords[t]))return!1;return!0}};function Pb(e){if(e.charCode){let t=String.fromCharCode(e.charCode).toUpperCase();return jb.fromString(t)}let t=e.keyCode;if(t===3)return 7;if($y)switch(t){case 59:return 85;case 60:if(vb)return 97;break;case 61:return 86;case 107:return 109;case 109:return 111;case 173:return 88;case 224:if(_b)return 57}else if(eb&&(_b&&t===93||!_b&&t===92))return 57;return Ab[t]||0}var Fb=_b?256:2048,Ib=512,Lb=1024,Rb=_b?2048:256,zb=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.(`AltGraph`),this.keyCode=Pb(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===5,this.altKey=this.altKey||this.keyCode===6,this.shiftKey=this.shiftKey||this.keyCode===4,this.metaKey=this.metaKey||this.keyCode===57,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=0;this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=Fb),this.altKey&&(t|=Ib),this.shiftKey&&(t|=Lb),this.metaKey&&(t|=Rb),t|=e,t}_computeKeyCodeChord(){let e=0;return this.keyCode!==5&&this.keyCode!==4&&this.keyCode!==6&&this.keyCode!==57&&(e=this.keyCode),new Mb(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}},Bb=new WeakMap;function Vb(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,n=e.parent.location;if(t.origin!==`null`&&n.origin!==`null`&&t.origin!==n.origin)return null}catch{return null}return e.parent}var Hb=class{static getSameOriginWindowChain(e){let t=Bb.get(e);if(!t){t=[],Bb.set(e,t);let n=e,r;do r=Vb(n),r?t.push({window:new WeakRef(n),iframeElement:n.frameElement||null}):t.push({window:new WeakRef(n),iframeElement:null}),n=r;while(n)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let n=0,r=0,i=this.getSameOriginWindowChain(e);for(let e of i){let i=e.window.deref();if(n+=i?.scrollY??0,r+=i?.scrollX??0,i===t||!e.iframeElement)break;let a=e.iframeElement.getBoundingClientRect();n+=a.top,r+=a.left}return{top:n,left:r}}},Ub=class{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type===`dblclick`&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX==`number`?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let n=Hb.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=n.left,this.posy-=n.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}},Wb=class{constructor(e,t=0,n=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=n,this.deltaX=t;let r=!1;if(tb){let e=navigator.userAgent.match(/Chrome\/(\d+)/);r=(e?parseInt(e[1]):123)<=122}if(e){let t=e,n=e,i=e.view?.devicePixelRatio||1;if(typeof t.wheelDeltaY<`u`)this.deltaY=r?t.wheelDeltaY/(120*i):t.wheelDeltaY/120;else if(typeof n.VERTICAL_AXIS<`u`&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type===`wheel`){let t=e;this.deltaY=t.deltaMode===t.DOM_DELTA_LINE?$y&&!_b?-e.deltaY/3:-e.deltaY:-e.deltaY/40}if(typeof t.wheelDeltaX<`u`)this.deltaX=nb&&gb?-(t.wheelDeltaX/120):r?t.wheelDeltaX/(120*i):t.wheelDeltaX/120;else if(typeof n.HORIZONTAL_AXIS<`u`&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type===`wheel`){let t=e;this.deltaX=t.deltaMode===t.DOM_DELTA_LINE?$y&&!_b?-e.deltaX/3:-e.deltaX:-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(this.deltaY=r?e.wheelDelta/(120*i):e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}},Gb=Object.freeze(function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}),Kb;(e=>{function t(t){return t===e.None||t===e.Cancelled||t instanceof qb?!0:!t||typeof t!=`object`?!1:typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`}e.isCancellationToken=t,e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:Fy.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:Gb})})(Kb||={});var qb=class{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Gb:(this._emitter||=new Z,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}},Jb=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new dy(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout(()=>{this._token=-1,e()},t)}setIfNotSet(e,t){if(this._isDisposed)throw new dy(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout(()=>{this._token=-1,e()},t))}},Yb=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new dy(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval(()=>{e()},t);this.disposable=wy(()=>{n.clearInterval(r),this.disposable=void 0})}dispose(){this.cancel(),this.isDisposed=!0}};(function(){typeof globalThis.requestIdleCallback!=`function`||globalThis.cancelIdleCallback})();var Xb;(e=>{async function t(e){let t,n=await Promise.all(e.map(e=>e.then(e=>e,e=>{t||=e})));if(typeof t<`u`)throw t;return n}e.settled=t;function n(e){return new Promise(async(t,n)=>{try{await e(t,n)}catch(e){n(e)}})}e.withAsyncBody=n})(Xb||={});var Zb=class e{static fromArray(t){return new e(e=>{e.emitMany(t)})}static fromPromise(t){return new e(async e=>{e.emitMany(await t)})}static fromPromises(t){return new e(async e=>{await Promise.all(t.map(async t=>e.emitOne(await t)))})}static merge(t){return new e(async e=>{await Promise.all(t.map(async t=>{for await(let n of t)e.emitOne(n)}))})}constructor(e,t){this._state=0,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new Z,queueMicrotask(async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}})}[Symbol.asyncIterator](){let e=0;return{next:async()=>{do{if(this._state===2)throw this._error;if(e<this._results.length)return{done:!1,value:this._results[e++]};if(this._state===1)return{done:!0,value:void 0};await Fy.toPromise(this._onStateChanged.event)}while(1)},return:async()=>(this._onReturn?.(),{done:!0,value:void 0})}}static map(t,n){return new e(async e=>{for await(let r of t)e.emitOne(n(r))})}map(t){return e.map(this,t)}static filter(t,n){return new e(async e=>{for await(let r of t)n(r)&&e.emitOne(r)})}filter(t){return e.filter(this,t)}static coalesce(t){return e.filter(t,e=>!!e)}coalesce(){return e.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return e.toPromise(this)}emitOne(e){this._state===0&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===0&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===0&&(this._state=1,this._onStateChanged.fire())}reject(e){this._state===0&&(this._state=2,this._error=e,this._onStateChanged.fire())}};Zb.EMPTY=Zb.fromArray([]);function Qb(e){return $b(e,0)}function $b(e,t){switch(typeof e){case`object`:return e===null?ex(349,t):Array.isArray(e)?rx(e,t):ix(e,t);case`string`:return nx(e,t);case`boolean`:return tx(e,t);case`number`:return ex(e,t);case`undefined`:return ex(937,t);default:return ex(617,t)}}function ex(e,t){return(t<<5)-t+e|0}function tx(e,t){return ex(e?433:863,t)}function nx(e,t){t=ex(149417,t);for(let n=0,r=e.length;n<r;n++)t=ex(e.charCodeAt(n),t);return t}function rx(e,t){return t=ex(104579,t),e.reduce((e,t)=>$b(t,e),t)}function ix(e,t){return t=ex(181387,t),Object.keys(e).sort().reduce((t,n)=>(t=nx(n,t),$b(e[n],t)),t)}var{registerWindow:ax,getWindow:ox,getDocument:sx,getWindows:cx,getWindowsCount:lx,getWindowId:ux,getWindowById:dx,hasWindow:fx,onDidRegisterWindow:px,onWillUnregisterWindow:mx,onDidUnregisterWindow:hx}=function(){let e=new Map,t={window:ky,disposables:new Ey};e.set(ky.vscodeWindowId,t);let n=new Z,r=new Z,i=new Z;function a(n,r){return(typeof n==`number`?e.get(n):void 0)??(r?t:void 0)}return{onDidRegisterWindow:n.event,onWillUnregisterWindow:i.event,onDidUnregisterWindow:r.event,registerWindow(t){if(e.has(t.vscodeWindowId))return Dy.None;let a=new Ey,o={window:t,disposables:a.add(new Ey)};return e.set(t.vscodeWindowId,o),a.add(wy(()=>{e.delete(t.vscodeWindowId),r.fire(t)})),a.add(Q(t,Tx.BEFORE_UNLOAD,()=>{i.fire(t)})),n.fire(o),a},getWindows(){return e.values()},getWindowsCount(){return e.size},getWindowId(e){return e.vscodeWindowId},hasWindow(t){return e.has(t)},getWindowById:a,getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:ky},getDocument(e){return ox(e).document}}}(),gx=class{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}};function Q(e,t,n,r){return new gx(e,t,n,r)}function _x(e,t){return function(n){return t(new Ub(e,n))}}function vx(e){return function(t){return e(new zb(t))}}var yx=function(e,t,n,r){let i=n;return t===`click`||t===`mousedown`||t===`contextmenu`?i=_x(ox(e),n):(t===`keydown`||t===`keypress`||t===`keyup`)&&(i=vx(n)),Q(e,t,i,r)},bx,xx=class extends Yb{constructor(e){super(),this.defaultTarget=e&&ox(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}},Sx=class{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){ay(e)}}static sort(e,t){return t.priority-e.priority}};(function(){let e=new Map,t=new Map,n=new Map,r=new Map,i=i=>{n.set(i,!1);let a=e.get(i)??[];for(t.set(i,a),e.set(i,[]),r.set(i,!0);a.length>0;)a.sort(Sx.sort),a.shift().execute();r.set(i,!1)};bx=(t,r,a=0)=>{let o=ux(t),s=new Sx(r,a),c=e.get(o);return c||(c=[],e.set(o,c)),c.push(s),n.get(o)||(n.set(o,!0),t.requestAnimationFrame(()=>i(o))),s}})();var Cx=class e{constructor(e,t){this.width=e,this.height=t}with(t=this.width,n=this.height){return t!==this.width||n!==this.height?new e(t,n):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(t){return t instanceof e?t:new e(t.width,t.height)}static equals(e,t){return e===t?!0:!e||!t?!1:e.width===t.width&&e.height===t.height}};Cx.None=new Cx(0,0);function wx(e){let t=e.getBoundingClientRect(),n=ox(e);return{left:t.left+n.scrollX,top:t.top+n.scrollY,width:t.width,height:t.height}}new class{constructor(){this.mutationObservers=new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=new Map,this.mutationObservers.set(e,r));let i=Qb(n),a=r.get(i);if(a)a.users+=1;else{let o=new Z,s=new MutationObserver(e=>o.fire(e));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add(wy(()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))})),r.set(i,a)}return a.onDidMutate}};var Tx={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:eb?`webkitAnimationStart`:`animationstart`,ANIMATION_END:eb?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:eb?`webkitAnimationIteration`:`animationiteration`},Ex=class{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=Dx(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=Dx(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=Dx(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=Dx(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=Dx(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=Dx(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=Dx(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=Dx(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=Dx(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=Dx(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=Dx(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=Dx(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=Dx(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=Dx(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}};function Dx(e){return typeof e==`number`?`${e}px`:e}function Ox(e){return new Ex(e)}var kx=class{constructor(){this._hooks=new Ey,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add(wy(()=>{try{e.releasePointerCapture(t)}catch{}}))}catch{a=ox(e)}this._hooks.add(Q(a,Tx.POINTER_MOVE,e=>{e.buttons===n?(e.preventDefault(),this._pointerMoveCallback(e)):this.stopMonitoring(!0)})),this._hooks.add(Q(a,Tx.POINTER_UP,e=>this.stopMonitoring(!0)))}};function Ax(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}}var jx;(e=>(e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`))(jx||={});var Mx=class e extends Dy{constructor(){super(),this.dispatched=!1,this.targets=new My,this.ignoreTargets=new My,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(Fy.runAndSubscribe(px,({window:e,disposables:t})=>{t.add(Q(e.document,`touchstart`,e=>this.onTouchStart(e),{passive:!1})),t.add(Q(e.document,`touchend`,t=>this.onTouchEnd(e,t))),t.add(Q(e.document,`touchmove`,e=>this.onTouchMove(e),{passive:!1}))},{window:ky,disposables:this._store}))}static addTarget(t){return e.isTouchDevice()?(e.INSTANCE||=xy(new e),wy(e.INSTANCE.targets.push(t))):Dy.None}static ignoreTarget(t){return e.isTouchDevice()?(e.INSTANCE||=xy(new e),wy(e.INSTANCE.ignoreTargets.push(t))):Dy.None}static isTouchDevice(){return`ontouchstart`in ky||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n<r;n++){let r=e.targetTouches.item(n);this.activeTouches[r.identifier]={id:r.identifier,initialTarget:r.target,initialTimeStamp:t,initialPageX:r.pageX,initialPageY:r.pageY,rollingTimestamps:[t],rollingPageX:[r.pageX],rollingPageY:[r.pageY]};let i=this.newGestureEvent(jx.Start,r.target);i.pageX=r.pageX,i.pageY=r.pageY,this.dispatchEvent(i)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}onTouchEnd(t,n){let r=Date.now(),i=Object.keys(this.activeTouches).length;for(let a=0,o=n.changedTouches.length;a<o;a++){let o=n.changedTouches.item(a);if(!this.activeTouches.hasOwnProperty(String(o.identifier))){console.warn(`move of an UNKNOWN touch`,o);continue}let s=this.activeTouches[o.identifier],c=Date.now()-s.initialTimeStamp;if(c<e.HOLD_DELAY&&Math.abs(s.initialPageX-fy(s.rollingPageX))<30&&Math.abs(s.initialPageY-fy(s.rollingPageY))<30){let e=this.newGestureEvent(jx.Tap,s.initialTarget);e.pageX=fy(s.rollingPageX),e.pageY=fy(s.rollingPageY),this.dispatchEvent(e)}else if(c>=e.HOLD_DELAY&&Math.abs(s.initialPageX-fy(s.rollingPageX))<30&&Math.abs(s.initialPageY-fy(s.rollingPageY))<30){let e=this.newGestureEvent(jx.Contextmenu,s.initialTarget);e.pageX=fy(s.rollingPageX),e.pageY=fy(s.rollingPageY),this.dispatchEvent(e)}else if(i===1){let e=fy(s.rollingPageX),n=fy(s.rollingPageY),i=fy(s.rollingTimestamps)-s.rollingTimestamps[0],a=e-s.rollingPageX[0],o=n-s.rollingPageY[0],c=[...this.targets].filter(e=>s.initialTarget instanceof Node&&e.contains(s.initialTarget));this.inertia(t,c,r,Math.abs(a)/i,a>0?1:-1,e,Math.abs(o)/i,o>0?1:-1,n)}this.dispatchEvent(this.newGestureEvent(jx.End,s.initialTarget)),delete this.activeTouches[o.identifier]}this.dispatched&&=(n.preventDefault(),n.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(t){if(t.type===jx.Tap){let n=new Date().getTime(),r=0;r=n-this._lastSetTapCountTime>e.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=n,t.tapCount=r}else(t.type===jx.Change||t.type===jx.Contextmenu)&&(this._lastSetTapCountTime=0);if(t.initialTarget instanceof Node){for(let e of this.ignoreTargets)if(e.contains(t.initialTarget))return;let e=[];for(let n of this.targets)if(n.contains(t.initialTarget)){let r=0,i=t.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;e.push([r,n])}e.sort((e,t)=>e[0]-t[0]);for(let[n,r]of e)r.dispatchEvent(t),this.dispatched=!0}}inertia(t,n,r,i,a,o,s,c,l){this.handle=bx(t,()=>{let u=Date.now(),d=u-r,f=0,p=0,m=!0;i+=e.SCROLL_FRICTION*d,s+=e.SCROLL_FRICTION*d,i>0&&(m=!1,f=a*i*d),s>0&&(m=!1,p=c*s*d);let h=this.newGestureEvent(jx.Change);h.translationX=f,h.translationY=p,n.forEach(e=>e.dispatchEvent(h)),m||this.inertia(t,n,u,i,a,o+f,s,c,l+p)})}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n<r;n++){let r=e.changedTouches.item(n);if(!this.activeTouches.hasOwnProperty(String(r.identifier))){console.warn(`end of an UNKNOWN touch`,r);continue}let i=this.activeTouches[r.identifier],a=this.newGestureEvent(jx.Change,i.initialTarget);a.translationX=r.pageX-fy(i.rollingPageX),a.translationY=r.pageY-fy(i.rollingPageY),a.pageX=r.pageX,a.pageY=r.pageY,this.dispatchEvent(a),i.rollingPageX.length>3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}};Mx.SCROLL_FRICTION=-.005,Mx.HOLD_DELAY=700,Mx.CLEAR_TAP_COUNT_TIME=400,dv([Ax],Mx,`isTouchDevice`,1);var Nx=Mx,Px=class extends Dy{onclick(e,t){this._register(Q(e,Tx.CLICK,n=>t(new Ub(ox(e),n))))}onmousedown(e,t){this._register(Q(e,Tx.MOUSE_DOWN,n=>t(new Ub(ox(e),n))))}onmouseover(e,t){this._register(Q(e,Tx.MOUSE_OVER,n=>t(new Ub(ox(e),n))))}onmouseleave(e,t){this._register(Q(e,Tx.MOUSE_LEAVE,n=>t(new Ub(ox(e),n))))}onkeydown(e,t){this._register(Q(e,Tx.KEY_DOWN,e=>t(new zb(e))))}onkeyup(e,t){this._register(Q(e,Tx.KEY_UP,e=>t(new zb(e))))}oninput(e,t){this._register(Q(e,Tx.INPUT,t))}onblur(e,t){this._register(Q(e,Tx.BLUR,t))}onfocus(e,t){this._register(Q(e,Tx.FOCUS,t))}onchange(e,t){this._register(Q(e,Tx.CHANGE,t))}ignoreGesture(e){return Nx.ignoreTarget(e)}},Fx=11,Ix=class extends Px{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,typeof e.top<`u`&&(this.bgDomNode.style.top=`0px`),typeof e.left<`u`&&(this.bgDomNode.style.left=`0px`),typeof e.bottom<`u`&&(this.bgDomNode.style.bottom=`0px`),typeof e.right<`u`&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=Fx+`px`,this.domNode.style.height=Fx+`px`,typeof e.top<`u`&&(this.domNode.style.top=e.top+`px`),typeof e.left<`u`&&(this.domNode.style.left=e.left+`px`),typeof e.bottom<`u`&&(this.domNode.style.bottom=e.bottom+`px`),typeof e.right<`u`&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new kx),this._register(yx(this.bgDomNode,Tx.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._register(yx(this.domNode,Tx.POINTER_DOWN,e=>this._arrowPointerDown(e))),this._pointerdownRepeatTimer=this._register(new xx),this._pointerdownScheduleRepeatTimer=this._register(new Jb)}_arrowPointerDown(e){e.target&&e.target instanceof Element&&(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet(()=>{this._pointerdownRepeatTimer.cancelAndSet(()=>this._onActivate(),1e3/24,ox(e))},200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{},()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()}),e.preventDefault())}},Lx=class e{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(t,n){return new e(this._forceIntegerValues,typeof t.width<`u`?t.width:this.width,typeof t.scrollWidth<`u`?t.scrollWidth:this.scrollWidth,n?this.rawScrollLeft:this.scrollLeft,typeof t.height<`u`?t.height:this.height,typeof t.scrollHeight<`u`?t.scrollHeight:this.scrollHeight,n?this.rawScrollTop:this.scrollTop)}withScrollPosition(t){return new e(this._forceIntegerValues,this.width,this.scrollWidth,typeof t.scrollLeft<`u`?t.scrollLeft:this.rawScrollLeft,this.height,this.scrollHeight,typeof t.scrollTop<`u`?t.scrollTop:this.rawScrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}},Rx=class extends Dy{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new Lx(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:typeof e.scrollLeft>`u`?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:typeof e.scrollTop>`u`?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new Hx(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=Hx.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);if(this._setState(t,!0),this._smoothScrolling){if(e.isDone){this._smoothScrolling.dispose(),this._smoothScrolling=null;return}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame(()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})}}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}},zx=class{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}};function Bx(e,t){let n=t-e;return function(t){return e+n*Wx(t)}}function Vx(e,t,n){return function(r){return r<n?e(r/n):t((r-n)/(1-n))}}var Hx=class e{constructor(e,t,n,r){this.from=e,this.to=t,this.duration=r,this.startTime=n,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,n){if(Math.abs(e-t)>2.5*n){let r,i;return e<t?(r=e+.75*n,i=t-.75*n):(r=e-.75*n,i=t+.75*n),Vx(Bx(e,r),Bx(i,t),.33)}return Bx(e,t)}dispose(){this.animationFrameDisposable!==null&&(this.animationFrameDisposable.dispose(),this.animationFrameDisposable=null)}acceptScrollDimensions(e){this.to=e.withScrollPosition(this.to),this._initAnimations()}tick(){return this._tick(Date.now())}_tick(e){let t=(e-this.startTime)/this.duration;return t<1?new zx(this.scrollLeft(t),this.scrollTop(t),!1):new zx(this.to.scrollLeft,this.to.scrollTop,!0)}combine(t,n,r){return e.start(t,n,r)}static start(t,n,r){r+=10;let i=Date.now()-10;return new e(t,n,i,r)}};function Ux(e){return e**3}function Wx(e){return 1-Ux(1-e)}var Gx=class extends Dy{constructor(e,t,n){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=n,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new Jb)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility===2?!1:this._visibility===3||this._rawShouldBeVisible}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){this._isNeeded?this._shouldBeVisible?this._reveal():this._hide(!0):this._hide(!1)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet(()=>{this._domNode?.setClassName(this._visibleClassName)},0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}},Kx=140,qx=class extends Px{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new Gx(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new kx),this._shouldRender=!0,this.domNode=Ox(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register(Q(this.domNode.domNode,Tx.POINTER_DOWN,e=>this._domNodePointerDown(e)))}_createArrow(e){let t=this._register(new Ix(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=Ox(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(Q(this.slider.domNode,Tx.POINTER_DOWN,e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))})),this.onclick(this.slider.domNode,e=>{e.leftButton&&e.stopPropagation()})}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=wx(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!e.target||!(e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(gb&&a>Kx){this._setDesiredScrollPositionNow(r.getScrollPosition());return}let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))},()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()}),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}},Jx=class e{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new e(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let t=e._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=t.computedAvailableSize,this._computedIsNeeded=t.computedIsNeeded,this._computedSliderSize=t.computedSliderSize,this._computedSliderRatio=t.computedSliderRatio,this._computedSliderPosition=t.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t<this._computedSliderPosition?n-=this._visibleSize:n+=this._visibleSize,n}getDesiredScrollPositionFromDelta(e){if(!this._computedIsNeeded)return 0;let t=this._computedSliderPosition+e;return Math.round(t/this._computedSliderRatio)}},Yx=class extends qx{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new Jx(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===2?0:t.horizontalScrollbarSize,t.vertical===2?0:t.verticalScrollbarSize,r.width,r.scrollWidth,i.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:`horizontal`,scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===2?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}},Xx=class extends qx{constructor(e,t,n){let r=e.getScrollDimensions(),i=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new Jx(t.verticalHasArrows?t.arrowSize:0,t.vertical===2?0:t.verticalScrollbarSize,0,r.height,r.scrollHeight,i.scrollTop),visibility:t.vertical,extraScrollbarClassName:`vertical`,scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===2?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}},Zx=500,Qx=50,$x=!0,eS=class{constructor(e,t,n){this.timestamp=e,this.deltaX=t,this.deltaY=n,this.score=0}},tS=class{constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let e=1,t=0,n=1,r=this._rear;do{let i=r===this._front?e:2**-n;if(e-=i,t+=this._memory[r].score*i,r===this._front)break;r=(this._capacity+r-1)%this._capacity,n++}while(1);return t<=.5}acceptStandardWheelEvent(e){if(tb){let t=Zy(ox(e.browserEvent));this.accept(Date.now(),e.deltaX*t,e.deltaY*t)}else this.accept(Date.now(),e.deltaX,e.deltaY)}accept(e,t,n){let r=null,i=new eS(e,t,n);this._front===-1&&this._rear===-1?(this._memory[0]=i,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=i),i.score=this._computeScore(i,r)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if((!this._isAlmostInt(e.deltaX)||!this._isAlmostInt(e.deltaY))&&(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s===0&&u%c===0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}};tS.INSTANCE=new tS;var nS=tS,rS=class extends Px{constructor(e,t,n){super(),this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new Z),this.onWillScroll=this._onWillScroll.event,this._options=aS(t),this._scrollable=n,this._register(this._scrollable.onScroll(e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)}));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new Xx(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new Yx(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=Ox(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=Ox(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=Ox(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,e=>this._onMouseOver(e)),this.onmouseleave(this._listenOnDomNode,e=>this._onMouseLeave(e)),this._hideTimeout=this._register(new Jb),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}get options(){return this._options}dispose(){this._mouseWheelToDispose=Sy(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,_b&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){typeof e.handleMouseWheel<`u`&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),typeof e.mouseWheelScrollSensitivity<`u`&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),typeof e.fastScrollSensitivity<`u`&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),typeof e.scrollPredominantAxis<`u`&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),typeof e.horizontal<`u`&&(this._options.horizontal=e.horizontal),typeof e.vertical<`u`&&(this._options.vertical=e.vertical),typeof e.horizontalScrollbarSize<`u`&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),typeof e.verticalScrollbarSize<`u`&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),typeof e.scrollByPage<`u`&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new Wb(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=Sy(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(Q(this._listenOnDomNode,Tx.MOUSE_WHEEL,e=>{this._onMouseWheel(new Wb(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=nS.INSTANCE;$x&&t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!_b&&e.browserEvent&&e.browserEvent.shiftKey;(this._options.scrollYToX||a)&&!i&&(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=Qx*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=Qx*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&($x&&this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){!this._mouseIsOver&&!this._isDragging&&(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){!this._mouseIsOver&&!this._isDragging&&this._hideTimeout.cancelAndSet(()=>this._hide(),Zx)}},iS=class extends rS{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}};function aS(e){let t={lazyRender:typeof e.lazyRender<`u`&&e.lazyRender,className:typeof e.className<`u`?e.className:``,useShadows:typeof e.useShadows<`u`?e.useShadows:!0,handleMouseWheel:typeof e.handleMouseWheel<`u`?e.handleMouseWheel:!0,flipAxes:typeof e.flipAxes<`u`&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:typeof e.consumeMouseWheelIfScrollbarIsNeeded<`u`&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:typeof e.alwaysConsumeMouseWheel<`u`&&e.alwaysConsumeMouseWheel,scrollYToX:typeof e.scrollYToX<`u`&&e.scrollYToX,mouseWheelScrollSensitivity:typeof e.mouseWheelScrollSensitivity<`u`?e.mouseWheelScrollSensitivity:1,fastScrollSensitivity:typeof e.fastScrollSensitivity<`u`?e.fastScrollSensitivity:5,scrollPredominantAxis:typeof e.scrollPredominantAxis<`u`?e.scrollPredominantAxis:!0,mouseWheelSmoothScroll:typeof e.mouseWheelSmoothScroll<`u`?e.mouseWheelSmoothScroll:!0,arrowSize:typeof e.arrowSize<`u`?e.arrowSize:11,listenOnDomNode:typeof e.listenOnDomNode<`u`?e.listenOnDomNode:null,horizontal:typeof e.horizontal<`u`?e.horizontal:1,horizontalScrollbarSize:typeof e.horizontalScrollbarSize<`u`?e.horizontalScrollbarSize:10,horizontalSliderSize:typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:0,horizontalHasArrows:typeof e.horizontalHasArrows<`u`&&e.horizontalHasArrows,vertical:typeof e.vertical<`u`?e.vertical:1,verticalScrollbarSize:typeof e.verticalScrollbarSize<`u`?e.verticalScrollbarSize:10,verticalHasArrows:typeof e.verticalHasArrows<`u`&&e.verticalHasArrows,verticalSliderSize:typeof e.verticalSliderSize<`u`?e.verticalSliderSize:0,scrollByPage:typeof e.scrollByPage<`u`&&e.scrollByPage};return t.horizontalSliderSize=typeof e.horizontalSliderSize<`u`?e.horizontalSliderSize:t.horizontalScrollbarSize,t.verticalSliderSize=typeof e.verticalSliderSize<`u`?e.verticalSliderSize:t.verticalScrollbarSize,_b&&(t.className+=` mac`),t}var oS=class extends Dy{constructor(e,t,n,r,i,a,o,s){super(),this._bufferService=n,this._optionsService=o,this._renderService=s,this._onRequestScrollLines=this._register(new Z),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let c=this._register(new Rx({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>bx(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,()=>{c.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)})),this._scrollableElement=this._register(new iS(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},c)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],()=>this._scrollableElement.updateOptions(this._getChangeOptions()))),this._register(i.onProtocolChange(e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(e&16)})})),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(Fy.runAndSubscribe(a.onChangeColors,()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css})),e.appendChild(this._scrollableElement.getDomNode()),this._register(wy(()=>this._scrollableElement.getDomNode().remove())),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register(wy(()=>this._styleElement.remove())),this._register(Fy.runAndSubscribe(a.onChangeColors,()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(`
|
|
84
|
+
`)})),this._register(this._bufferService.onResize(()=>this.queueSync())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._latestYDisp=void 0,this.queueSync()})),this._register(this._bufferService.onScroll(()=>this._sync())),this._register(this._scrollableElement.onScroll(e=>this._handleScroll(e)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback(()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)}))}_sync(e=this._bufferService.buffer.ydisp){!this._renderService||this._isSyncing||(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};oS=dv([X(2,Rv),X(3,Zv),X(4,zv),X(5,ny),X(6,Wv),X(7,$v)],oS);var sS=class extends Dy{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange(()=>this._doRefreshDecorations())),this._register(this._renderService.onDimensionsChange(()=>{this._dimensionsChanged=!0,this._queueRefresh()})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt})),this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh())),this._register(this._decorationService.onDecorationRemoved(e=>this._removeDecoration(e))),this._register(wy(()=>{this._container.remove(),this._decorationElements.clear()}))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback(()=>{this._doRefreshDecorations(),this._animationFrame=void 0}))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,t.style.top=`${(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height}px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose(()=>{this._decorationElements.delete(e),n.remove()})),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=`${(e.options.height||1)*this._renderService.dimensions.css.cell.height}px`,n.style.top=`${t*this._renderService.dimensions.css.cell.height}px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?`${n*this._renderService.dimensions.css.cell.width}px`:``:t.style.left=n?`${n*this._renderService.dimensions.css.cell.width}px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};sS=dv([X(1,Rv),X(2,Zv),X(3,qv),X(4,$v)],sS);var cS=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position)){this._addLineToZone(t,e.marker.line);return}}if(this._zonePoolIndex<this._zonePool.length){this._zonePool[this._zonePoolIndex].color=e.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=e.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=e.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=e.marker.line,this._zones.push(this._zonePool[this._zonePoolIndex++]);return}this._zones.push({color:e.options.overviewRulerOptions.color,position:e.options.overviewRulerOptions.position,startBufferLine:e.marker.line,endBufferLine:e.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(e){this._linePadding=e}_lineIntersectsZone(e,t){return t>=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}},lS={full:0,left:0,center:0,right:0},uS={full:0,left:0,center:0,right:0},dS={full:0,left:0,center:0,right:0},fS=class extends Dy{constructor(e,t,n,r,i,a,o,s){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=a,this._themeService=o,this._coreBrowserService=s,this._colorZoneStore=new cS,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register(wy(()=>this._canvas?.remove()));let c=this._canvas.getContext(`2d`);if(c)this._ctx=c;else throw Error(`Ctx cannot be null`);this._register(this._decorationService.onDecorationRegistered(()=>this._queueRefresh(void 0,!0))),this._register(this._decorationService.onDecorationRemoved(()=>this._queueRefresh(void 0,!0))),this._register(this._renderService.onRenderedViewportChange(()=>this._queueRefresh())),this._register(this._bufferService.buffers.onBufferActivate(()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`})),this._register(this._bufferService.onScroll(()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})),this._register(this._renderService.onRender(()=>{(!this._containerHeight||this._containerHeight!==this._screenElement.clientHeight)&&(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)})),this._register(this._coreBrowserService.onDprChange(()=>this._queueRefresh(!0))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,()=>this._queueRefresh(!0))),this._register(this._themeService.onChangeColors(()=>this._queueRefresh())),this._queueRefresh(!0)}get _width(){return this._optionsService.options.overviewRuler?.width||0}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);uS.full=this._canvas.width,uS.left=e,uS.center=t,uS.right=e,this._refreshDrawHeightConstants(),dS.full=1,dS.left=1,dS.center=1+uS.left,dS.right=1+uS.left+uS.center}_refreshDrawHeightConstants(){lS.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);lS.left=t,lS.center=t,lS.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*lS.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*lS.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*lS.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*lS.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(dS[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-lS[e.position||`full`]/2),uS[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+lS[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};fS=dv([X(2,Rv),X(3,qv),X(4,$v),X(5,Wv),X(6,ny),X(7,Zv)],fS);var $;(e=>(e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=`
|
|
85
|
+
`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``))($||={});var pS;(e=>(e.PAD=``,e.HOP=``,e.BPH=``,e.NBH=``,e.IND=``,e.NEL=`
`,e.SSA=``,e.ESA=``,e.HTS=``,e.HTJ=``,e.VTS=``,e.PLD=``,e.PLU=``,e.RI=``,e.SS2=``,e.SS3=``,e.DCS=``,e.PU1=``,e.PU2=``,e.STS=``,e.CCH=``,e.MW=``,e.SPA=``,e.EPA=``,e.SOS=``,e.SGCI=``,e.SCI=``,e.CSI=``,e.ST=``,e.OSC=``,e.PM=``,e.APC=``))(pS||={});var mS;(e=>e.ST=`${$.ESC}\\`)(mS||={});var hS=class{constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout(()=>{this._compositionPosition.end=this._textarea.value.length},0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=!1;let t;e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}},0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.length<e.length?this._coreService.triggerDataEvent(`${$.DEL}`,!0):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,!0)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let e=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),t=this._renderService.dimensions.css.cell.height,n=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,r=e*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=r+`px`,this._compositionView.style.top=n+`px`,this._compositionView.style.height=t+`px`,this._compositionView.style.lineHeight=t+`px`,this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+`px`;let i=this._compositionView.getBoundingClientRect();this._textarea.style.left=r+`px`,this._textarea.style.top=n+`px`,this._textarea.style.width=Math.max(i.width,1)+`px`,this._textarea.style.height=Math.max(i.height,1)+`px`,this._textarea.style.lineHeight=i.height+`px`}e||setTimeout(()=>this.updateCompositionElements(!0),0)}}};hS=dv([X(2,Rv),X(3,Wv),X(4,Bv),X(5,$v)],hS);var gS=0,_S=0,vS=0,yS=0,bS={css:`#00000000`,rgba:0},xS;(e=>{function t(e,t,n,r){return r===void 0?`#${ES(e)}${ES(t)}${ES(n)}`:`#${ES(e)}${ES(t)}${ES(n)}${ES(r)}`}e.toCss=t;function n(e,t,n,r=255){return(e<<24|t<<16|n<<8|r)>>>0}e.toRgba=n;function r(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}e.toColor=r})(xS||={});var SS;(e=>{function t(e,t){if(yS=(t.rgba&255)/255,yS===1)return{css:t.css,rgba:t.rgba};let n=t.rgba>>24&255,r=t.rgba>>16&255,i=t.rgba>>8&255,a=e.rgba>>24&255,o=e.rgba>>16&255,s=e.rgba>>8&255;return gS=a+Math.round((n-a)*yS),_S=o+Math.round((r-o)*yS),vS=s+Math.round((i-s)*yS),{css:xS.toCss(gS,_S,vS),rgba:xS.toRgba(gS,_S,vS)}}e.blend=t;function n(e){return(e.rgba&255)==255}e.isOpaque=n;function r(e,t,n){let r=TS.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return xS.toColor(r>>24&255,r>>16&255,r>>8&255)}e.ensureContrastRatio=r;function i(e){let t=(e.rgba|255)>>>0;return[gS,_S,vS]=TS.toChannels(t),{css:xS.toCss(gS,_S,vS),rgba:t}}e.opaque=i;function a(e,t){return yS=Math.round(t*255),[gS,_S,vS]=TS.toChannels(e.rgba),{css:xS.toCss(gS,_S,vS,yS),rgba:xS.toRgba(gS,_S,vS,yS)}}e.opacity=a;function o(e,t){return yS=e.rgba&255,a(e,yS*t/255)}e.multiplyOpacity=o;function s(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}e.toColorRGB=s})(SS||={});var CS;(e=>{let t,n;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let r=e.getContext(`2d`,{willReadFrequently:!0});r&&(t=r,t.globalCompositeOperation=`copy`,n=t.createLinearGradient(0,0,1,1))}catch{}function r(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return gS=parseInt(e.slice(1,2).repeat(2),16),_S=parseInt(e.slice(2,3).repeat(2),16),vS=parseInt(e.slice(3,4).repeat(2),16),xS.toColor(gS,_S,vS);case 5:return gS=parseInt(e.slice(1,2).repeat(2),16),_S=parseInt(e.slice(2,3).repeat(2),16),vS=parseInt(e.slice(3,4).repeat(2),16),yS=parseInt(e.slice(4,5).repeat(2),16),xS.toColor(gS,_S,vS,yS);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let r=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(r)return gS=parseInt(r[1]),_S=parseInt(r[2]),vS=parseInt(r[3]),yS=Math.round((r[5]===void 0?1:parseFloat(r[5]))*255),xS.toColor(gS,_S,vS,yS);if(!t||!n||(t.fillStyle=n,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[gS,_S,vS,yS]=t.getImageData(0,0,1,1).data,yS!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:xS.toRgba(gS,_S,vS,yS),css:e}}e.toColor=r})(CS||={});var wS;(e=>{function t(e){return n(e>>16&255,e>>8&255,e&255)}e.relativeLuminance=t;function n(e,t,n){let r=e/255,i=t/255,a=n/255,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4,s=i<=.03928?i/12.92:((i+.055)/1.055)**2.4,c=a<=.03928?a/12.92:((a+.055)/1.055)**2.4;return o*.2126+s*.7152+c*.0722}e.relativeLuminance2=n})(wS||={});var TS;(e=>{function t(e,t){if(yS=(t&255)/255,yS===1)return t;let n=t>>24&255,r=t>>16&255,i=t>>8&255,a=e>>24&255,o=e>>16&255,s=e>>8&255;return gS=a+Math.round((n-a)*yS),_S=o+Math.round((r-o)*yS),vS=s+Math.round((i-s)*yS),xS.toRgba(gS,_S,vS)}e.blend=t;function n(e,t,n){let a=wS.relativeLuminance(e>>8),o=wS.relativeLuminance(t>>8);if(DS(a,o)<n){if(o<a){let o=r(e,t,n),s=DS(a,wS.relativeLuminance(o>>8));if(s<n){let r=i(e,t,n);return s>DS(a,wS.relativeLuminance(r>>8))?o:r}return o}let s=i(e,t,n),c=DS(a,wS.relativeLuminance(s>>8));if(c<n){let i=r(e,t,n);return c>DS(a,wS.relativeLuminance(i>>8))?s:i}return s}}e.ensureContrastRatio=n;function r(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=DS(wS.relativeLuminance2(o,s,c),wS.relativeLuminance2(r,i,a));for(;l<n&&(o>0||s>0||c>0);)o-=Math.max(0,Math.ceil(o*.1)),s-=Math.max(0,Math.ceil(s*.1)),c-=Math.max(0,Math.ceil(c*.1)),l=DS(wS.relativeLuminance2(o,s,c),wS.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.reduceLuminance=r;function i(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,l=DS(wS.relativeLuminance2(o,s,c),wS.relativeLuminance2(r,i,a));for(;l<n&&(o<255||s<255||c<255);)o=Math.min(255,o+Math.ceil((255-o)*.1)),s=Math.min(255,s+Math.ceil((255-s)*.1)),c=Math.min(255,c+Math.ceil((255-c)*.1)),l=DS(wS.relativeLuminance2(o,s,c),wS.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}e.increaseLuminance=i;function a(e){return[e>>24&255,e>>16&255,e>>8&255,e&255]}e.toChannels=a})(TS||={});function ES(e){let t=e.toString(16);return t.length<2?`0`+t:t}function DS(e,t){return e<t?(t+.05)/(e+.05):(e+.05)/(t+.05)}var OS=class extends kv{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}},kS=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new jv}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t<this._characterJoiners.length;t++)if(this._characterJoiners[t].id===e)return this._characterJoiners.splice(t,1),!0;return!1}getJoinedCharacters(e){if(this._characterJoiners.length===0)return[];let t=this._bufferService.buffer.lines.get(e);if(!t||t.length===0)return[];let n=[],r=t.translateToString(!0),i=0,a=0,o=0,s=t.getFg(0),c=t.getBg(0);for(let e=0;e<t.getTrimmedLength();e++)if(t.loadCell(e,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==s||this._workCell.bg!==c){if(e-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}i=e,o=a,s=this._workCell.fg,c=this._workCell.bg}a+=this._workCell.getChars().length||Ov.length}if(this._bufferService.cols-i>1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t<e.length;t++)n.push(e[t])}return n}_getJoinedRanges(e,t,n,r,i){let a=e.substring(t,n),o=[];try{o=this._characterJoiners[0].handler(a)}catch(e){console.error(e)}for(let e=1;e<this._characterJoiners.length;e++)try{let t=this._characterJoiners[e].handler(a);for(let e=0;e<t.length;e++)kS._mergeRanges(o,t[e])}catch(e){console.error(e)}return this._stringRangesToCellRanges(o,r,i),o}_stringRangesToCellRanges(e,t,n){let r=0,i=!1,a=0,o=e[r];if(o){for(let s=n;s<this._bufferService.cols;s++){let n=t.getWidth(s),c=t.getString(s).length||Ov.length;if(n!==0){if(!i&&o[0]<=a&&(o[0]=s,i=!0),o[1]<=a){if(o[1]=s,o=e[++r],!o)break;o[0]<=a?(o[0]=s,i=!0):i=!1}a+=c}}o&&(o[1]=this._bufferService.cols)}}static _mergeRanges(e,t){let n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(n){if(t[1]<=i[0])return e[r-1][1]=t[1],e;if(t[1]<=i[1])return e[r-1][1]=Math.max(t[1],i[1]),e.splice(r,1),e;e.splice(r,1),r--}else{if(t[1]<=i[0])return e.splice(r,0,t),e;if(t[1]<=i[1])return i[0]=Math.min(t[0],i[0]),e;t[0]<i[1]&&(i[0]=Math.min(t[0],i[0]),n=!0);continue}}return n?e[e.length-1][1]=t[1]:e.push(t),e}};kS=dv([X(0,Rv)],kS);function AS(e){return 57508<=e&&e<=57558}function jS(e){return 9472<=e&&e<=9631}function MS(e){return AS(e)||jS(e)}function NS(){return{css:{canvas:PS(),cell:PS()},device:{canvas:PS(),cell:PS(),char:{width:0,height:0,left:0,top:0}}}}function PS(){return{width:0,height:0}}var FS=class{constructor(e,t,n,r,i,a,o){this._document=e,this._characterJoinerService=t,this._optionsService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._themeService=o,this._workCell=new jv,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,n){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=n}createRow(e,t,n,r,i,a,o,s,c,l,u){let d=[],f=this._characterJoinerService.getJoinedCharacters(t),p=this._themeService.colors,m=e.getNoBgTrimmedLength();n&&m<a+1&&(m=a+1);let h,g=0,_=``,v=0,y=0,b=0,x=0,S=!1,C=0,w=!1,T=0,E=0,D=[],O=l!==-1&&u!==-1;for(let k=0;k<m;k++){e.loadCell(k,this._workCell);let m=this._workCell.getWidth();if(m===0)continue;let A=!1,ee=k>=E,j=k,M=this._workCell;if(f.length>0&&k===f[0][0]&&ee){let r=f.shift(),i=this._isCellInSelection(r[0],t);for(v=r[0]+1;v<r[1];v++)ee&&=i===this._isCellInSelection(v,t);ee&&=!n||a<r[0]||a>=r[1],ee?(A=!0,M=new OS(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),j=r[1]-1,m=M.getWidth()):E=r[1]}let N=this._isCellInSelection(k,t),te=n&&k===a,ne=O&&k>=l&&k<=u,re=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{re=!0});let ie=M.getChars()||Ov;if(ie===` `&&(M.isUnderline()||M.isOverline())&&(ie=`\xA0`),T=m*s-c.get(ie,M.isBold(),M.isItalic()),!h)h=this._document.createElement(`span`);else if(g&&(N&&w||!N&&!w&&M.bg===y)&&(N&&w&&p.selectionForeground||M.fg===b)&&M.extended.ext===x&&ne===S&&T===C&&!te&&!A&&!re&&ee){M.isInvisible()?_+=Ov:_+=ie,g++;continue}else g&&(h.textContent=_),h=this._document.createElement(`span`),g=0,_=``;if(y=M.bg,b=M.fg,x=M.extended.ext,S=ne,C=T,w=N,A&&a>=k&&a<=j&&(a=k),!this._coreService.isCursorHidden&&te&&this._coreService.isCursorInitialized){if(D.push(`xterm-cursor`),this._coreBrowserService.isFocused)o&&D.push(`xterm-cursor-blink`),D.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:D.push(`xterm-cursor-outline`);break;case`block`:D.push(`xterm-cursor-block`);break;case`bar`:D.push(`xterm-cursor-bar`);break;case`underline`:D.push(`xterm-cursor-underline`)}}if(M.isBold()&&D.push(`xterm-bold`),M.isItalic()&&D.push(`xterm-italic`),M.isDim()&&D.push(`xterm-dim`),_=M.isInvisible()?Ov:M.getChars()||Ov,M.isUnderline()&&(D.push(`xterm-underline-${M.extended.underlineStyle}`),_===` `&&(_=`\xA0`),!M.isUnderlineColorDefault())){if(M.isUnderlineColorRGB())h.style.textDecorationColor=`rgb(${kv.toColorRGB(M.getUnderlineColor()).join(`,`)})`;else{let e=M.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&M.isBold()&&e<8&&(e+=8),h.style.textDecorationColor=p.ansi[e].css}}M.isOverline()&&(D.push(`xterm-overline`),_===` `&&(_=`\xA0`)),M.isStrikethrough()&&D.push(`xterm-strikethrough`),ne&&(h.style.textDecoration=`underline`);let ae=M.getFgColor(),oe=M.getFgColorMode(),se=M.getBgColor(),ce=M.getBgColorMode(),le=!!M.isInverse();if(le){let e=ae;ae=se,se=e;let t=oe;oe=ce,ce=t}let ue,de,fe=!1;this._decorationService.forEachDecorationAtCell(k,t,void 0,e=>{e.options.layer!==`top`&&fe||(e.backgroundColorRGB&&(ce=50331648,se=e.backgroundColorRGB.rgba>>8&16777215,ue=e.backgroundColorRGB),e.foregroundColorRGB&&(oe=50331648,ae=e.foregroundColorRGB.rgba>>8&16777215,de=e.foregroundColorRGB),fe=e.options.layer===`top`)}),!fe&&N&&(ue=this._coreBrowserService.isFocused?p.selectionBackgroundOpaque:p.selectionInactiveBackgroundOpaque,se=ue.rgba>>8&16777215,ce=50331648,fe=!0,p.selectionForeground&&(oe=50331648,ae=p.selectionForeground.rgba>>8&16777215,de=p.selectionForeground)),fe&&D.push(`xterm-decoration-top`);let pe;switch(ce){case 16777216:case 33554432:pe=p.ansi[se],D.push(`xterm-bg-${se}`);break;case 50331648:pe=xS.toColor(se>>16,se>>8&255,se&255),this._addStyle(h,`background-color:#${IS((se>>>0).toString(16),`0`,6)}`);break;default:le?(pe=p.foreground,D.push(`xterm-bg-257`)):pe=p.background}switch(ue||M.isDim()&&(ue=SS.multiplyOpacity(pe,.5)),oe){case 16777216:case 33554432:M.isBold()&&ae<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(ae+=8),this._applyMinimumContrast(h,pe,p.ansi[ae],M,ue,void 0)||D.push(`xterm-fg-${ae}`);break;case 50331648:let e=xS.toColor(ae>>16&255,ae>>8&255,ae&255);this._applyMinimumContrast(h,pe,e,M,ue,de)||this._addStyle(h,`color:#${IS(ae.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(h,pe,p.foreground,M,ue,de)||le&&D.push(`xterm-fg-257`)}D.length&&=(h.className=D.join(` `),0),!te&&!A&&!re&&ee?g++:h.textContent=_,T!==this.defaultSpacing&&(h.style.letterSpacing=`${T}px`),d.push(h),k=j}return h&&g&&(h.textContent=_),d}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||MS(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(!i&&!a&&(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=SS.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return s?(this._addStyle(e,`color:${s.css}`),!0):!1}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!n||!r?!1:this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e<r[0]&&t<=r[1]:e<n[0]&&t>=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t<r[1]||n[1]===r[1]&&t===n[1]&&e>=n[0]&&e<r[0]||n[1]<r[1]&&t===r[1]&&e<r[0]||n[1]<r[1]&&t===n[1]&&e>=n[0]}};FS=dv([X(1,ty),X(2,Wv),X(3,Zv),X(4,Bv),X(5,qv),X(6,ny)],FS);function IS(e,t,n){for(;e.length<n;)e=t+e;return e}var LS=class{constructor(e,t){this._flat=new Float32Array(256),this._font=``,this._fontSize=0,this._weight=`normal`,this._weightBold=`bold`,this._measureElements=[],this._container=e.createElement(`div`),this._container.classList.add(`xterm-width-cache-measure-container`),this._container.setAttribute(`aria-hidden`,`true`),this._container.style.whiteSpace=`pre`,this._container.style.fontKerning=`none`;let n=e.createElement(`span`);n.classList.add(`xterm-char-measure-element`);let r=e.createElement(`span`);r.classList.add(`xterm-char-measure-element`),r.style.fontWeight=`bold`;let i=e.createElement(`span`);i.classList.add(`xterm-char-measure-element`),i.style.fontStyle=`italic`;let a=e.createElement(`span`);a.classList.add(`xterm-char-measure-element`),a.style.fontWeight=`bold`,a.style.fontStyle=`italic`,this._measureElements=[n,r,i,a],this._container.appendChild(n),this._container.appendChild(r),this._container.appendChild(i),this._container.appendChild(a),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,n,r){e===this._font&&t===this._fontSize&&n===this._weight&&r===this._weightBold||(this._font=e,this._fontSize=t,this._weight=n,this._weightBold=r,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${n}`,this._measureElements[1].style.fontWeight=`${r}`,this._measureElements[2].style.fontWeight=`${n}`,this._measureElements[3].style.fontWeight=`${r}`,this.clear())}get(e,t,n){let r=0;if(!t&&!n&&e.length===1&&(r=e.charCodeAt(0))<256){if(this._flat[r]!==-9999)return this._flat[r];let t=this._measure(e,0);return t>0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}},RS=class{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1]){this.clear();return}let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);s>=e.rows||c<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0])}isCellSelected(e,t,n){return this.hasSelection?(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t<this.endCol&&n<=this.viewportCappedEndRow:t<this.startCol&&n>=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportEndRow&&t<this.endCol||this.viewportStartRow<this.viewportEndRow&&n===this.viewportStartRow&&t>=this.startCol):!1}};function zS(){return new RS}var BS=`xterm-dom-renderer-owner-`,VS=`xterm-rows`,HS=`xterm-fg-`,US=`xterm-bg-`,WS=`xterm-focus`,GS=`xterm-selection`,KS=1,qS=class extends Dy{constructor(e,t,n,r,i,a,o,s,c,l,u,d,f,p){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=a,this._linkifier2=o,this._charSizeService=c,this._optionsService=l,this._bufferService=u,this._coreService=d,this._coreBrowserService=f,this._themeService=p,this._terminalClass=KS++,this._rowElements=[],this._selectionRenderModel=zS(),this.onRequestRedraw=this._register(new Z).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(VS),this._rowContainer.style.lineHeight=`normal`,this._rowContainer.setAttribute(`aria-hidden`,`true`),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(`div`),this._selectionContainer.classList.add(GS),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=NS(),this._updateDimensions(),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._themeService.onChangeColors(e=>this._injectCss(e))),this._injectCss(this._themeService.colors),this._rowFactory=s.createInstance(FS,document),this._element.classList.add(BS+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline(e=>this._handleLinkHover(e))),this._register(this._linkifier2.onHideLinkUnderline(e=>this._handleLinkLeave(e))),this._register(wy(()=>{this._element.classList.remove(BS+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new LS(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${VS} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${VS} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${VS} .xterm-dim { color: ${SS.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${VS}.${WS} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${VS}.${WS} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${VS}.${WS} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${VS} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${VS} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${VS} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${VS} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${VS} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${GS} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${GS} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${GS} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${HS}${n} { color: ${r.css}; }${this._terminalSelector} .${HS}${n}.xterm-dim { color: ${SS.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${US}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${HS}257 { color: ${SS.opaque(e.background).css}; }${this._terminalSelector} .${HS}257.xterm-dim { color: ${SS.multiplyOpacity(SS.opaque(e.background),.5).css}; }${this._terminalSelector} .${US}257 { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(WS),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(WS),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=`${r*this.dimensions.css.cell.height}px`,i.style.top=`${e*this.dimensions.css.cell.height}px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${BS}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};qS=dv([X(7,Hv),X(8,Xv),X(9,Wv),X(10,Rv),X(11,Bv),X(12,Zv),X(13,ny)],qS);var JS=class extends Dy{constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new Z),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new ZS(this._optionsService))}catch{this._measureStrategy=this._register(new XS(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],()=>this.measure()))}get hasValidSize(){return this.width>0&&this.height>0}measure(){let e=this._measureStrategy.measure();(e.width!==this.width||e.height!==this.height)&&(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};JS=dv([X(2,Wv)],JS);var YS=class extends Dy{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}},XS=class extends YS{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}},ZS=class extends YS{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}},QS=class extends Dy{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new $S(this._window)),this._onDprChange=this._register(new Z),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new Z),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange(e=>this._screenDprMonitor.setWindow(e))),this._register(Fy.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register(Q(this._textarea,`focus`,()=>this._isFocused=!0)),this._register(Q(this._textarea,`blur`,()=>this._isFocused=!1))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask(()=>this._cachedIsFocused=void 0)),this._cachedIsFocused}},$S=class extends Dy{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new Oy),this._onDprChange=this._register(new Z),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register(wy(()=>this.clearListener()))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=Q(this._parentWindow,`resize`,()=>this._setDprAndFireIfDiffers())}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){!this._resolutionMediaMatchList||!this._outerListener||(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}},eC=class extends Dy{constructor(){super(),this.linkProviders=[],this._register(wy(()=>this.linkProviders.length=0))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}};function tC(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}function nC(e,t,n,r,i,a,o,s,c){if(!a)return;let l=tC(e,t,n);if(l)return l[0]=Math.ceil((l[0]+(c?o/2:0))/o),l[1]=Math.ceil(l[1]/s),l[0]=Math.min(Math.max(l[0],1),r+ +!!c),l[1]=Math.min(Math.max(l[1],1),i),l}var rC=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return nC(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=tC(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};rC=dv([X(0,$v),X(1,Xv)],rC);var iC=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),!this._animationFrame&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0){this._runRefreshCallbacks();return}let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}},aC={};uv(aC,{getSafariVersion:()=>fC,isChromeOS:()=>vC,isFirefox:()=>lC,isIpad:()=>mC,isIphone:()=>hC,isLegacyEdge:()=>uC,isLinux:()=>_C,isMac:()=>pC,isNode:()=>oC,isSafari:()=>dC,isWindows:()=>gC});var oC=typeof process<`u`&&`title`in process,sC=oC?`node`:navigator.userAgent,cC=oC?`node`:navigator.platform,lC=sC.includes(`Firefox`),uC=sC.includes(`Edge`),dC=/^((?!chrome|android).)*safari/i.test(sC);function fC(){if(!dC)return 0;let e=sC.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])}var pC=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(cC),mC=cC===`iPad`,hC=cC===`iPhone`,gC=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(cC),_C=cC.indexOf(`Linux`)>=0,vC=/\bCrOS\b/.test(sC),yC=class{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&=(this._cancelCallback(this._idleCallback),void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||=this._requestCallback(this._process.bind(this))}_process(e){this._idleCallback=void 0;let t=0,n=0,r=e.timeRemaining(),i=0;for(;this._i<this._tasks.length;){if(t=performance.now(),this._tasks[this._i]()||this._i++,t=Math.max(1,performance.now()-t),n=Math.max(t,n),i=e.timeRemaining(),n*1.5>i){r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),this._start();return}r=i}this.clear()}},bC=class extends yC{_requestCallback(e){return setTimeout(()=>e(this._createDeadline(16)))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}},xC=class extends yC{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}},SC=!oC&&`requestIdleCallback`in window?xC:bC,CC=class{constructor(){this._queue=new SC}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}},wC=class extends Dy{constructor(e,t,n,r,i,a,o,s,c){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=s,this._renderer=this._register(new Oy),this._pausedResizeTask=new CC,this._observerDisposable=this._register(new Oy),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new Z),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new Z),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new Z),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new Z),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new iC((e,t)=>this._renderRows(e,t),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new TC(this._coreBrowserService,this._coreService,()=>this._fullRefresh()),this._register(wy(()=>this._syncOutputHandler.dispose())),this._register(this._coreBrowserService.onDprChange(()=>this.handleDevicePixelRatioChange())),this._register(o.onResize(()=>this._fullRefresh())),this._register(o.buffers.onBufferActivate(()=>this._renderer.value?.clear())),this._register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this._register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this._register(a.onDecorationRegistered(()=>this._fullRefresh())),this._register(a.onDecorationRemoved(()=>this._fullRefresh())),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],()=>{this.clear(),this.handleResize(o.cols,o.rows),this._fullRefresh()})),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],()=>this.refreshRows(o.buffer.y,o.buffer.y,!0))),this._register(c.onChangeColors(()=>this._fullRefresh())),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange(e=>this._registerIntersectionObserver(e,t)))}get dimensions(){return this._renderer.value.dimensions}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver(e=>this._handleIntersectionChange(e[e.length-1]),{threshold:0});n.observe(t),this._observerDisposable.value=wy(()=>n.disconnect())}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,!this._isPaused&&!this._charSizeService.hasValidSize&&this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused){this._needsFullRefresh=!0;return}if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){if(this._renderer.value){if(this._coreService.decPrivateModes.synchronizedOutput){this._syncOutputHandler.bufferRows(e,t);return}e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0}}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw(e=>this.refreshRows(e.start,e.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value?.handleResize(e,t)):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};wC=dv([X(2,Wv),X(3,Xv),X(4,Bv),X(5,qv),X(6,Rv),X(7,Zv),X(8,ny)],wC);var TC=class{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout(()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()},1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}};function EC(e,t,n,r){let i=n.buffer.x,a=n.buffer.y;if(!n.buffer.hasScrollback)return kC(i,a,e,t,n,r)+AC(a,t,n,r)+jC(i,a,e,t,n,r);let o;if(a===t)return o=i>e?`D`:`C`,RC(Math.abs(i-e),LC(o,r));o=a>t?`D`:`C`;let s=Math.abs(a-t);return RC(OC(a>t?e:i,n)+(s-1)*n.cols+1+DC(a>t?i:e,n),LC(o,r))}function DC(e,t){return e-1}function OC(e,t){return t.cols-e}function kC(e,t,n,r,i,a){return AC(t,r,i,a).length===0?``:RC(IC(e,t,e,t-NC(t,i),!1,i).length,LC(`D`,a))}function AC(e,t,n,r){let i=e-NC(e,n),a=t-NC(t,n);return RC(Math.abs(i-a)-MC(e,t,n),LC(FC(e,t),r))}function jC(e,t,n,r,i,a){let o;o=AC(t,r,i,a).length>0?r-NC(r,i):t;let s=r,c=PC(e,t,n,r,i,a);return RC(IC(e,o,n,s,c===`C`,i).length,LC(c,a))}function MC(e,t,n){let r=0,i=e-NC(e,n),a=t-NC(t,n);for(let o=0;o<Math.abs(i-a);o++){let a=FC(e,t)===`A`?-1:1;n.buffer.lines.get(i+a*o)?.isWrapped&&r++}return r}function NC(e,t){let n=0,r=t.buffer.lines.get(e),i=r?.isWrapped;for(;i&&e>=0&&e<t.rows;)n++,r=t.buffer.lines.get(--e),i=r?.isWrapped;return n}function PC(e,t,n,r,i,a){let o;return o=AC(n,r,i,a).length>0?r-NC(r,i):t,e<n&&o<=r||e>=n&&o<r?`C`:`D`}function FC(e,t){return e>t?`A`:`B`}function IC(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&s<a.buffer.lines.length;)o+=i?1:-1,i&&o>a.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function LC(e,t){let n=t?`O`:`[`;return $.ESC+n+e}function RC(e,t){e=Math.floor(e);let n=``;for(let r=0;r<e;r++)n+=t;return n}var zC=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:!this.selectionEnd||!this.selectionStart?this.selectionStart:this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols===0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!e||!t?!1:e[1]>t[1]||e[1]===t[1]&&e[0]>t[0]}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}};function BC(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}var VC=50,HC=15,UC=50,WC=500,GC=RegExp(`\xA0`,`g`),KC=class extends Dy{constructor(e,t,n,r,i,a,o,s,c){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=s,this._coreBrowserService=c,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new jv,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new Z),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new Z),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new Z),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new Z),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput(()=>{this.hasSelection&&this.clearSelection()}),this._trimListener=this._bufferService.buffer.lines.onTrim(e=>this._handleTrim(e)),this._register(this._bufferService.buffers.onBufferActivate(e=>this._handleBufferActivate(e))),this.enable(),this._model=new zC(this._bufferService),this._activeSelectionMode=0,this._register(wy(()=>{this._removeMouseDownListeners()})),this._register(this._bufferService.onResize(e=>{e.rowsChanged&&this.clearSelection()}))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!e||!t?!1:e[0]!==t[0]||e[1]!==t[1]}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]<t[0]?e[0]:t[0],a=e[0]<t[0]?t[0]:e[0];for(let o=e[1];o<=t[1];o++){let e=n.translateBufferLineToString(o,!0,i,a);r.push(e)}}else{let i=e[1]===t[1]?t[0]:void 0;r.push(n.translateBufferLineToString(e[1],!0,e[0],i));for(let i=e[1]+1;i<=t[1]-1;i++){let e=n.lines.get(i),t=n.translateBufferLineToString(i,!0);e?.isWrapped?r[r.length-1]+=t:r.push(t)}if(e[1]!==t[1]){let e=n.lines.get(t[1]),i=n.translateBufferLineToString(t[1],!0,0,t[0]);e&&e.isWrapped?r[r.length-1]+=i:r.push(i)}}return r.map(e=>e.replace(GC,` `)).join(gC?`\r
|
|
86
86
|
`:`
|
|
87
|
-
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),dC&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=PC(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=YS(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-FC),FC),t/=FC,t/Math.abs(t)+Math.round(t*(IC-1)))}shouldForceSelection(e){return sC?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),LC)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(sC&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let e=n.lines.get(this._model.selectionEnd[1]);e&&e.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<RC&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=bC(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);n?!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n):this._oldHasSelection&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c<o.length&&o.charAt(c+1)===` `;)c++}else{let t=e[0],n=e[0];a.getWidth(t)===0&&(u++,t--),a.getWidth(n)===2&&(d++,n++);let r=a.getString(n).length;for(r>1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(n+1,this._workCell));){a.loadCell(n+1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,n++):e>1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(t||o.slice(s,c).trim()!==``){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=PC(n,this._bufferService.cols)}};BC=av([X(3,Mv),X(4,Pv),X(5,Kv),X(6,Rv),X(7,qv),X(8,Gv)],BC);var VC=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},HC=class{constructor(){this._color=new VC,this._css=new VC}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},UC=Object.freeze((()=>{let e=[_S.toColor(`#2e3436`),_S.toColor(`#cc0000`),_S.toColor(`#4e9a06`),_S.toColor(`#c4a000`),_S.toColor(`#3465a4`),_S.toColor(`#75507b`),_S.toColor(`#06989a`),_S.toColor(`#d3d7cf`),_S.toColor(`#555753`),_S.toColor(`#ef2929`),_S.toColor(`#8ae234`),_S.toColor(`#fce94f`),_S.toColor(`#729fcf`),_S.toColor(`#ad7fa8`),_S.toColor(`#34e2e2`),_S.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:hS.toCss(r,i,a),rgba:hS.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:hS.toCss(n,n,n),rgba:hS.toRgba(n,n,n)})}return e})()),WC=_S.toColor(`#ffffff`),GC=_S.toColor(`#000000`),KC=_S.toColor(`#ffffff`),qC=GC,JC={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},YC=WC,XC=class extends xy{constructor(e){super(),this._optionsService=e,this._contrastCache=new HC,this._halfContrastCache=new HC,this._onChangeColors=this._register(new Z),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:WC,background:GC,cursor:KC,cursorAccent:qC,selectionForeground:void 0,selectionBackgroundTransparent:JC,selectionBackgroundOpaque:gS.blend(GC,JC),selectionInactiveBackgroundTransparent:JC,selectionInactiveBackgroundOpaque:gS.blend(GC,JC),scrollbarSliderBackground:gS.opacity(WC,.2),scrollbarSliderHoverBackground:gS.opacity(WC,.4),scrollbarSliderActiveBackground:gS.opacity(WC,.5),overviewRulerBorder:WC,ansi:UC.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=ZC(e.foreground,WC),t.background=ZC(e.background,GC),t.cursor=gS.blend(t.background,ZC(e.cursor,KC)),t.cursorAccent=gS.blend(t.background,ZC(e.cursorAccent,qC)),t.selectionBackgroundTransparent=ZC(e.selectionBackground,JC),t.selectionBackgroundOpaque=gS.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=ZC(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=gS.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?ZC(e.selectionForeground,mS):void 0,t.selectionForeground===mS&&(t.selectionForeground=void 0),gS.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=gS.opacity(t.selectionBackgroundTransparent,.3)),gS.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=gS.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=ZC(e.scrollbarSliderBackground,gS.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=ZC(e.scrollbarSliderHoverBackground,gS.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=ZC(e.scrollbarSliderActiveBackground,gS.opacity(t.foreground,.5)),t.overviewRulerBorder=ZC(e.overviewRulerBorder,YC),t.ansi=UC.slice(),t.ansi[0]=ZC(e.black,UC[0]),t.ansi[1]=ZC(e.red,UC[1]),t.ansi[2]=ZC(e.green,UC[2]),t.ansi[3]=ZC(e.yellow,UC[3]),t.ansi[4]=ZC(e.blue,UC[4]),t.ansi[5]=ZC(e.magenta,UC[5]),t.ansi[6]=ZC(e.cyan,UC[6]),t.ansi[7]=ZC(e.white,UC[7]),t.ansi[8]=ZC(e.brightBlack,UC[8]),t.ansi[9]=ZC(e.brightRed,UC[9]),t.ansi[10]=ZC(e.brightGreen,UC[10]),t.ansi[11]=ZC(e.brightYellow,UC[11]),t.ansi[12]=ZC(e.brightBlue,UC[12]),t.ansi[13]=ZC(e.brightMagenta,UC[13]),t.ansi[14]=ZC(e.brightCyan,UC[14]),t.ansi[15]=ZC(e.brightWhite,UC[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<n;r++)t.ansi[r+16]=ZC(e.extendedAnsi[r],UC[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0)for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];else switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};XC=av([X(0,Rv)],XC);function ZC(e,t){if(e!==void 0)try{return _S.toColor(e)}catch{}return t}var QC=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},$C=class{constructor(){this._services=new QC,this._services.set(Iv,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=kv(e).sort((e,t)=>e.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},ew={trace:0,debug:1,info:2,warn:3,error:4,off:5},tw=`xterm.js: `,nw=class extends xy{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),rw=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=ew[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:tw)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};nw=av([X(0,Rv)],nw);var rw,iw=class extends xy{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new Z),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new Z),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new Z),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},aw=3,ow=Object.freeze(new Cv),sw=0,cw=2,lw=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*aw);let r=t||Tv.fromCharData([0,xv,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*aw+0],n=t&2097151;return[this._data[e*aw+1],t&2097152?this._combined[e]:n?_v(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*aw+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*aw+0]=e|2097152|t[2]<<22):this._data[e*aw+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*aw+0]>>22}hasWidth(e){return this._data[e*aw+0]&12582912}getFg(e){return this._data[e*aw+1]}getBg(e){return this._data[e*aw+2]}hasContent(e){return this._data[e*aw+0]&4194303}getCodePoint(e){let t=this._data[e*aw+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*aw+0]&2097152}getString(e){let t=this._data[e*aw+0];return t&2097152?this._combined[e]:t&2097151?_v(t&2097151):``}isProtected(e){return this._data[e*aw+2]&536870912}loadCell(e,t){return sw=e*aw,t.content=this._data[sw+0],t.fg=this._data[sw+1],t.bg=this._data[sw+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*aw+0]=t.content,this._data[e*aw+1]=t.fg,this._data[e*aw+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*aw+0]=t|n<<22,this._data[e*aw+1]=r.fg,this._data[e*aw+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*aw+0];r&2097152?this._combined[e]+=_v(t):r&2097151?(this._combined[e]=_v(r&2097151)+_v(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*aw+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new Tv;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new Tv;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)===0&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return this._data.length*4*cw<this._data.buffer.byteLength;let n=e*aw;if(e>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*cw<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*cw<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*aw+0]&4194303)return e+(this._data[e*aw+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*aw+0]&4194303||this._data[e*aw+2]&50331648)return e+(this._data[e*aw+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<aw;e++)this._data[(n+i)*aw+e]=a[(t+i)*aw+e];a[(t+i)*aw+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<aw;e++)this._data[(n+i)*aw+e]=a[(t+i)*aw+e];a[(t+i)*aw+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[t*aw+0],n=e&2097151,a=e&2097152?this._combined[t]:n?_v(n):Sv;if(i+=a,r)for(let e=0;e<a.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}};function uw(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(!a&&r>=s&&r<c){s+=u.length-1;continue}let d=0,f=mw(u,d,t),p=1,m=0;for(;p<u.length;){let e=mw(u,p,t),r=e-m,a=n-f,o=Math.min(r,a);u[d].copyCellsFrom(u[p],m,f,o,!1),f+=o,f===n&&(d++,f=0),m+=o,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(n-1)===2&&(u[d].copyCellsFrom(u[d-1],n-1,f++,1,!1),u[d-1].setCell(n-1,i))}u[d].replaceCells(f,n,i);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function dw(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}}function fw(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length}function pw(e,t,n){let r=[],i=e.map((n,r)=>mw(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;s<i;){if(i-s<n){r.push(i-s);break}a+=n;let c=mw(e,o,t);a>c&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function mw(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var hw=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new Z),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),gy(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};hw._nextId=1;var gw=hw,_w={},vw=_w.B;_w[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:``,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},_w.A={"#":`£`},_w.B=void 0,_w[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},_w.C=_w[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},_w.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},_w.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},_w.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},_w.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},_w.E=_w[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},_w.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},_w.H=_w[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},_w[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var yw=4294967295,bw=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=ow.clone(),this.savedCharset=vw,this.markers=[],this._nullCell=Tv.fromCharData([0,xv,1,0]),this._whitespaceCell=Tv.fromCharData([0,Sv,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new gC,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new iw(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new wv),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new wv),this._whitespaceCell}getBlankLine(e,t){return new lw(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>yw?yw:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=ow);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new iw(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(ow),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new lw(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new lw(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=uw(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(ow),n);if(r.length>0){let n=dw(this.lines,r);fw(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(ow),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new lw(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=this.getNullCell(ow),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let l=c[c.length-1].getTrimmedLength(),u=pw(c,this._cols,e),d=u.length-c.length,f;f=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+d):Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let e=0;e<d;e++){let e=this.getBlankLine(ow,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=mw(c,Math.max(g,0),this._cols))}for(let t=0;t<c.length;t++)u[t]<e&&c[t].setCell(u[t],r);let v=d-f;for(;v-->0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(i.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,r=n-1,o=0,s=i[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+a-1);l>=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new gw(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},xw=class extends xy{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Z),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(`scrollback`,()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,()=>this.setupTabStops()))}reset(){this._normal=new bw(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new bw(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Sw=2,Cw=1,ww=class extends xy{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Z),this.onResize=this._onResize.event,this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Sw),this.rows=Math.max(e.rawOptions.rows||0,Cw),this.buffers=this._register(new xw(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};ww=av([X(0,Rv)],ww);var Tw={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:sC,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},Ew=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],Dw=class extends xy{constructor(e){super(),this._onOptionChange=this._register(new Z),this.onOptionChange=this._onOptionChange.event;let t={...Tw};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(vy(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in Tw))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in Tw))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=Tw[e],!Ow(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=Tw[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=Ew.includes(t)?t:Tw[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function Ow(e){return e===`block`||e===`underline`||e===`bar`}function kw(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&kw(e[r],t-1);return n}var Aw=Object.freeze({insertMode:!1}),jw=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Mw=class extends xy{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new Z),this.onData=this._onData.event,this._onUserInput=this._register(new Z),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Z),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Z),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=kw(Aw),this.decPrivateModes=kw(jw)}reset(){this.modes=kw(Aw),this.decPrivateModes=kw(jw)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};Mw=av([X(0,Mv),X(1,Lv),X(2,Rv)],Mw);var Nw={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function Pw(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var Fw=String.fromCharCode,Iw={DEFAULT:e=>{let t=[Pw(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${Fw(t[0])}${Fw(t[1])}${Fw(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Pw(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Pw(e,!0)};${e.x};${e.y}${t}`}},Lw=class extends xy{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new Z),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(Nw))this.addProtocol(e,Nw[e]);for(let e of Object.keys(Iw))this.addEncoding(e,Iw[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};Lw=av([X(0,Mv),X(1,Pv),X(2,Rv)],Lw);var Rw=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],zw=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Bw;function Vw(e,t){let n=0,r=t.length-1,i;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e<t[i][0])r=i-1;else return!0;return!1}var Hw=class{constructor(){if(this.version=`6`,!Bw){Bw=new Uint8Array(65536),Bw.fill(1),Bw[0]=0,Bw.fill(0,1,32),Bw.fill(0,127,160),Bw.fill(2,4352,4448),Bw[9001]=2,Bw[9002]=2,Bw.fill(2,11904,42192),Bw[12351]=1,Bw.fill(2,44032,55204),Bw.fill(2,63744,64256),Bw.fill(2,65040,65050),Bw.fill(2,65072,65136),Bw.fill(2,65280,65377),Bw.fill(2,65504,65511);for(let e=0;e<Rw.length;++e)Bw.fill(0,Rw[e][0],Rw[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?Bw[e]:Vw(e,zw)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=Uw.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return Uw.createPropertyValue(0,n,r)}},Uw=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new Z,this.onChange=this._onChange.event;let e=new Hw;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a<i;++a){let o=t.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},Ww=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Gw(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var Kw=2147483647,qw=256,Jw=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>qw)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e<t.length;++e){let r=t[e];if(Array.isArray(r))for(let e=0;e<r.length;++e)n.addSubParam(r[e]);else n.addParam(r)}return n}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>Kw?Kw:e}}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>Kw?Kw:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,Kw):e}},Yw=[],Xw=class{constructor(){this._state=0,this._active=Yw,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Yw}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=Yw,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||Yw,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,vv(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3){if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}}this._active=Yw,this._id=-1,this._state=0}}},Zw=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=vv(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},Qw=[],$w=class{constructor(){this._handlers=Object.create(null),this._active=Qw,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Qw}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=Qw,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||Qw,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,vv(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=Qw,this._ident=0}},eT=new Jw;eT.addParam(0);var tT=class{constructor(e){this._handler=e,this._data=``,this._params=eT,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():eT,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=vv(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=eT,this._data=``,this._hitLimit=!1,e));return this._params=eT,this._data=``,this._hitLimit=!1,t}},nT=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}},rT=160,iT=function(){let e=new nT(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(rT,0,2,0),e.add(rT,8,5,8),e.add(rT,6,0,6),e.add(rT,11,0,11),e.add(rT,13,13,13),e}(),aT=class extends xy{constructor(e=iT){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new Jw,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(vy(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new Xw),this._dcsParser=this._register(new $w),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state){if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}}for(let n=a;n<t;++n){switch(r=e[n],i=this._transitions.table[this.currentState<<8|(r<160?r:rT)],i>>4){case 2:for(let i=n+1;;++i)if(i>=t||(r=e[i])<32||r>126&&r<rT||++i>=t||(r=e[i])<32||r>126&&r<rT||++i>=t||(r=e[i])<32||r>126&&r<rT||++i>=t||(r=e[i])<32||r>126&&r<rT){this._printHandler(e,n,i),n=i-1;break}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|r],s=a?a.length-1:-1;for(;s>=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n<t&&(r=e[n])>47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r<rT){this._dcsParser.put(e,n,i),n=i-1;break}break;case 14:if(o=this._dcsParser.unhook(r!==24&&r!==26),o)return this._preserveStack(6,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=n+1;;i++)if(i>=t||(r=e[i])<32||r>127&&r<rT){this._oscParser.put(e,n,i),n=i-1;break}break;case 6:if(o=this._oscParser.end(r!==24&&r!==26),o)return this._preserveStack(5,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=i&15}}},oT=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,sT=/^[\da-f]+$/;function cT(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=oT.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),sT.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}}function lT(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function uT(e,t=16){let[n,r,i]=e;return`rgb:${lT(n,t)}/${lT(r,t)}/${lT(i,t)}`}var dT={"(":0,")":1,"*":2,"+":3,"-":1,".":2},fT=131072,pT=10;function mT(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var hT=5e3,gT=0,_T=class extends xy{constructor(e,t,n,r,i,a,o,s,c=new aT){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new yv,this._utf8Decoder=new bv,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=ow.clone(),this._eraseAttrDataInternal=ow.clone(),this._onRequestBell=this._register(new Z),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new Z),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new Z),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new Z),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new Z),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new Z),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new Z),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new Z),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new Z),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new Z),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new Z),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new Z),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new vT(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler($.BEL,()=>this.bell()),this._parser.setExecuteHandler($.LF,()=>this.lineFeed()),this._parser.setExecuteHandler($.VT,()=>this.lineFeed()),this._parser.setExecuteHandler($.FF,()=>this.lineFeed()),this._parser.setExecuteHandler($.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler($.BS,()=>this.backspace()),this._parser.setExecuteHandler($.HT,()=>this.tab()),this._parser.setExecuteHandler($.SO,()=>this.shiftOut()),this._parser.setExecuteHandler($.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(sS.IND,()=>this.index()),this._parser.setExecuteHandler(sS.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(sS.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Zw(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new Zw(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new Zw(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new Zw(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new Zw(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new Zw(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new Zw(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new Zw(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new Zw(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new Zw(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new Zw(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new Zw(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:`7`},()=>this.saveCursor()),this._parser.registerEscHandler({final:`8`},()=>this.restoreCursor()),this._parser.registerEscHandler({final:`D`},()=>this.index()),this._parser.registerEscHandler({final:`E`},()=>this.nextLine()),this._parser.registerEscHandler({final:`H`},()=>this.tabSet()),this._parser.registerEscHandler({final:`M`},()=>this.reverseIndex()),this._parser.registerEscHandler({final:`=`},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:`>`},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:`c`},()=>this.fullReset()),this._parser.registerEscHandler({final:`n`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`o`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`|`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`}`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`~`},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:`%`,final:`@`},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:`%`,final:`G`},()=>this.selectDefaultCharset());for(let e in _w)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new tT((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),hT))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${hT} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>fT&&(a=this._parseStack.position+fT)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<fT&&(this._parseBuffer=new Uint32Array(Math.min(e.length,fT))),o||this._dirtyRowTracker.clearRange(),e.length>fT)for(let t=a;t<e.length;t+=fT){let a=t+fT<e.length?t+fT:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==r||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(s,this._bufferService.rows-1)})}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;p<n;++p){if(r=e[p],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,f);i=Uw.extractWidth(t);let n=Uw.extractShouldJoin(t),m=n?Uw.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(_v(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>s){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof lw&&d.copyCellsFrom(e,t,0,m,!1);t<s;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-m;--e>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}else if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<s&&n-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!mT(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new tT(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Zw(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(ow));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=Uw.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent($.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent($.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent($.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent($.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent($.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,vw),this._charsetService.setgCharset(1,vw),this._charsetService.setgCharset(2,vw),this._charsetService.setgCharset(3,vw);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e,t){let n;(e=>(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${$.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=Cv.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=ow.fg,e.bg=ow.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=ow.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=ow.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=ow.fg&16777215,r.bg&=-67108864,r.bg|=ow.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${$.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=ow.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!mT(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${$.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>pT&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>pT&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(yT(n)){if(r===`?`)t.push({type:0,index:n});else{let e=cT(r);e&&t.push({type:1,index:n,color:e})}}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=cT(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);yT(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,vw),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(dT[e[0]],_w[e[1]]||vw),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=ow.clone(),this._eraseAttrDataInternal=ow.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new Tv;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=e=>(this._coreService.triggerDataEvent(`${$.ESC}${e}${$.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},vT=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(gT=e,e=t,t=gT),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};vT=av([X(0,Mv)],vT);function yT(e){return 0<=e&&e<256}var bT=5e7,xT=12,ST=50,CT=class extends xy{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new Z),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>bT)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=xT?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=xT)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>ST&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},wT=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};wT=av([X(0,Mv)],wT);var TT=!1,ET=class extends xy{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Sy),this._onBinary=this._register(new Z),this.onBinary=this._onBinary.event,this._onData=this._register(new Z),this.onData=this._onData.event,this._onLineFeed=this._register(new Z),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Z),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Z),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Z),this._instantiationService=new $C,this.optionsService=this._register(new Dw(e)),this._instantiationService.setService(Rv,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(ww)),this._instantiationService.setService(Mv,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(nw)),this._instantiationService.setService(Lv,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Mw)),this._instantiationService.setService(Pv,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Lw)),this._instantiationService.setService(Nv,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Uw)),this._instantiationService.setService(Bv,this.unicodeService),this._charsetService=this._instantiationService.createInstance(Ww),this._instantiationService.setService(Fv,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(wT),this._instantiationService.setService(zv,this._oscLinkService),this._inputHandler=this._register(new _T(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(ky.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(ky.forward(this._bufferService.onResize,this._onResize)),this._register(ky.forward(this.coreService.onData,this._onData)),this._register(ky.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new CT((e,t)=>this._inputHandler.parse(e,t))),this._register(ky.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Z),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!TT&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),TT=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Sw),t=Math.max(t,Cw),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Gw.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(Gw(this._bufferService),!1))),this._windowsWrappingHeuristics.value=vy(()=>{for(let t of e)t.dispose()})}}},DT={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function OT(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=+!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?$.ESC+`OA`:$.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?$.ESC+`OD`:$.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?$.ESC+`OC`:$.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?$.ESC+`OB`:$.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:$.DEL,e.altKey&&(i.key=$.ESC+i.key);break;case 9:if(e.shiftKey){i.key=$.ESC+`[Z`;break}i.key=$.HT,i.cancel=!0;break;case 13:i.key=e.altKey?$.ESC+$.CR:$.CR,i.cancel=!0;break;case 27:i.key=$.ESC,e.altKey&&(i.key=$.ESC+$.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`D`:t?$.ESC+`OD`:$.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`C`:t?$.ESC+`OC`:$.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`A`:t?$.ESC+`OA`:$.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`B`:t?$.ESC+`OB`:$.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=$.ESC+`[2~`);break;case 46:i.key=a?$.ESC+`[3;`+(a+1)+`~`:$.ESC+`[3~`;break;case 36:i.key=a?$.ESC+`[1;`+(a+1)+`H`:t?$.ESC+`OH`:$.ESC+`[H`;break;case 35:i.key=a?$.ESC+`[1;`+(a+1)+`F`:t?$.ESC+`OF`:$.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?$.ESC+`[5;`+(a+1)+`~`:$.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?$.ESC+`[6;`+(a+1)+`~`:$.ESC+`[6~`;break;case 112:i.key=a?$.ESC+`[1;`+(a+1)+`P`:$.ESC+`OP`;break;case 113:i.key=a?$.ESC+`[1;`+(a+1)+`Q`:$.ESC+`OQ`;break;case 114:i.key=a?$.ESC+`[1;`+(a+1)+`R`:$.ESC+`OR`;break;case 115:i.key=a?$.ESC+`[1;`+(a+1)+`S`:$.ESC+`OS`;break;case 116:i.key=a?$.ESC+`[15;`+(a+1)+`~`:$.ESC+`[15~`;break;case 117:i.key=a?$.ESC+`[17;`+(a+1)+`~`:$.ESC+`[17~`;break;case 118:i.key=a?$.ESC+`[18;`+(a+1)+`~`:$.ESC+`[18~`;break;case 119:i.key=a?$.ESC+`[19;`+(a+1)+`~`:$.ESC+`[19~`;break;case 120:i.key=a?$.ESC+`[20;`+(a+1)+`~`:$.ESC+`[20~`;break;case 121:i.key=a?$.ESC+`[21;`+(a+1)+`~`:$.ESC+`[21~`;break;case 122:i.key=a?$.ESC+`[23;`+(a+1)+`~`:$.ESC+`[23~`;break;case 123:i.key=a?$.ESC+`[24;`+(a+1)+`~`:$.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=$.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=$.DEL:e.keyCode===219?i.key=$.ESC:e.keyCode===220?i.key=$.FS:e.keyCode===221&&(i.key=$.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=DT[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=$.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=$.ESC+n}else if(e.keyCode===32)i.key=$.ESC+(e.ctrlKey?$.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=$.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=$.US),e.key===`@`&&(i.key=$.NUL))}return i}var kT=0,AT=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new gC,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new gC,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i<r.length;i++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(kT=this._search(t),kT===-1)||this._getKey(this._array[kT])!==t)return!1;do if(this._array[kT]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(kT),!0;while(++kT<this._array.length&&this._getKey(this._array[kT])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:n[r++]=this._array[i];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(kT=this._search(e),!(kT<0||kT>=this._array.length)&&this._getKey(this._array[kT])===e))do yield this._array[kT];while(++kT<this._array.length&&this._getKey(this._array[kT])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(kT=this._search(e),!(kT<0||kT>=this._array.length)&&this._getKey(this._array[kT])===e))do t(this._array[kT]);while(++kT<this._array.length&&this._getKey(this._array[kT])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i<e)t=r+1;else{for(;r>0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},jT=0,MT=0,NT=class extends xy{constructor(){super(),this._decorations=new AT(e=>e?.marker.line),this._onDecorationRegistered=this._register(new Z),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Z),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(vy(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new PT(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e<i&&(!n||(a.options.layer??`bottom`)===n)&&(yield a)}forEachDecorationAtCell(e,t,n,r){this._decorations.forEachByKey(t,t=>{jT=t.options.x??0,MT=jT+(t.options.width??1),e>=jT&&e<MT&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},PT=class extends by{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new Z),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new Z),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=`full`)}get backgroundColorRGB(){return this._cachedBg===null&&(this._cachedBg=this.options.backgroundColor?_S.toColor(this.options.backgroundColor):void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this._cachedFg=this.options.foregroundColor?_S.toColor(this.options.foregroundColor):void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},FT=1e3,IT=class{constructor(e,t=FT){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},LT=20,RT=class extends xy{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new IT(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
|
|
88
|
-
`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Q(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(
|
|
89
|
-
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===LT+1&&(this._liveRegion.textContent+=lv.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};RT=av([X(1,Iv),X(2,Gv),X(3,qv)],RT);var zT=class extends xy{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new Z),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new Z),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(vy(()=>{gy(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Q(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Q(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(Q(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(Q(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){this._activeLine!==e.y||this._wasResized?(this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1):this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&BT(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,gy(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0||e.link.decorations.underline,pointerCursor:e.link.decorations===void 0||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};zT=av([X(1,Kv),X(2,qv),X(3,Mv),X(4,Zv)],zT);function BT(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var VT=class extends ET{constructor(e={}){super(e),this._linkifier=this._register(new Sy),this.browser=$S,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Sy),this._onCursorMove=this._register(new Z),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Z),this.onKey=this._onKey.event,this._onRender=this._register(new Z),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Z),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Z),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Z),this.onBell=this._onBell.event,this._onFocus=this._register(new Z),this._onBlur=this._register(new Z),this._onA11yCharEmitter=this._register(new Z),this._onA11yTabEmitter=this._register(new Z),this._onWillOpen=this._register(new Z),this._setup(),this._decorationService=this._instantiationService.createInstance(NT),this._instantiationService.setService(Vv,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(JS),this._instantiationService.setService(Zv,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Hv)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(ky.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(ky.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(ky.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(ky.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(vy(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=gS.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${$.ESC}]${n};${uT(r)}${cS.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=hS.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=hS.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(RT,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(Q(this.element,`copy`,e=>{this.hasSelection()&&fv(e,this._selectionService)}));let e=e=>pv(e,this.textarea,this.coreService,this.optionsService);this._register(Q(this.textarea,`paste`,e)),this._register(Q(this.element,`paste`,e)),rC?this._register(Q(this.element,`mousedown`,e=>{e.button===2&&gv(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Q(this.element,`contextmenu`,e=>{gv(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),dC&&this._register(Q(this.element,`auxclick`,e=>{e.button===1&&hv(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Q(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(Q(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(Q(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(Q(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(Q(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(Q(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(Q(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(Q(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,sv.get()),fC||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(KS,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(Gv,this._coreBrowserService),this._register(Q(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(Q(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(HS,this._document,this._helperContainer),this._instantiationService.setService(Wv,this._charSizeService),this._themeService=this._instantiationService.createInstance(XC),this._instantiationService.setService(Xv,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(CS),this._instantiationService.setService(Yv,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(vC,this.rows,this.screenElement)),this._instantiationService.setService(qv,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(lS,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(ZS),this._instantiationService.setService(Kv,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(zT,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(eS,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(BC,this.element,this.screenElement,r)),this._instantiationService.setService(Jv,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(ky.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(tS,this.screenElement)),this._register(Q(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(RT,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(oS,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(oS,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(VS,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Q(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(Q(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=$.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){mv(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=OT(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===$.ETX||n.key===$.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(HT(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e===this.cols&&t===this.rows?this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure():super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(ow));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(`focus`)?this.coreService.triggerDataEvent($.ESC+`[I`):this.coreService.triggerDataEvent($.ESC+`[O`)}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[4;${t};${e}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[6;${r};${n}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};function HT(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var UT=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},WT=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new Tv)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},GT=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new WT(t)}getNullCell(){return new Tv}},KT=class extends xy{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Z),this.onBufferChange=this._onBufferChange.event,this._normal=new GT(this._core.buffers.normal,`normal`),this._alternate=new GT(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},qT=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},JT=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},YT=[`cols`,`rows`],XT=0,ZT=class extends xy{constructor(e){super(),this._core=this._register(new VT(e)),this._addonManager=this._register(new UT),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(YT.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||=new qT(this._core),this._parser}get unicode(){return this._checkProposedApi(),new JT(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||=this._register(new KT(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
|
|
90
|
-
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return sv.get()},set promptLabel(e){sv.set(e)},get tooMuchOutput(){return lv.get()},set tooMuchOutput(e){lv.set(e)}}}_verifyIntegers(...e){for(XT of e)if(XT===1/0||isNaN(XT)||XT%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(XT of e)if(XT&&(XT===1/0||isNaN(XT)||XT%1!=0||XT<0))throw Error(`This API only accepts positive integers`)}},QT=2,$T=1,eE=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(QT,Math.floor(u/e.css.cell.width)),rows:Math.max($T,Math.floor(l/e.css.cell.height))}}},tE=5,nE=20,rE=5,iE=240,aE=120,oE={checking:`检查中`,unavailable:`不可用`,starting:`启动中`,running:`运行中`,exited:`已结束`},sE=new Map,cE=e=>{let t=sE.get(e);if(!t){let n={id:`${e}-1`,title:`1`,phase:`checking`};t={slots:[n],activeId:n.id,opened:new Set,terminals:new Map,fits:new Map},sE.set(e,t)}return t};function lE({workspaceId:e,workspaceLabel:t,connected:n,sendCommand:r,registerSink:i,conversationId:a}){let o=a?`term-${a}`:`terminal-right-rail`,s=cE(o),[c,l]=(0,z.useState)(()=>s.slots),[u,d]=(0,z.useState)(()=>s.activeId),f=(0,z.useRef)(u);f.current=u,s.activeId=u;let p=(0,z.useRef)(c);p.current=c,s.slots=c;let m=(0,z.useRef)(e);m.current=e;let h=(0,z.useRef)(r);h.current=r;let g=(0,z.useRef)(s.opened);g.current=s.opened;let _=(0,z.useRef)(!1),v=(0,z.useRef)(s.terminals);v.current=s.terminals;let y=(0,z.useRef)(s.fits);y.current=s.fits;let b=(0,z.useRef)(new Map),[x,S]=(0,z.useState)(0),C=(0,z.useRef)(n),w=(0,z.useCallback)(e=>{v.current.get(e)?.dispose(),v.current.delete(e),y.current.delete(e),b.current.delete(e)},[]),T=(0,z.useCallback)(e=>{let t=v.current.get(e),n=y.current.get(e);if(!t||!n)return;let r=b.current.get(e);if(!(!r||r.clientWidth<2||r.clientHeight<2)){try{n.fit()}catch{return}t.cols<nE||t.rows<rE||t.cols>iE||t.rows>aE||g.current.has(e)&&h.current({type:`terminal.resize`,sessionId:e,cols:t.cols,rows:t.rows})}},[]),E=(0,z.useCallback)((e,t)=>{if(!t){b.current.delete(e);return}b.current.set(e,t);let n=v.current.get(e);if(n){n.element&&!t.contains(n.element)&&(t.innerHTML=``,t.appendChild(n.element),requestAnimationFrame(()=>T(e)));return}let r=getComputedStyle(t),i=(e,t)=>r.getPropertyValue(e).trim()||t,a=new ZT({cursorBlink:!0,convertEol:!1,scrollback:5e3,fontFamily:`Consolas, 'Cascadia Mono', 'DejaVu Sans Mono', monospace`,fontSize:12,lineHeight:1.35,theme:{background:`#00000000`,foreground:i(`--term-fg`,`#dbe4f0`),cursor:i(`--term-fg`,`#dbe4f0`),selectionBackground:i(`--term-selection`,`#3a4f6b`)},allowProposedApi:!0}),o=new eE;a.loadAddon(o),a.open(t),a.onData(t=>{g.current.has(e)&&h.current({type:`terminal.input`,sessionId:e,data:t})}),a.onResize(({cols:t,rows:n})=>{g.current.has(e)&&h.current({type:`terminal.resize`,sessionId:e,cols:t,rows:n})}),v.current.set(e,a),y.current.set(e,o),requestAnimationFrame(()=>T(e)),S(e=>e+1)},[T]),D=(0,z.useCallback)(e=>{v.current.get(e)?.reset()},[]),O=(0,z.useCallback)(e=>{let t=m.current,n=v.current.get(e);if(!t||!n||g.current.has(e))return;n.reset(),T(e),l(t=>t.map(t=>t.id===e?{...t,phase:`starting`,exitCode:void 0,reason:``}:t));let r=Math.max(nE,Math.min(iE,n.cols||80)),i=Math.max(rE,Math.min(aE,n.rows||24));h.current({type:`terminal.open`,sessionId:e,workspaceId:t,cols:r,rows:i})?(g.current.add(e),l(t=>t.map(t=>t.id===e?{...t,phase:`running`}:t))):l(t=>t.map(t=>t.id===e?{...t,phase:`exited`,reason:`Super Pi 服务的连接尚未就绪`}:t))},[T]);(0,z.useEffect)(()=>{let e=!1;return fetch(`/api/terminal`).then(e=>e.json()).then(t=>{e||(t.enabled?(_.current=!0,l(e=>e.map(e=>e.phase===`checking`?{...e,phase:`starting`}:e))):l(e=>e.map(e=>({...e,phase:`unavailable`,reason:t.reason??`终端未启用`}))))}).catch(()=>{e||l(e=>e.map(e=>({...e,phase:`unavailable`,reason:`无法读取终端状态`})))}),()=>{e=!0}},[]),(0,z.useEffect)(()=>{if(_.current)for(let e of c)(e.phase===`checking`||e.phase===`starting`)&&!g.current.has(e.id)&&O(e.id)},[c,O,x]);let k=(0,z.useCallback)(e=>{if(e.type===`terminal.output`)for(let t of sE.values()){let n=t.terminals.get(e.sessionId);if(n){n.write(e.data);return}}else if(e.type===`terminal.exit`){for(let t of sE.values())t.opened.has(e.sessionId)&&(t.opened.delete(e.sessionId),t.slots=t.slots.map(t=>t.id===e.sessionId?{...t,phase:`exited`,exitCode:e.exitCode}:t));D(e.sessionId),l(t=>t.map(t=>t.id===e.sessionId?{...t,phase:`exited`,exitCode:e.exitCode}:t))}else if(e.type===`terminal.error`){for(let t of sE.values())t.opened.has(e.sessionId)&&(t.opened.delete(e.sessionId),t.slots=t.slots.map(t=>t.id===e.sessionId?{...t,phase:`exited`,reason:e.message}:t));D(e.sessionId),l(t=>t.map(t=>t.id===e.sessionId?{...t,phase:`exited`,reason:e.message}:t))}else e.type===`terminal.status`&&!e.enabled&&l(t=>t.map(t=>({...t,phase:`unavailable`,reason:e.reason??`终端未启用`})))},[D]);(0,z.useEffect)(()=>(i(k),()=>i(void 0)),[k,i]),(0,z.useEffect)(()=>()=>{b.current.clear()},[]),(0,z.useEffect)(()=>{let e=n&&!C.current;C.current=n,e&&l(e=>e.map(e=>e.phase===`exited`&&!e.deliberate?{...e,phase:`starting`,reason:``}:e))},[n]),(0,z.useLayoutEffect)(()=>{let e=new ResizeObserver(()=>T(f.current));for(let t of b.current.values())e.observe(t);return T(f.current),()=>e.disconnect()},[T,c,x]);let A=(0,z.useCallback)(e=>{d(e),requestAnimationFrame(()=>T(e))},[T]),ee=(0,z.useCallback)(()=>{let e=new Set(p.current.map(e=>e.title)),t=1;for(;e.has(String(t));)t+=1;let n={id:`${o}-${t}`,title:String(t),phase:`checking`};l(e=>e.length>=tE?e:[...e,n]),d(n.id)},[o]),j=(0,z.useCallback)(e=>{h.current({type:`terminal.close`,sessionId:e}),g.current.delete(e),w(e),l(t=>{if(t.length<=1)return t;let n=t.findIndex(t=>t.id===e),r=t.filter(t=>t.id!==e);return f.current===e&&d(r[Math.min(n,r.length-1)].id),r})},[w]),M=(0,z.useCallback)(()=>{let e=f.current;h.current({type:`terminal.close`,sessionId:e}),g.current.delete(e),l(t=>t.map(t=>t.id===e?{...t,phase:`exited`,deliberate:!0}:t))},[]),N=c.find(e=>e.id===u)??c[0];return N?N.phase===`checking`?(0,B.jsx)(`p`,{className:`rail-empty`,"data-terminal-phase":`checking`,children:`正在检查终端状态…`}):N.phase===`unavailable`?(0,B.jsxs)(`div`,{className:`terminal-unavailable`,"data-terminal-phase":`unavailable`,children:[(0,B.jsx)(`p`,{className:`terminal-unavailable-reason`,children:N.reason}),(0,B.jsx)(`p`,{className:`rail-empty`,children:`终端仅接受本机与局域网连接。`})]}):(0,B.jsxs)(`div`,{className:`terminal-panel`,"data-terminal-panel":`1`,"data-terminal-phase":N.phase,children:[(0,B.jsxs)(`div`,{className:`terminal-strip`,role:`tablist`,"aria-label":`终端会话`,"data-terminal-strip":`1`,children:[c.map(e=>(0,B.jsxs)(`div`,{className:`terminal-tab${e.id===u?` is-active`:``}`,children:[(0,B.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":e.id===u,className:`terminal-tab-btn`,"data-terminal-slot":e.id,onClick:()=>A(e.id),title:oE[e.phase],children:[(0,B.jsx)(`span`,{className:`terminal-tab-dot terminal-tab-dot-${e.phase}`,"aria-hidden":`true`}),e.title]}),(0,B.jsx)(`button`,{type:`button`,className:`terminal-tab-close`,"aria-label":`关闭终端 ${e.title}`,"data-terminal-slot-close":e.id,onClick:()=>j(e.id),children:`×`})]},e.id)),c.length<tE&&(0,B.jsx)(`button`,{type:`button`,className:`terminal-strip-add`,"data-terminal-add":`1`,onClick:ee,title:`新建终端`,"aria-label":`新建终端`,children:`+`})]}),(0,B.jsxs)(`div`,{className:`terminal-toolbar`,children:[(0,B.jsxs)(`span`,{className:`terminal-status terminal-status-${N.phase}`,"data-terminal-status":N.phase,children:[(0,B.jsx)(`span`,{className:`terminal-status-dot`,"aria-hidden":`true`}),oE[N.phase]]}),(0,B.jsxs)(`span`,{className:`terminal-toolbar-right`,children:[t&&(0,B.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-hint":`1`,title:t,children:t}),N.phase===`running`?(0,B.jsx)(`button`,{type:`button`,className:`terminal-close-btn`,"data-terminal-close":`1`,onClick:M,children:`结束会话`}):(0,B.jsx)(`button`,{type:`button`,className:`terminal-restart-btn`,"data-terminal-restart":`1`,onClick:()=>O(N.id),children:`重新打开`})]})]}),N.reason&&(0,B.jsx)(`p`,{className:`tool-error`,"data-terminal-error":`1`,role:`alert`,children:N.reason}),N.phase===`exited`&&N.exitCode!==void 0&&N.exitCode!==0&&(0,B.jsxs)(`p`,{className:`tool-error`,"data-terminal-exit":`1`,children:[`会话已结束,退出码 `,N.exitCode,`。`]}),(0,B.jsx)(`div`,{className:`terminal-surface`,"data-terminal-surface":`1`,children:c.map(e=>(0,B.jsx)(`div`,{ref:t=>E(e.id,t),className:`terminal-xterm-host`,"data-terminal-xterm":e.id,style:{display:e.id===u?`block`:`none`}},e.id))})]}):null}function uE(e){return!!(e&&typeof e==`object`&&e.type===`message.send`)}function dE(e){let t=[],n=[];for(let r of e)(r.retry?t:n).push(r);return{retry:t,failed:n}}var fE=`.super-pi-tool.json`,pE=512e3,mE=/^[a-z0-9][a-z0-9-]{0,63}$/,hE=/^[A-Za-z0-9][A-Za-z0-9_.-]*==[^=\s,;<>|'"`\\]{1,80}$/;function gE(e,t){let n;try{n=JSON.parse(e)}catch{return{ok:!1,reason:`「${t}」不是 JSON。确认一下选的是别人分享的工具文件(${fE})。`}}if(!n||typeof n!=`object`||Array.isArray(n))return{ok:!1,reason:`这个 JSON 不是一个工具包。`};let r=n,i=typeof r.format==`string`?r.format:void 0;if(i!==void 0&&i!==`super-pi.tool`)return{ok:!1,reason:`这不是 Super Pi 的工具文件(format: ${i})。`};if(typeof r.version==`number`&&r.version>1)return{ok:!1,reason:`这个工具文件是更新版本的 Super Pi 导出的(version: ${r.version}),当前版本读不了。`};let a=typeof r.slug==`string`?r.slug.trim():``,o=typeof r.name==`string`?r.name.trim():``;if(!a)return{ok:!1,reason:`这个工具包里没有 slug(那是它的短名字,也是它在磁盘上的目录名)。`};if(!o)return{ok:!1,reason:`这个工具包里没有名字。`};if(!Array.isArray(r.files)||!r.files.length)return{ok:!1,reason:`这个工具包里没有文件。`};if(r.files.length>32)return{ok:!1,reason:`文件太多了:${r.files.length} 个,上限 32 个。`};let s=[],c=0;for(let e of r.files){let t=e;if(!t||typeof t.path!=`string`||typeof t.content!=`string`)return{ok:!1,reason:`工具包里的文件项格式不对(每一项都要有 path 和 content)。`};let n=t.path.trim();if(!n||n.startsWith(`/`)||n.includes(`\\`)||n.includes(`\0`)||n.split(`/`).includes(`..`))return{ok:!1,reason:`文件路径「${n}」不合法:不能是绝对路径,也不能跳出工具自己的目录。`};if(s.some(e=>e.path===n))return{ok:!1,reason:`工具包里有重复的文件:${n}`};if(c+=new TextEncoder().encode(t.content).length,c>512e3)return{ok:!1,reason:`工具文件合计超过 ${wE(pE)} 的上限。`};s.push({path:n,content:t.content})}let l=typeof r.entrypoint==`string`&&r.entrypoint.trim()?r.entrypoint.trim():`index.html`;if(!l.endsWith(`.html`))return{ok:!1,reason:`入口文件必须是一个 HTML 文件。`};if(!s.some(e=>e.path===l))return{ok:!1,reason:`工具包里没有包含入口文件 ${l}。`};let u;if(r.script!==void 0&&r.script!==null){let e=r.script,t=typeof e.path==`string`?e.path.trim():``;if(!t.endsWith(`.py`))return{ok:!1,reason:`工具包声明的脚本必须是一个 .py 文件。`};if(!s.some(e=>e.path===t))return{ok:!1,reason:`工具包里没有包含它声明的脚本 ${t}。`};u={path:t,timeoutMs:typeof e.timeoutMs==`number`?e.timeoutMs:void 0,parameters:typeof e.parameters==`object`&&e.parameters!==null?e.parameters:void 0}}let d;if(r.environment!==void 0&&r.environment!==null){let e=r.environment,t=e.requires;if(t!==void 0&&!Array.isArray(t))return{ok:!1,reason:`工具包声明的依赖列表格式不对(requires 必须是数组)。`};if(Array.isArray(t)){for(let e of t)if(typeof e!=`string`||!hE.test(e.trim()))return{ok:!1,reason:`依赖必须钉死到精确版本(写成 pkg==version):${String(e).slice(0,60)}。`}}let n=e.fingerprint&&typeof e.fingerprint==`object`?e.fingerprint:void 0;d={requiresPython:typeof e.requiresPython==`string`?e.requiresPython:void 0,requires:Array.isArray(t)?t.map(e=>String(e).trim()):void 0,fingerprint:n}}let f=r.permissions&&typeof r.permissions==`object`&&r.permissions.llm===!0?{llm:!0}:void 0;return{ok:!0,unnamedFormat:i===void 0,bundle:{...i===void 0?{}:{format:i},...typeof r.version==`number`?{version:r.version}:{},...typeof r.exportedAt==`string`?{exportedAt:r.exportedAt}:{},slug:a,name:o,...typeof r.description==`string`&&r.description.trim()?{description:r.description.trim().slice(0,500)}:{},entrypoint:l,files:s,script:u,environment:d,...f?{permissions:f}:{}}}}function _E(e){let t=e.trim().toLowerCase();return t?mE.test(t)?{ok:!0,slug:t}:{ok:!1,reason:`slug 只能用小写字母、数字和连字符,且要以字母或数字开头。`}:{ok:!1,reason:`请填写 slug(工具的短名字,只能用小写字母、数字和连字符)。`}}function vE(e,t){let n=e.trim().toLowerCase().slice(0,60).replace(/[^a-z0-9-]+/g,`-`).replace(/^-+|-+$/g,``)||`tool`;if(!t.includes(n))return n;for(let e=2;e<100;e+=1){let r=`${n}-${e}`;if(!t.includes(r))return r}return n}function yE(e){return`${e.slug}${fE}`}function bE(e){let t=e.trim().replace(/[\\/:*?"<>|]/g,``).replace(/\.+$/,``).trim();return t?t.length>80?{ok:!1,reason:`文件名太长了,请控制在 80 个字符以内。`}:{ok:!0,name:t.endsWith(`.super-pi-tool.json`)?t:`${t}${fE}`}:{ok:!1,reason:`请填写文件名。`}}function xE(e){if(e.permissions?.llm)return{tone:`warn`,text:`这个工具可以调用模型:它能把内容发给你的模型回答,每次调用都会用你的模型额度`}}function SE(e){let t=e.environment?.requires??[];return!e.script&&t.length===0?{tone:`ok`,text:`纯页面工具 · 导入即用,不需要 Python`}:t.length===0?{tone:`ok`,text:`只用 Python 标准库 · 导入即用,不需要安装任何包${e.environment?.requiresPython?`(需要 Python ${e.environment.requiresPython})`:``}`}:{tone:`warn`,text:`首次运行时会安装 ${t.length} 个依赖:${t.join(`、`)}(装进这个工具自己的虚拟环境)${e.environment?.requiresPython?` · 需要 Python ${e.environment.requiresPython}`:``}`}}function CE(e){if(e)return e.state===`zero-deps`?{text:`零依赖`,warn:!1}:e.state===`ready`?{text:`环境就绪`,warn:!1}:e.state===`needs-env`?{text:`首次运行时安装依赖`,warn:!1}:e.state===`needs-python`?{text:`缺少可用的 Python`,warn:!0}:{text:`与导出方环境不一致`,warn:!0}}function wE(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function TE(e,t){let{format:n,version:r,exportedAt:i,...a}=e;return{...a,slug:t}}var EE={workspaces:[],conversations:[],subagentRuns:[]},DE=e=>e.nativeEvent.isComposing||e.keyCode===229,OE=(e,t,n)=>{let r=e.filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),i=r.findIndex(e=>e.id===t);if(i<0||r[i].delivery===`sending`)return e;let a=r.reduce((e,t,n)=>t.delivery===`sending`?n:e,-1),o=Math.max(a+1,Math.min(n,r.length-1));if(o===i)return e;let s=[...r],[c]=s.splice(i,1);s.splice(o,0,c);let l=[...e],u=0;for(let e=0;e<l.length;e+=1)(l[e].role===`user`||l[e].role===`tool`)&&l[e].delivery&&(l[e]=s[u++]);return l},kE=e=>{if(typeof e!=`string`||e.length===0)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:new Intl.DateTimeFormat(`zh-CN`,{hour:`2-digit`,minute:`2-digit`}).format(t)},AE=6e4,jE=60*AE,ME=24*jE,NE=7*ME,PE=30*ME,FE=365*ME,IE=(e,t)=>{let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t-n.getTime();return r<3e4?`now`:r<jE?`${Math.max(1,Math.floor(r/AE))}m ago`:r<ME?`${Math.floor(r/jE)}h ago`:r<NE?`${Math.floor(r/ME)}d ago`:r<PE?`${Math.floor(r/NE)}w ago`:r<FE?`${Math.floor(r/PE)}mo ago`:`${Math.floor(r/FE)}y ago`},LE=(e,t)=>e.updatedAt<t.updatedAt?1:e.updatedAt>t.updatedAt?-1:0,RE=(e,t)=>{let n=e.archivedAt??``,r=t.archivedAt??``;return n<r?1:n>r?-1:0},zE=e=>{if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`},BE=1e3,VE=3e4,HE=async e=>{try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,``),t.style.cssText=`position:fixed;top:0;left:0;width:1px;height:1px;padding:0;border:0;opacity:0;pointer-events:none`,document.body.appendChild(t);try{return t.select(),t.setSelectionRange(0,t.value.length),document.execCommand(`copy`)}catch{return!1}finally{t.remove()}};function UE({workspace:e,x:t,y:n,notify:r,onClose:i}){let a=(0,z.useRef)(null),[o,s]=(0,z.useState)({left:t,top:n});(0,z.useLayoutEffect)(()=>{let e=a.current;if(!e)return;let r=e.getBoundingClientRect();s({left:Math.max(8,Math.min(t,window.innerWidth-r.width-8)),top:Math.max(8,Math.min(n,window.innerHeight-r.height-8))})},[t,n]),(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),i())},t=e=>{a.current?.contains(e.target)||i()},n={x:window.scrollX,y:window.scrollY,width:window.innerWidth,height:window.innerHeight},r=()=>{(window.scrollX!==n.x||window.scrollY!==n.y)&&i()},o=()=>{(window.innerWidth!==n.width||window.innerHeight!==n.height)&&i()};return window.addEventListener(`keydown`,e,!0),window.addEventListener(`pointerdown`,t,!0),window.addEventListener(`scroll`,r,!0),window.addEventListener(`resize`,o),()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`pointerdown`,t,!0),window.removeEventListener(`scroll`,i,!0),window.removeEventListener(`resize`,o)}},[i]);let c=async()=>{let t=await HE(e.path);i(),t?r(`已复制工作区路径:${e.path}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中路径复制`,`error`)};return(0,B.jsxs)(`div`,{ref:a,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-workspace-id":e.id,style:{left:o.left,top:o.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,B.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-workspace-path":e.id,onClick:()=>void c(),children:`复制工作区路径`}),(0,B.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.path})]})}function WE({conversation:e,x:t,y:n,notify:r,onRename:i,onClose:a}){let o=(0,z.useRef)(null),[s,c]=(0,z.useState)({left:t,top:n});(0,z.useLayoutEffect)(()=>{let e=o.current;if(!e)return;let r=e.getBoundingClientRect();c({left:Math.max(8,Math.min(t,window.innerWidth-r.width-8)),top:Math.max(8,Math.min(n,window.innerHeight-r.height-8))})},[t,n]),(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),a())},t=e=>{o.current?.contains(e.target)||a()},n={x:window.scrollX,y:window.scrollY,width:window.innerWidth,height:window.innerHeight},r=()=>{(window.scrollX!==n.x||window.scrollY!==n.y)&&a()},i=()=>{(window.innerWidth!==n.width||window.innerHeight!==n.height)&&a()};return window.addEventListener(`keydown`,e,!0),window.addEventListener(`pointerdown`,t,!0),window.addEventListener(`scroll`,r,!0),window.addEventListener(`resize`,i),()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`pointerdown`,t,!0),window.removeEventListener(`scroll`,a,!0),window.removeEventListener(`resize`,i)}},[a]);let l=async()=>{let t=await HE(e.id);a(),t?r(`已复制会话 ID:${e.id}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入`,`error`)};return(0,B.jsxs)(`div`,{ref:o,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-session-id":e.id,style:{left:s.left,top:s.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,B.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-session-id":e.id,onClick:()=>void l(),children:`复制会话 ID`}),(0,B.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-ai-rename-session":e.id,onClick:()=>{a(),i()},children:`AI 智能重命名`}),(0,B.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.id})]})}var GE={model:`模型`,thinking:`思考`,agent:`智能体`,subagent:`子智能体`},KE={model:`模型`,thinking:`思考等级`,agent:`智能体`,subagent:`子智能体`},qE={model:`选择模型`,thinking:`选择思考等级`,agent:`选择智能体`,subagent:`选择子智能体`},JE=`图文`,YE=e=>e.imageInput?JE:void 0,XE=e=>e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLowerCase(),ZE=(e,t)=>{let n=XE(t.trim());return n?e.filter(e=>XE(`${e.label} ${e.detail??``} ${e.badge??``}`).includes(n)):e};function QE({onClose:e,onCreate:t}){let[n,r]=(0,z.useState)(),[i,a]=(0,z.useState)(!0),[o,s]=(0,z.useState)(),[c,l]=(0,z.useState)(``),[u,d]=(0,z.useState)(``),f=async e=>{a(!0),s(void 0);try{let t=await fetch(`/api/fs/dirs${e?`?path=${encodeURIComponent(e)}`:``}`),n=await t.json();if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);let i=n;r(i),d(i.path),l(i.suggestedName)}catch(e){s(e instanceof Error?e.message:`目录加载失败`)}finally{a(!1)}};(0,z.useEffect)(()=>{f()},[]),(0,z.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let p=e=>{e?.preventDefault();let t=u.trim();t&&f(t)};return(0,B.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,B.jsxs)(`div`,{className:`picker workspace-picker`,onClick:e=>e.stopPropagation(),children:[(0,B.jsx)(`h2`,{children:`选择工作区目录`}),(0,B.jsxs)(`form`,{className:`picker-path-bar`,onSubmit:p,children:[(0,B.jsx)(`input`,{className:`picker-path-input`,value:u,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(DE(e)?e.preventDefault():(e.preventDefault(),p()))},placeholder:`输入或粘贴目录绝对路径(如 D:\\projects 或 ~/code)`}),(0,B.jsx)(`button`,{type:`submit`,className:`picker-go-btn`,disabled:!u.trim()||i,children:`跳转`}),(0,B.jsx)(`button`,{type:`button`,className:`picker-up-btn`,disabled:!n?.parent||i,onClick:()=>n?.parent&&void f(n.parent),title:`返回上一级目录`,children:`上一级`})]}),n?.drives?.length||n?.homeDir?(0,B.jsxs)(`div`,{className:`picker-shortcuts`,children:[(0,B.jsx)(`span`,{className:`picker-shortcuts-label`,children:`快捷位置:`}),n?.homeDir&&(0,B.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void f(`~`),title:n.homeDir,children:`🏠 主目录`}),n?.drives?.map(e=>(0,B.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void f(e),children:e},e))]}):null,(0,B.jsxs)(`div`,{className:`picker-list`,children:[i&&(0,B.jsx)(`div`,{className:`picker-status`,children:`加载中…`}),!i&&o&&(0,B.jsxs)(`div`,{className:`picker-error`,children:[o,(0,B.jsx)(`button`,{onClick:()=>void f(n?.path||u),children:`重试`})]}),!i&&!o&&n?.entries.map(e=>(0,B.jsxs)(`button`,{className:`picker-dir`,onClick:()=>void f(e.path),children:[`📁 `,e.name]},e.path)),!i&&!o&&n&&n.entries.length===0&&(0,B.jsx)(`div`,{className:`picker-status`,children:`此目录下没有子目录`}),!i&&!o&&n?.truncated&&(0,B.jsx)(`div`,{className:`picker-status`,children:`目录过多,仅显示前 2000 项`})]}),(0,B.jsxs)(`label`,{className:`picker-name`,children:[`工作区名称`,(0,B.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(DE(e)?e.preventDefault():(e.preventDefault(),c.trim()&&n&&t(c.trim(),n.path)))},placeholder:`工作区名称`})]}),(0,B.jsxs)(`div`,{className:`picker-actions`,children:[(0,B.jsx)(`button`,{className:`picker-cancel`,onClick:e,children:`取消`}),(0,B.jsx)(`button`,{className:`picker-ok`,disabled:!c.trim()||i||!!o||!n,onClick:()=>n&&t(c.trim(),n.path),children:`使用这个目录`})]})]})})}var $E={timeout:`扩展提问超时,已取消`,aborted:`运行已停止,扩展提问已取消`,expired:`运行已结束,扩展提问已取消`},eD=10;function tD(e,t){if(!t)return`正在从 Pi 读取${e}列表…`;if(t.source!==`pi`)return`读取 Pi ${e}列表失败:${t.error??`未知原因`}`}function nD(e){if(!e)return`正在读取 agent 列表…`;if(e.source!==`directory`)return`读取 agent 列表失败:${e.error??`未知原因`}`;if(e.problems.length)return`${e.problems.length} 个 agent 文件无法使用:${e.problems.map(e=>e.file).join(`、`)}`;if(!e.agents.length)return`${e.directory} 下没有 primary agent`}var rD=e=>Math.abs(e)<1e3?String(e):`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`;function iD(e){if(e===void 0||!Number.isFinite(e))return``;let t=Math.max(0,e);return t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:`${Math.floor(t/6e4)}分${Math.round(t%6e4/1e3)}秒`}var aD={dispatch:`派发时(子进程还没起来)`,prompt:`派活时(Pi 拒收了任务)`,turn:`生成回答时`,tool:`调用工具时`,settle:`收尾时`};function oD({task:e,initialOutput:t,expanded:n}){let[r,i]=(0,z.useState)(t);(0,z.useEffect)(()=>{let n=t,r,a=t=>{let a=t.detail;a.sessionId===e.id&&(n=(n+a.data).slice(-512e3),r===void 0&&(r=requestAnimationFrame(()=>{r=void 0,i(n)})))};return window.addEventListener(`super-pi-exec-output`,a),()=>{window.removeEventListener(`super-pi-exec-output`,a),r!==void 0&&cancelAnimationFrame(r)}},[e.id]);let a=e.output??r;return(0,B.jsxs)(B.Fragment,{children:[!n&&a&&(0,B.jsx)(`div`,{className:`call-live-preview`,"data-background-preview":e.id,title:`展开调用查看完整输出`,children:a.split(`
|
|
91
|
-
`).slice(-1)[0]}),n&&(0,B.jsx)(`pre`,{className:`call-result-body`,"data-background-output":e.id,children:a||`等待输出…`})]})}function
|
|
92
|
-
`).slice(-1)[0]}),n&&(0,B.jsx)(`div`,{className:`call-args`,"data-call-args":o.length,children:o.length===0?(0,B.jsx)(`div`,{className:`call-arg call-arg-empty`,"data-call-arg-empty":t,children:`(这次调用没有可显示的参数)`}):o.map(e=>(0,B.jsxs)(`div`,{className:`call-arg`,"data-call-arg":e.key,"data-call-arg-value":e.value,children:[(0,B.jsx)(`span`,{className:`call-arg-key`,children:e.key}),(0,B.jsx)(`span`,{className:`call-arg-value`,title:e.value,children:e.value})]},e.key))}),n&&(e.result||e.live||i)&&(0,B.jsxs)(`div`,{className:`call-result`,"data-call-result":t,"data-call-result-state":e.result?`done`:`running`,children:[(e.result||e.live)&&(0,B.jsxs)(`div`,{className:`call-result-head`,children:[(0,B.jsx)(`span`,{className:`call-result-title`,children:e.result&&!e.live?`执行结果`:e.result?`执行结果 · 完整输出`:`执行中 · 输出预览`}),e.result?(0,B.jsx)(cD,{index:t,text:e.live??e.result.text}):null]}),(e.result||e.live)&&(0,B.jsx)(`pre`,{className:`call-result-body`,"data-call-result-body":t,children:e.live??e.result?.text}),e.result?.truncated&&e.live&&(0,B.jsx)(`div`,{className:`call-result-truncated`,children:`(服务端已截断到末尾 8 KB;上方显示的是执行中累积的完整输出)`}),e.result?.truncated&&!e.live&&(0,B.jsxs)(`div`,{className:`call-result-truncated`,children:[`(输出过长,已保留末尾关键内容`,e.result.droppedLines?`,省略前 ${e.result.droppedLines} 行`:``,`)`]}),i]}),!n&&i,a]})}function cD({index:e,text:t}){let[n,r]=(0,z.useState)(!1);return(0,B.jsx)(`button`,{type:`button`,className:`call-result-copy`,"data-call-result-copy":e,onClick:async()=>{await HE(t)&&(r(!0),window.setTimeout(()=>r(!1),1600))},children:n?`已复制`:`复制`})}function lD({messageId:e,nestedCount:t,liveCall:n,liveExtra:r,preview:i,expanded:a,onToggle:o,children:s}){return(0,B.jsxs)(`section`,{className:`thinking-block`,"data-thinking-block":e,"data-thinking-expanded":a?`true`:`false`,"data-thinking-calls":t,children:[(0,B.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-thinking-fold-edge":e,"aria-expanded":a,"aria-label":`${a?`折叠`:`展开`}这段思考`,title:a?`折叠这段思考`:`展开这段思考`,onClick:o}),(0,B.jsxs)(`button`,{type:`button`,className:`thinking-head`,"data-thinking-head":e,"aria-expanded":a,title:a?`折叠这段思考`:`展开这段思考`,onClick:o,children:[(0,B.jsx)(`span`,{className:`thinking-chevron`,"aria-hidden":`true`,children:a?`▾`:`▸`}),(0,B.jsx)(`span`,{className:`thinking-label`,children:`思考`}),t>0&&(0,B.jsxs)(`span`,{className:`thinking-count`,"data-thinking-count":t,children:[t,` 次工具调用`]}),!a&&n&&(0,B.jsxs)(`span`,{className:`thinking-live`,"data-thinking-live":n,"data-thinking-live-extra":r??0,children:[(0,B.jsx)(`span`,{className:`thinking-live-glyph`,"aria-hidden":`true`,children:`⚙`}),`正在执行 `,n,r?` 等 ${r+1} 个`:``]}),!a&&i&&(0,B.jsx)(`span`,{className:`thinking-preview`,title:i,children:i})]}),a&&(0,B.jsx)(`div`,{className:`thinking-body`,"data-thinking-body":e,children:s})]})}function uD({run:e,name:t,expanded:n,onToggle:r,onStop:i,stopping:a}){let o=e.toolCalls??[],s=n?o:o.slice(-10),c=o.length-s.length,l=e.status===`running`,u=e.output??``,d=e.dispatchedBy===`model`,[f,p]=(0,z.useState)(0);(0,z.useEffect)(()=>{if(!l)return;p(Date.now());let e=window.setInterval(()=>p(Date.now()),200);return()=>window.clearInterval(e)},[l,e.startedAt]);let m=Date.parse(e.startedAt),h=l&&f>0&&Number.isFinite(m)?f-m:void 0,g=[...o].reverse().find(e=>e.status===void 0)?.label;return(0,B.jsxs)(`article`,{className:`subagent-card subagent-${e.status}${d?` subagent-by-model`:``}`,"data-subagent-card":e.id,"data-subagent-status":e.status,"data-subagent-agent":e.agentId,"data-subagent-tools":o.length,"data-subagent-dispatched-by":d?`model`:`human`,children:[(0,B.jsxs)(`div`,{className:`subagent-head`,children:[(0,B.jsx)(`span`,{className:`subagent-badge`,children:`子智能体`}),d&&(0,B.jsxs)(`span`,{className:`subagent-source`,"data-subagent-source":`model`,title:`primary 模型自己决定派这个子智能体去干活`,children:[(0,B.jsx)(`span`,{className:`subagent-source-glyph`,"aria-hidden":`true`,children:`⚡`}),`模型自主派发`]}),(0,B.jsx)(`strong`,{className:`subagent-name`,"data-subagent-name":`1`,children:t||e.agentId}),(0,B.jsx)(`span`,{className:`subagent-status`,"data-subagent-status-text":`1`,children:l?`运行中`:e.status===`completed`?`已完成`:e.status===`stopped`?`已停止`:`失败`}),l?h!==void 0&&(0,B.jsxs)(`span`,{className:`subagent-clock`,"data-subagent-elapsed":`1`,"data-subagent-elapsed-ms":h,children:[`已运行 `,iD(h)]}):e.durationMs!==void 0&&(0,B.jsxs)(`span`,{className:`subagent-duration`,"data-subagent-duration":`1`,"data-subagent-duration-ms":e.durationMs,children:[`用时 `,iD(e.durationMs)]}),l&&(0,B.jsx)(`button`,{type:`button`,className:`subagent-stop`,"data-subagent-stop":e.id,disabled:a,onClick:i,children:`停止`})]}),l&&e.activity&&(0,B.jsxs)(`div`,{className:`subagent-activity`,"data-subagent-activity":e.activity.kind,"data-subagent-activity-at":e.activity.at,children:[(0,B.jsx)(`span`,{className:`subagent-activity-dot`,"aria-hidden":`true`}),e.activity.kind===`tool`?`正在调用 ${e.activity.label??`工具`}`:`正在思考…`]}),(0,B.jsxs)(`div`,{className:`subagent-task`,"data-subagent-task":`1`,children:[d&&(0,B.jsx)(`span`,{className:`subagent-task-source`,"data-subagent-model-task":`1`,children:`模型给的任务`}),e.task]}),(0,B.jsx)(`div`,{className:`subagent-output`,"data-subagent-output":`1`,"data-live-length":u.length,children:u||(l?`…`:e.outputTruncated?`(已按 50 KB 上限截断,浏览器仍收到完整内容)`:`(没有输出)`)}),e.failure&&(0,B.jsxs)(`div`,{className:`subagent-failure`,"data-subagent-failure":`1`,"data-subagent-failure-stage":e.failure.stage,children:[(0,B.jsx)(`span`,{className:`subagent-failure-label`,children:`卡在`}),(0,B.jsx)(`span`,{className:`subagent-failure-stage`,"data-subagent-failure-text":`1`,children:aD[e.failure.stage]}),e.failure.stage===`tool`&&g&&(0,B.jsxs)(`span`,{className:`subagent-failure-tool`,"data-subagent-failure-tool":`1`,children:[`· 正在跑 `,g]}),o.length>0&&(0,B.jsxs)(`span`,{className:`subagent-failure-progress`,children:[`· 死前已尝试 `,o.length,` 次工具调用`]})]}),e.error&&(0,B.jsx)(`div`,{className:`subagent-error`,"data-subagent-error":`1`,children:e.error}),o.length>0&&(0,B.jsxs)(`div`,{className:`subagent-tools`,"data-subagent-tool-count":o.length,children:[c>0&&!n&&(0,B.jsxs)(`button`,{type:`button`,className:`subagent-more`,"data-subagent-hidden":c,onClick:r,children:[`… 另有 `,c,` 条工具调用`]}),s.map((e,t)=>(0,B.jsxs)(`div`,{className:`subagent-tool${e.status?` subagent-tool-${e.status}`:``}`,"data-subagent-tool":e.label,"data-subagent-tool-detail":e.detail??void 0,"data-subagent-tool-status":e.status??`running`,children:[(0,B.jsx)(`span`,{className:`subagent-tool-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,B.jsx)(`span`,{className:`subagent-tool-label`,title:e.label,children:e.label}),e.detail&&(0,B.jsx)(`span`,{className:`subagent-tool-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,B.jsx)(`span`,{className:`subagent-tool-duration`,children:iD(e.durationMs)})]},`${t}:${e.label}`))]}),e.usage&&(0,B.jsxs)(`div`,{className:`subagent-usage`,"data-subagent-usage":`1`,"data-subagent-turns":e.usage.turns,children:[(0,B.jsxs)(`span`,{children:[e.usage.turns,` turns`]}),(0,B.jsxs)(`span`,{children:[`↑`,rD(e.usage.input)]}),(0,B.jsxs)(`span`,{children:[`↓`,rD(e.usage.output)]}),e.usage.cacheRead>0&&(0,B.jsxs)(`span`,{children:[`cache↓`,rD(e.usage.cacheRead)]}),e.usage.cacheWrite>0&&(0,B.jsxs)(`span`,{children:[`cache↑`,rD(e.usage.cacheWrite)]}),e.usage.cost>0&&(0,B.jsxs)(`span`,{children:[`$`,e.usage.cost.toFixed(4)]})]}),o.length>10&&(0,B.jsx)(`button`,{type:`button`,className:`subagent-collapse`,"data-subagent-collapse":e.id,"aria-expanded":n,onClick:r,children:n?`收起`:`展开全部 ${o.length} 条`})]})}function dD({messages:e,running:t,onSteer:n,onInterrupt:r,onSend:i,onCancel:a,onEdit:o}){let[s,c]=(0,z.useState)(!1);if(!e.length)return null;let l=e.filter(e=>e.delivery===`sending`).length;return(0,B.jsxs)(`section`,{className:`queue-dock`,"data-queue-dock":`1`,"data-queue-count":e.length,"data-queue-sending":l,"aria-label":`排队等待回答的消息`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`queue-dock-head`,"data-queue-collapse":`1`,"aria-expanded":!s,onClick:()=>c(e=>!e),children:[(0,B.jsx)(`span`,{className:`chevron`,children:s?`▸`:`▾`}),(0,B.jsxs)(`strong`,{children:[e.length,` 条等待回答`]}),l>0&&(0,B.jsxs)(`span`,{className:`queue-dock-badge`,"data-queue-badge":`sending`,children:[`已交给 Agent `,l,` 条`]}),s&&(0,B.jsx)(`span`,{className:`queue-dock-preview`,children:fD(e[0])})]}),!s&&(0,B.jsx)(`ul`,{className:`queue-dock-list`,children:e.map((s,c)=>(0,B.jsx)(mD,{message:s,order:c+1,total:e.length,running:t,onSteer:n,onInterrupt:r,onSend:i,onCancel:a,onEdit:o},s.id))})]})}function fD(e){return e.content||(e.images?.length?`【图片】(${e.images.length})`:``)}function pD(e){if(e.role!==`tool`)return{label:`后台回传`,state:`completed`};let t=(()=>{let t=/<summary>([\s\S]*?)<\/summary>/.exec(e.content);return t?t[1].trim():`后台回传`})(),n=/<task id="[^"]+" state="([^"]+)"/.exec(e.content);return{label:t,state:n?n[1]:`completed`}}function mD({message:e,order:t,total:n,running:r,onSteer:i,onInterrupt:a,onSend:o,onCancel:s,onEdit:c}){let[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(e.content),p=e.delivery===`sending`,m=e.role===`tool`,{label:h,state:g}=m?pD(e):{label:fD(e),state:`user`},_=()=>{let t=d.trim();t&&t!==e.content&&c(e.id,t),u(!1)};return(0,B.jsxs)(`li`,{className:`queue-row ${p?`queue-row-sending`:`queue-row-queued`} ${m?`queue-row-bg-result`:``}`,"data-queue-id":e.id,"data-message-delivery":e.delivery,"data-message-role":e.role,"data-bg-result-state":m?g:void 0,"data-waiting-order":t,"data-waiting-total":n,children:[(0,B.jsx)(`span`,{className:`queue-index`,"aria-hidden":`true`,children:t}),m?(0,B.jsxs)(`span`,{className:`queue-bg-result`,title:h,children:[(0,B.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:g===`error`?`✕`:`↩`}),(0,B.jsx)(`span`,{className:`bg-result-label`,children:`后台回传`}),(0,B.jsx)(`span`,{className:`bg-result-summary`,children:h})]}):l?(0,B.jsxs)(`div`,{className:`queue-row-edit`,children:[(0,B.jsx)(`textarea`,{value:d,autoFocus:!0,rows:2,"aria-label":`修改这条等待中的消息`,onChange:e=>f(e.target.value),onKeyDown:t=>{t.key===`Escape`&&(t.preventDefault(),f(e.content),u(!1)),t.key===`Enter`&&(t.metaKey||t.ctrlKey)&&(t.preventDefault(),_())}}),(0,B.jsx)(`button`,{type:`button`,className:`queue-edit-save`,"data-waiting-save":e.id,onClick:_,children:`保存`}),(0,B.jsx)(`button`,{type:`button`,className:`queue-edit-cancel`,"data-waiting-cancel-edit":e.id,onClick:()=>{f(e.content),u(!1)},children:`取消`})]}):(0,B.jsx)(`span`,{className:`queue-text`,title:h,children:h}),(0,B.jsx)(`span`,{className:`queue-state`,"data-waiting-state":p?`sending`:`queued`,children:p?`已交给 Agent`:t===1?`下一条回答这条`:`等待回答 · 第 ${t} 条`}),p?(0,B.jsx)(`span`,{className:`queue-locked`,"data-waiting-locked":e.id,children:`暂时改不了`}):(0,B.jsxs)(B.Fragment,{children:[r?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`button`,{type:`button`,className:`queue-interrupt`,"data-waiting-interrupt":e.id,title:`停止当前任务,立即回答这条消息`,"aria-label":`停止当前任务并回答「${h}」`,onClick:()=>a(e.id),children:`打断并回答`}),(0,B.jsx)(`button`,{type:`button`,className:`queue-steer`,"data-waiting-steer":e.id,title:t===1?`当前工具完成后回答这条消息`:`插到最前:让它成为下一条被回答的消息`,"aria-label":t===1?`当前工具完成后回答「${h}」`:`让「${h}」插到最前`,onClick:()=>i(e.id),children:t===1?`当前工具完成后回答`:`插到最前`})]}):(0,B.jsx)(`button`,{type:`button`,className:`queue-steer`,"data-waiting-send":e.id,title:`现在就回答这条消息`,"aria-label":`现在就回答「${h}」`,onClick:()=>o(e.id),children:`现在就回答`}),!m&&(0,B.jsx)(`button`,{type:`button`,className:`queue-edit`,"data-waiting-edit":e.id,title:`回答这条之前改字`,"aria-label":`修改「${h}」`,onClick:()=>{f(e.content),u(!0)},children:`改字`}),(0,B.jsx)(`button`,{type:`button`,className:`queue-cancel`,"data-waiting-cancel":e.id,title:`撤回这条消息,它不会被回答`,"aria-label":`撤回「${h}」`,onClick:()=>s(e.id),children:`撤回`})]})]})}function hD({question:e,index:t,expanded:n,onToggle:r,onAnswer:i}){return(0,B.jsxs)(`div`,{className:`call-block question-block-${e.status}`,"data-call-block":t,"data-call-tool":`question`,"data-call-detail":`提问`,"data-call-status":e.status===`answered`?`ok`:e.status===`cancelled`?`error`:`running`,"data-call-expanded":n?`true`:`false`,"data-question-block":t,children:[(0,B.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-question-fold-edge":t,"aria-expanded":n,"aria-label":`${n?`折叠`:`展开`}提问`,title:n?`折叠这段提问`:`展开这段提问`,onClick:r}),(0,B.jsxs)(`div`,{className:`call-head-row`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:r,children:[(0,B.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,B.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`answered`?`✓`:e.status===`cancelled`?`✕`:`?`}),(0,B.jsx)(`span`,{className:`call-label`,children:`提问`}),(0,B.jsxs)(`span`,{className:`call-detail`,children:[e.items.length,` 个问题`]})]}),n&&(0,B.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:r,children:`收起`})]}),n&&(0,B.jsx)(`div`,{className:`question-body`,"data-question-body":t,children:(0,B.jsx)(gD,{question:e,onAnswer:i})})]})}function gD({question:e,onAnswer:t}){let[n,r]=(0,z.useState)(()=>Object.fromEntries((e.answers??[]).map(e=>[e.id,e.selected]))),[i,a]=(0,z.useState)(()=>e.answers?.map(e=>e.note??``).join(`
|
|
93
|
-
`)??``),o=(e,t,n)=>{r(r=>{let i=r[e]??[];return n?{...r,[e]:i.includes(t)?i.filter(e=>e!==t):[...i,t]}:{...r,[e]:[t]}})},s=()=>{t(e.items.map(e=>({id:e.id,selected:n[e.id]??[],...e.extraNote&&i.trim()?{note:i.trim()}:{}})),!1)},c=e.items.some(e=>(n[e.id]??[]).length>0);return(0,B.jsxs)(`div`,{className:`question-block question-${e.status}`,"data-question-status":e.status,children:[e.items.map(t=>(0,B.jsxs)(`div`,{className:`question-item`,children:[(0,B.jsx)(`div`,{className:`question-text`,children:t.header?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`span`,{className:`question-header`,children:t.header}),(0,B.jsx)(`span`,{className:`question-sep`,children:` · `}),(0,B.jsx)(tm,{source:t.question})]}):(0,B.jsx)(tm,{source:t.question})}),(0,B.jsx)(`div`,{className:`question-options`,"data-question-options":t.id,children:t.options.map(r=>{let i=(n[t.id]??[]).includes(r),a=e.status!==`pending`;return(0,B.jsxs)(`label`,{className:i?`is-chosen`:``,"data-chosen":a&&i?`1`:void 0,children:[(0,B.jsx)(`input`,{type:t.multiple?`checkbox`:`radio`,name:`q-${t.id}`,checked:i,disabled:a,onChange:()=>o(t.id,r,t.multiple)}),(0,B.jsx)(nm,{source:r}),a&&i?(0,B.jsx)(`span`,{className:`question-mark`,"aria-label":`已选择`,children:`✓`}):null]},r)})}),e.status===`pending`&&t.extraNote?(0,B.jsx)(`textarea`,{value:i,placeholder:`补充说明(可选)`,onChange:e=>a(e.target.value)}):e.status===`answered`&&(e.answers??[]).some(e=>e.note)?(0,B.jsxs)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:[`补充:`,(e.answers??[]).map(e=>e.note).filter(Boolean).join(`;`)]}):null,e.status===`cancelled`&&(0,B.jsx)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:`已取消,没有作答。`})]},t.id)),e.status===`pending`&&(0,B.jsxs)(`div`,{className:`question-actions`,children:[(0,B.jsx)(`button`,{type:`button`,onClick:s,disabled:!c,children:`提交`}),(0,B.jsx)(`button`,{type:`button`,className:`question-skip`,onClick:()=>t([],!0),children:`跳过`})]})]})}function _D({request:e,onAnswer:t,pending:n}){let[r,i]=(0,z.useState)(e.prefill??``),a=e.method===`input`||e.method===`editor`,o=(0,B.jsx)(`button`,{type:`button`,className:`extui-cancel`,onClick:()=>t({cancelled:!0}),children:`取消提问`});return(0,B.jsxs)(`article`,{className:`extui-card extui-${e.method}`,"data-request-id":e.requestId,"data-method":e.method,children:[(0,B.jsxs)(`div`,{className:`extui-head`,children:[(0,B.jsx)(`span`,{className:`extui-badge`,children:`扩展提问`}),e.timeoutMs!==void 0&&(0,B.jsxs)(`span`,{className:`extui-deadline`,children:[Math.round(e.timeoutMs/1e3),`s 超时`]})]}),n&&(0,B.jsx)(`p`,{role:`status`,children:`提交中…`}),(0,B.jsxs)(`fieldset`,{disabled:n,style:{border:0,padding:0,margin:0},children:[(0,B.jsx)(`h3`,{className:`extui-title`,children:e.title||e.method}),e.method===`confirm`&&(0,B.jsx)(`p`,{className:`extui-body`,children:e.message}),e.method===`select`&&(0,B.jsxs)(`div`,{className:`extui-options`,children:[(e.options??[]).map(e=>(0,B.jsx)(`button`,{type:`button`,className:`extui-option`,onClick:()=>t({value:e}),children:e},e)),(e.options??[]).length===0&&(0,B.jsx)(`p`,{className:`extui-body`,children:`扩展没有提供任何选项`})]}),a&&(0,B.jsxs)(`form`,{className:`extui-form`,onSubmit:e=>{e.preventDefault(),!n&&r.trim()&&t({value:r})},children:[e.method===`input`?(0,B.jsx)(`input`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&DE(e)&&e.preventDefault()},placeholder:e.placeholder??``}):(0,B.jsx)(`textarea`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&DE(e)&&e.preventDefault()}}),(0,B.jsxs)(`div`,{className:`extui-actions`,children:[(0,B.jsx)(`button`,{type:`submit`,className:`extui-primary`,disabled:!r.trim(),children:`提交`}),o]})]}),!a&&(0,B.jsxs)(`div`,{className:`extui-actions`,children:[e.method===`confirm`&&(0,B.jsx)(`button`,{type:`button`,className:`extui-primary`,onClick:()=>t({confirmed:!0}),children:`确认`}),e.method===`confirm`&&(0,B.jsx)(`button`,{type:`button`,className:`extui-no`,onClick:()=>t({confirmed:!1}),children:`拒绝`}),o]})]})]})}function vD({initial:e,label:t,onCommit:n,onClose:r}){let[i,a]=(0,z.useState)(e),o=(0,z.useRef)(null),s=(0,z.useRef)(!1);(0,z.useEffect)(()=>{o.current?.focus(),o.current?.select()},[]);let c=!i.trim(),l=()=>{s.current=!0,r()},u=()=>{if(c)return;let t=i.trim();(t===e||n(t))&&l()};return(0,B.jsxs)(`div`,{className:`inline-edit`,"data-editing":`1`,children:[(0,B.jsx)(`input`,{ref:o,className:`inline-edit-input`,value:i,"aria-label":t,onChange:e=>a(e.target.value),onKeyDown:e=>{if(e.key===`Enter`){if(DE(e))return;e.preventDefault(),u()}else e.key===`Escape`&&(e.preventDefault(),l())},onBlur:()=>{s.current||r()}}),(0,B.jsx)(`button`,{type:`button`,className:`inline-edit-ok`,title:`确认重命名`,"aria-label":`确认重命名`,disabled:c,onMouseDown:e=>e.preventDefault(),onClick:u,children:`✓`}),(0,B.jsx)(`button`,{type:`button`,className:`inline-edit-cancel`,title:`取消重命名`,"aria-label":`取消重命名`,onMouseDown:e=>e.preventDefault(),onClick:l,children:`✗`})]})}function yD({kind:e,label:t,value:n,detail:r,options:i,disabled:a,note:o,onChoose:s,scope:c}){let[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(``),[p,m]=(0,z.useState)(0),h=(0,z.useRef)(null),g=(0,z.useRef)(null),_=(0,z.useRef)(null),v=(0,z.useRef)(null),y=(0,z.useRef)([]),b=i.find(e=>e.selected),x=ZE(i,d),S=x.length===0?-1:Math.min(Math.max(p,0),x.length-1),C=S<0?void 0:x[S],w=(e=!1)=>{u(!1),e&&g.current?.focus()},T=()=>{f(``),m(Math.max(i.findIndex(e=>e.selected),0)),u(!0)},E=e=>m(t=>x.length?Math.min(Math.max(t+e,0),x.length-1):0);(0,z.useEffect)(()=>{if(!l)return;let e=e=>{h.current?.contains(e.target)||w()};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[l]),(0,z.useEffect)(()=>{if(!l)return;let e=h.current,t=t=>{e?.contains(t.relatedTarget)||w()};return e?.addEventListener(`focusout`,t),()=>e?.removeEventListener(`focusout`,t)},[l]),(0,z.useEffect)(()=>{l&&v.current?.focus()},[l]),(0,z.useEffect)(()=>{l&&S>=0&&y.current[S]?.scrollIntoView({block:`nearest`})},[l,S]),(0,z.useLayoutEffect)(()=>{if(!l)return;let e=_.current;if(!e)return;e.style.setProperty(`--picker-nudge`,`0px`),e.style.setProperty(`--picker-drop`,`0px`);let t=e.getBoundingClientRect(),n=Math.min(window.innerWidth-8-t.right,Math.max(8-t.left,0)),r=Math.min(window.innerHeight-8-t.bottom,Math.max(8-t.top,0));e.style.setProperty(`--picker-nudge`,`${n}px`),e.style.setProperty(`--picker-drop`,`${r}px`)},[l,x.length,i.length]);let D=e=>{if(l){if(e.key===`Escape`)e.preventDefault(),w(!0);else if(e.key===`ArrowDown`)e.preventDefault(),E(1);else if(e.key===`ArrowUp`)e.preventDefault(),E(-1);else if(e.key===`Home`)e.preventDefault(),m(0);else if(e.key===`End`)e.preventDefault(),m(Math.max(x.length-1,0));else if(e.key===`Enter`){if(DE(e))return;e.preventDefault(),C&&(s(C.key),w(!0))}}},O=`picker-list-${c??e}`,k=t=>`picker-option-${c??e}-${t}`;return(0,B.jsxs)(`div`,{className:`session-picker-item session-picker-${e}`,ref:h,onKeyDown:l?D:void 0,children:[(0,B.jsxs)(`button`,{ref:g,type:`button`,className:`session-picker-trigger`,disabled:a,"aria-haspopup":`listbox`,"aria-expanded":l,title:o??`${GE[e]}:${r?`${t} · ${r}`:t}`,"data-picker-trigger":e,"data-picker-value":n??t,"data-picker-selected":i.some(e=>e.selected),onClick:()=>l?w():T(),children:[(0,B.jsx)(`span`,{className:`session-picker-kind`,children:GE[e]}),(0,B.jsx)(`span`,{className:`session-picker-name`,children:t}),r&&(0,B.jsx)(`span`,{className:`session-picker-detail`,children:r}),(0,B.jsx)(`span`,{className:`session-picker-caret`,"aria-hidden":`true`,children:`▾`})]}),l&&(0,B.jsxs)(`div`,{className:`picker-menu`,ref:_,"data-picker-menu":e,"data-picker-highlight":S,children:[(0,B.jsxs)(`div`,{className:`picker-filter`,children:[(0,B.jsx)(`span`,{className:`picker-filter-icon`,"aria-hidden":`true`,children:`🔍`}),(0,B.jsx)(`input`,{ref:v,className:`picker-filter-input`,"data-picker-filter":e,role:`combobox`,"aria-label":`筛选${KE[e]}选项`,"aria-expanded":`true`,"aria-controls":O,"aria-autocomplete":`list`,"aria-activedescendant":C?k(S):void 0,value:d,placeholder:`输入以筛选…`,autoComplete:`off`,spellCheck:!1,onChange:e=>{f(e.target.value),m(0)}}),d&&(0,B.jsx)(`button`,{type:`button`,className:`picker-filter-clear`,"data-picker-filter-clear":e,title:`清空筛选`,"aria-label":`清空筛选`,onMouseDown:e=>e.preventDefault(),onClick:()=>{f(``),m(0),v.current?.focus()},children:`✕`})]}),b&&!x.some(e=>e.key===b.key)&&(0,B.jsxs)(`div`,{className:`picker-current`,"data-picker-current":e,"data-picker-current-value":b.key,children:[(0,B.jsx)(`span`,{className:`picker-current-label`,children:`当前`}),(0,B.jsx)(`span`,{className:`picker-current-value`,children:b.label})]}),(0,B.jsxs)(`div`,{className:`picker-list`,role:`listbox`,id:O,"aria-label":qE[e],children:[x.map((e,t)=>(0,B.jsxs)(`button`,{id:k(t),type:`button`,role:`option`,"aria-selected":e.selected,ref:e=>{y.current[t]=e},className:`picker-option${e.selected?` selected`:``}${t===S&&!e.selected?` preview`:``}`,"data-picker-option":e.key,"data-picker-option-selected":e.selected,"data-picker-highlight":t===S,onClick:()=>{s(e.key),w(!0)},children:[e.color&&(0,B.jsx)(`span`,{className:`picker-option-swatch`,style:{background:e.color},"aria-hidden":`true`}),(0,B.jsx)(`span`,{className:`picker-option-name`,children:e.label}),e.badge&&(0,B.jsx)(`span`,{className:`picker-option-badge`,"data-picker-option-badge":e.badge,children:e.badge}),e.detail&&(0,B.jsx)(`span`,{className:`picker-option-detail`,children:e.detail}),e.selected&&(0,B.jsx)(`span`,{className:`picker-option-mark`,"aria-hidden":`true`,children:`✓`})]},e.key)),x.length===0&&(0,B.jsx)(`div`,{className:`picker-empty`,"data-picker-empty":e,children:`没有匹配「${d.trim()}」的${KE[e]}`})]})]})]})}var bD=`__pi_default__`;function xD({workspace:e,catalog:t,agents:n,onSave:r,onRename:i,onClose:a}){let[o,s]=(0,z.useState)(e.defaultAgentId),[c,l]=(0,z.useState)(e.defaultModel),[u,d]=(0,z.useState)(e.defaultThinkingLevel);(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.defaultPrevented&&a()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a]);let f=t?.source===`pi`,p=[{key:bD,label:`跟随 Pi 默认`,detail:`不为新会话指定模型`,selected:c===void 0},...(t?.models??[]).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:e.detail,badge:YE(e),selected:c?.provider===e.provider&&c.modelId===e.modelId}))],m=[{key:bD,label:`跟随 Pi 默认`,detail:`不为新会话指定思考等级`,selected:u===void 0},...(t?.levels??[]).map(e=>({key:e,label:e,selected:e===u}))],h=e=>{if(e===bD){l(void 0);return}let n=(t?.models??[]).find(t=>t.provider===e.split(`/`)[0]&&t.modelId===e.split(`/`)[1]);n&&l({provider:n.provider,modelId:n.modelId,label:n.label})},g=e=>d(e===bD?void 0:e),_=[{key:bD,label:`跟随 Pi 默认`,detail:`新会话不使用任何 agent 角色`,selected:o===void 0},...(n?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:o===e.id}))];return(0,B.jsx)(`div`,{className:`overlay`,onClick:a,children:(0,B.jsxs)(`div`,{className:`picker settings-dialog`,"data-settings-dialog":`1`,onClick:e=>e.stopPropagation(),children:[(0,B.jsx)(`h2`,{children:`工作区设置`}),(0,B.jsxs)(`div`,{className:`settings-scope`,children:[e.name,` · 默认值只影响之后新建的会话,已有会话不变`]}),(0,B.jsxs)(`div`,{className:`settings-row`,children:[(0,B.jsx)(`span`,{className:`settings-label`,children:`默认智能体`}),(0,B.jsx)(yD,{kind:`agent`,scope:`settings-agent`,label:n?.agents.find(e=>e.id===o)?.name??`跟随 Pi 默认`,value:o??bD,detail:o?`${n?.agents.find(e=>e.id===o)?.toolSummary??``}`:void 0,options:_,disabled:!n||n.source===`unavailable`,note:nD(n),onChoose:e=>s(e===bD?void 0:e)})]}),(0,B.jsxs)(`div`,{className:`settings-row`,children:[(0,B.jsx)(`span`,{className:`settings-label`,children:`默认模型`}),(0,B.jsx)(yD,{kind:`model`,scope:`settings-model`,label:c?.label??`跟随 Pi 默认`,value:c?`${c.provider}/${c.modelId}`:bD,detail:c?`${c.provider}/${c.modelId}`:void 0,options:p,disabled:!f,note:tD(`模型`,t),onChoose:h})]}),(0,B.jsxs)(`div`,{className:`settings-row`,children:[(0,B.jsx)(`span`,{className:`settings-label`,children:`思考强度`}),(0,B.jsx)(yD,{kind:`thinking`,scope:`settings-thinking`,label:u??`跟随 Pi 默认`,value:u??bD,options:m,disabled:!f,note:tD(`思考等级`,t),onChoose:g})]}),(0,B.jsxs)(`div`,{className:`picker-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-rename`,"data-settings-rename":`1`,onClick:i,children:`重命名工作区`}),(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,"data-settings-cancel":`1`,onClick:a,children:`取消`}),(0,B.jsx)(`button`,{type:`button`,className:`picker-ok`,"data-settings-save":`1`,onClick:()=>r(o,c,u),children:`保存`})]})]})})}var SD=[{id:`main`,label:`主`,name:`主 tab`},{id:`tools`,label:`工具`,name:`工具 tab`},{id:`files`,label:`文件`,name:`文件 tab`},{id:`git`,label:`Git`,name:`Git tab`},{id:`terminal`,label:`终端`,name:`终端 tab`}],CD={waiting:`⋯`,running:``,failed:`!`,question:`?`,unread:`•`,idle:``},wD={waiting:`等待 LLM`,running:`进行中`,failed:`出错`,question:`等你回答`,unread:`有未读`,idle:`空闲`};function TD(e,t,n){return t?`question`:e.status===`failed`?`failed`:e.status===`waiting`?`waiting`:e.status===`running`?`running`:e.updatedAt>(n??``)?`unread`:`idle`}function ED({state:e}){let t=CD[e];return e===`idle`?null:(0,B.jsx)(`i`,{className:`session-state session-state-${e}`,"data-session-state":e,title:wD[e],"aria-label":wD[e],children:(0,B.jsx)(`i`,{className:`session-state-mark`,"aria-hidden":`true`,children:t})})}var DD={pending:`未开始`,in_progress:`进行中`,completed:`已完成`},OD={pending:`○`,in_progress:`◐`,completed:`✓`},kD={high:`高`,medium:`中`,low:`低`};function AD(e){let t=e.filter(e=>e.status!==`completed`).length;return e.length?t?`${t} 个未完成 / 共 ${e.length} 个`:`全部完成:${e.length} 个`:`0 个待办任务`}function jD({todo:e,index:t}){let n=e.id??`todo_${t}`;return(0,B.jsxs)(`li`,{className:`todo-item todo-${e.status}`,"data-todo-item":n,"data-todo-status":e.status,children:[(0,B.jsx)(`span`,{className:`todo-mark`,"aria-hidden":`true`,children:OD[e.status]}),(0,B.jsx)(`span`,{className:`todo-text`,children:e.content}),(0,B.jsx)(`span`,{className:`todo-status`,"data-todo-status-text":`1`,children:DD[e.status]}),e.priority&&(0,B.jsx)(`span`,{className:`todo-priority`,"data-todo-priority":e.priority,children:kD[e.priority]})]})}function MD({tasks:e,onStop:t}){return(0,B.jsx)(`ul`,{className:`bg-list`,"data-bg-task-count":e.length,children:e.map((e,n)=>{let r=e.id||`bg_${n}`,i=e.status?.trim()||`未知状态`;return(0,B.jsxs)(`li`,{className:`bg-item`,"data-bg-task":r,"data-bg-task-status":e.status??`unknown`,children:[(0,B.jsxs)(`div`,{className:`bg-item-header`,children:[(0,B.jsx)(`span`,{className:`bg-title`,children:e.title?.trim()||e.id||`未命名任务 ${n+1}`}),t&&(0,B.jsx)(`button`,{type:`button`,className:`bg-stop-btn`,"data-bg-task-stop":e.id,title:`终止后台任务`,onClick:()=>t(e.id),children:`终止`})]}),(0,B.jsxs)(`span`,{className:`bg-meta`,children:[e.agentId?.trim()&&(0,B.jsx)(`span`,{className:`bg-agent`,"data-bg-agent":e.agentId,children:e.agentId}),(0,B.jsx)(`span`,{className:`bg-status`,children:i})]})]},r)})})}function ND({todos:e,tasks:t,collapsed:n,onToggle:r,workspaceId:i,workspaceLabel:a,conversationId:o,connected:s,files:c,onOpenFile:l,onOpenChanged:u,activeTab:d,onSelectTab:f,sendCommand:p,registerTerminalSink:m}){let h=SD;return h.some(e=>e.id===d)||h[0].id,(0,B.jsx)(`div`,{className:`right-rail${n?` right-rail-collapsed`:``}`,role:`complementary`,"aria-label":`右侧栏`,"data-right-rail":`1`,"data-right-rail-collapsed":n,children:n?(0,B.jsx)(`button`,{type:`button`,className:`right-rail-open`,"data-right-rail-open":`1`,title:`展开右侧栏`,"aria-label":`展开右侧栏`,onClick:r,children:`‹`}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`right-rail-head`,children:[(0,B.jsx)(`div`,{className:`right-tabs`,role:`tablist`,"aria-label":`右侧栏 tab`,"data-right-tab-count":h.length,children:h.map(e=>(0,B.jsx)(`button`,{type:`button`,role:`tab`,id:`right-tab-${e.id}`,className:`right-tab${e.id===d?` right-tab-active`:``}`,"data-right-tab":e.id,"aria-selected":e.id===d,"aria-controls":`right-panel-${e.id}`,title:e.name,"aria-label":e.name,onClick:()=>f(e.id),children:e.label},e.id))}),(0,B.jsx)(`button`,{type:`button`,className:`right-rail-collapse`,"data-right-rail-collapse":`1`,title:`收起右侧栏(聊天区会变宽)`,"aria-label":`收起右侧栏`,onClick:r,children:`›`})]}),SD.filter(e=>e.id===d).map(n=>(0,B.jsxs)(`div`,{className:`right-rail-body`,role:`tabpanel`,id:`right-panel-${n.id}`,"aria-labelledby":`right-tab-${n.id}`,"data-right-panel":n.id,children:[n.id===`main`&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`rail-section-head`,children:[(0,B.jsx)(`h2`,{className:`rail-section-title`,children:`待办任务`}),(0,B.jsx)(`span`,{className:`rail-section-count`,"data-todo-summary":`1`,children:AD(e)})]}),e.length>0?(0,B.jsx)(`ol`,{className:`todo-list`,"data-todo-count":e.length,children:e.map((e,t)=>(0,B.jsx)(jD,{todo:e,index:t},e.id??`todo_${t}`))}):(0,B.jsx)(`p`,{className:`rail-empty`,"data-todo-empty":`1`,children:`暂无待办任务。Agent 开始处理多步骤任务时,会自己把待办写到这里。`}),(0,B.jsxs)(`div`,{className:`rail-section-head`,children:[(0,B.jsx)(`h2`,{className:`rail-section-title`,children:`后台任务`}),(0,B.jsx)(`span`,{className:`rail-section-count`,"data-bg-summary":`1`,children:t.length?`${t.length} 个运行中`:`0 个`})]}),t.length>0?(0,B.jsx)(MD,{tasks:t,onStop:e=>p({type:`backgroundTask.stop`,taskId:e})}):(0,B.jsx)(`p`,{className:`rail-empty`,"data-bg-empty":`1`,children:`当前没有正在运行的后台任务。`})]}),n.id===`tools`&&(0,B.jsx)(ID,{}),n.id===`files`&&(0,B.jsx)(Ng,{workspaceId:i,files:c,onOpenFile:l,onOpenChanged:u}),n.id===`git`&&(0,B.jsx)(tp,{workspaceId:i??null,conversationId:o,onOpenChanged:u},o||`global`),n.id===`terminal`&&(0,B.jsx)(lE,{workspaceId:i,workspaceLabel:a,conversationId:o,connected:s,sendCommand:p,registerSink:m},o||`global`)]},n.id))]})})}function PD(){try{if(typeof window>`u`)return l_.slice();let e=h_(window.localStorage.getItem(f_));return window.localStorage.getItem(`super-pi:tools:v1`)===null?l_.slice():e}catch{return l_.slice()}}function FD(e){try{if(typeof window>`u`)return;window.localStorage.setItem(f_,g_(e))}catch{}}function ID(){let[e,t]=(0,z.useState)(PD),[n,r]=(0,z.useState)([]),[i,a]=(0,z.useState)(),[o,s]=(0,z.useState)(!1),[c,l]=(0,z.useState)(),u=e.find(e=>e.id===i),d=(0,z.useCallback)(async()=>{try{let e=await fetch(`/api/tools`),t=await e.json();e.ok&&Array.isArray(t.tools)&&r(t.tools.filter(e=>e.enabled))}catch{}},[]),f=async e=>{l(void 0);try{let t=await fetch(`/api/tools?id=${encodeURIComponent(e)}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);a(t=>t===e?void 0:t),await d()}catch(e){l(`移除工具失败:${e instanceof Error?e.message:String(e)}`)}};return(0,z.useEffect)(()=>{FD(e)},[e]),(0,z.useEffect)(()=>{d();let e=()=>{d()};return window.addEventListener(`super-pi-tools-updated`,e),()=>window.removeEventListener(`super-pi-tools-updated`,e)},[d]),(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`rail-section-head`,children:[(0,B.jsx)(`h2`,{className:`rail-section-title`,children:`工具`}),(0,B.jsxs)(`span`,{className:`rail-section-count`,"data-tool-summary":`1`,children:[e.length+n.length,` 个`]})]}),e.length+n.length>0?(0,B.jsxs)(`ul`,{className:`tool-grid`,"data-tool-count":e.length+n.length,children:[e.map(e=>(0,B.jsxs)(`li`,{className:`tool-slot`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`tool-icon`,"data-tool-icon":e.id,"data-tool-kind":e.kind,"data-tool-state":e.id===i?`open`:`idle`,title:`打开${e.name}`,"aria-label":`打开${e.name}`,"aria-current":e.id===i?`true`:void 0,onClick:()=>a(t=>t===e.id?void 0:e.id),children:[(0,B.jsx)(`span`,{className:`tool-icon-glyph`,"aria-hidden":`true`,children:e.glyph}),(0,B.jsx)(`span`,{className:`tool-icon-name`,children:e.name})]}),e.kind===`link`&&(0,B.jsx)(`button`,{type:`button`,className:`tool-remove`,"data-tool-remove":e.id,title:`移除${e.name}`,"aria-label":`移除${e.name}`,onClick:()=>{t(t=>b_(t,e.id)),i===e.id&&a(void 0)},children:`✕`})]},e.id)),n.map(e=>(0,B.jsxs)(`li`,{className:`tool-slot`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`tool-icon`,"data-mounted-tool-icon":e.id,title:`打开${e.name}`,"aria-label":`打开${e.name}`,onClick:()=>a(t=>t===e.id?void 0:e.id),children:[(0,B.jsx)(`span`,{className:`tool-icon-glyph`,"aria-hidden":`true`,children:`🧩`}),(0,B.jsx)(`span`,{className:`tool-icon-name`,children:e.name})]}),(0,B.jsx)(`button`,{type:`button`,className:`tool-remove`,"data-tool-remove":e.id,title:`移除${e.name}`,"aria-label":`移除${e.name}`,onClick:()=>void f(e.id),children:`✕`})]},e.id))]}):(0,B.jsx)(`p`,{className:`rail-empty`,"data-tool-empty":`1`,children:`还没有工具。点下面的「工具设置」添加。`}),(0,B.jsx)(`button`,{type:`button`,className:`tools-settings-btn`,"data-tool-settings-trigger":`1`,title:`添加预置工具、网址工具与说明`,"aria-label":`打开工具设置`,onClick:()=>{a(void 0),s(!0)},children:`⚙ 工具设置`}),c&&(0,B.jsx)(`p`,{role:`alert`,"data-tool-error":`1`,children:c}),o&&(0,B.jsx)(LD,{tools:e,onToolsChange:t,mountedTools:n,onRefreshMountedTools:d,onClose:()=>s(!1)}),u&&(0,B.jsx)(BD,{tool:u,onClose:()=>a(void 0)}),n.find(e=>e.id===i)&&(0,B.jsx)(qD,{tool:n.find(e=>e.id===i),onClose:()=>a(void 0)})]})}function LD({tools:e,onToolsChange:t,mountedTools:n,onRefreshMountedTools:r,onClose:i}){let[a,o]=(0,z.useState)(``),[s,c]=(0,z.useState)(``),[l,u]=(0,z.useState)(),[d,f]=(0,z.useState)(!1),[p,m]=(0,z.useState)(),[h,g]=(0,z.useState)(),[_,v]=(0,z.useState)(),[y,b]=(0,z.useState)(``),[x,S]=(0,z.useState)(),[C,w]=(0,z.useState)(),[T,E]=(0,z.useState)(!1),[D,O]=(0,z.useState)(),[k,A]=(0,z.useState)(),ee=(0,z.useRef)(null),j=(0,z.useRef)(null),M=async()=>{let e=await HE(`请为 Super Pi 开发一个全局右侧栏工具。不要启动独立 HTTP 服务器,也不要监听端口。
|
|
87
|
+
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),_C&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=BC(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=tC(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-VC),VC),t/=VC,t/Math.abs(t)+Math.round(t*(HC-1)))}shouldForceSelection(e){return pC?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),UC)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(pC&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let e=n.lines.get(this._model.selectionEnd[1]);e&&e.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<WC&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=EC(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);n?!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n):this._oldHasSelection&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c<o.length&&o.charAt(c+1)===` `;)c++}else{let t=e[0],n=e[0];a.getWidth(t)===0&&(u++,t--),a.getWidth(n)===2&&(d++,n++);let r=a.getString(n).length;for(r>1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(n+1,this._workCell));){a.loadCell(n+1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,n++):e>1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(t||o.slice(s,c).trim()!==``){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=BC(n,this._bufferService.cols)}};KC=dv([X(3,Rv),X(4,Bv),X(5,Qv),X(6,Wv),X(7,$v),X(8,Zv)],KC);var qC=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},JC=class{constructor(){this._color=new qC,this._css=new qC}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},YC=Object.freeze((()=>{let e=[CS.toColor(`#2e3436`),CS.toColor(`#cc0000`),CS.toColor(`#4e9a06`),CS.toColor(`#c4a000`),CS.toColor(`#3465a4`),CS.toColor(`#75507b`),CS.toColor(`#06989a`),CS.toColor(`#d3d7cf`),CS.toColor(`#555753`),CS.toColor(`#ef2929`),CS.toColor(`#8ae234`),CS.toColor(`#fce94f`),CS.toColor(`#729fcf`),CS.toColor(`#ad7fa8`),CS.toColor(`#34e2e2`),CS.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:xS.toCss(r,i,a),rgba:xS.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:xS.toCss(n,n,n),rgba:xS.toRgba(n,n,n)})}return e})()),XC=CS.toColor(`#ffffff`),ZC=CS.toColor(`#000000`),QC=CS.toColor(`#ffffff`),$C=ZC,ew={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},tw=XC,nw=class extends Dy{constructor(e){super(),this._optionsService=e,this._contrastCache=new JC,this._halfContrastCache=new JC,this._onChangeColors=this._register(new Z),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:XC,background:ZC,cursor:QC,cursorAccent:$C,selectionForeground:void 0,selectionBackgroundTransparent:ew,selectionBackgroundOpaque:SS.blend(ZC,ew),selectionInactiveBackgroundTransparent:ew,selectionInactiveBackgroundOpaque:SS.blend(ZC,ew),scrollbarSliderBackground:SS.opacity(XC,.2),scrollbarSliderHoverBackground:SS.opacity(XC,.4),scrollbarSliderActiveBackground:SS.opacity(XC,.5),overviewRulerBorder:XC,ansi:YC.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=rw(e.foreground,XC),t.background=rw(e.background,ZC),t.cursor=SS.blend(t.background,rw(e.cursor,QC)),t.cursorAccent=SS.blend(t.background,rw(e.cursorAccent,$C)),t.selectionBackgroundTransparent=rw(e.selectionBackground,ew),t.selectionBackgroundOpaque=SS.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=rw(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=SS.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?rw(e.selectionForeground,bS):void 0,t.selectionForeground===bS&&(t.selectionForeground=void 0),SS.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=SS.opacity(t.selectionBackgroundTransparent,.3)),SS.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=SS.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=rw(e.scrollbarSliderBackground,SS.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=rw(e.scrollbarSliderHoverBackground,SS.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=rw(e.scrollbarSliderActiveBackground,SS.opacity(t.foreground,.5)),t.overviewRulerBorder=rw(e.overviewRulerBorder,tw),t.ansi=YC.slice(),t.ansi[0]=rw(e.black,YC[0]),t.ansi[1]=rw(e.red,YC[1]),t.ansi[2]=rw(e.green,YC[2]),t.ansi[3]=rw(e.yellow,YC[3]),t.ansi[4]=rw(e.blue,YC[4]),t.ansi[5]=rw(e.magenta,YC[5]),t.ansi[6]=rw(e.cyan,YC[6]),t.ansi[7]=rw(e.white,YC[7]),t.ansi[8]=rw(e.brightBlack,YC[8]),t.ansi[9]=rw(e.brightRed,YC[9]),t.ansi[10]=rw(e.brightGreen,YC[10]),t.ansi[11]=rw(e.brightYellow,YC[11]),t.ansi[12]=rw(e.brightBlue,YC[12]),t.ansi[13]=rw(e.brightMagenta,YC[13]),t.ansi[14]=rw(e.brightCyan,YC[14]),t.ansi[15]=rw(e.brightWhite,YC[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<n;r++)t.ansi[r+16]=rw(e.extendedAnsi[r],YC[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0)for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];else switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};nw=dv([X(0,Wv)],nw);function rw(e,t){if(e!==void 0)try{return CS.toColor(e)}catch{}return t}var iw=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},aw=class{constructor(){this._services=new iw,this._services.set(Hv,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=Fv(e).sort((e,t)=>e.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},ow={trace:0,debug:1,info:2,warn:3,error:4,off:5},sw=`xterm.js: `,cw=class extends Dy{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),lw=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=ow[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:sw)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};cw=dv([X(0,Wv)],cw);var lw,uw=class extends Dy{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new Z),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new Z),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new Z),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},dw=3,fw=Object.freeze(new kv),pw=0,mw=2,hw=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*dw);let r=t||jv.fromCharData([0,Dv,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*dw+0],n=t&2097151;return[this._data[e*dw+1],t&2097152?this._combined[e]:n?Cv(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*dw+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*dw+0]=e|2097152|t[2]<<22):this._data[e*dw+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*dw+0]>>22}hasWidth(e){return this._data[e*dw+0]&12582912}getFg(e){return this._data[e*dw+1]}getBg(e){return this._data[e*dw+2]}hasContent(e){return this._data[e*dw+0]&4194303}getCodePoint(e){let t=this._data[e*dw+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*dw+0]&2097152}getString(e){let t=this._data[e*dw+0];return t&2097152?this._combined[e]:t&2097151?Cv(t&2097151):``}isProtected(e){return this._data[e*dw+2]&536870912}loadCell(e,t){return pw=e*dw,t.content=this._data[pw+0],t.fg=this._data[pw+1],t.bg=this._data[pw+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*dw+0]=t.content,this._data[e*dw+1]=t.fg,this._data[e*dw+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*dw+0]=t|n<<22,this._data[e*dw+1]=r.fg,this._data[e*dw+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*dw+0];r&2097152?this._combined[e]+=Cv(t):r&2097151?(this._combined[e]=Cv(r&2097151)+Cv(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*dw+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new jv;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new jv;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)===0&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return this._data.length*4*mw<this._data.buffer.byteLength;let n=e*dw;if(e>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*mw<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*mw<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*dw+0]&4194303)return e+(this._data[e*dw+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*dw+0]&4194303||this._data[e*dw+2]&50331648)return e+(this._data[e*dw+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<dw;e++)this._data[(n+i)*dw+e]=a[(t+i)*dw+e];a[(t+i)*dw+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<dw;e++)this._data[(n+i)*dw+e]=a[(t+i)*dw+e];a[(t+i)*dw+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[t*dw+0],n=e&2097151,a=e&2097152?this._combined[t]:n?Cv(n):Ov;if(i+=a,r)for(let e=0;e<a.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}};function gw(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(!a&&r>=s&&r<c){s+=u.length-1;continue}let d=0,f=bw(u,d,t),p=1,m=0;for(;p<u.length;){let e=bw(u,p,t),r=e-m,a=n-f,o=Math.min(r,a);u[d].copyCellsFrom(u[p],m,f,o,!1),f+=o,f===n&&(d++,f=0),m+=o,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(n-1)===2&&(u[d].copyCellsFrom(u[d-1],n-1,f++,1,!1),u[d-1].setCell(n-1,i))}u[d].replaceCells(f,n,i);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function _w(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}}function vw(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length}function yw(e,t,n){let r=[],i=e.map((n,r)=>bw(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;s<i;){if(i-s<n){r.push(i-s);break}a+=n;let c=bw(e,o,t);a>c&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function bw(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var xw=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new Z),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Sy(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};xw._nextId=1;var Sw=xw,Cw={},ww=Cw.B;Cw[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:``,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},Cw.A={"#":`£`},Cw.B=void 0,Cw[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},Cw.C=Cw[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Cw.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},Cw.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},Cw.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},Cw.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},Cw.E=Cw[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},Cw.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},Cw.H=Cw[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},Cw[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var Tw=4294967295,Ew=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=fw.clone(),this.savedCharset=ww,this.markers=[],this._nullCell=jv.fromCharData([0,Dv,1,0]),this._whitespaceCell=jv.fromCharData([0,Ov,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new SC,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new uw(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new Av),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new Av),this._whitespaceCell}getBlankLine(e,t){return new hw(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>Tw?Tw:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=fw);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new uw(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(fw),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new hw(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new hw(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=gw(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(fw),n);if(r.length>0){let n=_w(this.lines,r);vw(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(fw),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new hw(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=this.getNullCell(fw),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let l=c[c.length-1].getTrimmedLength(),u=yw(c,this._cols,e),d=u.length-c.length,f;f=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+d):Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let e=0;e<d;e++){let e=this.getBlankLine(fw,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=bw(c,Math.max(g,0),this._cols))}for(let t=0;t<c.length;t++)u[t]<e&&c[t].setCell(u[t],r);let v=d-f;for(;v-->0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(i.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,r=n-1,o=0,s=i[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+a-1);l>=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new Sw(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},Dw=class extends Dy{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Z),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(`scrollback`,()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,()=>this.setupTabStops()))}reset(){this._normal=new Ew(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new Ew(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},Ow=2,kw=1,Aw=class extends Dy{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Z),this.onResize=this._onResize.event,this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,Ow),this.rows=Math.max(e.rawOptions.rows||0,kw),this.buffers=this._register(new Dw(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};Aw=dv([X(0,Wv)],Aw);var jw={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:pC,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},Mw=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],Nw=class extends Dy{constructor(e){super(),this._onOptionChange=this._register(new Z),this.onOptionChange=this._onOptionChange.event;let t={...jw};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(wy(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in jw))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in jw))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=jw[e],!Pw(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=jw[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=Mw.includes(t)?t:jw[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function Pw(e){return e===`block`||e===`underline`||e===`bar`}function Fw(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&Fw(e[r],t-1);return n}var Iw=Object.freeze({insertMode:!1}),Lw=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),Rw=class extends Dy{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new Z),this.onData=this._onData.event,this._onUserInput=this._register(new Z),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Z),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Z),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=Fw(Iw),this.decPrivateModes=Fw(Lw)}reset(){this.modes=Fw(Iw),this.decPrivateModes=Fw(Lw)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};Rw=dv([X(0,Rv),X(1,Uv),X(2,Wv)],Rw);var zw={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function Bw(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var Vw=String.fromCharCode,Hw={DEFAULT:e=>{let t=[Bw(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${Vw(t[0])}${Vw(t[1])}${Vw(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Bw(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${Bw(e,!0)};${e.x};${e.y}${t}`}},Uw=class extends Dy{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new Z),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(zw))this.addProtocol(e,zw[e]);for(let e of Object.keys(Hw))this.addEncoding(e,Hw[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};Uw=dv([X(0,Rv),X(1,Bv),X(2,Wv)],Uw);var Ww=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],Gw=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],Kw;function qw(e,t){let n=0,r=t.length-1,i;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e<t[i][0])r=i-1;else return!0;return!1}var Jw=class{constructor(){if(this.version=`6`,!Kw){Kw=new Uint8Array(65536),Kw.fill(1),Kw[0]=0,Kw.fill(0,1,32),Kw.fill(0,127,160),Kw.fill(2,4352,4448),Kw[9001]=2,Kw[9002]=2,Kw.fill(2,11904,42192),Kw[12351]=1,Kw.fill(2,44032,55204),Kw.fill(2,63744,64256),Kw.fill(2,65040,65050),Kw.fill(2,65072,65136),Kw.fill(2,65280,65377),Kw.fill(2,65504,65511);for(let e=0;e<Ww.length;++e)Kw.fill(0,Ww[e][0],Ww[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?Kw[e]:qw(e,Gw)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=Yw.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return Yw.createPropertyValue(0,n,r)}},Yw=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new Z,this.onChange=this._onChange.event;let e=new Jw;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a<i;++a){let o=t.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},Xw=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function Zw(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var Qw=2147483647,$w=256,eT=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>$w)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e<t.length;++e){let r=t[e];if(Array.isArray(r))for(let e=0;e<r.length;++e)n.addSubParam(r[e]);else n.addParam(r)}return n}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>Qw?Qw:e}}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>Qw?Qw:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,Qw):e}},tT=[],nT=class{constructor(){this._state=0,this._active=tT,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=tT}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=tT,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||tT,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,wv(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3){if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}}this._active=tT,this._id=-1,this._state=0}}},rT=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=wv(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},iT=[],aT=class{constructor(){this._handlers=Object.create(null),this._active=iT,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=iT}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=iT,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||iT,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,wv(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=iT,this._ident=0}},oT=new eT;oT.addParam(0);var sT=class{constructor(e){this._handler=e,this._data=``,this._params=oT,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():oT,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=wv(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=oT,this._data=``,this._hitLimit=!1,e));return this._params=oT,this._data=``,this._hitLimit=!1,t}},cT=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}},lT=160,uT=function(){let e=new cT(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(lT,0,2,0),e.add(lT,8,5,8),e.add(lT,6,0,6),e.add(lT,11,0,11),e.add(lT,13,13,13),e}(),dT=class extends Dy{constructor(e=uT){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new eT,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(wy(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new nT),this._dcsParser=this._register(new aT),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state){if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}}for(let n=a;n<t;++n){switch(r=e[n],i=this._transitions.table[this.currentState<<8|(r<160?r:lT)],i>>4){case 2:for(let i=n+1;;++i)if(i>=t||(r=e[i])<32||r>126&&r<lT||++i>=t||(r=e[i])<32||r>126&&r<lT||++i>=t||(r=e[i])<32||r>126&&r<lT||++i>=t||(r=e[i])<32||r>126&&r<lT){this._printHandler(e,n,i),n=i-1;break}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|r],s=a?a.length-1:-1;for(;s>=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n<t&&(r=e[n])>47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r<lT){this._dcsParser.put(e,n,i),n=i-1;break}break;case 14:if(o=this._dcsParser.unhook(r!==24&&r!==26),o)return this._preserveStack(6,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=n+1;;i++)if(i>=t||(r=e[i])<32||r>127&&r<lT){this._oscParser.put(e,n,i),n=i-1;break}break;case 6:if(o=this._oscParser.end(r!==24&&r!==26),o)return this._preserveStack(5,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=i&15}}},fT=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,pT=/^[\da-f]+$/;function mT(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=fT.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),pT.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}}function hT(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function gT(e,t=16){let[n,r,i]=e;return`rgb:${hT(n,t)}/${hT(r,t)}/${hT(i,t)}`}var _T={"(":0,")":1,"*":2,"+":3,"-":1,".":2},vT=131072,yT=10;function bT(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var xT=5e3,ST=0,CT=class extends Dy{constructor(e,t,n,r,i,a,o,s,c=new dT){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new Tv,this._utf8Decoder=new Ev,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=fw.clone(),this._eraseAttrDataInternal=fw.clone(),this._onRequestBell=this._register(new Z),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new Z),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new Z),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new Z),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new Z),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new Z),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new Z),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new Z),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new Z),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new Z),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new Z),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new Z),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new Z),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new wT(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler($.BEL,()=>this.bell()),this._parser.setExecuteHandler($.LF,()=>this.lineFeed()),this._parser.setExecuteHandler($.VT,()=>this.lineFeed()),this._parser.setExecuteHandler($.FF,()=>this.lineFeed()),this._parser.setExecuteHandler($.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler($.BS,()=>this.backspace()),this._parser.setExecuteHandler($.HT,()=>this.tab()),this._parser.setExecuteHandler($.SO,()=>this.shiftOut()),this._parser.setExecuteHandler($.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(pS.IND,()=>this.index()),this._parser.setExecuteHandler(pS.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(pS.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new rT(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new rT(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new rT(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new rT(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new rT(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new rT(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new rT(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new rT(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new rT(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new rT(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new rT(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new rT(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:`7`},()=>this.saveCursor()),this._parser.registerEscHandler({final:`8`},()=>this.restoreCursor()),this._parser.registerEscHandler({final:`D`},()=>this.index()),this._parser.registerEscHandler({final:`E`},()=>this.nextLine()),this._parser.registerEscHandler({final:`H`},()=>this.tabSet()),this._parser.registerEscHandler({final:`M`},()=>this.reverseIndex()),this._parser.registerEscHandler({final:`=`},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:`>`},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:`c`},()=>this.fullReset()),this._parser.registerEscHandler({final:`n`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`o`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`|`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`}`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`~`},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:`%`,final:`@`},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:`%`,final:`G`},()=>this.selectDefaultCharset());for(let e in Cw)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new sT((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),xT))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${xT} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>vT&&(a=this._parseStack.position+vT)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<vT&&(this._parseBuffer=new Uint32Array(Math.min(e.length,vT))),o||this._dirtyRowTracker.clearRange(),e.length>vT)for(let t=a;t<e.length;t+=vT){let a=t+vT<e.length?t+vT:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==r||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(s,this._bufferService.rows-1)})}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;p<n;++p){if(r=e[p],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,f);i=Yw.extractWidth(t);let n=Yw.extractShouldJoin(t),m=n?Yw.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire(Cv(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>s){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof hw&&d.copyCellsFrom(e,t,0,m,!1);t<s;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-m;--e>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}else if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<s&&n-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!bT(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new sT(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new rT(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(fw));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=Yw.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent($.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent($.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent($.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent($.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent($.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,ww),this._charsetService.setgCharset(1,ww),this._charsetService.setgCharset(2,ww),this._charsetService.setgCharset(3,ww);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e,t){let n;(e=>(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${$.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=kv.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=fw.fg,e.bg=fw.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=fw.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=fw.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=fw.fg&16777215,r.bg&=-67108864,r.bg|=fw.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${$.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=fw.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!bT(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${$.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>yT&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>yT&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(TT(n)){if(r===`?`)t.push({type:0,index:n});else{let e=mT(r);e&&t.push({type:1,index:n,color:e})}}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=mT(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);TT(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,ww),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(_T[e[0]],Cw[e[1]]||ww),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=fw.clone(),this._eraseAttrDataInternal=fw.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new jv;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=e=>(this._coreService.triggerDataEvent(`${$.ESC}${e}${$.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},wT=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(ST=e,e=t,t=ST),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};wT=dv([X(0,Rv)],wT);function TT(e){return 0<=e&&e<256}var ET=5e7,DT=12,OT=50,kT=class extends Dy{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new Z),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>ET)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=DT?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=DT)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>OT&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},AT=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};AT=dv([X(0,Rv)],AT);var jT=!1,MT=class extends Dy{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new Oy),this._onBinary=this._register(new Z),this.onBinary=this._onBinary.event,this._onData=this._register(new Z),this.onData=this._onData.event,this._onLineFeed=this._register(new Z),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Z),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Z),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Z),this._instantiationService=new aw,this.optionsService=this._register(new Nw(e)),this._instantiationService.setService(Wv,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(Aw)),this._instantiationService.setService(Rv,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(cw)),this._instantiationService.setService(Uv,this._logService),this.coreService=this._register(this._instantiationService.createInstance(Rw)),this._instantiationService.setService(Bv,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(Uw)),this._instantiationService.setService(zv,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Yw)),this._instantiationService.setService(Kv,this.unicodeService),this._charsetService=this._instantiationService.createInstance(Xw),this._instantiationService.setService(Vv,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(AT),this._instantiationService.setService(Gv,this._oscLinkService),this._inputHandler=this._register(new CT(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(Fy.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(Fy.forward(this._bufferService.onResize,this._onResize)),this._register(Fy.forward(this.coreService.onData,this._onData)),this._register(Fy.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new kT((e,t)=>this._inputHandler.parse(e,t))),this._register(Fy.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Z),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!jT&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),jT=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,Ow),t=Math.max(t,kw),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(Zw.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(Zw(this._bufferService),!1))),this._windowsWrappingHeuristics.value=wy(()=>{for(let t of e)t.dispose()})}}},NT={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function PT(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=+!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?$.ESC+`OA`:$.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?$.ESC+`OD`:$.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?$.ESC+`OC`:$.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?$.ESC+`OB`:$.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:$.DEL,e.altKey&&(i.key=$.ESC+i.key);break;case 9:if(e.shiftKey){i.key=$.ESC+`[Z`;break}i.key=$.HT,i.cancel=!0;break;case 13:i.key=e.altKey?$.ESC+$.CR:$.CR,i.cancel=!0;break;case 27:i.key=$.ESC,e.altKey&&(i.key=$.ESC+$.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`D`:t?$.ESC+`OD`:$.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`C`:t?$.ESC+`OC`:$.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`A`:t?$.ESC+`OA`:$.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`B`:t?$.ESC+`OB`:$.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=$.ESC+`[2~`);break;case 46:i.key=a?$.ESC+`[3;`+(a+1)+`~`:$.ESC+`[3~`;break;case 36:i.key=a?$.ESC+`[1;`+(a+1)+`H`:t?$.ESC+`OH`:$.ESC+`[H`;break;case 35:i.key=a?$.ESC+`[1;`+(a+1)+`F`:t?$.ESC+`OF`:$.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?$.ESC+`[5;`+(a+1)+`~`:$.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?$.ESC+`[6;`+(a+1)+`~`:$.ESC+`[6~`;break;case 112:i.key=a?$.ESC+`[1;`+(a+1)+`P`:$.ESC+`OP`;break;case 113:i.key=a?$.ESC+`[1;`+(a+1)+`Q`:$.ESC+`OQ`;break;case 114:i.key=a?$.ESC+`[1;`+(a+1)+`R`:$.ESC+`OR`;break;case 115:i.key=a?$.ESC+`[1;`+(a+1)+`S`:$.ESC+`OS`;break;case 116:i.key=a?$.ESC+`[15;`+(a+1)+`~`:$.ESC+`[15~`;break;case 117:i.key=a?$.ESC+`[17;`+(a+1)+`~`:$.ESC+`[17~`;break;case 118:i.key=a?$.ESC+`[18;`+(a+1)+`~`:$.ESC+`[18~`;break;case 119:i.key=a?$.ESC+`[19;`+(a+1)+`~`:$.ESC+`[19~`;break;case 120:i.key=a?$.ESC+`[20;`+(a+1)+`~`:$.ESC+`[20~`;break;case 121:i.key=a?$.ESC+`[21;`+(a+1)+`~`:$.ESC+`[21~`;break;case 122:i.key=a?$.ESC+`[23;`+(a+1)+`~`:$.ESC+`[23~`;break;case 123:i.key=a?$.ESC+`[24;`+(a+1)+`~`:$.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=$.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=$.DEL:e.keyCode===219?i.key=$.ESC:e.keyCode===220?i.key=$.FS:e.keyCode===221&&(i.key=$.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=NT[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=$.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=$.ESC+n}else if(e.keyCode===32)i.key=$.ESC+(e.ctrlKey?$.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=$.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=$.US),e.key===`@`&&(i.key=$.NUL))}return i}var FT=0,IT=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new SC,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new SC,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i<r.length;i++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(FT=this._search(t),FT===-1)||this._getKey(this._array[FT])!==t)return!1;do if(this._array[FT]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(FT),!0;while(++FT<this._array.length&&this._getKey(this._array[FT])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:n[r++]=this._array[i];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(FT=this._search(e),!(FT<0||FT>=this._array.length)&&this._getKey(this._array[FT])===e))do yield this._array[FT];while(++FT<this._array.length&&this._getKey(this._array[FT])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(FT=this._search(e),!(FT<0||FT>=this._array.length)&&this._getKey(this._array[FT])===e))do t(this._array[FT]);while(++FT<this._array.length&&this._getKey(this._array[FT])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i<e)t=r+1;else{for(;r>0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},LT=0,RT=0,zT=class extends Dy{constructor(){super(),this._decorations=new IT(e=>e?.marker.line),this._onDecorationRegistered=this._register(new Z),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Z),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(wy(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new BT(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e<i&&(!n||(a.options.layer??`bottom`)===n)&&(yield a)}forEachDecorationAtCell(e,t,n,r){this._decorations.forEachByKey(t,t=>{LT=t.options.x??0,RT=LT+(t.options.width??1),e>=LT&&e<RT&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},BT=class extends Ey{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new Z),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new Z),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=`full`)}get backgroundColorRGB(){return this._cachedBg===null&&(this._cachedBg=this.options.backgroundColor?CS.toColor(this.options.backgroundColor):void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this._cachedFg=this.options.foregroundColor?CS.toColor(this.options.foregroundColor):void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},VT=1e3,HT=class{constructor(e,t=VT){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},UT=20,WT=class extends Dy{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new HT(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
|
|
88
|
+
`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Q(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(wy(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<UT+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
|
|
89
|
+
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===UT+1&&(this._liveRegion.textContent+=hv.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};WT=dv([X(1,Hv),X(2,Zv),X(3,$v)],WT);var GT=class extends Dy{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new Z),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new Z),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(wy(()=>{Sy(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Q(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Q(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(Q(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(Q(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){this._activeLine!==e.y||this._wasResized?(this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1):this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&KT(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Sy(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0||e.link.decorations.underline,pointerCursor:e.link.decorations===void 0||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};GT=dv([X(1,Qv),X(2,$v),X(3,Rv),X(4,ry)],GT);function KT(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var qT=class extends MT{constructor(e={}){super(e),this._linkifier=this._register(new Oy),this.browser=aC,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Oy),this._onCursorMove=this._register(new Z),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Z),this.onKey=this._onKey.event,this._onRender=this._register(new Z),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Z),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Z),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Z),this.onBell=this._onBell.event,this._onFocus=this._register(new Z),this._onBlur=this._register(new Z),this._onA11yCharEmitter=this._register(new Z),this._onA11yTabEmitter=this._register(new Z),this._onWillOpen=this._register(new Z),this._setup(),this._decorationService=this._instantiationService.createInstance(zT),this._instantiationService.setService(qv,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(eC),this._instantiationService.setService(ry,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(Jv)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(Fy.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(Fy.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(Fy.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(Fy.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(wy(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=SS.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${$.ESC}]${n};${gT(r)}${mS.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=xS.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=xS.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(WT,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(Q(this.element,`copy`,e=>{this.hasSelection()&&vv(e,this._selectionService)}));let e=e=>yv(e,this.textarea,this.coreService,this.optionsService);this._register(Q(this.textarea,`paste`,e)),this._register(Q(this.element,`paste`,e)),lC?this._register(Q(this.element,`mousedown`,e=>{e.button===2&&Sv(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Q(this.element,`contextmenu`,e=>{Sv(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),_C&&this._register(Q(this.element,`auxclick`,e=>{e.button===1&&xv(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Q(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(Q(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(Q(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(Q(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(Q(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(Q(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(Q(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(Q(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,pv.get()),vC||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(QS,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(Zv,this._coreBrowserService),this._register(Q(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(Q(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(JS,this._document,this._helperContainer),this._instantiationService.setService(Xv,this._charSizeService),this._themeService=this._instantiationService.createInstance(nw),this._instantiationService.setService(ny,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(kS),this._instantiationService.setService(ty,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(wC,this.rows,this.screenElement)),this._instantiationService.setService($v,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(hS,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(rC),this._instantiationService.setService(Qv,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(GT,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(oS,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(KC,this.element,this.screenElement,r)),this._instantiationService.setService(ey,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(Fy.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(sS,this.screenElement)),this._register(Q(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(WT,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(fS,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(fS,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(qS,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Q(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(Q(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=$.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){bv(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=PT(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===$.ETX||n.key===$.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(JT(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e===this.cols&&t===this.rows?this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure():super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(fw));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(`focus`)?this.coreService.triggerDataEvent($.ESC+`[I`):this.coreService.triggerDataEvent($.ESC+`[O`)}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[4;${t};${e}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[6;${r};${n}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};function JT(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var YT=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},XT=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new jv)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},ZT=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new XT(t)}getNullCell(){return new jv}},QT=class extends Dy{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Z),this.onBufferChange=this._onBufferChange.event,this._normal=new ZT(this._core.buffers.normal,`normal`),this._alternate=new ZT(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},$T=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},eE=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},tE=[`cols`,`rows`],nE=0,rE=class extends Dy{constructor(e){super(),this._core=this._register(new qT(e)),this._addonManager=this._register(new YT),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(tE.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||=new $T(this._core),this._parser}get unicode(){return this._checkProposedApi(),new eE(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||=this._register(new QT(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
|
|
90
|
+
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return pv.get()},set promptLabel(e){pv.set(e)},get tooMuchOutput(){return hv.get()},set tooMuchOutput(e){hv.set(e)}}}_verifyIntegers(...e){for(nE of e)if(nE===1/0||isNaN(nE)||nE%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(nE of e)if(nE&&(nE===1/0||isNaN(nE)||nE%1!=0||nE<0))throw Error(`This API only accepts positive integers`)}},iE=2,aE=1,oE=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(iE,Math.floor(u/e.css.cell.width)),rows:Math.max(aE,Math.floor(l/e.css.cell.height))}}},sE=5,cE=20,lE=5,uE=240,dE=120,fE={checking:`检查中`,unavailable:`不可用`,starting:`启动中`,running:`运行中`,exited:`已结束`},pE=new Map,mE=e=>{let t=pE.get(e);if(!t){let n={id:`${e}-1`,title:`1`,phase:`checking`};t={slots:[n],activeId:n.id,opened:new Set,terminals:new Map,fits:new Map},pE.set(e,t)}return t};function hE({workspaceId:e,workspaceLabel:t,connected:n,sendCommand:r,registerSink:i,conversationId:a}){let o=a?`term-${a}`:`terminal-right-rail`,s=mE(o),[c,l]=(0,z.useState)(()=>s.slots),[u,d]=(0,z.useState)(()=>s.activeId),f=(0,z.useRef)(u);f.current=u,s.activeId=u;let p=(0,z.useRef)(c);p.current=c,s.slots=c;let m=(0,z.useRef)(e);m.current=e;let h=(0,z.useRef)(r);h.current=r;let g=(0,z.useRef)(s.opened);g.current=s.opened;let _=(0,z.useRef)(!1),v=(0,z.useRef)(s.terminals);v.current=s.terminals;let y=(0,z.useRef)(s.fits);y.current=s.fits;let b=(0,z.useRef)(new Map),[x,S]=(0,z.useState)(0),C=(0,z.useRef)(n),w=(0,z.useCallback)(e=>{v.current.get(e)?.dispose(),v.current.delete(e),y.current.delete(e),b.current.delete(e)},[]),T=(0,z.useCallback)(e=>{let t=v.current.get(e),n=y.current.get(e);if(!t||!n)return;let r=b.current.get(e);if(!(!r||r.clientWidth<2||r.clientHeight<2)){try{n.fit()}catch{return}t.cols<cE||t.rows<lE||t.cols>uE||t.rows>dE||g.current.has(e)&&h.current({type:`terminal.resize`,sessionId:e,cols:t.cols,rows:t.rows})}},[]),E=(0,z.useCallback)((e,t)=>{if(!t){b.current.delete(e);return}b.current.set(e,t);let n=v.current.get(e);if(n){n.element&&!t.contains(n.element)&&(t.innerHTML=``,t.appendChild(n.element),requestAnimationFrame(()=>T(e)));return}let r=getComputedStyle(t),i=(e,t)=>r.getPropertyValue(e).trim()||t,a=new rE({cursorBlink:!0,convertEol:!1,scrollback:5e3,fontFamily:`Consolas, 'Cascadia Mono', 'DejaVu Sans Mono', monospace`,fontSize:12,lineHeight:1.35,theme:{background:`#00000000`,foreground:i(`--term-fg`,`#dbe4f0`),cursor:i(`--term-fg`,`#dbe4f0`),selectionBackground:i(`--term-selection`,`#3a4f6b`)},allowProposedApi:!0}),o=new oE;a.loadAddon(o),a.open(t),a.onData(t=>{g.current.has(e)&&h.current({type:`terminal.input`,sessionId:e,data:t})}),a.onResize(({cols:t,rows:n})=>{g.current.has(e)&&h.current({type:`terminal.resize`,sessionId:e,cols:t,rows:n})}),v.current.set(e,a),y.current.set(e,o),requestAnimationFrame(()=>T(e)),S(e=>e+1)},[T]),D=(0,z.useCallback)(e=>{v.current.get(e)?.reset()},[]),O=(0,z.useCallback)(e=>{let t=m.current,n=v.current.get(e);if(!t||!n||g.current.has(e))return;n.reset(),T(e),l(t=>t.map(t=>t.id===e?{...t,phase:`starting`,exitCode:void 0,reason:``}:t));let r=Math.max(cE,Math.min(uE,n.cols||80)),i=Math.max(lE,Math.min(dE,n.rows||24));h.current({type:`terminal.open`,sessionId:e,workspaceId:t,cols:r,rows:i})?(g.current.add(e),l(t=>t.map(t=>t.id===e?{...t,phase:`running`}:t))):l(t=>t.map(t=>t.id===e?{...t,phase:`exited`,reason:`Super Pi 服务的连接尚未就绪`}:t))},[T]);(0,z.useEffect)(()=>{let e=!1;return fetch(`/api/terminal`).then(e=>e.json()).then(t=>{e||(t.enabled?(_.current=!0,l(e=>e.map(e=>e.phase===`checking`?{...e,phase:`starting`}:e))):l(e=>e.map(e=>({...e,phase:`unavailable`,reason:t.reason??`终端未启用`}))))}).catch(()=>{e||l(e=>e.map(e=>({...e,phase:`unavailable`,reason:`无法读取终端状态`})))}),()=>{e=!0}},[]),(0,z.useEffect)(()=>{if(_.current)for(let e of c)(e.phase===`checking`||e.phase===`starting`)&&!g.current.has(e.id)&&O(e.id)},[c,O,x]);let k=(0,z.useCallback)(e=>{if(e.type===`terminal.output`)for(let t of pE.values()){let n=t.terminals.get(e.sessionId);if(n){n.write(e.data);return}}else if(e.type===`terminal.exit`){for(let t of pE.values())t.opened.has(e.sessionId)&&(t.opened.delete(e.sessionId),t.slots=t.slots.map(t=>t.id===e.sessionId?{...t,phase:`exited`,exitCode:e.exitCode}:t));D(e.sessionId),l(t=>t.map(t=>t.id===e.sessionId?{...t,phase:`exited`,exitCode:e.exitCode}:t))}else if(e.type===`terminal.error`){for(let t of pE.values())t.opened.has(e.sessionId)&&(t.opened.delete(e.sessionId),t.slots=t.slots.map(t=>t.id===e.sessionId?{...t,phase:`exited`,reason:e.message}:t));D(e.sessionId),l(t=>t.map(t=>t.id===e.sessionId?{...t,phase:`exited`,reason:e.message}:t))}else e.type===`terminal.status`&&!e.enabled&&l(t=>t.map(t=>({...t,phase:`unavailable`,reason:e.reason??`终端未启用`})))},[D]);(0,z.useEffect)(()=>(i(k),()=>i(void 0)),[k,i]),(0,z.useEffect)(()=>()=>{b.current.clear()},[]),(0,z.useEffect)(()=>{let e=n&&!C.current;C.current=n,e&&l(e=>e.map(e=>e.phase===`exited`&&!e.deliberate?{...e,phase:`starting`,reason:``}:e))},[n]),(0,z.useLayoutEffect)(()=>{let e=new ResizeObserver(()=>T(f.current));for(let t of b.current.values())e.observe(t);return T(f.current),()=>e.disconnect()},[T,c,x]);let A=(0,z.useCallback)(e=>{d(e),requestAnimationFrame(()=>T(e))},[T]),ee=(0,z.useCallback)(()=>{let e=new Set(p.current.map(e=>e.title)),t=1;for(;e.has(String(t));)t+=1;let n={id:`${o}-${t}`,title:String(t),phase:`checking`};l(e=>e.length>=sE?e:[...e,n]),d(n.id)},[o]),j=(0,z.useCallback)(e=>{h.current({type:`terminal.close`,sessionId:e}),g.current.delete(e),w(e),l(t=>{if(t.length<=1)return t;let n=t.findIndex(t=>t.id===e),r=t.filter(t=>t.id!==e);return f.current===e&&d(r[Math.min(n,r.length-1)].id),r})},[w]),M=(0,z.useCallback)(()=>{let e=f.current;h.current({type:`terminal.close`,sessionId:e}),g.current.delete(e),l(t=>t.map(t=>t.id===e?{...t,phase:`exited`,deliberate:!0}:t))},[]),N=c.find(e=>e.id===u)??c[0];return N?N.phase===`checking`?(0,B.jsx)(`p`,{className:`rail-empty`,"data-terminal-phase":`checking`,children:`正在检查终端状态…`}):N.phase===`unavailable`?(0,B.jsxs)(`div`,{className:`terminal-unavailable`,"data-terminal-phase":`unavailable`,children:[(0,B.jsx)(`p`,{className:`terminal-unavailable-reason`,children:N.reason}),(0,B.jsx)(`p`,{className:`rail-empty`,children:`终端仅接受本机与局域网连接。`})]}):(0,B.jsxs)(`div`,{className:`terminal-panel`,"data-terminal-panel":`1`,"data-terminal-phase":N.phase,children:[(0,B.jsxs)(`div`,{className:`terminal-strip`,role:`tablist`,"aria-label":`终端会话`,"data-terminal-strip":`1`,children:[c.map(e=>(0,B.jsxs)(`div`,{className:`terminal-tab${e.id===u?` is-active`:``}`,children:[(0,B.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":e.id===u,className:`terminal-tab-btn`,"data-terminal-slot":e.id,onClick:()=>A(e.id),title:fE[e.phase],children:[(0,B.jsx)(`span`,{className:`terminal-tab-dot terminal-tab-dot-${e.phase}`,"aria-hidden":`true`}),e.title]}),(0,B.jsx)(`button`,{type:`button`,className:`terminal-tab-close`,"aria-label":`关闭终端 ${e.title}`,"data-terminal-slot-close":e.id,onClick:()=>j(e.id),children:`×`})]},e.id)),c.length<sE&&(0,B.jsx)(`button`,{type:`button`,className:`terminal-strip-add`,"data-terminal-add":`1`,onClick:ee,title:`新建终端`,"aria-label":`新建终端`,children:`+`})]}),(0,B.jsxs)(`div`,{className:`terminal-toolbar`,children:[(0,B.jsxs)(`span`,{className:`terminal-status terminal-status-${N.phase}`,"data-terminal-status":N.phase,children:[(0,B.jsx)(`span`,{className:`terminal-status-dot`,"aria-hidden":`true`}),fE[N.phase]]}),(0,B.jsxs)(`span`,{className:`terminal-toolbar-right`,children:[t&&(0,B.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-hint":`1`,title:t,children:t}),N.phase===`running`?(0,B.jsx)(`button`,{type:`button`,className:`terminal-close-btn`,"data-terminal-close":`1`,onClick:M,children:`结束会话`}):(0,B.jsx)(`button`,{type:`button`,className:`terminal-restart-btn`,"data-terminal-restart":`1`,onClick:()=>O(N.id),children:`重新打开`})]})]}),N.reason&&(0,B.jsx)(`p`,{className:`tool-error`,"data-terminal-error":`1`,role:`alert`,children:N.reason}),N.phase===`exited`&&N.exitCode!==void 0&&N.exitCode!==0&&(0,B.jsxs)(`p`,{className:`tool-error`,"data-terminal-exit":`1`,children:[`会话已结束,退出码 `,N.exitCode,`。`]}),(0,B.jsx)(`div`,{className:`terminal-surface`,"data-terminal-surface":`1`,children:c.map(e=>(0,B.jsx)(`div`,{ref:t=>E(e.id,t),className:`terminal-xterm-host`,"data-terminal-xterm":e.id,style:{display:e.id===u?`block`:`none`}},e.id))})]}):null}function gE(e){return!!(e&&typeof e==`object`&&e.type===`message.send`)}function _E(e){let t=[],n=[];for(let r of e)(r.retry?t:n).push(r);return{retry:t,failed:n}}var vE=`.super-pi-tool.json`,yE=512e3,bE=/^[a-z0-9][a-z0-9-]{0,63}$/,xE=/^[A-Za-z0-9][A-Za-z0-9_.-]*==[^=\s,;<>|'"`\\]{1,80}$/;function SE(e,t){let n;try{n=JSON.parse(e)}catch{return{ok:!1,reason:`「${t}」不是 JSON。确认一下选的是别人分享的工具文件(${vE})。`}}if(!n||typeof n!=`object`||Array.isArray(n))return{ok:!1,reason:`这个 JSON 不是一个工具包。`};let r=n,i=typeof r.format==`string`?r.format:void 0;if(i!==void 0&&i!==`super-pi.tool`)return{ok:!1,reason:`这不是 Super Pi 的工具文件(format: ${i})。`};if(typeof r.version==`number`&&r.version>1)return{ok:!1,reason:`这个工具文件是更新版本的 Super Pi 导出的(version: ${r.version}),当前版本读不了。`};let a=typeof r.slug==`string`?r.slug.trim():``,o=typeof r.name==`string`?r.name.trim():``;if(!a)return{ok:!1,reason:`这个工具包里没有 slug(那是它的短名字,也是它在磁盘上的目录名)。`};if(!o)return{ok:!1,reason:`这个工具包里没有名字。`};if(!Array.isArray(r.files)||!r.files.length)return{ok:!1,reason:`这个工具包里没有文件。`};if(r.files.length>32)return{ok:!1,reason:`文件太多了:${r.files.length} 个,上限 32 个。`};let s=[],c=0;for(let e of r.files){let t=e;if(!t||typeof t.path!=`string`||typeof t.content!=`string`)return{ok:!1,reason:`工具包里的文件项格式不对(每一项都要有 path 和 content)。`};let n=t.path.trim();if(!n||n.startsWith(`/`)||n.includes(`\\`)||n.includes(`\0`)||n.split(`/`).includes(`..`))return{ok:!1,reason:`文件路径「${n}」不合法:不能是绝对路径,也不能跳出工具自己的目录。`};if(s.some(e=>e.path===n))return{ok:!1,reason:`工具包里有重复的文件:${n}`};if(c+=new TextEncoder().encode(t.content).length,c>512e3)return{ok:!1,reason:`工具文件合计超过 ${AE(yE)} 的上限。`};s.push({path:n,content:t.content})}let l=typeof r.entrypoint==`string`&&r.entrypoint.trim()?r.entrypoint.trim():`index.html`;if(!l.endsWith(`.html`))return{ok:!1,reason:`入口文件必须是一个 HTML 文件。`};if(!s.some(e=>e.path===l))return{ok:!1,reason:`工具包里没有包含入口文件 ${l}。`};let u;if(r.script!==void 0&&r.script!==null){let e=r.script,t=typeof e.path==`string`?e.path.trim():``;if(!t.endsWith(`.py`))return{ok:!1,reason:`工具包声明的脚本必须是一个 .py 文件。`};if(!s.some(e=>e.path===t))return{ok:!1,reason:`工具包里没有包含它声明的脚本 ${t}。`};u={path:t,timeoutMs:typeof e.timeoutMs==`number`?e.timeoutMs:void 0,parameters:typeof e.parameters==`object`&&e.parameters!==null?e.parameters:void 0}}let d;if(r.environment!==void 0&&r.environment!==null){let e=r.environment,t=e.requires;if(t!==void 0&&!Array.isArray(t))return{ok:!1,reason:`工具包声明的依赖列表格式不对(requires 必须是数组)。`};if(Array.isArray(t)){for(let e of t)if(typeof e!=`string`||!xE.test(e.trim()))return{ok:!1,reason:`依赖必须钉死到精确版本(写成 pkg==version):${String(e).slice(0,60)}。`}}let n=e.fingerprint&&typeof e.fingerprint==`object`?e.fingerprint:void 0;d={requiresPython:typeof e.requiresPython==`string`?e.requiresPython:void 0,requires:Array.isArray(t)?t.map(e=>String(e).trim()):void 0,fingerprint:n}}let f=r.permissions&&typeof r.permissions==`object`&&r.permissions.llm===!0?{llm:!0}:void 0;return{ok:!0,unnamedFormat:i===void 0,bundle:{...i===void 0?{}:{format:i},...typeof r.version==`number`?{version:r.version}:{},...typeof r.exportedAt==`string`?{exportedAt:r.exportedAt}:{},slug:a,name:o,...typeof r.description==`string`&&r.description.trim()?{description:r.description.trim().slice(0,500)}:{},entrypoint:l,files:s,script:u,environment:d,...f?{permissions:f}:{}}}}function CE(e){let t=e.trim().toLowerCase();return t?bE.test(t)?{ok:!0,slug:t}:{ok:!1,reason:`slug 只能用小写字母、数字和连字符,且要以字母或数字开头。`}:{ok:!1,reason:`请填写 slug(工具的短名字,只能用小写字母、数字和连字符)。`}}function wE(e,t){let n=e.trim().toLowerCase().slice(0,60).replace(/[^a-z0-9-]+/g,`-`).replace(/^-+|-+$/g,``)||`tool`;if(!t.includes(n))return n;for(let e=2;e<100;e+=1){let r=`${n}-${e}`;if(!t.includes(r))return r}return n}function TE(e){return`${e.slug}${vE}`}function EE(e){let t=e.trim().replace(/[\\/:*?"<>|]/g,``).replace(/\.+$/,``).trim();return t?t.length>80?{ok:!1,reason:`文件名太长了,请控制在 80 个字符以内。`}:{ok:!0,name:t.endsWith(`.super-pi-tool.json`)?t:`${t}${vE}`}:{ok:!1,reason:`请填写文件名。`}}function DE(e){if(e.permissions?.llm)return{tone:`warn`,text:`这个工具可以调用模型:它能把内容发给你的模型回答,每次调用都会用你的模型额度`}}function OE(e){let t=e.environment?.requires??[];return!e.script&&t.length===0?{tone:`ok`,text:`纯页面工具 · 导入即用,不需要 Python`}:t.length===0?{tone:`ok`,text:`只用 Python 标准库 · 导入即用,不需要安装任何包${e.environment?.requiresPython?`(需要 Python ${e.environment.requiresPython})`:``}`}:{tone:`warn`,text:`首次运行时会安装 ${t.length} 个依赖:${t.join(`、`)}(装进这个工具自己的虚拟环境)${e.environment?.requiresPython?` · 需要 Python ${e.environment.requiresPython}`:``}`}}function kE(e){if(e)return e.state===`zero-deps`?{text:`零依赖`,warn:!1}:e.state===`ready`?{text:`环境就绪`,warn:!1}:e.state===`needs-env`?{text:`首次运行时安装依赖`,warn:!1}:e.state===`needs-python`?{text:`缺少可用的 Python`,warn:!0}:{text:`与导出方环境不一致`,warn:!0}}function AE(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function jE(e,t){let{format:n,version:r,exportedAt:i,...a}=e;return{...a,slug:t}}var ME={workspaces:[],conversations:[],subagentRuns:[]},NE=e=>e.nativeEvent.isComposing||e.keyCode===229,PE=(e,t,n)=>{let r=e.filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),i=r.findIndex(e=>e.id===t);if(i<0||r[i].delivery===`sending`)return e;let a=r.reduce((e,t,n)=>t.delivery===`sending`?n:e,-1),o=Math.max(a+1,Math.min(n,r.length-1));if(o===i)return e;let s=[...r],[c]=s.splice(i,1);s.splice(o,0,c);let l=[...e],u=0;for(let e=0;e<l.length;e+=1)(l[e].role===`user`||l[e].role===`tool`)&&l[e].delivery&&(l[e]=s[u++]);return l},FE=e=>{if(typeof e!=`string`||e.length===0)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:new Intl.DateTimeFormat(`zh-CN`,{hour:`2-digit`,minute:`2-digit`}).format(t)},IE=6e4,LE=60*IE,RE=24*LE,zE=7*RE,BE=30*RE,VE=365*RE,HE=(e,t)=>{let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t-n.getTime();return r<3e4?`now`:r<LE?`${Math.max(1,Math.floor(r/IE))}m ago`:r<RE?`${Math.floor(r/LE)}h ago`:r<zE?`${Math.floor(r/RE)}d ago`:r<BE?`${Math.floor(r/zE)}w ago`:r<VE?`${Math.floor(r/BE)}mo ago`:`${Math.floor(r/VE)}y ago`},UE=(e,t)=>e.updatedAt<t.updatedAt?1:e.updatedAt>t.updatedAt?-1:0,WE=(e,t)=>{let n=e.archivedAt??``,r=t.archivedAt??``;return n<r?1:n>r?-1:0},GE=e=>{if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`},KE=1e3,qE=3e4,JE=async e=>{try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,``),t.style.cssText=`position:fixed;top:0;left:0;width:1px;height:1px;padding:0;border:0;opacity:0;pointer-events:none`,document.body.appendChild(t);try{return t.select(),t.setSelectionRange(0,t.value.length),document.execCommand(`copy`)}catch{return!1}finally{t.remove()}};function YE({workspace:e,x:t,y:n,notify:r,onClose:i}){let a=(0,z.useRef)(null),[o,s]=(0,z.useState)({left:t,top:n});(0,z.useLayoutEffect)(()=>{let e=a.current;if(!e)return;let r=e.getBoundingClientRect();s({left:Math.max(8,Math.min(t,window.innerWidth-r.width-8)),top:Math.max(8,Math.min(n,window.innerHeight-r.height-8))})},[t,n]),(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),i())},t=e=>{a.current?.contains(e.target)||i()},n={x:window.scrollX,y:window.scrollY,width:window.innerWidth,height:window.innerHeight},r=()=>{(window.scrollX!==n.x||window.scrollY!==n.y)&&i()},o=()=>{(window.innerWidth!==n.width||window.innerHeight!==n.height)&&i()};return window.addEventListener(`keydown`,e,!0),window.addEventListener(`pointerdown`,t,!0),window.addEventListener(`scroll`,r,!0),window.addEventListener(`resize`,o),()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`pointerdown`,t,!0),window.removeEventListener(`scroll`,i,!0),window.removeEventListener(`resize`,o)}},[i]);let c=async()=>{let t=await JE(e.path);i(),t?r(`已复制工作区路径:${e.path}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中路径复制`,`error`)};return(0,B.jsxs)(`div`,{ref:a,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-workspace-id":e.id,style:{left:o.left,top:o.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,B.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-workspace-path":e.id,onClick:()=>void c(),children:`复制工作区路径`}),(0,B.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.path})]})}function XE({conversation:e,x:t,y:n,notify:r,onRename:i,onClose:a}){let o=(0,z.useRef)(null),[s,c]=(0,z.useState)({left:t,top:n});(0,z.useLayoutEffect)(()=>{let e=o.current;if(!e)return;let r=e.getBoundingClientRect();c({left:Math.max(8,Math.min(t,window.innerWidth-r.width-8)),top:Math.max(8,Math.min(n,window.innerHeight-r.height-8))})},[t,n]),(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),a())},t=e=>{o.current?.contains(e.target)||a()},n={x:window.scrollX,y:window.scrollY,width:window.innerWidth,height:window.innerHeight},r=()=>{(window.scrollX!==n.x||window.scrollY!==n.y)&&a()},i=()=>{(window.innerWidth!==n.width||window.innerHeight!==n.height)&&a()};return window.addEventListener(`keydown`,e,!0),window.addEventListener(`pointerdown`,t,!0),window.addEventListener(`scroll`,r,!0),window.addEventListener(`resize`,i),()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`pointerdown`,t,!0),window.removeEventListener(`scroll`,a,!0),window.removeEventListener(`resize`,i)}},[a]);let l=async()=>{let t=await JE(e.id);a(),t?r(`已复制会话 ID:${e.id}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入`,`error`)};return(0,B.jsxs)(`div`,{ref:o,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-session-id":e.id,style:{left:s.left,top:s.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,B.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-session-id":e.id,onClick:()=>void l(),children:`复制会话 ID`}),(0,B.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-ai-rename-session":e.id,onClick:()=>{a(),i()},children:`AI 智能重命名`}),(0,B.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.id})]})}var ZE={model:`模型`,thinking:`思考`,agent:`智能体`,subagent:`子智能体`},QE={model:`模型`,thinking:`思考等级`,agent:`智能体`,subagent:`子智能体`},$E={model:`选择模型`,thinking:`选择思考等级`,agent:`选择智能体`,subagent:`选择子智能体`},eD=`图文`,tD=e=>e.imageInput?eD:void 0,nD=e=>e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLowerCase(),rD=(e,t)=>{let n=nD(t.trim());return n?e.filter(e=>nD(`${e.label} ${e.detail??``} ${e.badge??``}`).includes(n)):e};function iD({onClose:e,onCreate:t}){let[n,r]=(0,z.useState)(),[i,a]=(0,z.useState)(!0),[o,s]=(0,z.useState)(),[c,l]=(0,z.useState)(``),[u,d]=(0,z.useState)(``),f=async e=>{a(!0),s(void 0);try{let t=await fetch(`/api/fs/dirs${e?`?path=${encodeURIComponent(e)}`:``}`),n=await t.json();if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);let i=n;r(i),d(i.path),l(i.suggestedName)}catch(e){s(e instanceof Error?e.message:`目录加载失败`)}finally{a(!1)}};(0,z.useEffect)(()=>{f()},[]),(0,z.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let p=e=>{e?.preventDefault();let t=u.trim();t&&f(t)};return(0,B.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,B.jsxs)(`div`,{className:`picker workspace-picker`,onClick:e=>e.stopPropagation(),children:[(0,B.jsx)(`h2`,{children:`选择工作区目录`}),(0,B.jsxs)(`form`,{className:`picker-path-bar`,onSubmit:p,children:[(0,B.jsx)(`input`,{className:`picker-path-input`,value:u,onChange:e=>d(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(NE(e)?e.preventDefault():(e.preventDefault(),p()))},placeholder:`输入或粘贴目录绝对路径(如 D:\\projects 或 ~/code)`}),(0,B.jsx)(`button`,{type:`submit`,className:`picker-go-btn`,disabled:!u.trim()||i,children:`跳转`}),(0,B.jsx)(`button`,{type:`button`,className:`picker-up-btn`,disabled:!n?.parent||i,onClick:()=>n?.parent&&void f(n.parent),title:`返回上一级目录`,children:`上一级`})]}),n?.drives?.length||n?.homeDir?(0,B.jsxs)(`div`,{className:`picker-shortcuts`,children:[(0,B.jsx)(`span`,{className:`picker-shortcuts-label`,children:`快捷位置:`}),n?.homeDir&&(0,B.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void f(`~`),title:n.homeDir,children:`🏠 主目录`}),n?.drives?.map(e=>(0,B.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void f(e),children:e},e))]}):null,(0,B.jsxs)(`div`,{className:`picker-list`,children:[i&&(0,B.jsx)(`div`,{className:`picker-status`,children:`加载中…`}),!i&&o&&(0,B.jsxs)(`div`,{className:`picker-error`,children:[o,(0,B.jsx)(`button`,{onClick:()=>void f(n?.path||u),children:`重试`})]}),!i&&!o&&n?.entries.map(e=>(0,B.jsxs)(`button`,{className:`picker-dir`,onClick:()=>void f(e.path),children:[`📁 `,e.name]},e.path)),!i&&!o&&n&&n.entries.length===0&&(0,B.jsx)(`div`,{className:`picker-status`,children:`此目录下没有子目录`}),!i&&!o&&n?.truncated&&(0,B.jsx)(`div`,{className:`picker-status`,children:`目录过多,仅显示前 2000 项`})]}),(0,B.jsxs)(`label`,{className:`picker-name`,children:[`工作区名称`,(0,B.jsx)(`input`,{value:c,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(NE(e)?e.preventDefault():(e.preventDefault(),c.trim()&&n&&t(c.trim(),n.path)))},placeholder:`工作区名称`})]}),(0,B.jsxs)(`div`,{className:`picker-actions`,children:[(0,B.jsx)(`button`,{className:`picker-cancel`,onClick:e,children:`取消`}),(0,B.jsx)(`button`,{className:`picker-ok`,disabled:!c.trim()||i||!!o||!n,onClick:()=>n&&t(c.trim(),n.path),children:`使用这个目录`})]})]})})}var aD={timeout:`扩展提问超时,已取消`,aborted:`运行已停止,扩展提问已取消`,expired:`运行已结束,扩展提问已取消`},oD=10;function sD(e,t){if(!t)return`正在从 Pi 读取${e}列表…`;if(t.source!==`pi`)return`读取 Pi ${e}列表失败:${t.error??`未知原因`}`}function cD(e){if(!e)return`正在读取 agent 列表…`;if(e.source!==`directory`)return`读取 agent 列表失败:${e.error??`未知原因`}`;if(e.problems.length)return`${e.problems.length} 个 agent 文件无法使用:${e.problems.map(e=>e.file).join(`、`)}`;if(!e.agents.length)return`${e.directory} 下没有 primary agent`}var lD=e=>Math.abs(e)<1e3?String(e):`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`;function uD(e){if(e===void 0||!Number.isFinite(e))return``;let t=Math.max(0,e);return t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:`${Math.floor(t/6e4)}分${Math.round(t%6e4/1e3)}秒`}var dD={dispatch:`派发时(子进程还没起来)`,prompt:`派活时(Pi 拒收了任务)`,turn:`生成回答时`,tool:`调用工具时`,settle:`收尾时`};function fD({task:e,initialOutput:t,expanded:n}){let[r,i]=(0,z.useState)(t);(0,z.useEffect)(()=>{let n=t,r,a=t=>{let a=t.detail;a.sessionId===e.id&&(n=(n+a.data).slice(-512e3),r===void 0&&(r=requestAnimationFrame(()=>{r=void 0,i(n)})))};return window.addEventListener(`super-pi-exec-output`,a),()=>{window.removeEventListener(`super-pi-exec-output`,a),r!==void 0&&cancelAnimationFrame(r)}},[e.id]);let a=e.output??r;return(0,B.jsxs)(B.Fragment,{children:[!n&&a&&(0,B.jsx)(`div`,{className:`call-live-preview`,"data-background-preview":e.id,title:`展开调用查看完整输出`,children:a.split(`
|
|
91
|
+
`).slice(-1)[0]}),n&&(0,B.jsx)(`pre`,{className:`call-result-body`,"data-background-output":e.id,children:a||`等待输出…`})]})}function pD({call:e,index:t,expanded:n,onToggle:r,backgroundOutput:i,runCard:a}){let o=e.args??[];return(0,B.jsxs)(`div`,{className:`call-block call-block-${e.status??`running`}`,"data-call-block":t,"data-call-tool":e.label,"data-call-detail":e.detail??void 0,"data-call-status":e.status??`running`,"data-call-expanded":n?`true`:`false`,"data-call-arg-count":o.length,"data-thinking-at":e.thinkingAt,"data-background-exec":e.backgroundTask?.id,"data-background-status":e.backgroundTask?.status,children:[(0,B.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-call-fold-edge":t,"aria-expanded":n,"aria-label":`${n?`折叠`:`展开`} ${e.label} 调用`,title:n?`折叠这次调用`:`展开这次调用`,onClick:r}),(0,B.jsxs)(`div`,{className:`call-head-row`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:r,children:[(0,B.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,B.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,B.jsx)(`span`,{className:`call-label`,title:e.label,children:e.label}),e.detail&&(0,B.jsx)(`span`,{className:`call-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,B.jsx)(`span`,{className:`call-duration`,children:uD(e.durationMs)}),e.backgroundTask&&(0,B.jsxs)(`span`,{className:`call-background-status`,"data-background-status-text":e.backgroundTask.status,children:[`后台任务 · `,e.backgroundTask.status===`running`?`进行中`:e.backgroundTask.status===`completed`?`已完成`:`失败`,e.backgroundTask.exitCode===void 0?``:` · 退出码:${e.backgroundTask.exitCode}`]}),e.preparing&&(0,B.jsx)(`span`,{className:`call-preparing`,"data-call-preparing":t,children:`生成参数中…`})]}),n&&(0,B.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:r,children:`收起`})]}),!n&&e.live&&(0,B.jsx)(`div`,{className:`call-live-preview`,"data-call-live-preview":t,title:`展开查看完整输出`,children:e.live.split(`
|
|
92
|
+
`).slice(-1)[0]}),n&&(0,B.jsx)(`div`,{className:`call-args`,"data-call-args":o.length,children:o.length===0?(0,B.jsx)(`div`,{className:`call-arg call-arg-empty`,"data-call-arg-empty":t,children:`(这次调用没有可显示的参数)`}):o.map(e=>(0,B.jsxs)(`div`,{className:`call-arg`,"data-call-arg":e.key,"data-call-arg-value":e.value,children:[(0,B.jsx)(`span`,{className:`call-arg-key`,children:e.key}),(0,B.jsx)(`span`,{className:`call-arg-value`,title:e.value,children:e.value})]},e.key))}),n&&(e.result||e.live||i)&&(0,B.jsxs)(`div`,{className:`call-result`,"data-call-result":t,"data-call-result-state":e.result?`done`:`running`,children:[(e.result||e.live)&&(0,B.jsxs)(`div`,{className:`call-result-head`,children:[(0,B.jsx)(`span`,{className:`call-result-title`,children:e.result&&!e.live?`执行结果`:e.result?`执行结果 · 完整输出`:`执行中 · 输出预览`}),e.result?(0,B.jsx)(mD,{index:t,text:e.live??e.result.text}):null]}),(e.result||e.live)&&(0,B.jsx)(`pre`,{className:`call-result-body`,"data-call-result-body":t,children:e.live??e.result?.text}),e.result?.truncated&&e.live&&(0,B.jsx)(`div`,{className:`call-result-truncated`,children:`(服务端已截断到末尾 8 KB;上方显示的是执行中累积的完整输出)`}),e.result?.truncated&&!e.live&&(0,B.jsxs)(`div`,{className:`call-result-truncated`,children:[`(输出过长,已保留末尾关键内容`,e.result.droppedLines?`,省略前 ${e.result.droppedLines} 行`:``,`)`]}),i]}),!n&&i,a]})}function mD({index:e,text:t}){let[n,r]=(0,z.useState)(!1);return(0,B.jsx)(`button`,{type:`button`,className:`call-result-copy`,"data-call-result-copy":e,onClick:async()=>{await JE(t)&&(r(!0),window.setTimeout(()=>r(!1),1600))},children:n?`已复制`:`复制`})}function hD({messageId:e,nestedCount:t,liveCall:n,liveExtra:r,preview:i,expanded:a,onToggle:o,children:s}){return(0,B.jsxs)(`section`,{className:`thinking-block`,"data-thinking-block":e,"data-thinking-expanded":a?`true`:`false`,"data-thinking-calls":t,children:[(0,B.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-thinking-fold-edge":e,"aria-expanded":a,"aria-label":`${a?`折叠`:`展开`}这段思考`,title:a?`折叠这段思考`:`展开这段思考`,onClick:o}),(0,B.jsxs)(`button`,{type:`button`,className:`thinking-head`,"data-thinking-head":e,"aria-expanded":a,title:a?`折叠这段思考`:`展开这段思考`,onClick:o,children:[(0,B.jsx)(`span`,{className:`thinking-chevron`,"aria-hidden":`true`,children:a?`▾`:`▸`}),(0,B.jsx)(`span`,{className:`thinking-label`,children:`思考`}),t>0&&(0,B.jsxs)(`span`,{className:`thinking-count`,"data-thinking-count":t,children:[t,` 次工具调用`]}),!a&&n&&(0,B.jsxs)(`span`,{className:`thinking-live`,"data-thinking-live":n,"data-thinking-live-extra":r??0,children:[(0,B.jsx)(`span`,{className:`thinking-live-glyph`,"aria-hidden":`true`,children:`⚙`}),`正在执行 `,n,r?` 等 ${r+1} 个`:``]}),!a&&i&&(0,B.jsx)(`span`,{className:`thinking-preview`,title:i,children:i})]}),a&&(0,B.jsx)(`div`,{className:`thinking-body`,"data-thinking-body":e,children:s})]})}function gD({run:e,name:t,expanded:n,onToggle:r,onStop:i,stopping:a}){let o=e.toolCalls??[],s=n?o:o.slice(-10),c=o.length-s.length,l=e.status===`running`,u=e.output??``,d=e.dispatchedBy===`model`,[f,p]=(0,z.useState)(0);(0,z.useEffect)(()=>{if(!l)return;p(Date.now());let e=window.setInterval(()=>p(Date.now()),200);return()=>window.clearInterval(e)},[l,e.startedAt]);let m=Date.parse(e.startedAt),h=l&&f>0&&Number.isFinite(m)?f-m:void 0,g=[...o].reverse().find(e=>e.status===void 0)?.label;return(0,B.jsxs)(`article`,{className:`subagent-card subagent-${e.status}${d?` subagent-by-model`:``}`,"data-subagent-card":e.id,"data-subagent-status":e.status,"data-subagent-agent":e.agentId,"data-subagent-tools":o.length,"data-subagent-dispatched-by":d?`model`:`human`,children:[(0,B.jsxs)(`div`,{className:`subagent-head`,children:[(0,B.jsx)(`span`,{className:`subagent-badge`,children:`子智能体`}),d&&(0,B.jsxs)(`span`,{className:`subagent-source`,"data-subagent-source":`model`,title:`primary 模型自己决定派这个子智能体去干活`,children:[(0,B.jsx)(`span`,{className:`subagent-source-glyph`,"aria-hidden":`true`,children:`⚡`}),`模型自主派发`]}),(0,B.jsx)(`strong`,{className:`subagent-name`,"data-subagent-name":`1`,children:t||e.agentId}),(0,B.jsx)(`span`,{className:`subagent-status`,"data-subagent-status-text":`1`,children:l?`运行中`:e.status===`completed`?`已完成`:e.status===`stopped`?`已停止`:`失败`}),l?h!==void 0&&(0,B.jsxs)(`span`,{className:`subagent-clock`,"data-subagent-elapsed":`1`,"data-subagent-elapsed-ms":h,children:[`已运行 `,uD(h)]}):e.durationMs!==void 0&&(0,B.jsxs)(`span`,{className:`subagent-duration`,"data-subagent-duration":`1`,"data-subagent-duration-ms":e.durationMs,children:[`用时 `,uD(e.durationMs)]}),l&&(0,B.jsx)(`button`,{type:`button`,className:`subagent-stop`,"data-subagent-stop":e.id,disabled:a,onClick:i,children:`停止`})]}),l&&e.activity&&(0,B.jsxs)(`div`,{className:`subagent-activity`,"data-subagent-activity":e.activity.kind,"data-subagent-activity-at":e.activity.at,children:[(0,B.jsx)(`span`,{className:`subagent-activity-dot`,"aria-hidden":`true`}),e.activity.kind===`tool`?`正在调用 ${e.activity.label??`工具`}`:`正在思考…`]}),(0,B.jsxs)(`div`,{className:`subagent-task`,"data-subagent-task":`1`,children:[d&&(0,B.jsx)(`span`,{className:`subagent-task-source`,"data-subagent-model-task":`1`,children:`模型给的任务`}),e.task]}),(0,B.jsx)(`div`,{className:`subagent-output`,"data-subagent-output":`1`,"data-live-length":u.length,children:u||(l?`…`:e.outputTruncated?`(已按 50 KB 上限截断,浏览器仍收到完整内容)`:`(没有输出)`)}),e.failure&&(0,B.jsxs)(`div`,{className:`subagent-failure`,"data-subagent-failure":`1`,"data-subagent-failure-stage":e.failure.stage,children:[(0,B.jsx)(`span`,{className:`subagent-failure-label`,children:`卡在`}),(0,B.jsx)(`span`,{className:`subagent-failure-stage`,"data-subagent-failure-text":`1`,children:dD[e.failure.stage]}),e.failure.stage===`tool`&&g&&(0,B.jsxs)(`span`,{className:`subagent-failure-tool`,"data-subagent-failure-tool":`1`,children:[`· 正在跑 `,g]}),o.length>0&&(0,B.jsxs)(`span`,{className:`subagent-failure-progress`,children:[`· 死前已尝试 `,o.length,` 次工具调用`]})]}),e.error&&(0,B.jsx)(`div`,{className:`subagent-error`,"data-subagent-error":`1`,children:e.error}),o.length>0&&(0,B.jsxs)(`div`,{className:`subagent-tools`,"data-subagent-tool-count":o.length,children:[c>0&&!n&&(0,B.jsxs)(`button`,{type:`button`,className:`subagent-more`,"data-subagent-hidden":c,onClick:r,children:[`… 另有 `,c,` 条工具调用`]}),s.map((e,t)=>(0,B.jsxs)(`div`,{className:`subagent-tool${e.status?` subagent-tool-${e.status}`:``}`,"data-subagent-tool":e.label,"data-subagent-tool-detail":e.detail??void 0,"data-subagent-tool-status":e.status??`running`,children:[(0,B.jsx)(`span`,{className:`subagent-tool-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,B.jsx)(`span`,{className:`subagent-tool-label`,title:e.label,children:e.label}),e.detail&&(0,B.jsx)(`span`,{className:`subagent-tool-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,B.jsx)(`span`,{className:`subagent-tool-duration`,children:uD(e.durationMs)})]},`${t}:${e.label}`))]}),e.usage&&(0,B.jsxs)(`div`,{className:`subagent-usage`,"data-subagent-usage":`1`,"data-subagent-turns":e.usage.turns,children:[(0,B.jsxs)(`span`,{children:[e.usage.turns,` turns`]}),(0,B.jsxs)(`span`,{children:[`↑`,lD(e.usage.input)]}),(0,B.jsxs)(`span`,{children:[`↓`,lD(e.usage.output)]}),e.usage.cacheRead>0&&(0,B.jsxs)(`span`,{children:[`cache↓`,lD(e.usage.cacheRead)]}),e.usage.cacheWrite>0&&(0,B.jsxs)(`span`,{children:[`cache↑`,lD(e.usage.cacheWrite)]}),e.usage.cost>0&&(0,B.jsxs)(`span`,{children:[`$`,e.usage.cost.toFixed(4)]})]}),o.length>10&&(0,B.jsx)(`button`,{type:`button`,className:`subagent-collapse`,"data-subagent-collapse":e.id,"aria-expanded":n,onClick:r,children:n?`收起`:`展开全部 ${o.length} 条`})]})}function _D({messages:e,running:t,onSteer:n,onInterrupt:r,onSend:i,onCancel:a,onEdit:o}){let[s,c]=(0,z.useState)(!1);if(!e.length)return null;let l=e.filter(e=>e.delivery===`sending`).length;return(0,B.jsxs)(`section`,{className:`queue-dock`,"data-queue-dock":`1`,"data-queue-count":e.length,"data-queue-sending":l,"aria-label":`排队等待回答的消息`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`queue-dock-head`,"data-queue-collapse":`1`,"aria-expanded":!s,onClick:()=>c(e=>!e),children:[(0,B.jsx)(`span`,{className:`chevron`,children:s?`▸`:`▾`}),(0,B.jsxs)(`strong`,{children:[e.length,` 条等待回答`]}),l>0&&(0,B.jsxs)(`span`,{className:`queue-dock-badge`,"data-queue-badge":`sending`,children:[`已交给 Agent `,l,` 条`]}),s&&(0,B.jsx)(`span`,{className:`queue-dock-preview`,children:vD(e[0])})]}),!s&&(0,B.jsx)(`ul`,{className:`queue-dock-list`,children:e.map((s,c)=>(0,B.jsx)(bD,{message:s,order:c+1,total:e.length,running:t,onSteer:n,onInterrupt:r,onSend:i,onCancel:a,onEdit:o},s.id))})]})}function vD(e){return e.content||(e.images?.length?`【图片】(${e.images.length})`:``)}function yD(e){if(e.role!==`tool`)return{label:`后台回传`,state:`completed`};let t=(()=>{let t=/<summary>([\s\S]*?)<\/summary>/.exec(e.content);return t?t[1].trim():`后台回传`})(),n=/<task id="[^"]+" state="([^"]+)"/.exec(e.content);return{label:t,state:n?n[1]:`completed`}}function bD({message:e,order:t,total:n,running:r,onSteer:i,onInterrupt:a,onSend:o,onCancel:s,onEdit:c}){let[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(e.content),p=e.delivery===`sending`,m=e.role===`tool`,{label:h,state:g}=m?yD(e):{label:vD(e),state:`user`},_=()=>{let t=d.trim();t&&t!==e.content&&c(e.id,t),u(!1)};return(0,B.jsxs)(`li`,{className:`queue-row ${p?`queue-row-sending`:`queue-row-queued`} ${m?`queue-row-bg-result`:``}`,"data-queue-id":e.id,"data-message-delivery":e.delivery,"data-message-role":e.role,"data-bg-result-state":m?g:void 0,"data-waiting-order":t,"data-waiting-total":n,children:[(0,B.jsx)(`span`,{className:`queue-index`,"aria-hidden":`true`,children:t}),m?(0,B.jsxs)(`span`,{className:`queue-bg-result`,title:h,children:[(0,B.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:g===`error`?`✕`:`↩`}),(0,B.jsx)(`span`,{className:`bg-result-label`,children:`后台回传`}),(0,B.jsx)(`span`,{className:`bg-result-summary`,children:h})]}):l?(0,B.jsxs)(`div`,{className:`queue-row-edit`,children:[(0,B.jsx)(`textarea`,{value:d,autoFocus:!0,rows:2,"aria-label":`修改这条等待中的消息`,onChange:e=>f(e.target.value),onKeyDown:t=>{t.key===`Escape`&&(t.preventDefault(),f(e.content),u(!1)),t.key===`Enter`&&(t.metaKey||t.ctrlKey)&&(t.preventDefault(),_())}}),(0,B.jsx)(`button`,{type:`button`,className:`queue-edit-save`,"data-waiting-save":e.id,onClick:_,children:`保存`}),(0,B.jsx)(`button`,{type:`button`,className:`queue-edit-cancel`,"data-waiting-cancel-edit":e.id,onClick:()=>{f(e.content),u(!1)},children:`取消`})]}):(0,B.jsx)(`span`,{className:`queue-text`,title:h,children:h}),(0,B.jsx)(`span`,{className:`queue-state`,"data-waiting-state":p?`sending`:`queued`,children:p?`已交给 Agent`:t===1?`下一条回答这条`:`等待回答 · 第 ${t} 条`}),p?(0,B.jsx)(`span`,{className:`queue-locked`,"data-waiting-locked":e.id,children:`暂时改不了`}):(0,B.jsxs)(B.Fragment,{children:[r?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`button`,{type:`button`,className:`queue-interrupt`,"data-waiting-interrupt":e.id,title:`停止当前任务,立即回答这条消息`,"aria-label":`停止当前任务并回答「${h}」`,onClick:()=>a(e.id),children:`打断并回答`}),(0,B.jsx)(`button`,{type:`button`,className:`queue-steer`,"data-waiting-steer":e.id,title:t===1?`当前工具完成后回答这条消息`:`插到最前:让它成为下一条被回答的消息`,"aria-label":t===1?`当前工具完成后回答「${h}」`:`让「${h}」插到最前`,onClick:()=>i(e.id),children:t===1?`当前工具完成后回答`:`插到最前`})]}):(0,B.jsx)(`button`,{type:`button`,className:`queue-steer`,"data-waiting-send":e.id,title:`现在就回答这条消息`,"aria-label":`现在就回答「${h}」`,onClick:()=>o(e.id),children:`现在就回答`}),!m&&(0,B.jsx)(`button`,{type:`button`,className:`queue-edit`,"data-waiting-edit":e.id,title:`回答这条之前改字`,"aria-label":`修改「${h}」`,onClick:()=>{f(e.content),u(!0)},children:`改字`}),(0,B.jsx)(`button`,{type:`button`,className:`queue-cancel`,"data-waiting-cancel":e.id,title:`撤回这条消息,它不会被回答`,"aria-label":`撤回「${h}」`,onClick:()=>s(e.id),children:`撤回`})]})]})}function xD({question:e,index:t,expanded:n,onToggle:r,onAnswer:i}){return(0,B.jsxs)(`div`,{className:`call-block question-block-${e.status}`,"data-call-block":t,"data-call-tool":`question`,"data-call-detail":`提问`,"data-call-status":e.status===`answered`?`ok`:e.status===`cancelled`?`error`:`running`,"data-call-expanded":n?`true`:`false`,"data-question-block":t,children:[(0,B.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-question-fold-edge":t,"aria-expanded":n,"aria-label":`${n?`折叠`:`展开`}提问`,title:n?`折叠这段提问`:`展开这段提问`,onClick:r}),(0,B.jsxs)(`div`,{className:`call-head-row`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:r,children:[(0,B.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,B.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`answered`?`✓`:e.status===`cancelled`?`✕`:`?`}),(0,B.jsx)(`span`,{className:`call-label`,children:`提问`}),(0,B.jsxs)(`span`,{className:`call-detail`,children:[e.items.length,` 个问题`]})]}),n&&(0,B.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:r,children:`收起`})]}),n&&(0,B.jsx)(`div`,{className:`question-body`,"data-question-body":t,children:(0,B.jsx)(SD,{question:e,onAnswer:i})})]})}function SD({question:e,onAnswer:t}){let[n,r]=(0,z.useState)(()=>Object.fromEntries((e.answers??[]).map(e=>[e.id,e.selected]))),[i,a]=(0,z.useState)(()=>e.answers?.map(e=>e.note??``).join(`
|
|
93
|
+
`)??``),o=(e,t,n)=>{r(r=>{let i=r[e]??[];return n?{...r,[e]:i.includes(t)?i.filter(e=>e!==t):[...i,t]}:{...r,[e]:[t]}})},s=()=>{t(e.items.map(e=>({id:e.id,selected:n[e.id]??[],...e.extraNote&&i.trim()?{note:i.trim()}:{}})),!1)},c=e.items.some(e=>(n[e.id]??[]).length>0);return(0,B.jsxs)(`div`,{className:`question-block question-${e.status}`,"data-question-status":e.status,children:[e.items.map(t=>(0,B.jsxs)(`div`,{className:`question-item`,children:[(0,B.jsx)(`div`,{className:`question-text`,children:t.header?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`span`,{className:`question-header`,children:t.header}),(0,B.jsx)(`span`,{className:`question-sep`,children:` · `}),(0,B.jsx)(tm,{source:t.question})]}):(0,B.jsx)(tm,{source:t.question})}),(0,B.jsx)(`div`,{className:`question-options`,"data-question-options":t.id,children:t.options.map(r=>{let i=(n[t.id]??[]).includes(r),a=e.status!==`pending`;return(0,B.jsxs)(`label`,{className:i?`is-chosen`:``,"data-chosen":a&&i?`1`:void 0,children:[(0,B.jsx)(`input`,{type:t.multiple?`checkbox`:`radio`,name:`q-${t.id}`,checked:i,disabled:a,onChange:()=>o(t.id,r,t.multiple)}),(0,B.jsx)(nm,{source:r}),a&&i?(0,B.jsx)(`span`,{className:`question-mark`,"aria-label":`已选择`,children:`✓`}):null]},r)})}),e.status===`pending`&&t.extraNote?(0,B.jsx)(`textarea`,{value:i,placeholder:`补充说明(可选)`,onChange:e=>a(e.target.value)}):e.status===`answered`&&(e.answers??[]).some(e=>e.note)?(0,B.jsxs)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:[`补充:`,(e.answers??[]).map(e=>e.note).filter(Boolean).join(`;`)]}):null,e.status===`cancelled`&&(0,B.jsx)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:`已取消,没有作答。`})]},t.id)),e.status===`pending`&&(0,B.jsxs)(`div`,{className:`question-actions`,children:[(0,B.jsx)(`button`,{type:`button`,onClick:s,disabled:!c,children:`提交`}),(0,B.jsx)(`button`,{type:`button`,className:`question-skip`,onClick:()=>t([],!0),children:`跳过`})]})]})}function CD({request:e,onAnswer:t,pending:n}){let[r,i]=(0,z.useState)(e.prefill??``),a=e.method===`input`||e.method===`editor`,o=(0,B.jsx)(`button`,{type:`button`,className:`extui-cancel`,onClick:()=>t({cancelled:!0}),children:`取消提问`});return(0,B.jsxs)(`article`,{className:`extui-card extui-${e.method}`,"data-request-id":e.requestId,"data-method":e.method,children:[(0,B.jsxs)(`div`,{className:`extui-head`,children:[(0,B.jsx)(`span`,{className:`extui-badge`,children:`扩展提问`}),e.timeoutMs!==void 0&&(0,B.jsxs)(`span`,{className:`extui-deadline`,children:[Math.round(e.timeoutMs/1e3),`s 超时`]})]}),n&&(0,B.jsx)(`p`,{role:`status`,children:`提交中…`}),(0,B.jsxs)(`fieldset`,{disabled:n,style:{border:0,padding:0,margin:0},children:[(0,B.jsx)(`h3`,{className:`extui-title`,children:e.title||e.method}),e.method===`confirm`&&(0,B.jsx)(`p`,{className:`extui-body`,children:e.message}),e.method===`select`&&(0,B.jsxs)(`div`,{className:`extui-options`,children:[(e.options??[]).map(e=>(0,B.jsx)(`button`,{type:`button`,className:`extui-option`,onClick:()=>t({value:e}),children:e},e)),(e.options??[]).length===0&&(0,B.jsx)(`p`,{className:`extui-body`,children:`扩展没有提供任何选项`})]}),a&&(0,B.jsxs)(`form`,{className:`extui-form`,onSubmit:e=>{e.preventDefault(),!n&&r.trim()&&t({value:r})},children:[e.method===`input`?(0,B.jsx)(`input`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&NE(e)&&e.preventDefault()},placeholder:e.placeholder??``}):(0,B.jsx)(`textarea`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&NE(e)&&e.preventDefault()}}),(0,B.jsxs)(`div`,{className:`extui-actions`,children:[(0,B.jsx)(`button`,{type:`submit`,className:`extui-primary`,disabled:!r.trim(),children:`提交`}),o]})]}),!a&&(0,B.jsxs)(`div`,{className:`extui-actions`,children:[e.method===`confirm`&&(0,B.jsx)(`button`,{type:`button`,className:`extui-primary`,onClick:()=>t({confirmed:!0}),children:`确认`}),e.method===`confirm`&&(0,B.jsx)(`button`,{type:`button`,className:`extui-no`,onClick:()=>t({confirmed:!1}),children:`拒绝`}),o]})]})]})}function wD({initial:e,label:t,onCommit:n,onClose:r}){let[i,a]=(0,z.useState)(e),o=(0,z.useRef)(null),s=(0,z.useRef)(!1);(0,z.useEffect)(()=>{o.current?.focus(),o.current?.select()},[]);let c=!i.trim(),l=()=>{s.current=!0,r()},u=()=>{if(c)return;let t=i.trim();(t===e||n(t))&&l()};return(0,B.jsxs)(`div`,{className:`inline-edit`,"data-editing":`1`,children:[(0,B.jsx)(`input`,{ref:o,className:`inline-edit-input`,value:i,"aria-label":t,onChange:e=>a(e.target.value),onKeyDown:e=>{if(e.key===`Enter`){if(NE(e))return;e.preventDefault(),u()}else e.key===`Escape`&&(e.preventDefault(),l())},onBlur:()=>{s.current||r()}}),(0,B.jsx)(`button`,{type:`button`,className:`inline-edit-ok`,title:`确认重命名`,"aria-label":`确认重命名`,disabled:c,onMouseDown:e=>e.preventDefault(),onClick:u,children:`✓`}),(0,B.jsx)(`button`,{type:`button`,className:`inline-edit-cancel`,title:`取消重命名`,"aria-label":`取消重命名`,onMouseDown:e=>e.preventDefault(),onClick:l,children:`✗`})]})}function TD({kind:e,label:t,value:n,detail:r,options:i,disabled:a,note:o,onChoose:s,scope:c}){let[l,u]=(0,z.useState)(!1),[d,f]=(0,z.useState)(``),[p,m]=(0,z.useState)(0),h=(0,z.useRef)(null),g=(0,z.useRef)(null),_=(0,z.useRef)(null),v=(0,z.useRef)(null),y=(0,z.useRef)([]),b=i.find(e=>e.selected),x=rD(i,d),S=x.length===0?-1:Math.min(Math.max(p,0),x.length-1),C=S<0?void 0:x[S],w=(e=!1)=>{u(!1),e&&g.current?.focus()},T=()=>{f(``),m(Math.max(i.findIndex(e=>e.selected),0)),u(!0)},E=e=>m(t=>x.length?Math.min(Math.max(t+e,0),x.length-1):0);(0,z.useEffect)(()=>{if(!l)return;let e=e=>{h.current?.contains(e.target)||w()};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[l]),(0,z.useEffect)(()=>{if(!l)return;let e=h.current,t=t=>{e?.contains(t.relatedTarget)||w()};return e?.addEventListener(`focusout`,t),()=>e?.removeEventListener(`focusout`,t)},[l]),(0,z.useEffect)(()=>{l&&v.current?.focus()},[l]),(0,z.useEffect)(()=>{l&&S>=0&&y.current[S]?.scrollIntoView({block:`nearest`})},[l,S]),(0,z.useLayoutEffect)(()=>{if(!l)return;let e=_.current;if(!e)return;e.style.setProperty(`--picker-nudge`,`0px`),e.style.setProperty(`--picker-drop`,`0px`);let t=e.getBoundingClientRect(),n=Math.min(window.innerWidth-8-t.right,Math.max(8-t.left,0)),r=Math.min(window.innerHeight-8-t.bottom,Math.max(8-t.top,0));e.style.setProperty(`--picker-nudge`,`${n}px`),e.style.setProperty(`--picker-drop`,`${r}px`)},[l,x.length,i.length]);let D=e=>{if(l){if(e.key===`Escape`)e.preventDefault(),w(!0);else if(e.key===`ArrowDown`)e.preventDefault(),E(1);else if(e.key===`ArrowUp`)e.preventDefault(),E(-1);else if(e.key===`Home`)e.preventDefault(),m(0);else if(e.key===`End`)e.preventDefault(),m(Math.max(x.length-1,0));else if(e.key===`Enter`){if(NE(e))return;e.preventDefault(),C&&(s(C.key),w(!0))}}},O=`picker-list-${c??e}`,k=t=>`picker-option-${c??e}-${t}`;return(0,B.jsxs)(`div`,{className:`session-picker-item session-picker-${e}`,ref:h,onKeyDown:l?D:void 0,children:[(0,B.jsxs)(`button`,{ref:g,type:`button`,className:`session-picker-trigger`,disabled:a,"aria-haspopup":`listbox`,"aria-expanded":l,title:o??`${ZE[e]}:${r?`${t} · ${r}`:t}`,"data-picker-trigger":e,"data-picker-value":n??t,"data-picker-selected":i.some(e=>e.selected),onClick:()=>l?w():T(),children:[(0,B.jsx)(`span`,{className:`session-picker-kind`,children:ZE[e]}),(0,B.jsx)(`span`,{className:`session-picker-name`,children:t}),r&&(0,B.jsx)(`span`,{className:`session-picker-detail`,children:r}),(0,B.jsx)(`span`,{className:`session-picker-caret`,"aria-hidden":`true`,children:`▾`})]}),l&&(0,B.jsxs)(`div`,{className:`picker-menu`,ref:_,"data-picker-menu":e,"data-picker-highlight":S,children:[(0,B.jsxs)(`div`,{className:`picker-filter`,children:[(0,B.jsx)(`span`,{className:`picker-filter-icon`,"aria-hidden":`true`,children:`🔍`}),(0,B.jsx)(`input`,{ref:v,className:`picker-filter-input`,"data-picker-filter":e,role:`combobox`,"aria-label":`筛选${QE[e]}选项`,"aria-expanded":`true`,"aria-controls":O,"aria-autocomplete":`list`,"aria-activedescendant":C?k(S):void 0,value:d,placeholder:`输入以筛选…`,autoComplete:`off`,spellCheck:!1,onChange:e=>{f(e.target.value),m(0)}}),d&&(0,B.jsx)(`button`,{type:`button`,className:`picker-filter-clear`,"data-picker-filter-clear":e,title:`清空筛选`,"aria-label":`清空筛选`,onMouseDown:e=>e.preventDefault(),onClick:()=>{f(``),m(0),v.current?.focus()},children:`✕`})]}),b&&!x.some(e=>e.key===b.key)&&(0,B.jsxs)(`div`,{className:`picker-current`,"data-picker-current":e,"data-picker-current-value":b.key,children:[(0,B.jsx)(`span`,{className:`picker-current-label`,children:`当前`}),(0,B.jsx)(`span`,{className:`picker-current-value`,children:b.label})]}),(0,B.jsxs)(`div`,{className:`picker-list`,role:`listbox`,id:O,"aria-label":$E[e],children:[x.map((e,t)=>(0,B.jsxs)(`button`,{id:k(t),type:`button`,role:`option`,"aria-selected":e.selected,ref:e=>{y.current[t]=e},className:`picker-option${e.selected?` selected`:``}${t===S&&!e.selected?` preview`:``}`,"data-picker-option":e.key,"data-picker-option-selected":e.selected,"data-picker-highlight":t===S,onClick:()=>{s(e.key),w(!0)},children:[e.color&&(0,B.jsx)(`span`,{className:`picker-option-swatch`,style:{background:e.color},"aria-hidden":`true`}),(0,B.jsx)(`span`,{className:`picker-option-name`,children:e.label}),e.badge&&(0,B.jsx)(`span`,{className:`picker-option-badge`,"data-picker-option-badge":e.badge,children:e.badge}),e.detail&&(0,B.jsx)(`span`,{className:`picker-option-detail`,children:e.detail}),e.selected&&(0,B.jsx)(`span`,{className:`picker-option-mark`,"aria-hidden":`true`,children:`✓`})]},e.key)),x.length===0&&(0,B.jsx)(`div`,{className:`picker-empty`,"data-picker-empty":e,children:`没有匹配「${d.trim()}」的${QE[e]}`})]})]})]})}var ED=`__pi_default__`;function DD({workspace:e,catalog:t,agents:n,onSave:r,onRename:i,onClose:a}){let[o,s]=(0,z.useState)(e.defaultAgentId),[c,l]=(0,z.useState)(e.defaultModel),[u,d]=(0,z.useState)(e.defaultThinkingLevel);(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.defaultPrevented&&a()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[a]);let f=t?.source===`pi`,p=[{key:ED,label:`跟随 Pi 默认`,detail:`不为新会话指定模型`,selected:c===void 0},...(t?.models??[]).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:e.detail,badge:tD(e),selected:c?.provider===e.provider&&c.modelId===e.modelId}))],m=[{key:ED,label:`跟随 Pi 默认`,detail:`不为新会话指定思考等级`,selected:u===void 0},...(t?.levels??[]).map(e=>({key:e,label:e,selected:e===u}))],h=e=>{if(e===ED){l(void 0);return}let n=(t?.models??[]).find(t=>t.provider===e.split(`/`)[0]&&t.modelId===e.split(`/`)[1]);n&&l({provider:n.provider,modelId:n.modelId,label:n.label})},g=e=>d(e===ED?void 0:e),_=[{key:ED,label:`跟随 Pi 默认`,detail:`新会话不使用任何 agent 角色`,selected:o===void 0},...(n?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:o===e.id}))];return(0,B.jsx)(`div`,{className:`overlay`,onClick:a,children:(0,B.jsxs)(`div`,{className:`picker settings-dialog`,"data-settings-dialog":`1`,onClick:e=>e.stopPropagation(),children:[(0,B.jsx)(`h2`,{children:`工作区设置`}),(0,B.jsxs)(`div`,{className:`settings-scope`,children:[e.name,` · 默认值只影响之后新建的会话,已有会话不变`]}),(0,B.jsxs)(`div`,{className:`settings-row`,children:[(0,B.jsx)(`span`,{className:`settings-label`,children:`默认智能体`}),(0,B.jsx)(TD,{kind:`agent`,scope:`settings-agent`,label:n?.agents.find(e=>e.id===o)?.name??`跟随 Pi 默认`,value:o??ED,detail:o?`${n?.agents.find(e=>e.id===o)?.toolSummary??``}`:void 0,options:_,disabled:!n||n.source===`unavailable`,note:cD(n),onChoose:e=>s(e===ED?void 0:e)})]}),(0,B.jsxs)(`div`,{className:`settings-row`,children:[(0,B.jsx)(`span`,{className:`settings-label`,children:`默认模型`}),(0,B.jsx)(TD,{kind:`model`,scope:`settings-model`,label:c?.label??`跟随 Pi 默认`,value:c?`${c.provider}/${c.modelId}`:ED,detail:c?`${c.provider}/${c.modelId}`:void 0,options:p,disabled:!f,note:sD(`模型`,t),onChoose:h})]}),(0,B.jsxs)(`div`,{className:`settings-row`,children:[(0,B.jsx)(`span`,{className:`settings-label`,children:`思考强度`}),(0,B.jsx)(TD,{kind:`thinking`,scope:`settings-thinking`,label:u??`跟随 Pi 默认`,value:u??ED,options:m,disabled:!f,note:sD(`思考等级`,t),onChoose:g})]}),(0,B.jsxs)(`div`,{className:`picker-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`settings-rename`,"data-settings-rename":`1`,onClick:i,children:`重命名工作区`}),(0,B.jsx)(`button`,{type:`button`,className:`picker-cancel`,"data-settings-cancel":`1`,onClick:a,children:`取消`}),(0,B.jsx)(`button`,{type:`button`,className:`picker-ok`,"data-settings-save":`1`,onClick:()=>r(o,c,u),children:`保存`})]})]})})}var OD=[{id:`main`,label:`主`,name:`主 tab`},{id:`tools`,label:`工具`,name:`工具 tab`},{id:`files`,label:`文件`,name:`文件 tab`},{id:`git`,label:`Git`,name:`Git tab`},{id:`terminal`,label:`终端`,name:`终端 tab`}],kD={waiting:`⋯`,running:``,failed:`!`,question:`?`,unread:`•`,idle:``},AD={waiting:`等待 LLM`,running:`进行中`,failed:`出错`,question:`等你回答`,unread:`有未读`,idle:`空闲`};function jD(e,t,n){return t?`question`:e.status===`failed`?`failed`:e.status===`waiting`?`waiting`:e.status===`running`?`running`:e.updatedAt>(n??``)?`unread`:`idle`}function MD({state:e}){let t=kD[e];return e===`idle`?null:(0,B.jsx)(`i`,{className:`session-state session-state-${e}`,"data-session-state":e,title:AD[e],"aria-label":AD[e],children:(0,B.jsx)(`i`,{className:`session-state-mark`,"aria-hidden":`true`,children:t})})}var ND={pending:`未开始`,in_progress:`进行中`,completed:`已完成`},PD={pending:`○`,in_progress:`◐`,completed:`✓`},FD={high:`高`,medium:`中`,low:`低`};function ID(e){let t=e.filter(e=>e.status!==`completed`).length;return e.length?t?`${t} 个未完成 / 共 ${e.length} 个`:`全部完成:${e.length} 个`:`0 个待办任务`}function LD({todo:e,index:t}){let n=e.id??`todo_${t}`;return(0,B.jsxs)(`li`,{className:`todo-item todo-${e.status}`,"data-todo-item":n,"data-todo-status":e.status,children:[(0,B.jsx)(`span`,{className:`todo-mark`,"aria-hidden":`true`,children:PD[e.status]}),(0,B.jsx)(`span`,{className:`todo-text`,children:e.content}),(0,B.jsx)(`span`,{className:`todo-status`,"data-todo-status-text":`1`,children:ND[e.status]}),e.priority&&(0,B.jsx)(`span`,{className:`todo-priority`,"data-todo-priority":e.priority,children:FD[e.priority]})]})}function RD({tasks:e,onStop:t}){return(0,B.jsx)(`ul`,{className:`bg-list`,"data-bg-task-count":e.length,children:e.map((e,n)=>{let r=e.id||`bg_${n}`,i=e.status?.trim()||`未知状态`;return(0,B.jsxs)(`li`,{className:`bg-item`,"data-bg-task":r,"data-bg-task-status":e.status??`unknown`,children:[(0,B.jsxs)(`div`,{className:`bg-item-header`,children:[(0,B.jsx)(`span`,{className:`bg-title`,children:e.title?.trim()||e.id||`未命名任务 ${n+1}`}),t&&(0,B.jsx)(`button`,{type:`button`,className:`bg-stop-btn`,"data-bg-task-stop":e.id,title:`终止后台任务`,onClick:()=>t(e.id),children:`终止`})]}),(0,B.jsxs)(`span`,{className:`bg-meta`,children:[e.agentId?.trim()&&(0,B.jsx)(`span`,{className:`bg-agent`,"data-bg-agent":e.agentId,children:e.agentId}),(0,B.jsx)(`span`,{className:`bg-status`,children:i})]})]},r)})})}function zD({todos:e,tasks:t,collapsed:n,onToggle:r,workspaceId:i,workspaceLabel:a,conversationId:o,connected:s,files:c,onOpenFile:l,onOpenChanged:u,activeTab:d,onSelectTab:f,sendCommand:p,registerTerminalSink:m}){let h=OD;return h.some(e=>e.id===d)||h[0].id,(0,B.jsx)(`div`,{className:`right-rail${n?` right-rail-collapsed`:``}`,role:`complementary`,"aria-label":`右侧栏`,"data-right-rail":`1`,"data-right-rail-collapsed":n,children:n?(0,B.jsx)(`button`,{type:`button`,className:`right-rail-open`,"data-right-rail-open":`1`,title:`展开右侧栏`,"aria-label":`展开右侧栏`,onClick:r,children:`‹`}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`right-rail-head`,children:[(0,B.jsx)(`div`,{className:`right-tabs`,role:`tablist`,"aria-label":`右侧栏 tab`,"data-right-tab-count":h.length,children:h.map(e=>(0,B.jsx)(`button`,{type:`button`,role:`tab`,id:`right-tab-${e.id}`,className:`right-tab${e.id===d?` right-tab-active`:``}`,"data-right-tab":e.id,"aria-selected":e.id===d,"aria-controls":`right-panel-${e.id}`,title:e.name,"aria-label":e.name,onClick:()=>f(e.id),children:e.label},e.id))}),(0,B.jsx)(`button`,{type:`button`,className:`right-rail-collapse`,"data-right-rail-collapse":`1`,title:`收起右侧栏(聊天区会变宽)`,"aria-label":`收起右侧栏`,onClick:r,children:`›`})]}),OD.filter(e=>e.id===d).map(n=>(0,B.jsxs)(`div`,{className:`right-rail-body`,role:`tabpanel`,id:`right-panel-${n.id}`,"aria-labelledby":`right-tab-${n.id}`,"data-right-panel":n.id,children:[n.id===`main`&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`rail-section-head`,children:[(0,B.jsx)(`h2`,{className:`rail-section-title`,children:`待办任务`}),(0,B.jsx)(`span`,{className:`rail-section-count`,"data-todo-summary":`1`,children:ID(e)})]}),e.length>0?(0,B.jsx)(`ol`,{className:`todo-list`,"data-todo-count":e.length,children:e.map((e,t)=>(0,B.jsx)(LD,{todo:e,index:t},e.id??`todo_${t}`))}):(0,B.jsx)(`p`,{className:`rail-empty`,"data-todo-empty":`1`,children:`暂无待办任务。Agent 开始处理多步骤任务时,会自己把待办写到这里。`}),(0,B.jsxs)(`div`,{className:`rail-section-head`,children:[(0,B.jsx)(`h2`,{className:`rail-section-title`,children:`后台任务`}),(0,B.jsx)(`span`,{className:`rail-section-count`,"data-bg-summary":`1`,children:t.length?`${t.length} 个运行中`:`0 个`})]}),t.length>0?(0,B.jsx)(RD,{tasks:t,onStop:e=>p({type:`backgroundTask.stop`,taskId:e})}):(0,B.jsx)(`p`,{className:`rail-empty`,"data-bg-empty":`1`,children:`当前没有正在运行的后台任务。`})]}),n.id===`tools`&&(0,B.jsx)(HD,{}),n.id===`files`&&(0,B.jsx)(zg,{workspaceId:i,files:c,onOpenFile:l,onOpenChanged:u}),n.id===`git`&&(0,B.jsx)(tp,{workspaceId:i??null,conversationId:o,onOpenChanged:u},o||`global`),n.id===`terminal`&&(0,B.jsx)(hE,{workspaceId:i,workspaceLabel:a,conversationId:o,connected:s,sendCommand:p,registerSink:m},o||`global`)]},n.id))]})})}function BD(){try{if(typeof window>`u`)return h_.slice();let e=x_(window.localStorage.getItem(v_));return window.localStorage.getItem(`super-pi:tools:v1`)===null?h_.slice():e}catch{return h_.slice()}}function VD(e){try{if(typeof window>`u`)return;window.localStorage.setItem(v_,S_(e))}catch{}}function HD(){let[e,t]=(0,z.useState)(BD),[n,r]=(0,z.useState)([]),[i,a]=(0,z.useState)(),[o,s]=(0,z.useState)(!1),[c,l]=(0,z.useState)(),u=e.find(e=>e.id===i),d=(0,z.useCallback)(async()=>{try{let e=await fetch(`/api/tools`),t=await e.json();e.ok&&Array.isArray(t.tools)&&r(t.tools.filter(e=>e.enabled))}catch{}},[]),f=async e=>{l(void 0);try{let t=await fetch(`/api/tools?id=${encodeURIComponent(e)}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);a(t=>t===e?void 0:t),await d()}catch(e){l(`移除工具失败:${e instanceof Error?e.message:String(e)}`)}};return(0,z.useEffect)(()=>{VD(e)},[e]),(0,z.useEffect)(()=>{d();let e=()=>{d()};return window.addEventListener(`super-pi-tools-updated`,e),()=>window.removeEventListener(`super-pi-tools-updated`,e)},[d]),(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`rail-section-head`,children:[(0,B.jsx)(`h2`,{className:`rail-section-title`,children:`工具`}),(0,B.jsxs)(`span`,{className:`rail-section-count`,"data-tool-summary":`1`,children:[e.length+n.length,` 个`]})]}),e.length+n.length>0?(0,B.jsxs)(`ul`,{className:`tool-grid`,"data-tool-count":e.length+n.length,children:[e.map(e=>(0,B.jsxs)(`li`,{className:`tool-slot`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`tool-icon`,"data-tool-icon":e.id,"data-tool-kind":e.kind,"data-tool-state":e.id===i?`open`:`idle`,title:`打开${e.name}`,"aria-label":`打开${e.name}`,"aria-current":e.id===i?`true`:void 0,onClick:()=>a(t=>t===e.id?void 0:e.id),children:[(0,B.jsx)(`span`,{className:`tool-icon-glyph`,"aria-hidden":`true`,children:e.glyph}),(0,B.jsx)(`span`,{className:`tool-icon-name`,children:e.name})]}),e.kind===`link`&&(0,B.jsx)(`button`,{type:`button`,className:`tool-remove`,"data-tool-remove":e.id,title:`移除${e.name}`,"aria-label":`移除${e.name}`,onClick:()=>{t(t=>E_(t,e.id)),i===e.id&&a(void 0)},children:`✕`})]},e.id)),n.map(e=>(0,B.jsxs)(`li`,{className:`tool-slot`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`tool-icon`,"data-mounted-tool-icon":e.id,title:`打开${e.name}`,"aria-label":`打开${e.name}`,onClick:()=>a(t=>t===e.id?void 0:e.id),children:[(0,B.jsx)(`span`,{className:`tool-icon-glyph`,"aria-hidden":`true`,children:`🧩`}),(0,B.jsx)(`span`,{className:`tool-icon-name`,children:e.name})]}),(0,B.jsx)(`button`,{type:`button`,className:`tool-remove`,"data-tool-remove":e.id,title:`移除${e.name}`,"aria-label":`移除${e.name}`,onClick:()=>void f(e.id),children:`✕`})]},e.id))]}):(0,B.jsx)(`p`,{className:`rail-empty`,"data-tool-empty":`1`,children:`还没有工具。点下面的「工具设置」添加。`}),(0,B.jsx)(`button`,{type:`button`,className:`tools-settings-btn`,"data-tool-settings-trigger":`1`,title:`添加预置工具、网址工具与说明`,"aria-label":`打开工具设置`,onClick:()=>{a(void 0),s(!0)},children:`⚙ 工具设置`}),c&&(0,B.jsx)(`p`,{role:`alert`,"data-tool-error":`1`,children:c}),o&&(0,B.jsx)(UD,{tools:e,onToolsChange:t,mountedTools:n,onRefreshMountedTools:d,onClose:()=>s(!1)}),u&&(0,B.jsx)(KD,{tool:u,onClose:()=>a(void 0)}),n.find(e=>e.id===i)&&(0,B.jsx)($D,{tool:n.find(e=>e.id===i),onClose:()=>a(void 0)})]})}function UD({tools:e,onToolsChange:t,mountedTools:n,onRefreshMountedTools:r,onClose:i}){let[a,o]=(0,z.useState)(``),[s,c]=(0,z.useState)(``),[l,u]=(0,z.useState)(),[d,f]=(0,z.useState)(!1),[p,m]=(0,z.useState)(),[h,g]=(0,z.useState)(),[_,v]=(0,z.useState)(),[y,b]=(0,z.useState)(``),[x,S]=(0,z.useState)(),[C,w]=(0,z.useState)(),[T,E]=(0,z.useState)(!1),[D,O]=(0,z.useState)(),[k,A]=(0,z.useState)(),ee=(0,z.useRef)(null),j=(0,z.useRef)(null),M=async()=>{let e=await JE(`请为 Super Pi 开发一个全局右侧栏工具。不要启动独立 HTTP 服务器,也不要监听端口。
|
|
94
94
|
|
|
95
95
|
工具不属于当前 workspace;通过内置 tool_register 一次性提交完整文件(index.html、JS/CSS,必要时 .py),Super Pi 会保存为全局工具并自动出现在每个 workspace 的工具 Tab。
|
|
96
96
|
|
|
97
|
-
如需本地计算,声明 script: { path, timeoutMs, parameters }。脚本必须是 Python,参数以 JSON 从 stdin 传入,stdout 必须只输出一个 JSON 对象。在 index.html 中加载 <script src="./super-pi-tool.js"><\/script>,然后调用 SuperPiTool.run(params)、SuperPiTool.get(runId)、SuperPiTool.wait(runId) 或 SuperPiTool.cancel(runId)。这些都是已绑定本工具身份的相对接口;不要调用 /api/exec,不要猜测 toolId,也不要传 shell 命令、任意文件路径或未声明参数。页面必须实际执行一次示例任务并显示运行状态、日志和结构化结果。第三方包写进 environment.requires(必须钉死成 pkg==version),首次运行时会装进这个工具自己的虚拟环境。需要模型能力(摘要、改写、抽取、分类)时调用 SuperPiTool.llm({ prompt, system }),不要自己写模型客户端或保管密钥,并在注册时声明 permissions: { llm: true }——否则服务端会拒绝,导入页面也会提示用户。最后返回注册 id、访问地址、文件清单和验证结果。`);f(e),window.setTimeout(()=>f(!1),1800)};(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&i()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i]);let N=n.map(e=>e.slug).filter(e=>typeof e==`string`),te=e=>{m(void 0),g(void 0),A(void 0),O({tool:e,name:yE({slug:e.slug??`tool`})})},ne=async(e,t)=>{m(void 0),g(void 0),A(void 0);let n=bE(t);if(!n.ok)A(n.reason);else try{let t=await fetch(`/api/tools/export?id=${encodeURIComponent(e.id)}`),r=await t.json();if(!t.ok||!r.bundle)throw Error(r.error??`HTTP ${t.status}`);let i=new Blob([JSON.stringify(r.bundle,null,2)],{type:`application/json`}),a=URL.createObjectURL(i),o=document.createElement(`a`);o.href=a,o.download=n.name,document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(a),g(r.skipped?.length?`已导出「${e.name}」,但有 ${r.skipped.length} 个文件没有包含:${r.skipped.join(`、`)}。`:`已导出「${e.name}」。`)}catch(e){m(`导出失败:${e instanceof Error?e.message:String(e)}`)}finally{O(void 0)}},re=async e=>{let t=e.target.files?.[0];if(e.target.value=``,!t)return;m(void 0),g(void 0),S(void 0);let n=gE(await t.text(),t.name);n.ok?(v({filename:t.name,bundle:n.bundle,unnamedFormat:n.unnamedFormat}),b(N.includes(n.bundle.slug)?vE(n.bundle.slug,N):n.bundle.slug),w(n.bundle.files[0]?.path)):m(n.reason)},ie=()=>{v(void 0),b(``),S(void 0),w(void 0)},ae=async()=>{if(!_)return;S(void 0);let e=_E(y);if(!e.ok)S(e.reason);else if(N.includes(e.slug))S(`本机已经有 slug「${e.slug}」的工具,换一个名字再导入。`);else{E(!0);try{let t=await fetch(`/api/tools`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(TE(_.bundle,e.slug))}),n=await t.json();if(!t.ok||!n.id)throw Error(n.error??`HTTP ${t.status}`);await r(),g(`已导入「${_.bundle.name}」,它现在出现在工具栏里,所有工作区都能用。`),ie()}catch(e){m(`导入失败:${e instanceof Error?e.message:String(e)}`)}finally{E(!1)}}};return(0,z.useEffect)(()=>{D&&j.current?.scrollIntoView({block:`center`})},[D]),(0,la.createPortal)((0,B.jsx)(`div`,{className:`tool-overlay`,"data-tool-settings-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&i()},children:(0,B.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-settings-title`,"data-tool-settings":`1`,children:[(0,B.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,B.jsx)(`h2`,{className:`tool-dialog-title`,id:`tool-settings-title`,children:`⚙ 工具设置`}),(0,B.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-settings-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭工具设置`,onClick:i,children:`✕`})]}),(0,B.jsx)(`div`,{className:`tool-dialog-body`,children:_?(0,B.jsx)(RD,{pending:_,slugDraft:y,slugError:x,preview:C,busy:T,onSlugChange:e=>{b(e),S(void 0)},onPreviewChange:w,onCancel:ie,onConfirm:()=>void ae()}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`tool-prompt-card`,children:[(0,B.jsx)(`strong`,{children:`给 Agent 开发新工具`}),(0,B.jsx)(`p`,{className:`tool-hint`,children:`工具会挂载到 Super Pi 的统一 HTTP 服务,不需要再启动独立服务器。`}),(0,B.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-development-prompt":`1`,onClick:()=>void M(),children:d?`已复制`:`复制工具开发 Prompt`})]}),(0,B.jsx)(`div`,{className:`rail-section-head`,children:(0,B.jsx)(`h2`,{className:`rail-section-title`,children:`从预置列表添加`})}),(0,B.jsx)(`div`,{className:`tool-presets`,"data-tool-presets":c_.length,children:c_.map(n=>{let r=e.some(e=>e.kind===n.kind);return(0,B.jsxs)(`div`,{className:`tool-preset`,"data-tool-preset":n.kind,children:[(0,B.jsx)(`span`,{className:`tool-preset-glyph`,"aria-hidden":`true`,children:n.glyph}),(0,B.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,B.jsx)(`strong`,{children:n.name}),(0,B.jsx)(`small`,{children:n.blurb})]}),(0,B.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-add-preset":n.kind,disabled:r,title:r?`${n.name}已经在工具栏里了`:`添加${n.name}`,"aria-label":r?`${n.name}已添加`:`添加${n.name}`,onClick:()=>t(y_(e,n.kind)),children:r?`已添加`:`添加`})]},n.kind)})}),(0,B.jsx)(`div`,{className:`rail-section-head`,children:(0,B.jsx)(`h2`,{className:`rail-section-title`,children:`添加网址工具`})}),(0,B.jsx)(`p`,{className:`tool-hint`,children:`填一个网址,它会变成一个图标;点开后在弹窗里用按钮在新标签页打开。网址只接受 http / https / mailto。`}),(0,B.jsx)(`input`,{className:`tool-input`,"data-tool-url-input":`1`,value:a,maxLength:2048,placeholder:`https://example.com/工具`,"aria-label":`工具网址`,onChange:e=>{o(e.target.value),u(void 0)}}),(0,B.jsx)(`input`,{className:`tool-input`,"data-tool-url-name":`1`,value:s,maxLength:40,placeholder:`名称(可留空,默认用域名)`,"aria-label":`工具名称(可选)`,onChange:e=>c(e.target.value)}),(0,B.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-url-add":`1`,disabled:!a.trim(),onClick:()=>{let n=m_(a);n.ok?e.length>=32?u(`工具最多 32 个,先删掉一个再加。`):(t([...e,{id:v_(`link`,e.map(e=>e.id)),kind:`link`,name:s.trim()||zD(n.url),glyph:`↗`,url:n.url}]),o(``),c(``),u(void 0)):u(n.reason)},children:`添加网址工具`}),l&&(0,B.jsx)(`p`,{className:`tool-error`,"data-tool-error":`1`,role:`alert`,children:l}),(0,B.jsxs)(`p`,{className:`tool-hint`,"data-tool-scope-note":`1`,children:[`能自定义到哪:从上面挑预置工具,或自己填一个网址。`,(0,B.jsx)(`b`,{children:`没有开放「写一段脚本来执行」这一档`}),`——它在浏览器里等同于任意代码执行,会拿着本应用的权限跑。计算器是手写的算术解析器,不含 eval,也认不出变量名。`]}),(0,B.jsx)(`div`,{className:`rail-section-head`,children:(0,B.jsxs)(`h2`,{className:`rail-section-title`,children:[`已安装的全局工具(`,n.length,`)`]})}),n.length===0?(0,B.jsx)(`p`,{className:`tool-hint`,"data-tool-mounted-empty":`1`,children:`还没有通过 tool_register 注册的工具。上面复制那段 Prompt,让 Agent 写一个。`}):(0,B.jsx)(`div`,{className:`tool-presets`,"data-tool-mounted-list":n.length,children:n.map(e=>{let t=CE(e.environmentState);return(0,B.jsxs)(`div`,{className:`tool-share-row`,"data-tool-share-row":e.id,children:[(0,B.jsx)(`span`,{className:`tool-preset-glyph`,"aria-hidden":`true`,children:`🧩`}),(0,B.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,B.jsx)(`strong`,{children:e.name}),(0,B.jsx)(`small`,{"data-tool-env":e.environmentState?.state??`unknown`,children:t?`${t.warn?`⚠ `:``}${t.text}${e.environmentState?.detail?` · ${e.environmentState.detail}`:``}`:`环境未知`}),e.permissions?.llm&&(0,B.jsx)(`small`,{"data-tool-model":`1`,children:`⚠ 会调用模型`})]}),(0,B.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export":e.id,title:`导出${e.name},得到一个可以发给别人导入的文件`,"aria-label":`导出${e.name}`,onClick:()=>te(e),children:`导出`})]},e.id)})}),D&&(0,B.jsxs)(`div`,{className:`tool-share-review`,ref:j,"data-tool-export-name":`1`,children:[(0,B.jsxs)(`h3`,{className:`tool-share-title`,children:[`导出「`,D.tool.name,`」`]}),(0,B.jsxs)(`label`,{className:`tool-hint`,children:[`文件名(发给别人的就是这个文件)`,(0,B.jsx)(`input`,{className:`tool-input`,value:D.name,"aria-label":`导出文件名`,"data-tool-export-input":`1`,onChange:e=>O({...D,name:e.target.value})})]}),k&&(0,B.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-export-name-error":`1`,children:k}),(0,B.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export-cancel":`1`,onClick:()=>{O(void 0),A(void 0)},children:`取消`}),(0,B.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-export-confirm":`1`,onClick:()=>void ne(D.tool,D.name),children:`导出`})]})]}),h&&(0,B.jsx)(`p`,{className:`tool-hint`,"data-tool-share-notice":`1`,children:h}),p&&(0,B.jsx)(`p`,{className:`tool-error`,"data-tool-share-error":`1`,role:`alert`,children:p}),(0,B.jsx)(`div`,{className:`rail-section-head`,children:(0,B.jsx)(`h2`,{className:`rail-section-title`,children:`从文件导入`})}),(0,B.jsxs)(`p`,{className:`tool-hint`,children:[`收到别人分享的工具文件(`,(0,B.jsx)(`code`,{children:fE}),`)?导入后它出现在工具栏里,所有工作区都能用。`,(0,B.jsx)(`b`,{children:`导入前会先给你看这个包里有什么。`})]}),(0,B.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-pick":`1`,onClick:()=>ee.current?.click(),children:`选择文件…`}),(0,B.jsx)(`input`,{ref:ee,type:`file`,accept:`.json,application/json`,style:{display:`none`},"data-tool-import-input":`1`,onChange:e=>void re(e)})]})})]})}),document.body)}function RD({pending:e,slugDraft:t,slugError:n,preview:r,busy:i,onSlugChange:a,onPreviewChange:o,onCancel:s,onConfirm:c}){let l=e.bundle,u=l.files.reduce((e,t)=>e+new TextEncoder().encode(t.content).length,0),d=SE(l),f=xE(l),p=l.files.find(e=>e.path===r)??l.files[0];return(0,B.jsxs)(`div`,{className:`tool-share-review`,"data-tool-import-review":`1`,children:[(0,B.jsx)(`h3`,{className:`tool-share-title`,"data-tool-import-name":`1`,children:l.name}),l.description&&(0,B.jsx)(`p`,{className:`tool-hint`,"data-tool-import-desc":`1`,children:l.description}),e.unnamedFormat&&(0,B.jsx)(`p`,{className:`tool-import-note`,"data-tool-import-unbranded":`1`,children:`这个文件没有 Super Pi 的工具标记,已按内容形状读取——粘出来的 tool_register 参数也认。`}),(0,B.jsxs)(`p`,{className:`tool-hint`,"data-tool-import-files":`1`,children:[l.files.length,` 个文件 · 共 `,wE(u)]}),(0,B.jsx)(`p`,{className:`tool-hint`,"data-tool-import-paths":`1`,children:l.files.map(e=>e.path).join(` · `)}),l.script&&(0,B.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-script":l.script.path,children:[(0,B.jsxs)(`b`,{children:[`⚠ 含 Python 脚本 `,l.script.path]}),(0,B.jsx)(`br`,{}),`导入后运行这个工具时,这段代码会在本机上执行,权限和你自己的 Python 一样(能读你的文件、能联网)。 可以先展开下面的文件列表把它读完。`]}),(0,B.jsxs)(`p`,{className:d.tone===`warn`?`tool-import-warn`:`tool-import-note`,"data-tool-import-env":d.tone,children:[(0,B.jsxs)(`b`,{children:[d.tone===`warn`?`⚠ `:`✓ `,d.text]}),l.environment?.fingerprint?.python&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`br`,{}),`导出方环境:Python `,l.environment.fingerprint.python,` / `,l.environment.fingerprint.platform,`。版本对不上时会标出来,但不会拦住你运行。`]})]}),f&&(0,B.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-model":`1`,children:[(0,B.jsx)(`b`,{children:`⚠ 这个工具可以调用模型`}),(0,B.jsx)(`br`,{}),f.text,`。模型由 Super Pi 通过 Pi 调用(凭据和模型选择都在 Super Pi 这边),工具只拿到文字。`]}),(0,B.jsxs)(`details`,{className:`tool-import-files`,"data-tool-import-filebox":l.files.length,children:[(0,B.jsxs)(`summary`,{children:[`查看文件(`,l.files.length,`)`]}),(0,B.jsx)(`div`,{className:`tool-share-tabs`,children:l.files.map(e=>(0,B.jsx)(`button`,{type:`button`,className:`tool-share-tab`,"aria-pressed":e.path===p?.path,"data-tool-import-file":e.path,onClick:()=>o(e.path),children:e.path},e.path))}),(0,B.jsx)(`pre`,{className:`tool-import-code`,"data-tool-import-code":p?.path,children:p?.content??``})]}),(0,B.jsxs)(`label`,{className:`tool-hint`,"data-tool-import-slug":`1`,children:[`导入后的 slug(工具的短名字,也是它在磁盘上的目录名)`,(0,B.jsx)(`input`,{className:`tool-input`,value:t,"aria-label":`导入后的 slug`,onChange:e=>a(e.target.value)})]}),n&&(0,B.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-import-slug-error":`1`,children:n}),(0,B.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-import-cancel":`1`,onClick:s,children:`取消`}),(0,B.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-confirm":`1`,disabled:i,onClick:c,children:i?`导入中…`:`导入`})]})]})}function zD(e){let t=e.replace(/^[./]+/,``).slice(0,30).trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(e))return t||e.slice(0,30);try{return new URL(e,typeof window>`u`?`http://localhost`:window.location.href).hostname||t||e.slice(0,30)}catch{return e.slice(0,30)}}function BD({tool:e,onClose:t}){return(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,la.createPortal)((0,B.jsx)(`div`,{className:`tool-overlay`,"data-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,B.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-dialog-title`,"data-tool-dialog":e.id,children:[(0,B.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,B.jsxs)(`h2`,{className:`tool-dialog-title`,id:`tool-dialog-title`,children:[(0,B.jsx)(`span`,{className:`tool-dialog-glyph`,"aria-hidden":`true`,children:e.glyph}),e.name]}),(0,B.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭${e.name}`,onClick:t,children:`✕`})]}),(0,B.jsxs)(`div`,{className:`tool-dialog-body`,children:[e.kind===`calculator`&&(0,B.jsx)(HD,{}),e.kind===`timestamp`&&(0,B.jsx)(UD,{}),e.kind===`link`&&(0,B.jsx)(WD,{tool:e})]})]})}),document.body)}function VD({image:e,onClose:t}){return(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,la.createPortal)((0,B.jsx)(`div`,{className:`lightbox-overlay`,"data-lightbox-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,B.jsxs)(`div`,{className:`lightbox-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`lightbox-title`,"data-lightbox-dialog":`1`,children:[(0,B.jsxs)(`div`,{className:`lightbox-head`,children:[(0,B.jsx)(`h2`,{className:`lightbox-title`,id:`lightbox-title`,children:e.name||`图片大图`}),(0,B.jsx)(`button`,{type:`button`,className:`lightbox-close`,"data-lightbox-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭大图`,onClick:t,children:`✕`})]}),(0,B.jsx)(`div`,{className:`lightbox-body`,children:(0,B.jsx)(`img`,{src:e.url,alt:e.name||`图片大图`,className:`lightbox-image`})})]})}),document.body)}function HD(){let[e,t]=(0,z.useState)(`12 * (3 + 4)`),n=N_(e),r=e=>{t(t=>t+e)};return(0,B.jsxs)(`div`,{className:`tool-calc`,"data-tool-calc":`1`,children:[(0,B.jsx)(`input`,{className:`tool-input tool-calc-input`,"data-calc-input":`1`,value:e,maxLength:200,"aria-label":`算式`,spellCheck:!1,autoComplete:`off`,placeholder:`例如 (12 + 8) / 4`,onChange:e=>{t(e.target.value)},onKeyDown:e=>{e.key===`Enter`&&e.preventDefault()}}),(0,B.jsx)(`div`,{className:`tool-calc-keys`,"data-calc-keys":`1`,children:[[`7`,`7`],[`8`,`8`],[`9`,`9`],[`÷`,`/`],[`(`,`(`],[`)`,`)`],[`4`,`4`],[`5`,`5`],[`6`,`6`],[`×`,`*`],[`^`,`^`],[`%`,`%`],[`1`,`1`],[`2`,`2`],[`3`,`3`],[`-`,`-`],[`←`,`back`],[`C`,`clear`],[`0`,`0`],[`.`,`.`],[`+`,`+`]].map(([e,n])=>(0,B.jsx)(`button`,{type:`button`,className:`tool-calc-key`,"data-calc-key":n,"aria-label":e===`C`?`清空`:e===`←`?`退格`:`输入 ${e}`,onClick:()=>{n===`clear`?t(``):n===`back`?t(e=>e.slice(0,-1)):r(n)},children:e},e))}),n.ok?(0,B.jsx)(`p`,{className:`tool-calc-result`,"data-calc-result":`1`,"data-calc-value":String(n.value),children:P_(n.value)}):(0,B.jsx)(`p`,{className:`tool-calc-error`,"data-calc-error":`1`,role:`alert`,children:n.reason})]})}function UD(){let[e,t]=(0,z.useState)(``),n=F_(e),r=n.ok?L_(n.ms):null;return(0,B.jsxs)(`div`,{className:`tool-stamp`,"data-tool-stamp":`1`,children:[(0,B.jsx)(`input`,{className:`tool-input`,"data-stamp-input":`1`,value:e,maxLength:64,spellCheck:!1,"aria-label":`时间戳或日期`,placeholder:`1757000000 或 2026-10-08T09:00:00`,onChange:e=>t(e.target.value)}),r?(0,B.jsxs)(`dl`,{className:`tool-stamp-out`,"data-stamp-result":`1`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`本地时间`}),(0,B.jsx)(`dd`,{"data-stamp-local":`1`,children:r.local})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`ISO(UTC)`}),(0,B.jsx)(`dd`,{"data-stamp-iso":`1`,children:r.iso})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`秒`}),(0,B.jsx)(`dd`,{"data-stamp-seconds":`1`,children:r.seconds})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`毫秒`}),(0,B.jsx)(`dd`,{"data-stamp-ms":`1`,children:r.milliseconds})]})]}):(0,B.jsx)(`p`,{className:`tool-stamp-error`,"data-stamp-error":`1`,role:`alert`,children:n.ok?`这个日期无法显示。`:n.reason})]})}function WD({tool:e}){let[t,n]=(0,z.useState)(!1),r=async()=>{let e=await HE(`请为 Super Pi 开发一个全局右侧栏工具并自动挂载。不要启动独立 HTTP 服务器。通过内置 tool_register 提交完整的 HTML/JS/CSS 文件;工具将被 Super Pi 保存并在所有 workspace 可用。如需计算,注册一个 Python 脚本(不接受 shell 命令),参数经 JSON stdin 传入,stdout 只输出 JSON 结果。在页面里加载 ./super-pi-tool.js,使用 SuperPiTool.run(params)、wait(runId)、get(runId) 和 cancel(runId) 执行、等待、查看和取消任务。它们会自动绑定当前工具;不要调用 /api/exec,也不要猜测 toolId。`);n(e),window.setTimeout(()=>n(!1),1800)};return(0,B.jsxs)(`div`,{className:`tool-link`,"data-tool-link":e.id,children:[(0,B.jsx)(`p`,{className:`tool-hint`,children:`这是旧版外部网页链接;新工具由 Super Pi 统一托管,并可选绑定受控 Python 脚本。`}),(0,B.jsx)(`code`,{className:`tool-link-url`,"data-tool-link-url":e.id,children:e.url}),(0,B.jsxs)(`div`,{className:`tool-link-actions`,children:[(0,B.jsx)(`a`,{className:`tool-link-open`,"data-tool-link-open":e.id,href:e.url,target:`_blank`,rel:`noopener noreferrer`,title:e.url,children:`在新标签页打开 ↗`}),(0,B.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-copy-prompt":e.id,onClick:()=>void r(),children:t?`已复制`:`复制开发 Prompt`})]}),/^https?:\/\//i.test(e.url??``)&&(0,B.jsx)(`iframe`,{className:`tool-link-frame`,"data-tool-frame":e.id,src:e.url,title:e.name,sandbox:`allow-forms allow-modals allow-pointer-lock allow-popups allow-same-origin allow-scripts`,referrerPolicy:`no-referrer`})]})}var GD=`(max-width: 1100px)`,KD=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function qD({tool:e,onClose:t}){return(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,la.createPortal)((0,B.jsx)(`div`,{className:`tool-overlay`,"data-mounted-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,B.jsxs)(`div`,{className:`tool-dialog`,"data-mounted-tool-dialog":e.id,role:`dialog`,"aria-modal":`true`,children:[(0,B.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,B.jsxs)(`h2`,{className:`tool-dialog-title`,children:[`🧩 `,e.name]}),(0,B.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,onClick:t,children:`✕`})]}),(0,B.jsx)(`div`,{className:`tool-dialog-body`,children:(0,B.jsx)(`iframe`,{className:`tool-link-frame`,src:`/tools/${encodeURIComponent(e.id)}/`,title:e.name,sandbox:`allow-forms allow-modals allow-popups allow-scripts`,referrerPolicy:`no-referrer`})})]})}),document.body)}function JD(e,t,n){let r=Math.max(0,Math.round(n)-480),i=KD(520,180,Math.max(180,r-240)),a=KD(Math.round(e),180,i),o=KD(640,240,Math.max(240,r-a));return{sidebar:a,rail:KD(Math.round(t),240,o),sidebarMin:180,sidebarMax:i,railMin:240,railMax:o,sumCap:r}}var YD=`super-pi.rail-widths.v1`,XD=`super-pi.reader-state.v1`,ZD=32,QD=48,$D=e=>{e.dataset.programmaticScroll=`true`,window.setTimeout(()=>{delete e.dataset.programmaticScroll},0)};function eO(){try{if(typeof window>`u`)return{conversations:{}};let e=JSON.parse(window.localStorage.getItem(`super-pi.reader-state.v1`)??`null`);if(!e||typeof e!=`object`)return{conversations:{}};let t={};if(e.conversations&&typeof e.conversations==`object`)for(let[n,r]of Object.entries(e.conversations)){let e=r;typeof e.followTail==`boolean`&&(t[n]={followTail:e.followTail,scrollTop:Number.isFinite(e.scrollTop)?Math.max(0,Number(e.scrollTop)):0,...typeof e.anchorKey==`string`?{anchorKey:e.anchorKey}:{},...Number.isFinite(e.anchorOffset)?{anchorOffset:Number(e.anchorOffset)}:{}})}let n={};if(e.readAt&&typeof e.readAt==`object`)for(let[t,r]of Object.entries(e.readAt))typeof r==`string`&&(n[t]=r);return{activeId:typeof e.activeId==`string`?e.activeId:void 0,workspaceId:typeof e.workspaceId==`string`?e.workspaceId:void 0,conversations:t,readAt:n}}catch{return{conversations:{}}}}function tO(e){try{typeof window<`u`&&window.localStorage.setItem(XD,JSON.stringify(e))}catch{}}var nO=`super-pi.session-tabs.v1`;function rO(){try{if(typeof window>`u`)return{ids:[]};let e=JSON.parse(window.sessionStorage.getItem(`super-pi.session-tabs.v1`)??`null`);if(!e||typeof e!=`object`)return{ids:[]};let t=e,n=Array.isArray(t.ids)?[...new Set(t.ids.filter(e=>typeof e==`string`))]:[];return{ids:n,activeId:typeof t.activeId==`string`&&n.includes(t.activeId)?t.activeId:void 0}}catch{return{ids:[]}}}function iO(e,t){try{typeof window<`u`&&window.sessionStorage.setItem(nO,JSON.stringify({ids:e,...t&&e.includes(t)?{activeId:t}:{}}))}catch{}}function aO(){try{if(typeof window>`u`)return{};let e=window.localStorage.getItem(YD);if(e===null)return{};let t=JSON.parse(e),n=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.round(e):void 0;return{sidebar:n(t.sidebar),rail:n(t.rail)}}catch{return{}}}function oO(e){try{if(typeof window>`u`)return;window.localStorage.setItem(YD,JSON.stringify(e))}catch{}}function sO({side:e,width:t,min:n,max:r,label:i,onWidth:a}){let[o,s]=(0,z.useState)(!1),c=e=>e.shiftKey?64:16;return(0,B.jsx)(`div`,{className:`rail-resizer rail-resizer-${e}${o?` rail-resizer-dragging`:``}`,"data-rail-resizer":e,"data-rail-resizer-dragging":o?`true`:`false`,"data-rail-resizer-width":t,role:`separator`,"aria-orientation":`vertical`,"aria-label":i,"aria-valuenow":t,"aria-valuemin":n,"aria-valuemax":r,tabIndex:0,onMouseDown:i=>{i.preventDefault(),i.currentTarget.focus();let o=i.clientX,c=t;s(!0);let l=document.body,u=l.style.cursor,d=l.style.userSelect;l.style.cursor=`col-resize`,l.style.userSelect=`none`;let f=t=>{let i=e===`left`?t.clientX-o:o-t.clientX;a(KD(c+i,n,r))},p=()=>{l.style.cursor=u,l.style.userSelect=d,s(!1),window.removeEventListener(`mousemove`,f),window.removeEventListener(`mouseup`,p)};window.addEventListener(`mousemove`,f),window.addEventListener(`mouseup`,p)},onKeyDown:i=>{let o=c(i);i.key===`ArrowLeft`?(i.preventDefault(),a(KD(e===`left`?t-o:t+o,n,r))):i.key===`ArrowRight`?(i.preventDefault(),a(KD(e===`left`?t+o:t-o,n,r))):i.key===`Home`?(i.preventDefault(),a(n)):i.key===`End`&&(i.preventDefault(),a(r))}})}var cO=`super-pi.composer-height.v1`,lO=148,uO=.55,dO=()=>Math.max(lO,Math.round((typeof window>`u`?800:window.innerHeight)*uO)),fO=e=>{let t=Number.isFinite(e)?e:lO;return Math.round(Math.min(dO(),Math.max(lO,t)))},pO=()=>{try{let e=window.localStorage.getItem(cO);return e===null?lO:fO(Number(e))}catch{return lO}};function mO({height:e,onHeight:t}){let[n,r]=(0,z.useState)(!1),i=e=>e.shiftKey?64:16,a=dO();return(0,B.jsx)(`div`,{className:`composer-resize${n?` composer-resize-dragging`:``}`,"data-composer-resize":`1`,"data-composer-resize-dragging":n?`true`:`false`,"data-composer-height":e,role:`separator`,"aria-orientation":`horizontal`,"aria-label":`调整消息编辑区高度`,"aria-valuenow":e,"aria-valuemin":lO,"aria-valuemax":a,tabIndex:0,onMouseDown:n=>{n.preventDefault(),n.currentTarget.focus();let i=n.clientY,a=e;r(!0);let o=document.documentElement,s=document.body.style.userSelect;document.body.style.cursor=`ns-resize`,document.body.style.userSelect=`none`;let c=e=>{let t=fO(a+(i-e.clientY));o.style.setProperty(`--composer-height`,`${t}px`)},l=()=>{document.body.style.cursor=``,document.body.style.userSelect=s;let n=Number.parseFloat(o.style.getPropertyValue(`--composer-height`));r(!1),window.removeEventListener(`mousemove`,c),window.removeEventListener(`mouseup`,l),t(Number.isFinite(n)?n:e)};window.addEventListener(`mousemove`,c),window.addEventListener(`mouseup`,l)},onKeyDown:n=>{let r=i(n);n.key===`ArrowUp`?(n.preventDefault(),t(fO(e+r))):n.key===`ArrowDown`?(n.preventDefault(),t(fO(e-r))):n.key===`Home`?(n.preventDefault(),t(lO)):n.key===`End`?(n.preventDefault(),t(a)):n.key===`PageUp`?(n.preventDefault(),t(fO(e+96))):n.key===`PageDown`&&(n.preventDefault(),t(fO(e-96)))}})}function hO(){let[e,t]=(0,z.useState)(EE),[n,r]=(0,z.useState)([]),i=(0,z.useRef)([]),a=(0,z.useRef)(null);a.current||=eO();let o=(0,z.useRef)(null);o.current||=rO();let s=n.reduce((e,t)=>t.apply(e),e),[c,l]=(0,z.useState)(o.current.activeId??a.current.activeId),[u,d]=(0,z.useState)(!1),[f,p]=(0,z.useState)(),[m,h]=(0,z.useState)({}),[g,_]=(0,z.useState)(a.current.workspaceId),[v,y]=(0,z.useState)(o.current.ids),[b,x]=(0,z.useState)(!1),[S,C]=(0,z.useState)(!1),w=(0,z.useRef)(void 0),T=(0,z.useRef)(a.current.conversations),E=(0,z.useRef)(v);E.current=v;let D=(0,z.useRef)(a.current.readAt??{}),[O,k]=(0,z.useState)(0),A=(0,z.useRef)(null),ee=(0,z.useRef)(null),j=(0,z.useRef)(void 0),M=(0,z.useRef)(a.current.activeId),[N,te]=(0,z.useState)({followTail:!0,scrollTop:0}),ne=(0,z.useRef)(!1),re=(0,z.useRef)(new Map),ie=(0,z.useRef)(void 0),ae=(0,z.useRef)([]),oe=(0,z.useRef)(void 0),se=(0,z.useCallback)(()=>{if(oe.current!==void 0&&(cancelAnimationFrame(oe.current),oe.current=void 0),!ae.current.length)return;let e=ae.current;ae.current=[];let n=new Map;for(let t of e){let e=`${t.conversationId}\u0000${t.messageId}`,r=n.get(e)??[];r.push(t),n.set(e,r)}t(e=>({...e,conversations:e.conversations.map(e=>{let t=e.messages.map(t=>{let r=n.get(`${e.id}\u0000${t.id}`);if(!r)return t;let i={...t};for(let e of r){if(e.type===`message.delta`){i.content+=e.delta;continue}if(i.thinkingActive=e.active,!e.delta)continue;let t=e.at??i.content.length,n=[...i.thinkingBlocks??[]],r=n.at(-1);r&&r.at===t&&(e.blockIndex===void 0||e.blockIndex===n.length-1)?n[n.length-1]={...r,text:r.text+e.delta}:n.push({at:t,text:e.delta}),i={...i,thinking:(i.thinking??``)+e.delta,thinkingBlocks:n}}return i});return t.every((t,n)=>t===e.messages[n])?e:{...e,messages:t}})}))},[]),ce=(0,z.useCallback)(e=>{let t=ae.current,n=t.at(-1);n&&n.type===e.type&&n.conversationId===e.conversationId&&n.messageId===e.messageId&&(e.type!==`message.thinking`||n.type===`message.thinking`&&n.at===e.at&&n.active===e.active&&n.blockIndex===e.blockIndex)?t[t.length-1]={...e,delta:n.delta+e.delta}:t.push(e),oe.current===void 0&&(oe.current=requestAnimationFrame(se))},[se]),le=(0,z.useCallback)(e=>{ie.current=e},[]),[ue,de]=(0,z.useState)({}),[fe,pe]=(0,z.useState)(()=>{if(typeof window>`u`)return``;try{return window.localStorage.getItem(`super-pi.user-nickname`)??``}catch{return``}}),me=e=>{let t=e.slice(0,24);pe(t);try{window.localStorage.setItem(`super-pi.user-nickname`,t)}catch{}},he=fe.trim()||`你`,[ge,P]=(0,z.useState)([]),[_e,ve]=(0,z.useState)([]),[ye,be]=(0,z.useState)(new Map),[xe,Se]=(0,z.useState)(new Map),[Ce,we]=(0,z.useState)(),[Te,Ee]=(0,z.useState)(),[De,Oe]=(0,z.useState)(),[ke,Ae]=(0,z.useState)([]),[je,Me]=(0,z.useState)([]),[Ne,Pe]=(0,z.useState)(),[Fe,Ie]=(0,z.useState)(),[Le,Re]=(0,z.useState)(),[ze,Be]=(0,z.useState)(`idle`),[Ve,He]=(0,z.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1100px)`).matches),[Ue,We]=(0,z.useState)(`chat`),[Ge,Ke]=(0,z.useState)(()=>typeof window>`u`?1440:window.innerWidth);(0,z.useEffect)(()=>{let e=()=>Ke(window.innerWidth);return window.addEventListener(`resize`,e),e(),()=>window.removeEventListener(`resize`,e)},[]);let[qe,Je]=(0,z.useState)(aO),Ye=JD(qe.sidebar??270,qe.rail??320,Ge);(0,z.useEffect)(()=>{oO({sidebar:Ye.sidebar,rail:Ye.rail})},[Ye.sidebar,Ye.rail]);let Xe=e=>Je(t=>({...t,sidebar:e})),Ze=e=>Je(t=>({...t,rail:e})),[Qe,$e]=(0,z.useState)(null);(0,z.useEffect)(()=>{$e(pO())},[]),(0,z.useEffect)(()=>{Qe!==null&&document.documentElement.style.setProperty(`--composer-height`,`${Qe}px`)},[Qe]);let et=e=>{let t=fO(e);$e(t);try{window.localStorage.setItem(cO,String(t))}catch{}};(0,z.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(GD),t=e=>{e.matches&&He(!0)};return e.addEventListener(`change`,t),e.matches&&He(!0),()=>e.removeEventListener(`change`,t)},[]);let[tt,nt]=(0,z.useState)({}),[rt,it]=(0,z.useState)({}),[at,ot]=(0,z.useState)({}),[st,ct]=(0,z.useState)(),[lt,ut]=(0,z.useState)(),[dt,ft]=(0,z.useState)(),pt=(0,z.useRef)(new Map),[mt,ht]=(0,z.useState)({}),gt=(0,z.useRef)(new Set),[_t,vt]=(0,z.useState)([]),[yt,bt]=(0,z.useState)([]),[xt,St]=(0,z.useState)(),[Ct,wt]=(0,z.useState)(!1),Tt=(0,z.useRef)(null),Et=(0,z.useRef)(!1),Dt=(0,z.useRef)(0),Ot=(0,z.useRef)([]),kt=(0,z.useRef)(void 0),At=(0,z.useRef)(!1),jt=(0,z.useRef)(new Set),Mt=(0,z.useRef)(new Map),Nt=(0,z.useRef)(new Map),[Pt,Ft]=(0,z.useState)(()=>Date.now());(0,z.useEffect)(()=>{let e=window.setInterval(()=>Ft(Date.now()),3e4);return()=>window.clearInterval(e)},[]);let It=(0,z.useMemo)(()=>s.conversations.filter(e=>!e.archivedAt),[s.conversations]),F=(0,z.useMemo)(()=>It.find(e=>e.id===c)??It.find(e=>e.workspaceId===g)??(g&&s.workspaces.some(e=>e.id===g)?void 0:It[0]),[c,It,g,s.workspaces]);(0,z.useEffect)(()=>{p(void 0)},[c,g]);let Lt=(0,z.useMemo)(()=>s.workspaces.find(e=>e.id===g)??s.workspaces[0],[s.workspaces,g]),Rt=(0,z.useRef)(g);Rt.current=g,(0,z.useEffect)(()=>{F&&_(F.workspaceId)},[F?.id]),(0,z.useEffect)(()=>{kt.current=c},[c]),(0,z.useEffect)(()=>{j.current=F?.id},[F?.id]),(0,z.useEffect)(()=>{let e=F?.id;if(!e)return;let t=s.conversations.find(t=>t.id===e);if(!t)return;let n=D.current[e];D.current[e]=t.updatedAt,n!==t.updatedAt&&k(e=>e+1),tO({activeId:kt.current,workspaceId:F?.workspaceId??g,conversations:T.current,readAt:D.current})},[F?.id,s.conversations]),(0,z.useEffect)(()=>{u&&c&&tO({activeId:c,workspaceId:F?.workspaceId??g,conversations:T.current})},[c,F?.workspaceId,u,g]),(0,z.useEffect)(()=>{let e=A.current;if(!e||!F?.id)return;let t=F.id;ne.current=!1;let n=T.current[t]??{followTail:!0,scrollTop:0};te(n),requestAnimationFrame(()=>{if(A.current===e){if(n.followTail)$D(e),e.scrollTop=e.scrollHeight;else{let t=n.anchorKey?e.querySelector(`[data-transcript-key="${CSS.escape(n.anchorKey)}"]`):null;e.scrollTop=t?Math.max(0,e.scrollTop+t.getBoundingClientRect().top-(n.anchorOffset??0)-e.getBoundingClientRect().top):n.scrollTop}}}),M.current=void 0},[F?.id]);let zt=(0,z.useCallback)((e,t=!1,n=!1)=>{let r=j.current;if(!r)return;let i=e.scrollHeight-e.clientHeight-e.scrollTop,a=T.current[r]??{followTail:!0,scrollTop:0},o=t?!1:n?!0:a.followTail?i<=QD:i<=ZD,s,c;if(!o){let t=e.getBoundingClientRect().top,n=[...e.querySelectorAll(`[data-transcript-key]`)].find(e=>e.getBoundingClientRect().bottom>t);s=n?.dataset.transcriptKey,c=n?n.getBoundingClientRect().top-t:void 0}let l={followTail:o,scrollTop:e.scrollTop,...s?{anchorKey:s,anchorOffset:c}:{}};ne.current=!o,T.current[r]=l,te(l),tO({activeId:r,workspaceId:Rt.current,conversations:T.current})},[]),Bt=mt[F?.id??``]??{text:``,images:[],attachments:[],uploading:0},Vt=Bt.text,Ht=Bt.images,Ut=Bt.attachments,Wt=Bt.uploading,Gt=(e,t)=>ht(n=>({...n,[e]:t(n[e]??{text:``,images:[],attachments:[],uploading:0})})),Kt=e=>Gt(F?.id??``,t=>({...t,text:e})),qt=e=>Gt(F?.id??``,t=>({...t,attachments:t.attachments.some(t=>t.kind===e.kind&&t.id===e.id)?t.attachments:[...t.attachments,e]})),Jt=(e,t)=>Gt(F?.id??``,n=>({...n,attachments:n.attachments.filter(n=>n.kind!==e||n.id!==t)})),[Yt,Xt]=(0,z.useState)({visible:!1,query:``,rect:null}),Zt=e=>Gt(F?.id??``,t=>({...t,images:typeof e==`function`?e(t.images):e})),Qt=v.length>0?v:F?[F.id]:[],$t=(0,z.useMemo)(()=>Qt.map(e=>It.find(t=>t.id===e)).filter(e=>e!==void 0),[Qt,It]);(0,z.useEffect)(()=>{if(!b)return;let e=new Set(It.map(e=>e.id));y(t=>{let n=t.filter(t=>e.has(t));return n.length===t.length?t:n})},[b,It]),(0,z.useEffect)(()=>{iO(v,c)},[c,v]);let en=(0,z.useCallback)(e=>{l(e);let t=It.find(t=>t.id===e)?.workspaceId;t&&_(t),yn(`session`),y(t=>t.includes(e)?t:t.length>0?[...t,e]:[...F?.id&&F.id!==e?[F.id]:[],e])},[F]),tn=(0,z.useCallback)(e=>{let t=v.indexOf(e);if(t<0)return;let n=v.filter(t=>t!==e);if(y(n),F?.id!==e)return;let r=n[Math.min(t,n.length-1)];r&&l(r)},[v,F]),I=kg(g),nn=(0,z.useRef)(I.setChangedFor),rn=(0,z.useRef)(I.setIndex),an=(0,z.useRef)(I.setIndexStatus);(0,z.useEffect)(()=>{nn.current=I.setChangedFor},[I.setChangedFor]),(0,z.useEffect)(()=>{rn.current=I.setIndex},[I.setIndex]),(0,z.useEffect)(()=>{an.current=I.setIndexStatus},[I.setIndexStatus]);let[on,sn]=(0,z.useState)(SD[0].id),[cn,ln]=(0,z.useState)({}),un=(F?.id?cn[F.id]:void 0)??on,dn=(0,z.useCallback)(e=>{sn(e),F?.id&&ln(t=>({...t,[F.id]:e}))},[F?.id]),[fn,pn]=(0,z.useState)(!1),[mn,hn]=(0,z.useState)(!1),[gn,_n]=(0,z.useState)(),[vn,yn]=(0,z.useState)(`session`),[bn,xn]=(0,z.useState)();(0,z.useEffect)(()=>{vn===`file`&&!I.active&&yn(`session`)},[vn,I.active]),(0,z.useEffect)(()=>{vn===`diff`&&!bn&&yn(`session`)},[vn,bn]),(0,z.useEffect)(()=>{I.restoredActive&&yn(`file`)},[I.restoredActive]);let Sn=(0,z.useCallback)(e=>{xn(e),yn(`diff`),sn(`files`)},[]),[Cn,wn]=(0,z.useState)({diff:null,loading:!1,error:``}),[Tn,En]=(0,z.useState)(`server`);(0,z.useEffect)(()=>{if(vn!==`diff`||!bn||!g)return;let e=!0;return wn({diff:null,loading:!0,error:``}),fetch(`/api/files/diff?workspaceId=${encodeURIComponent(g)}&path=${encodeURIComponent(bn)}`).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error??`HTTP ${e.status}`);return t}).then(t=>{e&&wn({diff:t,loading:!1,error:``})}).catch(t=>{e&&wn({diff:null,loading:!1,error:t instanceof Error?t.message:`读取差异失败`})}),()=>{e=!1}},[vn,bn,g]);let Dn=(0,z.useMemo)(()=>{if(!bn)return;let e=I.open.find(e=>e.path===bn);return e&&e.dirty?e.content:void 0},[bn,I.open]),On=(0,z.useCallback)(e=>{I.setActivePath(e),yn(`file`),sn(`files`)},[I.setActivePath]),kn=(0,z.useCallback)(async(e,t)=>{_n(t?{workspaceId:g,path:e.path,line:t,request:Date.now()}:void 0),await I.openFile(e),yn(`file`)},[I.openFile,g]);(0,z.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&e.shiftKey&&e.key.toLowerCase()===`f`?(e.preventDefault(),hn(!0)):(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`p`&&(e.preventDefault(),pn(!0))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let An=(0,z.useMemo)(()=>$t.map(e=>({id:`session:${e.id}`,rawId:e.id,kind:`session`,label:e.title,title:e.title,closable:$t.length>1||I.open.length>0,badge:(0,B.jsx)(ED,{state:TD(e,ge.some(t=>t.conversationId===e.id),D.current[e.id])})})),[$t,I.open.length,ge,s.conversations,O]),jn=(0,z.useMemo)(()=>I.open.map(e=>({id:`file:${e.path}`,rawId:e.path,kind:`file`,label:e.name,title:e.path,closable:!0,badge:e.dirty?(0,B.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[I.open]),Mn=(0,z.useMemo)(()=>[...An,...jn],[An,jn]),Nn=vn===`file`&&I.activePath?`file:${I.activePath}`:F?.id?`session:${F.id}`:void 0,Pn=(0,z.useCallback)(e=>{if(e.startsWith(`file:`)){let t=e.slice(5);On(t)}else if(e.startsWith(`session:`)){let t=e.slice(8);en(t)}},[On,en]),Fn=(0,z.useCallback)(e=>{if(e.startsWith(`file:`)){let t=e.slice(5);I.closeFile(t),I.activePath===t&&I.open.length<=1&&yn(`session`)}else if(e.startsWith(`session:`)){let t=e.slice(8);tn(t)}},[I,tn]),In=I.active,Ln=F?.id;(0,z.useEffect)(()=>{Ln&&!Ln.startsWith(`pending:`)&&Hn({type:`conversation.select`,conversationId:Ln})},[Ln]);let L=(e,t=`info`)=>{if(!e)return;let n=++Dt.current;ve(r=>[...r,{key:n,text:e,kind:t}]),Ot.current.push(window.setTimeout(()=>ve(e=>e.filter(e=>e.key!==n)),7e3))},Rn=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);if(n<0)return[t,...e];let r=[...e];return r[n]=t,r},zn=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);if(n<0)return[t,...e];let r=[...e];return r[n]=t,r},Bn=(e,t)=>{if(t.blocking)P(n=>[...n.filter(n=>n.conversationId!==e||n.request.requestId!==t.requestId),{conversationId:e,request:t}]);else if(t.method===`notify`)L(t.message||t.title,t.notifyType??`info`);else if(t.method===`setStatus`){let e=t.statusKey??``;be(n=>{let r=new Map(n);return t.statusText===void 0?r.delete(e):r.set(e,t.statusText),r})}else if(t.method===`setWidget`){let e=t.widgetKey??``;Se(n=>{let r=new Map(n);return t.widgetLines===void 0?r.delete(e):r.set(e,{lines:t.widgetLines,placement:t.widgetPlacement??`aboveEditor`}),r})}else t.method===`setTitle`?we(t.title):t.method===`set_editor_text`&&e===kt.current&&Kt(t.text??``)},Vn=(e,t,n)=>{P(n=>n.filter(n=>n.conversationId!==e||n.request.requestId!==t));let r=$E[n];r&&L(r,`warning`)};(0,z.useEffect)(()=>{let e=!1,n=0,o,s=()=>{if(e)return;let c=location.protocol===`https:`?`wss`:`ws`,u=new WebSocket(`${c}://${location.host}/ws`);w.current=u,u.onopen=()=>{if(!e){n=0,d(!0),u.send(JSON.stringify({type:`stream.configure`,coalesce:!0})),u.send(JSON.stringify({type:`catalog.fetch`,conversationId:kt.current})),u.send(JSON.stringify({type:`catalog.fetchAll`})),u.send(JSON.stringify({type:`agent.catalog.fetch`})),u.send(JSON.stringify({type:`subagent.catalog.fetch`}));for(let e of i.current)e.retry&&e.command&&u.send(JSON.stringify({...e.command,operationRequestId:e.id}))}},u.onclose=()=>{if(e)return;At.current=!1;let t=dE(i.current);for(let e of t.failed)e.onFailure?.();i.current=t.retry,r(t.retry),d(!1),o=window.setTimeout(s,Math.min(VE,BE*2**n++))},u.onmessage=({data:n})=>{if(e)return;let o=JSON.parse(n);if(o.type!==`message.delta`&&o.type!==`message.thinking`&&se(),o.type===`exec.output`){let e=re.current.get(o.sessionId)??``;re.current.set(o.sessionId,(e+o.data).slice(-512e3)),re.current.size>64&&re.current.delete(re.current.keys().next().value),window.dispatchEvent(new CustomEvent(`super-pi-exec-output`,{detail:o}))}else if(o.type===`exec.exit`)re.current.delete(o.sessionId);else if(o.type.startsWith(`terminal.`))ie.current?.(o);else if(o.type===`conversation.autoRename.result`){let e=pt.current.get(o.conversationId);e&&(pt.current.delete(o.conversationId),o.ok?e.resolve(o.title):e.reject(Error(o.error)))}else if(o.type===`message.thinking`)ce(o);else if(o.type===`state`){se(),At.current=!1;let e=kt.current,n=!!(e&&jt.current.has(e)),s=!(!e||o.state.conversations.some(t=>t.id===e)),c=n&&s&&e&&Mt.current.has(e)?{...o.state,conversations:[Mt.current.get(e),...o.state.conversations]}:o.state;e&&!s&&(jt.current.delete(e),Mt.current.delete(e)),i.current=i.current.filter(e=>!e.accepted?.(c)),r(i.current),t(c),x(!0),d(!0),l(e=>{let t=c.conversations.filter(e=>!e.archivedAt),n=a.current?.activeId,r=!!(e&&t.some(t=>t.id===e)),o=!!(e&&i.current.some(t=>t.temporaryId===e));return r||o?e:n&&t.some(e=>e.id===n)?n:t.find(e=>e.workspaceId===Rt.current)?.id}),_(e=>{let t=a.current?.workspaceId;return t&&c.workspaces.some(e=>e.id===t)?t:e&&(c.workspaces.some(t=>t.id===e)||i.current.some(t=>t.temporaryId===e))?e:c.workspaces[0]?.id})}else if(o.type===`message.delta`)ce(o);else if(o.type===`message.revert.result`)ci(void 0),ct(void 0),o.ok||p(o.message);else if(o.type===`operation.result`){let e=i.current.find(e=>e.id===o.requestId);if(i.current=i.current.filter(e=>e.id!==o.requestId),r(i.current),e?.temporaryId){let t=e.temporaryId;if(o.ok&&o.entityId){let e=Nt.current.get(t);e&&Mt.current.set(o.entityId,{...e,id:o.entityId}),jt.current.add(o.entityId)}l(n=>n===t?o.ok?o.entityId:e.previousActiveId:n),y(e=>e.flatMap(e=>e===t?o.ok&&o.entityId?[o.entityId]:[]:[e])),_(e=>e===t?o.ok?o.entityId:void 0:e)}o.ok||(e?.onFailure?.(o.message),p(o.message??`操作失败`))}else o.type===`tools.updated`?window.dispatchEvent(new Event(`super-pi-tools-updated`)):o.type===`files.changed`?nn.current(o.workspaceId,o.changes,o.dropped):o.type===`files.index`?o.workspaceId===Rt.current&&(rn.current(o.changed,o.removed),an.current(o.complete,o.skipped)):o.type===`error`?(p(o.message),At.current&&(At.current=!1,L(`重命名失败:${o.message}`,`error`))):o.type===`extension.ui`?Bn(o.conversationId,o.request):o.type===`extension.ui.closed`?Vn(o.conversationId,o.requestId,o.reason):o.type===`model.catalog`?(!o.conversationId||o.conversationId===kt.current)&&Ee(o.catalog):o.type===`model.catalog.all`?Oe(o.catalog):o.type===`providers.list`?(Ae(o.providers),Me(o.apis)):o.type===`agent.catalog`?Pe(o.catalog):o.type===`subagent.catalog`?Ie(o.catalog):o.type===`server.version`?(Re(o.version),o.version.needsRestart&&L(`检测到 Super Pi 代码已更新(v${o.version.runningVersion} → v${o.version.diskVersion}),请执行 /super_pi restart 重启服务生效`,`warning`)):o.type===`subagent.event`?t(e=>({...e,subagentRuns:Rn(e.subagentRuns??[],o.run)})):o.type===`workflow.event`?t(e=>({...e,workflows:zn(e.workflows??[],o.workflow)})):o.type===`message.tools`?t(e=>({...e,conversations:e.conversations.map(e=>e.id===o.conversationId?{...e,messages:e.messages.map(e=>e.id===o.messageId?{...e,toolCalls:o.toolCalls}:e)}:e)})):o.type===`conversation.fork.result`&&(hi(e=>e===o.conversationId?void 0:e),L(o.ok?`已从「${o.title}」分叉出新会话,放在侧边栏最上面;没有切换过去。${o.messagesCopied?`复制了 ${o.messagesCopied} 条消息。`:`原会话还没有消息,只复制了会话本身。`}`:`分叉失败:${o.message}`,o.ok?`info`:`error`))}};return s(),()=>{e=!0,se(),window.clearTimeout(o);for(let e of Ot.current)window.clearTimeout(e);w.current?.close()}},[ce,se]);let Hn=(0,z.useCallback)(e=>w.current?.readyState===WebSocket.OPEN&&(w.current.send(JSON.stringify(e)),!0),[]),Un=(e,t,n,a,o,s)=>{let c=w.current?.readyState===WebSocket.OPEN,l=uE(e);if(i.current.some(e=>e.key===t)||!c&&!l)return!1;let u=__(),d={id:u,key:t,apply:n,temporaryId:a,previousActiveId:kt.current,onFailure:o,accepted:s,...l?{retry:!0,command:e}:{}};return i.current=[...i.current,d],r(i.current),c&&w.current.send(JSON.stringify({...e,operationRequestId:u})),!0},Wn=(e,t)=>n=>({...n,conversations:n.conversations.map(n=>n.id===e?{...n,...t}:n)}),Gn=(e,t)=>n=>({...n,workspaces:n.workspaces.map(n=>n.id===e?{...n,...t}:n)}),Kn=n.some(e=>e.key===`send:${F?.id}`||e.key===`configuration:${F?.id}`||e.temporaryId===F?.id||e.key===`archive:${F?.id}`),qn=(e,t,n,r,i)=>{e&&w.current?.send(JSON.stringify({type:`question.answer`,conversationId:e,messageId:t,callIndex:n,answers:r,cancelled:i}))},Jn=(e,t,n)=>Un({type:`extension.ui.answer`,conversationId:e,requestId:t,...n},`answer:${e}:${t}`,e=>e),Yn=F?.model??Te?.defaultModel,Xn=F?.thinkingLevel??Te?.defaultThinkingLevel,Zn=Te?.source===`pi`,Qn=!!Te?.models.find(e=>e.provider===Yn?.provider&&e.modelId===Yn?.modelId)?.imageInput,$n=(e,t)=>!e||!t?e:{...e,models:e.models.filter(e=>(s.modelFilterRules??[]).every(n=>{try{return!new RegExp(n.workspacePattern,`i`).test(t.name)||new RegExp(n.modelPattern,`i`).test(e.label)||new RegExp(n.modelPattern,`i`).test(`${e.provider}/${e.modelId}`)}catch{return!0}}))},er=($n(Te,s.workspaces.find(e=>e.id===F?.workspaceId))?.models??[]).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:e.detail,badge:YE(e),selected:Yn?.provider===e.provider&&Yn.modelId===e.modelId})),tr=(Te?.levels??[]).map(e=>({key:e,label:e,selected:e===Xn})),nr=e=>{if(!F)return;let[t,n]=e.split(`/`);t&&n&&Un({type:`conversation.model`,conversationId:F.id,provider:t,modelId:n},`configuration:${F.id}`,Wn(F.id,{model:Te?.models.find(e=>e.provider===t&&e.modelId===n)??{provider:t,modelId:n,label:n}}))},rr=e=>{F&&Un({type:`conversation.thinking`,conversationId:F.id,level:e},`configuration:${F.id}`,Wn(F.id,{thinkingLevel:e}))},ir=Ne?.agents.find(e=>e.id===F?.agentId),ar=[{key:bD,label:`跟随 Pi 默认`,detail:`不使用任何 agent 角色`,selected:!F?.agentId},...(Ne?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:F?.agentId===e.id}))],or=ir?.model,sr=!!(or&&F?.model&&F.model.provider===or.provider&&F.model.modelId===or.modelId);ir?.thinkingLevel&&(F?.thinkingLevel,ir.thinkingLevel);let cr=e=>{if(F){let t=Ne?.agents.find(t=>t.id===e);Un({type:`conversation.agent`,conversationId:F.id,agentId:e===bD?null:e},`configuration:${F.id}`,Wn(F.id,{agentId:t?.id,...t?.model?{model:{...t.model,label:t.model.modelId}}:{},...t?.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{}}))}},lr=ge.filter(e=>e.conversationId===F?.id),ur=(0,z.useMemo)(()=>(s.subagentRuns??[]).filter(e=>e.conversationId===F?.id),[s.subagentRuns,F?.id]),dr=(0,z.useMemo)(()=>(s.workflows??[]).filter(e=>e.conversationId===F?.id),[s.workflows,F?.id]),fr=(0,z.useMemo)(()=>new Map(dr.map(e=>[e.id,e])),[dr]),pr=(0,z.useMemo)(()=>new Map((Fe?.agents??[]).map(e=>[e.id,e.name])),[Fe]),mr=(0,z.useMemo)(()=>new Map((F?.messages??[]).map(e=>[e.id,e])),[F?.messages]),hr=(0,z.useMemo)(()=>new Map(ur.map(e=>[e.id,e])),[ur]),gr=(0,z.useMemo)(()=>{let e=new Map;for(let t of ur)t.originMessageId!==void 0&&t.originCallRow!==void 0&&e.set(`${t.originMessageId}:${t.originCallRow}`,t);return e},[ur]),_r=(0,z.useMemo)(()=>{if(!F)return[];let e=st?.conversationId===F.id?(()=>{let e=F.messages.find(e=>e.id===st.messageId);if(e)return{index:F.messages.indexOf(e),at:Date.parse(e.createdAt)||0,...st.kind===`withdraw`?{inclusive:!0}:{inclusive:!1}}})():void 0,t=[];return F.messages.forEach((n,r)=>{e&&(r>e.index||e.inclusive&&r===e.index)||n.delivery||t.push({at:Date.parse(n.createdAt)||0,seq:r,key:`m:${n.id}`})}),ur.forEach((n,r)=>{n.originMessageId&&n.originCallRow!==void 0&&F?.messages.some(e=>e.id===n.originMessageId&&e.toolCalls?.[n.originCallRow])||e&&(Date.parse(n.startedAt)||0)>e.at||t.push({at:Date.parse(n.startedAt)||0,seq:t.length+r,key:`r:${n.id}`})}),dr.forEach((n,r)=>{e&&(Date.parse(n.startedAt)||0)>e.at||t.push({at:Date.parse(n.startedAt)||0,seq:t.length+r,key:`w:${n.id}`})}),t.sort((e,t)=>e.at-t.at||e.seq-t.seq).map(e=>e.key)},[F,ur,dr,st]);(0,z.useEffect)(()=>{let e=A.current;if(!e||!F?.id)return;let t=()=>{!ne.current&&T.current[F.id]?.followTail&&($D(e),e.scrollTop=e.scrollHeight)};if(t(),typeof ResizeObserver>`u`)return;let n=new ResizeObserver(t);n.observe(e);for(let t of e.children)n.observe(t);return()=>n.disconnect()},[F?.id,F?.messages,ur,dr,_r]);let vr=e=>nt(t=>({...t,[e]:!t[e]})),yr=(e,t)=>it(n=>({...n,[`${e}:${t}`]:!n[`${e}:${t}`]})),br=(e,t)=>ot(n=>({...n,[`${e}:${t}`]:n[`${e}:${t}`]!==!1})),[xr,Sr]=(0,z.useState)({}),Cr=e=>Sr(t=>({...t,[e]:t[e]!==!0})),wr=e=>{Un({type:`subagent.stop`,runId:e},`stop:${e}`,e=>e)||L(`连接断开,无法停止子智能体,请重试`,`error`)},Tr=e=>{Un({type:`workflow.stop`,workflowId:e},`stop:${e}`,e=>e)||L(`连接断开,无法停止编排,请重试`,`error`)},Er=e=>[...xe].filter(([,t])=>t.placement===e).map(([e,t])=>{let n=t.lines;return(0,B.jsxs)(`div`,{className:`extui-widget`,"data-widget-key":e,"data-widget-lines":n.length,children:[n.slice(0,eD).map((e,t)=>(0,B.jsx)(`div`,{children:e},`${t}:${e}`)),n.length>eD&&(0,B.jsx)(`div`,{children:`… (widget truncated)`})]},e)}),Dr=(e,t)=>{let n=`pending:${__()}`,r={id:n,name:e,path:t,updatedAt:new Date().toISOString()};Un({type:`workspace.create`,name:e,path:t},`create-workspace`,e=>({...e,workspaces:[...e.workspaces,r]}),n)&&(_(n),l(void 0),C(!1))},[Or,kr]=(0,z.useState)(),Ar=(e,t)=>kr(n=>n?.kind===e&&n.id===t?n:{kind:e,id:t}),jr=()=>kr(void 0),Mr=(e,t)=>Or?.kind===e&&Or.id===t,Nr=(e,t,n)=>t.startsWith(`pending:`)?!1:Un(e===`workspace`?{type:`workspace.rename`,workspaceId:t,name:n}:{type:`conversation.rename`,conversationId:t,name:n},`rename:${t}`,e===`workspace`?Gn(t,{name:n}):Wn(t,{title:n}))?(At.current=!0,jr(),!0):(L(`连接断开,改名未保存,请重试`,`error`),!1),Pr=async e=>{if(e.startsWith(`pending:`)){L(`这个会话还在创建中,稍后再试`,`warning`);return}if(pt.current.has(e))return;L(`正在根据对话内容生成标题…`,`info`);let t=new Promise((t,n)=>{pt.current.set(e,{resolve:t,reject:n}),window.setTimeout(()=>{pt.current.delete(e)&&n(Error(`模型在 30 秒内没有返回标题`))},32e3)});if(!Hn({type:`conversation.autoRename`,conversationId:e}))pt.current.delete(e),L(`连接断开,无法生成标题`,`error`);else try{let n=await t;Nr(`conversation`,e,n),L(`已重命名为「${n}」`,`info`)}catch(e){L(`重命名失败:${e instanceof Error?e.message:String(e)}`,`error`)}},Fr=e=>{if(e.id.startsWith(`pending:`))return;let t=s.conversations.filter(t=>t.workspaceId===e.id).length;window.confirm(`删除工作区「${e.name}」?${t?`其中 ${t} 条会话将一并删除,`:``}此操作不可撤销。`)&&Un({type:`workspace.delete`,workspaceId:e.id},`delete:${e.id}`,t=>({...t,workspaces:t.workspaces.filter(t=>t.id!==e.id),conversations:t.conversations.filter(t=>t.workspaceId!==e.id)}))},[Ir,Lr]=(0,z.useState)(),Rr=Ir?s.workspaces.find(e=>e.id===Ir):void 0,{theme:zr,setTheme:Br}=G_(),[Vr,Hr]=(0,z.useState)(!1),[Ur,Wr]=(0,z.useState)(!1),Gr=(e,t,n,r)=>{e.startsWith(`pending:`)||(Un({type:`workspace.settings`,workspaceId:e,model:n?{provider:n.provider,modelId:n.modelId}:null,thinkingLevel:r??null,agentId:t??null},`defaults:${e}`,Gn(e,{defaultModel:n,defaultThinkingLevel:r,defaultAgentId:t}))?Lr(void 0):L(`连接断开,设置未保存,请重试`,`error`))},Kr=e=>{if(e.startsWith(`pending:`)||i.current.some(t=>t.key===`defaults:${e}`))return;let t=`pending:${__()}`,n={id:t,workspaceId:e,title:`新会话`,status:`idle`,updatedAt:new Date().toISOString(),messages:[]};Nt.current.set(t,n),Un({type:`conversation.create`,workspaceId:e},`create-session:${e}`,e=>({...e,conversations:[n,...e.conversations]}),t)&&(_(e),l(t),yn(`session`),y(e=>[...e.filter(e=>e!==t),t]))},qr=e=>{e.startsWith(`pending:`)||Un({type:`conversation.archive`,conversationId:e},`archive:${e}`,Wn(e,{archivedAt:new Date().toISOString()}))},Jr=e=>Un({type:`conversation.unarchive`,conversationId:e},`archive:${e}`,Wn(e,{archivedAt:void 0})),Yr=async e=>{if(!F){L(`请先选择或创建会话`,`error`);return}if(!Qn){L(`当前模型不支持图片输入`,`error`);return}let t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=e.filter(e=>t.includes(e.type)?e.size>5242880?(L(`图片「${e.name}」超过 5MB 上限`,`error`),!1):!0:(L(`不支持的文件格式「${e.name}」,仅支持 PNG/JPEG/GIF/WebP`,`error`),!1));if(n.length===0)return;let r=F.id;Gt(r,e=>({...e,uploading:e.uploading+n.length}));let i=n.map(e=>({id:__(),conversationId:r,name:e.name,url:URL.createObjectURL(e)}));bt(e=>[...e,...i]);for(let[e,t]of n.entries()){let n=i[e];try{let e=await new Promise((e,n)=>{let r=new FileReader;r.onload=()=>{let t=r.result,n=t.indexOf(`,`);e(n>=0?t.slice(n+1):t)},r.onerror=n,r.readAsDataURL(t)}),i=await fetch(`/api/upload`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({conversationId:r,name:t.name,mimeType:t.type,data:e})});if(!(i.headers.get(`content-type`)??``).includes(`application/json`)){L(`服务器未返回 JSON 响应,请刷新或重启服务`,`error`);continue}if(i.ok){let e=await i.json();if(gt.current.has(n.id))continue;bt(e=>e.filter(e=>e.id!==n.id)),URL.revokeObjectURL(n.url),Gt(r,t=>({...t,images:[...t.images,{id:e.id,name:e.name,mimeType:e.mimeType,bytes:e.bytes}]}))}else{let e=await i.json().catch(()=>({error:`上传失败`}));L(e.error||`上传失败: ${i.status}`,`error`)}}catch(e){L(`上传错误: ${e instanceof Error?e.message:`网络错误`}`,`error`)}finally{bt(e=>e.map(e=>e.id===n.id?{...e,failed:!0}:e)),Gt(r,e=>({...e,uploading:Math.max(0,e.uploading-1)}))}}},Xr=e=>{let t=e.clipboardData?.items;if(!t)return;let n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.type.startsWith(`image/`)){let e=r.getAsFile();e&&n.push(e)}}if(n.length>0){if(!Qn){L(`当前模型不支持图片输入`,`error`);return}e.preventDefault(),Yr(n)}},Zr=e=>{e.dataTransfer?.types?.includes(`Files`)&&(e.preventDefault(),wt(!0))},Qr=e=>{e.currentTarget.contains(e.relatedTarget)||wt(!1)},$r=e=>{wt(!1);let t=Array.from(e.dataTransfer?.files??[]).filter(e=>e.type.startsWith(`image/`));if(t.length>0){if(e.preventDefault(),!Qn){L(`当前模型不支持图片输入`,`error`);return}Yr(t)}},ei=e=>{if(e.preventDefault(),!F||Kn||!Vt.trim()&&Ht.length===0)return;if(Ht.length>0&&!Qn){L(`当前模型不支持图片输入,请移除图片或切换至支持图文的模型`,`error`);return}if(Wt>0){L(`图片正在上传中,请稍候…`,`info`);return}let t=`message_${__()}`,n=F.id,r=Vt,i=Ht;Un({type:`message.send`,conversationId:n,content:Vt,clientId:t,...Ht.length>0?{images:Ht}:{},...Ut.length>0?{attachments:Ut}:{}},`send:${n}`,e=>{let a=e.conversations.find(e=>e.id===n);if(!a||a.messages.some(e=>e.id===t))return e;let o=a.status===`running`,s=new Date().toISOString();return{...e,conversations:e.conversations.map(e=>e.id===n?{...e,...o?{}:{status:`waiting`,updatedAt:s},messages:[...e.messages,{id:t,role:`user`,content:r,...i.length>0?{images:i}:{},...Ut.length>0?{attachments:Ut}:{},...o?{delivery:`waiting`}:{},createdAt:s}]}:e)}},t,e=>{vt(a=>[...a,{id:t,conversationId:n,content:r,images:i,reason:e}]),Gt(n,e=>e.text||e.images.length?e:{...e,text:r,images:i})},e=>!!e.conversations.find(e=>e.id===n)?.messages.some(e=>e.id===t))?Gt(F.id,e=>({...e,text:``,images:[]})):L(`这条消息已经在发送队列中,请稍候`,`info`)},ti=(0,z.useMemo)(()=>(F?.messages??[]).filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),[F?.messages]),ni=e=>{Un({type:`message.cancel`,conversationId:F?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===F?.id?{...t,messages:t.messages.filter(t=>t.id!==e)}:t)}))||L(`连接断开,撤回没有生效,请重试`,`error`)},ri=e=>{Un({type:`message.steer`,conversationId:F?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===F?.id?{...t,messages:OE(t.messages,e,0)}:t)}),void 0,void 0,t=>t.conversations.find(e=>e.id===F?.id)?.messages.find(t=>t.id===e)?.delivery===`sending`)||L(`连接断开,插到最前没有生效,请重试`,`error`)},ii=e=>{Un({type:`message.interrupt`,conversationId:F?.id??``,messageId:e},`interrupt:${F?.id}:${e}`,e=>e,void 0,void 0,t=>{let n=t.conversations.find(e=>e.id===F?.id);return n?.status===`running`&&!n.messages.find(t=>t.id===e)?.delivery})||L(`请求正在处理,请稍候`,`info`)},ai=e=>{Un({type:`message.sendQueued`,conversationId:F?.id??``,messageId:e},`send-queued:${e}`,e=>e,void 0,void 0,t=>!t.conversations.find(e=>e.id===F?.id)?.messages.find(t=>t.id===e)?.delivery)||L(`连接断开,发送没有生效,请重试`,`error`)},oi=(e,t)=>{Un({type:`message.edit`,conversationId:F?.id??``,messageId:e,content:t},`edit:${e}`,n=>({...n,conversations:n.conversations.map(n=>n.id===F?.id?{...n,messages:n.messages.map(n=>n.id===e?{...n,content:t}:n)}:n)}))||L(`连接断开,修改没有生效,请重试`,`error`)},[si,ci]=(0,z.useState)(),li=(e,t=!1)=>{if(!F||si)return;let n=F.messages.find(t=>t.id===e);n&&(n&&ht(e=>{let t=e[F.id]??{text:``,images:[],uploading:0};return t.text.trim()||t.images.length?e:{...e,[F.id]:{...t,text:n.content,images:n.images??[]}}}),ct({conversationId:F.id,messageId:e,kind:t?`withdraw`:`revert`})),Hn({type:`message.revert`,conversationId:F.id,messageId:e,withdraw:t})?ci(e):(ct(void 0),L(`连接断开,回退未执行,请重试`,`error`))},[ui,di]=(0,z.useState)(),fi=(0,z.useRef)(void 0),pi=async(e,t)=>{fi.current&&clearTimeout(fi.current);let n=await HE(t);di({id:e,kind:n?`copied`:`error`}),n||L(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中这条消息的文字复制`,`error`),fi.current=setTimeout(()=>di(void 0),2e3)};(0,z.useEffect)(()=>()=>{fi.current&&clearTimeout(fi.current)},[]);let[mi,hi]=(0,z.useState)(),gi=e=>{mi||e.startsWith(`pending:`)||(Hn({type:`conversation.fork`,conversationId:e})?hi(e):L(`连接断开,分叉没有执行,请重试`,`error`))};return(0,B.jsxs)(`main`,{className:`shell${Ve?` shell-rail-collapsed`:``} mobile-panel-${Ue}`,"data-rail-collapsed":Ve,"data-selected-workspace":g??``,style:{"--sidebar-width":`${Ye.sidebar}px`,"--rail-col":Ve?void 0:`${Ye.rail}px`},children:[(0,B.jsxs)(`aside`,{children:[(0,B.jsxs)(`div`,{className:`brand`,children:[(0,B.jsx)(`span`,{children:`π`}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:`SUPER PI`}),(0,B.jsx)(`small`,{children:`agent workspace`})]})]}),(0,B.jsx)(`div`,{className:`sidebar-actions`,children:(0,B.jsx)(`button`,{className:`workspace-new`,onClick:()=>C(!0),children:`+ 工作区`})}),(0,B.jsx)(`div`,{className:`label`,children:`工作区`}),(0,B.jsx)(`nav`,{children:s.workspaces.map(e=>{let t=s.conversations.filter(t=>t.workspaceId===e.id),n=t.filter(e=>!e.archivedAt).sort(LE),r=t.filter(e=>e.archivedAt).sort(RE),i=m[e.id]??!1,a=ue[e.id]??!0;return(0,B.jsxs)(`section`,{className:`workspace-group`,children:[(0,B.jsx)(`div`,{className:`workspace-header`,children:Mr(`workspace`,e.id)?(0,B.jsx)(vD,{initial:e.name,label:`重命名工作区 ${e.name}`,onCommit:t=>Nr(`workspace`,e.id,t),onClose:jr}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`button`,{className:`workspace-toggle`,"aria-expanded":!i,title:e.path,onContextMenu:t=>{t.preventDefault();let n=t.currentTarget.getBoundingClientRect();ut({workspace:e,x:t.clientX||n.left+24,y:t.clientY||n.top+n.height})},onClick:()=>{_(e.id),l(It.find(t=>t.workspaceId===e.id)?.id),h(t=>({...t,[e.id]:!i}))},children:[(0,B.jsx)(`span`,{className:`chevron chevron-folder`,"aria-hidden":`true`,children:i?`📁`:`📂`}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{onDoubleClick:()=>Ar(`workspace`,e.id),children:e.name}),(0,B.jsx)(`small`,{children:e.path})]})]}),(0,B.jsx)(`button`,{className:`workspace-add`,title:`在此工作区新建会话`,onClick:()=>Kr(e.id),children:`+`}),(0,B.jsx)(`button`,{className:`workspace-settings`,title:`工作区设置(默认智能体 / 模型 / 思考强度)`,"aria-label":`工作区设置 ${e.name}`,onClick:()=>Lr(e.id),children:`⚙`}),(0,B.jsx)(`button`,{className:`workspace-delete`,title:`删除工作区`,onClick:()=>Fr(e),children:`×`})]})}),!i&&(n.length?n.map(t=>(0,B.jsx)(`div`,{className:`conversation-row`,children:Mr(`conversation`,t.id)?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(vD,{initial:t.title,label:`重命名会话 ${t.title}`,onCommit:e=>Nr(`conversation`,t.id,e),onClose:jr}),(0,B.jsx)(`small`,{className:`conversation-time`,children:IE(t.updatedAt,Pt)})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`button`,{className:`conversation ${F?.id===t.id?`selected`:``}`,"data-conversation":t.id,title:t.title,"aria-label":`打开会话 ${t.title}`,onContextMenu:e=>{e.preventDefault();let n=e.currentTarget.getBoundingClientRect();ft({conversation:t,x:e.clientX||n.left+24,y:e.clientY||n.top+n.height})},onClick:()=>{en(t.id),_(e.id)},children:[(0,B.jsx)(`i`,{className:`conversation-mark`,children:(0,B.jsx)(ED,{state:TD(t,ge.some(e=>e.conversationId===t.id),D.current[t.id])})}),(0,B.jsx)(`span`,{"data-conversation-title":t.id,onDoubleClick:()=>Ar(`conversation`,t.id),children:t.title}),(0,B.jsx)(`small`,{children:IE(t.updatedAt,Pt)})]}),(0,B.jsx)(`button`,{type:`button`,className:`conversation-fork`,"data-fork-conversation":t.id,"data-fork-state":mi===t.id?`pending`:`idle`,disabled:!!mi,title:`从此会话分叉出一个新会话`,"aria-label":`从会话 ${t.title} 分叉出一个新会话`,onClick:()=>gi(t.id),children:`⑂`}),(0,B.jsx)(`button`,{className:`conversation-archive`,title:`归档会话`,"aria-label":`归档会话 ${t.title}`,onClick:()=>qr(t.id),children:`×`})]})},t.id)):(0,B.jsx)(`div`,{className:`conversation-empty`,children:`暂无会话`})),!i&&r.length>0&&(0,B.jsxs)(`div`,{className:`archived-group`,"data-archived-count":r.length,children:[(0,B.jsxs)(`button`,{className:`archived-toggle`,title:a?`展开已归档会话`:`收起已归档会话`,"aria-expanded":!a,onClick:()=>de(t=>({...t,[e.id]:!a})),children:[(0,B.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:a?`▸`:`▾`}),(0,B.jsxs)(`span`,{className:`archived-label`,children:[`Archived (`,r.length,`)`]})]}),!a&&r.map(e=>(0,B.jsx)(`div`,{className:`conversation-archived`,"data-archived-at":e.archivedAt,children:Mr(`conversation`,e.id)?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(vD,{initial:e.title,label:`重命名已归档会话 ${e.title}`,onCommit:t=>Nr(`conversation`,e.id,t),onClose:jr}),(0,B.jsx)(`small`,{children:zE(e.archivedAt)})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`i`,{className:`conversation-mark`,"aria-hidden":`true`}),(0,B.jsx)(`span`,{"data-archived-title":e.id,onDoubleClick:()=>Ar(`conversation`,e.id),children:e.title}),(0,B.jsx)(`small`,{children:zE(e.archivedAt)}),(0,B.jsx)(`button`,{type:`button`,className:`conversation-fork`,"data-fork-conversation":e.id,"data-fork-state":mi===e.id?`pending`:`idle`,disabled:!!mi,title:`从此会话分叉出一个新会话`,"aria-label":`从已归档会话 ${e.title} 分叉出一个新会话`,onClick:()=>gi(e.id),children:`⑂`}),(0,B.jsx)(`button`,{className:`conversation-restore`,title:`恢复为正常会话`,"aria-label":`恢复会话 ${e.title}`,onClick:()=>Jr(e.id),children:`↑`})]})},e.id))]})]},e.id)})}),(0,B.jsxs)(`footer`,{children:[(0,B.jsxs)(`div`,{className:`footer-status`,children:[(0,B.jsx)(`i`,{className:u?`online`:`offline`}),u?`已连接`:`正在连接`,(0,B.jsx)(`span`,{children:`本地持久化`})]}),(0,B.jsxs)(`div`,{className:`footer-version`,"data-super-pi-version":Le?.runningVersion??``,children:[`Super Pi v`,Le?.runningVersion??`…`]}),(0,B.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-theme-open":`1`,"aria-haspopup":`dialog`,"aria-expanded":Vr,onClick:()=>{Hr(!0),Hn({type:`catalog.fetchAll`}),Hn({type:`providers.fetch`})},children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,children:`⚙`}),`设置`]}),(0,B.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-help-open":`1`,"aria-haspopup":`dialog`,"aria-expanded":Ur,onClick:()=>Wr(!0),children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,children:`📖`}),`使用指南`]}),(0,B.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger restart-needed-trigger`,title:`检查 Super Pi 更新`,onClick:async()=>{Be(`updating`);try{let e=await fetch(`/api/update-check`);if(!e.ok)throw Error(`check failed`);let t=await e.json();if(t.needsRestart)L(`当前代码已更新,正在重启服务…`,`info`);else if(t.updateAvailable){if(!window.confirm(`发现新版本 v${t.latestVersion??``},是否立即更新并重启 Super Pi?`))L(`已取消更新`,`info`);else{if(!(await fetch(`/api/update`,{method:`POST`})).ok)throw Error(`update failed`);L(`正在更新到 v${t.latestVersion} 并重启…`,`info`)}}else L(`当前已是最新版本`,`info`)}catch{L(`检查更新失败,请检查网络或服务日志`,`error`)}finally{Be(`idle`)}},children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,children:ze===`updating`?`⟳`:`↻`}),ze===`updating`?`正在检查更新…`:`检查更新`]}),Le?.needsRestart&&(0,B.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger restart-needed-trigger`,title:`代码已更新:当前运行 v${Le.runningVersion},磁盘版本 v${Le.diskVersion}。点击复制重启命令 /super_pi restart`,onClick:async()=>{Be(`updating`);try{if(!(await fetch(`/api/update`,{method:`POST`})).ok)throw Error(`update failed`);L(`正在更新 Super Pi,服务即将重启…`,`info`)}catch{Be(`idle`),L(`更新启动失败,请检查服务日志`,`error`)}},children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,children:ze===`updating`?`⟳`:`⚠️`}),ze===`updating`?`正在更新并重启…`:`更新并重启服务`]})]})]}),(0,B.jsx)(sO,{side:`left`,width:Ye.sidebar,min:Ye.sidebarMin,max:Ye.sidebarMax,label:`调整左侧栏宽度`,onWidth:Xe}),(0,B.jsxs)(`section`,{className:`chat`,"data-main-view":vn,"data-main-view-kind":vn,children:[Mn.length>0&&(0,B.jsx)(`div`,{className:`chat-tab-strip`,"data-chat-tab-strip":`1`,"data-session-count":$t.length,"data-file-count":I.open.length,children:(0,B.jsx)(zg,{tabs:Mn,prefix:`workspace-tab`,ariaLabel:`工作区标签页`,activeId:Nn,onSelect:Pn,onClose:Fn,minWidth:120,maxWidth:320})}),(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`div`,{className:`chat-head`,children:[(0,B.jsx)(`h1`,{children:F?.title??`准备开始`}),ye.size>0?[...ye].map(([e,t])=>(0,B.jsx)(`p`,{"data-role":`run-status`,"data-status-key":e,children:`扩展状态:${e?`${e} · `:``}${t}`},e)):(0,B.jsx)(`p`,{"data-role":`run-status`,children:F?.status===`running`?`Agent 正在工作`:`Pi runtime · Web 控制台`})]}),(0,B.jsxs)(`span`,{className:`chat-view chat-view-${vn}`,"data-main-view-indicator":vn,"data-main-view-kind":vn,title:vn===`file`?`中间主画面正在显示文件 ${I.active?.path??``}`:vn===`diff`?`中间主画面正在显示 ${bn??``} 的改动`:`中间主画面正在显示这个会话的消息流`,children:[(0,B.jsx)(`span`,{className:`chat-view-label`,children:`主区显示`}),(0,B.jsx)(`span`,{className:`chat-view-kind`,children:vn===`file`?`文件`:vn===`diff`?`改动`:`会话`}),vn===`file`&&I.active&&(0,B.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":I.active.name,children:I.active.name}),vn===`diff`&&bn&&(0,B.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":bn,children:bn})]}),(0,B.jsx)(`div`,{className:`badge`,children:F?.status??`idle`})]}),f&&(0,B.jsxs)(`div`,{className:`error`,role:`alert`,"data-global-error":!0,children:[(0,B.jsx)(`span`,{children:f}),(0,B.jsx)(`button`,{type:`button`,"aria-label":`关闭错误提示`,title:`关闭错误提示`,onClick:()=>p(void 0),children:`×`})]}),F?.error&&(0,B.jsx)(`div`,{className:`error`,"data-role":`conversation-error`,children:F.error}),Ce&&(0,B.jsxs)(`div`,{className:`extui-title-note`,children:[`扩展建议标题:`,Ce]}),_e.length>0&&(0,B.jsx)(`div`,{className:`toasts`,role:`status`,"aria-live":`polite`,"data-toast-count":_e.length,children:_e.map(e=>(0,B.jsx)(`div`,{className:`toast toast-${e.kind}`,"data-toast-kind":e.kind,children:e.text},e.key))}),vn===`file`?(0,B.jsx)(`div`,{className:`chat-file-view`,"data-main-file-view":In?.path,"data-file-view-kind":`editor`,children:In?(0,B.jsx)(Tg,{file:In,state:I.saves[In.path]?.state??`idle`,message:I.saves[In.path]?.message??``,external:I.external[In.path]===!0,jumpToLine:gn&&gn.workspaceId===g&&gn.path===In.path?gn:void 0,onChange:e=>I.updateBuffer(In.path,e),onSave:()=>void I.save(In.path,!1),onReload:()=>void I.reload(In.path),onOverwrite:()=>void I.save(In.path,!0)}):(0,B.jsx)(`p`,{className:`rail-empty`,"data-main-file-empty":`1`,children:`没有选中的文件。`})}):vn===`diff`?(0,B.jsx)(`div`,{className:`chat-file-view`,"data-main-diff-view":bn??``,"data-file-view-kind":`diff`,children:(0,B.jsx)(Dg,{diff:Cn.diff,loading:Cn.loading,error:Cn.error,bufferContent:Dn,mode:Tn,onMode:En})}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`messages`,ref:A,"data-message-scroll-container":F?.id??``,onWheel:e=>{e.deltaY<0&&T.current[F?.id??``]?.followTail&&(ne.current=!0,zt(e.currentTarget,!0))},onScroll:e=>{let t=e.currentTarget;t.dataset.programmaticScroll===`true`?delete t.dataset.programmaticScroll:zt(t)},children:[!F&&(0,B.jsxs)(`div`,{className:`empty`,children:[(0,B.jsx)(`div`,{className:`orb`,children:`π`}),(0,B.jsx)(`h2`,{children:`开始一个新会话`}),s.workspaces.length===0?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{children:`先创建一个工作区,再开始会话。`}),(0,B.jsx)(`button`,{onClick:()=>C(!0),children:`+ 新建工作区`})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{children:s.workspaces.length===1&&Lt?`在「${Lt.name}」中创建会话,即可向 Super Pi 发送任务。`:`选择工作区即可开始会话,向 Super Pi 发送任务。`}),s.workspaces.length>1&&(0,B.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,B.jsx)(`label`,{htmlFor:`empty-workspace-choice`,children:`工作区:`}),(0,B.jsxs)(`select`,{id:`empty-workspace-choice`,"aria-label":`选择工作区`,value:Lt?.id,onChange:e=>{e.target.value===`__new__`?C(!0):_(e.target.value)},children:[s.workspaces.map(e=>(0,B.jsx)(`option`,{value:e.id,children:e.name},e.id)),(0,B.jsx)(`option`,{value:`__new__`,children:`+ 新建工作区…`})]})]}),Lt&&(0,B.jsx)(`button`,{onClick:()=>Kr(Lt.id),children:`新建会话`}),(0,B.jsx)(`span`,{className:`empty-secondary-action`,role:`button`,tabIndex:0,onClick:()=>C(!0),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),C(!0))},children:`+ 新建工作区`})]})]}),_r.map(e=>{if(e.startsWith(`m:`)){let t=mr.get(e.slice(2));if(!t)return null;let r=!F?.messages.some(n=>n.id!==t.id&&n.role===`user`&&_r.indexOf(`m:${n.id}`)>_r.indexOf(e)),i=t.role===`user`&&F?.status!==`running`&&F?.status!==`waiting`&&si!==t.id,a=i&&r&&!t.id.startsWith(`pending:`),o=i&&!r&&!!t.piEntryId,s=t.content?(0,B.jsx)(tm,{source:t.content}):(0,B.jsx)(`span`,{className:`typing`,children:`正在思考`}),c=t.toolCalls??[];if(t.role===`user`){let n=ui?.id===t.id?ui.kind:void 0,r=t.content||(t.images?.length?`[图片]`:``);return(0,B.jsxs)(`article`,{className:`message user`,"data-transcript-key":e,children:[(0,B.jsxs)(`div`,{className:`message-body`,children:[(0,B.jsxs)(`div`,{className:`bubble`,children:[(0,B.jsxs)(`div`,{className:`meta`,children:[he,(0,B.jsx)(`time`,{children:kE(t.createdAt)})]}),t.images&&t.images.length>0&&(0,B.jsx)(`div`,{className:`message-images`,"data-message-images":`1`,children:t.images.map(e=>(0,B.jsx)(`button`,{type:`button`,className:`message-image-btn`,"data-message-image-id":e.id,onClick:()=>St({url:`/api/upload/${encodeURIComponent(F?.id??``)}/${encodeURIComponent(e.id)}`,name:e.name,bytes:e.bytes}),title:e.name?`查看大图:${e.name}`:`查看大图`,children:(0,B.jsx)(`img`,{src:`/api/upload/${encodeURIComponent(F?.id??``)}/${encodeURIComponent(e.id)}`,alt:e.name||`图片`,className:`message-image-thumb`,loading:`lazy`})},e.id))}),(0,B.jsx)(`div`,{className:`content`,children:s})]}),t.attachments&&t.attachments.length>0&&(0,B.jsx)(`div`,{className:`message-attachments`,"data-message-attachments":`1`,children:t.attachments.map(e=>{let n=`att:${t.id}:${e.kind}:${e.id}`,r=rt[n]??!1;return(0,B.jsxs)(`div`,{className:`message-attachment`,"data-message-attachment":e.kind,children:[(0,B.jsxs)(`button`,{type:`button`,className:`message-attachment-head`,"data-message-attachment-toggle":e.id,"aria-expanded":r,onClick:()=>it(e=>({...e,[n]:!r})),children:[(0,B.jsx)(`span`,{className:`message-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,B.jsx)(`span`,{className:`message-attachment-label`,children:`技能`}),(0,B.jsx)(`span`,{className:`message-attachment-name`,title:e.name,children:e.name}),(0,B.jsx)(`span`,{className:`message-attachment-chevron`,"aria-hidden":`true`,children:r?`▾`:`▸`})]}),r&&(0,B.jsx)(`pre`,{className:`message-attachment-body`,"data-message-attachment-body":e.id,children:e.content})]},n)})}),(0,B.jsxs)(`div`,{className:`message-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`message-copy`,"data-copy-message":t.id,"data-copy-state":n,"aria-label":`复制这条消息:${r}`,onClick:()=>pi(t.id,r),children:n===`copied`?`已复制`:n===`error`?`复制失败`:`复制`}),a&&(0,B.jsx)(`button`,{type:`button`,className:`message-revert`,"data-withdraw-message":t.id,title:`撤回并编辑:删除这条消息并将文字恢复到输入框继续编辑`,onClick:()=>li(t.id,!0),children:`撤回`}),o&&(0,B.jsx)(`button`,{type:`button`,className:`message-revert`,"data-revert-message":t.id,title:`回退到这里:删除后续全部内容(Pi 的记录和这里的历史一起清掉,不会新建会话,也不动任何代码文件)`,onClick:()=>li(t.id),children:`回退`})]})]}),(0,B.jsx)(`div`,{className:`avatar`,title:he,children:he})]},e)}if(t.role===`tool`){let n=(()=>{let e=/<summary>([\s\S]*?)<\/summary>/.exec(t.content);return e?e[1].trim():`后台回传`})(),r=(()=>{let e=/<task id="[^"]+" state="([^"]+)"/.exec(t.content);return e?e[1]:`completed`})(),i=(()=>{let e=/<task_(?:result|error)>\n?([\s\S]*?)\n?<\/(?:task_result|task_error)>/.exec(t.content);return e?e[1]:t.content})(),a=`tool:${t.id}`,o=rt[a]??!1;return(0,B.jsx)(`article`,{className:`message tool`,"data-transcript-key":e,"data-tool-state":r,children:(0,B.jsxs)(`div`,{className:`message-body`,children:[(0,B.jsx)(`div`,{className:`bg-result-head`,"data-bg-result-head":t.id,children:(0,B.jsxs)(`button`,{type:`button`,className:`bg-result-toggle`,"data-bg-result-toggle":t.id,"aria-expanded":o,title:o?`折叠后台回传`:`展开后台回传`,onClick:()=>it(e=>({...e,[a]:!o})),children:[(0,B.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:r===`error`?`✕`:`↩`}),(0,B.jsx)(`span`,{className:`bg-result-label`,children:`后台回传`}),(0,B.jsx)(`span`,{className:`bg-result-summary`,title:n,children:n}),!o&&(0,B.jsx)(`span`,{className:`bg-result-preview`,"data-bg-result-preview":t.id,title:`展开查看完整输出`,children:i.split(`
|
|
98
|
-
`).slice(-1)[0]}),(0,B.jsx)(`span`,{className:`bg-result-chevron`,"aria-hidden":`true`,children:o?`▾`:`▸`})]})}),o&&(0,B.jsx)(`div`,{className:`bg-result-body`,"data-bg-result-body":t.id,children:(0,B.jsx)(`pre`,{className:`bg-result-pre`,"data-bg-result-pre":t.id,children:i})})]})},e)}let l=t.thinking?.trim()?t.thinking:``,u=t.thinkingBlocks?.length?t.thinkingBlocks:l?[{at:0,text:l}]:[],d=(e,n)=>{let r=typeof e.at==`number`&&Number.isFinite(e.at)?e.at:n;return Math.max(0,Math.min(r,t.content.length))},f=e=>e.thinkingBlock===void 0?typeof e.thinkingAt!=`number`||!(e.thinkingAt<l.length||t.thinkingActive)?-1:u.findIndex((t,n)=>(e.at??0)>=t.at&&(u[n+1]===void 0||(e.at??0)<u[n+1].at)):e.thinkingBlock??-1,p=e=>c.map((e,t)=>({call:e,index:t})).filter(({call:t})=>f(t)===e),m=[],h=[...u.map((e,t)=>({at:e.at,order:u.slice(0,t).reduce((e,t)=>e+t.text.length,0)*2+1,segment:{blockIndex:t}})),...c.map((e,t)=>({at:d(e,t),order:(e.thinkingAt??0)*2,segment:{call:e,index:t}})).filter(({segment:e})=>`call`in e&&f(e.call)<0)].sort((e,t)=>e.at-t.at||e.order-t.order),g=0;for(let e of h){let n=Math.max(g,Math.min(e.at,t.content.length));n>g&&m.push({text:t.content.slice(g,n)}),m.push(e.segment),g=n}g<t.content.length&&m.push({text:t.content.slice(g)});let _=e=>{let t=gr.get(e);if(t)return(0,B.jsx)(`div`,{className:`call-anchored-run`,"data-call-anchored-run":t.id,"data-call-anchored-site":e,children:(0,B.jsx)(
|
|
99
|
-
`).map(e=>e.trim()).find(Boolean)??``,expanded:xr[`${t.id}:${e}`]===!0,onToggle:()=>Cr(`${t.id}:${e}`),children:a},`${t.id}:thinking:${e}`)};return(0,B.jsxs)(`article`,{className:`message assistant`,"data-transcript-key":e,children:[(0,B.jsx)(`div`,{className:`avatar`,children:`π`}),(0,B.jsxs)(`div`,{className:`message-body`,children:[(0,B.jsxs)(`div`,{className:`meta`,children:[t.agentIdentity?.name??`Super Pi`,(0,B.jsx)(`time`,{children:kE(t.createdAt)})]}),m.map((e,t)=>`blockIndex`in e?y(e.blockIndex):`text`in e?e.text?(0,B.jsx)(`div`,{className:`content`,children:(0,B.jsx)(tm,{source:e.text})},`t${t}`):null:v(e))]})]},e)}if(e.startsWith(`w:`)){let t=fr.get(e.slice(2));return t?(0,B.jsxs)(`div`,{"data-transcript-key":e,children:[n.some(e=>e.key===`stop:${t.id}`)&&(0,B.jsx)(`span`,{children:`停止中…`}),(0,B.jsx)(qg,{workflow:t,names:pr,stopping:n.some(e=>e.key===`stop:${t.id}`),onStop:()=>Tr(t.id)},e)]},e):null}let t=hr.get(e.slice(2));return t?(0,B.jsxs)(`div`,{"data-transcript-key":e,children:[n.some(e=>e.key===`stop:${t.id}`)&&(0,B.jsx)(`span`,{children:`停止中…`}),(0,B.jsx)(uD,{run:t,stopping:n.some(e=>e.key===`stop:${t.id}`),name:pr.get(t.agentId)??``,expanded:!!tt[t.id],onToggle:()=>vr(t.id),onStop:()=>wr(t.id)},e)]},e):null})]}),(0,B.jsx)(dD,{messages:ti,running:F?.status===`running`,onSteer:ri,onInterrupt:ii,onSend:ai,onCancel:ni,onEdit:oi}),(0,B.jsxs)(`div`,{className:`stream-tail`,"data-stream-tail":`1`,"data-follow-tail":N.followTail?`true`:`false`,children:[Qe!==null&&(0,B.jsx)(mO,{height:Qe,onHeight:et}),(0,B.jsx)(`span`,{className:`stream-tail-status`,"data-run-status":F?.status??`idle`,"data-stream-state":u?F?.status===`waiting`?`waiting`:F?.status===`running`?`streaming`:ti.length?`waiting`:F?.status===`failed`?`failed`:`ready`:`waiting`,children:u?F?.status===`waiting`?`等待 LLM 返回`:F?.status===`running`?`Streaming · 正在生成`:ti.length?`Waiting · 消息排队中`:F?.status===`failed`?`运行失败`:F?.status===`stopped`?`已停止`:`就绪`:`连接中 / 等待连接`}),!N.followTail&&(0,B.jsx)(`button`,{type:`button`,className:`stream-tail-jump`,"data-jump-to-bottom":`1`,onClick:()=>{let e=A.current;e&&($D(e),e.scrollTop=e.scrollHeight,zt(e,!1,!0))},children:`↓ 跳到底部`}),(0,B.jsx)(`span`,{className:`stream-tail-mode`,"data-follow-tail":N.followTail?`true`:`false`,children:N.followTail?`贴底`:`自由浏览`})]}),(lr.length>0||[...xe.values()].some(e=>e.placement===`aboveEditor`))&&(0,B.jsxs)(`div`,{className:`extui`,"data-extui-count":lr.length,children:[lr.map(e=>(0,B.jsx)(_D,{request:e.request,pending:n.some(t=>t.key===`answer:${e.conversationId}:${e.request.requestId}`),onAnswer:t=>Jn(e.conversationId,e.request.requestId,t)},e.request.requestId)),Er(`aboveEditor`)]}),(0,B.jsxs)(`form`,{onSubmit:ei,onPaste:Xr,onDragOver:Zr,onDragLeave:Qr,onDrop:$r,className:Ct?`composer-dropzone-active`:void 0,children:[(0,B.jsx)(`textarea`,{ref:ee,value:Vt,onCompositionStart:()=>{Et.current=!0},onCompositionEnd:()=>{Et.current=!1},onChange:e=>{Kt(e.target.value);let t=e.target.value,n=e.target.selectionStart??t.length,r=t.slice(0,n),i=r.lastIndexOf(`/`),a=r.slice(i+1),o=i>0?r[i-1]:``;i>=0&&(i===0||/\s/.test(o))&&/^[\w:-]*$/u.test(a)?Xt({visible:!0,query:a,rect:e.currentTarget.getBoundingClientRect()}):Xt({visible:!1,query:``,rect:null})},placeholder:F?Qn?`描述你要完成的任务(支持粘贴/拖放图片)…`:`描述你要完成的任务…`:`先创建会话`,disabled:!F,onKeyDown:e=>{if(!(Et.current||DE(e))){if(Yt.visible){if(e.key===`Escape`){e.preventDefault(),Xt({visible:!1,query:``,rect:null});return}if([`ArrowDown`,`ArrowUp`,`Enter`].includes(e.key)){e.preventDefault();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),e.currentTarget.form?.requestSubmit())}}}),Yt.visible&&Yt.rect&&(0,B.jsx)(mm,{query:Yt.query,anchorRect:Yt.rect,workspaceId:F?.workspaceId,command:Hn,onSelect:e=>{if(e.id.startsWith(`skill:`)){let t=e.id.slice(6),n=document.querySelector(`[data-selected-workspace]`)?.dataset.selectedWorkspace;n&&fetch(`/api/memory/tool`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({workspaceId:n,conversationId:F?.id,kind:`skill.read`,skillId:t})}).then(async n=>{if(!n.ok){L(`读取技能失败`,`error`);return}let r=await n.json();typeof r.content==`string`&&qt({kind:`skill`,id:r.id??t,name:r.name??e.label,content:r.content})}).catch(()=>L(`读取技能失败`,`error`))}let t=ee.current?.selectionStart??Vt.length,n=Vt.slice(0,t),r=n.lastIndexOf(`/`),i=fm(e,Yt.query),a=`${n.slice(0,r)}/${i} ${Vt.slice(t)}`;Kt(a),Xt({visible:!1,query:``,rect:null})},onClose:()=>Xt({visible:!1,query:``,rect:null})}),_t.filter(e=>e.conversationId===F?.id).map(e=>(0,B.jsxs)(`div`,{className:`composer-notice`,"data-failed-send":e.id,role:`alert`,children:[(0,B.jsx)(`span`,{className:`composer-notice-mark`,"aria-hidden":`true`,children:`!`}),(0,B.jsxs)(`div`,{className:`composer-notice-body`,children:[(0,B.jsx)(`p`,{className:`composer-notice-title`,"data-failed-send-reason":`1`,children:e.reason?.trim()||`服务端没有接受这条消息。`}),(0,B.jsx)(`p`,{className:`composer-notice-text`,title:e.content,children:e.content})]}),(0,B.jsxs)(`div`,{className:`composer-notice-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`composer-notice-action`,"data-failed-send-restore":`1`,disabled:!!(Vt||Ht.length),title:Vt||Ht.length?`输入框里已经有内容,先把这条留在下面`:`放回输入框,改完再发`,onClick:()=>{Gt(e.conversationId,t=>({...t,text:e.content,images:e.images})),vt(t=>t.filter(t=>t.id!==e.id))},children:`放回输入框`}),(0,B.jsx)(`button`,{type:`button`,className:`composer-notice-dismiss`,"data-failed-send-dismiss":`1`,onClick:()=>vt(t=>t.filter(t=>t.id!==e.id)),children:`丢弃`})]})]},e.id)),yt.filter(e=>e.conversationId===F?.id).map(e=>(0,B.jsxs)(`div`,{"data-upload-preview":e.id,children:[(0,B.jsx)(`img`,{src:e.url,alt:e.name,width:48,height:48}),(0,B.jsx)(`span`,{children:e.failed?`上传失败`:`上传中…`}),(0,B.jsx)(`button`,{type:`button`,onClick:()=>{gt.current.add(e.id),URL.revokeObjectURL(e.url),bt(t=>t.filter(t=>t.id!==e.id))},children:`移除`})]},e.id)),(Ht.length>0||Wt>0)&&(0,B.jsxs)(`div`,{className:`composer-attachments`,"data-composer-attachments":`1`,children:[Ht.map((e,t)=>(0,B.jsxs)(`div`,{className:`composer-attachment-item`,"data-composer-attachment-id":e.id,children:[(0,B.jsx)(`img`,{src:`/api/upload/${encodeURIComponent(F?.id??``)}/${encodeURIComponent(e.id)}`,alt:e.name||`已附图片`,className:`composer-attachment-thumb`,onClick:()=>St({url:`/api/upload/${encodeURIComponent(F?.id??``)}/${encodeURIComponent(e.id)}`,name:e.name,bytes:e.bytes}),title:`点击查看大图`}),(0,B.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name||`图片`}),(0,B.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-attachment-remove":e.id,onClick:()=>Zt(e=>e.filter((e,n)=>n!==t)),"aria-label":`移除 ${e.name||`图片`}`,title:`移除图片`,children:`✕`})]},e.id)),Wt>0&&(0,B.jsx)(`div`,{className:`composer-attachment-item composer-attachment-uploading`,children:(0,B.jsxs)(`span`,{children:[`图片上传中 (`,Wt,`)…`]})}),Ut.map(e=>(0,B.jsxs)(`div`,{className:`composer-attachment-item composer-attachment-skill`,"data-composer-skill-id":e.id,children:[(0,B.jsx)(`span`,{className:`composer-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,B.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name}),(0,B.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-skill-remove":e.id,onClick:()=>Jt(e.kind,e.id),"aria-label":`移除 ${e.name}`,title:`移除技能`,children:`✕`})]},`${e.kind}:${e.id}`))]}),(0,B.jsxs)(`div`,{className:`composer`,children:[(0,B.jsxs)(`div`,{className:`session-picker`,"data-session-picker":`1`,children:[(0,B.jsx)(yD,{kind:`agent`,label:ir?.name??`跟随 Pi 默认`,value:F?.agentId??bD,options:ar,disabled:!Ne||Ne.source===`unavailable`||Kn,note:nD(Ne),onChoose:cr}),(0,B.jsx)(yD,{kind:`model`,label:Yn?.label??(Te?`Pi 默认`:`读取中…`),value:Yn?`${Yn.provider}/${Yn.modelId}`:void 0,detail:sr?`来自 ${ir?.name}`:Yn&&Te?.source===`pi`&&!F?.model?`Pi 默认模型`:Yn?`${Yn.provider}/${Yn.modelId}`:void 0,options:er,disabled:!Zn||Kn,note:tD(`模型`,Te),onChoose:nr}),(0,B.jsx)(yD,{kind:`thinking`,label:Xn??(Te?`Pi 默认`:`读取中…`),value:Xn,options:tr,disabled:!Zn||Kn,note:tD(`思考等级`,Te),onChoose:rr})]}),(0,B.jsxs)(`div`,{className:`composer-hints`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`composer-attach-btn`,"data-composer-attach":`1`,onClick:()=>Tt.current?.click(),disabled:!F||!Qn||Wt>0,title:F?Qn?`添加图片(支持剪贴板粘贴与拖拽)`:`当前模型不支持图片输入`:`请先创建或选择会话`,"aria-label":`添加图片`,children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` 图片`]}),(0,B.jsx)(`input`,{ref:Tt,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,multiple:!0,style:{display:`none`},onChange:e=>{e.target.files?.length&&(Yr(Array.from(e.target.files)),e.target.value=``)}}),(0,B.jsx)(`span`,{children:`Enter 发送 · Shift + Enter 换行`})]}),(0,B.jsxs)(`div`,{className:`composer-actions`,children:[F?.status===`running`&&(0,B.jsx)(`button`,{type:`button`,className:`stop`,"data-stop-run":F.id,disabled:n.some(e=>e.key===`stop:${F.id}`),onClick:()=>Un({type:`run.stop`,conversationId:F.id},`stop:${F.id}`,e=>e),children:n.some(e=>e.key===`stop:${F.id}`)?`停止中…`:`停止`}),(0,B.jsx)(`button`,{className:`send ${F?.status===`running`?`send-queued`:``}`,"data-send-mode":F?.status===`running`?`queued`:`direct`,disabled:!Vt.trim()&&Ht.length===0||!F||Wt>0||!!si||Kn,title:F?si?`正在撤回:Pi 的历史还没截断完成,撤回结束后即可发送`:!Vt.trim()&&Ht.length===0?`请输入消息或添加图片后发送`:Wt>0?`图片上传中…`:F.status===`running`?`这一轮结束后发送(发送后可在上面的排队区取消或插队)`:void 0:`请先创建或选择会话`,children:si?`撤回中…`:F?.status===`running`?`排队发送 ↑`:`发送 ↑`})]})]})]}),Er(`belowEditor`)]})]}),(0,B.jsx)(sO,{side:`right`,width:Ve?30:Ye.rail,min:Ye.railMin,max:Ye.railMax,label:`调整右侧栏宽度`,onWidth:Ze}),fn&&(0,B.jsx)(Fg,{entries:I.index,complete:I.indexComplete,skipped:I.indexSkipped,onOpen:e=>{kn(e)},onClose:()=>pn(!1)}),mn&&(0,B.jsx)(Pg,{workspaceId:g,onOpen:e=>{kn({path:e.path,name:e.name,text:!0},e.line)},onClose:()=>hn(!1)},g),(0,B.jsxs)(`nav`,{className:`mobile-nav`,"aria-label":`移动端主导航`,children:[(0,B.jsxs)(`button`,{type:`button`,"data-mobile-nav":`workspaces`,className:Ue===`workspaces`?`active`:``,onClick:()=>We(`workspaces`),children:[`☰`,(0,B.jsx)(`span`,{children:`工作区`})]}),(0,B.jsxs)(`button`,{type:`button`,"data-mobile-nav":`chat`,className:Ue===`chat`?`active`:``,onClick:()=>We(`chat`),children:[`◉`,(0,B.jsx)(`span`,{children:`对话`})]}),(0,B.jsxs)(`button`,{type:`button`,"data-mobile-nav":`rail`,className:Ue===`rail`?`active`:``,onClick:()=>{We(`rail`),He(!1)},children:[`▣`,(0,B.jsx)(`span`,{children:`工具`})]})]}),` `,lt&&(0,B.jsx)(UE,{workspace:lt.workspace,x:lt.x,y:lt.y,notify:L,onClose:()=>ut(void 0)}),dt&&(0,B.jsx)(WE,{conversation:dt.conversation,x:dt.x,y:dt.y,notify:L,onRename:()=>void Pr(dt.conversation.id),onClose:()=>ft(void 0)}),S&&(0,B.jsx)(QE,{onClose:()=>C(!1),onCreate:Dr}),Vr&&(0,B.jsx)(tv,{workspaceId:g,theme:zr,onChooseTheme:e=>Br(e),onClose:()=>Hr(!1),agentCatalog:Ne,subagentCatalog:Fe,modelFilterRules:s.modelFilterRules??[],pendingSettings:n.some(e=>e.key===`model-rules`||e.key===`agent-directories`||e.key===`default-model`),onSetModelRules:e=>Un({type:`model.rules.set`,rules:e},`model-rules`,t=>({...t,modelFilterRules:e})),defaultModel:s.defaultModel,modelCatalog:De,onSetDefaultModel:e=>Un({type:`settings.defaultModel`,model:e?{provider:e.provider,modelId:e.modelId}:null},`default-model`,t=>{let n={...t};return e?n.defaultModel=e:delete n.defaultModel,n}),providers:ke,providerApis:je,onSetProvider:e=>{Hn({type:`providers.set`,provider:e})},onRemoveProvider:e=>{Hn({type:`providers.remove`,providerId:e})},onRemoveProviderModel:(e,t)=>{Hn({type:`providers.removeModel`,providerId:e,modelId:t})},customAgentDirs:s.customAgentDirs??[],onSetCustomAgentDirs:e=>Un({type:`agents.setCustomDirs`,dirs:e},`agent-directories`,t=>({...t,customAgentDirs:e})),onRescanAgents:()=>Hn({type:`agents.rescan`}),userNickname:fe,onSetUserNickname:me}),Ur&&(0,B.jsx)(Yg,{onClose:()=>Wr(!1)}),Rr&&(0,B.jsx)(xD,{workspace:Rr,catalog:$n(Te,Rr),agents:Ne,onClose:()=>Lr(void 0),onRename:()=>{let e=Rr.id;Lr(void 0),Ar(`workspace`,e)},onSave:(e,t,n)=>Gr(Rr.id,e,t,n)}),xt&&(0,B.jsx)(VD,{image:xt,onClose:()=>St(void 0)}),(0,B.jsx)(ND,{todos:s.todosByConversation?.[F?.id??``]??[],tasks:(s.backgroundTasks??[]).filter(e=>e.conversationId===F?.id),collapsed:Ve,onToggle:()=>He(e=>!e),workspaceId:g,workspaceLabel:s.workspaces.find(e=>e.id===g)?.path,conversationId:F?.id,connected:u,files:I,onOpenFile:e=>void kn(e),onOpenChanged:Sn,activeTab:un,onSelectTab:dn,sendCommand:Hn,registerTerminalSink:le})]})}W_(U_()),(0,ua.createRoot)(document.getElementById(`root`)).render((0,B.jsx)(z.StrictMode,{children:(0,B.jsx)(hO,{})}));export{l as a,s as i,y as n,d as r,cg as t};
|
|
97
|
+
如需本地计算,声明 script: { path, timeoutMs, parameters }。脚本必须是 Python,参数以 JSON 从 stdin 传入,stdout 必须只输出一个 JSON 对象。在 index.html 中加载 <script src="./super-pi-tool.js"><\/script>,然后调用 SuperPiTool.run(params)、SuperPiTool.get(runId)、SuperPiTool.wait(runId) 或 SuperPiTool.cancel(runId)。这些都是已绑定本工具身份的相对接口;不要调用 /api/exec,不要猜测 toolId,也不要传 shell 命令、任意文件路径或未声明参数。页面必须实际执行一次示例任务并显示运行状态、日志和结构化结果。第三方包写进 environment.requires(必须钉死成 pkg==version),首次运行时会装进这个工具自己的虚拟环境。需要模型能力(摘要、改写、抽取、分类)时调用 SuperPiTool.llm({ prompt, system }),不要自己写模型客户端或保管密钥,并在注册时声明 permissions: { llm: true }——否则服务端会拒绝,导入页面也会提示用户。最后返回注册 id、访问地址、文件清单和验证结果。`);f(e),window.setTimeout(()=>f(!1),1800)};(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&i()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[i]);let N=n.map(e=>e.slug).filter(e=>typeof e==`string`),te=e=>{m(void 0),g(void 0),A(void 0),O({tool:e,name:TE({slug:e.slug??`tool`})})},ne=async(e,t)=>{m(void 0),g(void 0),A(void 0);let n=EE(t);if(!n.ok)A(n.reason);else try{let t=await fetch(`/api/tools/export?id=${encodeURIComponent(e.id)}`),r=await t.json();if(!t.ok||!r.bundle)throw Error(r.error??`HTTP ${t.status}`);let i=new Blob([JSON.stringify(r.bundle,null,2)],{type:`application/json`}),a=URL.createObjectURL(i),o=document.createElement(`a`);o.href=a,o.download=n.name,document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(a),g(r.skipped?.length?`已导出「${e.name}」,但有 ${r.skipped.length} 个文件没有包含:${r.skipped.join(`、`)}。`:`已导出「${e.name}」。`)}catch(e){m(`导出失败:${e instanceof Error?e.message:String(e)}`)}finally{O(void 0)}},re=async e=>{let t=e.target.files?.[0];if(e.target.value=``,!t)return;m(void 0),g(void 0),S(void 0);let n=SE(await t.text(),t.name);n.ok?(v({filename:t.name,bundle:n.bundle,unnamedFormat:n.unnamedFormat}),b(N.includes(n.bundle.slug)?wE(n.bundle.slug,N):n.bundle.slug),w(n.bundle.files[0]?.path)):m(n.reason)},ie=()=>{v(void 0),b(``),S(void 0),w(void 0)},ae=async()=>{if(!_)return;S(void 0);let e=CE(y);if(!e.ok)S(e.reason);else if(N.includes(e.slug))S(`本机已经有 slug「${e.slug}」的工具,换一个名字再导入。`);else{E(!0);try{let t=await fetch(`/api/tools`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(jE(_.bundle,e.slug))}),n=await t.json();if(!t.ok||!n.id)throw Error(n.error??`HTTP ${t.status}`);await r(),g(`已导入「${_.bundle.name}」,它现在出现在工具栏里,所有工作区都能用。`),ie()}catch(e){m(`导入失败:${e instanceof Error?e.message:String(e)}`)}finally{E(!1)}}};return(0,z.useEffect)(()=>{D&&j.current?.scrollIntoView({block:`center`})},[D]),(0,la.createPortal)((0,B.jsx)(`div`,{className:`tool-overlay`,"data-tool-settings-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&i()},children:(0,B.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-settings-title`,"data-tool-settings":`1`,children:[(0,B.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,B.jsx)(`h2`,{className:`tool-dialog-title`,id:`tool-settings-title`,children:`⚙ 工具设置`}),(0,B.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-settings-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭工具设置`,onClick:i,children:`✕`})]}),(0,B.jsx)(`div`,{className:`tool-dialog-body`,children:_?(0,B.jsx)(WD,{pending:_,slugDraft:y,slugError:x,preview:C,busy:T,onSlugChange:e=>{b(e),S(void 0)},onPreviewChange:w,onCancel:ie,onConfirm:()=>void ae()}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`tool-prompt-card`,children:[(0,B.jsx)(`strong`,{children:`给 Agent 开发新工具`}),(0,B.jsx)(`p`,{className:`tool-hint`,children:`工具会挂载到 Super Pi 的统一 HTTP 服务,不需要再启动独立服务器。`}),(0,B.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-development-prompt":`1`,onClick:()=>void M(),children:d?`已复制`:`复制工具开发 Prompt`})]}),(0,B.jsx)(`div`,{className:`rail-section-head`,children:(0,B.jsx)(`h2`,{className:`rail-section-title`,children:`从预置列表添加`})}),(0,B.jsx)(`div`,{className:`tool-presets`,"data-tool-presets":m_.length,children:m_.map(n=>{let r=e.some(e=>e.kind===n.kind);return(0,B.jsxs)(`div`,{className:`tool-preset`,"data-tool-preset":n.kind,children:[(0,B.jsx)(`span`,{className:`tool-preset-glyph`,"aria-hidden":`true`,children:n.glyph}),(0,B.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,B.jsx)(`strong`,{children:n.name}),(0,B.jsx)(`small`,{children:n.blurb})]}),(0,B.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-add-preset":n.kind,disabled:r,title:r?`${n.name}已经在工具栏里了`:`添加${n.name}`,"aria-label":r?`${n.name}已添加`:`添加${n.name}`,onClick:()=>t(T_(e,n.kind)),children:r?`已添加`:`添加`})]},n.kind)})}),(0,B.jsx)(`div`,{className:`rail-section-head`,children:(0,B.jsx)(`h2`,{className:`rail-section-title`,children:`添加网址工具`})}),(0,B.jsx)(`p`,{className:`tool-hint`,children:`填一个网址,它会变成一个图标;点开后在弹窗里用按钮在新标签页打开。网址只接受 http / https / mailto。`}),(0,B.jsx)(`input`,{className:`tool-input`,"data-tool-url-input":`1`,value:a,maxLength:2048,placeholder:`https://example.com/工具`,"aria-label":`工具网址`,onChange:e=>{o(e.target.value),u(void 0)}}),(0,B.jsx)(`input`,{className:`tool-input`,"data-tool-url-name":`1`,value:s,maxLength:40,placeholder:`名称(可留空,默认用域名)`,"aria-label":`工具名称(可选)`,onChange:e=>c(e.target.value)}),(0,B.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-url-add":`1`,disabled:!a.trim(),onClick:()=>{let n=b_(a);n.ok?e.length>=32?u(`工具最多 32 个,先删掉一个再加。`):(t([...e,{id:w_(`link`,e.map(e=>e.id)),kind:`link`,name:s.trim()||GD(n.url),glyph:`↗`,url:n.url}]),o(``),c(``),u(void 0)):u(n.reason)},children:`添加网址工具`}),l&&(0,B.jsx)(`p`,{className:`tool-error`,"data-tool-error":`1`,role:`alert`,children:l}),(0,B.jsxs)(`p`,{className:`tool-hint`,"data-tool-scope-note":`1`,children:[`能自定义到哪:从上面挑预置工具,或自己填一个网址。`,(0,B.jsx)(`b`,{children:`没有开放「写一段脚本来执行」这一档`}),`——它在浏览器里等同于任意代码执行,会拿着本应用的权限跑。计算器是手写的算术解析器,不含 eval,也认不出变量名。`]}),(0,B.jsx)(`div`,{className:`rail-section-head`,children:(0,B.jsxs)(`h2`,{className:`rail-section-title`,children:[`已安装的全局工具(`,n.length,`)`]})}),n.length===0?(0,B.jsx)(`p`,{className:`tool-hint`,"data-tool-mounted-empty":`1`,children:`还没有通过 tool_register 注册的工具。上面复制那段 Prompt,让 Agent 写一个。`}):(0,B.jsx)(`div`,{className:`tool-presets`,"data-tool-mounted-list":n.length,children:n.map(e=>{let t=kE(e.environmentState);return(0,B.jsxs)(`div`,{className:`tool-share-row`,"data-tool-share-row":e.id,children:[(0,B.jsx)(`span`,{className:`tool-preset-glyph`,"aria-hidden":`true`,children:`🧩`}),(0,B.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,B.jsx)(`strong`,{children:e.name}),(0,B.jsx)(`small`,{"data-tool-env":e.environmentState?.state??`unknown`,children:t?`${t.warn?`⚠ `:``}${t.text}${e.environmentState?.detail?` · ${e.environmentState.detail}`:``}`:`环境未知`}),e.permissions?.llm&&(0,B.jsx)(`small`,{"data-tool-model":`1`,children:`⚠ 会调用模型`})]}),(0,B.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export":e.id,title:`导出${e.name},得到一个可以发给别人导入的文件`,"aria-label":`导出${e.name}`,onClick:()=>te(e),children:`导出`})]},e.id)})}),D&&(0,B.jsxs)(`div`,{className:`tool-share-review`,ref:j,"data-tool-export-name":`1`,children:[(0,B.jsxs)(`h3`,{className:`tool-share-title`,children:[`导出「`,D.tool.name,`」`]}),(0,B.jsxs)(`label`,{className:`tool-hint`,children:[`文件名(发给别人的就是这个文件)`,(0,B.jsx)(`input`,{className:`tool-input`,value:D.name,"aria-label":`导出文件名`,"data-tool-export-input":`1`,onChange:e=>O({...D,name:e.target.value})})]}),k&&(0,B.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-export-name-error":`1`,children:k}),(0,B.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export-cancel":`1`,onClick:()=>{O(void 0),A(void 0)},children:`取消`}),(0,B.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-export-confirm":`1`,onClick:()=>void ne(D.tool,D.name),children:`导出`})]})]}),h&&(0,B.jsx)(`p`,{className:`tool-hint`,"data-tool-share-notice":`1`,children:h}),p&&(0,B.jsx)(`p`,{className:`tool-error`,"data-tool-share-error":`1`,role:`alert`,children:p}),(0,B.jsx)(`div`,{className:`rail-section-head`,children:(0,B.jsx)(`h2`,{className:`rail-section-title`,children:`从文件导入`})}),(0,B.jsxs)(`p`,{className:`tool-hint`,children:[`收到别人分享的工具文件(`,(0,B.jsx)(`code`,{children:vE}),`)?导入后它出现在工具栏里,所有工作区都能用。`,(0,B.jsx)(`b`,{children:`导入前会先给你看这个包里有什么。`})]}),(0,B.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-pick":`1`,onClick:()=>ee.current?.click(),children:`选择文件…`}),(0,B.jsx)(`input`,{ref:ee,type:`file`,accept:`.json,application/json`,style:{display:`none`},"data-tool-import-input":`1`,onChange:e=>void re(e)})]})})]})}),document.body)}function WD({pending:e,slugDraft:t,slugError:n,preview:r,busy:i,onSlugChange:a,onPreviewChange:o,onCancel:s,onConfirm:c}){let l=e.bundle,u=l.files.reduce((e,t)=>e+new TextEncoder().encode(t.content).length,0),d=OE(l),f=DE(l),p=l.files.find(e=>e.path===r)??l.files[0];return(0,B.jsxs)(`div`,{className:`tool-share-review`,"data-tool-import-review":`1`,children:[(0,B.jsx)(`h3`,{className:`tool-share-title`,"data-tool-import-name":`1`,children:l.name}),l.description&&(0,B.jsx)(`p`,{className:`tool-hint`,"data-tool-import-desc":`1`,children:l.description}),e.unnamedFormat&&(0,B.jsx)(`p`,{className:`tool-import-note`,"data-tool-import-unbranded":`1`,children:`这个文件没有 Super Pi 的工具标记,已按内容形状读取——粘出来的 tool_register 参数也认。`}),(0,B.jsxs)(`p`,{className:`tool-hint`,"data-tool-import-files":`1`,children:[l.files.length,` 个文件 · 共 `,AE(u)]}),(0,B.jsx)(`p`,{className:`tool-hint`,"data-tool-import-paths":`1`,children:l.files.map(e=>e.path).join(` · `)}),l.script&&(0,B.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-script":l.script.path,children:[(0,B.jsxs)(`b`,{children:[`⚠ 含 Python 脚本 `,l.script.path]}),(0,B.jsx)(`br`,{}),`导入后运行这个工具时,这段代码会在本机上执行,权限和你自己的 Python 一样(能读你的文件、能联网)。 可以先展开下面的文件列表把它读完。`]}),(0,B.jsxs)(`p`,{className:d.tone===`warn`?`tool-import-warn`:`tool-import-note`,"data-tool-import-env":d.tone,children:[(0,B.jsxs)(`b`,{children:[d.tone===`warn`?`⚠ `:`✓ `,d.text]}),l.environment?.fingerprint?.python&&(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`br`,{}),`导出方环境:Python `,l.environment.fingerprint.python,` / `,l.environment.fingerprint.platform,`。版本对不上时会标出来,但不会拦住你运行。`]})]}),f&&(0,B.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-model":`1`,children:[(0,B.jsx)(`b`,{children:`⚠ 这个工具可以调用模型`}),(0,B.jsx)(`br`,{}),f.text,`。模型由 Super Pi 通过 Pi 调用(凭据和模型选择都在 Super Pi 这边),工具只拿到文字。`]}),(0,B.jsxs)(`details`,{className:`tool-import-files`,"data-tool-import-filebox":l.files.length,children:[(0,B.jsxs)(`summary`,{children:[`查看文件(`,l.files.length,`)`]}),(0,B.jsx)(`div`,{className:`tool-share-tabs`,children:l.files.map(e=>(0,B.jsx)(`button`,{type:`button`,className:`tool-share-tab`,"aria-pressed":e.path===p?.path,"data-tool-import-file":e.path,onClick:()=>o(e.path),children:e.path},e.path))}),(0,B.jsx)(`pre`,{className:`tool-import-code`,"data-tool-import-code":p?.path,children:p?.content??``})]}),(0,B.jsxs)(`label`,{className:`tool-hint`,"data-tool-import-slug":`1`,children:[`导入后的 slug(工具的短名字,也是它在磁盘上的目录名)`,(0,B.jsx)(`input`,{className:`tool-input`,value:t,"aria-label":`导入后的 slug`,onChange:e=>a(e.target.value)})]}),n&&(0,B.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-import-slug-error":`1`,children:n}),(0,B.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-import-cancel":`1`,onClick:s,children:`取消`}),(0,B.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-confirm":`1`,disabled:i,onClick:c,children:i?`导入中…`:`导入`})]})]})}function GD(e){let t=e.replace(/^[./]+/,``).slice(0,30).trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(e))return t||e.slice(0,30);try{return new URL(e,typeof window>`u`?`http://localhost`:window.location.href).hostname||t||e.slice(0,30)}catch{return e.slice(0,30)}}function KD({tool:e,onClose:t}){return(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,la.createPortal)((0,B.jsx)(`div`,{className:`tool-overlay`,"data-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,B.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-dialog-title`,"data-tool-dialog":e.id,children:[(0,B.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,B.jsxs)(`h2`,{className:`tool-dialog-title`,id:`tool-dialog-title`,children:[(0,B.jsx)(`span`,{className:`tool-dialog-glyph`,"aria-hidden":`true`,children:e.glyph}),e.name]}),(0,B.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭${e.name}`,onClick:t,children:`✕`})]}),(0,B.jsxs)(`div`,{className:`tool-dialog-body`,children:[e.kind===`calculator`&&(0,B.jsx)(JD,{}),e.kind===`timestamp`&&(0,B.jsx)(YD,{}),e.kind===`link`&&(0,B.jsx)(XD,{tool:e})]})]})}),document.body)}function qD({image:e,onClose:t}){return(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,la.createPortal)((0,B.jsx)(`div`,{className:`lightbox-overlay`,"data-lightbox-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,B.jsxs)(`div`,{className:`lightbox-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`lightbox-title`,"data-lightbox-dialog":`1`,children:[(0,B.jsxs)(`div`,{className:`lightbox-head`,children:[(0,B.jsx)(`h2`,{className:`lightbox-title`,id:`lightbox-title`,children:e.name||`图片大图`}),(0,B.jsx)(`button`,{type:`button`,className:`lightbox-close`,"data-lightbox-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭大图`,onClick:t,children:`✕`})]}),(0,B.jsx)(`div`,{className:`lightbox-body`,children:(0,B.jsx)(`img`,{src:e.url,alt:e.name||`图片大图`,className:`lightbox-image`})})]})}),document.body)}function JD(){let[e,t]=(0,z.useState)(`12 * (3 + 4)`),n=z_(e),r=e=>{t(t=>t+e)};return(0,B.jsxs)(`div`,{className:`tool-calc`,"data-tool-calc":`1`,children:[(0,B.jsx)(`input`,{className:`tool-input tool-calc-input`,"data-calc-input":`1`,value:e,maxLength:200,"aria-label":`算式`,spellCheck:!1,autoComplete:`off`,placeholder:`例如 (12 + 8) / 4`,onChange:e=>{t(e.target.value)},onKeyDown:e=>{e.key===`Enter`&&e.preventDefault()}}),(0,B.jsx)(`div`,{className:`tool-calc-keys`,"data-calc-keys":`1`,children:[[`7`,`7`],[`8`,`8`],[`9`,`9`],[`÷`,`/`],[`(`,`(`],[`)`,`)`],[`4`,`4`],[`5`,`5`],[`6`,`6`],[`×`,`*`],[`^`,`^`],[`%`,`%`],[`1`,`1`],[`2`,`2`],[`3`,`3`],[`-`,`-`],[`←`,`back`],[`C`,`clear`],[`0`,`0`],[`.`,`.`],[`+`,`+`]].map(([e,n])=>(0,B.jsx)(`button`,{type:`button`,className:`tool-calc-key`,"data-calc-key":n,"aria-label":e===`C`?`清空`:e===`←`?`退格`:`输入 ${e}`,onClick:()=>{n===`clear`?t(``):n===`back`?t(e=>e.slice(0,-1)):r(n)},children:e},e))}),n.ok?(0,B.jsx)(`p`,{className:`tool-calc-result`,"data-calc-result":`1`,"data-calc-value":String(n.value),children:B_(n.value)}):(0,B.jsx)(`p`,{className:`tool-calc-error`,"data-calc-error":`1`,role:`alert`,children:n.reason})]})}function YD(){let[e,t]=(0,z.useState)(``),n=V_(e),r=n.ok?U_(n.ms):null;return(0,B.jsxs)(`div`,{className:`tool-stamp`,"data-tool-stamp":`1`,children:[(0,B.jsx)(`input`,{className:`tool-input`,"data-stamp-input":`1`,value:e,maxLength:64,spellCheck:!1,"aria-label":`时间戳或日期`,placeholder:`1757000000 或 2026-10-08T09:00:00`,onChange:e=>t(e.target.value)}),r?(0,B.jsxs)(`dl`,{className:`tool-stamp-out`,"data-stamp-result":`1`,children:[(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`本地时间`}),(0,B.jsx)(`dd`,{"data-stamp-local":`1`,children:r.local})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`ISO(UTC)`}),(0,B.jsx)(`dd`,{"data-stamp-iso":`1`,children:r.iso})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`秒`}),(0,B.jsx)(`dd`,{"data-stamp-seconds":`1`,children:r.seconds})]}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`dt`,{children:`毫秒`}),(0,B.jsx)(`dd`,{"data-stamp-ms":`1`,children:r.milliseconds})]})]}):(0,B.jsx)(`p`,{className:`tool-stamp-error`,"data-stamp-error":`1`,role:`alert`,children:n.ok?`这个日期无法显示。`:n.reason})]})}function XD({tool:e}){let[t,n]=(0,z.useState)(!1),r=async()=>{let e=await JE(`请为 Super Pi 开发一个全局右侧栏工具并自动挂载。不要启动独立 HTTP 服务器。通过内置 tool_register 提交完整的 HTML/JS/CSS 文件;工具将被 Super Pi 保存并在所有 workspace 可用。如需计算,注册一个 Python 脚本(不接受 shell 命令),参数经 JSON stdin 传入,stdout 只输出 JSON 结果。在页面里加载 ./super-pi-tool.js,使用 SuperPiTool.run(params)、wait(runId)、get(runId) 和 cancel(runId) 执行、等待、查看和取消任务。它们会自动绑定当前工具;不要调用 /api/exec,也不要猜测 toolId。`);n(e),window.setTimeout(()=>n(!1),1800)};return(0,B.jsxs)(`div`,{className:`tool-link`,"data-tool-link":e.id,children:[(0,B.jsx)(`p`,{className:`tool-hint`,children:`这是旧版外部网页链接;新工具由 Super Pi 统一托管,并可选绑定受控 Python 脚本。`}),(0,B.jsx)(`code`,{className:`tool-link-url`,"data-tool-link-url":e.id,children:e.url}),(0,B.jsxs)(`div`,{className:`tool-link-actions`,children:[(0,B.jsx)(`a`,{className:`tool-link-open`,"data-tool-link-open":e.id,href:e.url,target:`_blank`,rel:`noopener noreferrer`,title:e.url,children:`在新标签页打开 ↗`}),(0,B.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-copy-prompt":e.id,onClick:()=>void r(),children:t?`已复制`:`复制开发 Prompt`})]}),/^https?:\/\//i.test(e.url??``)&&(0,B.jsx)(`iframe`,{className:`tool-link-frame`,"data-tool-frame":e.id,src:e.url,title:e.name,sandbox:`allow-forms allow-modals allow-pointer-lock allow-popups allow-same-origin allow-scripts`,referrerPolicy:`no-referrer`})]})}var ZD=`(max-width: 1100px)`,QD=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function $D({tool:e,onClose:t}){return(0,z.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,la.createPortal)((0,B.jsx)(`div`,{className:`tool-overlay`,"data-mounted-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,B.jsxs)(`div`,{className:`tool-dialog`,"data-mounted-tool-dialog":e.id,role:`dialog`,"aria-modal":`true`,children:[(0,B.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,B.jsxs)(`h2`,{className:`tool-dialog-title`,children:[`🧩 `,e.name]}),(0,B.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,onClick:t,children:`✕`})]}),(0,B.jsx)(`div`,{className:`tool-dialog-body`,children:(0,B.jsx)(`iframe`,{className:`tool-link-frame`,src:`/tools/${encodeURIComponent(e.id)}/`,title:e.name,sandbox:`allow-forms allow-modals allow-popups allow-scripts`,referrerPolicy:`no-referrer`})})]})}),document.body)}function eO(e,t,n){let r=Math.max(0,Math.round(n)-480),i=QD(520,180,Math.max(180,r-240)),a=QD(Math.round(e),180,i),o=QD(640,240,Math.max(240,r-a));return{sidebar:a,rail:QD(Math.round(t),240,o),sidebarMin:180,sidebarMax:i,railMin:240,railMax:o,sumCap:r}}var tO=`super-pi.rail-widths.v1`,nO=`super-pi.reader-state.v1`,rO=32,iO=48,aO=e=>{e.dataset.programmaticScroll=`true`,window.setTimeout(()=>{delete e.dataset.programmaticScroll},0)};function oO(){try{if(typeof window>`u`)return{conversations:{}};let e=JSON.parse(window.localStorage.getItem(`super-pi.reader-state.v1`)??`null`);if(!e||typeof e!=`object`)return{conversations:{}};let t={};if(e.conversations&&typeof e.conversations==`object`)for(let[n,r]of Object.entries(e.conversations)){let e=r;typeof e.followTail==`boolean`&&(t[n]={followTail:e.followTail,scrollTop:Number.isFinite(e.scrollTop)?Math.max(0,Number(e.scrollTop)):0,...typeof e.anchorKey==`string`?{anchorKey:e.anchorKey}:{},...Number.isFinite(e.anchorOffset)?{anchorOffset:Number(e.anchorOffset)}:{}})}let n={};if(e.readAt&&typeof e.readAt==`object`)for(let[t,r]of Object.entries(e.readAt))typeof r==`string`&&(n[t]=r);return{activeId:typeof e.activeId==`string`?e.activeId:void 0,workspaceId:typeof e.workspaceId==`string`?e.workspaceId:void 0,conversations:t,readAt:n}}catch{return{conversations:{}}}}function sO(e){try{typeof window<`u`&&window.localStorage.setItem(nO,JSON.stringify(e))}catch{}}var cO=`super-pi.session-tabs.v1`;function lO(){try{if(typeof window>`u`)return{ids:[]};let e=JSON.parse(window.sessionStorage.getItem(`super-pi.session-tabs.v1`)??`null`);if(!e||typeof e!=`object`)return{ids:[]};let t=e,n=Array.isArray(t.ids)?[...new Set(t.ids.filter(e=>typeof e==`string`))]:[];return{ids:n,activeId:typeof t.activeId==`string`&&n.includes(t.activeId)?t.activeId:void 0}}catch{return{ids:[]}}}function uO(e,t){try{typeof window<`u`&&window.sessionStorage.setItem(cO,JSON.stringify({ids:e,...t&&e.includes(t)?{activeId:t}:{}}))}catch{}}function dO(){try{if(typeof window>`u`)return{};let e=window.localStorage.getItem(tO);if(e===null)return{};let t=JSON.parse(e),n=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.round(e):void 0;return{sidebar:n(t.sidebar),rail:n(t.rail)}}catch{return{}}}function fO(e){try{if(typeof window>`u`)return;window.localStorage.setItem(tO,JSON.stringify(e))}catch{}}function pO({side:e,width:t,min:n,max:r,label:i,onWidth:a}){let[o,s]=(0,z.useState)(!1),c=e=>e.shiftKey?64:16;return(0,B.jsx)(`div`,{className:`rail-resizer rail-resizer-${e}${o?` rail-resizer-dragging`:``}`,"data-rail-resizer":e,"data-rail-resizer-dragging":o?`true`:`false`,"data-rail-resizer-width":t,role:`separator`,"aria-orientation":`vertical`,"aria-label":i,"aria-valuenow":t,"aria-valuemin":n,"aria-valuemax":r,tabIndex:0,onMouseDown:i=>{i.preventDefault(),i.currentTarget.focus();let o=i.clientX,c=t;s(!0);let l=document.body,u=l.style.cursor,d=l.style.userSelect;l.style.cursor=`col-resize`,l.style.userSelect=`none`;let f=t=>{let i=e===`left`?t.clientX-o:o-t.clientX;a(QD(c+i,n,r))},p=()=>{l.style.cursor=u,l.style.userSelect=d,s(!1),window.removeEventListener(`mousemove`,f),window.removeEventListener(`mouseup`,p)};window.addEventListener(`mousemove`,f),window.addEventListener(`mouseup`,p)},onKeyDown:i=>{let o=c(i);i.key===`ArrowLeft`?(i.preventDefault(),a(QD(e===`left`?t-o:t+o,n,r))):i.key===`ArrowRight`?(i.preventDefault(),a(QD(e===`left`?t+o:t-o,n,r))):i.key===`Home`?(i.preventDefault(),a(n)):i.key===`End`&&(i.preventDefault(),a(r))}})}var mO=`super-pi.composer-height.v1`,hO=148,gO=.55,_O=()=>Math.max(hO,Math.round((typeof window>`u`?800:window.innerHeight)*gO)),vO=e=>{let t=Number.isFinite(e)?e:hO;return Math.round(Math.min(_O(),Math.max(hO,t)))},yO=()=>{try{let e=window.localStorage.getItem(mO);return e===null?hO:vO(Number(e))}catch{return hO}};function bO({height:e,onHeight:t}){let[n,r]=(0,z.useState)(!1),i=e=>e.shiftKey?64:16,a=_O();return(0,B.jsx)(`div`,{className:`composer-resize${n?` composer-resize-dragging`:``}`,"data-composer-resize":`1`,"data-composer-resize-dragging":n?`true`:`false`,"data-composer-height":e,role:`separator`,"aria-orientation":`horizontal`,"aria-label":`调整消息编辑区高度`,"aria-valuenow":e,"aria-valuemin":hO,"aria-valuemax":a,tabIndex:0,onMouseDown:n=>{n.preventDefault(),n.currentTarget.focus();let i=n.clientY,a=e;r(!0);let o=document.documentElement,s=document.body.style.userSelect;document.body.style.cursor=`ns-resize`,document.body.style.userSelect=`none`;let c=e=>{let t=vO(a+(i-e.clientY));o.style.setProperty(`--composer-height`,`${t}px`)},l=()=>{document.body.style.cursor=``,document.body.style.userSelect=s;let n=Number.parseFloat(o.style.getPropertyValue(`--composer-height`));r(!1),window.removeEventListener(`mousemove`,c),window.removeEventListener(`mouseup`,l),t(Number.isFinite(n)?n:e)};window.addEventListener(`mousemove`,c),window.addEventListener(`mouseup`,l)},onKeyDown:n=>{let r=i(n);n.key===`ArrowUp`?(n.preventDefault(),t(vO(e+r))):n.key===`ArrowDown`?(n.preventDefault(),t(vO(e-r))):n.key===`Home`?(n.preventDefault(),t(hO)):n.key===`End`?(n.preventDefault(),t(a)):n.key===`PageUp`?(n.preventDefault(),t(vO(e+96))):n.key===`PageDown`&&(n.preventDefault(),t(vO(e-96)))}})}function xO(){let[e,t]=(0,z.useState)(ME),[n,r]=(0,z.useState)([]),i=(0,z.useRef)([]),a=(0,z.useRef)(null);a.current||=oO();let o=(0,z.useRef)(null);o.current||=lO();let s=n.reduce((e,t)=>t.apply(e),e),[c,l]=(0,z.useState)(o.current.activeId??a.current.activeId),[u,d]=(0,z.useState)(!1),[f,p]=(0,z.useState)(),[m,h]=(0,z.useState)({}),[g,_]=(0,z.useState)(a.current.workspaceId),[v,y]=(0,z.useState)(o.current.ids),[b,x]=(0,z.useState)(!1),[S,C]=(0,z.useState)(!1),w=(0,z.useRef)(void 0),T=(0,z.useRef)(a.current.conversations),E=(0,z.useRef)(v);E.current=v;let D=(0,z.useRef)(a.current.readAt??{}),[O,k]=(0,z.useState)(0),A=(0,z.useRef)(null),ee=(0,z.useRef)(null),j=(0,z.useRef)(void 0),M=(0,z.useRef)(a.current.activeId),[N,te]=(0,z.useState)({followTail:!0,scrollTop:0}),ne=(0,z.useRef)(!1),re=(0,z.useRef)(new Map),ie=(0,z.useRef)(void 0),ae=(0,z.useRef)([]),oe=(0,z.useRef)(void 0),se=(0,z.useCallback)(()=>{if(oe.current!==void 0&&(cancelAnimationFrame(oe.current),oe.current=void 0),!ae.current.length)return;let e=ae.current;ae.current=[];let n=new Map;for(let t of e){let e=`${t.conversationId}\u0000${t.messageId}`,r=n.get(e)??[];r.push(t),n.set(e,r)}t(e=>({...e,conversations:e.conversations.map(e=>{let t=e.messages.map(t=>{let r=n.get(`${e.id}\u0000${t.id}`);if(!r)return t;let i={...t};for(let e of r){if(e.type===`message.delta`){i.content+=e.delta;continue}if(i.thinkingActive=e.active,!e.delta)continue;let t=e.at??i.content.length,n=[...i.thinkingBlocks??[]],r=n.at(-1);r&&r.at===t&&(e.blockIndex===void 0||e.blockIndex===n.length-1)?n[n.length-1]={...r,text:r.text+e.delta}:n.push({at:t,text:e.delta}),i={...i,thinking:(i.thinking??``)+e.delta,thinkingBlocks:n}}return i});return t.every((t,n)=>t===e.messages[n])?e:{...e,messages:t}})}))},[]),ce=(0,z.useCallback)(e=>{let t=ae.current,n=t.at(-1);n&&n.type===e.type&&n.conversationId===e.conversationId&&n.messageId===e.messageId&&(e.type!==`message.thinking`||n.type===`message.thinking`&&n.at===e.at&&n.active===e.active&&n.blockIndex===e.blockIndex)?t[t.length-1]={...e,delta:n.delta+e.delta}:t.push(e),oe.current===void 0&&(oe.current=requestAnimationFrame(se))},[se]),le=(0,z.useCallback)(e=>{ie.current=e},[]),[ue,de]=(0,z.useState)({}),[fe,pe]=(0,z.useState)(()=>{if(typeof window>`u`)return``;try{return window.localStorage.getItem(`super-pi.user-nickname`)??``}catch{return``}}),me=e=>{let t=e.slice(0,24);pe(t);try{window.localStorage.setItem(`super-pi.user-nickname`,t)}catch{}},he=fe.trim()||`你`,[ge,P]=(0,z.useState)([]),[_e,ve]=(0,z.useState)([]),[ye,be]=(0,z.useState)(new Map),[xe,Se]=(0,z.useState)(new Map),[Ce,we]=(0,z.useState)(),[Te,Ee]=(0,z.useState)(),[De,Oe]=(0,z.useState)(),[ke,Ae]=(0,z.useState)([]),[je,Me]=(0,z.useState)([]),[Ne,Pe]=(0,z.useState)(),[Fe,Ie]=(0,z.useState)(),[Le,Re]=(0,z.useState)(),[ze,Be]=(0,z.useState)(`idle`),[Ve,He]=(0,z.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1100px)`).matches),[Ue,We]=(0,z.useState)(`chat`),[Ge,Ke]=(0,z.useState)(()=>typeof window>`u`?1440:window.innerWidth);(0,z.useEffect)(()=>{let e=()=>Ke(window.innerWidth);return window.addEventListener(`resize`,e),e(),()=>window.removeEventListener(`resize`,e)},[]);let[qe,Je]=(0,z.useState)(dO),Ye=eO(qe.sidebar??270,qe.rail??320,Ge);(0,z.useEffect)(()=>{fO({sidebar:Ye.sidebar,rail:Ye.rail})},[Ye.sidebar,Ye.rail]);let Xe=e=>Je(t=>({...t,sidebar:e})),Ze=e=>Je(t=>({...t,rail:e})),[Qe,$e]=(0,z.useState)(null);(0,z.useEffect)(()=>{$e(yO())},[]),(0,z.useEffect)(()=>{Qe!==null&&document.documentElement.style.setProperty(`--composer-height`,`${Qe}px`)},[Qe]);let et=e=>{let t=vO(e);$e(t);try{window.localStorage.setItem(mO,String(t))}catch{}};(0,z.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(ZD),t=e=>{e.matches&&He(!0)};return e.addEventListener(`change`,t),e.matches&&He(!0),()=>e.removeEventListener(`change`,t)},[]);let[tt,nt]=(0,z.useState)({}),[rt,it]=(0,z.useState)({}),[at,ot]=(0,z.useState)({}),[st,ct]=(0,z.useState)(),[lt,ut]=(0,z.useState)(),[dt,ft]=(0,z.useState)(),pt=(0,z.useRef)(new Map),[mt,ht]=(0,z.useState)({}),gt=(0,z.useRef)(new Set),[_t,vt]=(0,z.useState)([]),[yt,bt]=(0,z.useState)([]),[xt,St]=(0,z.useState)(),[Ct,wt]=(0,z.useState)(!1),Tt=(0,z.useRef)(null),Et=(0,z.useRef)(!1),Dt=(0,z.useRef)(0),Ot=(0,z.useRef)([]),kt=(0,z.useRef)(void 0),At=(0,z.useRef)(!1),jt=(0,z.useRef)(new Set),Mt=(0,z.useRef)(new Map),Nt=(0,z.useRef)(new Map),[Pt,Ft]=(0,z.useState)(()=>Date.now());(0,z.useEffect)(()=>{let e=window.setInterval(()=>Ft(Date.now()),3e4);return()=>window.clearInterval(e)},[]);let It=(0,z.useMemo)(()=>s.conversations.filter(e=>!e.archivedAt),[s.conversations]),F=(0,z.useMemo)(()=>It.find(e=>e.id===c)??It.find(e=>e.workspaceId===g)??(g&&s.workspaces.some(e=>e.id===g)?void 0:It[0]),[c,It,g,s.workspaces]);(0,z.useEffect)(()=>{p(void 0)},[c,g]);let Lt=(0,z.useMemo)(()=>s.workspaces.find(e=>e.id===g)??s.workspaces[0],[s.workspaces,g]),Rt=(0,z.useRef)(g);Rt.current=g,(0,z.useEffect)(()=>{F&&_(F.workspaceId)},[F?.id]),(0,z.useEffect)(()=>{kt.current=c},[c]),(0,z.useEffect)(()=>{j.current=F?.id},[F?.id]),(0,z.useEffect)(()=>{let e=F?.id;if(!e)return;let t=s.conversations.find(t=>t.id===e);if(!t)return;let n=D.current[e];D.current[e]=t.updatedAt,n!==t.updatedAt&&k(e=>e+1),sO({activeId:kt.current,workspaceId:F?.workspaceId??g,conversations:T.current,readAt:D.current})},[F?.id,s.conversations]),(0,z.useEffect)(()=>{u&&c&&sO({activeId:c,workspaceId:F?.workspaceId??g,conversations:T.current})},[c,F?.workspaceId,u,g]),(0,z.useEffect)(()=>{let e=A.current;if(!e||!F?.id)return;let t=F.id;ne.current=!1;let n=T.current[t]??{followTail:!0,scrollTop:0};te(n),requestAnimationFrame(()=>{if(A.current===e){if(n.followTail)aO(e),e.scrollTop=e.scrollHeight;else{let t=n.anchorKey?e.querySelector(`[data-transcript-key="${CSS.escape(n.anchorKey)}"]`):null;e.scrollTop=t?Math.max(0,e.scrollTop+t.getBoundingClientRect().top-(n.anchorOffset??0)-e.getBoundingClientRect().top):n.scrollTop}}}),M.current=void 0},[F?.id]);let zt=(0,z.useCallback)((e,t=!1,n=!1)=>{let r=j.current;if(!r)return;let i=e.scrollHeight-e.clientHeight-e.scrollTop,a=T.current[r]??{followTail:!0,scrollTop:0},o=t?!1:n?!0:a.followTail?i<=iO:i<=rO,s,c;if(!o){let t=e.getBoundingClientRect().top,n=[...e.querySelectorAll(`[data-transcript-key]`)].find(e=>e.getBoundingClientRect().bottom>t);s=n?.dataset.transcriptKey,c=n?n.getBoundingClientRect().top-t:void 0}let l={followTail:o,scrollTop:e.scrollTop,...s?{anchorKey:s,anchorOffset:c}:{}};ne.current=!o,T.current[r]=l,te(l),sO({activeId:r,workspaceId:Rt.current,conversations:T.current})},[]),Bt=mt[F?.id??``]??{text:``,images:[],attachments:[],uploading:0},Vt=Bt.text,Ht=Bt.images,Ut=Bt.attachments,Wt=Bt.uploading,Gt=(e,t)=>ht(n=>({...n,[e]:t(n[e]??{text:``,images:[],attachments:[],uploading:0})})),Kt=e=>Gt(F?.id??``,t=>({...t,text:e})),qt=e=>Gt(F?.id??``,t=>({...t,attachments:t.attachments.some(t=>t.kind===e.kind&&t.id===e.id)?t.attachments:[...t.attachments,e]})),Jt=(e,t)=>Gt(F?.id??``,n=>({...n,attachments:n.attachments.filter(n=>n.kind!==e||n.id!==t)})),[Yt,Xt]=(0,z.useState)({visible:!1,query:``,rect:null}),Zt=e=>Gt(F?.id??``,t=>({...t,images:typeof e==`function`?e(t.images):e})),Qt=v.length>0?v:F?[F.id]:[],$t=(0,z.useMemo)(()=>Qt.map(e=>It.find(t=>t.id===e)).filter(e=>e!==void 0),[Qt,It]);(0,z.useEffect)(()=>{if(!b)return;let e=new Set(It.map(e=>e.id));y(t=>{let n=t.filter(t=>e.has(t));return n.length===t.length?t:n})},[b,It]),(0,z.useEffect)(()=>{uO(v,c)},[c,v]);let en=(0,z.useCallback)(e=>{l(e);let t=It.find(t=>t.id===e)?.workspaceId;t&&_(t),yn(`session`),y(t=>t.includes(e)?t:t.length>0?[...t,e]:[...F?.id&&F.id!==e?[F.id]:[],e])},[F]),tn=(0,z.useCallback)(e=>{let t=v.indexOf(e);if(t<0)return;let n=v.filter(t=>t!==e);if(y(n),F?.id!==e)return;let r=n[Math.min(t,n.length-1)];r&&l(r)},[v,F]),I=Fg(g),nn=(0,z.useRef)(I.setChangedFor),rn=(0,z.useRef)(I.setIndex),an=(0,z.useRef)(I.setIndexStatus);(0,z.useEffect)(()=>{nn.current=I.setChangedFor},[I.setChangedFor]),(0,z.useEffect)(()=>{rn.current=I.setIndex},[I.setIndex]),(0,z.useEffect)(()=>{an.current=I.setIndexStatus},[I.setIndexStatus]);let[on,sn]=(0,z.useState)(OD[0].id),[cn,ln]=(0,z.useState)({}),un=(F?.id?cn[F.id]:void 0)??on,dn=(0,z.useCallback)(e=>{sn(e),F?.id&&ln(t=>({...t,[F.id]:e}))},[F?.id]),[fn,pn]=(0,z.useState)(!1),[mn,hn]=(0,z.useState)(!1),[gn,_n]=(0,z.useState)(),[vn,yn]=(0,z.useState)(`session`),[bn,xn]=(0,z.useState)();(0,z.useEffect)(()=>{vn===`file`&&!I.active&&yn(`session`)},[vn,I.active]),(0,z.useEffect)(()=>{vn===`diff`&&!bn&&yn(`session`)},[vn,bn]),(0,z.useEffect)(()=>{I.restoredActive&&yn(`file`)},[I.restoredActive]);let Sn=(0,z.useCallback)(e=>{xn(e),yn(`diff`),sn(`files`)},[]),[Cn,wn]=(0,z.useState)({diff:null,loading:!1,error:``}),[Tn,En]=(0,z.useState)(`server`);(0,z.useEffect)(()=>{if(vn!==`diff`||!bn||!g)return;let e=!0;return wn({diff:null,loading:!0,error:``}),fetch(`/api/files/diff?workspaceId=${encodeURIComponent(g)}&path=${encodeURIComponent(bn)}`).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error??`HTTP ${e.status}`);return t}).then(t=>{e&&wn({diff:t,loading:!1,error:``})}).catch(t=>{e&&wn({diff:null,loading:!1,error:t instanceof Error?t.message:`读取差异失败`})}),()=>{e=!1}},[vn,bn,g]);let Dn=(0,z.useMemo)(()=>{if(!bn)return;let e=I.open.find(e=>e.path===bn);return e&&e.dirty?e.content:void 0},[bn,I.open]),On=(0,z.useCallback)(e=>{I.setActivePath(e),yn(`file`),sn(`files`)},[I.setActivePath]),kn=(0,z.useCallback)(async(e,t)=>{_n(t?{workspaceId:g,path:e.path,line:t,request:Date.now()}:void 0),await I.openFile(e),yn(`file`)},[I.openFile,g]);(0,z.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&e.shiftKey&&e.key.toLowerCase()===`f`?(e.preventDefault(),hn(!0)):(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`p`&&(e.preventDefault(),pn(!0))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let An=(0,z.useMemo)(()=>$t.map(e=>({id:`session:${e.id}`,rawId:e.id,kind:`session`,label:e.title,title:e.title,closable:$t.length>1||I.open.length>0,badge:(0,B.jsx)(MD,{state:jD(e,ge.some(t=>t.conversationId===e.id),D.current[e.id])})})),[$t,I.open.length,ge,s.conversations,O]),jn=(0,z.useMemo)(()=>I.open.map(e=>({id:`file:${e.path}`,rawId:e.path,kind:`file`,label:e.name,title:e.path,closable:!0,badge:e.dirty?(0,B.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[I.open]),Mn=(0,z.useMemo)(()=>[...An,...jn],[An,jn]),Nn=vn===`file`&&I.activePath?`file:${I.activePath}`:F?.id?`session:${F.id}`:void 0,Pn=(0,z.useCallback)(e=>{if(e.startsWith(`file:`)){let t=e.slice(5);On(t)}else if(e.startsWith(`session:`)){let t=e.slice(8);en(t)}},[On,en]),Fn=(0,z.useCallback)(e=>{if(e.startsWith(`file:`)){let t=e.slice(5);I.closeFile(t),I.activePath===t&&I.open.length<=1&&yn(`session`)}else if(e.startsWith(`session:`)){let t=e.slice(8);tn(t)}},[I,tn]),In=I.active,Ln=F?.id;(0,z.useEffect)(()=>{Ln&&!Ln.startsWith(`pending:`)&&Hn({type:`conversation.select`,conversationId:Ln})},[Ln]);let L=(e,t=`info`)=>{if(!e)return;let n=++Dt.current;ve(r=>[...r,{key:n,text:e,kind:t}]),Ot.current.push(window.setTimeout(()=>ve(e=>e.filter(e=>e.key!==n)),7e3))},Rn=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);if(n<0)return[t,...e];let r=[...e];return r[n]=t,r},zn=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);if(n<0)return[t,...e];let r=[...e];return r[n]=t,r},Bn=(e,t)=>{if(t.blocking)P(n=>[...n.filter(n=>n.conversationId!==e||n.request.requestId!==t.requestId),{conversationId:e,request:t}]);else if(t.method===`notify`)L(t.message||t.title,t.notifyType??`info`);else if(t.method===`setStatus`){let e=t.statusKey??``;be(n=>{let r=new Map(n);return t.statusText===void 0?r.delete(e):r.set(e,t.statusText),r})}else if(t.method===`setWidget`){let e=t.widgetKey??``;Se(n=>{let r=new Map(n);return t.widgetLines===void 0?r.delete(e):r.set(e,{lines:t.widgetLines,placement:t.widgetPlacement??`aboveEditor`}),r})}else t.method===`setTitle`?we(t.title):t.method===`set_editor_text`&&e===kt.current&&Kt(t.text??``)},Vn=(e,t,n)=>{P(n=>n.filter(n=>n.conversationId!==e||n.request.requestId!==t));let r=aD[n];r&&L(r,`warning`)};(0,z.useEffect)(()=>{let e=!1,n=0,o,s=()=>{if(e)return;let c=location.protocol===`https:`?`wss`:`ws`,u=new WebSocket(`${c}://${location.host}/ws`);w.current=u,u.onopen=()=>{if(!e){n=0,d(!0),u.send(JSON.stringify({type:`stream.configure`,coalesce:!0})),u.send(JSON.stringify({type:`catalog.fetch`,conversationId:kt.current})),u.send(JSON.stringify({type:`catalog.fetchAll`})),u.send(JSON.stringify({type:`agent.catalog.fetch`})),u.send(JSON.stringify({type:`subagent.catalog.fetch`}));for(let e of i.current)e.retry&&e.command&&u.send(JSON.stringify({...e.command,operationRequestId:e.id}))}},u.onclose=()=>{if(e)return;At.current=!1;let t=_E(i.current);for(let e of t.failed)e.onFailure?.();i.current=t.retry,r(t.retry),d(!1),o=window.setTimeout(s,Math.min(qE,KE*2**n++))},u.onmessage=({data:n})=>{if(e)return;let o=JSON.parse(n);if(o.type!==`message.delta`&&o.type!==`message.thinking`&&se(),o.type===`exec.output`){let e=re.current.get(o.sessionId)??``;re.current.set(o.sessionId,(e+o.data).slice(-512e3)),re.current.size>64&&re.current.delete(re.current.keys().next().value),window.dispatchEvent(new CustomEvent(`super-pi-exec-output`,{detail:o}))}else if(o.type===`exec.exit`)re.current.delete(o.sessionId);else if(o.type.startsWith(`terminal.`))ie.current?.(o);else if(o.type===`conversation.autoRename.result`){let e=pt.current.get(o.conversationId);e&&(pt.current.delete(o.conversationId),o.ok?e.resolve(o.title):e.reject(Error(o.error)))}else if(o.type===`message.thinking`)ce(o);else if(o.type===`state`){se(),At.current=!1;let e=kt.current,n=!!(e&&jt.current.has(e)),s=!(!e||o.state.conversations.some(t=>t.id===e)),c=n&&s&&e&&Mt.current.has(e)?{...o.state,conversations:[Mt.current.get(e),...o.state.conversations]}:o.state;e&&!s&&(jt.current.delete(e),Mt.current.delete(e)),i.current=i.current.filter(e=>!e.accepted?.(c)),r(i.current),t(c),x(!0),d(!0),l(e=>{let t=c.conversations.filter(e=>!e.archivedAt),n=a.current?.activeId,r=!!(e&&t.some(t=>t.id===e)),o=!!(e&&i.current.some(t=>t.temporaryId===e));return r||o?e:n&&t.some(e=>e.id===n)?n:t.find(e=>e.workspaceId===Rt.current)?.id}),_(e=>{let t=a.current?.workspaceId;return t&&c.workspaces.some(e=>e.id===t)?t:e&&(c.workspaces.some(t=>t.id===e)||i.current.some(t=>t.temporaryId===e))?e:c.workspaces[0]?.id})}else if(o.type===`message.delta`)ce(o);else if(o.type===`message.revert.result`)ci(void 0),ct(void 0),o.ok||p(o.message);else if(o.type===`operation.result`){let e=i.current.find(e=>e.id===o.requestId);if(i.current=i.current.filter(e=>e.id!==o.requestId),r(i.current),e?.temporaryId){let t=e.temporaryId;if(o.ok&&o.entityId){let e=Nt.current.get(t);e&&Mt.current.set(o.entityId,{...e,id:o.entityId}),jt.current.add(o.entityId)}l(n=>n===t?o.ok?o.entityId:e.previousActiveId:n),y(e=>e.flatMap(e=>e===t?o.ok&&o.entityId?[o.entityId]:[]:[e])),_(e=>e===t?o.ok?o.entityId:void 0:e)}o.ok||(e?.onFailure?.(o.message),p(o.message??`操作失败`))}else o.type===`tools.updated`?window.dispatchEvent(new Event(`super-pi-tools-updated`)):o.type===`files.changed`?nn.current(o.workspaceId,o.changes,o.dropped):o.type===`files.index`?o.workspaceId===Rt.current&&(rn.current(o.changed,o.removed),an.current(o.complete,o.skipped)):o.type===`error`?(p(o.message),At.current&&(At.current=!1,L(`重命名失败:${o.message}`,`error`))):o.type===`extension.ui`?Bn(o.conversationId,o.request):o.type===`extension.ui.closed`?Vn(o.conversationId,o.requestId,o.reason):o.type===`model.catalog`?(!o.conversationId||o.conversationId===kt.current)&&Ee(o.catalog):o.type===`model.catalog.all`?Oe(o.catalog):o.type===`providers.list`?(Ae(o.providers),Me(o.apis)):o.type===`agent.catalog`?Pe(o.catalog):o.type===`subagent.catalog`?Ie(o.catalog):o.type===`server.version`?(Re(o.version),o.version.needsRestart&&L(`检测到 Super Pi 代码已更新(v${o.version.runningVersion} → v${o.version.diskVersion}),请执行 /super_pi restart 重启服务生效`,`warning`)):o.type===`subagent.event`?t(e=>({...e,subagentRuns:Rn(e.subagentRuns??[],o.run)})):o.type===`workflow.event`?t(e=>({...e,workflows:zn(e.workflows??[],o.workflow)})):o.type===`message.tools`?t(e=>({...e,conversations:e.conversations.map(e=>e.id===o.conversationId?{...e,messages:e.messages.map(e=>e.id===o.messageId?{...e,toolCalls:o.toolCalls}:e)}:e)})):o.type===`conversation.fork.result`&&(hi(e=>e===o.conversationId?void 0:e),L(o.ok?`已从「${o.title}」分叉出新会话,放在侧边栏最上面;没有切换过去。${o.messagesCopied?`复制了 ${o.messagesCopied} 条消息。`:`原会话还没有消息,只复制了会话本身。`}`:`分叉失败:${o.message}`,o.ok?`info`:`error`))}};return s(),()=>{e=!0,se(),window.clearTimeout(o);for(let e of Ot.current)window.clearTimeout(e);w.current?.close()}},[ce,se]);let Hn=(0,z.useCallback)(e=>w.current?.readyState===WebSocket.OPEN&&(w.current.send(JSON.stringify(e)),!0),[]),Un=(e,t,n,a,o,s)=>{let c=w.current?.readyState===WebSocket.OPEN,l=gE(e);if(i.current.some(e=>e.key===t)||!c&&!l)return!1;let u=C_(),d={id:u,key:t,apply:n,temporaryId:a,previousActiveId:kt.current,onFailure:o,accepted:s,...l?{retry:!0,command:e}:{}};return i.current=[...i.current,d],r(i.current),c&&w.current.send(JSON.stringify({...e,operationRequestId:u})),!0},Wn=(e,t)=>n=>({...n,conversations:n.conversations.map(n=>n.id===e?{...n,...t}:n)}),Gn=(e,t)=>n=>({...n,workspaces:n.workspaces.map(n=>n.id===e?{...n,...t}:n)}),Kn=n.some(e=>e.key===`send:${F?.id}`||e.key===`configuration:${F?.id}`||e.temporaryId===F?.id||e.key===`archive:${F?.id}`),qn=(e,t,n,r,i)=>{e&&w.current?.send(JSON.stringify({type:`question.answer`,conversationId:e,messageId:t,callIndex:n,answers:r,cancelled:i}))},Jn=(e,t,n)=>Un({type:`extension.ui.answer`,conversationId:e,requestId:t,...n},`answer:${e}:${t}`,e=>e),Yn=F?.model??Te?.defaultModel,Xn=F?.thinkingLevel??Te?.defaultThinkingLevel,Zn=Te?.source===`pi`,Qn=!!Te?.models.find(e=>e.provider===Yn?.provider&&e.modelId===Yn?.modelId)?.imageInput,$n=(e,t)=>!e||!t?e:{...e,models:e.models.filter(e=>(s.modelFilterRules??[]).every(n=>{try{return!new RegExp(n.workspacePattern,`i`).test(t.name)||new RegExp(n.modelPattern,`i`).test(e.label)||new RegExp(n.modelPattern,`i`).test(`${e.provider}/${e.modelId}`)}catch{return!0}}))},er=($n(Te,s.workspaces.find(e=>e.id===F?.workspaceId))?.models??[]).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:e.detail,badge:tD(e),selected:Yn?.provider===e.provider&&Yn.modelId===e.modelId})),tr=(Te?.levels??[]).map(e=>({key:e,label:e,selected:e===Xn})),nr=e=>{if(!F)return;let[t,n]=e.split(`/`);t&&n&&Un({type:`conversation.model`,conversationId:F.id,provider:t,modelId:n},`configuration:${F.id}`,Wn(F.id,{model:Te?.models.find(e=>e.provider===t&&e.modelId===n)??{provider:t,modelId:n,label:n}}))},rr=e=>{F&&Un({type:`conversation.thinking`,conversationId:F.id,level:e},`configuration:${F.id}`,Wn(F.id,{thinkingLevel:e}))},ir=Ne?.agents.find(e=>e.id===F?.agentId),ar=[{key:ED,label:`跟随 Pi 默认`,detail:`不使用任何 agent 角色`,selected:!F?.agentId},...(Ne?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:F?.agentId===e.id}))],or=ir?.model,sr=!!(or&&F?.model&&F.model.provider===or.provider&&F.model.modelId===or.modelId);ir?.thinkingLevel&&(F?.thinkingLevel,ir.thinkingLevel);let cr=e=>{if(F){let t=Ne?.agents.find(t=>t.id===e);Un({type:`conversation.agent`,conversationId:F.id,agentId:e===ED?null:e},`configuration:${F.id}`,Wn(F.id,{agentId:t?.id,...t?.model?{model:{...t.model,label:t.model.modelId}}:{},...t?.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{}}))}},lr=ge.filter(e=>e.conversationId===F?.id),ur=(0,z.useMemo)(()=>(s.subagentRuns??[]).filter(e=>e.conversationId===F?.id),[s.subagentRuns,F?.id]),dr=(0,z.useMemo)(()=>(s.workflows??[]).filter(e=>e.conversationId===F?.id),[s.workflows,F?.id]),fr=(0,z.useMemo)(()=>new Map(dr.map(e=>[e.id,e])),[dr]),pr=(0,z.useMemo)(()=>new Map((Fe?.agents??[]).map(e=>[e.id,e.name])),[Fe]),mr=(0,z.useMemo)(()=>new Map((F?.messages??[]).map(e=>[e.id,e])),[F?.messages]),hr=(0,z.useMemo)(()=>new Map(ur.map(e=>[e.id,e])),[ur]),gr=(0,z.useMemo)(()=>{let e=new Map;for(let t of ur)t.originMessageId!==void 0&&t.originCallRow!==void 0&&e.set(`${t.originMessageId}:${t.originCallRow}`,t);return e},[ur]),_r=(0,z.useMemo)(()=>{if(!F)return[];let e=st?.conversationId===F.id?(()=>{let e=F.messages.find(e=>e.id===st.messageId);if(e)return{index:F.messages.indexOf(e),at:Date.parse(e.createdAt)||0,...st.kind===`withdraw`?{inclusive:!0}:{inclusive:!1}}})():void 0,t=[];return F.messages.forEach((n,r)=>{e&&(r>e.index||e.inclusive&&r===e.index)||n.delivery||t.push({at:Date.parse(n.createdAt)||0,seq:r,key:`m:${n.id}`})}),ur.forEach((n,r)=>{n.originMessageId&&n.originCallRow!==void 0&&F?.messages.some(e=>e.id===n.originMessageId&&e.toolCalls?.[n.originCallRow])||e&&(Date.parse(n.startedAt)||0)>e.at||t.push({at:Date.parse(n.startedAt)||0,seq:t.length+r,key:`r:${n.id}`})}),dr.forEach((n,r)=>{e&&(Date.parse(n.startedAt)||0)>e.at||t.push({at:Date.parse(n.startedAt)||0,seq:t.length+r,key:`w:${n.id}`})}),t.sort((e,t)=>e.at-t.at||e.seq-t.seq).map(e=>e.key)},[F,ur,dr,st]);(0,z.useEffect)(()=>{let e=A.current;if(!e||!F?.id)return;let t=()=>{!ne.current&&T.current[F.id]?.followTail&&(aO(e),e.scrollTop=e.scrollHeight)};if(t(),typeof ResizeObserver>`u`)return;let n=new ResizeObserver(t);n.observe(e);for(let t of e.children)n.observe(t);return()=>n.disconnect()},[F?.id,F?.messages,ur,dr,_r]);let vr=e=>nt(t=>({...t,[e]:!t[e]})),yr=(e,t)=>it(n=>({...n,[`${e}:${t}`]:!n[`${e}:${t}`]})),br=(e,t)=>ot(n=>({...n,[`${e}:${t}`]:n[`${e}:${t}`]!==!1})),[xr,Sr]=(0,z.useState)({}),Cr=e=>Sr(t=>({...t,[e]:t[e]!==!0})),wr=e=>{Un({type:`subagent.stop`,runId:e},`stop:${e}`,e=>e)||L(`连接断开,无法停止子智能体,请重试`,`error`)},Tr=e=>{Un({type:`workflow.stop`,workflowId:e},`stop:${e}`,e=>e)||L(`连接断开,无法停止编排,请重试`,`error`)},Er=e=>[...xe].filter(([,t])=>t.placement===e).map(([e,t])=>{let n=t.lines;return(0,B.jsxs)(`div`,{className:`extui-widget`,"data-widget-key":e,"data-widget-lines":n.length,children:[n.slice(0,oD).map((e,t)=>(0,B.jsx)(`div`,{children:e},`${t}:${e}`)),n.length>oD&&(0,B.jsx)(`div`,{children:`… (widget truncated)`})]},e)}),Dr=(e,t)=>{let n=`pending:${C_()}`,r={id:n,name:e,path:t,updatedAt:new Date().toISOString()};Un({type:`workspace.create`,name:e,path:t},`create-workspace`,e=>({...e,workspaces:[...e.workspaces,r]}),n)&&(_(n),l(void 0),C(!1))},[Or,kr]=(0,z.useState)(),Ar=(e,t)=>kr(n=>n?.kind===e&&n.id===t?n:{kind:e,id:t}),jr=()=>kr(void 0),Mr=(e,t)=>Or?.kind===e&&Or.id===t,Nr=(e,t,n)=>t.startsWith(`pending:`)?!1:Un(e===`workspace`?{type:`workspace.rename`,workspaceId:t,name:n}:{type:`conversation.rename`,conversationId:t,name:n},`rename:${t}`,e===`workspace`?Gn(t,{name:n}):Wn(t,{title:n}))?(At.current=!0,jr(),!0):(L(`连接断开,改名未保存,请重试`,`error`),!1),Pr=async e=>{if(e.startsWith(`pending:`)){L(`这个会话还在创建中,稍后再试`,`warning`);return}if(pt.current.has(e))return;L(`正在根据对话内容生成标题…`,`info`);let t=new Promise((t,n)=>{pt.current.set(e,{resolve:t,reject:n}),window.setTimeout(()=>{pt.current.delete(e)&&n(Error(`模型在 30 秒内没有返回标题`))},32e3)});if(!Hn({type:`conversation.autoRename`,conversationId:e}))pt.current.delete(e),L(`连接断开,无法生成标题`,`error`);else try{let n=await t;Nr(`conversation`,e,n),L(`已重命名为「${n}」`,`info`)}catch(e){L(`重命名失败:${e instanceof Error?e.message:String(e)}`,`error`)}},Fr=e=>{if(e.id.startsWith(`pending:`))return;let t=s.conversations.filter(t=>t.workspaceId===e.id).length;window.confirm(`删除工作区「${e.name}」?${t?`其中 ${t} 条会话将一并删除,`:``}此操作不可撤销。`)&&Un({type:`workspace.delete`,workspaceId:e.id},`delete:${e.id}`,t=>({...t,workspaces:t.workspaces.filter(t=>t.id!==e.id),conversations:t.conversations.filter(t=>t.workspaceId!==e.id)}))},[Ir,Lr]=(0,z.useState)(),Rr=Ir?s.workspaces.find(e=>e.id===Ir):void 0,{theme:zr,setTheme:Br}=Z_(),[Vr,Hr]=(0,z.useState)(!1),[Ur,Wr]=(0,z.useState)(!1),Gr=(e,t,n,r)=>{e.startsWith(`pending:`)||(Un({type:`workspace.settings`,workspaceId:e,model:n?{provider:n.provider,modelId:n.modelId}:null,thinkingLevel:r??null,agentId:t??null},`defaults:${e}`,Gn(e,{defaultModel:n,defaultThinkingLevel:r,defaultAgentId:t}))?Lr(void 0):L(`连接断开,设置未保存,请重试`,`error`))},Kr=e=>{if(e.startsWith(`pending:`)||i.current.some(t=>t.key===`defaults:${e}`))return;let t=`pending:${C_()}`,n={id:t,workspaceId:e,title:`新会话`,status:`idle`,updatedAt:new Date().toISOString(),messages:[]};Nt.current.set(t,n),Un({type:`conversation.create`,workspaceId:e},`create-session:${e}`,e=>({...e,conversations:[n,...e.conversations]}),t)&&(_(e),l(t),yn(`session`),y(e=>[...e.filter(e=>e!==t),t]))},qr=e=>{e.startsWith(`pending:`)||Un({type:`conversation.archive`,conversationId:e},`archive:${e}`,Wn(e,{archivedAt:new Date().toISOString()}))},Jr=e=>Un({type:`conversation.unarchive`,conversationId:e},`archive:${e}`,Wn(e,{archivedAt:void 0})),Yr=async e=>{if(!F){L(`请先选择或创建会话`,`error`);return}if(!Qn){L(`当前模型不支持图片输入`,`error`);return}let t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=e.filter(e=>t.includes(e.type)?e.size>5242880?(L(`图片「${e.name}」超过 5MB 上限`,`error`),!1):!0:(L(`不支持的文件格式「${e.name}」,仅支持 PNG/JPEG/GIF/WebP`,`error`),!1));if(n.length===0)return;let r=F.id;Gt(r,e=>({...e,uploading:e.uploading+n.length}));let i=n.map(e=>({id:C_(),conversationId:r,name:e.name,url:URL.createObjectURL(e)}));bt(e=>[...e,...i]);for(let[e,t]of n.entries()){let n=i[e];try{let e=await new Promise((e,n)=>{let r=new FileReader;r.onload=()=>{let t=r.result,n=t.indexOf(`,`);e(n>=0?t.slice(n+1):t)},r.onerror=n,r.readAsDataURL(t)}),i=await fetch(`/api/upload`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({conversationId:r,name:t.name,mimeType:t.type,data:e})});if(!(i.headers.get(`content-type`)??``).includes(`application/json`)){L(`服务器未返回 JSON 响应,请刷新或重启服务`,`error`);continue}if(i.ok){let e=await i.json();if(gt.current.has(n.id))continue;bt(e=>e.filter(e=>e.id!==n.id)),URL.revokeObjectURL(n.url),Gt(r,t=>({...t,images:[...t.images,{id:e.id,name:e.name,mimeType:e.mimeType,bytes:e.bytes}]}))}else{let e=await i.json().catch(()=>({error:`上传失败`}));L(e.error||`上传失败: ${i.status}`,`error`)}}catch(e){L(`上传错误: ${e instanceof Error?e.message:`网络错误`}`,`error`)}finally{bt(e=>e.map(e=>e.id===n.id?{...e,failed:!0}:e)),Gt(r,e=>({...e,uploading:Math.max(0,e.uploading-1)}))}}},Xr=e=>{let t=e.clipboardData?.items;if(!t)return;let n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.type.startsWith(`image/`)){let e=r.getAsFile();e&&n.push(e)}}if(n.length>0){if(!Qn){L(`当前模型不支持图片输入`,`error`);return}e.preventDefault(),Yr(n)}},Zr=e=>{e.dataTransfer?.types?.includes(`Files`)&&(e.preventDefault(),wt(!0))},Qr=e=>{e.currentTarget.contains(e.relatedTarget)||wt(!1)},$r=e=>{wt(!1);let t=Array.from(e.dataTransfer?.files??[]).filter(e=>e.type.startsWith(`image/`));if(t.length>0){if(e.preventDefault(),!Qn){L(`当前模型不支持图片输入`,`error`);return}Yr(t)}},ei=e=>{if(e.preventDefault(),!F||Kn||!Vt.trim()&&Ht.length===0)return;if(Ht.length>0&&!Qn){L(`当前模型不支持图片输入,请移除图片或切换至支持图文的模型`,`error`);return}if(Wt>0){L(`图片正在上传中,请稍候…`,`info`);return}let t=`message_${C_()}`,n=F.id,r=Vt,i=Ht;Un({type:`message.send`,conversationId:n,content:Vt,clientId:t,...Ht.length>0?{images:Ht}:{},...Ut.length>0?{attachments:Ut}:{}},`send:${n}`,e=>{let a=e.conversations.find(e=>e.id===n);if(!a||a.messages.some(e=>e.id===t))return e;let o=a.status===`running`,s=new Date().toISOString();return{...e,conversations:e.conversations.map(e=>e.id===n?{...e,...o?{}:{status:`waiting`,updatedAt:s},messages:[...e.messages,{id:t,role:`user`,content:r,...i.length>0?{images:i}:{},...Ut.length>0?{attachments:Ut}:{},...o?{delivery:`waiting`}:{},createdAt:s}]}:e)}},t,e=>{vt(a=>[...a,{id:t,conversationId:n,content:r,images:i,reason:e}]),Gt(n,e=>e.text||e.images.length?e:{...e,text:r,images:i})},e=>!!e.conversations.find(e=>e.id===n)?.messages.some(e=>e.id===t))?Gt(F.id,e=>({...e,text:``,images:[]})):L(`这条消息已经在发送队列中,请稍候`,`info`)},ti=(0,z.useMemo)(()=>(F?.messages??[]).filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),[F?.messages]),ni=e=>{Un({type:`message.cancel`,conversationId:F?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===F?.id?{...t,messages:t.messages.filter(t=>t.id!==e)}:t)}))||L(`连接断开,撤回没有生效,请重试`,`error`)},ri=e=>{Un({type:`message.steer`,conversationId:F?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===F?.id?{...t,messages:PE(t.messages,e,0)}:t)}),void 0,void 0,t=>t.conversations.find(e=>e.id===F?.id)?.messages.find(t=>t.id===e)?.delivery===`sending`)||L(`连接断开,插到最前没有生效,请重试`,`error`)},ii=e=>{Un({type:`message.interrupt`,conversationId:F?.id??``,messageId:e},`interrupt:${F?.id}:${e}`,e=>e,void 0,void 0,t=>{let n=t.conversations.find(e=>e.id===F?.id);return n?.status===`running`&&!n.messages.find(t=>t.id===e)?.delivery})||L(`请求正在处理,请稍候`,`info`)},ai=e=>{Un({type:`message.sendQueued`,conversationId:F?.id??``,messageId:e},`send-queued:${e}`,e=>e,void 0,void 0,t=>!t.conversations.find(e=>e.id===F?.id)?.messages.find(t=>t.id===e)?.delivery)||L(`连接断开,发送没有生效,请重试`,`error`)},oi=(e,t)=>{Un({type:`message.edit`,conversationId:F?.id??``,messageId:e,content:t},`edit:${e}`,n=>({...n,conversations:n.conversations.map(n=>n.id===F?.id?{...n,messages:n.messages.map(n=>n.id===e?{...n,content:t}:n)}:n)}))||L(`连接断开,修改没有生效,请重试`,`error`)},[si,ci]=(0,z.useState)(),li=(e,t=!1)=>{if(!F||si)return;let n=F.messages.find(t=>t.id===e);n&&(n&&ht(e=>{let t=e[F.id]??{text:``,images:[],uploading:0};return t.text.trim()||t.images.length?e:{...e,[F.id]:{...t,text:n.content,images:n.images??[]}}}),ct({conversationId:F.id,messageId:e,kind:t?`withdraw`:`revert`})),Hn({type:`message.revert`,conversationId:F.id,messageId:e,withdraw:t})?ci(e):(ct(void 0),L(`连接断开,回退未执行,请重试`,`error`))},[ui,di]=(0,z.useState)(),fi=(0,z.useRef)(void 0),pi=async(e,t)=>{fi.current&&clearTimeout(fi.current);let n=await JE(t);di({id:e,kind:n?`copied`:`error`}),n||L(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中这条消息的文字复制`,`error`),fi.current=setTimeout(()=>di(void 0),2e3)};(0,z.useEffect)(()=>()=>{fi.current&&clearTimeout(fi.current)},[]);let[mi,hi]=(0,z.useState)(),gi=e=>{mi||e.startsWith(`pending:`)||(Hn({type:`conversation.fork`,conversationId:e})?hi(e):L(`连接断开,分叉没有执行,请重试`,`error`))};return(0,B.jsxs)(`main`,{className:`shell${Ve?` shell-rail-collapsed`:``} mobile-panel-${Ue}`,"data-rail-collapsed":Ve,"data-selected-workspace":g??``,style:{"--sidebar-width":`${Ye.sidebar}px`,"--rail-col":Ve?void 0:`${Ye.rail}px`},children:[(0,B.jsxs)(`aside`,{children:[(0,B.jsxs)(`div`,{className:`brand`,children:[(0,B.jsx)(`span`,{children:`π`}),(0,B.jsxs)(`div`,{children:[(0,B.jsx)(`strong`,{children:`SUPER PI`}),(0,B.jsx)(`small`,{children:`agent workspace`})]})]}),(0,B.jsx)(`div`,{className:`sidebar-actions`,children:(0,B.jsx)(`button`,{className:`workspace-new`,onClick:()=>C(!0),children:`+ 工作区`})}),(0,B.jsx)(`div`,{className:`label`,children:`工作区`}),(0,B.jsx)(`nav`,{children:s.workspaces.map(e=>{let t=s.conversations.filter(t=>t.workspaceId===e.id),n=t.filter(e=>!e.archivedAt).sort(UE),r=t.filter(e=>e.archivedAt).sort(WE),i=m[e.id]??!1,a=ue[e.id]??!0;return(0,B.jsxs)(`section`,{className:`workspace-group`,children:[(0,B.jsx)(`div`,{className:`workspace-header`,children:Mr(`workspace`,e.id)?(0,B.jsx)(wD,{initial:e.name,label:`重命名工作区 ${e.name}`,onCommit:t=>Nr(`workspace`,e.id,t),onClose:jr}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`button`,{className:`workspace-toggle`,"aria-expanded":!i,title:e.path,onContextMenu:t=>{t.preventDefault();let n=t.currentTarget.getBoundingClientRect();ut({workspace:e,x:t.clientX||n.left+24,y:t.clientY||n.top+n.height})},onClick:()=>{_(e.id),l(It.find(t=>t.workspaceId===e.id)?.id),h(t=>({...t,[e.id]:!i}))},children:[(0,B.jsx)(`span`,{className:`chevron chevron-folder`,"aria-hidden":`true`,children:i?`📁`:`📂`}),(0,B.jsxs)(`span`,{children:[(0,B.jsx)(`strong`,{onDoubleClick:()=>Ar(`workspace`,e.id),children:e.name}),(0,B.jsx)(`small`,{children:e.path})]})]}),(0,B.jsx)(`button`,{className:`workspace-add`,title:`在此工作区新建会话`,onClick:()=>Kr(e.id),children:`+`}),(0,B.jsx)(`button`,{className:`workspace-settings`,title:`工作区设置(默认智能体 / 模型 / 思考强度)`,"aria-label":`工作区设置 ${e.name}`,onClick:()=>Lr(e.id),children:`⚙`}),(0,B.jsx)(`button`,{className:`workspace-delete`,title:`删除工作区`,onClick:()=>Fr(e),children:`×`})]})}),!i&&(n.length?n.map(t=>(0,B.jsx)(`div`,{className:`conversation-row`,children:Mr(`conversation`,t.id)?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(wD,{initial:t.title,label:`重命名会话 ${t.title}`,onCommit:e=>Nr(`conversation`,t.id,e),onClose:jr}),(0,B.jsx)(`small`,{className:`conversation-time`,children:HE(t.updatedAt,Pt)})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`button`,{className:`conversation ${F?.id===t.id?`selected`:``}`,"data-conversation":t.id,title:t.title,"aria-label":`打开会话 ${t.title}`,onContextMenu:e=>{e.preventDefault();let n=e.currentTarget.getBoundingClientRect();ft({conversation:t,x:e.clientX||n.left+24,y:e.clientY||n.top+n.height})},onClick:()=>{en(t.id),_(e.id)},children:[(0,B.jsx)(`i`,{className:`conversation-mark`,children:(0,B.jsx)(MD,{state:jD(t,ge.some(e=>e.conversationId===t.id),D.current[t.id])})}),(0,B.jsx)(`span`,{"data-conversation-title":t.id,onDoubleClick:()=>Ar(`conversation`,t.id),children:t.title}),(0,B.jsx)(`small`,{children:HE(t.updatedAt,Pt)})]}),(0,B.jsx)(`button`,{type:`button`,className:`conversation-fork`,"data-fork-conversation":t.id,"data-fork-state":mi===t.id?`pending`:`idle`,disabled:!!mi,title:`从此会话分叉出一个新会话`,"aria-label":`从会话 ${t.title} 分叉出一个新会话`,onClick:()=>gi(t.id),children:`⑂`}),(0,B.jsx)(`button`,{className:`conversation-archive`,title:`归档会话`,"aria-label":`归档会话 ${t.title}`,onClick:()=>qr(t.id),children:`×`})]})},t.id)):(0,B.jsx)(`div`,{className:`conversation-empty`,children:`暂无会话`})),!i&&r.length>0&&(0,B.jsxs)(`div`,{className:`archived-group`,"data-archived-count":r.length,children:[(0,B.jsxs)(`button`,{className:`archived-toggle`,title:a?`展开已归档会话`:`收起已归档会话`,"aria-expanded":!a,onClick:()=>de(t=>({...t,[e.id]:!a})),children:[(0,B.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:a?`▸`:`▾`}),(0,B.jsxs)(`span`,{className:`archived-label`,children:[`Archived (`,r.length,`)`]})]}),!a&&r.map(e=>(0,B.jsx)(`div`,{className:`conversation-archived`,"data-archived-at":e.archivedAt,children:Mr(`conversation`,e.id)?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(wD,{initial:e.title,label:`重命名已归档会话 ${e.title}`,onCommit:t=>Nr(`conversation`,e.id,t),onClose:jr}),(0,B.jsx)(`small`,{children:GE(e.archivedAt)})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`i`,{className:`conversation-mark`,"aria-hidden":`true`}),(0,B.jsx)(`span`,{"data-archived-title":e.id,onDoubleClick:()=>Ar(`conversation`,e.id),children:e.title}),(0,B.jsx)(`small`,{children:GE(e.archivedAt)}),(0,B.jsx)(`button`,{type:`button`,className:`conversation-fork`,"data-fork-conversation":e.id,"data-fork-state":mi===e.id?`pending`:`idle`,disabled:!!mi,title:`从此会话分叉出一个新会话`,"aria-label":`从已归档会话 ${e.title} 分叉出一个新会话`,onClick:()=>gi(e.id),children:`⑂`}),(0,B.jsx)(`button`,{className:`conversation-restore`,title:`恢复为正常会话`,"aria-label":`恢复会话 ${e.title}`,onClick:()=>Jr(e.id),children:`↑`})]})},e.id))]})]},e.id)})}),(0,B.jsxs)(`footer`,{children:[(0,B.jsxs)(`div`,{className:`footer-status`,children:[(0,B.jsx)(`i`,{className:u?`online`:`offline`}),u?`已连接`:`正在连接`,(0,B.jsx)(`span`,{children:`本地持久化`})]}),(0,B.jsxs)(`div`,{className:`footer-version`,"data-super-pi-version":Le?.runningVersion??``,children:[`Super Pi v`,Le?.runningVersion??`…`]}),(0,B.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-theme-open":`1`,"aria-haspopup":`dialog`,"aria-expanded":Vr,onClick:()=>{Hr(!0),Hn({type:`catalog.fetchAll`}),Hn({type:`providers.fetch`})},children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,children:`⚙`}),`设置`]}),(0,B.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-help-open":`1`,"aria-haspopup":`dialog`,"aria-expanded":Ur,onClick:()=>Wr(!0),children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,children:`📖`}),`使用指南`]}),(0,B.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger restart-needed-trigger`,title:`检查 Super Pi 更新`,onClick:async()=>{Be(`updating`);try{let e=await fetch(`/api/update-check`);if(!e.ok)throw Error(`check failed`);let t=await e.json();if(t.needsRestart)L(`当前代码已更新,正在重启服务…`,`info`);else if(t.updateAvailable){if(!window.confirm(`发现新版本 v${t.latestVersion??``},是否立即更新并重启 Super Pi?`))L(`已取消更新`,`info`);else{if(!(await fetch(`/api/update`,{method:`POST`})).ok)throw Error(`update failed`);L(`正在更新到 v${t.latestVersion} 并重启…`,`info`)}}else L(`当前已是最新版本`,`info`)}catch{L(`检查更新失败,请检查网络或服务日志`,`error`)}finally{Be(`idle`)}},children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,children:ze===`updating`?`⟳`:`↻`}),ze===`updating`?`正在检查更新…`:`检查更新`]}),Le?.needsRestart&&(0,B.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger restart-needed-trigger`,title:`代码已更新:当前运行 v${Le.runningVersion},磁盘版本 v${Le.diskVersion}。点击复制重启命令 /super_pi restart`,onClick:async()=>{Be(`updating`);try{if(!(await fetch(`/api/update`,{method:`POST`})).ok)throw Error(`update failed`);L(`正在更新 Super Pi,服务即将重启…`,`info`)}catch{Be(`idle`),L(`更新启动失败,请检查服务日志`,`error`)}},children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,children:ze===`updating`?`⟳`:`⚠️`}),ze===`updating`?`正在更新并重启…`:`更新并重启服务`]})]})]}),(0,B.jsx)(pO,{side:`left`,width:Ye.sidebar,min:Ye.sidebarMin,max:Ye.sidebarMax,label:`调整左侧栏宽度`,onWidth:Xe}),(0,B.jsxs)(`section`,{className:`chat`,"data-main-view":vn,"data-main-view-kind":vn,children:[Mn.length>0&&(0,B.jsx)(`div`,{className:`chat-tab-strip`,"data-chat-tab-strip":`1`,"data-session-count":$t.length,"data-file-count":I.open.length,children:(0,B.jsx)(Gg,{tabs:Mn,prefix:`workspace-tab`,ariaLabel:`工作区标签页`,activeId:Nn,onSelect:Pn,onClose:Fn,minWidth:120,maxWidth:320})}),(0,B.jsxs)(`header`,{children:[(0,B.jsxs)(`div`,{className:`chat-head`,children:[(0,B.jsx)(`h1`,{children:F?.title??`准备开始`}),ye.size>0?[...ye].map(([e,t])=>(0,B.jsx)(`p`,{"data-role":`run-status`,"data-status-key":e,children:`扩展状态:${e?`${e} · `:``}${t}`},e)):(0,B.jsx)(`p`,{"data-role":`run-status`,children:F?.status===`running`?`Agent 正在工作`:`Pi runtime · Web 控制台`})]}),(0,B.jsxs)(`span`,{className:`chat-view chat-view-${vn}`,"data-main-view-indicator":vn,"data-main-view-kind":vn,title:vn===`file`?`中间主画面正在显示文件 ${I.active?.path??``}`:vn===`diff`?`中间主画面正在显示 ${bn??``} 的改动`:`中间主画面正在显示这个会话的消息流`,children:[(0,B.jsx)(`span`,{className:`chat-view-label`,children:`主区显示`}),(0,B.jsx)(`span`,{className:`chat-view-kind`,children:vn===`file`?`文件`:vn===`diff`?`改动`:`会话`}),vn===`file`&&I.active&&(0,B.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":I.active.name,children:I.active.name}),vn===`diff`&&bn&&(0,B.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":bn,children:bn})]}),(0,B.jsx)(`div`,{className:`badge`,children:F?.status??`idle`})]}),f&&(0,B.jsxs)(`div`,{className:`error`,role:`alert`,"data-global-error":!0,children:[(0,B.jsx)(`span`,{children:f}),(0,B.jsx)(`button`,{type:`button`,"aria-label":`关闭错误提示`,title:`关闭错误提示`,onClick:()=>p(void 0),children:`×`})]}),F?.error&&(0,B.jsx)(`div`,{className:`error`,"data-role":`conversation-error`,children:F.error}),Ce&&(0,B.jsxs)(`div`,{className:`extui-title-note`,children:[`扩展建议标题:`,Ce]}),_e.length>0&&(0,B.jsx)(`div`,{className:`toasts`,role:`status`,"aria-live":`polite`,"data-toast-count":_e.length,children:_e.map(e=>(0,B.jsx)(`div`,{className:`toast toast-${e.kind}`,"data-toast-kind":e.kind,children:e.text},e.key))}),vn===`file`?(0,B.jsx)(`div`,{className:`chat-file-view`,"data-main-file-view":In?.path,"data-file-view-kind":`editor`,children:In?(0,B.jsx)(jg,{file:In,state:I.saves[In.path]?.state??`idle`,message:I.saves[In.path]?.message??``,external:I.external[In.path]===!0,jumpToLine:gn&&gn.workspaceId===g&&gn.path===In.path?gn:void 0,onChange:e=>I.updateBuffer(In.path,e),onSave:()=>void I.save(In.path,!1),onReload:()=>void I.reload(In.path),onOverwrite:()=>void I.save(In.path,!0)}):(0,B.jsx)(`p`,{className:`rail-empty`,"data-main-file-empty":`1`,children:`没有选中的文件。`})}):vn===`diff`?(0,B.jsx)(`div`,{className:`chat-file-view`,"data-main-diff-view":bn??``,"data-file-view-kind":`diff`,children:(0,B.jsx)(Ng,{diff:Cn.diff,loading:Cn.loading,error:Cn.error,bufferContent:Dn,mode:Tn,onMode:En})}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsxs)(`div`,{className:`messages`,ref:A,"data-message-scroll-container":F?.id??``,onWheel:e=>{e.deltaY<0&&T.current[F?.id??``]?.followTail&&(ne.current=!0,zt(e.currentTarget,!0))},onScroll:e=>{let t=e.currentTarget;t.dataset.programmaticScroll===`true`?delete t.dataset.programmaticScroll:zt(t)},children:[!F&&(0,B.jsxs)(`div`,{className:`empty`,children:[(0,B.jsx)(`div`,{className:`orb`,children:`π`}),(0,B.jsx)(`h2`,{children:`开始一个新会话`}),s.workspaces.length===0?(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{children:`先创建一个工作区,再开始会话。`}),(0,B.jsx)(`button`,{onClick:()=>C(!0),children:`+ 新建工作区`})]}):(0,B.jsxs)(B.Fragment,{children:[(0,B.jsx)(`p`,{children:s.workspaces.length===1&&Lt?`在「${Lt.name}」中创建会话,即可向 Super Pi 发送任务。`:`选择工作区即可开始会话,向 Super Pi 发送任务。`}),s.workspaces.length>1&&(0,B.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,B.jsx)(`label`,{htmlFor:`empty-workspace-choice`,children:`工作区:`}),(0,B.jsxs)(`select`,{id:`empty-workspace-choice`,"aria-label":`选择工作区`,value:Lt?.id,onChange:e=>{e.target.value===`__new__`?C(!0):_(e.target.value)},children:[s.workspaces.map(e=>(0,B.jsx)(`option`,{value:e.id,children:e.name},e.id)),(0,B.jsx)(`option`,{value:`__new__`,children:`+ 新建工作区…`})]})]}),Lt&&(0,B.jsx)(`button`,{onClick:()=>Kr(Lt.id),children:`新建会话`}),(0,B.jsx)(`span`,{className:`empty-secondary-action`,role:`button`,tabIndex:0,onClick:()=>C(!0),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),C(!0))},children:`+ 新建工作区`})]})]}),_r.map(e=>{if(e.startsWith(`m:`)){let t=mr.get(e.slice(2));if(!t)return null;let r=!F?.messages.some(n=>n.id!==t.id&&n.role===`user`&&_r.indexOf(`m:${n.id}`)>_r.indexOf(e)),i=t.role===`user`&&F?.status!==`running`&&F?.status!==`waiting`&&si!==t.id,a=i&&r&&!t.id.startsWith(`pending:`),o=i&&!r&&!!t.piEntryId,s=t.content?(0,B.jsx)(tm,{source:t.content}):(0,B.jsx)(`span`,{className:`typing`,children:`正在思考`}),c=t.toolCalls??[];if(t.role===`user`){let n=ui?.id===t.id?ui.kind:void 0,r=t.content||(t.images?.length?`[图片]`:``);return(0,B.jsxs)(`article`,{className:`message user`,"data-transcript-key":e,children:[(0,B.jsxs)(`div`,{className:`message-body`,children:[(0,B.jsxs)(`div`,{className:`bubble`,children:[(0,B.jsxs)(`div`,{className:`meta`,children:[he,(0,B.jsx)(`time`,{children:FE(t.createdAt)})]}),t.images&&t.images.length>0&&(0,B.jsx)(`div`,{className:`message-images`,"data-message-images":`1`,children:t.images.map(e=>(0,B.jsx)(`button`,{type:`button`,className:`message-image-btn`,"data-message-image-id":e.id,onClick:()=>St({url:`/api/upload/${encodeURIComponent(F?.id??``)}/${encodeURIComponent(e.id)}`,name:e.name,bytes:e.bytes}),title:e.name?`查看大图:${e.name}`:`查看大图`,children:(0,B.jsx)(`img`,{src:`/api/upload/${encodeURIComponent(F?.id??``)}/${encodeURIComponent(e.id)}`,alt:e.name||`图片`,className:`message-image-thumb`,loading:`lazy`})},e.id))}),(0,B.jsx)(`div`,{className:`content`,children:s})]}),t.attachments&&t.attachments.length>0&&(0,B.jsx)(`div`,{className:`message-attachments`,"data-message-attachments":`1`,children:t.attachments.map(e=>{let n=`att:${t.id}:${e.kind}:${e.id}`,r=rt[n]??!1;return(0,B.jsxs)(`div`,{className:`message-attachment`,"data-message-attachment":e.kind,children:[(0,B.jsxs)(`button`,{type:`button`,className:`message-attachment-head`,"data-message-attachment-toggle":e.id,"aria-expanded":r,onClick:()=>it(e=>({...e,[n]:!r})),children:[(0,B.jsx)(`span`,{className:`message-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,B.jsx)(`span`,{className:`message-attachment-label`,children:`技能`}),(0,B.jsx)(`span`,{className:`message-attachment-name`,title:e.name,children:e.name}),(0,B.jsx)(`span`,{className:`message-attachment-chevron`,"aria-hidden":`true`,children:r?`▾`:`▸`})]}),r&&(0,B.jsx)(`pre`,{className:`message-attachment-body`,"data-message-attachment-body":e.id,children:e.content})]},n)})}),(0,B.jsxs)(`div`,{className:`message-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`message-copy`,"data-copy-message":t.id,"data-copy-state":n,"aria-label":`复制这条消息:${r}`,onClick:()=>pi(t.id,r),children:n===`copied`?`已复制`:n===`error`?`复制失败`:`复制`}),a&&(0,B.jsx)(`button`,{type:`button`,className:`message-revert`,"data-withdraw-message":t.id,title:`撤回并编辑:删除这条消息并将文字恢复到输入框继续编辑`,onClick:()=>li(t.id,!0),children:`撤回`}),o&&(0,B.jsx)(`button`,{type:`button`,className:`message-revert`,"data-revert-message":t.id,title:`回退到这里:删除后续全部内容(Pi 的记录和这里的历史一起清掉,不会新建会话,也不动任何代码文件)`,onClick:()=>li(t.id),children:`回退`})]})]}),(0,B.jsx)(`div`,{className:`avatar`,title:he,children:he})]},e)}if(t.role===`tool`){let n=(()=>{let e=/<summary>([\s\S]*?)<\/summary>/.exec(t.content);return e?e[1].trim():`后台回传`})(),r=(()=>{let e=/<task id="[^"]+" state="([^"]+)"/.exec(t.content);return e?e[1]:`completed`})(),i=(()=>{let e=/<task_(?:result|error)>\n?([\s\S]*?)\n?<\/(?:task_result|task_error)>/.exec(t.content);return e?e[1]:t.content})(),a=`tool:${t.id}`,o=rt[a]??!1;return(0,B.jsx)(`article`,{className:`message tool`,"data-transcript-key":e,"data-tool-state":r,children:(0,B.jsxs)(`div`,{className:`message-body`,children:[(0,B.jsx)(`div`,{className:`bg-result-head`,"data-bg-result-head":t.id,children:(0,B.jsxs)(`button`,{type:`button`,className:`bg-result-toggle`,"data-bg-result-toggle":t.id,"aria-expanded":o,title:o?`折叠后台回传`:`展开后台回传`,onClick:()=>it(e=>({...e,[a]:!o})),children:[(0,B.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:r===`error`?`✕`:`↩`}),(0,B.jsx)(`span`,{className:`bg-result-label`,children:`后台回传`}),(0,B.jsx)(`span`,{className:`bg-result-summary`,title:n,children:n}),!o&&(0,B.jsx)(`span`,{className:`bg-result-preview`,"data-bg-result-preview":t.id,title:`展开查看完整输出`,children:i.split(`
|
|
98
|
+
`).slice(-1)[0]}),(0,B.jsx)(`span`,{className:`bg-result-chevron`,"aria-hidden":`true`,children:o?`▾`:`▸`})]})}),o&&(0,B.jsx)(`div`,{className:`bg-result-body`,"data-bg-result-body":t.id,children:(0,B.jsx)(`pre`,{className:`bg-result-pre`,"data-bg-result-pre":t.id,children:i})})]})},e)}let l=t.thinking?.trim()?t.thinking:``,u=t.thinkingBlocks?.length?t.thinkingBlocks:l?[{at:0,text:l}]:[],d=(e,n)=>{let r=typeof e.at==`number`&&Number.isFinite(e.at)?e.at:n;return Math.max(0,Math.min(r,t.content.length))},f=e=>e.thinkingBlock===void 0?typeof e.thinkingAt!=`number`||!(e.thinkingAt<l.length||t.thinkingActive)?-1:u.findIndex((t,n)=>(e.at??0)>=t.at&&(u[n+1]===void 0||(e.at??0)<u[n+1].at)):e.thinkingBlock??-1,p=e=>c.map((e,t)=>({call:e,index:t})).filter(({call:t})=>f(t)===e),m=[],h=[...u.map((e,t)=>({at:e.at,order:u.slice(0,t).reduce((e,t)=>e+t.text.length,0)*2+1,segment:{blockIndex:t}})),...c.map((e,t)=>({at:d(e,t),order:(e.thinkingAt??0)*2,segment:{call:e,index:t}})).filter(({segment:e})=>`call`in e&&f(e.call)<0)].sort((e,t)=>e.at-t.at||e.order-t.order),g=0;for(let e of h){let n=Math.max(g,Math.min(e.at,t.content.length));n>g&&m.push({text:t.content.slice(g,n)}),m.push(e.segment),g=n}g<t.content.length&&m.push({text:t.content.slice(g)});let _=e=>{let t=gr.get(e);if(t)return(0,B.jsx)(`div`,{className:`call-anchored-run`,"data-call-anchored-run":t.id,"data-call-anchored-site":e,children:(0,B.jsx)(gD,{run:t,name:pr.get(t.agentId)??``,expanded:!!tt[t.id],onToggle:()=>vr(t.id),onStop:()=>wr(t.id),stopping:n.some(e=>e.key===`stop:${t.id}`)})})},v=e=>e.call.question?(0,B.jsx)(`div`,{className:`call-blocks`,"data-call-block-index":e.index,children:(0,B.jsx)(xD,{question:e.call.question,index:e.index,expanded:`${t.id}:${e.index}`in at?!!at[`${t.id}:${e.index}`]:!0,onToggle:()=>br(t.id,e.index),onAnswer:(n,r)=>qn(F?.id??``,t.id,e.index,n,r)})},`c${e.index}`):(0,B.jsx)(`div`,{className:`call-blocks`,"data-call-block-index":e.index,children:(0,B.jsx)(pD,{call:e.call,index:e.index,expanded:`${t.id}:${e.index}`in rt&&!!rt[`${t.id}:${e.index}`],onToggle:()=>yr(t.id,e.index),backgroundOutput:e.call.backgroundTask&&(0,B.jsx)(fD,{task:e.call.backgroundTask,initialOutput:re.current.get(e.call.backgroundTask.id)??``,expanded:`${t.id}:${e.index}`in rt&&!!rt[`${t.id}:${e.index}`]}),runCard:_(`${t.id}:${e.index}`)})},`c${e.index}`),y=e=>{let n=u[e],r=u.slice(0,e).reduce((e,t)=>e+t.text.length,0),i=0,a=[];for(let{call:t,index:o}of p(e).sort((e,t)=>(e.call.thinkingAt??r)-(t.call.thinkingAt??r)||e.index-t.index)){let e=Math.max(i,Math.min(n.text.length,(t.thinkingAt??r)-r));e>i&&a.push((0,B.jsx)(`div`,{className:`content thinking-text`,children:(0,B.jsx)(tm,{source:n.text.slice(i,e)})},`t${o}`)),a.push(v({call:t,index:o})),i=e}i<n.text.length&&a.push((0,B.jsx)(`div`,{className:`content thinking-text`,children:(0,B.jsx)(tm,{source:n.text.slice(i)})},`tail`));let o=p(e).filter(e=>e.call.status===void 0);return(0,B.jsx)(hD,{liveCall:o.at(-1)?.call.label,liveExtra:o.length>1?o.length-1:void 0,messageId:`${t.id}:${e}`,nestedCount:p(e).length,preview:n.text.split(`
|
|
99
|
+
`).map(e=>e.trim()).find(Boolean)??``,expanded:xr[`${t.id}:${e}`]===!0,onToggle:()=>Cr(`${t.id}:${e}`),children:a},`${t.id}:thinking:${e}`)};return(0,B.jsxs)(`article`,{className:`message assistant`,"data-transcript-key":e,children:[(0,B.jsx)(`div`,{className:`avatar`,children:`π`}),(0,B.jsxs)(`div`,{className:`message-body`,children:[(0,B.jsxs)(`div`,{className:`meta`,children:[t.agentIdentity?.name??`Super Pi`,(0,B.jsx)(`time`,{children:FE(t.createdAt)})]}),m.map((e,t)=>`blockIndex`in e?y(e.blockIndex):`text`in e?e.text?(0,B.jsx)(`div`,{className:`content`,children:(0,B.jsx)(tm,{source:e.text})},`t${t}`):null:v(e))]})]},e)}if(e.startsWith(`w:`)){let t=fr.get(e.slice(2));return t?(0,B.jsxs)(`div`,{"data-transcript-key":e,children:[n.some(e=>e.key===`stop:${t.id}`)&&(0,B.jsx)(`span`,{children:`停止中…`}),(0,B.jsx)($g,{workflow:t,names:pr,stopping:n.some(e=>e.key===`stop:${t.id}`),onStop:()=>Tr(t.id)},e)]},e):null}let t=hr.get(e.slice(2));return t?(0,B.jsxs)(`div`,{"data-transcript-key":e,children:[n.some(e=>e.key===`stop:${t.id}`)&&(0,B.jsx)(`span`,{children:`停止中…`}),(0,B.jsx)(gD,{run:t,stopping:n.some(e=>e.key===`stop:${t.id}`),name:pr.get(t.agentId)??``,expanded:!!tt[t.id],onToggle:()=>vr(t.id),onStop:()=>wr(t.id)},e)]},e):null})]}),(0,B.jsx)(_D,{messages:ti,running:F?.status===`running`,onSteer:ri,onInterrupt:ii,onSend:ai,onCancel:ni,onEdit:oi}),(0,B.jsxs)(`div`,{className:`stream-tail`,"data-stream-tail":`1`,"data-follow-tail":N.followTail?`true`:`false`,children:[Qe!==null&&(0,B.jsx)(bO,{height:Qe,onHeight:et}),(0,B.jsx)(`span`,{className:`stream-tail-status`,"data-run-status":F?.status??`idle`,"data-stream-state":u?F?.status===`waiting`?`waiting`:F?.status===`running`?`streaming`:ti.length?`waiting`:F?.status===`failed`?`failed`:`ready`:`waiting`,children:u?F?.status===`waiting`?`等待 LLM 返回`:F?.status===`running`?`Streaming · 正在生成`:ti.length?`Waiting · 消息排队中`:F?.status===`failed`?`运行失败`:F?.status===`stopped`?`已停止`:`就绪`:`连接中 / 等待连接`}),!N.followTail&&(0,B.jsx)(`button`,{type:`button`,className:`stream-tail-jump`,"data-jump-to-bottom":`1`,onClick:()=>{let e=A.current;e&&(aO(e),e.scrollTop=e.scrollHeight,zt(e,!1,!0))},children:`↓ 跳到底部`}),(0,B.jsx)(`span`,{className:`stream-tail-mode`,"data-follow-tail":N.followTail?`true`:`false`,children:N.followTail?`贴底`:`自由浏览`})]}),(lr.length>0||[...xe.values()].some(e=>e.placement===`aboveEditor`))&&(0,B.jsxs)(`div`,{className:`extui`,"data-extui-count":lr.length,children:[lr.map(e=>(0,B.jsx)(CD,{request:e.request,pending:n.some(t=>t.key===`answer:${e.conversationId}:${e.request.requestId}`),onAnswer:t=>Jn(e.conversationId,e.request.requestId,t)},e.request.requestId)),Er(`aboveEditor`)]}),(0,B.jsxs)(`form`,{onSubmit:ei,onPaste:Xr,onDragOver:Zr,onDragLeave:Qr,onDrop:$r,className:Ct?`composer-dropzone-active`:void 0,children:[(0,B.jsx)(`textarea`,{ref:ee,value:Vt,onCompositionStart:()=>{Et.current=!0},onCompositionEnd:()=>{Et.current=!1},onChange:e=>{Kt(e.target.value);let t=e.target.value,n=e.target.selectionStart??t.length,r=t.slice(0,n),i=r.lastIndexOf(`/`),a=r.slice(i+1),o=i>0?r[i-1]:``;i>=0&&(i===0||/\s/.test(o))&&/^[\w:-]*$/u.test(a)?Xt({visible:!0,query:a,rect:e.currentTarget.getBoundingClientRect()}):Xt({visible:!1,query:``,rect:null})},placeholder:F?Qn?`描述你要完成的任务(支持粘贴/拖放图片)…`:`描述你要完成的任务…`:`先创建会话`,disabled:!F,onKeyDown:e=>{if(!(Et.current||NE(e))){if(Yt.visible){if(e.key===`Escape`){e.preventDefault(),Xt({visible:!1,query:``,rect:null});return}if([`ArrowDown`,`ArrowUp`,`Enter`].includes(e.key)){e.preventDefault();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),e.currentTarget.form?.requestSubmit())}}}),Yt.visible&&Yt.rect&&(0,B.jsx)(mm,{query:Yt.query,anchorRect:Yt.rect,workspaceId:F?.workspaceId,command:Hn,onSelect:e=>{if(e.id.startsWith(`skill:`)){let t=e.id.slice(6),n=document.querySelector(`[data-selected-workspace]`)?.dataset.selectedWorkspace??F?.workspaceId,r=new URLSearchParams({name:t,...n?{workspaceId:n}:{}});fetch(`/api/skills/read?${r.toString()}`).then(async n=>{if(!n.ok){L(`读取技能失败`,`error`);return}let r=await n.json();typeof r.content==`string`&&qt({kind:`skill`,id:r.id??e.id,name:r.name??t,content:r.content})}).catch(()=>L(`读取技能失败`,`error`))}let t=ee.current?.selectionStart??Vt.length,n=Vt.slice(0,t),r=n.lastIndexOf(`/`),i=fm(e,Yt.query),a=`${n.slice(0,r)}/${i} ${Vt.slice(t)}`;Kt(a),Xt({visible:!1,query:``,rect:null})},onClose:()=>Xt({visible:!1,query:``,rect:null})}),_t.filter(e=>e.conversationId===F?.id).map(e=>(0,B.jsxs)(`div`,{className:`composer-notice`,"data-failed-send":e.id,role:`alert`,children:[(0,B.jsx)(`span`,{className:`composer-notice-mark`,"aria-hidden":`true`,children:`!`}),(0,B.jsxs)(`div`,{className:`composer-notice-body`,children:[(0,B.jsx)(`p`,{className:`composer-notice-title`,"data-failed-send-reason":`1`,children:e.reason?.trim()||`服务端没有接受这条消息。`}),(0,B.jsx)(`p`,{className:`composer-notice-text`,title:e.content,children:e.content})]}),(0,B.jsxs)(`div`,{className:`composer-notice-actions`,children:[(0,B.jsx)(`button`,{type:`button`,className:`composer-notice-action`,"data-failed-send-restore":`1`,disabled:!!(Vt||Ht.length),title:Vt||Ht.length?`输入框里已经有内容,先把这条留在下面`:`放回输入框,改完再发`,onClick:()=>{Gt(e.conversationId,t=>({...t,text:e.content,images:e.images})),vt(t=>t.filter(t=>t.id!==e.id))},children:`放回输入框`}),(0,B.jsx)(`button`,{type:`button`,className:`composer-notice-dismiss`,"data-failed-send-dismiss":`1`,onClick:()=>vt(t=>t.filter(t=>t.id!==e.id)),children:`丢弃`})]})]},e.id)),yt.filter(e=>e.conversationId===F?.id).map(e=>(0,B.jsxs)(`div`,{"data-upload-preview":e.id,children:[(0,B.jsx)(`img`,{src:e.url,alt:e.name,width:48,height:48}),(0,B.jsx)(`span`,{children:e.failed?`上传失败`:`上传中…`}),(0,B.jsx)(`button`,{type:`button`,onClick:()=>{gt.current.add(e.id),URL.revokeObjectURL(e.url),bt(t=>t.filter(t=>t.id!==e.id))},children:`移除`})]},e.id)),(Ht.length>0||Wt>0)&&(0,B.jsxs)(`div`,{className:`composer-attachments`,"data-composer-attachments":`1`,children:[Ht.map((e,t)=>(0,B.jsxs)(`div`,{className:`composer-attachment-item`,"data-composer-attachment-id":e.id,children:[(0,B.jsx)(`img`,{src:`/api/upload/${encodeURIComponent(F?.id??``)}/${encodeURIComponent(e.id)}`,alt:e.name||`已附图片`,className:`composer-attachment-thumb`,onClick:()=>St({url:`/api/upload/${encodeURIComponent(F?.id??``)}/${encodeURIComponent(e.id)}`,name:e.name,bytes:e.bytes}),title:`点击查看大图`}),(0,B.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name||`图片`}),(0,B.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-attachment-remove":e.id,onClick:()=>Zt(e=>e.filter((e,n)=>n!==t)),"aria-label":`移除 ${e.name||`图片`}`,title:`移除图片`,children:`✕`})]},e.id)),Wt>0&&(0,B.jsx)(`div`,{className:`composer-attachment-item composer-attachment-uploading`,children:(0,B.jsxs)(`span`,{children:[`图片上传中 (`,Wt,`)…`]})}),Ut.map(e=>(0,B.jsxs)(`div`,{className:`composer-attachment-item composer-attachment-skill`,"data-composer-skill-id":e.id,children:[(0,B.jsx)(`span`,{className:`composer-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,B.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name}),(0,B.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-skill-remove":e.id,onClick:()=>Jt(e.kind,e.id),"aria-label":`移除 ${e.name}`,title:`移除技能`,children:`✕`})]},`${e.kind}:${e.id}`))]}),(0,B.jsxs)(`div`,{className:`composer`,children:[(0,B.jsxs)(`div`,{className:`session-picker`,"data-session-picker":`1`,children:[(0,B.jsx)(TD,{kind:`agent`,label:ir?.name??`跟随 Pi 默认`,value:F?.agentId??ED,options:ar,disabled:!Ne||Ne.source===`unavailable`||Kn,note:cD(Ne),onChoose:cr}),(0,B.jsx)(TD,{kind:`model`,label:Yn?.label??(Te?`Pi 默认`:`读取中…`),value:Yn?`${Yn.provider}/${Yn.modelId}`:void 0,detail:sr?`来自 ${ir?.name}`:Yn&&Te?.source===`pi`&&!F?.model?`Pi 默认模型`:Yn?`${Yn.provider}/${Yn.modelId}`:void 0,options:er,disabled:!Zn||Kn,note:sD(`模型`,Te),onChoose:nr}),(0,B.jsx)(TD,{kind:`thinking`,label:Xn??(Te?`Pi 默认`:`读取中…`),value:Xn,options:tr,disabled:!Zn||Kn,note:sD(`思考等级`,Te),onChoose:rr})]}),(0,B.jsxs)(`div`,{className:`composer-hints`,children:[(0,B.jsxs)(`button`,{type:`button`,className:`composer-attach-btn`,"data-composer-attach":`1`,onClick:()=>Tt.current?.click(),disabled:!F||!Qn||Wt>0,title:F?Qn?`添加图片(支持剪贴板粘贴与拖拽)`:`当前模型不支持图片输入`:`请先创建或选择会话`,"aria-label":`添加图片`,children:[(0,B.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),` 图片`]}),(0,B.jsx)(`input`,{ref:Tt,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,multiple:!0,style:{display:`none`},onChange:e=>{e.target.files?.length&&(Yr(Array.from(e.target.files)),e.target.value=``)}}),(0,B.jsx)(`span`,{children:`Enter 发送 · Shift + Enter 换行`})]}),(0,B.jsxs)(`div`,{className:`composer-actions`,children:[F?.status===`running`&&(0,B.jsx)(`button`,{type:`button`,className:`stop`,"data-stop-run":F.id,disabled:n.some(e=>e.key===`stop:${F.id}`),onClick:()=>Un({type:`run.stop`,conversationId:F.id},`stop:${F.id}`,e=>e),children:n.some(e=>e.key===`stop:${F.id}`)?`停止中…`:`停止`}),(0,B.jsx)(`button`,{className:`send ${F?.status===`running`?`send-queued`:``}`,"data-send-mode":F?.status===`running`?`queued`:`direct`,disabled:!Vt.trim()&&Ht.length===0||!F||Wt>0||!!si||Kn,title:F?si?`正在撤回:Pi 的历史还没截断完成,撤回结束后即可发送`:!Vt.trim()&&Ht.length===0?`请输入消息或添加图片后发送`:Wt>0?`图片上传中…`:F.status===`running`?`这一轮结束后发送(发送后可在上面的排队区取消或插队)`:void 0:`请先创建或选择会话`,children:si?`撤回中…`:F?.status===`running`?`排队发送 ↑`:`发送 ↑`})]})]})]}),Er(`belowEditor`)]})]}),(0,B.jsx)(pO,{side:`right`,width:Ve?30:Ye.rail,min:Ye.railMin,max:Ye.railMax,label:`调整右侧栏宽度`,onWidth:Ze}),fn&&(0,B.jsx)(Vg,{entries:I.index,complete:I.indexComplete,skipped:I.indexSkipped,onOpen:e=>{kn(e)},onClose:()=>pn(!1)}),mn&&(0,B.jsx)(Bg,{workspaceId:g,onOpen:e=>{kn({path:e.path,name:e.name,text:!0},e.line)},onClose:()=>hn(!1)},g),(0,B.jsxs)(`nav`,{className:`mobile-nav`,"aria-label":`移动端主导航`,children:[(0,B.jsxs)(`button`,{type:`button`,"data-mobile-nav":`workspaces`,className:Ue===`workspaces`?`active`:``,onClick:()=>We(`workspaces`),children:[`☰`,(0,B.jsx)(`span`,{children:`工作区`})]}),(0,B.jsxs)(`button`,{type:`button`,"data-mobile-nav":`chat`,className:Ue===`chat`?`active`:``,onClick:()=>We(`chat`),children:[`◉`,(0,B.jsx)(`span`,{children:`对话`})]}),(0,B.jsxs)(`button`,{type:`button`,"data-mobile-nav":`rail`,className:Ue===`rail`?`active`:``,onClick:()=>{We(`rail`),He(!1)},children:[`▣`,(0,B.jsx)(`span`,{children:`工具`})]})]}),` `,lt&&(0,B.jsx)(YE,{workspace:lt.workspace,x:lt.x,y:lt.y,notify:L,onClose:()=>ut(void 0)}),dt&&(0,B.jsx)(XE,{conversation:dt.conversation,x:dt.x,y:dt.y,notify:L,onRename:()=>void Pr(dt.conversation.id),onClose:()=>ft(void 0)}),S&&(0,B.jsx)(iD,{onClose:()=>C(!1),onCreate:Dr}),Vr&&(0,B.jsx)(sv,{workspaceId:g,theme:zr,onChooseTheme:e=>Br(e),onClose:()=>Hr(!1),agentCatalog:Ne,subagentCatalog:Fe,modelFilterRules:s.modelFilterRules??[],pendingSettings:n.some(e=>e.key===`model-rules`||e.key===`agent-directories`||e.key===`default-model`),onSetModelRules:e=>Un({type:`model.rules.set`,rules:e},`model-rules`,t=>({...t,modelFilterRules:e})),defaultModel:s.defaultModel,modelCatalog:De,onSetDefaultModel:e=>Un({type:`settings.defaultModel`,model:e?{provider:e.provider,modelId:e.modelId}:null},`default-model`,t=>{let n={...t};return e?n.defaultModel=e:delete n.defaultModel,n}),providers:ke,providerApis:je,onSetProvider:e=>{Hn({type:`providers.set`,provider:e})},onRemoveProvider:e=>{Hn({type:`providers.remove`,providerId:e})},onRemoveProviderModel:(e,t)=>{Hn({type:`providers.removeModel`,providerId:e,modelId:t})},customAgentDirs:s.customAgentDirs??[],onSetCustomAgentDirs:e=>Un({type:`agents.setCustomDirs`,dirs:e},`agent-directories`,t=>({...t,customAgentDirs:e})),onRescanAgents:()=>Hn({type:`agents.rescan`}),userNickname:fe,onSetUserNickname:me}),Ur&&(0,B.jsx)(t_,{onClose:()=>Wr(!1)}),Rr&&(0,B.jsx)(DD,{workspace:Rr,catalog:$n(Te,Rr),agents:Ne,onClose:()=>Lr(void 0),onRename:()=>{let e=Rr.id;Lr(void 0),Ar(`workspace`,e)},onSave:(e,t,n)=>Gr(Rr.id,e,t,n)}),xt&&(0,B.jsx)(qD,{image:xt,onClose:()=>St(void 0)}),(0,B.jsx)(zD,{todos:s.todosByConversation?.[F?.id??``]??[],tasks:(s.backgroundTasks??[]).filter(e=>e.conversationId===F?.id),collapsed:Ve,onToggle:()=>He(e=>!e),workspaceId:g,workspaceLabel:s.workspaces.find(e=>e.id===g)?.path,conversationId:F?.id,connected:u,files:I,onOpenFile:e=>void kn(e),onOpenChanged:Sn,activeTab:un,onSelectTab:dn,sendCommand:Hn,registerTerminalSink:le})]})}X_(Y_()),(0,ua.createRoot)(document.getElementById(`root`)).render((0,B.jsx)(z.StrictMode,{children:(0,B.jsx)(xO,{})}));export{l as a,s as i,y as n,d as r,mg as t};
|