pi-web-ui 0.86.1 → 0.86.2

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.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-fC8DLbDz.js","assets/markdown-D3PKeHAZ.js","assets/xterm-B96xOxS9.js","assets/react-w24rH0km.js","assets/TerminalPanel-DOrYoP_4.css"])))=>i.map(i=>d[i]);
2
- import{R as es,a as c,j as s,f as eu,s as zn,h as ii,w as Xt,b as tu,c as su,d as mo,o as Sa,z as ho,e as nu,g as au,p as is,v as iu,i as fo,k as Ni,M as ru,l as ou,m as lu,n as go,q as bo}from"./markdown-D3PKeHAZ.js";import{r as Eo}from"./react-w24rH0km.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))a(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&a(l)}).observe(document,{childList:!0,subtree:!0});function n(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function a(i){if(i.ep)return;i.ep=!0;const o=n(i);fetch(i.href,o)}})();var nn={},vi;function cu(){if(vi)return nn;vi=1;var e=Eo();return nn.createRoot=e.createRoot,nn.hydrateRoot=e.hydrateRoot,nn}var uu=cu();const du="modulepreload",pu=function(e){return"/"+e},Ci={},mu=function(t,n,a){let i=Promise.resolve();if(n&&n.length>0){let l=function(h){return Promise.all(h.map(b=>Promise.resolve(b).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const u=document.querySelector("meta[property=csp-nonce]"),p=u?.nonce||u?.getAttribute("nonce");i=l(n.map(h=>{if(h=pu(h),h in Ci)return;Ci[h]=!0;const b=h.endsWith(".css"),m=b?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${h}"]${m}`))return;const f=document.createElement("link");if(f.rel=b?"stylesheet":du,b||(f.as="script"),f.crossOrigin="",f.href=h,p&&f.setAttribute("nonce",p),document.head.appendChild(f),b)return new Promise((x,v)=>{f.addEventListener("load",x),f.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${h}`)))})}))}function o(l){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=l,window.dispatchEvent(u),!u.defaultPrevented)throw l}return i.then(l=>{for(const u of l||[])u.status==="rejected"&&o(u.reason);return t().catch(o)})};var To={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},wi=es.createContext&&es.createContext(To),hu=["attr","size","title"];function fu(e,t){if(e==null)return{};var n,a,i=gu(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(a=0;a<o.length;a++)n=o[a],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function gu(e,t){if(e==null)return{};var n={};for(var a in e)if({}.hasOwnProperty.call(e,a)){if(t.indexOf(a)!==-1)continue;n[a]=e[a]}return n}function kn(){return kn=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)({}).hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},kn.apply(null,arguments)}function Si(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,a)}return n}function Nn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Si(Object(n),!0).forEach(function(a){bu(e,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Si(Object(n)).forEach(function(a){Object.defineProperty(e,a,Object.getOwnPropertyDescriptor(n,a))})}return e}function bu(e,t,n){return(t=Eu(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Eu(e){var t=Tu(e,"string");return typeof t=="symbol"?t:t+""}function Tu(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var a=n.call(e,t);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function xo(e){return e&&e.map((t,n)=>es.createElement(t.tag,Nn({key:n},t.attr),xo(t.child)))}function xe(e){return t=>es.createElement(xu,kn({attr:Nn({},e.attr)},t),xo(e.child))}function xu(e){var t=n=>{var a=e.attr,i=e.size,o=e.title,l=fu(e,hu),u=i||n.size||"1em",p;return n.className&&(p=n.className),e.className&&(p=(p?p+" ":"")+e.className),es.createElement("svg",kn({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,a,l,{className:p,style:Nn(Nn({color:e.color||n.color},n.style),e.style),height:u,width:u,xmlns:"http://www.w3.org/2000/svg"}),o&&es.createElement("title",null,o),e.children)};return wi!==void 0?es.createElement(wi.Consumer,null,n=>t(n)):t(To)}function yu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]},{tag:"line",attr:{x1:"8",y1:"11",x2:"14",y2:"11"},child:[]}]})(e)}function ku(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]},{tag:"line",attr:{x1:"11",y1:"8",x2:"11",y2:"14"},child:[]},{tag:"line",attr:{x1:"8",y1:"11",x2:"14",y2:"11"},child:[]}]})(e)}function hs(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"},child:[]}]})(e)}function tt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"18",y1:"6",x2:"6",y2:"18"},child:[]},{tag:"line",attr:{x1:"6",y1:"6",x2:"18",y2:"18"},child:[]}]})(e)}function yo(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"},child:[]},{tag:"path",attr:{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"},child:[]}]})(e)}function _i(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"},child:[]},{tag:"circle",attr:{cx:"9",cy:"7",r:"4"},child:[]},{tag:"path",attr:{d:"M23 21v-2a4 4 0 0 0-3-3.87"},child:[]},{tag:"path",attr:{d:"M16 3.13a4 4 0 0 1 0 7.75"},child:[]}]})(e)}function Nu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"17 8 12 3 7 8"},child:[]},{tag:"line",attr:{x1:"12",y1:"3",x2:"12",y2:"15"},child:[]}]})(e)}function vu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M7 11V7a5 5 0 0 1 9.9-1"},child:[]}]})(e)}function ut(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"3 6 5 6 21 6"},child:[]},{tag:"path",attr:{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"},child:[]},{tag:"line",attr:{x1:"10",y1:"11",x2:"10",y2:"17"},child:[]},{tag:"line",attr:{x1:"14",y1:"11",x2:"14",y2:"17"},child:[]}]})(e)}function Ai(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"},child:[]}]})(e)}function Vn(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"4 17 10 11 4 5"},child:[]},{tag:"line",attr:{x1:"12",y1:"19",x2:"20",y2:"19"},child:[]}]})(e)}function Ii(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"6"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"2"},child:[]}]})(e)}function Cu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"5"},child:[]},{tag:"line",attr:{x1:"12",y1:"1",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"23"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"},child:[]},{tag:"line",attr:{x1:"1",y1:"12",x2:"3",y2:"12"},child:[]},{tag:"line",attr:{x1:"21",y1:"12",x2:"23",y2:"12"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"},child:[]}]})(e)}function vn(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]}]})(e)}function ji(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"4",y1:"21",x2:"4",y2:"14"},child:[]},{tag:"line",attr:{x1:"4",y1:"10",x2:"4",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"20",y1:"21",x2:"20",y2:"16"},child:[]},{tag:"line",attr:{x1:"20",y1:"12",x2:"20",y2:"3"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"7",y2:"14"},child:[]},{tag:"line",attr:{x1:"9",y1:"8",x2:"15",y2:"8"},child:[]},{tag:"line",attr:{x1:"17",y1:"16",x2:"23",y2:"16"},child:[]}]})(e)}function Cn(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"3"},child:[]},{tag:"path",attr:{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"},child:[]}]})(e)}function _a(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"22",y1:"2",x2:"11",y2:"13"},child:[]},{tag:"polygon",attr:{points:"22 2 15 22 11 13 2 9 22 2"},child:[]}]})(e)}function wn(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]}]})(e)}function wu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"},child:[]},{tag:"polyline",attr:{points:"17 21 17 13 7 13 7 21"},child:[]},{tag:"polyline",attr:{points:"7 3 7 8 15 8"},child:[]}]})(e)}function ko(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"1 4 1 10 7 10"},child:[]},{tag:"path",attr:{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"},child:[]}]})(e)}function Rt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"23 4 23 10 17 10"},child:[]},{tag:"polyline",attr:{points:"1 20 1 14 7 14"},child:[]},{tag:"path",attr:{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"},child:[]}]})(e)}function kt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"5",x2:"12",y2:"19"},child:[]},{tag:"line",attr:{x1:"5",y1:"12",x2:"19",y2:"12"},child:[]}]})(e)}function h1(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"5 3 19 12 5 21 5 3"},child:[]}]})(e)}function Su(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"},child:[]}]})(e)}function da(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"16.5",y1:"9.4",x2:"7.5",y2:"4.21"},child:[]},{tag:"path",attr:{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"},child:[]},{tag:"polyline",attr:{points:"3.27 6.96 12 12.01 20.73 6.96"},child:[]},{tag:"line",attr:{x1:"12",y1:"22.08",x2:"12",y2:"12"},child:[]}]})(e)}function _u(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"1"},child:[]},{tag:"circle",attr:{cx:"19",cy:"12",r:"1"},child:[]},{tag:"circle",attr:{cx:"5",cy:"12",r:"1"},child:[]}]})(e)}function Aa(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"},child:[]},{tag:"line",attr:{x1:"8",y1:"21",x2:"16",y2:"21"},child:[]},{tag:"line",attr:{x1:"12",y1:"17",x2:"12",y2:"21"},child:[]}]})(e)}function Au(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"5",y1:"12",x2:"19",y2:"12"},child:[]}]})(e)}function Iu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"},child:[]}]})(e)}function ts(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},child:[]}]})(e)}function ju(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"3",y1:"12",x2:"21",y2:"12"},child:[]},{tag:"line",attr:{x1:"3",y1:"6",x2:"21",y2:"6"},child:[]},{tag:"line",attr:{x1:"3",y1:"18",x2:"21",y2:"18"},child:[]}]})(e)}function Ru(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"},child:[]}]})(e)}function Lu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"15 3 21 3 21 9"},child:[]},{tag:"polyline",attr:{points:"9 21 3 21 3 15"},child:[]},{tag:"line",attr:{x1:"21",y1:"3",x2:"14",y2:"10"},child:[]},{tag:"line",attr:{x1:"3",y1:"21",x2:"10",y2:"14"},child:[]}]})(e)}function Du(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M7 11V7a5 5 0 0 1 10 0v4"},child:[]}]})(e)}function Pu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"2",x2:"12",y2:"6"},child:[]},{tag:"line",attr:{x1:"12",y1:"18",x2:"12",y2:"22"},child:[]},{tag:"line",attr:{x1:"4.93",y1:"4.93",x2:"7.76",y2:"7.76"},child:[]},{tag:"line",attr:{x1:"16.24",y1:"16.24",x2:"19.07",y2:"19.07"},child:[]},{tag:"line",attr:{x1:"2",y1:"12",x2:"6",y2:"12"},child:[]},{tag:"line",attr:{x1:"18",y1:"12",x2:"22",y2:"12"},child:[]},{tag:"line",attr:{x1:"4.93",y1:"19.07",x2:"7.76",y2:"16.24"},child:[]},{tag:"line",attr:{x1:"16.24",y1:"7.76",x2:"19.07",y2:"4.93"},child:[]}]})(e)}function Ou(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"8",y1:"6",x2:"21",y2:"6"},child:[]},{tag:"line",attr:{x1:"8",y1:"12",x2:"21",y2:"12"},child:[]},{tag:"line",attr:{x1:"8",y1:"18",x2:"21",y2:"18"},child:[]},{tag:"line",attr:{x1:"3",y1:"6",x2:"3.01",y2:"6"},child:[]},{tag:"line",attr:{x1:"3",y1:"12",x2:"3.01",y2:"12"},child:[]},{tag:"line",attr:{x1:"3",y1:"18",x2:"3.01",y2:"18"},child:[]}]})(e)}function Ia(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"},child:[]},{tag:"path",attr:{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"},child:[]}]})(e)}function Sn(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"12 2 2 7 12 12 22 7 12 2"},child:[]},{tag:"polyline",attr:{points:"2 17 12 22 22 17"},child:[]},{tag:"polyline",attr:{points:"2 12 12 17 22 12"},child:[]}]})(e)}function Mu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12.01",y2:"8"},child:[]}]})(e)}function Bu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]},{tag:"circle",attr:{cx:"8.5",cy:"8.5",r:"1.5"},child:[]},{tag:"polyline",attr:{points:"21 15 16 10 5 21"},child:[]}]})(e)}function Ri(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"path",attr:{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"},child:[]},{tag:"line",attr:{x1:"12",y1:"17",x2:"12.01",y2:"17"},child:[]}]})(e)}function Fu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"14",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"3",y:"14",width:"7",height:"7"},child:[]}]})(e)}function No(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"2",y1:"12",x2:"22",y2:"12"},child:[]},{tag:"path",attr:{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"},child:[]}]})(e)}function Li(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"},child:[]}]})(e)}function un(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"6",y1:"3",x2:"6",y2:"15"},child:[]},{tag:"circle",attr:{cx:"18",cy:"6",r:"3"},child:[]},{tag:"circle",attr:{cx:"6",cy:"18",r:"3"},child:[]},{tag:"path",attr:{d:"M18 9a9 9 0 0 1-9 9"},child:[]}]})(e)}function Bt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"},child:[]}]})(e)}function Hu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"},child:[]},{tag:"polyline",attr:{points:"13 2 13 9 20 9"},child:[]}]})(e)}function vo(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"},child:[]},{tag:"polyline",attr:{points:"14 2 14 8 20 8"},child:[]},{tag:"line",attr:{x1:"16",y1:"13",x2:"8",y2:"13"},child:[]},{tag:"line",attr:{x1:"16",y1:"17",x2:"8",y2:"17"},child:[]},{tag:"polyline",attr:{points:"10 9 9 9 8 9"},child:[]}]})(e)}function _n(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"3"},child:[]}]})(e)}function Ys(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M12 20h9"},child:[]},{tag:"path",attr:{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"},child:[]}]})(e)}function An(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"},child:[]}]})(e)}function ss(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"7 10 12 15 17 10"},child:[]},{tag:"line",attr:{x1:"12",y1:"15",x2:"12",y2:"3"},child:[]}]})(e)}function Gs(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"4",y:"4",width:"16",height:"16",rx:"2",ry:"2"},child:[]},{tag:"rect",attr:{x:"9",y:"9",width:"6",height:"6"},child:[]},{tag:"line",attr:{x1:"9",y1:"1",x2:"9",y2:"4"},child:[]},{tag:"line",attr:{x1:"15",y1:"1",x2:"15",y2:"4"},child:[]},{tag:"line",attr:{x1:"9",y1:"20",x2:"9",y2:"23"},child:[]},{tag:"line",attr:{x1:"15",y1:"20",x2:"15",y2:"23"},child:[]},{tag:"line",attr:{x1:"20",y1:"9",x2:"23",y2:"9"},child:[]},{tag:"line",attr:{x1:"20",y1:"14",x2:"23",y2:"14"},child:[]},{tag:"line",attr:{x1:"1",y1:"9",x2:"4",y2:"9"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"4",y2:"14"},child:[]}]})(e)}function Uu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 10 4 15 9 20"},child:[]},{tag:"path",attr:{d:"M20 4v7a4 4 0 0 1-4 4H4"},child:[]}]})(e)}function Dt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"},child:[]}]})(e)}function Di(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"16 18 22 12 16 6"},child:[]},{tag:"polyline",attr:{points:"8 6 2 12 8 18"},child:[]}]})(e)}function ja(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"polyline",attr:{points:"12 6 12 12 16 14"},child:[]}]})(e)}function Pi(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"},child:[]},{tag:"rect",attr:{x:"8",y:"2",width:"8",height:"4",rx:"1",ry:"1"},child:[]}]})(e)}function Co(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"13 17 18 12 13 7"},child:[]},{tag:"polyline",attr:{points:"6 17 11 12 6 7"},child:[]}]})(e)}function wo(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"11 17 6 12 11 7"},child:[]},{tag:"polyline",attr:{points:"18 17 13 12 18 7"},child:[]}]})(e)}function Qn(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"18 15 12 9 6 15"},child:[]}]})(e)}function rs(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 18 15 12 9 6"},child:[]}]})(e)}function Vt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"6 9 12 15 18 9"},child:[]}]})(e)}function Lt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"20 6 9 17 4 12"},child:[]}]})(e)}function Es(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"},child:[]},{tag:"polyline",attr:{points:"22 4 12 14.01 9 11.01"},child:[]}]})(e)}function an(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"},child:[]},{tag:"polyline",attr:{points:"3.27 6.96 12 12.01 20.73 6.96"},child:[]},{tag:"line",attr:{x1:"12",y1:"22.08",x2:"12",y2:"12"},child:[]}]})(e)}function $u(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"},child:[]},{tag:"path",attr:{d:"M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"},child:[]}]})(e)}function qu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"},child:[]},{tag:"path",attr:{d:"M13.73 21a2 2 0 0 1-3.46 0"},child:[]}]})(e)}function Ra(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"19",x2:"12",y2:"5"},child:[]},{tag:"polyline",attr:{points:"5 12 12 5 19 12"},child:[]}]})(e)}function Wu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"5",y1:"12",x2:"19",y2:"12"},child:[]},{tag:"polyline",attr:{points:"12 5 19 12 12 19"},child:[]}]})(e)}function So(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"5",x2:"12",y2:"19"},child:[]},{tag:"polyline",attr:{points:"19 12 12 19 5 12"},child:[]}]})(e)}function _o(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"21 8 21 21 3 21 3 8"},child:[]},{tag:"rect",attr:{x:"1",y:"3",width:"22",height:"5"},child:[]},{tag:"line",attr:{x1:"10",y1:"12",x2:"14",y2:"12"},child:[]}]})(e)}function Ku(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"},child:[]},{tag:"line",attr:{x1:"12",y1:"9",x2:"12",y2:"13"},child:[]},{tag:"line",attr:{x1:"12",y1:"17",x2:"12.01",y2:"17"},child:[]}]})(e)}function Yu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12.01",y2:"16"},child:[]}]})(e)}function Gu(e){return e.map(t=>t.kind==="package"?`pi update npm:${t.name}`:`npm i -g ${t.name}@latest`).join("; ")}function St(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let n=0;n<16;n++)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Yt({trigger:e,open:t,onOpenChange:n,children:a,align:i="right",fit:o=!1,direction:l="down",menuClassName:u,menuRef:p,menuStyle:h}){const b=c.useRef(null);return c.useEffect(()=>{if(!t)return;const m=x=>{b.current&&!b.current.contains(x.target)&&n(!1)},f=x=>{x.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",m),document.addEventListener("keydown",f),()=>{document.removeEventListener("mousedown",m),document.removeEventListener("keydown",f)}},[t,n]),s.jsxs("div",{className:`dropdown ${i} ${o?"fit":""} ${l==="up"?"dd-up":""}`,ref:b,children:[s.jsxs("button",{type:"button",className:"chip",onClick:()=>n(!t),"aria-expanded":t,children:[e,s.jsx(Vt,{className:`dd-caret ${t?"up":""}`})]}),t&&s.jsx("div",{className:`dd-menu ${u??""}`,ref:p,style:h,children:a})]})}function ft({active:e,disabled:t=!1,title:n,onClick:a,children:i}){return s.jsx("button",{type:"button",className:`dd-item ${e?"active":""}`,disabled:t,title:n,onClick:a,children:i})}let pa=null;function zu(e){if(e===void 0){const n=globalThis.document;if(n&&typeof n.baseURI=="string"&&n.baseURI)try{e=new URL(n.baseURI).pathname}catch{}if(e===void 0)return"/"}if(!e||e==="/")return"/";let t=e.replace(/index\.html$/i,"");return t.endsWith("/")||(t+="/"),t}function Ao(){return pa===null&&(pa=zu()),pa}function Vu(e,t){return t==="/"?e:t+e.replace(/^\/+/,"")}function lt(e){return Vu(e,Ao())}const Io="pi-web-ui:token";function Qu(){try{const e=new URL(window.location.href),t=e.searchParams.get("token");t&&(localStorage.setItem(Io,t.trim()),e.searchParams.delete("token"),window.history.replaceState(null,"",e.toString()))}catch{}}function Xu(){try{return localStorage.getItem(Io)??""}catch{return""}}function Ft(e){const t=Xu();return t?`${e}${e.includes("?")?"&":"?"}token=${encodeURIComponent(t)}`:e}const Ju=["zh","en","de","es","fr","it","ja","ko","pt","ru"];function La(e,t,n,a=Ju){const i=(e??"").trim();if(i)return i;for(const l of t??[]){const u=String(l??"").trim().toLowerCase().replace(/_/g,"-");if(!u)continue;if(a.includes(u))return u;const p=u.split("-")[0];if(p&&a.includes(p))return p}const o=(n??"").trim().toLowerCase();return o&&a.includes(o)?o:"en"}const Da="pi-web-ui:lang",Zu={docTitle:"pi-web-ui — pi 编码智能体",cancel:"取消",ok:"确定",save:"保存",close:"关闭",widgetExpand:"点击放大查看完整输出",collapsePanel:"收起面板",expandPanel:"展开面板",dragToResize:"拖拽调整宽度 · 双击复位",loading:"加载中…",connected:"已连接",connecting:"连接中…",reconnecting:"重连中…",language:"语言",langZh:"中文",langEn:"English",langIt:"Italiano",langJa:"日语",langKo:"韩语",langFr:"法语",langDe:"德语",langEs:"西班牙语",langRu:"俄语",langPt:"葡萄牙语",githubRepo:"GitHub 仓库(xing-shuyin/pi-web-ui)",copy:"复制",viewSwitch:"视图切换",chat:"对话",terminal:"终端",selectModel:"选择模型",availableModels:"可用模型",allProviders:"全部",providers:"服务商",noModels:"暂无可用模型(请先配置 API 密钥)",reasoning:"推理",vision:"识图",refreshModels:"刷新模型列表(保留手填,合并新增)",manageModels:"⚙ 管理模型(新增 / 修改)",manageModelsTitle:"管理模型",thinkingLevel:"思考强度",thinking:"思考",thinkingChip:"思考:{level}",sound:"声音",theme:"主题",themeDefault:"深色(默认)",newChat:"新对话",more:"更多",newChatTip:"新建对话(每个浏览器独立保存会话)","thinking.off":"关闭","thinking.minimal":"极简","thinking.low":"低","thinking.medium":"中","thinking.high":"高","thinking.xhigh":"极高","thinking.max":"最大",thinkingUnsupported:"当前模型不支持该级别,已按模型能力就近生效",context:"上下文",contextUsage:"上下文用量",cumulativeCost:"累计成本",sessionMessages:"会话消息数",messages:"消息",pluginStatus:"插件状态",engineBadge:"引擎",working:"工作中",queued:"排队",enterPath:"输入路径,Enter 切换",cwdTip:"工作目录:{path}(点击切换)",cwdGoUp:"上级目录",cwdPickCurrent:"选择当前目录",cwdChoose:"选择",cwdEnter:"进入",cwdEmpty:"(空目录)",cwdNewFolder:"新建文件夹",cwdNewName:"文件夹名称",cwdCreate:"创建",cwdCancel:"取消",cacheHit:"缓存命中",cacheHitTip:"缓存读取 {read} · 缓存写入 {write} · 未命中 {miss}(共 {input} 输入 token)",tps:"t/s",rateTip:"实时生成速率(估算)",folderRef:"文件夹引用:{path}",refOnly:"仅引用:{path}",attachContent:"附加内容:{path}",attachLines:"附加选中行:{path}(第 {start}-{end} 行)",attachImage:"图片:{name}",attachFile:"文件:{name}",removeAttachment:"移除附件",attachHint:"将随下一条消息发送",uploadFile:"添加文件(图片/文本/任意文件,也可直接拖入或粘贴截图)",dropHereToAttach:"松开以添加文件",imageNotSupported:"当前模型不支持识图:图片将交给视觉桥转写(若未配置视觉模型则可能被忽略)",imageLoadFailed:"图片读取失败:{name}",fileLoadFailed:"文件读取失败:{name}",fileTooLarge:"文件过大已跳过(>{size}MB):{name}",foldersNotSupported:"不支持直接拖入文件夹,请展开后选择文件",placeholderStreaming:"智能体正在工作中…回车插队发送,或点「排队」等回答结束后发送",placeholderStreamingQueued:"智能体正在工作中…回车或点「排队」,回答完全结束后发送(本引擎不支持插队)",placeholderIdle:"给 pi 发送消息 — Enter 发送,/ 查看命令",placeholderConnecting:"正在连接服务器…",stopAgent:"停止智能体",stop:"停止",bgTasks:"后台任务",bgTasksTip:"AI 在后台启动的服务(npm run dev & 等)——可逐个停止或全部关闭,对话结束后仍保留",bgTasksEmpty:"暂无后台任务",bgTasksDesc:"AI 运行中启动并仍在监听的进程(按监听端口检测)",bgTaskPort:"端口",bgTaskPid:"PID",bgTaskSince:"启动",bgTaskStop:"停止",bgTaskStopAll:"全部关闭",bgTaskRefresh:"刷新",bgTaskJustNow:"刚刚",bgTaskMinutes:"{n} 分钟前",bgTaskHours:"{n} 小时前",bgTaskDays:"{n} 天前",stopBash:"停止",stopBashTip:"停止正在运行的 bash 命令(对话继续)",supplement:"排队",supplementTip:"加入队列:AI 回答完全结束后才发送(不打断)",steerTip:"插队:立即发送,本回合马上响应(Enter)",queueSteerTag:"插队",queueFollowTag:"排队",queueRemoveTip:"移除此排队消息",queueRecallTip:"撤回并放回输入框(可编辑后重发)",sendTip:"发送(Enter)",quickPhrases:"快捷短语",quickPhrasesDesc:"输入框上方的一排常用短语按钮,点击即发送(会带上当前已选的文件附件,不清空输入框草稿)",quickPhrasesEnabled:"启用快捷短语",quickPhrasesOffHint:"已关闭:输入框上方不再显示快捷短语按钮(已配置的短语保留,可随时重新启用)",quickPhrasesPlaceholder:"输入常用短语…(Enter 添加)",quickPhrasesAdd:"添加",quickPhrasesEmpty:"还没有快捷短语,在下面添加第一条",quickPhrasesTip:"点击发送:{text}",quickPhrasesMoveUp:"上移",quickPhrasesMoveDown:"下移",quickPhrasesDelete:"删除该短语",quickPhrasesEdit:"编辑该短语",quickPhrasesEditPh:"修改短语…(Enter 保存,Esc 取消)",quickPhrasesReset:"恢复默认短语",slashCommands:"命令",slashMenuHint:"↑↓ 选择 · Enter/Tab 补全",slashHelpTitle:"pi 命令",slashHelpHint:"输入 / 随时打开命令列表",slashLoading:"命令列表加载中…(连接服务器后可用)",slashBuiltin:"内置",slashExtension:"扩展",slashPrompt:"模板",slashSkill:"技能",slashPlugin:"插件",slashCopied:"已复制上一条助手回复",slashCopyFailed:"复制失败,请手动复制",slashCopyEmpty:"还没有可复制的助手回复",recentProjects:"最近项目",runningConversations:"运行的对话",elsewhereBadge:"另一处",elsewhereTip:"在其他标签页 / 设备上运行的对话(只读,不可点)",subagentBadge:"子代理",convErrorBadge:"子代理运行报错:{error}",subagentTitle:"子代理 · {title}",historySessions:"历史对话",openHistory:"历史对话",openFiles:"文件列表",streaming:"进行中…",noHistory:"还没有历史对话",current:"当前",messageCount:"{n} 条消息",tuiTip:"pi 终端(TUI)中的对话",deleteProject:"从最近项目移出",deleteProjectConfirm:"确认移出",deleteSession:"删除该对话记录(不可恢复)",deleteSessionConfirm:"确认删除",renameSession:"重命名该对话",renameSessionPlaceholder:"输入新名称…",renameSessionConfirm:"重命名",dismissConversation:"从运行列表移出(历史记录保留)",dismissConversationConfirm:"确认移出",dismissFinishedSubagents:"关闭已结束的子代理({n} 个)",dismissFinishedSubagentsScoped:"关闭该对话下已结束的子代理(含嵌套,{n} 个)",dismissConversationWithSubagents:"同时关闭已结束的子代理({n} 个)?请确认其结果已不再需要,再点一次确认",dismissConversationWithSubagentsMixed:"同时关闭已结束的子代理({n} 个)?运行中的 {m} 个不受影响、父对话暂留;请确认已结束的已不再需要,再点一次确认",dismissStreamingConfirm:"仍在运行,确认强行关闭?(运行将被中止)",dismissFinishedOnly:"仅关已结束({n})",dismissForceAll:"强行全关(含子代理 {n})",forceDismissTitle:"强行关闭本对话及全部 {n} 个子代理(运行中的 {m} 个将被中止)",forceDismissConversation:"强行关闭对话(含全部子代理)",forceDismissConfirm:"确认强行关闭?未结束的运行将被中止,再点一次",noFinishedSubagents:"没有可关闭的已结束子代理",collapseSection:"折叠",expandSection:"展开",emptyChat:"空对话",editReask:"编辑重问",editReaskTip:"修改此问题,并从这里重新提问(会新建一个分支对话,原对话保留)",reaskFromHere:"从此处重新提问",editPlaceholder:"修改问题内容…",editHint:"⌘/Ctrl+Enter 提交 · Esc 取消",editAttachmentHint:"原附件已保留,可粘贴/拖入新图片或文件 · ⌘/Ctrl+Enter 提交 · Esc 取消",expandMsg:"展开",collapseMsg:"收起",toolCalls:"工具调用",bashRuns:"终端运行",images:"图片",update:"更新",updateTip:"检查并更新 pi-web-ui",currentVersion:"当前版本",latestVersion:"最新版本",checkingUpdate:"检查中…",checkUpdate:"检查更新",upToDate:"已是最新版本",updateAvailable:"发现新版本 v{version}",updateJustPublished:"v{version} 刚刚发布,npm 缓存可能尚未同步——若未检测到新版本,请稍后重新检查",updateNow:"在终端中更新",updateTabTitle:"更新 pi-web-ui",updateTerminalHint:"点击后会在可见终端中运行 npm i -g pi-web-ui@latest;完成后重启服务生效(pi-web-ui server restart)。",updatesAllTitle:"全部组件更新",updatesAllBadge:"{n} 个更新",updatesAllUpToDate:"全部组件均为最新",kindWebUi:"Web 界面",kindPiCore:"核心",kindPackage:"组件",updatesAllRefresh:"重新检查全部",updateCheckFailed:"检查失败",updateBtn:"更新",updateAllBtn:"全部更新",updatePkgTabTitle:"更新 {name}",updateAllTabTitle:"更新全部组件",restartService:"重启服务",restartingService:"重启中…",restartServiceTip:"重启 pi-web-ui 服务({name}):本实例由系统服务托管(launchd/systemd/Windows watchdog),进程退出后会被自动拉起,本页会自动重连;更新完成后用它生效",computer:"此电脑",rootDir:"根目录",workspaceRoots:"工作区根",workspaceRootsHint:"文件树可切换到这些根;插件读写这些目录不必再单独授权。",addWorkspaceRoot:"添加为工作区根",addWorkspaceRootHint:"把当前目录加成工作区根(右栏文件树可切换浏览;插件读写该目录不再单独授权)",removeWorkspaceRoot:"移除工作区根",noFiles:"暂无文件",filesTruncated:"目录过大,列表已截断,仅显示前 2000 项",linkFolderTip:"链接文件夹路径到对话",attachInlineTip:"附加内容到对话",referenceTip:"仅引用路径(AI 按需读取)",previewFile:"预览",downloadFile:"下载文件",copyName:"复制名称",copyPath:"复制路径",downloadFailed:"下载失败:{error}",fileNotFoundShort:"文件不存在",pluginMountFailed:"插件 {name} 挂载失败",liveOutputOmitted:`…[前 {n} 字符已省略]…
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-BytY8dx7.js","assets/markdown-D3PKeHAZ.js","assets/xterm-B96xOxS9.js","assets/react-w24rH0km.js","assets/TerminalPanel-DOrYoP_4.css"])))=>i.map(i=>d[i]);
2
+ import{R as es,a as c,j as s,f as tu,s as Xn,h as ri,w as Xt,b as su,c as nu,d as fo,o as _a,z as go,e as au,g as iu,p as is,v as ru,i as bo,k as vi,M as ou,l as lu,m as cu,n as Eo,q as To}from"./markdown-D3PKeHAZ.js";import{r as xo}from"./react-w24rH0km.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))a(i);new MutationObserver(i=>{for(const o of i)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&a(l)}).observe(document,{childList:!0,subtree:!0});function n(i){const o={};return i.integrity&&(o.integrity=i.integrity),i.referrerPolicy&&(o.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?o.credentials="include":i.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function a(i){if(i.ep)return;i.ep=!0;const o=n(i);fetch(i.href,o)}})();var on={},Ci;function uu(){if(Ci)return on;Ci=1;var e=xo();return on.createRoot=e.createRoot,on.hydrateRoot=e.hydrateRoot,on}var du=uu();const pu="modulepreload",mu=function(e){return"/"+e},wi={},hu=function(t,n,a){let i=Promise.resolve();if(n&&n.length>0){let l=function(h){return Promise.all(h.map(b=>Promise.resolve(b).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const u=document.querySelector("meta[property=csp-nonce]"),p=u?.nonce||u?.getAttribute("nonce");i=l(n.map(h=>{if(h=mu(h),h in wi)return;wi[h]=!0;const b=h.endsWith(".css"),m=b?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${h}"]${m}`))return;const f=document.createElement("link");if(f.rel=b?"stylesheet":pu,b||(f.as="script"),f.crossOrigin="",f.href=h,p&&f.setAttribute("nonce",p),document.head.appendChild(f),b)return new Promise((x,v)=>{f.addEventListener("load",x),f.addEventListener("error",()=>v(new Error(`Unable to preload CSS for ${h}`)))})}))}function o(l){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=l,window.dispatchEvent(u),!u.defaultPrevented)throw l}return i.then(l=>{for(const u of l||[])u.status==="rejected"&&o(u.reason);return t().catch(o)})};var yo={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Si=es.createContext&&es.createContext(yo),fu=["attr","size","title"];function gu(e,t){if(e==null)return{};var n,a,i=bu(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(a=0;a<o.length;a++)n=o[a],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function bu(e,t){if(e==null)return{};var n={};for(var a in e)if({}.hasOwnProperty.call(e,a)){if(t.indexOf(a)!==-1)continue;n[a]=e[a]}return n}function Cn(){return Cn=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var a in n)({}).hasOwnProperty.call(n,a)&&(e[a]=n[a])}return e},Cn.apply(null,arguments)}function _i(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,a)}return n}function wn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?_i(Object(n),!0).forEach(function(a){Eu(e,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_i(Object(n)).forEach(function(a){Object.defineProperty(e,a,Object.getOwnPropertyDescriptor(n,a))})}return e}function Eu(e,t,n){return(t=Tu(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Tu(e){var t=xu(e,"string");return typeof t=="symbol"?t:t+""}function xu(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var a=n.call(e,t);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ko(e){return e&&e.map((t,n)=>es.createElement(t.tag,wn({key:n},t.attr),ko(t.child)))}function xe(e){return t=>es.createElement(yu,Cn({attr:wn({},e.attr)},t),ko(e.child))}function yu(e){var t=n=>{var a=e.attr,i=e.size,o=e.title,l=gu(e,fu),u=i||n.size||"1em",p;return n.className&&(p=n.className),e.className&&(p=(p?p+" ":"")+e.className),es.createElement("svg",Cn({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,a,l,{className:p,style:wn(wn({color:e.color||n.color},n.style),e.style),height:u,width:u,xmlns:"http://www.w3.org/2000/svg"}),o&&es.createElement("title",null,o),e.children)};return Si!==void 0?es.createElement(Si.Consumer,null,n=>t(n)):t(yo)}function ku(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]},{tag:"line",attr:{x1:"8",y1:"11",x2:"14",y2:"11"},child:[]}]})(e)}function Nu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]},{tag:"line",attr:{x1:"11",y1:"8",x2:"11",y2:"14"},child:[]},{tag:"line",attr:{x1:"8",y1:"11",x2:"14",y2:"11"},child:[]}]})(e)}function ms(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"},child:[]}]})(e)}function tt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"18",y1:"6",x2:"6",y2:"18"},child:[]},{tag:"line",attr:{x1:"6",y1:"6",x2:"18",y2:"18"},child:[]}]})(e)}function No(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"},child:[]},{tag:"path",attr:{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"},child:[]}]})(e)}function Ai(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"},child:[]},{tag:"circle",attr:{cx:"9",cy:"7",r:"4"},child:[]},{tag:"path",attr:{d:"M23 21v-2a4 4 0 0 0-3-3.87"},child:[]},{tag:"path",attr:{d:"M16 3.13a4 4 0 0 1 0 7.75"},child:[]}]})(e)}function vu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"17 8 12 3 7 8"},child:[]},{tag:"line",attr:{x1:"12",y1:"3",x2:"12",y2:"15"},child:[]}]})(e)}function Cu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M7 11V7a5 5 0 0 1 9.9-1"},child:[]}]})(e)}function dt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"3 6 5 6 21 6"},child:[]},{tag:"path",attr:{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"},child:[]},{tag:"line",attr:{x1:"10",y1:"11",x2:"10",y2:"17"},child:[]},{tag:"line",attr:{x1:"14",y1:"11",x2:"14",y2:"17"},child:[]}]})(e)}function Ii(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"},child:[]}]})(e)}function Jn(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"4 17 10 11 4 5"},child:[]},{tag:"line",attr:{x1:"12",y1:"19",x2:"20",y2:"19"},child:[]}]})(e)}function ji(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"6"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"2"},child:[]}]})(e)}function wu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"5"},child:[]},{tag:"line",attr:{x1:"12",y1:"1",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"23"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"},child:[]},{tag:"line",attr:{x1:"1",y1:"12",x2:"3",y2:"12"},child:[]},{tag:"line",attr:{x1:"21",y1:"12",x2:"23",y2:"12"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"},child:[]}]})(e)}function Sn(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]}]})(e)}function Ri(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"4",y1:"21",x2:"4",y2:"14"},child:[]},{tag:"line",attr:{x1:"4",y1:"10",x2:"4",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"20",y1:"21",x2:"20",y2:"16"},child:[]},{tag:"line",attr:{x1:"20",y1:"12",x2:"20",y2:"3"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"7",y2:"14"},child:[]},{tag:"line",attr:{x1:"9",y1:"8",x2:"15",y2:"8"},child:[]},{tag:"line",attr:{x1:"17",y1:"16",x2:"23",y2:"16"},child:[]}]})(e)}function _n(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"3"},child:[]},{tag:"path",attr:{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"},child:[]}]})(e)}function Aa(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"22",y1:"2",x2:"11",y2:"13"},child:[]},{tag:"polygon",attr:{points:"22 2 15 22 11 13 2 9 22 2"},child:[]}]})(e)}function An(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]}]})(e)}function Su(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"},child:[]},{tag:"polyline",attr:{points:"17 21 17 13 7 13 7 21"},child:[]},{tag:"polyline",attr:{points:"7 3 7 8 15 8"},child:[]}]})(e)}function vo(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"1 4 1 10 7 10"},child:[]},{tag:"path",attr:{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"},child:[]}]})(e)}function jt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"23 4 23 10 17 10"},child:[]},{tag:"polyline",attr:{points:"1 20 1 14 7 14"},child:[]},{tag:"path",attr:{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"},child:[]}]})(e)}function yt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"5",x2:"12",y2:"19"},child:[]},{tag:"line",attr:{x1:"5",y1:"12",x2:"19",y2:"12"},child:[]}]})(e)}function h1(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"5 3 19 12 5 21 5 3"},child:[]}]})(e)}function _u(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"},child:[]}]})(e)}function pa(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"16.5",y1:"9.4",x2:"7.5",y2:"4.21"},child:[]},{tag:"path",attr:{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"},child:[]},{tag:"polyline",attr:{points:"3.27 6.96 12 12.01 20.73 6.96"},child:[]},{tag:"line",attr:{x1:"12",y1:"22.08",x2:"12",y2:"12"},child:[]}]})(e)}function Au(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"1"},child:[]},{tag:"circle",attr:{cx:"19",cy:"12",r:"1"},child:[]},{tag:"circle",attr:{cx:"5",cy:"12",r:"1"},child:[]}]})(e)}function Ia(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"},child:[]},{tag:"line",attr:{x1:"8",y1:"21",x2:"16",y2:"21"},child:[]},{tag:"line",attr:{x1:"12",y1:"17",x2:"12",y2:"21"},child:[]}]})(e)}function Iu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"5",y1:"12",x2:"19",y2:"12"},child:[]}]})(e)}function ju(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"},child:[]}]})(e)}function ts(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},child:[]}]})(e)}function Ru(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"3",y1:"12",x2:"21",y2:"12"},child:[]},{tag:"line",attr:{x1:"3",y1:"6",x2:"21",y2:"6"},child:[]},{tag:"line",attr:{x1:"3",y1:"18",x2:"21",y2:"18"},child:[]}]})(e)}function Lu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"},child:[]}]})(e)}function Du(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"15 3 21 3 21 9"},child:[]},{tag:"polyline",attr:{points:"9 21 3 21 3 15"},child:[]},{tag:"line",attr:{x1:"21",y1:"3",x2:"14",y2:"10"},child:[]},{tag:"line",attr:{x1:"3",y1:"21",x2:"10",y2:"14"},child:[]}]})(e)}function Pu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M7 11V7a5 5 0 0 1 10 0v4"},child:[]}]})(e)}function Ou(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"2",x2:"12",y2:"6"},child:[]},{tag:"line",attr:{x1:"12",y1:"18",x2:"12",y2:"22"},child:[]},{tag:"line",attr:{x1:"4.93",y1:"4.93",x2:"7.76",y2:"7.76"},child:[]},{tag:"line",attr:{x1:"16.24",y1:"16.24",x2:"19.07",y2:"19.07"},child:[]},{tag:"line",attr:{x1:"2",y1:"12",x2:"6",y2:"12"},child:[]},{tag:"line",attr:{x1:"18",y1:"12",x2:"22",y2:"12"},child:[]},{tag:"line",attr:{x1:"4.93",y1:"19.07",x2:"7.76",y2:"16.24"},child:[]},{tag:"line",attr:{x1:"16.24",y1:"7.76",x2:"19.07",y2:"4.93"},child:[]}]})(e)}function Mu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"8",y1:"6",x2:"21",y2:"6"},child:[]},{tag:"line",attr:{x1:"8",y1:"12",x2:"21",y2:"12"},child:[]},{tag:"line",attr:{x1:"8",y1:"18",x2:"21",y2:"18"},child:[]},{tag:"line",attr:{x1:"3",y1:"6",x2:"3.01",y2:"6"},child:[]},{tag:"line",attr:{x1:"3",y1:"12",x2:"3.01",y2:"12"},child:[]},{tag:"line",attr:{x1:"3",y1:"18",x2:"3.01",y2:"18"},child:[]}]})(e)}function ja(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"},child:[]},{tag:"path",attr:{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"},child:[]}]})(e)}function In(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"12 2 2 7 12 12 22 7 12 2"},child:[]},{tag:"polyline",attr:{points:"2 17 12 22 22 17"},child:[]},{tag:"polyline",attr:{points:"2 12 12 17 22 12"},child:[]}]})(e)}function Bu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12.01",y2:"8"},child:[]}]})(e)}function Fu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]},{tag:"circle",attr:{cx:"8.5",cy:"8.5",r:"1.5"},child:[]},{tag:"polyline",attr:{points:"21 15 16 10 5 21"},child:[]}]})(e)}function Li(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"path",attr:{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"},child:[]},{tag:"line",attr:{x1:"12",y1:"17",x2:"12.01",y2:"17"},child:[]}]})(e)}function Hu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"14",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"3",y:"14",width:"7",height:"7"},child:[]}]})(e)}function Co(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"2",y1:"12",x2:"22",y2:"12"},child:[]},{tag:"path",attr:{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"},child:[]}]})(e)}function Di(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"},child:[]}]})(e)}function mn(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"6",y1:"3",x2:"6",y2:"15"},child:[]},{tag:"circle",attr:{cx:"18",cy:"6",r:"3"},child:[]},{tag:"circle",attr:{cx:"6",cy:"18",r:"3"},child:[]},{tag:"path",attr:{d:"M18 9a9 9 0 0 1-9 9"},child:[]}]})(e)}function Bt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"},child:[]}]})(e)}function Uu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"},child:[]},{tag:"polyline",attr:{points:"13 2 13 9 20 9"},child:[]}]})(e)}function wo(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"},child:[]},{tag:"polyline",attr:{points:"14 2 14 8 20 8"},child:[]},{tag:"line",attr:{x1:"16",y1:"13",x2:"8",y2:"13"},child:[]},{tag:"line",attr:{x1:"16",y1:"17",x2:"8",y2:"17"},child:[]},{tag:"polyline",attr:{points:"10 9 9 9 8 9"},child:[]}]})(e)}function jn(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"3"},child:[]}]})(e)}function Ys(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M12 20h9"},child:[]},{tag:"path",attr:{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"},child:[]}]})(e)}function Rn(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"},child:[]}]})(e)}function ss(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"7 10 12 15 17 10"},child:[]},{tag:"line",attr:{x1:"12",y1:"15",x2:"12",y2:"3"},child:[]}]})(e)}function Gs(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"4",y:"4",width:"16",height:"16",rx:"2",ry:"2"},child:[]},{tag:"rect",attr:{x:"9",y:"9",width:"6",height:"6"},child:[]},{tag:"line",attr:{x1:"9",y1:"1",x2:"9",y2:"4"},child:[]},{tag:"line",attr:{x1:"15",y1:"1",x2:"15",y2:"4"},child:[]},{tag:"line",attr:{x1:"9",y1:"20",x2:"9",y2:"23"},child:[]},{tag:"line",attr:{x1:"15",y1:"20",x2:"15",y2:"23"},child:[]},{tag:"line",attr:{x1:"20",y1:"9",x2:"23",y2:"9"},child:[]},{tag:"line",attr:{x1:"20",y1:"14",x2:"23",y2:"14"},child:[]},{tag:"line",attr:{x1:"1",y1:"9",x2:"4",y2:"9"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"4",y2:"14"},child:[]}]})(e)}function $u(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 10 4 15 9 20"},child:[]},{tag:"path",attr:{d:"M20 4v7a4 4 0 0 1-4 4H4"},child:[]}]})(e)}function Lt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"},child:[]}]})(e)}function Pi(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"16 18 22 12 16 6"},child:[]},{tag:"polyline",attr:{points:"8 6 2 12 8 18"},child:[]}]})(e)}function Ra(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"polyline",attr:{points:"12 6 12 12 16 14"},child:[]}]})(e)}function Oi(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"},child:[]},{tag:"rect",attr:{x:"8",y:"2",width:"8",height:"4",rx:"1",ry:"1"},child:[]}]})(e)}function So(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"13 17 18 12 13 7"},child:[]},{tag:"polyline",attr:{points:"6 17 11 12 6 7"},child:[]}]})(e)}function _o(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"11 17 6 12 11 7"},child:[]},{tag:"polyline",attr:{points:"18 17 13 12 18 7"},child:[]}]})(e)}function Zn(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"18 15 12 9 6 15"},child:[]}]})(e)}function rs(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 18 15 12 9 6"},child:[]}]})(e)}function Vt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"6 9 12 15 18 9"},child:[]}]})(e)}function Rt(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"20 6 9 17 4 12"},child:[]}]})(e)}function bs(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"},child:[]},{tag:"polyline",attr:{points:"22 4 12 14.01 9 11.01"},child:[]}]})(e)}function ln(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"},child:[]},{tag:"polyline",attr:{points:"3.27 6.96 12 12.01 20.73 6.96"},child:[]},{tag:"line",attr:{x1:"12",y1:"22.08",x2:"12",y2:"12"},child:[]}]})(e)}function qu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"},child:[]},{tag:"path",attr:{d:"M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"},child:[]}]})(e)}function Wu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"},child:[]},{tag:"path",attr:{d:"M13.73 21a2 2 0 0 1-3.46 0"},child:[]}]})(e)}function La(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"19",x2:"12",y2:"5"},child:[]},{tag:"polyline",attr:{points:"5 12 12 5 19 12"},child:[]}]})(e)}function Ku(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"5",y1:"12",x2:"19",y2:"12"},child:[]},{tag:"polyline",attr:{points:"12 5 19 12 12 19"},child:[]}]})(e)}function Ao(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"5",x2:"12",y2:"19"},child:[]},{tag:"polyline",attr:{points:"19 12 12 19 5 12"},child:[]}]})(e)}function Io(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"21 8 21 21 3 21 3 8"},child:[]},{tag:"rect",attr:{x:"1",y:"3",width:"22",height:"5"},child:[]},{tag:"line",attr:{x1:"10",y1:"12",x2:"14",y2:"12"},child:[]}]})(e)}function Yu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"},child:[]},{tag:"line",attr:{x1:"12",y1:"9",x2:"12",y2:"13"},child:[]},{tag:"line",attr:{x1:"12",y1:"17",x2:"12.01",y2:"17"},child:[]}]})(e)}function Gu(e){return xe({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12.01",y2:"16"},child:[]}]})(e)}function zu(e){return e.map(t=>t.kind==="package"?`pi update npm:${t.name}`:`npm i -g ${t.name}@latest`).join("; ")}function St(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const e=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else for(let n=0;n<16;n++)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function Yt({trigger:e,open:t,onOpenChange:n,children:a,align:i="right",fit:o=!1,direction:l="down",menuClassName:u,menuRef:p,menuStyle:h}){const b=c.useRef(null);return c.useEffect(()=>{if(!t)return;const m=x=>{b.current&&!b.current.contains(x.target)&&n(!1)},f=x=>{x.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",m),document.addEventListener("keydown",f),()=>{document.removeEventListener("mousedown",m),document.removeEventListener("keydown",f)}},[t,n]),s.jsxs("div",{className:`dropdown ${i} ${o?"fit":""} ${l==="up"?"dd-up":""}`,ref:b,children:[s.jsxs("button",{type:"button",className:"chip",onClick:()=>n(!t),"aria-expanded":t,children:[e,s.jsx(Vt,{className:`dd-caret ${t?"up":""}`})]}),t&&s.jsx("div",{className:`dd-menu ${u??""}`,ref:p,style:h,children:a})]})}function ft({active:e,disabled:t=!1,title:n,onClick:a,children:i}){return s.jsx("button",{type:"button",className:`dd-item ${e?"active":""}`,disabled:t,title:n,onClick:a,children:i})}let ma=null;function Vu(e){if(e===void 0){const n=globalThis.document;if(n&&typeof n.baseURI=="string"&&n.baseURI)try{e=new URL(n.baseURI).pathname}catch{}if(e===void 0)return"/"}if(!e||e==="/")return"/";let t=e.replace(/index\.html$/i,"");return t.endsWith("/")||(t+="/"),t}function jo(){return ma===null&&(ma=Vu()),ma}function Qu(e,t){return t==="/"?e:t+e.replace(/^\/+/,"")}function lt(e){return Qu(e,jo())}const Ro="pi-web-ui:token";function Xu(){try{const e=new URL(window.location.href),t=e.searchParams.get("token");t&&(localStorage.setItem(Ro,t.trim()),e.searchParams.delete("token"),window.history.replaceState(null,"",e.toString()))}catch{}}function Ju(){try{return localStorage.getItem(Ro)??""}catch{return""}}function Ft(e){const t=Ju();return t?`${e}${e.includes("?")?"&":"?"}token=${encodeURIComponent(t)}`:e}const Zu=["zh","en","de","es","fr","it","ja","ko","pt","ru"];function Da(e,t,n,a=Zu){const i=(e??"").trim();if(i)return i;for(const l of t??[]){const u=String(l??"").trim().toLowerCase().replace(/_/g,"-");if(!u)continue;if(a.includes(u))return u;const p=u.split("-")[0];if(p&&a.includes(p))return p}const o=(n??"").trim().toLowerCase();return o&&a.includes(o)?o:"en"}const Pa="pi-web-ui:lang",ed={docTitle:"pi-web-ui — pi 编码智能体",cancel:"取消",ok:"确定",save:"保存",close:"关闭",widgetExpand:"点击放大查看完整输出",collapsePanel:"收起面板",expandPanel:"展开面板",dragToResize:"拖拽调整宽度 · 双击复位",loading:"加载中…",connected:"已连接",connecting:"连接中…",reconnecting:"重连中…",language:"语言",langZh:"中文",langEn:"English",langIt:"Italiano",langJa:"日语",langKo:"韩语",langFr:"法语",langDe:"德语",langEs:"西班牙语",langRu:"俄语",langPt:"葡萄牙语",githubRepo:"GitHub 仓库(xing-shuyin/pi-web-ui)",copy:"复制",viewSwitch:"视图切换",chat:"对话",terminal:"终端",selectModel:"选择模型",availableModels:"可用模型",allProviders:"全部",providers:"服务商",noModels:"暂无可用模型(请先配置 API 密钥)",reasoning:"推理",vision:"识图",refreshModels:"刷新模型列表(保留手填,合并新增)",manageModels:"⚙ 管理模型(新增 / 修改)",manageModelsTitle:"管理模型",thinkingLevel:"思考强度",thinking:"思考",thinkingChip:"思考:{level}",sound:"声音",theme:"主题",themeDefault:"深色(默认)",newChat:"新对话",more:"更多",newChatTip:"新建对话(每个浏览器独立保存会话)","thinking.off":"关闭","thinking.minimal":"极简","thinking.low":"低","thinking.medium":"中","thinking.high":"高","thinking.xhigh":"极高","thinking.max":"最大",thinkingUnsupported:"当前模型不支持该级别,已按模型能力就近生效",context:"上下文",contextUsage:"上下文用量",cumulativeCost:"累计成本",sessionMessages:"会话消息数",messages:"消息",pluginStatus:"插件状态",engineBadge:"引擎",working:"工作中",queued:"排队",enterPath:"输入路径,Enter 切换",cwdTip:"工作目录:{path}(点击切换)",cwdGoUp:"上级目录",cwdPickCurrent:"选择当前目录",cwdChoose:"选择",cwdEnter:"进入",cwdEmpty:"(空目录)",cwdNewFolder:"新建文件夹",cwdNewName:"文件夹名称",cwdCreate:"创建",cwdCancel:"取消",cacheHit:"缓存命中",cacheHitTip:"缓存读取 {read} · 缓存写入 {write} · 未命中 {miss}(共 {input} 输入 token)",tps:"t/s",rateTip:"实时生成速率(估算)",folderRef:"文件夹引用:{path}",refOnly:"仅引用:{path}",attachContent:"附加内容:{path}",attachLines:"附加选中行:{path}(第 {start}-{end} 行)",attachImage:"图片:{name}",attachFile:"文件:{name}",removeAttachment:"移除附件",attachHint:"将随下一条消息发送",uploadFile:"添加文件(图片/文本/任意文件,也可直接拖入或粘贴截图)",dropHereToAttach:"松开以添加文件",imageNotSupported:"当前模型不支持识图:图片将交给视觉桥转写(若未配置视觉模型则可能被忽略)",imageLoadFailed:"图片读取失败:{name}",fileLoadFailed:"文件读取失败:{name}",fileTooLarge:"文件过大已跳过(>{size}MB):{name}",foldersNotSupported:"不支持直接拖入文件夹,请展开后选择文件",placeholderStreaming:"智能体正在工作中…回车插队发送,或点「排队」等回答结束后发送",placeholderStreamingQueued:"智能体正在工作中…回车或点「排队」,回答完全结束后发送(本引擎不支持插队)",placeholderIdle:"给 pi 发送消息 — Enter 发送,/ 查看命令",placeholderConnecting:"正在连接服务器…",stopAgent:"停止智能体",stop:"停止",bgTasks:"后台任务",bgTasksTip:"AI 在后台启动的服务(npm run dev & 等)——可逐个停止或全部关闭,对话结束后仍保留",bgTasksEmpty:"暂无后台任务",bgTasksDesc:"AI 运行中启动并仍在监听的进程(按监听端口检测)",bgTaskPort:"端口",bgTaskPid:"PID",bgTaskSince:"启动",bgTaskStop:"停止",bgTaskStopAll:"全部关闭",bgTaskRefresh:"刷新",bgTaskJustNow:"刚刚",bgTaskMinutes:"{n} 分钟前",bgTaskHours:"{n} 小时前",bgTaskDays:"{n} 天前",stopBash:"停止",stopBashTip:"停止正在运行的 bash 命令(对话继续)",supplement:"排队",supplementTip:"加入队列:AI 回答完全结束后才发送(不打断)",steerTip:"插队:立即发送,本回合马上响应(Enter)",queueSteerTag:"插队",queueFollowTag:"排队",queueRemoveTip:"移除此排队消息",queueRecallTip:"撤回并放回输入框(可编辑后重发)",sendTip:"发送(Enter)",quickPhrases:"快捷短语",quickPhrasesDesc:"输入框上方的一排常用短语按钮,点击即发送(会带上当前已选的文件附件,不清空输入框草稿)",quickPhrasesEnabled:"启用快捷短语",quickPhrasesOffHint:"已关闭:输入框上方不再显示快捷短语按钮(已配置的短语保留,可随时重新启用)",quickPhrasesPlaceholder:"输入常用短语…(Enter 添加)",quickPhrasesAdd:"添加",quickPhrasesEmpty:"还没有快捷短语,在下面添加第一条",quickPhrasesTip:"点击发送:{text}",quickPhrasesMoveUp:"上移",quickPhrasesMoveDown:"下移",quickPhrasesDelete:"删除该短语",quickPhrasesEdit:"编辑该短语",quickPhrasesEditPh:"修改短语…(Enter 保存,Esc 取消)",quickPhrasesReset:"恢复默认短语",slashCommands:"命令",slashMenuHint:"↑↓ 选择 · Enter/Tab 补全",slashHelpTitle:"pi 命令",slashHelpHint:"输入 / 随时打开命令列表",slashLoading:"命令列表加载中…(连接服务器后可用)",slashBuiltin:"内置",slashExtension:"扩展",slashPrompt:"模板",slashSkill:"技能",slashPlugin:"插件",slashCopied:"已复制上一条助手回复",slashCopyFailed:"复制失败,请手动复制",slashCopyEmpty:"还没有可复制的助手回复",recentProjects:"最近项目",runningConversations:"运行的对话",elsewhereBadge:"另一处",elsewhereTip:"在其他标签页 / 设备上运行的对话(只读,不可点)",subagentBadge:"子代理",convErrorBadge:"子代理运行报错:{error}",subagentTitle:"子代理 · {title}",historySessions:"历史对话",openHistory:"历史对话",openFiles:"文件列表",streaming:"进行中…",noHistory:"还没有历史对话",current:"当前",messageCount:"{n} 条消息",tuiTip:"pi 终端(TUI)中的对话",deleteProject:"从最近项目移出",deleteProjectConfirm:"确认移出",deleteSession:"删除该对话记录(不可恢复)",deleteSessionConfirm:"确认删除",renameSession:"重命名该对话",renameSessionPlaceholder:"输入新名称…",renameSessionConfirm:"重命名",dismissConversation:"从运行列表移出(历史记录保留)",dismissConversationConfirm:"确认移出",dismissFinishedSubagents:"关闭已结束的子代理({n} 个)",dismissFinishedSubagentsScoped:"关闭该对话下已结束的子代理(含嵌套,{n} 个)",dismissConversationWithSubagents:"同时关闭已结束的子代理({n} 个)?请确认其结果已不再需要,再点一次确认",dismissConversationWithSubagentsMixed:"同时关闭已结束的子代理({n} 个)?运行中的 {m} 个不受影响、父对话暂留;请确认已结束的已不再需要,再点一次确认",dismissStreamingConfirm:"仍在运行,确认强行关闭?(运行将被中止)",dismissFinishedOnly:"仅关已结束({n})",dismissForceAll:"强行全关(含子代理 {n})",forceDismissTitle:"强行关闭本对话及全部 {n} 个子代理(运行中的 {m} 个将被中止)",forceDismissConversation:"强行关闭对话(含全部子代理)",forceDismissConfirm:"确认强行关闭?未结束的运行将被中止,再点一次",noFinishedSubagents:"没有可关闭的已结束子代理",collapseSection:"折叠",expandSection:"展开",emptyChat:"空对话",editReask:"编辑重问",editReaskTip:"修改此问题,并从这里重新提问(会新建一个分支对话,原对话保留)",reaskFromHere:"从此处重新提问",editPlaceholder:"修改问题内容…",editHint:"⌘/Ctrl+Enter 提交 · Esc 取消",editAttachmentHint:"原附件已保留,可粘贴/拖入新图片或文件 · ⌘/Ctrl+Enter 提交 · Esc 取消",expandMsg:"展开",collapseMsg:"收起",toolCalls:"工具调用",bashRuns:"终端运行",images:"图片",update:"更新",updateTip:"检查并更新 pi-web-ui",currentVersion:"当前版本",latestVersion:"最新版本",checkingUpdate:"检查中…",checkUpdate:"检查更新",upToDate:"已是最新版本",updateAvailable:"发现新版本 v{version}",updateJustPublished:"v{version} 刚刚发布,npm 缓存可能尚未同步——若未检测到新版本,请稍后重新检查",updateNow:"在终端中更新",updateTabTitle:"更新 pi-web-ui",updateTerminalHint:"点击后会在可见终端中运行 npm i -g pi-web-ui@latest;完成后重启服务生效(pi-web-ui server restart)。",updatesAllTitle:"全部组件更新",updatesAllBadge:"{n} 个更新",updatesAllUpToDate:"全部组件均为最新",kindWebUi:"Web 界面",kindPiCore:"核心",kindPackage:"组件",updatesAllRefresh:"重新检查全部",updateCheckFailed:"检查失败",updateBtn:"更新",updateAllBtn:"全部更新",updatePkgTabTitle:"更新 {name}",updateAllTabTitle:"更新全部组件",restartService:"重启服务",restartingService:"重启中…",restartServiceTip:"重启 pi-web-ui 服务({name}):本实例由系统服务托管(launchd/systemd/Windows watchdog),进程退出后会被自动拉起,本页会自动重连;更新完成后用它生效",computer:"此电脑",rootDir:"根目录",workspaceRoots:"工作区根",workspaceRootsHint:"文件树可切换到这些根;插件读写这些目录不必再单独授权。",addWorkspaceRoot:"添加为工作区根",addWorkspaceRootHint:"把当前目录加成工作区根(右栏文件树可切换浏览;插件读写该目录不再单独授权)",removeWorkspaceRoot:"移除工作区根",noFiles:"暂无文件",filesTruncated:"目录过大,列表已截断,仅显示前 2000 项",linkFolderTip:"链接文件夹路径到对话",attachInlineTip:"附加内容到对话",referenceTip:"仅引用路径(AI 按需读取)",previewFile:"预览",downloadFile:"下载文件",copyName:"复制名称",copyPath:"复制路径",downloadFailed:"下载失败:{error}",fileNotFoundShort:"文件不存在",pluginMountFailed:"插件 {name} 挂载失败",liveOutputOmitted:`…[前 {n} 字符已省略]…
3
3
  `,uploadToFolder:"上传文件到此文件夹",uploadToCurrentDir:"上传文件到当前目录",openAsProject:"以项目打开",protocolMismatch:"页面版本与服务器不一致(应用刚更新过),请刷新页面以恢复全部功能。",selectLinesHint:"点击选择行;拖拽或 Shift+点击选择范围",enableWrap:"开启自动换行",disableWrap:"关闭自动换行",selectedRange:"已选 {n} 行(第 {start}-{end} 行)",fileLines:"{n} 行",selectAll:"全选",clearSelection:"清除",addToChat:"添加到对话",addedToChat:"已添加",previewTruncated:"⚠ 文件过大,仅预览前 512KB",previewLinesTruncated:"… 文件行数过多,仅显示前 {n} 行",binaryFile:"🔣 二进制文件,已显示前 4KB 十六进制",binaryHexTruncated:"(文件更大,可下载完整文件)",previewNotSupported:"该类型文件不支持预览(仅图片 / 视频 / 文本)",emptyFile:"(空文件)",editFile:"编辑文件",exitEditFile:"退出编辑",saveFile:"保存文件",discardFileChanges:"放弃未保存的修改?",fileSaved:"已保存",fileEditTruncated:"文件过大,预览不完整,无法编辑",showMarkdownSource:"显示 Markdown 原文",showMarkdownPreview:"显示 Markdown 预览",showHtmlSource:"显示 HTML 源码",showHtmlPreview:"显示 HTML 预览",htmlJsOff:"🛡 脚本已禁用(静态预览)",htmlJsOffTip:"当前是纯静态渲染:页面里的 JavaScript 不会执行。只对你信任的文件开启脚本。",htmlJsOn:"⚠ 脚本已启用",htmlJsOnTip:"页面里的 JavaScript 正在运行。它仍碰不到本应用(无同源、无表单、无顶层跳转),但可能产生网络请求或挖矿等行为,仅用于你信任的文件。",htmlEnableJs:"启用脚本",htmlDisableJs:"禁用脚本",fullscreen:"全屏",exitFullscreen:"退出全屏",zoomIn:"放大字号",zoomOut:"缩小字号",resetZoom:"重置缩放",pluginRequest:"插件请求",modelQuestion:"模型提问",modelQuestionCustom:"补充回答(可选)",modelQuestionSubmit:"提交回答",next:"下一步",previous:"上一步",questionStep:"第 {cur} / {total} 题",optionPreview:"选项预览",noOptions:"(无选项)",inputPlaceholder:"输入内容",questionTimeout:"⏳ 剩余 {s} 秒,超时将自动取消",questionTimeoutExpired:"提问已超时,正在恢复对话…",modelNoVision:"当前模型 {name} 不支持图片,请切换到 DeepSeek V4 Flash Vision (exp)",dshSkillsNote:"DSH 引擎使用运行时内置技能(dsh-skill),暂不支持在设置面板启停",dshExtensionsNote:"DSH 引擎无 pi 扩展体系,能力由运行时内置(MCP/subagent/goal/plan/skill 等)",dshReviewPromptNote:"DSH 无独立审查会话:此指令将随目标轮次附加到系统提示词,供模型在目标轮次中遵守",dshVisionHiddenNote:"DSH 引擎直接支持图片输入(仅 DeepSeek V4 Flash Vision (exp) 模型),无需视觉桥转写",dshNoReviewModel:"DSH 无独立审查模型:目标由模型自判定完成/受阻,轮次上限即自动迭代次数",soundHeader:"声音提示",enableSound:"启用声音",preview:"试听",volume:"音量",notifyHeader:"桌面通知",notifyEnable:"启用桌面通知(PWA)",notifyEnableDesc:"会话完成或需要你输入时提醒你(需授权;仅当页面不在你眼前时触发:切到其他应用、最小化窗口或后台标签页;Windows 上窗口最小化后系统给的状态信号是错的,因此 2 分钟没操作页面也照常提醒——宁可多提醒一次也不静默)。",notifyDenied:"通知权限已被拒绝 —— 请在浏览器站点设置里为本站点开启通知(Windows 还要在「设置 → 系统 → 通知」里允许浏览器/应用,并关闭专注助手)。",notifyUnsupported:"此浏览器不支持通知。",notifyInsecure:"当前地址不是安全上下文(非 localhost 的 http 访问),浏览器不提供通知接口 —— 请改用 127.0.0.1 或 HTTPS 打开,或将本机地址加入浏览器白名单。",notifyWindowsHint:"Windows 额外一层系统开关:请允许浏览器(或已安装的 pi-web-ui 应用)在「设置 → 系统 → 通知」里推送,并关闭专注助手/勿扰;关窗后进程结束也不会再提醒。",notifyTest:"发送测试通知",notifyTestBody:"能看到这条系统通知,就说明浏览器和 Windows 都放行了。",notifyTestSent:"已发送(通道:{path})",notifyTestFailed:"发送失败:{error}",notifyTestState:"系统状态:焦点 {focus} · 可见性 {visibility} · 最小化 {minimized} · 空闲 {idle}s",notifyTestHeld:"浏览器已受理(通知中心里现有 {count} 条):屏幕上没弹横幅的话,是 Windows/Edge 的横幅开关或静默设置把它压住了。",notifyTestDropped:"浏览器没有保留这条通知 → Edge 自己把它丢了(站点通知被静默/阻止,或被系统策略丢弃)。",notifyTestGateSuppressed:"当前判定:会被吞掉(系统认为你正看着这个页面)。",notifyTestGateOpen:"当前判定:会正常提醒(系统认为你没在看)。",notifyDoneTitle:"任务完成",notifyDoneBody:"会话已完成,等待你的输入。",notifyQuestionTitle:"需要你回答",notifyQuestionBody:"pi 正在等你回答一个问题。",notifyErrorTitle:"出错了",notifyErrorBody:"一个会话报告了错误。","sound.question":"问卷弹出","sound.question.desc":"ask_user_question 出现时","sound.done":"回复结束","sound.done.desc":"智能体完成一轮回答时","sound.start":"回复开始","sound.start.desc":"智能体开始新一轮时","sound.error":"出错","sound.error.desc":"出现错误提示时",setupTitle:"未检测到 pi agent 配置",setupDesc:"pi-web-ui 需要 pi 的配置目录(~/.pi/agent)和至少一个 API 密钥才能运行智能体。pi 内置了 openai、anthropic、deepseek 等服务商——选一个填密钥即可,全程无需打开终端。",installFailed:"✖ pi agent 安装失败:",retryInstall:"重试安装",skip:"跳过",installDone:"✅ pi agent CLI 已安装。选择服务商并填入 API 密钥即可开始对话:",cliReadyHint:"✅ 本地已检测到 pi agent,选择服务商并填入 API 密钥即可开始对话:",provider:"服务商",configured:"已配置",providerKeyReady:"该服务商已配置密钥,可直接使用或更换新密钥。",apiKey:"API 密钥",saving:"保存中…",saveAndStart:"保存并开始使用",recheck:"重新检测",installing:"正在安装 pi agent CLI…",autoInstall:"自动安装 pi agent",attachment:"附件",plugin:"插件",unknown:"未知",thinkingWait:"正在思考",exitCode:"退出码 {code}",cancelled:"已取消",truncated:"… 内容过长,当前视图已截断",outputTruncated:"… 输出过长,当前视图已截断",refOnlyShort:"仅引用",folderRefShort:"文件夹 · 仅引用",inlineLines:"内联 · {n} 行",inlineLinesRange:"行 {start}-{end}",image:"🖼 图片",bridgedVision:"👁 已转写",bridgedVisionDetail:"图片已由视觉桥转写(当前模型不支持识图)",folderNotExpanded:"文件夹,未展开内容 —— 智能体会按需浏览目录",fileNotExpanded:"文件较大({size}),未展开内容 —— 智能体会按需读取","role.user":"你","role.assistant":"pi","role.tool":"工具","role.bash":"终端","role.branch":"分支摘要","role.compaction":"上下文已压缩",directory:"目录",waitingResponse:"正在等待模型响应…",retryingApi:"大模型 API 出错,正在自动重试({attempt}/{max}):{error}",retryingApiSoon:"大模型 API 出错,正在自动重试:{error}",modelRetryAttempts:"模型报错自动重试次数",modelRetryHint:"大模型 API 调用出错时自动重试的次数。次数用完后本轮停止并标红,可点「重试」手动再试;设为 0 则失败即停。修改即时生效,无需重载。",retryNow:"重试",retryLastTip:"手动重试上次失败的模型请求",compactingContext:"正在压缩上下文,摘要生成中…",compactingReasonManual:"手动触发",compactingReasonThreshold:"上下文达到阈值,自动触发",compactingReasonOverflow:"上下文溢出,自动触发",compactionFrom:"从 {tokens} tokens 压缩",compactionKeptHint:"此前历史已折叠为该摘要,上下文中仅保留最近消息",backToBottom:"回到底部",questionNavTitle:"问题列表",searchPlaceholder:"在对话中搜索…",searchNoResults:"无结果",searchModels:"搜索模型…",noModelMatches:"无匹配模型",modelUsedCount:"已用 {n} 次",searchGlobal:"搜索",searchGlobalTip:"全局搜索:对话 / 项目 / 文件(Ctrl+K)",gsPlaceholder:"搜索项目、历史对话、工作区文件…",gsHint:"输入关键词:搜索历史对话全文(含 AI 回复)、最近项目与当前项目的文件名",gsSessions:"对话",gsProjects:"项目",gsFiles:"文件",gsNoResults:"无匹配结果",gsSearching:"正在搜索…",gsTruncated:"匹配过多,仅显示部分结果",gsCurrentProject:"当前",gsOpenPreview:"打开文件预览",gsNavigate:"选择",gsOpen:"打开",gsCloseHint:"关闭",bgTaskCommand:"命令行",searchPrev:"上一个(Shift+Enter)",searchNext:"下一个(Enter)",searchClose:"关闭(Esc)",questionNavTip:"本对话的全部问题,悬浮展开,点击跳转","tpl.title":"提示词模板","tpl.hint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.clickCard":"点击填入输入框","tpl.editTpl":"编辑 / 删除模板","tpl.openPicker":"提示词模板(常用提示词,随时取用)","tpl.pickerTitle":"提示词模板","tpl.pickerHint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.add":"新建模板","tpl.addDesc":"把常用工作流存成模板","tpl.reset":"恢复默认模板","tpl.resetConfirm":"确认恢复默认?","tpl.builtin":"内置","tpl.custom":"自定义","tpl.newTitle":"新建提示词模板","tpl.editTitle":"编辑提示词模板","tpl.fieldIcon":"图标","tpl.fieldTitle":"标题","tpl.fieldTitlePh":"卡片上显示的短标题","tpl.fieldDesc":"说明","tpl.fieldDescPh":"一句话说明,显示在卡片上","tpl.fieldPrompt":"提示词","tpl.fieldPromptPh":"完整提示词 —— 发送给智能体的内容","tpl.required":"标题和提示词不能为空","tpl.save":"保存修改","tpl.fill":"填入输入框","tpl.fillTip":"填入输入框,可再编辑后发送","tpl.sendNow":"直接发送","tpl.sendTip":"立即作为新对话发送","tpl.delete":"删除","tpl.deleteTip":"删除这个自定义模板","tpl.remove":"移出模板库","tpl.removeTip":"把内置模板移出模板库,可在底部「恢复默认模板」找回","tpl.restore":"恢复默认","tpl.restoreTip":"撤掉你的修改,恢复内置默认","tpl.sk.setup":"仓库初始化","tpl.sk.setup.desc":"让仓库了解它的构建与约定","tpl.sk.setup.prompt":`请先扫描这个仓库,建立「其他工作流都能用」的基础上下文,输出一份简明报告:
4
4
 
5
5
  1. 项目类型、技术栈与目录结构
@@ -156,7 +156,7 @@ import{R as es,a as c,j as s,f as eu,s as zn,h as ii,w as Xt,b as tu,c as su,d a
156
156
 
157
157
  {path}
158
158
 
159
- 只在你确认后打开。`,settingsExtensions:"插件",settingsUiPlugins:"界面插件",noUiPlugins:"未安装界面组件(<dataDir>/plugins/)",dshPatches:"DSH 用户补丁",dshPatchesDesc:"启动时按文件名序加载的 Cordis patch(<dataDir>/dsh-patches/*.yml)。新增/修改后点「重扫」重启运行时生效;失败的文件会被跳过并打印到运行时 stderr。",dshPatchesRescan:"重扫",dshPatchesRescanHint:"重新扫描补丁目录并重启 DSH 运行时使新补丁生效",dshPatchesEmpty:"未放置补丁文件",dshPatchesPath:"补丁目录:",uiPluginNoSource:"手工安装,无来源信息,无法在线更新",uiPluginPerms:"能力声明",pluginSettingsSave:"保存插件设置",pluginSettingsSaving:"保存中…",pluginSettingsReset:"恢复默认",settingsPresets:"预设",settingsSubagentTemplates:"子代理模板",settingsSubagentTemplatesDesc:"配置子代理预设(角色系统提示词 + 技能/扩展白名单 + 可选模型与思考强度)。AI 派生子代理时可选用模板(subagent_spawn 的 template 参数),也可不传按默认运行;停用的模板保留在面板但对 AI 不可见。",noSubagentTemplates:"还没有子代理模板。AI 派生子代理时可选用模板(角色提示词 + 技能/扩展白名单 + 可选模型与思考强度),也可以不传 template 按默认配置运行。",subagentTemplateNew:"新建模板",subagentTemplateEdit:"编辑",subagentTemplateClosed:"已停用",tplDefaultBadge:"默认",subagentTemplateOffHint:"关闭的模板保留在面板、可随时重新启用,但 AI 工具查询不到、不能选择",subagentTemplateEnable:"启用",subagentTemplateDisable:"停用",subagentDefaultModelLabel:"子代理默认模型",subagentFollowMain:"跟随主对话当前模型",subagentDefaultModelHint:"所有子代理的兜底模型(模板里指定的模型和 subagent_spawn 的 model 参数优先级更高);不改主对话模型。",subagentNoModels:"暂无可用的模型(需要先配置服务商 API Key)——子代理将跟随主对话模型。",tplNamePlaceholder:"模板名(AI 用 subagent_spawn 的 template 参数引用)…",tplDescriptionPlaceholder:"简介(AI 据此判断适用场景)…",tplDescriptionEnPlaceholder:"英文简介(英文 UI 时 AI 看这个,留空则用中文简介)…",tplPromptModeLabel:"系统提示词模式",tplModelLabel:"模型(空 = 跟随主对话)",tplThinkingLabel:"思考强度",tplThinkingFollowMain:"跟随主对话当前思考强度",tplThinkingHint:"空 = 跟随主对话当前思考强度(与不指定模型时的「跟随主对话」同语义);模型不支持所选档位时自动收敛到最接近的可用档位。",tplSystemPromptLabel:"系统提示词",tplSystemPromptPlaceholder:"模板角色系统提示词…(append 模式可留空)",tplSystemPromptEnPlaceholder:"英文系统提示词…(英文 UI 时生效,留空则用中文)",tplWhitelistHint:"白名单:勾选 = 子代理只启用这些;全部不勾 = 跟随主会话设置",tplSkillsLabel:"技能白名单",tplExtensionsLabel:"扩展白名单",tplSave:"保存模板",tplCancel:"取消编辑",tplDelete:"删除模板",tplInherit:"跟随主会话",settingsEnabled:"已启用",settingsDisabled:"已禁用",presetNamePlaceholder:"预设名称…",saveAsPreset:"保存为预设",applyPreset:"应用",deletePreset:"删除预设",noSkills:"暂无技能",noExtensions:"暂无插件",noPresets:"暂无预设(先调整上面的设置,再保存为预设组合)",loadingSession:"正在加载会话…",connectingServer:"正在连接 pi-web-ui 服务器…",localePacks:"语言包",localeGetMore:"获取更多语言",localeInstalled:"已安装",localeInstall:"下载",localeRemove:"移除",localeDownloading:"下载中…",localeRemoving:"移除中…",localeInstallFailed:"下载失败:{error}",localeListFailed:"获取语言包列表失败:{error}",localeRemoveHint:"移除后随时可重新下载",wallpaperTitle:"聊天背景图",wallpaperDesc:"给整个窗口加一张背景图(左右面板、顶栏、底栏也会透出):主题自带的图会自动生效,在此填地址则优先用你的;用压暗与模糊保证文字清晰。",wallpaperUrlPh:"图片地址(https://…,留空关闭)",wallpaperDim:"压暗",wallpaperBlur:"模糊",wallpaperClear:"清除",wallpaperUpload:"上传图片",wallpaperUploadFailed:"图片读取失败或过大,请换一张试试",skillFullTextLabel:"技能全文注入",skillFullTextDesc:"把技能文件正文直接展开进系统提示词(单文件 8KB、总量 32KB 封顶),否则只列名录由模型按需读取",skillFullTextShort:"全文",delegateOpenSubagent:"查看子代理",delegateSecTask:"任务",delegateSecExpected:"期望产出",delegateSecTools:"可用工具",delegateSecMustDo:"必须做",delegateSecMustNotDo:"禁止做",delegateSecContext:"上下文"},ed={docTitle:"pi-web-ui — pi coding agent",cancel:"Cancel",ok:"OK",save:"Save",close:"Close",widgetExpand:"Click to view full output",collapsePanel:"Collapse panel",expandPanel:"Expand panel",dragToResize:"Drag to resize · double-click to reset",loading:"Loading…",connected:"Connected",connecting:"Connecting…",reconnecting:"Reconnecting…",language:"Language",langZh:"中文",langEn:"English",langIt:"Italiano",langJa:"日本語",langKo:"한국어",langFr:"Français",langDe:"Deutsch",langEs:"Español",langRu:"Русский",langPt:"Português",githubRepo:"GitHub repository (xing-shuyin/pi-web-ui)",copy:"Copy",viewSwitch:"Switch view",chat:"Chat",terminal:"Terminal",selectModel:"Select model",availableModels:"Available models",allProviders:"All",providers:"Providers",noModels:"No models available (configure an API key first)",reasoning:"reasoning",vision:"vision",refreshModels:"Refresh model list (keeps manual rows, merges new ones)",manageModels:"⚙ Manage models (add / edit)",manageModelsTitle:"Manage models",thinkingLevel:"Thinking level",thinking:"Thinking",thinkingChip:"Thinking: {level}",sound:"Sound",theme:"Theme",themeDefault:"Dark (default)",newChat:"New chat",more:"More",newChatTip:"New chat (sessions are saved per browser)","thinking.off":"Off","thinking.minimal":"Minimal","thinking.low":"Low","thinking.medium":"Medium","thinking.high":"High","thinking.xhigh":"Extra high","thinking.max":"Max",thinkingUnsupported:"Not supported by this model — snapped to the nearest supported level",context:"Context",contextUsage:"Context usage",cumulativeCost:"Cumulative cost",sessionMessages:"Session messages",messages:"messages",pluginStatus:"Plugin status",engineBadge:"Engine",working:"Working",queued:"queued",enterPath:"Type a path, Enter to switch",cwdTip:"Working directory: {path} (click to switch)",cwdGoUp:"Up one level",cwdPickCurrent:"Select this folder",cwdChoose:"Select",cwdEnter:"Enter",cwdEmpty:"(empty)",cwdNewFolder:"New folder",cwdNewName:"Folder name",cwdCreate:"Create",cwdCancel:"Cancel",cacheHit:"Cache hit",cacheHitTip:"read {read} · write {write} · miss {miss} (of {input} input tokens)",tps:"t/s",rateTip:"Live generation rate (estimated)",folderRef:"Folder reference: {path}",refOnly:"Reference only: {path}",attachContent:"Attached content: {path}",attachLines:"Attached selected lines: {path} (lines {start}-{end})",attachImage:"Image: {name}",attachFile:"File: {name}",removeAttachment:"Remove attachment",attachHint:"Will be sent with the next message",uploadFile:"Add files (images / text / any file — or drag in / paste a screenshot)",dropHereToAttach:"Release to attach file",imageNotSupported:"The current model doesn't support vision — images will be transcribed by the vision bridge (may be ignored if no vision model is configured)",imageLoadFailed:"Couldn't read image: {name}",fileLoadFailed:"Couldn't read file: {name}",fileTooLarge:"File too large, skipped (> {size}MB): {name}",foldersNotSupported:"Folders can't be dropped directly — expand and pick files instead",placeholderStreaming:"The agent is working… press Enter to steer, or click Queue to send after the reply finishes",placeholderStreamingQueued:"The agent is working… press Enter or click Queue — delivered after the reply finishes (this engine cannot steer)",placeholderIdle:"Message pi — Enter to send, / for commands",placeholderConnecting:"Connecting to server…",stopAgent:"Stop agent",stop:"Stop",bgTasks:"Background tasks",bgTasksTip:"Servers the AI started in the background (npm run dev & etc.) — stop them individually or all at once; they survive the conversation",bgTasksEmpty:"No background tasks",bgTasksDesc:"Processes the AI started that are still listening (detected by port)",bgTaskPort:"Port",bgTaskPid:"PID",bgTaskSince:"Started",bgTaskStop:"Stop",bgTaskStopAll:"Stop all",bgTaskRefresh:"Refresh",bgTaskJustNow:"just now",bgTaskMinutes:"{n} min ago",bgTaskHours:"{n} hr ago",bgTaskDays:"{n} days ago",stopBash:"Stop",stopBashTip:"Stop the running bash command (conversation continues)",supplement:"Queue",supplementTip:"Add to queue: sent only after the whole run finishes (no interruption)",steerTip:"Steer: send right away — the current turn responds immediately (Enter)",queueSteerTag:"Steer",queueFollowTag:"Queued",queueRemoveTip:"Remove this queued message",queueRecallTip:"Recall into the input box for editing",sendTip:"Send (Enter)",quickPhrases:"Quick phrases",quickPhrasesDesc:"A row of frequently-used phrase buttons above the input box — click to send (current file attachments are included, the input draft is kept)",quickPhrasesEnabled:"Enable quick phrases",quickPhrasesOffHint:"Off: the phrase buttons above the input box are hidden (saved phrases are kept and can be re-enabled anytime)",quickPhrasesPlaceholder:"Type a frequently-used phrase… (Enter to add)",quickPhrasesAdd:"Add",quickPhrasesEmpty:"No quick phrases yet — add your first one below",quickPhrasesTip:"Click to send: {text}",quickPhrasesMoveUp:"Move up",quickPhrasesMoveDown:"Move down",quickPhrasesDelete:"Delete this phrase",quickPhrasesEdit:"Edit this phrase",quickPhrasesEditPh:"Edit phrase… (Enter to save, Esc to cancel)",quickPhrasesReset:"Reset to defaults",slashCommands:"Commands",slashMenuHint:"↑↓ select · Enter/Tab complete",slashHelpTitle:"pi commands",slashHelpHint:"Type / anytime to open the command list",slashLoading:"Loading commands… (available once connected)",slashBuiltin:"Builtin",slashExtension:"Extension",slashPrompt:"Template",slashSkill:"Skill",slashPlugin:"Plugin",slashCopied:"Copied the last assistant reply",slashCopyFailed:"Copy failed — please copy manually",slashCopyEmpty:"No assistant reply to copy yet",recentProjects:"Recent projects",runningConversations:"Running chats",elsewhereBadge:"Elsewhere",elsewhereTip:"Conversation running in another tab / device (read-only)",subagentBadge:"Subagent",convErrorBadge:"Subagent failed: {error}",subagentTitle:"Subagent · {title}",historySessions:"History",openHistory:"History",openFiles:"Files",streaming:"Streaming…",noHistory:"No previous chats",current:"Current",messageCount:"{n} messages",tuiTip:"Chat in the pi terminal (TUI)",deleteProject:"Remove from recent projects",deleteProjectConfirm:"Confirm remove",deleteSession:"Delete this chat transcript permanently",deleteSessionConfirm:"Confirm delete",renameSession:"Rename this chat",renameSessionPlaceholder:"Type a new name…",renameSessionConfirm:"Rename",dismissConversation:"Dismiss from running (keep in history)",dismissConversationConfirm:"Confirm dismiss",dismissFinishedSubagents:"Dismiss finished subagents ({n})",dismissFinishedSubagentsScoped:"Dismiss finished subagents under this chat, incl. nested ({n})",dismissConversationWithSubagents:"Also dismiss finished subagents ({n})? Make sure their results are no longer needed — click again to confirm",dismissConversationWithSubagentsMixed:"Also dismiss finished subagents ({n})? {m} running one(s) stay, parent stays; make sure the finished ones are no longer needed — click again to confirm",dismissStreamingConfirm:"Still running — confirm force-dismiss? (The run will be aborted)",dismissFinishedOnly:"Dismiss finished only ({n})",dismissForceAll:"Force-dismiss all (incl. {n} subagent(s))",forceDismissTitle:"Force-dismiss this conversation and all {n} subagent(s) ({m} running will be aborted)",forceDismissConversation:"Force-dismiss conversation (incl. all subagents)",forceDismissConfirm:"Confirm force-dismiss? Unfinished runs will be aborted — click again",noFinishedSubagents:"No finished subagents to dismiss",collapseSection:"Collapse",expandSection:"Expand",emptyChat:"Empty chat",editReask:"Edit & re-ask",editReaskTip:"Edit this question and re-ask from here (forks a new conversation; the original is kept)",reaskFromHere:"Re-ask from here",editPlaceholder:"Edit the question…",editHint:"⌘/Ctrl+Enter to submit · Esc to cancel",editAttachmentHint:"Original attachments kept — paste/drop images or files · ⌘/Ctrl+Enter to submit · Esc to cancel",expandMsg:"Expand",collapseMsg:"Collapse",toolCalls:"tool calls",bashRuns:"bash runs",images:"images",update:"Update",updateTip:"Check & update pi-web-ui",currentVersion:"Current version",latestVersion:"Latest version",checkingUpdate:"Checking…",checkUpdate:"Check for updates",upToDate:"You're up to date",updateAvailable:"New version v{version} available",updateJustPublished:"v{version} was just published — npm cache may lag; if the new version isn't detected yet, re-check in a moment",updateNow:"Update in terminal",updateTabTitle:"Update pi-web-ui",updateTerminalHint:"Clicking runs npm i -g pi-web-ui@latest in a visible terminal; restart the service afterwards to take effect (pi-web-ui server restart).",updatesAllTitle:"Component updates",updatesAllBadge:"{n} updates",updatesAllUpToDate:"All components up to date",kindWebUi:"Web UI",kindPiCore:"Core",kindPackage:"Package",updatesAllRefresh:"Re-check all",updateCheckFailed:"Check failed",updateBtn:"Update",updateAllBtn:"Update all",updatePkgTabTitle:"Update {name}",updateAllTabTitle:"Update all components",restartService:"Restart service",restartingService:"Restarting…",restartServiceTip:"Restart the pi-web-ui service ({name}): this instance is supervised (launchd/systemd/Windows watchdog), so it comes back automatically and the page reconnects — run it after an update",computer:"This PC",rootDir:"Root",workspaceRoots:"Workspace roots",workspaceRootsHint:"Roots the file tree can switch to; plugins may read and write them without a separate prompt.",addWorkspaceRoot:"Add as workspace root",addWorkspaceRootHint:"Add the current directory as a workspace root (switchable in the file tree; plugins may read/write it without a separate prompt)",removeWorkspaceRoot:"Remove workspace root",noFiles:"No files",filesTruncated:"Directory too large — list truncated (first 2000 shown)",linkFolderTip:"Link folder path to chat",attachInlineTip:"Attach content to chat",referenceTip:"Reference path only (AI reads on demand)",previewFile:"Preview",downloadFile:"Download file",copyName:"Copy name",copyPath:"Copy path",downloadFailed:"Download failed: {error}",fileNotFoundShort:"File not found",pluginMountFailed:"Plugin {name} failed to mount",liveOutputOmitted:`…[{n} chars omitted above]…
159
+ 只在你确认后打开。`,settingsExtensions:"插件",settingsUiPlugins:"界面插件",noUiPlugins:"未安装界面组件(<dataDir>/plugins/)",dshPatches:"DSH 用户补丁",dshPatchesDesc:"启动时按文件名序加载的 Cordis patch(<dataDir>/dsh-patches/*.yml)。新增/修改后点「重扫」重启运行时生效;失败的文件会被跳过并打印到运行时 stderr。",dshPatchesRescan:"重扫",dshPatchesRescanHint:"重新扫描补丁目录并重启 DSH 运行时使新补丁生效",dshPatchesEmpty:"未放置补丁文件",dshPatchesPath:"补丁目录:",uiPluginNoSource:"手工安装,无来源信息,无法在线更新",uiPluginPerms:"能力声明",pluginSettingsSave:"保存插件设置",pluginSettingsSaving:"保存中…",pluginSettingsReset:"恢复默认",settingsPresets:"预设",settingsSubagentTemplates:"子代理模板",settingsSubagentTemplatesDesc:"配置子代理预设(角色系统提示词 + 技能/扩展白名单 + 可选模型与思考强度)。AI 派生子代理时可选用模板(subagent_spawn 的 template 参数),也可不传按默认运行;停用的模板保留在面板但对 AI 不可见。",noSubagentTemplates:"还没有子代理模板。AI 派生子代理时可选用模板(角色提示词 + 技能/扩展白名单 + 可选模型与思考强度),也可以不传 template 按默认配置运行。",subagentTemplateNew:"新建模板",subagentTemplateEdit:"编辑",subagentTemplateClosed:"已停用",tplDefaultBadge:"默认",subagentTemplateOffHint:"关闭的模板保留在面板、可随时重新启用,但 AI 工具查询不到、不能选择",subagentTemplateEnable:"启用",subagentTemplateDisable:"停用",subagentDefaultModelLabel:"子代理默认模型",subagentFollowMain:"跟随主对话当前模型",subagentDefaultModelHint:"所有子代理的兜底模型(模板里指定的模型和 subagent_spawn 的 model 参数优先级更高);不改主对话模型。",subagentNoModels:"暂无可用的模型(需要先配置服务商 API Key)——子代理将跟随主对话模型。",tplNamePlaceholder:"模板名(AI 用 subagent_spawn 的 template 参数引用)…",tplDescriptionPlaceholder:"简介(AI 据此判断适用场景)…",tplDescriptionEnPlaceholder:"英文简介(英文 UI 时 AI 看这个,留空则用中文简介)…",tplPromptModeLabel:"系统提示词模式",tplModelLabel:"模型(空 = 跟随主对话)",tplThinkingLabel:"思考强度",tplThinkingFollowMain:"跟随主对话当前思考强度",tplThinkingHint:"空 = 跟随主对话当前思考强度(与不指定模型时的「跟随主对话」同语义);模型不支持所选档位时自动收敛到最接近的可用档位。",tplSystemPromptLabel:"系统提示词",tplSystemPromptPlaceholder:"模板角色系统提示词…(append 模式可留空)",tplSystemPromptEnPlaceholder:"英文系统提示词…(英文 UI 时生效,留空则用中文)",tplWhitelistHint:"白名单:勾选 = 子代理只启用这些;全部不勾 = 跟随主会话设置",tplSkillsLabel:"技能白名单",tplExtensionsLabel:"扩展白名单",tplSave:"保存模板",tplCancel:"取消编辑",tplDelete:"删除模板",tplInherit:"跟随主会话",settingsEnabled:"已启用",settingsDisabled:"已禁用",presetNamePlaceholder:"预设名称…",saveAsPreset:"保存为预设",applyPreset:"应用",deletePreset:"删除预设",noSkills:"暂无技能",noExtensions:"暂无插件",noPresets:"暂无预设(先调整上面的设置,再保存为预设组合)",loadingSession:"正在加载会话…",connectingServer:"正在连接 pi-web-ui 服务器…",localePacks:"语言包",localeGetMore:"获取更多语言",localeInstalled:"已安装",localeInstall:"下载",localeRemove:"移除",localeDownloading:"下载中…",localeRemoving:"移除中…",localeInstallFailed:"下载失败:{error}",localeListFailed:"获取语言包列表失败:{error}",localeRemoveHint:"移除后随时可重新下载",wallpaperTitle:"聊天背景图",wallpaperDesc:"给整个窗口加一张背景图(左右面板、顶栏、底栏也会透出):主题自带的图会自动生效,在此填地址则优先用你的;用压暗与模糊保证文字清晰。",wallpaperUrlPh:"图片地址(https://…,留空关闭)",wallpaperDim:"压暗",wallpaperBlur:"模糊",wallpaperClear:"清除",wallpaperUpload:"上传图片",wallpaperUploadFailed:"图片读取失败或过大,请换一张试试",skillFullTextLabel:"技能全文注入",skillFullTextDesc:"把技能文件正文直接展开进系统提示词(单文件 8KB、总量 32KB 封顶),否则只列名录由模型按需读取",skillFullTextShort:"全文",delegateOpenSubagent:"查看子代理",delegateSecTask:"任务",delegateSecExpected:"期望产出",delegateSecTools:"可用工具",delegateSecMustDo:"必须做",delegateSecMustNotDo:"禁止做",delegateSecContext:"上下文"},td={docTitle:"pi-web-ui — pi coding agent",cancel:"Cancel",ok:"OK",save:"Save",close:"Close",widgetExpand:"Click to view full output",collapsePanel:"Collapse panel",expandPanel:"Expand panel",dragToResize:"Drag to resize · double-click to reset",loading:"Loading…",connected:"Connected",connecting:"Connecting…",reconnecting:"Reconnecting…",language:"Language",langZh:"中文",langEn:"English",langIt:"Italiano",langJa:"日本語",langKo:"한국어",langFr:"Français",langDe:"Deutsch",langEs:"Español",langRu:"Русский",langPt:"Português",githubRepo:"GitHub repository (xing-shuyin/pi-web-ui)",copy:"Copy",viewSwitch:"Switch view",chat:"Chat",terminal:"Terminal",selectModel:"Select model",availableModels:"Available models",allProviders:"All",providers:"Providers",noModels:"No models available (configure an API key first)",reasoning:"reasoning",vision:"vision",refreshModels:"Refresh model list (keeps manual rows, merges new ones)",manageModels:"⚙ Manage models (add / edit)",manageModelsTitle:"Manage models",thinkingLevel:"Thinking level",thinking:"Thinking",thinkingChip:"Thinking: {level}",sound:"Sound",theme:"Theme",themeDefault:"Dark (default)",newChat:"New chat",more:"More",newChatTip:"New chat (sessions are saved per browser)","thinking.off":"Off","thinking.minimal":"Minimal","thinking.low":"Low","thinking.medium":"Medium","thinking.high":"High","thinking.xhigh":"Extra high","thinking.max":"Max",thinkingUnsupported:"Not supported by this model — snapped to the nearest supported level",context:"Context",contextUsage:"Context usage",cumulativeCost:"Cumulative cost",sessionMessages:"Session messages",messages:"messages",pluginStatus:"Plugin status",engineBadge:"Engine",working:"Working",queued:"queued",enterPath:"Type a path, Enter to switch",cwdTip:"Working directory: {path} (click to switch)",cwdGoUp:"Up one level",cwdPickCurrent:"Select this folder",cwdChoose:"Select",cwdEnter:"Enter",cwdEmpty:"(empty)",cwdNewFolder:"New folder",cwdNewName:"Folder name",cwdCreate:"Create",cwdCancel:"Cancel",cacheHit:"Cache hit",cacheHitTip:"read {read} · write {write} · miss {miss} (of {input} input tokens)",tps:"t/s",rateTip:"Live generation rate (estimated)",folderRef:"Folder reference: {path}",refOnly:"Reference only: {path}",attachContent:"Attached content: {path}",attachLines:"Attached selected lines: {path} (lines {start}-{end})",attachImage:"Image: {name}",attachFile:"File: {name}",removeAttachment:"Remove attachment",attachHint:"Will be sent with the next message",uploadFile:"Add files (images / text / any file — or drag in / paste a screenshot)",dropHereToAttach:"Release to attach file",imageNotSupported:"The current model doesn't support vision — images will be transcribed by the vision bridge (may be ignored if no vision model is configured)",imageLoadFailed:"Couldn't read image: {name}",fileLoadFailed:"Couldn't read file: {name}",fileTooLarge:"File too large, skipped (> {size}MB): {name}",foldersNotSupported:"Folders can't be dropped directly — expand and pick files instead",placeholderStreaming:"The agent is working… press Enter to steer, or click Queue to send after the reply finishes",placeholderStreamingQueued:"The agent is working… press Enter or click Queue — delivered after the reply finishes (this engine cannot steer)",placeholderIdle:"Message pi — Enter to send, / for commands",placeholderConnecting:"Connecting to server…",stopAgent:"Stop agent",stop:"Stop",bgTasks:"Background tasks",bgTasksTip:"Servers the AI started in the background (npm run dev & etc.) — stop them individually or all at once; they survive the conversation",bgTasksEmpty:"No background tasks",bgTasksDesc:"Processes the AI started that are still listening (detected by port)",bgTaskPort:"Port",bgTaskPid:"PID",bgTaskSince:"Started",bgTaskStop:"Stop",bgTaskStopAll:"Stop all",bgTaskRefresh:"Refresh",bgTaskJustNow:"just now",bgTaskMinutes:"{n} min ago",bgTaskHours:"{n} hr ago",bgTaskDays:"{n} days ago",stopBash:"Stop",stopBashTip:"Stop the running bash command (conversation continues)",supplement:"Queue",supplementTip:"Add to queue: sent only after the whole run finishes (no interruption)",steerTip:"Steer: send right away — the current turn responds immediately (Enter)",queueSteerTag:"Steer",queueFollowTag:"Queued",queueRemoveTip:"Remove this queued message",queueRecallTip:"Recall into the input box for editing",sendTip:"Send (Enter)",quickPhrases:"Quick phrases",quickPhrasesDesc:"A row of frequently-used phrase buttons above the input box — click to send (current file attachments are included, the input draft is kept)",quickPhrasesEnabled:"Enable quick phrases",quickPhrasesOffHint:"Off: the phrase buttons above the input box are hidden (saved phrases are kept and can be re-enabled anytime)",quickPhrasesPlaceholder:"Type a frequently-used phrase… (Enter to add)",quickPhrasesAdd:"Add",quickPhrasesEmpty:"No quick phrases yet — add your first one below",quickPhrasesTip:"Click to send: {text}",quickPhrasesMoveUp:"Move up",quickPhrasesMoveDown:"Move down",quickPhrasesDelete:"Delete this phrase",quickPhrasesEdit:"Edit this phrase",quickPhrasesEditPh:"Edit phrase… (Enter to save, Esc to cancel)",quickPhrasesReset:"Reset to defaults",slashCommands:"Commands",slashMenuHint:"↑↓ select · Enter/Tab complete",slashHelpTitle:"pi commands",slashHelpHint:"Type / anytime to open the command list",slashLoading:"Loading commands… (available once connected)",slashBuiltin:"Builtin",slashExtension:"Extension",slashPrompt:"Template",slashSkill:"Skill",slashPlugin:"Plugin",slashCopied:"Copied the last assistant reply",slashCopyFailed:"Copy failed — please copy manually",slashCopyEmpty:"No assistant reply to copy yet",recentProjects:"Recent projects",runningConversations:"Running chats",elsewhereBadge:"Elsewhere",elsewhereTip:"Conversation running in another tab / device (read-only)",subagentBadge:"Subagent",convErrorBadge:"Subagent failed: {error}",subagentTitle:"Subagent · {title}",historySessions:"History",openHistory:"History",openFiles:"Files",streaming:"Streaming…",noHistory:"No previous chats",current:"Current",messageCount:"{n} messages",tuiTip:"Chat in the pi terminal (TUI)",deleteProject:"Remove from recent projects",deleteProjectConfirm:"Confirm remove",deleteSession:"Delete this chat transcript permanently",deleteSessionConfirm:"Confirm delete",renameSession:"Rename this chat",renameSessionPlaceholder:"Type a new name…",renameSessionConfirm:"Rename",dismissConversation:"Dismiss from running (keep in history)",dismissConversationConfirm:"Confirm dismiss",dismissFinishedSubagents:"Dismiss finished subagents ({n})",dismissFinishedSubagentsScoped:"Dismiss finished subagents under this chat, incl. nested ({n})",dismissConversationWithSubagents:"Also dismiss finished subagents ({n})? Make sure their results are no longer needed — click again to confirm",dismissConversationWithSubagentsMixed:"Also dismiss finished subagents ({n})? {m} running one(s) stay, parent stays; make sure the finished ones are no longer needed — click again to confirm",dismissStreamingConfirm:"Still running — confirm force-dismiss? (The run will be aborted)",dismissFinishedOnly:"Dismiss finished only ({n})",dismissForceAll:"Force-dismiss all (incl. {n} subagent(s))",forceDismissTitle:"Force-dismiss this conversation and all {n} subagent(s) ({m} running will be aborted)",forceDismissConversation:"Force-dismiss conversation (incl. all subagents)",forceDismissConfirm:"Confirm force-dismiss? Unfinished runs will be aborted — click again",noFinishedSubagents:"No finished subagents to dismiss",collapseSection:"Collapse",expandSection:"Expand",emptyChat:"Empty chat",editReask:"Edit & re-ask",editReaskTip:"Edit this question and re-ask from here (forks a new conversation; the original is kept)",reaskFromHere:"Re-ask from here",editPlaceholder:"Edit the question…",editHint:"⌘/Ctrl+Enter to submit · Esc to cancel",editAttachmentHint:"Original attachments kept — paste/drop images or files · ⌘/Ctrl+Enter to submit · Esc to cancel",expandMsg:"Expand",collapseMsg:"Collapse",toolCalls:"tool calls",bashRuns:"bash runs",images:"images",update:"Update",updateTip:"Check & update pi-web-ui",currentVersion:"Current version",latestVersion:"Latest version",checkingUpdate:"Checking…",checkUpdate:"Check for updates",upToDate:"You're up to date",updateAvailable:"New version v{version} available",updateJustPublished:"v{version} was just published — npm cache may lag; if the new version isn't detected yet, re-check in a moment",updateNow:"Update in terminal",updateTabTitle:"Update pi-web-ui",updateTerminalHint:"Clicking runs npm i -g pi-web-ui@latest in a visible terminal; restart the service afterwards to take effect (pi-web-ui server restart).",updatesAllTitle:"Component updates",updatesAllBadge:"{n} updates",updatesAllUpToDate:"All components up to date",kindWebUi:"Web UI",kindPiCore:"Core",kindPackage:"Package",updatesAllRefresh:"Re-check all",updateCheckFailed:"Check failed",updateBtn:"Update",updateAllBtn:"Update all",updatePkgTabTitle:"Update {name}",updateAllTabTitle:"Update all components",restartService:"Restart service",restartingService:"Restarting…",restartServiceTip:"Restart the pi-web-ui service ({name}): this instance is supervised (launchd/systemd/Windows watchdog), so it comes back automatically and the page reconnects — run it after an update",computer:"This PC",rootDir:"Root",workspaceRoots:"Workspace roots",workspaceRootsHint:"Roots the file tree can switch to; plugins may read and write them without a separate prompt.",addWorkspaceRoot:"Add as workspace root",addWorkspaceRootHint:"Add the current directory as a workspace root (switchable in the file tree; plugins may read/write it without a separate prompt)",removeWorkspaceRoot:"Remove workspace root",noFiles:"No files",filesTruncated:"Directory too large — list truncated (first 2000 shown)",linkFolderTip:"Link folder path to chat",attachInlineTip:"Attach content to chat",referenceTip:"Reference path only (AI reads on demand)",previewFile:"Preview",downloadFile:"Download file",copyName:"Copy name",copyPath:"Copy path",downloadFailed:"Download failed: {error}",fileNotFoundShort:"File not found",pluginMountFailed:"Plugin {name} failed to mount",liveOutputOmitted:`…[{n} chars omitted above]…
160
160
  `,uploadToFolder:"Upload files to this folder",uploadToCurrentDir:"Upload files to current directory",openAsProject:"Open as project",protocolMismatch:"Page version differs from the server (the app was just updated). Refresh the page to restore full functionality.",selectLinesHint:"Click a line to select; drag or Shift+click for a range",enableWrap:"Enable line wrap",disableWrap:"Disable line wrap",selectedRange:"Selected {n} lines (lines {start}-{end})",fileLines:"{n} lines",selectAll:"Select all",clearSelection:"Clear",addToChat:"Add to chat",addedToChat:"Added",previewTruncated:"⚠ File too large — previewing the first 512KB",previewLinesTruncated:"… too many lines — showing the first {n}",binaryFile:"🔣 Binary file — first 4KB shown as hex",binaryHexTruncated:" (file larger — download for the full file)",previewNotSupported:"This file type can't be previewed (only images / videos / text)",emptyFile:"(empty file)",editFile:"Edit file",exitEditFile:"Exit editing",saveFile:"Save file",discardFileChanges:"Discard unsaved changes?",fileSaved:"Saved",fileEditTruncated:"The preview is incomplete, so this file can't be edited",showMarkdownSource:"Show Markdown source",showMarkdownPreview:"Show Markdown preview",showHtmlSource:"Show HTML source",showHtmlPreview:"Show HTML preview",htmlJsOff:"🛡 Scripts disabled (static preview)",htmlJsOffTip:"Pure static render: JavaScript in the page will not run. Only enable scripts for files you trust.",htmlJsOn:"⚠ Scripts enabled",htmlJsOnTip:"JavaScript in the page is running. It still cannot reach this app (no same-origin, no forms, no top navigation), but it may make network requests or mine crypto — only for files you trust.",htmlEnableJs:"Enable scripts",htmlDisableJs:"Disable scripts",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",zoomIn:"Increase font size",zoomOut:"Decrease font size",resetZoom:"Reset zoom",pluginRequest:"Plugin request",modelQuestion:"Model question",modelQuestionCustom:"Custom answer (optional)",modelQuestionSubmit:"Submit answer",next:"Next",previous:"Previous",questionStep:"Q {cur} / {total}",optionPreview:"Option preview",questionTimeout:"⏳ {s}s left — auto-cancels on timeout",questionTimeoutExpired:"Question timed out, resuming conversation…",modelNoVision:"Current model {name} doesn't support images — switch to DeepSeek V4 Flash Vision (exp)",dshSkillsNote:"DSH uses runtime-built-in skills (dsh-skill); toggling is not supported in settings yet",dshExtensionsNote:"DSH has no pi extension system; capabilities are runtime-built-in (MCP/subagent/goal/plan/skill…)",dshReviewPromptNote:"DSH has no separate reviewer: this text is appended to the system prompt for goal rounds",dshVisionHiddenNote:"DSH supports real image input (DeepSeek V4 Flash Vision (exp) only) — no vision bridge needed",dshNoReviewModel:"DSH has no separate reviewer model — the model self-certifies goal completion; max rounds = auto-iteration count",noOptions:"(no options)",inputPlaceholder:"Enter content",soundHeader:"Sound notifications",enableSound:"Enable sound",preview:"Preview",volume:"Volume",notifyHeader:"Desktop notifications",notifyEnable:"Enable desktop notifications",notifyEnableDesc:"Ping you when a session finishes or needs your input. Requires permission; fires only while the page is out of sight (another app, a minimised window or a background tab). On Windows it also fires once you have been idle on the page for two minutes — the platform's presence signals are wrong there, and a redundant toast beats a silent one.",notifyDenied:"Notification permission was blocked — allow notifications for this site in browser settings (on Windows also allow the browser/app under Settings → System → Notifications and turn Focus assist off).",notifyUnsupported:"Notifications are not supported by this browser.",notifyInsecure:"This address is not a secure context (plain http on a non-localhost host), so the browser withholds the notification API — open the app via 127.0.0.1 or HTTPS.",notifyWindowsHint:"Windows adds an OS-level gate: allow the browser (or the installed pi-web-ui app) under Settings → System → Notifications and turn off Focus assist, otherwise toasts stay silent; closing the window also ends the process, so nothing can be delivered after that.",notifyTest:"Send test notification",notifyTestBody:"If you can see this OS notification, both the browser and Windows are letting notifications through.",notifyTestSent:"Sent (path: {path})",notifyTestFailed:"Delivery failed: {error}",notifyTestState:"Platform state: focus {focus} · visibility {visibility} · minimised {minimized} · idle {idle}s",notifyTestHeld:"The browser accepted it ({count} in your notification centre): if no banner popped up, Windows/Edge banner or quiet-notification settings are suppressing it.",notifyTestDropped:"The browser did not keep this notification → Edge dropped it (site notifications muted/blocked).",notifyTestGateSuppressed:"Current decision: would be swallowed (the platform thinks you are watching this page).",notifyTestGateOpen:"Current decision: would be delivered (the platform thinks you are away).",notifyDoneTitle:"Task finished",notifyDoneBody:"The session finished and is ready for your input.",notifyQuestionTitle:"Needs your input",notifyQuestionBody:"pi is waiting for your answer to a question.",notifyErrorTitle:"Something went wrong",notifyErrorBody:"A session reported an error.","sound.question":"Question popup","sound.question.desc":"When ask_user_question appears","sound.done":"Reply finished","sound.done.desc":"When the agent finishes a turn","sound.start":"Reply started","sound.start.desc":"When the agent starts a new turn","sound.error":"Error","sound.error.desc":"When an error notice appears",setupTitle:"pi agent config not detected",setupDesc:"pi-web-ui needs pi's config directory (~/.pi/agent) and at least one API key to run the agent. pi has built-in providers such as openai, anthropic, and deepseek — just pick one and enter a key, no terminal needed.",installFailed:"✖ pi agent installation failed:",retryInstall:"Retry install",skip:"Skip",installDone:"✅ pi agent CLI installed. Pick a provider and enter an API key to start chatting:",cliReadyHint:"✅ pi agent CLI already installed locally. Pick a provider and enter an API key to start chatting:",provider:"Provider",configured:"configured",providerKeyReady:"This provider already has a key — use it or replace it.",apiKey:"API key",saving:"Saving…",saveAndStart:"Save and start using",recheck:"Recheck",installing:"Installing pi agent CLI…",autoInstall:"Auto-install pi agent",attachment:"Attachment",plugin:"plugin",unknown:"unknown",thinkingWait:"Thinking",exitCode:"Exit code {code}",cancelled:"Cancelled",truncated:"… content too long, truncated in this view",outputTruncated:"… output too long, truncated in this view",refOnlyShort:"Reference only",folderRefShort:"Folder · reference only",inlineLines:"Inline · {n} lines",inlineLinesRange:"Lines {start}-{end}",image:"🖼 Image",bridgedVision:"👁 Transcribed",bridgedVisionDetail:"Image transcribed by the vision bridge (current model can't see images)",folderNotExpanded:"Folder — content not expanded, the agent will browse it as needed",fileNotExpanded:"Large file ({size}) — content not expanded, the agent will read it as needed","role.user":"You","role.assistant":"pi","role.tool":"Tool","role.bash":"Terminal","role.branch":"Branch summary","role.compaction":"Context compacted",directory:"Directory",waitingResponse:"Waiting for model response…",retryingApi:"Model API error, auto-retrying ({attempt}/{max}): {error}",retryingApiSoon:"Model API error, auto-retrying: {error}",modelRetryAttempts:"Auto-retry attempts on model errors",modelRetryHint:"How many times a failed model API call is retried automatically. When the budget runs out the turn stops with a red error and you can retry manually; 0 stops at the first failure. Applies immediately, no reload needed.",retryNow:"Retry",retryLastTip:"Manually retry the last failed model request",compactingContext:"Compacting context, generating summary…",compactingReasonManual:"Triggered manually",compactingReasonThreshold:"Auto-triggered by context threshold",compactingReasonOverflow:"Auto-triggered by context overflow",compactionFrom:"Compacted from {tokens} tokens",compactionKeptHint:"Earlier history is folded into this summary; only recent messages stay in context",backToBottom:"Back to bottom",questionNavTitle:"Questions",searchPlaceholder:"Search in conversation…",searchNoResults:"No results",searchModels:"Filter models…",noModelMatches:"No matching models",modelUsedCount:"used {n}×",searchGlobal:"Search",searchGlobalTip:"Global search: sessions / projects / files (Ctrl+K)",gsPlaceholder:"Search projects, past conversations, workspace files…",gsHint:"Type to search full conversation text (AI replies included), recent projects and file names in the current workspace at once",gsSessions:"Conversations",gsProjects:"Projects",gsFiles:"Files",gsNoResults:"No matches",gsSearching:"Searching…",gsTruncated:"Too many matches — showing a subset",gsCurrentProject:"current",gsOpenPreview:"Open file preview",gsNavigate:"select",gsOpen:"open",gsCloseHint:"close",bgTaskCommand:"Command",searchPrev:"Previous (Shift+Enter)",searchNext:"Next (Enter)",searchClose:"Close (Esc)",questionNavTip:"All questions in this conversation — hover to expand, click to jump","tpl.title":"Prompt templates","tpl.hint":"Click a card to fill the input; ✏️ to edit or delete; add your own too","tpl.clickCard":"Click to fill the input","tpl.editTpl":"Edit / delete template","tpl.openPicker":"Prompt templates (reusable prompts, anytime)","tpl.pickerTitle":"Prompt templates","tpl.pickerHint":"Click a card to fill the input; ✏️ to edit or delete; add your own too","tpl.add":"New template","tpl.addDesc":"Save a workflow you use often","tpl.reset":"Restore defaults","tpl.resetConfirm":"Restore defaults?","tpl.builtin":"Built-in","tpl.custom":"Custom","tpl.newTitle":"New prompt template","tpl.editTitle":"Edit prompt template","tpl.fieldIcon":"Icon","tpl.fieldTitle":"Title","tpl.fieldTitlePh":"Short title shown on the card","tpl.fieldDesc":"Description","tpl.fieldDescPh":"One-liner shown on the card","tpl.fieldPrompt":"Prompt","tpl.fieldPromptPh":"The full prompt sent to the agent","tpl.required":"Title and prompt are required","tpl.save":"Save","tpl.fill":"Fill input","tpl.fillTip":"Fill the input so you can tweak it before sending","tpl.sendNow":"Send now","tpl.sendTip":"Send immediately as a new conversation","tpl.delete":"Delete","tpl.deleteTip":"Delete this custom template","tpl.remove":"Remove from library","tpl.removeTip":"Remove this built-in template; restore later via “Restore defaults”","tpl.restore":"Restore default","tpl.restoreTip":"Discard your edits and restore the built-in default","tpl.sk.setup":"Repo setup","tpl.sk.setup.desc":"Give the repo a baseline that other workflows can use","tpl.sk.setup.prompt":`Scan this repository and build the baseline context other workflows rely on, then report concisely:
161
161
 
162
162
  1. Project type, tech stack and directory layout
@@ -313,49 +313,49 @@ Avoid three test anti-patterns: tests coupled to the implementation, tautologica
313
313
 
314
314
  {path}
315
315
 
316
- It only opens after you confirm.`,settingsExtensions:"Extensions",settingsUiPlugins:"UI plugins",noUiPlugins:"No UI plugins installed (<dataDir>/plugins/)",dshPatches:"DSH user patches",dshPatchesDesc:"Cordis patches loaded at runtime boot, in filename order (<dataDir>/dsh-patches/*.yml). New/edited files take effect after 'Rescan' restarts the runtime; broken files are skipped and logged to runtime stderr.",dshPatchesRescan:"Rescan",dshPatchesRescanHint:"Re-scan the patch directory and restart the DSH runtime so new patches take effect",dshPatchesEmpty:"No patch files yet",dshPatchesPath:"Patch directory: ",uiPluginNoSource:"Installed manually — no recorded source, online update unavailable",uiPluginPerms:"Permissions",pluginSettingsSave:"Save plugin settings",pluginSettingsSaving:"Saving…",pluginSettingsReset:"Reset defaults",settingsPresets:"Presets",settingsSubagentTemplates:"Subagent templates",settingsSubagentTemplatesDesc:"Presets for spawned subagents (role system prompt + skills/extensions whitelist + optional model and thinking level). AI may pick a template (subagent_spawn template param) or spawn without one; disabled templates stay in the panel but are invisible to AI tools.",noSubagentTemplates:"No subagent templates yet. AI can pick a template when spawning a subagent (role prompt + skills/extensions whitelist + optional model and thinking level), or spawn without a template param for default config.",subagentTemplateNew:"New template",subagentTemplateEdit:"Edit",subagentTemplateClosed:"Disabled",tplDefaultBadge:"Built-in",subagentDefaultModelLabel:"Default subagent model",subagentFollowMain:"Follow the main conversation's current model",subagentDefaultModelHint:"Fallback model for all subagents (a template's own model and the subagent_spawn model param take priority); does not change the main conversation's model.",subagentNoModels:"No usable models yet (configure a provider API key first) — subagents will follow the main conversation's model.",subagentTemplateOffHint:"Disabled templates stay in the panel and can be re-enabled, but AI tools can't see or pick them",subagentTemplateEnable:"Enable",subagentTemplateDisable:"Disable",tplNamePlaceholder:"Template name (referenced by AI via subagent_spawn's template param)…",tplDescriptionPlaceholder:"Description (AI uses it to judge when to pick this template)…",tplDescriptionEnPlaceholder:"English description (shown to AI under English UI; falls back to the description above)…",tplPromptModeLabel:"System prompt mode",tplModelLabel:"Model (empty = follow main conversation)",tplThinkingLabel:"Thinking level",tplThinkingFollowMain:"Follow the main conversation's current thinking level",tplThinkingHint:"Empty = follow the main conversation's current thinking level (same idea as the model fallback); unsupported levels are clamped to the nearest one the model supports.",tplSystemPromptLabel:"System prompt",tplSystemPromptPlaceholder:"Template role system prompt… (may be empty in append mode)",tplSystemPromptEnPlaceholder:"English system prompt… (used under English UI; falls back to the prompt above)",tplWhitelistHint:"Whitelist: checked = the subagent only gets these; none checked = follow the main session settings",tplSkillsLabel:"Skills whitelist",tplExtensionsLabel:"Extensions whitelist",tplSave:"Save template",tplCancel:"Cancel edit",tplDelete:"Delete template",tplInherit:"Follow main session",settingsEnabled:"Enabled",settingsDisabled:"Disabled",presetNamePlaceholder:"Preset name…",saveAsPreset:"Save as preset",applyPreset:"Apply",deletePreset:"Delete preset",noSkills:"No skills",noExtensions:"No extensions",noPresets:"No presets yet (tune the settings above, then save them as a preset)",loadingSession:"Loading session…",connectingServer:"Connecting to pi-web-ui server…",localePacks:"Language packs",localeGetMore:"Get more languages",localeInstalled:"Installed",localeInstall:"Download",localeRemove:"Remove",localeDownloading:"Downloading…",localeRemoving:"Removing…",localeInstallFailed:"Download failed: {error}",localeListFailed:"Couldn't load language packs: {error}",localeRemoveHint:"You can re-download it anytime",wallpaperTitle:"Chat wallpaper",wallpaperDesc:"Show a full-window background image (side panels, top and bottom bars included): a theme-provided image applies automatically, a URL here takes precedence; use dim and blur to keep text readable.",wallpaperUrlPh:"Image URL (https://…, empty = off)",wallpaperDim:"Dim",wallpaperBlur:"Blur",wallpaperClear:"Clear",wallpaperUpload:"Upload image",wallpaperUploadFailed:"Couldn't read the image (or it's too big) — try another one",skillFullTextLabel:"Inject full skill text",skillFullTextDesc:"Expand skill file contents inline into the system prompt (8KB per file, 32KB total cap); otherwise only a catalog is listed and the model reads files on demand",skillFullTextShort:"Full",delegateOpenSubagent:"Open subagent",delegateSecTask:"Task",delegateSecExpected:"Expected outcome",delegateSecTools:"Required tools",delegateSecMustDo:"Must do",delegateSecMustNotDo:"Must not do",delegateSecContext:"Context"},td=[{code:"zh",nativeName:"中文"},{code:"en",nativeName:"English"}],Ds={};function sd(e){return!e||typeof e.code!="string"||!e.code||e.code==="zh"||e.code==="en"||!e.strings||typeof e.strings!="object"?!1:(Ds[e.code]=e,!0)}function nd(e){delete Ds[e]}function ad(e){return e==="zh"?"中文":e.toUpperCase()}function id(e){return e==="zh"?"zh-CN":e==="pt"?"pt-BR":e}async function Oi(e){const t=await fetch(Ft(lt(e)));if(!t.ok)throw new Error(`HTTP ${t.status} for ${e}`);return await t.json()}const jo=c.createContext(null);function Ro(){try{return localStorage.getItem(Da)}catch{return null}}function rd(){return La(Ro(),typeof navigator<"u"?navigator.languages:[],null)}function od({children:e}){const[t,n]=c.useState(rd),[a,i]=c.useState(0),o=c.useRef(t);o.current=t;const l=c.useCallback(m=>{n(m);try{localStorage.setItem(Da,m)}catch{}try{window.dispatchEvent(new CustomEvent("pi-web-ui:locale",{detail:m}))}catch{}},[]),u=c.useCallback(async()=>{let m,f=null;try{const x=await Oi("/api/locales");m=x.packs??[],f=x.defaultLocale??null}catch{return null}return await Promise.all(m.filter(x=>x.installed).map(async x=>{try{const v=await Oi(`/api/locales/${x.code}`);sd({code:v.code||x.code,nativeName:v.nativeName||x.nativeName,strings:v.strings})}catch{}})),i(x=>x+1),f},[]);c.useEffect(()=>{u().then(m=>{if(!Ro()?.trim()){const x=La(null,typeof navigator<"u"?navigator.languages:[],m);x!==o.current&&(o.current=x,n(x))}const f=o.current;if(f!=="zh"&&f!=="en"&&!Ds[f]){const x=La(null,typeof navigator<"u"?navigator.languages:[],m,["zh","en"]);o.current=x,n(x);try{localStorage.setItem(Da,x)}catch{}}})},[u]);const p=c.useMemo(()=>[...td,...Object.values(Ds).map(m=>({code:m.code,nativeName:m.nativeName}))],[a]),h=c.useCallback((m,f)=>{let x=Ds[t]?.strings[m]??(t==="zh"?Zu[m]:ed[m]);if(f)for(const[v,N]of Object.entries(f))x=x.replaceAll(`{${v}}`,String(N));return x},[t,a]);c.useEffect(()=>{document.documentElement.lang=id(t)},[t]);const b=c.useMemo(()=>({locale:t,setLocale:l,t:h,packs:p,reloadPacks:u}),[t,l,h,p,u]);return s.jsx(jo.Provider,{value:b,children:e})}function Ut(){const e=c.useContext(jo);if(!e)throw new Error("useI18n must be used within LanguageProvider");return e}function Me(){return Ut().t}const ld=[{kind:"question",labelKey:"sound.question",descKey:"sound.question.desc"},{kind:"done",labelKey:"sound.done",descKey:"sound.done.desc"},{kind:"start",labelKey:"sound.start",descKey:"sound.start.desc"},{kind:"error",labelKey:"sound.error",descKey:"sound.error.desc"}];function Mi({settings:e,onChange:t,onPreview:n}){const a=Me(),i=o=>t({...e,...o});return s.jsxs("div",{className:"sound-menu",children:[s.jsx("div",{className:"dd-header",children:a("soundHeader")}),s.jsxs("label",{className:"sound-row sound-master",children:[s.jsxs("span",{className:"sound-label",children:[s.jsx(yo,{className:"sound-icon"}),s.jsx("span",{children:a("enableSound")})]}),s.jsx("input",{type:"checkbox",checked:e.enabled,onChange:o=>i({enabled:o.target.checked})})]}),ld.map(({kind:o,labelKey:l,descKey:u})=>s.jsxs("label",{className:`sound-row ${e.enabled?"":"disabled"}`,children:[s.jsxs("span",{className:"sound-label",children:[s.jsx("span",{className:"sound-name",children:a(l)}),s.jsx("span",{className:"sound-desc",children:a(u)})]}),s.jsxs("span",{className:"sound-right",children:[s.jsx("button",{type:"button",className:"sound-preview",title:a("preview"),disabled:!e.enabled,onClick:p=>{p.preventDefault(),n(o)},children:a("preview")}),s.jsx("input",{type:"checkbox",checked:e[o],disabled:!e.enabled,onChange:p=>i({[o]:p.target.checked})})]})]},o)),s.jsxs("div",{className:`sound-volume ${e.enabled?"":"disabled"}`,children:[s.jsx("span",{className:"sound-name",children:a("volume")}),s.jsx("input",{type:"range",min:0,max:100,step:5,value:e.volume,disabled:!e.enabled,onChange:o=>i({volume:Number(o.target.value)})}),s.jsxs("span",{className:"sound-vol-num",children:[e.volume,"%"]})]})]})}function Lo(e){const t=typeof window>"u"?void 0:window;if(!t)return!1;if(t.piDesktop?.isDesktop===!0)return!0;const n=t.navigator?.userAgent;return typeof n=="string"&&n.includes("Electron/")}const cd="https://github.com/xing-shuyin/pi-web-ui/releases/latest/download/page-picker-extension.zip",Do=()=>window.__piWebUiHost?.pageCall?.bind(window.__piWebUiHost);async function ud(){if(Lo())return{available:!1,pages:[],desktop:!0,error:"桌面版不支持浏览器操作:窗口里没有 Chrome 扩展运行时,请改用系统浏览器打开同一个地址(网页版)"};const e=Do();if(!e)return{available:!1,pages:[],error:"宿主页面桥不可用:这个 pi-web-ui 页面还没装上扩展桥(装/启用 page-picker 后刷新本页)"};try{const t=await e({op:"status",timeoutMs:5e3});if(!t.ok)return{available:!1,pages:[],error:t.error??"扩展没有返回状态"};const n=t.result??{};return{available:n.installed===!0,aiControl:n.aiControl===!0,allowEval:n.allowEval===!0,pages:Array.isArray(n.pages)?n.pages:[]}}catch(t){return{available:!1,pages:[],error:t instanceof Error?t.message:String(t)}}}function dd(e){return e.length===1?e[0]:null}function pd(e){return{path:e.origin,name:e.title?.trim()||e.origin,mode:"page",key:`page:${e.origin}`}}async function md(){const e=Do();if(!e)return!1;try{return(await e({op:"openOptions",timeoutMs:5e3})).ok===!0}catch{return!1}}function hd(e=45e3){const[t,n]=c.useState(null),a=c.useRef(!0),i=c.useCallback(async o=>{const l=await ud();a.current&&(n(l),o&&!l.available&&setTimeout(()=>{a.current&&i(!1)},1500))},[]);return c.useEffect(()=>{a.current=!0,i(!0);const o=setInterval(()=>void i(!1),Math.max(5e3,e));return()=>{a.current=!1,clearInterval(o)}},[i,e]),{status:t,refresh:()=>void i(!0)}}let In=null,jn=null;function Bi(e){In=e}function Fi(e){jn=e}function fd(){return!!(In||jn)}function Po(e){const t=typeof e?.text=="string"?e.text:"",n=Array.isArray(e?.attachments)?e.attachments:[],a=t.trim()!=="",i=n.length>0;return!a&&!i||a&&!In||i&&!jn?!1:(i&&jn?.(n),a&&In?.(t),!0)}function gd(){const e=Me(),{status:t,refresh:n}=hd(),[a,i]=c.useState(!1),[o,l]=c.useState(null),u=c.useRef(null),p=t?.pages??[],h=t?.available===!0&&(p.length===0||t.aiControl===!1),b=dd(p),m=v=>{l(v),u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>l(null),2600)},f=v=>{const N=Po({attachments:[pd(v)]});m(e(N?"browserControlCited":"browserControlCiteFailed"))},x=()=>{i(!0),n()};return s.jsxs("span",{className:"bc-anchor",children:[b?s.jsxs("span",{className:"browser-control-split",children:[s.jsxs("button",{type:"button",className:`chip browser-control single${h?" attention":""}`,title:e("browserControlSingleTip",{name:b.title||b.origin}),onClick:()=>f(b),children:[s.jsx(Aa,{size:14,"aria-hidden":!0}),s.jsx("span",{className:"bc-chip-label",children:b.title||b.origin})]}),s.jsx("button",{type:"button",className:"chip browser-control caret",title:e("browserControlOpenPanel"),"aria-label":e("browserControlOpenPanel"),onClick:x,children:"▾"})]}):s.jsxs("button",{type:"button",className:`chip browser-control${h?" attention":""}`,title:t?.error??e(h?"browserControlEmpty":"browserControlTip"),onClick:x,children:[s.jsx(Aa,{size:14,"aria-hidden":!0}),s.jsxs("span",{children:[e("browserControl"),p.length>0?` · ${p.length}`:""]})]}),o&&s.jsx("span",{className:"bc-flash",children:o}),a&&s.jsx(bd,{status:t,onRefresh:n,onCite:f,onClose:()=>i(!1)})]})}function bd({status:e,onRefresh:t,onCite:n,onClose:a}){const i=Me(),[o,l]=c.useState(!1),u=e?.pages??[],p=async()=>{l(!0);try{await md()||t()}finally{l(!1)}};return s.jsx("div",{className:"modal-backdrop",onClick:a,children:s.jsxs("div",{className:"modal browser-control-modal",onClick:h=>h.stopPropagation(),children:[s.jsx("button",{type:"button",className:"modal-close","aria-label":i("close"),onClick:a,children:"✕"}),s.jsxs("div",{className:"modal-head",children:[s.jsx(Aa,{size:16,"aria-hidden":!0}),s.jsx("h2",{children:i("browserControl")})]}),s.jsx("div",{className:"modal-desc",children:i("browserControlTip")}),e===null&&s.jsx("div",{className:"bc-note",children:i("browserControlChecking")}),e?.available===!1&&!e.desktop&&s.jsx("div",{className:"bc-note warn",children:i("browserControlOffline")}),e?.desktop===!0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"bc-note warn",children:i("browserControlDesktop")}),s.jsx("div",{className:"bc-note",children:i("browserControlDesktopLead")}),s.jsx("div",{className:"bc-actions",style:{marginTop:0},children:s.jsx("a",{className:"btn primary",href:window.location.href,target:"_blank",rel:"noreferrer noopener",children:i("browserControlOpenInBrowser")})})]}),e?.available===!1&&!e.desktop&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"bc-section",children:i("browserControlInstall")}),s.jsx("div",{className:"bc-note",children:i("browserControlInstallLead")}),s.jsx("div",{className:"bc-actions",style:{marginTop:0},children:s.jsx("a",{className:"btn primary",href:cd,target:"_blank",rel:"noreferrer noopener",children:i("browserControlInstallDownload")})}),s.jsxs("ol",{className:"bc-steps",children:[s.jsx("li",{children:i("browserControlInstallStep1")}),s.jsx("li",{children:i("browserControlInstallStep2")}),s.jsx("li",{children:i("browserControlInstallStep3")}),s.jsx("li",{children:i("browserControlInstallStep4")})]})]}),e?.available===!0&&e.aiControl===!1&&s.jsx("div",{className:"bc-note warn",children:i("browserControlDisabled")}),e?.available===!0&&u.length===0&&s.jsx("div",{className:"bc-note warn",children:i("browserControlEmpty")}),u.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"bc-section",children:i("browserControlPages")}),s.jsx("ul",{className:"bc-pages",children:u.map(h=>s.jsxs("li",{children:[s.jsx("span",{className:"bc-title",title:h.title,children:h.title}),s.jsx("span",{className:"bc-origin",title:h.origin,children:h.origin}),s.jsx("span",{className:`bc-open${h.open?" on":""}`,children:h.open?i("browserControlPageOpen"):i("browserControlPageClosed")}),s.jsx("button",{type:"button",className:"bc-cite",title:i("browserControlCiteTip",{name:h.title||h.origin}),onClick:()=>n(h),children:i("browserControlCite")})]},h.origin))}),s.jsx("div",{className:"bc-note",children:i("browserControlCiteNote")})]}),e?.desktop!==!0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"bc-section",children:i("browserControlExamples")}),s.jsxs("ul",{className:"bc-examples",children:[s.jsx("li",{children:i("browserControlExample1")}),s.jsx("li",{children:i("browserControlExample2")})]})]}),s.jsxs("div",{className:"bc-actions",children:[e?.desktop!==!0&&s.jsx("button",{type:"button",className:"primary",disabled:o,onClick:()=>void p(),children:i("browserControlOpenOptions")}),s.jsx("button",{type:"button",onClick:t,children:i("browserControlRefresh")})]})]})})}const Oo=["terminal_create","terminal_list","terminal_close","terminal_input","terminal_key","terminal_read","terminal_wait"],Mo=["subagent_spawn","subagent_get_result","subagent_steer","subagent_list","subagent_stop","subagent_wait_all","subagent_templates"],dn="edit_soft",pn="delegate_task",mn="ask_user_question",hn="todo_list",Ps="browser_page",Ed=[...Oo.map(e=>({name:e,group:"terminal",defaultOn:!1,dshVisible:!0})),...Mo.map(e=>({name:e,group:"subagent",defaultOn:!0,dshVisible:!1})),{name:dn,group:"other",defaultOn:!1,dshVisible:!1},{name:pn,group:"other",defaultOn:!0,dshVisible:!1},{name:mn,group:"other",defaultOn:!0,dshVisible:!0},{name:hn,group:"other",defaultOn:!0,dshVisible:!0},{name:Ps,group:"other",defaultOn:!1,dshVisible:!1}];new Set(Ed.map(e=>e.name));const Bo="pi-web-notify",ma={enabled:!1};function Fo(){try{const e=localStorage.getItem(Bo);if(!e)return{...ma};const t=JSON.parse(e);return{enabled:typeof t.enabled=="boolean"?t.enabled:ma.enabled}}catch{return{...ma}}}function Hi(e){try{localStorage.setItem(Bo,JSON.stringify(e))}catch{}}function Qs(){return typeof window<"u"&&"Notification"in window}function Td(){return Qs()?null:typeof window<"u"&&window.isSecureContext===!1?"insecure":"unsupported"}const xd=12e4;function yd(e){const{screenX:t,screenY:n,outerWidth:a,outerHeight:i}=e;return Number.isFinite(t)&&Ui(t)||Number.isFinite(n)&&Ui(n)?!0:a>0&&a<=400&&i>0&&i<=40}function Ui(e){return e<=-1e4}function kd(e){return!(e.visibility!=="visible"||e.minimized||!e.hasFocus||e.windows&&e.idleMs>xd)}let Ho=Date.now(),$i=!1;function qi(){Ho=Date.now()}function Nd(){return Math.max(0,Date.now()-Ho)}function vd(){if($i||typeof window>"u")return;$i=!0;const e={passive:!0,capture:!0};for(const t of["pointerdown","pointermove","keydown","wheel","touchstart","focus","scroll"])window.addEventListener(t,qi,e);typeof document<"u"&&document.addEventListener("visibilitychange",qi,e)}function Uo(){return typeof navigator>"u"?!1:/windows/i.test(navigator.userAgent??"")}function Cd(){return vd(),typeof window>"u"||typeof document>"u"?{hasFocus:!0,visibility:"visible",minimized:!1,idleMs:0,windows:!1}:{hasFocus:typeof document.hasFocus=="function"?document.hasFocus():!0,visibility:document.visibilityState??"",minimized:yd({screenX:window.screenX,screenY:window.screenY,outerWidth:window.outerWidth,outerHeight:window.outerHeight}),idleMs:Nd(),windows:Uo()}}function Wi(){return Qs()?Notification.permission:"denied"}async function wd(){if(!Qs())return"denied";try{return await Notification.requestPermission()}catch{return"denied"}}function Ki(e){return e instanceof Error?`${e.name}: ${e.message}`:String(e)}function Sd(e,t=!1){return{body:e,requireInteraction:t,icon:lt("/icons/icon-192.png"),badge:lt("/icons/icon-192.png"),data:{url:typeof location<"u"?location.href:lt("/")}}}async function _d(e,t,n=!1){if(!Qs())return{path:"none",error:"unsupported"};if(Notification.permission!=="granted")return{path:"none",error:`permission: ${Notification.permission}`};const a=Sd(t,n);let i;try{const o=await navigator.serviceWorker?.getRegistration();if(o?.active&&typeof o.showNotification=="function")return await o.showNotification(e,a),{path:"sw"};i=o?"service worker not active":"no service worker registration"}catch(o){i=Ki(o)}try{return new Notification(e,a),{path:"page",error:i}}catch(o){return{path:"none",error:`${i}; page: ${Ki(o)}`}}}async function rn(e,t){Qs()&&(kd(Cd())||Fo().enabled&&await _d(e,t))}const Ad=!1;function Yi(){const e=Me(),[t,n]=c.useState(Fo),[a,i]=c.useState(()=>Wi()),[o,l]=c.useState(null),u=Td(),p=u!==null,h=Uo();c.useEffect(()=>{const m=()=>i(Wi());return window.addEventListener("focus",m),document.addEventListener("visibilitychange",m),()=>{window.removeEventListener("focus",m),document.removeEventListener("visibilitychange",m)}},[]);const b=async m=>{const f={...t,enabled:m};if(n(f),Hi(f),m){const x=await wd();if(i(x),x!=="granted"){const v={...f,enabled:!1};n(v),Hi(v)}}};return s.jsxs("div",{className:"sound-menu notify-menu",children:[s.jsx("div",{className:"dd-header",children:e("notifyHeader")}),s.jsxs("label",{className:`sound-row sound-master${p?" disabled":""}`,children:[s.jsxs("span",{className:"sound-label",children:[s.jsx(qu,{className:"sound-icon"}),s.jsx("span",{children:e("notifyEnable")})]}),s.jsx("input",{type:"checkbox",checked:t.enabled&&!p,disabled:p,onChange:m=>b(m.target.checked)})]}),s.jsx("div",{className:"sound-hint",children:e("notifyEnableDesc")}),u==="insecure"&&s.jsx("div",{className:"sound-hint",children:e("notifyInsecure")}),u==="unsupported"&&s.jsx("div",{className:"sound-hint",children:e("notifyUnsupported")}),!p&&a==="denied"&&s.jsx("div",{className:"sound-hint",children:e("notifyDenied")}),!p&&h&&s.jsx("div",{className:"sound-hint",children:e("notifyWindowsHint")}),Ad]})}let Rn=null;const Pa=new Set;function $o(){for(const e of Pa)e()}function Xn(e){Rn={x:Number.isFinite(e.x)?e.x:0,y:Number.isFinite(e.y)?e.y:0,slot:e.slot,target:e.target??{id:""},entries:Array.isArray(e.entries)?e.entries:[],...typeof e.onHostAction=="function"?{onHostAction:e.onHostAction}:{}},$o()}function qt(){Rn!==null&&(Rn=null,$o())}function Id(e){return Pa.add(e),()=>{Pa.delete(e)}}function Gi(){return Rn}function jd(){return c.useSyncExternalStore(Id,Gi,Gi)}const Ot=8;function cs(e){return Number.isFinite(e)?e:0}function Rd(e,t,n,a,i,o){const l=Math.max(0,cs(n)),u=Math.max(0,cs(a)),p=Math.max(Ot,cs(i)-l-Ot),h=Math.max(Ot,cs(o)-u-Ot);return{x:Math.min(Math.max(Ot,cs(e)),p),y:Math.min(Math.max(Ot,cs(t)),h)}}function fn(e){return e?(e.when??[]).some(n=>n==="disabled"||typeof n=="string"&&n.startsWith("!")):!0}function Ln(e){if(!Array.isArray(e)||e.length===0)return[];const t=e.filter(m=>m&&m.hidden!==!0),n=t.filter(m=>m.kind!=="divider"),a=new Map,i=new Map;n.forEach((m,f)=>{const x=m.group??"";a.has(x)||a.set(x,f);const v=Number.isFinite(m.order)?m.order:100,N=i.get(x);(N===void 0||v<N)&&i.set(x,v)});const o=[...a.keys()].sort((m,f)=>{const x=i.get(m)??100,v=i.get(f)??100;return x!==v?x-v:(a.get(m)??0)-(a.get(f)??0)}),l=new Map(o.map((m,f)=>[m,f])),u=new Map;n.forEach((m,f)=>u.set(m,f));const p=[...n].sort((m,f)=>{const x=l.get(m.group??"")??0,v=l.get(f.group??"")??0;if(x!==v)return x-v;const N=Number.isFinite(m.order)?m.order:100,B=Number.isFinite(f.order)?f.order:100;return N!==B?N-B:(u.get(m)??0)-(u.get(f)??0)}),h=new Map;t.forEach((m,f)=>{if(m.kind!=="divider")return;const x=t.slice(f+1).find(N=>N.kind!=="divider");if(!x)return;const v=h.get(x)??[];v.push(m),h.set(x,v)});const b=[];for(const m of p){for(const f of h.get(m)??[])b.push(f);b.push(m)}return b}function zi(e){const t=[];let n=null,a=!1;return e.forEach((i,o)=>{if(!i||i.kind==="divider"){a=!0;return}const l=i.group??"";n!==null&&(a||l!==n)&&t.push({kind:"sep",key:`sep:${o}`}),t.push({kind:"item",key:`${i.id}#${o}`,index:o,entry:i}),n=l,a=!1}),t}function Ld(e){return!e||e.kind==="divider"||e.hidden===!0?!1:!fn(e)}function Vi(e,t,n){const a=Array.isArray(e)?e.length:0;if(a===0)return-1;const i=n>=0?1:-1;let o=Number.isFinite(t)?Math.trunc(t):-1;(o<0||o>=a)&&(o=i>0?-1:a);for(let l=0;l<a;l++)if(o=(o+i+a)%a,Ld(e[o]))return o;return-1}const Dd={menu:"☰",folder:"📁",plus:"+",chat:"💬",terminal:"▙",git:"⎇",search:"🔍",browser:"🌐",layers:"🗂",settings:"⚙",sound:"🔊",globe:"🌍",sun:"☀",download:"⤓",github:"⌗",x:"✕",upload:"⬆",copy:"⧉",edit:"✎",dot:"●",cpu:"▣",gauge:"▤",coins:"◉",database:"▥",message:"✉",activity:"〜"};function Pd(e){const t=(e??"").trim();if(!t)return"";const n=Dd[t.toLowerCase()];return n||(/[^\p{L}\p{N}\s]/u.test(t)&&t.length<=4?t:"")}const Od={engine:"pi",managed:!1,status:"connecting",ready:!1,cwd:"",workspaceRoots:[]};let fs=Od;const Oa=new Set;function Qi(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,a)=>n===t[a])}function Md(e,t){return e.engine===t.engine&&e.managed===t.managed&&e.appVersion===t.appVersion&&e.serverVersion===t.serverVersion&&e.status===t.status&&e.ready===t.ready&&e.cwd===t.cwd&&Qi(e.workspaceRoots,t.workspaceRoots)&&Qi(e.tabs,t.tabs)&&e.service?.name===t.service?.name&&e.service?.supervisor===t.service?.supervisor}function Xi(e){const t={...fs,...e};if(!Md(fs,t)){fs=t;for(const n of Oa)n()}}function qo(e){return Oa.add(e),()=>{Oa.delete(e)}}function Ji(){return fs}function ri(){return c.useSyncExternalStore(qo,Ji,Ji)}function wt(e){return c.useSyncExternalStore(qo,()=>fs[e],()=>fs[e])}function Wo(){return wt("engine")==="dsh"}function Ko(){return wt("managed")}function Bd(){return wt("service")}let Ma=null;function Fd(e){Ma=e}const ie=e=>Ma?Ma(e):!1;function Hd({onClose:e}){const t=Me(),{locale:n,setLocale:a,reloadPacks:i}=Ut(),[o,l]=c.useState(null),[u,p]=c.useState(""),[h,b]=c.useState("");async function m(){try{const v=await fetch(Ft(lt("/api/locales")));if(!v.ok)throw new Error(`HTTP ${v.status}`);const N=await v.json();l(N.packs??[]),p("")}catch(v){p(t("localeListFailed",{error:v instanceof Error?v.message:String(v)}))}}c.useEffect(()=>{m()},[]);async function f(v){b(v),p("");try{const N=await fetch(Ft(lt(`/api/locales/${v}/install`)),{method:"POST"});if(!N.ok){let B=`HTTP ${N.status}`;try{B=(await N.json()).error??B}catch{}throw new Error(B)}await i(),await m()}catch(N){p(t("localeInstallFailed",{error:N instanceof Error?N.message:String(N)}))}finally{b("")}}async function x(v){b(v),p("");try{const N=await fetch(Ft(lt(`/api/locales/${v}`)),{method:"DELETE"});if(!N.ok)throw new Error(`HTTP ${N.status}`);nd(v),n===v&&a("zh"),await i(),await m()}catch(N){p(t("localeInstallFailed",{error:N instanceof Error?N.message:String(N)}))}finally{b("")}}return s.jsx("div",{className:"modal-backdrop",onClick:e,children:s.jsxs("div",{className:"bg-task-modal",onClick:v=>v.stopPropagation(),children:[s.jsxs("div",{className:"bg-task-head",children:[s.jsxs("span",{className:"bg-task-title",children:[s.jsx(No,{})," ",t("localePacks")]}),s.jsx("button",{type:"button",className:"btn",title:t("close"),onClick:e,children:s.jsx(tt,{})})]}),u&&s.jsx("div",{className:"bg-task-empty",children:u}),o===null&&!u?s.jsx("div",{className:"bg-task-empty",children:t("loading")}):s.jsx("ul",{className:"bg-task-list",children:(o??[]).map(v=>{const N=h===v.code;return s.jsxs("li",{className:"bg-task-item",children:[s.jsxs("div",{className:"bg-task-info",children:[s.jsxs("div",{className:"bg-task-line1",children:[s.jsx("span",{className:"bg-task-port",children:v.nativeName}),v.installed&&v.version&&s.jsxs("span",{className:"bg-task-name",children:["v",v.version]})]}),s.jsxs("div",{className:"bg-task-line2",children:[s.jsx("span",{children:v.code}),v.installed?s.jsxs("span",{children:[t("localeInstalled")," · ",t("localeRemoveHint")]}):s.jsx("span",{children:t("localeGetMore")})]})]}),v.installed?s.jsxs("button",{type:"button",className:"btn bg-task-stop",disabled:N,title:t("localeRemove"),onClick:()=>void x(v.code),children:[s.jsx(ut,{}),s.jsx("span",{children:t(N?"localeRemoving":"localeRemove")})]}):s.jsxs("button",{type:"button",className:"btn",disabled:N,title:t("localeInstall"),onClick:()=>void f(v.code),children:[s.jsx(ss,{}),s.jsx("span",{children:t(N?"localeDownloading":"localeInstall")})]})]},v.code)})}),s.jsx("div",{className:"bg-task-foot",children:s.jsxs("button",{type:"button",className:"btn",title:t("bgTaskRefresh"),onClick:()=>void m(),children:[s.jsx(Rt,{}),s.jsx("span",{children:t("bgTaskRefresh")})]})})]})})}function Ud({chat:e,terminal:t,view:n,plugins:a,uiPrimary:i,uiOverflow:o,uiContextTopbar:l,onUiAction:u,onViewChange:p,onOpenPanel:h,onOpenSettings:b,onOpenBgTasks:m,onOpenGlobalSearch:f,sound:x,onSoundChange:v,onSoundPreview:N,themes:B,theme:X,onThemeChange:K}){const{locale:A,setLocale:R,t:I,packs:$}=Ut(),[ce,ge]=c.useState(!1),q=4,Y=new Set((i??[]).filter(L=>L.source==="host").map(L=>L.id)),J=(i??[]).filter(L=>L.source!=="host"),j=J.slice(0,q),F=[...J.slice(q),...o??[]],T=L=>Q(L)&&(i===void 0||Y.has(`host:${L}`)),U=L=>{if(L.source!=="host")return!1;switch(L.id){case"host:history":return h("left"),!0;case"host:files":return h("right"),!0;case"host:new-chat":return ie({type:"new_chat"}),!0;case"host:search":return f(),!0;case"host:tasks":return m(),!0;case"host:settings":return b(),!0;default:return!1}},G=(L,De,Ge)=>{L.preventDefault(),Xn({x:L.clientX,y:L.clientY,slot:"contextmenu.topbar",target:{id:De,label:Ge},entries:l??[]})},{appVersion:D}=ri(),se=Ko(),ee=Bd(),[Ne,w]=c.useState(!1);c.useEffect(()=>{Ne&&e.status==="open"&&w(!1)},[Ne,e.status]);const[de,ue]=c.useState(!1),[pe,ke]=c.useState(!1),[Be,ye]=c.useState(!1),[Ae,ve]=c.useState(!1),[Ye,Pe]=c.useState(!1),[ae,be]=c.useState(!1),Oe=e.ready?I("connected"):e.status==="closed"?I("reconnecting"):I("connecting"),Le=e.ready?"ok":"busy",We=()=>{if(!e.ready)return;const L=I("updateTabTitle"),De={name:L,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},Ge=e.terminals.find(C=>C.title===L);Ge?(t.restart(Ge.id),ie({type:"run_command",terminalId:Ge.id,conversationId:Ge.conversationId,command:De,cols:80,rows:24})):t.create({id:St(),conversationId:e.activeConversationId||e.state?.conversationId||"",title:L,cwd:e.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:De}),ve(!1),Pe(!1),p("terminal")},_=(L,De)=>{if(!e.ready||L.length===0)return;const Ge={name:De,command:Gu(L),cwd:"${pwd}"},C=e.terminals.find(S=>S.title===De);C?(t.restart(C.id),ie({type:"run_command",terminalId:C.id,conversationId:C.conversationId,command:Ge,cols:80,rows:24})):t.create({id:St(),conversationId:e.activeConversationId||e.state?.conversationId||"",title:De,cwd:e.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:Ge}),ve(!1),Pe(!1),p("terminal")},Q=L=>!e.tabs||L==="chat"||e.tabs.includes(L),V=e.updatesAll??[],Ee=V.filter(L=>!L.upToDate&&!L.error).length,oe=V.filter(L=>!L.upToDate&&!L.error&&L.kind!=="webui"),Z=()=>s.jsxs("div",{className:"dd-updates-all",children:[s.jsx("div",{className:"dd-header",children:I("updatesAllTitle")}),e.updatesAll===null?s.jsx("div",{className:"dd-note",children:I("checkingUpdate")}):V.length===0?s.jsx("div",{className:"dd-note",children:I("updatesAllUpToDate")}):s.jsx("ul",{className:"dd-all-list",children:V.map(L=>s.jsxs("li",{className:`dd-all-item${L.error?" err":L.upToDate?"":" warn"}`,children:[s.jsx("span",{className:"dd-all-name",title:L.name,children:L.name}),s.jsx("span",{className:"dd-all-kind",children:L.kind==="webui"?I("kindWebUi"):L.kind==="pi-core"?I("kindPiCore"):I("kindPackage")}),s.jsx("span",{className:"dd-all-vers",children:L.error?I("updateCheckFailed"):L.upToDate?`v${L.current}`:s.jsxs(s.Fragment,{children:["v",L.current," → v",L.latest]})}),L.kind!=="webui"&&!L.upToDate&&!L.error&&s.jsx("button",{type:"button",className:"dd-update-btn",onClick:()=>_([L],I("updatePkgTabTitle",{name:L.name})),children:I("updateBtn")})]},`${L.kind}:${L.name}`))}),s.jsxs("div",{className:"dd-actions",children:[oe.length>0&&s.jsx("button",{type:"button",className:"dd-refresh accent",style:{flex:1},onClick:()=>_(oe,I("updateAllTabTitle")),children:I("updateAllBtn")}),s.jsx("button",{type:"button",className:"dd-refresh",style:oe.length>0?{flex:1}:void 0,onClick:()=>ie({type:"check_updates_all",force:!0}),children:I("updatesAllRefresh")})]})]}),y=()=>s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"dd-update",children:[s.jsxs("div",{className:"dd-row",children:[s.jsx("span",{children:I("currentVersion")}),s.jsxs("b",{children:["v",e.update?.current??"…"]})]}),s.jsxs("div",{className:"dd-row",children:[s.jsx("span",{children:I("latestVersion")}),s.jsx("b",{children:e.update===null?I("checkingUpdate"):e.update.error?e.update.error:e.update.latest?`v${e.update.latest}`:I("checkingUpdate")})]}),e.update&&e.update.upToDate&&s.jsx("div",{className:"dd-note ok",children:I("upToDate")}),e.update&&!e.update.upToDate&&e.update.latest&&s.jsx("div",{className:"dd-note warn",children:I("updateAvailable",{version:e.update.latest})}),e.update?.latestPublishedAt&&Date.now()-new Date(e.update.latestPublishedAt).getTime()<30*6e4&&s.jsx("div",{className:"dd-note warn",children:I("updateJustPublished",{version:e.update.latest??""})}),e.update&&!e.update.upToDate&&e.update.latest&&s.jsx("div",{className:"dd-note",children:I("updateTerminalHint")})]}),s.jsxs("div",{className:"dd-actions",children:[s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>ie({type:"check_update"}),children:e.update===null?I("checkingUpdate"):I("checkUpdate")}),e.update&&!e.update.upToDate&&e.update.latest&&s.jsx("button",{type:"button",className:"dd-refresh accent",onClick:We,children:I("updateNow")}),ee&&s.jsx("button",{type:"button",className:"dd-refresh accent",disabled:Ne,title:I("restartServiceTip",{name:ee.name}),onClick:()=>{Ne||(w(!0),ie({type:"restart_service"}))},children:I(Ne?"restartingService":"restartService")})]})]}),P={"host:search":s.jsxs("button",{type:"button",className:"chip",title:I("searchGlobalTip"),onClick:f,children:[s.jsx(wn,{}),s.jsx("span",{className:"chip-sub",children:I("searchGlobal")})]}),"host:browser":e.settings?.disabledAgentTools?.includes(Ps)??!1?null:s.jsx(gd,{}),"host:tasks":s.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":I("bgTasksTip"),onClick:m,children:[s.jsx(Sn,{}),s.jsx("span",{className:"chip-sub",children:I("bgTasks")}),e.bgServers.length>0&&s.jsx("span",{className:"bg-task-badge",children:e.bgServers.length})]}),"host:settings":s.jsxs("button",{type:"button",className:"chip",title:I("settingsTitle"),onClick:b,children:[s.jsx(Cn,{}),s.jsx("span",{className:"chip-sub",children:I("settings")})]}),"host:sound":s.jsxs(Yt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(yo,{}),s.jsx("span",{className:"chip-sub",children:I("sound")})]}),open:de,onOpenChange:ue,children:[s.jsx(Mi,{settings:x,onChange:v,onPreview:N}),s.jsx(Yi,{})]}),"host:language":s.jsxs(Yt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(No,{}),s.jsx("span",{className:"chip-sub",children:ad(A)})]}),open:pe,onOpenChange:ke,children:[s.jsx("div",{className:"dd-header",children:I("language")}),$.map(L=>s.jsx(ft,{active:A===L.code,onClick:()=>{R(L.code),ke(!1)},children:L.nativeName},L.code)),s.jsxs(ft,{onClick:()=>{ke(!1),be(!0)},children:[s.jsx(ss,{})," ",I("localeGetMore")]})]}),"host:theme":s.jsxs(Yt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(Cu,{}),s.jsx("span",{className:"chip-sub",children:I("theme")})]}),open:Be,onOpenChange:ye,children:[s.jsx("div",{className:"dd-header",children:I("theme")}),s.jsx(ft,{active:X===null,onClick:()=>{K(null),ye(!1)},children:I("themeDefault")}),B.map(L=>s.jsx(ft,{active:X===L.id,onClick:()=>{K(L.id),ye(!1)},children:A==="zh"?L.name:L.nameEn??L.name},L.id))]}),"host:update":se?s.jsxs("span",{className:"chip",title:I("updatesManaged"),children:[s.jsx(ss,{}),s.jsxs("span",{className:"chip-sub",children:["v",D??e.update?.current??"…"]})]}):s.jsxs(Yt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(ss,{}),s.jsxs("span",{className:"chip-sub",children:["v",e.update?.current??"…"]}),e.update&&!e.update.upToDate&&s.jsx("span",{className:"update-dot",title:I("updateAvailable",{version:e.update.latest??""})}),Ee>0&&s.jsx("span",{className:"update-badge",children:I("updatesAllBadge",{n:Ee})})]}),open:Ae,onOpenChange:L=>{ve(L),L&&(ie({type:"check_update"}),ie({type:"check_updates_all"}))},fit:!0,children:[s.jsx("div",{className:"dd-header",children:I("update")}),y(),Z()]}),"host:github":s.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:I("githubRepo"),children:s.jsx(Li,{})})},le=["host:search","host:browser","host:tasks","host:settings","host:sound","host:language","host:theme","host:update","host:github"],Te=new Set(["host:search","host:tasks","host:settings"]),Ie=new Set(["host:sound","host:language","host:theme","host:update","host:github","host:browser"]),Fe=new Set(le),Re=i===void 0?le.filter(L=>Q(L.slice(5))):i.filter(L=>L.source==="host"&&Fe.has(L.id)).filter(L=>Te.has(L.id)?Q(L.id.slice(5)):!0).map(L=>L.id);return s.jsxs("header",{className:"topbar",children:[s.jsxs("div",{className:"brand",children:[n==="chat"&&T("history")&&s.jsx("button",{type:"button",className:"panel-toggle",title:I("openHistory"),onClick:()=>h("left"),children:s.jsx(ju,{})}),s.jsx("span",{className:"brand-logo",children:"π"}),s.jsx("span",{className:"brand-name",children:"pi-web-ui"}),s.jsx("span",{className:`conn-dot ${Le}`,title:Oe}),s.jsx("span",{className:"conn-label",children:Oe})]}),s.jsxs("div",{className:"topbar-actions",children:[s.jsxs("div",{className:"view-switch",role:"tablist","aria-label":I("viewSwitch"),children:[s.jsxs("button",{type:"button",role:"tab","aria-selected":n==="chat",className:n==="chat"?"active":"",onClick:()=>p("chat"),children:[s.jsx(ts,{}),s.jsx("span",{children:I("chat")})]}),T("terminal")&&s.jsxs("button",{type:"button",role:"tab","aria-selected":n==="terminal",className:n==="terminal"?"active":"",onClick:()=>p("terminal"),children:[s.jsx(Vn,{}),s.jsx("span",{children:I("terminal")})]}),T("git")&&s.jsxs("button",{type:"button",role:"tab","aria-selected":n==="git",className:n==="git"?"active":"",onClick:()=>p("git"),children:[s.jsx(un,{}),s.jsx("span",{children:I("scmTab")})]}),(Q("plugins")?a:[]).filter(L=>L.view!==!1).map(L=>{const De=L.error?`${L.name}: ${L.error}`:L.description?`${L.name} — ${L.description}`:L.name;return s.jsxs("button",{type:"button",role:"tab","aria-selected":n===`plugin:${L.id}`,className:`plugin-tab${n===`plugin:${L.id}`?" active":""}${L.error?" broken":""}`,title:De,onClick:()=>p(`plugin:${L.id}`),children:[L.icon?s.jsx("span",{"aria-hidden":!0,children:L.icon}):null,s.jsx("span",{children:L.name})]},L.id)}),j.map(L=>s.jsxs("button",{type:"button",className:"plugin-topbar-item",title:L.hint??L.label,onClick:()=>u?.(L),onContextMenu:De=>G(De,L.id,L.label),children:[L.icon?s.jsx("span",{"aria-hidden":!0,children:L.icon}):null,s.jsx("span",{children:L.label})]},L.id)),F.length>0&&s.jsxs("div",{className:"plugin-topbar-more",children:[s.jsx("button",{type:"button",className:"plugin-topbar-item","aria-haspopup":"menu","aria-expanded":ce,title:I("pluginTopbarMore"),onClick:()=>ge(L=>!L),children:"⋯"}),ce&&s.jsx("div",{className:"plugin-topbar-menu",role:"menu",children:F.map(L=>{const De=L.source==="host"&&Ie.has(L.id)?P[L.id]:void 0;return De!==void 0?s.jsx(c.Fragment,{children:De},L.id):s.jsxs("button",{type:"button",role:"menuitem",title:L.hint??L.label,onClick:()=>{ge(!1),U(L)||u?.(L)},children:[L.icon&&!/[a-z]/i.test(L.icon)?`${L.icon} `:"",L.label]},L.id)})})]})," "]}),s.jsx("div",{className:"topbar-desktop",children:Re.map(L=>s.jsx(c.Fragment,{children:P[L]??null},L))}),T("new-chat")&&s.jsxs("button",{type:"button",className:"chip newchat","data-tip":I("newChatTip"),onClick:()=>ie({type:"new_chat"}),children:[s.jsx(kt,{}),s.jsx("span",{children:I("newChat")})]}),s.jsx("div",{className:"topbar-more",children:s.jsxs(Yt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(_u,{}),s.jsx("span",{className:"chip-sub",children:I("more")}),!se&&e.update&&!e.update.upToDate&&s.jsx("span",{className:"update-dot"})]}),open:Ye,onOpenChange:L=>{Pe(L),L&&!se&&(ie({type:"check_update"}),ie({type:"check_updates_all"}))},children:[s.jsx("div",{className:"dd-header",children:I("sound")}),s.jsx("div",{className:"dd-header",children:I("settings")}),s.jsxs(ft,{onClick:()=>{Pe(!1),b()},children:[s.jsx(Cn,{})," ",I("settingsTitle")]}),s.jsxs(ft,{onClick:()=>{Pe(!1),f()},children:[s.jsx(wn,{})," ",I("searchGlobal")]}),s.jsxs(ft,{onClick:()=>{Pe(!1),m()},children:[s.jsx(Sn,{})," ",I("bgTasks"),e.bgServers.length>0&&s.jsx("em",{className:"bg-task-badge",children:e.bgServers.length})]}),s.jsx(Mi,{settings:x,onChange:v,onPreview:N}),s.jsx(Yi,{}),s.jsx("div",{className:"dd-header",children:I("language")}),$.map(L=>s.jsx(ft,{active:A===L.code,onClick:()=>R(L.code),children:L.nativeName},L.code)),s.jsx("div",{className:"dd-header",children:I("theme")}),s.jsx(ft,{active:X===null,onClick:()=>{K(null),Pe(!1)},children:I("themeDefault")}),B.map(L=>s.jsx(ft,{active:X===L.id,onClick:()=>{K(L.id),Pe(!1)},children:A==="zh"?L.name:L.nameEn??L.name},L.id)),s.jsx("div",{className:"dd-header",children:I("update")}),y(),Z(),s.jsxs("a",{className:"dd-refresh dd-more-link",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",children:[s.jsx(Li,{})," ",I("githubRepo")]})]})})]}),n==="chat"&&T("files")&&s.jsx("button",{type:"button",className:"panel-toggle",title:I("openFiles"),onClick:()=>h("right"),children:s.jsx(Bt,{})}),ae&&s.jsx(Hd,{onClose:()=>be(!1)})]})}function Yo(e,t){const n={...t};if(!e)return n;try{const a=JSON.parse(e);if(a&&typeof a=="object"&&!Array.isArray(a))for(const i of Object.keys(t)){const o=a[i];typeof o=="number"&&Number.isFinite(o)&&o>0&&(n[i]=o)}}catch{}return n}function Go(e){const t=e.start.above+e.start.below,n=Math.max(1,e.availablePx),a=e.totalWeight>0?e.totalWeight:1,i=n/a,o=e.minAbovePx/i,l=e.minBelowPx/i;if(o+l>=t){const p=e.minAbovePx+e.minBelowPx||1,h=t*e.minAbovePx/p;return{above:h,below:t-h}}const u=Math.min(t-l,Math.max(o,e.start.above+e.deltaPx/i));return{above:u,below:t-u}}function $d(e,t,n){const a=new Map(e.map(h=>[h.id,h])),i=h=>h.parentId?a.get(h.parentId)?.cwd??h.cwd:h.cwd,o=e.find(h=>h.id===n),l=o?i(o):t,u=new Map;for(const h of e){const b=i(h),m=u.get(b)??[];m.push(h),u.set(b,m)}const p=[...u.entries()].map(([h,b])=>({cwd:h,isCurrent:h===l,convs:b}));return p.sort((h,b)=>h.isCurrent?-1:b.isCurrent?1:h.cwd<b.cwd?-1:h.cwd>b.cwd?1:0),p}function Zi(e){const t=new Date(e),n=new Date;return t.toDateString()===n.toDateString()?`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`:`${t.getMonth()+1}/${t.getDate()}`}function qd(e){const t=e instanceof HTMLElement?e:null;if(!t)return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"?!0:t.isContentEditable}const Wd="pi-web-ui:lp-collapse-projects",Kd="pi-web-ui:lp-collapse-convs",Yd="pi-web-ui:lp-collapse-sessions";function ha(e,t=!1){const[n,a]=c.useState(()=>{try{const o=localStorage.getItem(e);if(o==="1")return!0;if(o==="0")return!1}catch{}return t}),i=c.useCallback(()=>{a(o=>{const l=!o;try{localStorage.setItem(e,l?"1":"0")}catch{}return l})},[e]);return[n,i]}const zo="pi-web-ui:lp-sizes",Dn={projects:1,convs:1,sessions:1},Gd=32,er=72;function zd(){try{return Yo(localStorage.getItem(zo),Dn)}catch{return{...Dn}}}const Vd=c.memo(function({sessionFile:t,conversations:n,elsewhere:a,sessions:i,projects:o,activeConversationId:l,panelSend:u,active:p,collapsible:h,onToggleCollapse:b,uiContextSession:m}){const f=Me(),x=t,v=wt("ready"),N=wt("status"),B=wt("cwd"),X=B,[K,A]=c.useState(null),[R,I]=c.useState(null),[$,ce]=c.useState(""),[ge,q]=ha(Wd,!1),[Y,J]=ha(Kd,!1),[j,F]=ha(Yd,!1),T=c.useCallback((_,Q)=>{if(!Q)return _.filter(oe=>oe.isSubagent&&!oe.isStreaming&&oe.id!==l).length;const V=new Map(_.map(oe=>[oe.id,oe])),Ee=oe=>{if(oe.id===Q)return(V.get(Q)?.isSubagent??!1)&&!oe.isStreaming&&oe.id!==l;let Z=oe;const y=new Set;for(;Z?.parentId;){if(Z.parentId===Q)return!0;if(y.has(Z.parentId)||(y.add(Z.parentId),Z=V.get(Z.parentId),!Z))return!1}return!1};return _.filter(oe=>oe.isSubagent&&!oe.isStreaming&&oe.id!==l&&Ee(oe)).length},[l]),U=c.useCallback((_,Q)=>{if(!Q)return _.filter(oe=>oe.isSubagent).length;const V=new Map(_.map(oe=>[oe.id,oe])),Ee=oe=>{if(oe.id===Q)return V.get(Q)?.isSubagent??!1;let Z=oe;const y=new Set;for(;Z?.parentId;){if(Z.parentId===Q)return!0;if(y.has(Z.parentId)||(y.add(Z.parentId),Z=V.get(Z.parentId),!Z))return!1}return!1};return _.filter(oe=>oe.isSubagent&&Ee(oe)).length},[]),G=c.useCallback((_,Q)=>{if(!Q)return 0;const V=new Map(_.map(oe=>[oe.id,oe])),Ee=oe=>{let Z=oe;const y=new Set;for(;Z?.parentId;){if(Z.parentId===Q)return!0;if(y.has(Z.parentId)||(y.add(Z.parentId),Z=V.get(Z.parentId),!Z))return!1}return!1};return _.filter(oe=>oe.isSubagent&&oe.isStreaming&&Ee(oe)).length},[]),D=c.useRef(null),se=c.useRef(null),ee=c.useRef(()=>{}),Ne=Ln(m??[]).length>0,w=c.useCallback((_,Q,V)=>{D.current={x:_,y:Q,target:V};const Ee=V.kind==="running"?V.id:void 0,oe=T(n,Ee),Z=oe===0?f("noFinishedSubagents"):Ee?f("dismissFinishedSubagentsScoped",{n:oe}):f("dismissFinishedSubagents",{n:oe}),y=!!Ee&&se.current===Ee,P=(m??[]).map(le=>le.source!=="host"?le:le.id==="host:conv-dismiss-subagents"?{...le,label:Z,...oe===0?{when:[...le.when??[],"disabled"]}:{}}:le.id==="host:conv-force-dismiss"?Ee?{...le,...y?{label:f("forceDismissConfirm")}:{}}:{...le,hidden:!0}:le);Xn({x:_,y:Q,slot:"contextmenu.session",target:V,entries:P,onHostAction:(le,Te)=>ee.current(le,Te)})},[m,n,T,f]),de=c.useCallback((_,Q)=>{const V=Q.kind==="running"?Q.id:void 0;if(_.id==="host:conv-dismiss-subagents"){u(V?{type:"dismiss_finished_subagents",parentId:V}:{type:"dismiss_finished_subagents"});return}if(_.id!=="host:conv-force-dismiss")return;const Ee=D.current;if(!(!V||!Ee)){if(se.current!==V)return se.current=V,w(Ee.x,Ee.y,Ee.target),!0;se.current=null,u({type:"dismiss_conversation",id:V,force:!0})}},[u,w]);ee.current=de;const ue=c.useCallback((_,Q)=>{qd(_.target)||Ne&&(_.preventDefault(),_.stopPropagation(),se.current=null,w(_.clientX,_.clientY,Q))},[Ne,w]),pe=c.useRef(null),[ke,Be]=c.useState(()=>zd());c.useEffect(()=>{try{localStorage.setItem(zo,JSON.stringify(ke))}catch{}},[ke]);const ye=[...n,...a.map((_,Q)=>({id:`elsewhere:${_.cwd}:${_.title}:${Q}`,title:_.title,cwd:_.cwd,messageCount:0,isStreaming:_.isStreaming,isSubagent:!1,elsewhere:!0}))],Ae=c.useCallback((_,Q)=>V=>{V.preventDefault();const Ee=V.currentTarget,oe=V.clientY,Z={...ke},y=pe.current;if(!y)return;const P=[{key:"projects",visible:o.length>0,collapsed:ge},{key:"convs",visible:ye.length>0,collapsed:Y},{key:"sessions",visible:!0,collapsed:j}].filter(De=>De.visible),le=P.filter(De=>De.collapsed).length,Ie=P.filter(De=>!De.collapsed).map(De=>De.key).reduce((De,Ge)=>De+(Z[Ge]??1),0)||1,Fe=Math.max(120,y.clientHeight-le*Gd);Ee.classList.add("dragging"),document.body.classList.add("lp-resizing");const Re=De=>{const{above:Ge,below:C}=Go({start:{above:Z[_]??1,below:Z[Q]??1},deltaPx:De.clientY-oe,availablePx:Fe,totalWeight:Ie,minAbovePx:er,minBelowPx:er});Be(S=>({...S,[_]:Ge,[Q]:C}))},L=()=>{window.removeEventListener("pointermove",Re),window.removeEventListener("pointerup",L),Ee.classList.remove("dragging"),document.body.classList.remove("lp-resizing")};window.addEventListener("pointermove",Re),window.addEventListener("pointerup",L)},[ke,o.length,ye.length,ge,Y,j]);c.useEffect(()=>{!p||!v||N!=="open"||B&&(u({type:"list_sessions"}),u({type:"list_projects"}))},[p,v,N,B,u]);const ve=_=>{const Q=_.name||_.firstMessage.trim();return Q.length>0?Q:f("emptyChat")},Ye=_=>_.split(/[\\/]/).pop()||_,Pe=(_,Q,V,Ee,oe)=>{const Z=K===_;return s.jsx("button",{type:"button",className:`lp-del ${Z?"confirm":""}`,title:Z?V:Q,onClick:y=>{y.stopPropagation(),Z?(A(null),Ee()):A(_)},children:Z?s.jsx(Lt,{}):oe??s.jsx(ut,{})})},ae=(_,Q,V,Ee)=>s.jsxs("button",{type:"button",className:"lp-section-title panel-section-title",onClick:V,title:f(Q?"expandSection":"collapseSection"),children:[s.jsxs("span",{className:"lp-section-title-text",children:[_,Ee!==void 0?` (${Ee})`:""]}),s.jsx("span",{className:"lp-section-chevron",children:Q?s.jsx(Vt,{}):s.jsx(Qn,{})})]}),Oe=[{key:"projects",visible:o.length>0,collapsed:ge},{key:"convs",visible:ye.length>0,collapsed:Y},{key:"sessions",visible:!0,collapsed:j}].filter(_=>_.visible).filter(_=>!_.collapsed),Le=Oe.reduce((_,Q)=>_+(ke[Q.key]??1),0)||1,We=_=>Oe.length<=1?1:(ke[_]??1)/Le*Oe.length;return s.jsxs("aside",{ref:pe,className:"panel panel-left lp-panel",children:[h&&b&&s.jsx("button",{type:"button",className:"panel-collapse-btn",title:f("collapsePanel"),onClick:b,children:s.jsx(wo,{})}),o.length>0&&s.jsxs("div",{className:`lp-section panel-projects ${ge?"collapsed":""}`,style:ge?void 0:{flex:`${We("projects")} 1 0px`},children:[ae(f("recentProjects"),ge,q,o.length),!ge&&s.jsx("div",{className:"lp-section-body projects-scroll",children:o.map(_=>{const Q=X===_.path;return s.jsxs("div",{className:"lp-row",onMouseLeave:()=>A(V=>V===`proj:${_.path}`?null:V),children:[s.jsxs("button",{type:"button",className:`project-item ${Q?"active":""}`,title:_.path,onClick:()=>{Q||u({type:"set_cwd",path:_.path})},children:[s.jsx(Bt,{className:"project-icon"}),s.jsxs("span",{className:"project-info",children:[s.jsx("span",{className:"project-name",children:Ye(_.path)}),s.jsx("span",{className:"project-path",children:_.path})]}),s.jsx("span",{className:"project-time",children:Zi(_.lastUsed)})]}),Pe(`proj:${_.path}`,f("deleteProject"),f("deleteProjectConfirm"),()=>u({type:"remove_project",path:_.path}))]},_.path)})})]}),o.length>0&&!ge&&(ye.length>0?!Y:!j)&&s.jsx("div",{className:"lp-sash",onPointerDown:Ae("projects",ye.length>0?"convs":"sessions"),onDoubleClick:()=>Be({...Dn}),title:f("dragToResize")}),ye.length>0&&s.jsxs("div",{className:`lp-section lp-section-convs panel-convs ${Y?"collapsed":""}`,style:Y?void 0:{flex:`${We("convs")} 1 0px`},onContextMenu:_=>ue(_,{id:"",kind:"section",label:f("runningConversations")}),children:[ae(f("runningConversations"),Y,J,ye.length),!Y&&s.jsx("div",{className:"lp-section-body convs-scroll",children:$d(ye,B,l).map(_=>s.jsxs("div",{className:"panel-conv-group",children:[!_.isCurrent&&s.jsx("div",{className:"panel-conv-group-title",title:_.cwd,children:Ye(_.cwd)}),(()=>{const Q=new Map(_.convs.map(P=>[P.id,P])),V=new Map,Ee=[];for(const P of _.convs)if(P.parentId&&Q.has(P.parentId)){const le=V.get(P.parentId)??[];le.push(P),V.set(P.parentId,le)}else Ee.push(P);const oe=[],Z=new Set,y=(P,le)=>{if(!Z.has(P.id)){Z.add(P.id),oe.push({c:P,depth:le});for(const Te of V.get(P.id)??[])y(Te,le+1)}};for(const P of Ee)y(P,0);for(const P of _.convs)y(P,0);return oe.map(({c:P,depth:le})=>{if(P.elsewhere)return s.jsx("div",{className:"lp-row",children:s.jsxs("div",{className:"session-item elsewhere-item",title:`${f("elsewhereTip")}
317
- ${P.cwd}`,children:[s.jsx(ts,{className:"session-icon"}),s.jsxs("span",{className:"session-info",children:[s.jsxs("span",{className:"session-title",children:[s.jsx("span",{className:"elsewhere-badge",children:f("elsewhereBadge")}),P.title]}),s.jsx("span",{className:"session-sub",children:Ye(P.cwd)})]}),P.isStreaming&&s.jsx("span",{className:"conv-streaming",title:f("streaming")})]})},P.id);const Te=l===P.id;return s.jsxs("div",{className:`lp-row${le>0?" lp-sub":""}`,style:le>0?{marginLeft:le*18}:void 0,onMouseLeave:()=>A(Ie=>Ie===`conv:${P.id}`?null:Ie),onContextMenu:Ie=>ue(Ie,{id:P.id,kind:"running",label:P.title}),children:[s.jsxs("button",{type:"button",className:`session-item ${Te?"active":""}`,title:`${P.title}${_.isCurrent?"":` — ${_.cwd}`}`,onClick:()=>{Te||u({type:"switch_conversation",id:P.id})},children:[s.jsx(ts,{className:"session-icon"}),s.jsxs("span",{className:"session-info",children:[R===`conv:${P.id}`?s.jsx("input",{autoFocus:!0,className:"session-rename-input",value:$,placeholder:f("renameSessionPlaceholder"),onClick:Ie=>Ie.stopPropagation(),onChange:Ie=>ce(Ie.target.value),onKeyDown:Ie=>{if(Ie.stopPropagation(),Ie.key==="Enter"&&!Ie.nativeEvent.isComposing){const Fe=$.trim();Fe&&u({type:"rename_conversation",id:P.id,name:Fe}),I(null)}else Ie.key==="Escape"&&I(null)},onBlur:()=>I(null)}):s.jsxs("span",{className:"session-title",children:[P.isSubagent&&s.jsx("span",{className:"subagent-badge",children:f("subagentBadge")}),P.title,P.error&&s.jsx("span",{className:"conv-error-badge",title:f("convErrorBadge",{error:P.error})})]}),R===`conv:${P.id}`?null:s.jsx("span",{className:"session-sub",children:Te?f("current"):f("messageCount",{n:P.messageCount})})]}),P.isStreaming&&s.jsx("span",{className:"conv-streaming",title:f("streaming")})]}),s.jsx("button",{type:"button",className:"lp-del lp-rename",title:f("renameSession"),onClick:Ie=>{Ie.stopPropagation(),A(null),ce(P.title),I(`conv:${P.id}`)},children:s.jsx(An,{})}),(()=>{const Ie=`conv:${P.id}`,Fe=K===Ie,Re=T(n,P.id),L=G(n,P.id),De=U(n,P.id);return De===0&&!P.isStreaming?Pe(Ie,f("dismissConversation"),f("dismissConversationConfirm"),()=>u({type:"dismiss_conversation",id:P.id}),s.jsx(tt,{})):De===0?Pe(Ie,f("dismissConversation"),f("dismissStreamingConfirm"),()=>u({type:"dismiss_conversation",id:P.id,force:!0}),s.jsx(tt,{})):Fe?s.jsxs("span",{className:"lp-del-group",children:[Re>0&&s.jsx("button",{type:"button",className:"lp-del-opt",title:f("dismissFinishedSubagentsScoped",{n:Re}),onClick:Ge=>{Ge.stopPropagation(),A(null),u({type:"dismiss_finished_subagents",parentId:P.id})},children:f("dismissFinishedOnly",{n:Re})}),s.jsx("button",{type:"button",className:"lp-del-opt danger",title:f("forceDismissTitle",{n:De,m:L}),onClick:Ge=>{Ge.stopPropagation(),A(null),u({type:"dismiss_conversation",id:P.id,force:!0})},children:f("dismissForceAll",{n:De})})]}):s.jsx("button",{type:"button",className:"lp-del",title:f("dismissConversation"),onClick:Ge=>{Ge.stopPropagation(),A(Ie)},children:s.jsx(tt,{})})})(),P.isStreaming&&s.jsx("span",{className:"lp-row-stalled",title:f("streaming"),style:{position:"absolute",right:28,top:"50%",transform:"translateY(-50%)"}})]},P.id)})})()]},_.cwd))})]}),ye.length>0&&!Y&&!j&&s.jsx("div",{className:"lp-sash",onPointerDown:Ae("convs","sessions"),onDoubleClick:()=>Be({...Dn}),title:f("dragToResize")}),s.jsxs("div",{className:`lp-section lp-section-sessions panel-sessions ${j?"collapsed":""}`,style:j?void 0:{flex:`${We("sessions")} 1 0px`},children:[ae(f("historySessions"),j,F,i.length),!j&&s.jsxs("div",{className:"lp-section-body sessions-scroll",children:[i.length===0&&s.jsx("div",{className:"panel-empty",children:f("noHistory")}),i.map(_=>{const Q=x===_.path;return s.jsxs("div",{className:"lp-row",onMouseLeave:()=>A(V=>V===`sess:${_.path}`?null:V),onContextMenu:V=>ue(V,{id:_.path,kind:"history",label:ve(_)}),children:[s.jsxs("button",{type:"button",className:`session-item ${Q?"active":""}`,title:_.path,onClick:()=>{R||Q||u({type:"switch_session",path:_.path})},children:[s.jsx(ts,{className:"session-icon"}),s.jsxs("span",{className:"session-info",children:[R===_.path?s.jsx("input",{autoFocus:!0,className:"session-rename-input",value:$,placeholder:f("renameSessionPlaceholder"),onClick:V=>V.stopPropagation(),onChange:V=>ce(V.target.value),onKeyDown:V=>{if(V.stopPropagation(),V.key==="Enter"&&!V.nativeEvent.isComposing){const Ee=$.trim();Ee&&u({type:"rename_session",path:_.path,name:Ee}),I(null)}else V.key==="Escape"&&I(null)},onBlur:()=>I(null)}):s.jsx("span",{className:"session-title",children:ve(_)}),R===_.path?null:s.jsxs("span",{className:"session-sub",children:[Q?f("current"):f("messageCount",{n:_.messageCount}),_.source==="tui"&&s.jsx("span",{className:"session-src",title:f("tuiTip"),children:"TUI"})]})]}),s.jsx("span",{className:"session-time",children:Zi(_.modified)})]}),s.jsx("button",{type:"button",className:"lp-del lp-rename",title:f("renameSession"),onClick:V=>{V.stopPropagation(),A(null),ce(_.name??""),I(_.path)},children:s.jsx(An,{})}),Pe(`sess:${_.path}`,f("deleteSession"),f("deleteSessionConfirm"),()=>u({type:"delete_session",path:_.path}))]},_.path)})]})]})]})});function Qd(e,t){const n=t.assistantMessageEvent,a=e.stats.tokens,i=t.usage!==null?{...a,...t.usage}:a,o=i===a?e.stats:{...e.stats,tokens:i};if(n.type!=="text_delta"&&n.type!=="thinking_delta")return o===e.stats?e:{...e,stats:o};const l=n.delta??"";if(!l)return o===e.stats?e:{...e,stats:o};const u=e.streamingMessage??null,p=u&&u.id===t.messageId?u:{id:t.messageId,content:[]},h=[...p.content],b=n.type==="thinking_delta"?"thinking":"text",m=n.contentIndex??h.length-1;return m>=0&&m<h.length&&h[m].type===b?h[m]=b==="thinking"?{type:"thinking",thinking:(h[m].thinking??"")+l}:{type:"text",text:(h[m].text??"")+l}:h.push(b==="thinking"?{type:"thinking",thinking:l}:{type:"text",text:l}),{...e,stats:o,streamingMessage:{...p,id:t.messageId,content:h}}}function Xd(e){const{current:t,source:n,snapshot:a,answered:i}=e;return a&&a.id&&!i.has(a.id)?t?.id===a.id?{changed:!1,question:t,source:n}:{changed:!0,question:a,source:"snapshot"}:!a&&t&&n==="snapshot"?{changed:!0,question:null,source:"live"}:{changed:!1,question:t,source:n}}const tr="__piWebUiHost",Jd=6,Vo=e=>new Promise(t=>setTimeout(t,e));async function Zd(e=3e3){const t=Date.now()+e;for(;;){const n=window.__piBridge;if(n&&typeof n.call=="function")return n;if(Date.now()>=t)return null;await Vo(100)}}function ep(e){const t=Math.max(1,Number(e.pollMs??100)),n=Math.max(t,Number(e.timeoutMs??8e3)),a=async o=>{const l=Date.now()+n;for(;;){if(o())return!0;if(Date.now()>=l)return o();await Vo(t)}},i=async(o,l)=>{const u=String(l.cwd??"").trim();if(u&&e.getCwd()!==u&&(e.send({type:"set_cwd",path:u}),await a(()=>e.getCwd()===u)),l.newChat!==!1){const p=e.getConversationId();e.send({type:"new_chat"}),await a(()=>e.getConversationId()!==p||e.isConversationBlank())}e.send({type:"prompt",text:o})};return{version:Jd,setView(o){const l=String(o??"").trim();l&&e.setView(l)},startChat(o){const l=String(o?.prompt??"").trim();return!l||!e.isReady()?!1:(i(l,o??{}).catch(()=>{}),!0)},compose(o){return fd()?Po({text:typeof o?.text=="string"?o.text:void 0,attachments:Array.isArray(o?.attachments)?o.attachments:void 0}):!1},async openSession(o){const l=Array.isArray(o?.folders)?o.folders.filter(N=>typeof N=="string"&&N.trim().length>0).map(N=>N.trim()):[],u=Array.isArray(o?.roots)?o.roots.filter(N=>typeof N=="string"&&N.trim().length>0).map(N=>N.trim()):[],p=String(o?.cwd??"").trim(),h=[...new Set([...l,...u])],b=p||h[0]||"";if(!b)return{ok:!1,error:"openSession 需要 cwd / folders / roots(绝对路径)"};if(!e.isReady())return{ok:!1,error:"尚未连接到服务器(还没有快照)"};const m=h.filter(N=>N!==b).slice(0,7),f=new Set([...e.listProjects?.()??[],...e.grantedPaths?.()??[]]);for(const N of[b,...m]){if(f.has(N))continue;if(!(e.confirm?await e.confirm({path:N}).catch(()=>!1):!1))return{ok:!1,error:`用户拒绝了该目录的访问:${N}`};e.grantPath?.(N)}if(e.getCwd()!==b&&(e.send({type:"set_cwd",path:b}),!await a(()=>e.getCwd()===b)))return{ok:!1,error:`切换工作目录失败或超时:${b}`};(m.length>0||e.getWorkspaceRoots().length>0)&&e.send({type:"set_workspace_roots",roots:m});let x=e.getConversationId()??void 0;if(o?.newChat!==!1){const N=x;e.send({type:"new_chat"}),await a(()=>e.getConversationId()!==N||e.isConversationBlank()),x=e.getConversationId()??void 0}const v=String(o?.prompt??"").trim();return v&&e.send({type:"prompt",text:v}),{ok:!0,...x?{sessionId:x}:{}}},sessions:{list:()=>e.listSessions(),async open(o){const l=String(o??"").trim();if(!l)return{ok:!1,error:"sessions.open 需要一个会话 id(先调 list)"};if(!e.isReady())return{ok:!1,error:"尚未连接到服务器(还没有快照)"};const u=e.listSessions().find(b=>b.id===l);if(!u)return{ok:!1,error:`找不到会话:${l}`};if(u.cwd&&u.cwd!==e.getCwd()){if(!new Set([...e.listProjects?.()??[],...e.grantedPaths?.()??[]]).has(u.cwd)){if(!(e.confirm?await e.confirm({path:u.cwd}).catch(()=>!1):!1))return{ok:!1,error:`用户拒绝了该目录的访问:${u.cwd}`};e.grantPath?.(u.cwd)}if(e.send({type:"set_cwd",path:u.cwd}),!await a(()=>e.getCwd()===u.cwd))return{ok:!1,error:`切换工作目录失败或超时:${u.cwd}`}}const p=e.getConversationId();return u.kind==="running"?e.send({type:"switch_conversation",id:u.id}):e.send({type:"switch_session",path:u.id}),await a(()=>e.getConversationId()!==p)?{ok:!0,sessionId:e.getConversationId()??void 0}:{ok:!1,error:`切换会话超时:${u.title}`}}},async reloadCatalog(o,l){const u=String(o??"").trim();if(!u)return{ok:!1,error:"reloadCatalog 需要一个目录来源(http(s) URL 或本地文件路径)"};if(!e.isReady())return{ok:!1,error:"尚未连接到服务器(还没有快照)"};const p=St();return new Promise(h=>{const b=setTimeout(()=>{Pn.delete(p),h({ok:!1,error:"目录同步超时(服务端未在等待窗口内回执)"})},Math.max(1e3,Number(e.catalogTimeoutMs??18e4)));Pn.set(p,m=>{clearTimeout(b),h(m)}),e.send({type:"plugin_catalog_sync",requestId:p,source:u,...l?.install?{install:!0}:{},...l?.replace?{replace:!0}:{}})})},onUiAction(o,l){return nr(Os,String(o??"").trim(),l)},onTopbarAction(o,l){return nr(Os,String(o??"").trim(),l)},async pageCall(o){const l=String(o?.op??"").trim();if(!l)return{ok:!1,error:"pageCall 需要一个动作名(op)"};if(Lo())return{ok:!1,error:"桌面版(Electron 外壳)不支持 browser_page:窗口里没有 Chrome 扩展运行时。请让用户改用系统浏览器打开同一个 pi-web-ui 地址(网页版)再试。/ The desktop app cannot run browser_page (no Chrome extension runtime); ask the user to open the same pi-web-ui address in a regular browser instead."};const u=await Zd(e.bridgeWaitMs??3e3);if(!u)return{ok:!1,error:"浏览器扩展的页面桥没就绪:确认已安装并启用 page-picker 扩展、本页地址已绑定,然后刷新本页"};try{const p=await u.call({op:l,...o.args===void 0?{}:{args:o.args},...o.target?{to:o.target}:{},...o.timeoutMs?{timeoutMs:o.timeoutMs}:{}});return p===void 0?{ok:!0}:{ok:!0,result:p}}catch(p){return{ok:!1,error:p instanceof Error?p.message:String(p)}}}}}function sr(e){try{const t=window;e?t[tr]=e:delete t[tr]}catch{}}const gn=new Map;let Os=null;async function Qo(e,t){const n=Os;Os=e;try{return await t()}finally{Os=n}}function nr(e,t,n){if(!t||typeof n!="function")return()=>{};const a=e?`${e}:${t}`:t;let i=gn.get(a);i||(i=new Set,gn.set(a,i));const o=i;return o.add(n),()=>{o.delete(n),o.size===0&&gn.delete(a)}}async function tp(e,t,n,a){const i=o=>{const l=gn.get(o);if(!l||l.size===0)return!1;for(const u of[...l])try{u(n)}catch(p){console.error(`[plugin:${e}] 顶栏动作 ${t} 抛错:`,p)}return!0};if(i(`${e}:${t}`)||i(t))return!0;if(a?.loadBundle&&await a.loadBundle(e).catch(()=>!1)){const l=Date.now()+Math.max(100,Number(a.waitMs??1500));for(;;){if(i(`${e}:${t}`)||i(t))return!0;if(Date.now()>=l)break;await new Promise(u=>setTimeout(u,100))}}return!1}const Pn=new Map;function sp(e){const t=Pn.get(e.requestId);if(t){if(Pn.delete(e.requestId),!e.ok){t({ok:!1,error:e.error??"目录同步失败"});return}t({ok:!0,...e.entries?{entries:e.entries}:{},...e.installed?{installed:e.installed}:{}})}}const Ba="pi-web-ui:plugin-data";function np(e,t){window.dispatchEvent(new CustomEvent(Ba,{detail:{pluginId:e,payload:t}}))}function ap(e){const t=n=>{const a=n.detail;e(a.pluginId,a.payload)};return window.addEventListener(Ba,t),()=>window.removeEventListener(Ba,t)}const Jt=new Map,Fa=new Set,Zt=new Set;let ar=-1;function Xo(){return[...Jt.values()]}function Jo(){const e=Xo();for(const t of Fa)t(e)}function ip(e){return Fa.add(e),e(Xo()),()=>Fa.delete(e)}async function Zo(e,t){try{const a=(await Qo(e.id,()=>import(lt(`/plugins/${encodeURIComponent(e.id)}/client/entry.mjs?e=${t}`)))).default;return a&&typeof a.mount=="function"?(Jt.set(e.id,{info:e,module:a}),!0):(Zt.add(e.id),console.error(`[plugin:${e.id}] entry.mjs 缺少 default.mount`),!1)}catch(n){return Zt.add(e.id),console.error(`[plugin:${e.id}] 客户端加载失败:`,n),!1}}async function Ha(e,t){if(Jt.has(e.id))return!0;if(Zt.has(e.id)||!e.hasClient)return!1;const n=await Zo(e,t);return Jo(),n}async function rp(e,t){t!==ar&&(ar=t,Jt.clear(),Zt.clear());const n=new Set(e.map(a=>a.id));for(const a of[...Jt.keys()])n.has(a)||Jt.delete(a);for(const a of[...Zt])n.has(a)||Zt.delete(a);await Promise.all(e.filter(a=>a.hasClient&&a.view!==!1&&!a.error&&!Jt.has(a.id)&&!Zt.has(a.id)).map(a=>Zo(a,t))),Jo()}function el(e,t){return{pluginId:e,send:n=>t({type:"plugin_message",pluginId:e,payload:n}),onData:n=>ap((a,i)=>{a===e&&n(i)})}}const op=15,lp="pi-web-ui:lang";function ir(){try{return(localStorage.getItem(lp)??"").trim()}catch{return""}}const rr="pi-web-ui:locale",fa=2e5,cp=2e5,up="LIVE_OMIT",dp={conversationId:null,goal:null,reviewModel:null,maxRounds:3,locked:!0,reviewing:!1,round:0,status:"",verdict:"pending",wizard:{active:!1,draft:"",model:null,step:0,maxSteps:6,status:""}};function pp(){const e=new Map,t=new Map,n=(a,i)=>`${a}:${i}`;return{write(a,i,o){const l=n(a,i),u=e.get(l);if(u&&u.size>0){for(const b of u)try{b.write(o)}catch{}return}const p=t.get(l)??"",h=p.length+o.length>cp?o:p+o;t.set(l,h)},register(a,i,o){const l=n(a,i);let u=e.get(l);u||(u=new Set,e.set(l,u)),u.add(o);const p=t.get(l);if(p){try{o.write(p)}catch{}t.delete(l)}return()=>{const h=e.get(l);h&&(h.delete(o),h.size===0&&e.delete(l)),t.delete(l)}},clear(){e.clear(),t.clear()}}}function or(e,t){const n=new Set;for(const i of t.messages)i.role==="toolResult"&&i.toolCallId&&n.add(i.toolCallId),i.role==="bashExecution"&&n.add(`bash-${i.id}`);let a=!1;for(const i of e.keys())n.has(i)&&(e.delete(i),a=!0);return a?new Map(e):e}function lr(e,t){if(e.size===0)return e;const n=new Set;for(const i of t.messages)i.role==="toolResult"&&i.toolCallId&&n.add(i.toolCallId);let a=!1;for(const i of e.keys())n.has(i)&&(e.delete(i),a=!0);return a?new Map(e):e}function mp(e,t){switch(t.type){case"status":return{...e,status:t.status,ready:t.status==="open"?e.ready:!1,terminals:t.status==="closed"?[]:e.terminals};case"ready":return{...e,serverVersion:t.serverVersion,engine:t.engine,appVersion:t.appVersion,managed:t.managed===!0,tabs:t.tabs,ready:!0,protocolMismatch:t.protocolVersion!==void 0&&t.protocolVersion!==op};case"snapshot":return{...e,ready:!0,state:t.state,activeConversationId:t.state.conversationId,liveOutputs:or(e.liveOutputs,t.state),toolStatuses:lr(e.toolStatuses,t.state)};case"snapshot_delta":{const n=e.state,a=t.msg;if(!n||n.conversationId!==a.conversationId||n.rev!==a.baseRev)return e;const i={...n,...a.state,messages:a.appended.length>0?[...n.messages,...a.appended]:n.messages};return{...e,ready:!0,state:i,activeConversationId:i.conversationId,liveOutputs:or(e.liveOutputs,i),toolStatuses:lr(e.toolStatuses,i)}}case"tool_delta":{const a=(e.liveOutputs.get(t.toolCallId)?.text??"")+t.delta,i=a.length>fa?`…[${up}:${a.length-fa}]…
318
- `+a.slice(a.length-fa):a,o=new Map(e.liveOutputs);return o.set(t.toolCallId,{toolName:t.toolName,text:i}),{...e,liveOutputs:o}}case"message_delta":{const n=e.state;return!n||n.conversationId!==t.msg.conversationId?e:{...e,state:Qd(n,t.msg)}}case"tool_status":return{...e,toolStatuses:new Map(e.toolStatuses).set(t.status.toolCallId,t.status)};case"notice":return{...e,notices:[...e.notices,t.notice].slice(-6)};case"dismiss_notice":return{...e,notices:e.notices.filter(n=>n.id!==t.id)};case"sessions":return{...e,sessions:t.sessions};case"conversations":return{...e,conversations:t.conversations,elsewhere:t.elsewhere??[],activeConversationId:t.activeId};case"projects":return{...e,projects:t.projects};case"files":return{...e,files:t.files};case"file_changed":return{...e,fileChanged:{path:t.path}};case"file_content":return{...e,fileContent:t.content};case"models":return{...e,models:t.models,modelsLoading:t.loading};case"models_config":return{...e,modelsConfig:t.providers};case"providers_status":return{...e,providers:t.providers};case"provider_keys":return{...e,providerKeys:t.keys};case"fetch_models_result":return{...e,fetchModelsResult:t.result};case"refresh_provider_result":return{...e,refreshProviderResult:t.result};case"clone_provider_result":return{...e,cloneProviderResult:t.result};case"install_result":return{...e,installResult:t.result};case"scm_data":return{...e,scmData:t.data};case"file_search_result":return{...e,fileSearch:t.result};case"session_search_result":return{...e,sessionSearch:t.result};case"scm_changed":return{...e,scmDirty:e.scmDirty+1};case"path_completions":return{...e,pathCompletions:t.completions};case"update_status":return{...e,update:t.status};case"update_status_all":return{...e,updatesAll:t.items};case"updates_check_started":return{...e,updatesAll:null};case"widgets":return{...e,widgets:t.widgets};case"statuses":return{...e,statuses:t.statuses};case"dialog":return{...e,dialog:t.dialog};case"question":return{...e,question:t.question};case"commands":return{...e,commands:t.commands,commandsPath:t.path};case"slash_commands":return{...e,slashCommands:t.commands};case"goal_status":return{...e,goal:t.status};case"settings":return{...e,settings:t.settings};case"bg_servers":return{...e,bgServers:t.servers};case"plugins":return{...e,plugins:t.plugins,pluginsEpoch:t.epoch};case"plugin_catalog":return{...e,pluginCatalog:t.entries,pluginCatalogEpoch:t.epoch};case"plugin_grants":return{...e,pluginGrants:t.grants};case"plugin_path_request":return{...e,pathRequests:[...e.pathRequests.filter(n=>n.id!==t.req.id),t.req]};case"plugin_path_resolved":return{...e,pathRequests:e.pathRequests.filter(n=>n.id!==t.id)};case"plugin_job":{const n=e.pluginJobs[t.job.jobId],a=t.line?[...n?.lines??[],t.line].slice(-40):n?.lines??[],i={...n,...t.job,lines:a,startedAt:n?.startedAt??Date.now()};return{...e,pluginJobs:{...e.pluginJobs,[t.job.jobId]:i}}}case"dsh_patches":return{...e,dshPatches:{patchDir:t.patchDir,files:t.files}};case"terminal_add":return{...e,terminals:[...e.terminals,t.meta]};case"terminal_remove":return{...e,terminals:e.terminals.filter(n=>n.id!==t.id)};case"terminal_exit":return t.conversationId&&(e.activeConversationId||e.state?.conversationId)&&t.conversationId!==(e.activeConversationId||e.state?.conversationId)?e:{...e,terminals:e.terminals.map(n=>n.id===t.terminalId?{...n,running:!1,exitCode:t.exitCode}:n)};case"terminal_restart":return{...e,terminals:e.terminals.map(n=>n.id===t.terminalId?{...n,running:!0,exitCode:null}:n)};case"terminal_list":return t.conversationId&&(e.activeConversationId||e.state?.conversationId)&&t.conversationId!==(e.activeConversationId||e.state?.conversationId)?e:{...e,terminals:t.terminals.map(n=>({...n,conversationId:t.conversationId??e.state?.conversationId??""}))};case"terminal_active":return{...e,terminalActiveId:t.id};default:return e}}const cr="pi-web-client-id";let ga=null;function On(){if(ga)return ga;let e=null;try{e=sessionStorage.getItem(cr),e||(e=St(),sessionStorage.setItem(cr,e))}catch{e=e??St()}return ga=e,e}const tl="pi-web-last-cwd";function hp(){try{return localStorage.getItem(tl)}catch{return null}}function fp(e){try{localStorage.setItem(tl,e)}catch{}}function gp(){const e=location.protocol==="https:"?"wss:":"ws:";return Ft(`${e}//${location.host}${lt("/ws")}`)}function bp(){const[e,t]=c.useReducer(mp,{status:"connecting",ready:!1,state:null,liveOutputs:new Map,toolStatuses:new Map,notices:[],sessions:[],conversations:[],elsewhere:[],activeConversationId:"",projects:[],files:null,fileChanged:null,fileContent:null,models:[],modelsLoading:!1,modelsConfig:[],providers:[],providerKeys:{},installResult:null,pathCompletions:[],update:null,updatesAll:null,widgets:[],statuses:[],dialog:null,question:null,commands:[],commandsPath:"",slashCommands:[],terminals:[],terminalActiveId:null,goal:dp,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,sessionSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,pluginCatalog:[],pluginCatalogEpoch:0,pluginJobs:{},pluginGrants:[],pathRequests:[],dshPatches:null,protocolMismatch:!1}),n=c.useRef(null),a=c.useRef(pp()),i=c.useRef(0),o=c.useRef(null),l=c.useRef(!0),u=c.useRef(0),p=c.useRef(0),h=c.useRef(new Map),b=c.useRef(null),m=c.useRef(!1),f=c.useRef(null),x=c.useRef(new Set),v=c.useRef("live"),N=()=>{b.current||(b.current=setTimeout(()=>{b.current=null;const j=n.current;j&&j.readyState===WebSocket.OPEN&&j.send(JSON.stringify({type:"get_state"}))},300))},B=(j,F)=>{const T=h.current,U=T.get(j);if(U!==void 0&&F!==U+1){const G=J.current.chat,D=G.activeConversationId||G.state?.conversationId;j===D&&N()}T.set(j,F)},X=c.useCallback((j,F)=>{const T=++p.current;t({type:"notice",notice:{id:T,level:j,text:F}})},[]),K=c.useCallback(j=>{const F=n.current;if(F&&F.readyState===WebSocket.OPEN){if(j.type==="check_updates_all"&&j.force===!0&&t({type:"updates_check_started"}),F.send(JSON.stringify(j)),j.type==="question_answer"){if(x.current.add(j.id),x.current.size>64){const T=x.current.values().next().value;T!==void 0&&x.current.delete(T)}v.current="live",t({type:"question",question:null})}return!0}return!1},[]),A=c.useCallback(j=>{const F=Xd({current:J.current.chat.question,source:v.current,snapshot:j,answered:x.current});F.changed&&(v.current=F.source,t({type:"question",question:F.question}))},[]);Fd(K);const R=c.useCallback(()=>{if(!l.current)return;t({type:"status",status:"connecting"});const j=new WebSocket(gp());n.current=j,j.onopen=()=>{n.current===j&&(t({type:"status",status:"open"}),i.current=0,u.current=Date.now(),j.send(JSON.stringify({type:"hello",clientId:On(),locale:ir()})))},j.onmessage=F=>{if(n.current!==j)return;u.current=Date.now();let T;try{T=JSON.parse(F.data)}catch{return}switch(T.type){case"ready":{const U="20260915T02095";if((J.current.chat.settings?.autoReload??!0)&&T.buildId&&U&&T.buildId!==U){const D=`pi-web-ui-reloaded-${T.buildId}`;if(!sessionStorage.getItem(D)){sessionStorage.setItem(D,"1"),location.reload();return}}Xi({engine:T.engine??"pi",managed:!!T.managed,tabs:T.tabs,appVersion:T.appVersion,serverVersion:T.serverVersion,service:T.service}),t({type:"ready",serverVersion:T.serverVersion,protocolVersion:T.protocolVersion,engine:T.engine,appVersion:T.appVersion,managed:T.managed,tabs:T.tabs,service:T.service}),j.send(JSON.stringify({type:"get_state"})),j.send(JSON.stringify({type:"list_files"})),j.send(JSON.stringify({type:"list_models"})),j.send(JSON.stringify({type:"list_commands"})),j.send(JSON.stringify({type:"get_commands"})),T.managed||(j.send(JSON.stringify({type:"check_update"})),j.send(JSON.stringify({type:"check_updates_all"})));break}case"snapshot":h.current=new Map,t({type:"snapshot",state:T.state}),A(T.state.pendingQuestion);break;case"snapshot_delta":{const U=J.current.chat.state;(!U||U.conversationId!==T.conversationId||U.rev!==T.baseRev)&&N(),t({type:"snapshot_delta",msg:T}),A(T.state.pendingQuestion);break}case"tool_delta":B(T.conversationId,T.seq),t({type:"tool_delta",toolCallId:T.toolCallId,toolName:T.toolName,delta:T.delta});break;case"tool_status":t({type:"tool_status",status:T});break;case"message_delta":{B(T.conversationId,T.seq),t({type:"message_delta",msg:T});break}case"notice":{const U=++p.current;t({type:"notice",notice:{id:U,level:T.level,text:T.text,textEn:T.textEn}});break}case"sessions":t({type:"sessions",sessions:T.sessions});break;case"conversations":t({type:"conversations",conversations:T.conversations,activeId:T.activeId,elsewhere:T.elsewhere});break;case"projects":t({type:"projects",projects:T.projects});break;case"files":t({type:"files",files:T});break;case"file_changed":t({type:"file_changed",path:T.path});break;case"file_content":t({type:"file_content",content:T});break;case"models":t({type:"models",models:T.models,loading:!1});break;case"models_config":t({type:"models_config",providers:T.providers});break;case"providers_status":t({type:"providers_status",providers:T.providers});break;case"provider_keys":t({type:"provider_keys",keys:T.keys});break;case"fetch_models_result":t({type:"fetch_models_result",result:{reqId:T.reqId,ok:T.ok,models:T.models,error:T.error}});break;case"refresh_provider_result":t({type:"refresh_provider_result",result:{reqId:T.reqId,ok:T.ok,added:T.added,total:T.total,error:T.error}});break;case"clone_provider_result":t({type:"clone_provider_result",result:{reqId:T.reqId,ok:T.ok,config:T.config,configs:T.configs,error:T.error}});break;case"scm_data":t({type:"scm_data",data:T});break;case"search_files_result":t({type:"file_search_result",result:{reqId:T.reqId,ok:T.ok,results:T.results,truncated:T.truncated}});break;case"session_search_results":t({type:"session_search_result",result:{reqId:T.reqId,ok:T.ok,results:T.results}});break;case"scm_changed":t({type:"scm_changed"});break;case"install_result":t({type:"install_result",result:T});break;case"path_completions":t({type:"path_completions",completions:T.completions});break;case"update_status":t({type:"update_status",status:T});break;case"update_status_all":t({type:"update_status_all",items:T.items});break;case"widgets":t({type:"widgets",widgets:T.widgets});break;case"statuses":t({type:"statuses",statuses:T.statuses});break;case"dialog":t({type:"dialog",dialog:{id:T.id,kind:T.kind,title:T.title,args:T.args}});break;case"dialog_closed":t({type:"dialog",dialog:null});break;case"question_pending":v.current="live",t({type:"question",question:{id:T.id,...T.deadline!==void 0?{deadline:T.deadline}:{},questions:T.questions}});break;case"page_request":{(async()=>{const U=window.__piWebUiHost;let G;if(!U?.pageCall)G={ok:!1,error:"宿主页面桥不可用(页面版本过旧?)—— 刷新本页后再试"};else try{G=await U.pageCall({op:T.op,...T.args===void 0?{}:{args:T.args},...T.target?{target:T.target}:{},timeoutMs:T.timeoutMs})}catch(D){G={ok:!1,error:D instanceof Error?D.message:String(D)}}K({type:"page_response",id:T.id,ok:G.ok===!0,...G.ok===!0?G.result===void 0?{}:{result:G.result}:{error:G.error??"页面操作失败"}})})();break}case"terminal_output":a.current.write(T.conversationId??J.current.chat.activeConversationId,T.terminalId,T.data);break;case"terminal_exit":t({type:"terminal_exit",conversationId:T.conversationId,terminalId:T.terminalId,exitCode:T.exitCode});break;case"terminal_list":t({type:"terminal_list",conversationId:T.conversationId,terminals:T.terminals});break;case"commands":t({type:"commands",commands:T.commands,path:T.path});break;case"slash_commands":t({type:"slash_commands",commands:T.commands});break;case"goal_status":t({type:"goal_status",status:T.status});break;case"settings_state":t({type:"settings",settings:T.settings});break;case"bg_servers":t({type:"bg_servers",servers:T.servers});break;case"plugins":t({type:"plugins",plugins:T.plugins,epoch:T.epoch});break;case"plugin_catalog":t({type:"plugin_catalog",entries:T.entries,epoch:T.epoch});break;case"plugin_grants":t({type:"plugin_grants",grants:T.grants});break;case"plugin_path_request":t({type:"plugin_path_request",req:{id:T.id,pluginId:T.pluginId,path:T.path,...T.reason?{reason:T.reason}:{}}});break;case"plugin_job":t({type:"plugin_job",job:{jobId:T.jobId,action:T.action,pluginId:T.pluginId,phase:T.phase,...T.ok===void 0?{}:{ok:T.ok},...T.error?{error:T.error}:{},...T.output?{output:T.output}:{}},...T.line?{line:T.line}:{}});break;case"plugin_catalog_sync_result":sp(T);break;case"dsh_patches":t({type:"dsh_patches",patchDir:T.patchDir,files:T.files});break;case"plugin_data":np(T.pluginId,T.payload);break}},j.onclose=()=>{if(n.current===j&&(n.current=null),a.current.clear(),!l.current||n.current&&n.current!==j)return;t({type:"status",status:"closed"});const F=Math.min(1e3*2**i.current,1e4);i.current+=1,o.current=setTimeout(()=>{o.current=null,R()},F)},j.onerror=()=>{}},[]);c.useEffect(()=>{const j=F=>{const T=F.detail??ir();T&&K({type:"set_locale",locale:T})};return window.addEventListener(rr,j),()=>window.removeEventListener(rr,j)},[K]),c.useEffect(()=>{l.current=!0,R();const j=setInterval(()=>{if(!l.current)return;const F=n.current;F&&F.readyState===WebSocket.OPEN&&Date.now()-u.current>3e4&&F.close()},5e3);return()=>{l.current=!1,clearInterval(j),o.current&&(clearTimeout(o.current),o.current=null),n.current?.close(),n.current=null}},[R]),c.useEffect(()=>{const j=e.state?.cwd;if(j){if(!m.current){m.current=!0;const F=hp();if(F&&F!==j){K({type:"set_cwd",path:F});return}}f.current!==j&&(f.current=j,fp(j))}},[e.state?.cwd,K]),c.useEffect(()=>{Xi({ready:e.ready,status:e.status,cwd:e.state?.cwd??"",workspaceRoots:e.state?.workspaceRoots??[]})},[e.ready,e.status,e.state?.cwd,e.state?.workspaceRoots]);const I=c.useCallback(j=>t({type:"dismiss_notice",id:j}),[]),$=c.useCallback(j=>t({type:"terminal_add",meta:j}),[]),ce=c.useCallback(j=>t({type:"terminal_remove",id:j}),[]),ge=c.useCallback(j=>t({type:"terminal_restart",terminalId:j}),[]),q=c.useCallback(j=>t({type:"terminal_active",id:j}),[]),Y=c.useCallback((j,F,T)=>a.current.register(j,F,T),[]),J=c.useRef({chat:e,send:K,pushNotice:X,dismissNotice:I,terminal:{create:$,close:ce,register:Y,restart:ge,select:q}});return J.current={chat:e,send:K,pushNotice:X,dismissNotice:I,terminal:{create:$,close:ce,register:Y,restart:ge,select:q}},J.current}const Ep=200*1024*1024,Tp=/windows/i.test(navigator.userAgent),xp=/[<>:"/\\|?*\u0000-\u001f]/g,yp=/[. ]+$/,kp=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function Np(e){const t=e.replace(xp,"_").replace(yp,"");return t?kp.test(t)?`_${t}`:t:"_"}function ur(e,t=!0){const n=new URLSearchParams({clientId:On(),path:e,...t?{download:"1"}:{}});return Ft(lt(`/api/file?${n}`))}const sl="FILE_NOT_FOUND";async function vp(e,t){const n=Tp?Np(t):t;try{const a=await fetch(ur(e));if(!a.ok)return{ok:!1,cancelled:!1,error:await a.text().catch(()=>"")||(a.status===404?sl:`HTTP ${a.status}`)};if(Number(a.headers.get("content-length")??"0")>Ep)return window.location.assign(ur(e)),{ok:!0};const o=await a.blob();return window.showSaveFilePicker&&window.isSecureContext?Cp(o,n):Ua(o,n)}catch(a){return{ok:!1,cancelled:!1,error:a instanceof Error?a.message:String(a)}}}async function Cp(e,t){let n;const a=window.showSaveFilePicker;if(!a)return Ua(e,t);try{n=await a({suggestedName:t})}catch(i){return i instanceof DOMException&&i.name==="AbortError"?{ok:!1,cancelled:!0}:Ua(e,t)}try{const i=await n.createWritable();return await i.write(e),await i.close(),{ok:!0}}catch(i){return{ok:!1,cancelled:!1,error:i instanceof Error?i.message:String(i)}}}function Ua(e,t){const n=URL.createObjectURL(e),a=document.createElement("a");return a.href=n,a.download=t,document.body.appendChild(a),a.click(),a.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4),{ok:!0}}function wp(e){return e instanceof Error?e.message:String(e)}function Sp(e,t,n,a){const i=n==="zh";switch(e.kind){case"no-client":return i?`插件 ${t} 没有客户端脚本(client/entry.mjs),无法显示这一页。`:`Plugin ${t} ships no client bundle (client/entry.mjs), so this page cannot be shown.`;case"load":return i?`插件 ${t} 的页面脚本加载失败:${e.detail}`:`Failed to load plugin ${t}'s page bundle: ${e.detail}`;case"mount":return`${a("pluginMountFailed",{name:t})}:${e.detail}`}}function nl({plugin:e,epoch:t,send:n,className:a}){const i=c.useRef(null),{locale:o}=Ut(),l=Me(),[u,p]=c.useState(null),h=c.useRef(n);c.useEffect(()=>{h.current=n},[n]),c.useEffect(()=>{const m=i.current;if(!m)return;let f=!1,x,v=!1;if(p(null),!e.hasClient){p({kind:"no-client"});return}return(async()=>{try{if(await Ha(e,t),f)return;const N=await Qo(e.id,()=>import(lt(`/plugins/${encodeURIComponent(e.id)}/client/entry.mjs?e=${t}`)));if(f)return;const B=N.default;if(!B||typeof B.mount!="function")throw new Error("client/entry.mjs 没有导出 default.mount()");v=!0,x=B.mount(m,el(e.id,X=>h.current(X)))}catch(N){if(f)return;console.error(`[plugin:${e.id}] 页面${v?"挂载":"加载"}失败:`,N),p({kind:v?"mount":"load",detail:wp(N)})}})(),()=>{if(f=!0,typeof x=="function")try{x()}catch(N){console.error(`[plugin:${e.id}] cleanup 失败:`,N)}m.textContent=""}},[e.id,e.hasClient,t]);const b=a?`plugin-page ${a}`:"plugin-page";return s.jsxs("div",{className:b,children:[s.jsx("div",{className:"plugin-page-host",ref:i}),u&&s.jsx("div",{className:"plugin-page-error",role:"alert",children:Sp(u,e.name,o,l)})]})}function al(e){return`pi-web-ui:${e}:tab`}function _p(e,t){try{const n=localStorage.getItem(al(e));return n&&t.some(a=>a.id===n)?n:null}catch{return null}}function dr(e,t){try{localStorage.setItem(al(e),t)}catch{}}function Ap(e){return e.length>0&&!/[a-z]/i.test(e)}function pr(e){if(e.label)return e.label;const t=e.pluginPage;return t?.entry.label||t?.plugin.name||e.id}function Ip({storageKey:e,tabs:t,epoch:n,send:a,extra:i,className:o}){const l=c.useId(),[u,p]=c.useState(()=>_p(e,t)??t[0]?.id??""),h=c.useRef([]),b=c.useRef(""),m=t.findIndex(K=>K.id===u),f=m>=0?t[m]:t[0],x=f?t.indexOf(f):-1;c.useEffect(()=>{if(!f)return;u!==f.id&&p(f.id);const K=`${e}:${f.id}`;b.current!==K&&(b.current=K,dr(e,f.id))},[f,u,e]);const v=K=>{p(K.id),b.current=`${e}:${K.id}`,dr(e,K.id)},N=(K,A)=>{const R=t.length;let I=-1;if(K.key==="ArrowRight")I=(A+1)%R;else if(K.key==="ArrowLeft")I=(A-1+R)%R;else if(K.key==="Home")I=0;else if(K.key==="End")I=R-1;else return;const $=t[I];$&&(K.preventDefault(),v($),h.current[I]?.focus())};if(!f)return null;const B=`${l}-panel-${x}`,X=o?`slot-tabs ${o}`:"slot-tabs";return s.jsxs("div",{className:X,children:[s.jsxs("div",{className:"slot-tabs-bar",role:"tablist",children:[t.map((K,A)=>{const R=A===x;return s.jsxs("button",{type:"button",role:"tab",id:`${l}-tab-${A}`,className:R?"slot-tab active":"slot-tab",title:K.hint??pr(K),"aria-selected":R,"aria-controls":`${l}-panel-${A}`,tabIndex:R?0:-1,ref:I=>{h.current[A]=I},onClick:()=>v(K),onKeyDown:I=>N(I,A),children:[K.icon&&Ap(K.icon)?s.jsx("span",{className:"slot-tab-icon",children:K.icon}):null,s.jsx("span",{className:"slot-tab-label",children:pr(K)})]},K.id)}),i?s.jsx("div",{className:"slot-tabs-extra",children:i}):null]}),s.jsx("div",{className:"slot-tabs-body",id:B,role:"tabpanel","aria-labelledby":`${l}-tab-${x}`,children:f.pluginPage?s.jsx(nl,{plugin:f.pluginPage.plugin,epoch:n,send:a}):f.element??null})]})}const us="@root",mr="pi-web-ui:rp-sizes",ba={files:4,widgets:1},hr=120,fr=56;function jp(e,t){return t?Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top):32}const Rp="files",Lp=[],Dp=()=>{},Pp=c.memo(function({files:t,fileChanged:n,widgets:a,panelSend:i,onAttach:o,onPreview:l,onNotice:u,collapsible:p,onToggleCollapse:h,uiRightPanelTabs:b,uiContextFile:m,plugins:f,pluginsEpoch:x,send:v}){const N=Me(),B=f??Lp,X=wt("cwd"),K=wt("workspaceRoots"),[A,R]=c.useState(""),[I,$]=c.useState(null),[ce,ge]=c.useState(!1),q=c.useRef(null),Y=c.useRef(null),[J,j]=c.useState(()=>{try{return Yo(localStorage.getItem(mr),ba)}catch{return{...ba}}});c.useEffect(()=>{try{localStorage.setItem(mr,JSON.stringify(J))}catch{}},[J]);const F=a.some(C=>C.lines.length>0),T=c.useCallback(C=>{C.preventDefault();const S=q.current;if(!S)return;const he=C.currentTarget,Ce=C.clientY,$e={above:J.files,below:J.widgets},we=Math.max(120,S.clientHeight-jp(S,Y.current));he.classList.add("dragging"),document.body.classList.add("rp-resizing");const Je=bt=>{const{above:At,below:$t}=Go({start:$e,deltaPx:bt.clientY-Ce,availablePx:we,totalWeight:$e.above+$e.below,minAbovePx:hr,minBelowPx:fr});j({files:At,widgets:$t})},gt=()=>{window.removeEventListener("pointermove",Je),window.removeEventListener("pointerup",gt),he.classList.remove("dragging"),document.body.classList.remove("rp-resizing")};window.addEventListener("pointermove",Je),window.addEventListener("pointerup",gt)},[J.files,J.widgets]),U=c.useRef(null),G=c.useRef(0),D=c.useCallback(C=>{U.current=C,C&&(C.scrollTop=G.current)},[]),[se,ee]=c.useState(null),Ne=c.useRef(null);c.useEffect(()=>()=>{Ne.current&&clearTimeout(Ne.current)},[]);const w=c.useCallback(C=>{ee(C),Ne.current&&clearTimeout(Ne.current),Ne.current=setTimeout(()=>ee(null),1200)},[]),de=C=>{try{const S=document.createElement("textarea");S.value=C,S.style.position="fixed",S.style.opacity="0",document.body.appendChild(S),S.select();const he=document.execCommand("copy");return document.body.removeChild(S),he}catch{return!1}},ue=c.useCallback((C,S)=>{if(!C)return;const he=()=>w(S),Ce=()=>u("error",N("slashCopyFailed")),$e=navigator;$e.clipboard?.writeText?$e.clipboard.writeText(C).then(he,()=>{de(C)?he():Ce()}):de(C)?he():Ce()},[w,u,N]),pe=c.useCallback(C=>{if(!C)return X;if(/^[A-Za-z]:$/.test(C))return`${C}/`;if(C.startsWith("/")||/^[A-Za-z]:([/]|$)/.test(C))return C;const S=X.replace(/\\/g,"/").replace(/\/+$/,"");return S?`${S}/${C}`:C},[X]),ke=c.useCallback(C=>!C||C===us?null:C.startsWith("/")||/^[A-Za-z]:([/]|$)/.test(C)?C:`${X.replace(/\\/g,"/").replace(/\/+$/,"")}/${C}`,[X]),Be=c.useCallback((C,S)=>{for(const he of S){const Ce=new FileReader;Ce.onload=()=>{const $e=Ce.result,we=$e.slice($e.indexOf(",")+1);we&&i({type:"upload_file",dirPath:C,name:he.name,data:we})},Ce.readAsDataURL(he)}},[i]),ye=c.useRef(null),Ae=c.useRef(null),ve=c.useCallback(()=>{const C=ye.current?.project;C&&i({type:"set_cwd",path:C.path})},[i]),Ye=c.useCallback(()=>{Ae.current&&(Ae.current.value=""),Ae.current?.click()},[]),[Pe,ae]=c.useState(!1);c.useEffect(()=>{if(!Pe)return;const C=he=>{he.target?.closest(".root-picker")||ae(!1)},S=he=>{he.key==="Escape"&&ae(!1)};return window.addEventListener("mousedown",C,!0),window.addEventListener("keydown",S),()=>{window.removeEventListener("mousedown",C,!0),window.removeEventListener("keydown",S)}},[Pe]);const be=c.useCallback(C=>{i({type:"set_workspace_roots",roots:C})},[i]),Oe=c.useCallback(()=>{const C=ye.current?.target;if(!C||C.kind!=="dir")return;const S=ke(C.id);!S||K.includes(S)||be([...K,S])},[K,ke,be]),Le=c.useCallback(C=>{Be(ye.current?.dir??A,Array.from(C.target.files??[]))},[Be,A]),We=c.useCallback(C=>{C.id==="host:file-open-project"?ve():C.id==="host:file-upload"?Ye():C.id==="host:file-add-root"&&Oe()},[ve,Ye,Oe]),_=c.useCallback((C,S)=>{const he=S.kind==="dir"?ke(S.id):null,Ce={target:S,dir:S.kind==="dir"?S.id:A,project:he?{path:he,name:S.label}:null},$e=(m??[]).map(we=>we.source!=="host"?we:we.id==="host:file-upload"?{...we,label:Ce.dir===A?N("uploadToCurrentDir"):N("uploadToFolder")}:we.id==="host:file-open-project"?he?we:{...we,hidden:!0}:we.id==="host:file-add-root"?!!he&&he!==X&&!K.includes(he)?we:{...we,hidden:!0}:we);Ln($e).length!==0&&(C.preventDefault(),C.stopPropagation(),ye.current=Ce,Xn({x:C.clientX,y:C.clientY,slot:"contextmenu.file",target:S,entries:$e,onHostAction:We}))},[m,A,ke,N,We,X,K]),Q=C=>Array.from(C.dataTransfer?.types??[]).includes("Files"),V=c.useCallback(()=>{U.current?.querySelectorAll(".file-item.drop-target").forEach(C=>C.classList.remove("drop-target")),U.current?.classList.remove("drop-root")},[]),Ee=c.useCallback(C=>{if(V(),C==null)return;const S=U.current?.querySelector(`.file-item[data-path="${CSS.escape(C)}"]`);S?S.classList.add("drop-target"):U.current?.classList.add("drop-root")},[V]),oe=C=>{const S=C instanceof Element?C.closest(".file-item"):null;return S?.dataset.type==="dir"?S.dataset.path??A:A},Z=c.useCallback(()=>{const C=document.querySelector(".app");C&&C.dispatchEvent(new DragEvent("dragleave",{bubbles:!0}))},[]),y=1e4,P=c.useRef(0),le=c.useRef(void 0),Te=c.useCallback((C,S)=>{const he=++P.current;R(C),S?.silent||ge(!0),i({type:"list_files",path:C===""?void 0:C})||P.current===he&&ge(!1)},[i]),Ie=c.useCallback(C=>{const S=K.filter(he=>he!==C);be(S),(A===C||A.startsWith(`${C}/`))&&Te("")},[K,be,A,Te]);c.useEffect(()=>{t&&t.path===A&&ge(!1)},[t,A]),c.useEffect(()=>{if(X!==le.current){le.current=X,Te("",{silent:!0});return}const C=setInterval(()=>{document.visibilityState!=="hidden"&&Te(A,{silent:!0})},y);return()=>clearInterval(C)},[X,A,Te]),c.useEffect(()=>{n&&n.path===A&&Te(A,{silent:!0})},[n,A,Te]);const Fe=C=>Te(C),Re=()=>{t?.parent!==null&&t?.parent!==void 0&&Te(t.parent)},L=(()=>{if(A===""||A===us)return[];const C=A.split("/").filter(S=>!!S&&S!==us);return A.startsWith("/")?C.map((S,he)=>({label:he===0?"/":C[he],path:"/"+C.slice(0,he+1).join("/")})):C.map((S,he)=>({label:C[he],path:C.slice(0,he+1).join("/")}))})(),De=[];for(const C of b??[]){if(C.source==="host"||C.hidden||C.kind==="divider")continue;const S=B.find(he=>he.id===C.source.slice(7));S&&De.push({id:C.id,label:C.label,icon:C.icon,hint:C.hint,pluginPage:{plugin:S,entry:C}})}const Ge=(b??[]).some(C=>C.id==="host:right-files"&&C.hidden);return s.jsxs("aside",{className:"panel panel-right",ref:q,children:[p&&h&&s.jsx("button",{type:"button",className:"panel-collapse-btn",title:N("collapsePanel"),onClick:h,children:s.jsx(Co,{})}),s.jsx("div",{ref:Y,style:{display:"flex",flexDirection:"column",flex:F?`${J.files} 1 0`:"1 1 0",minHeight:F?hr:0},children:s.jsx(Ip,{storageKey:"rightpanel",epoch:x??0,send:v??Dp,tabs:[...Ge?[]:[{id:Rp,label:N("openFiles"),element:s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"panel-crumbs",children:[s.jsx("button",{type:"button",className:`crumb ${A===""?"active":""}`,onClick:()=>Te(""),children:N("rootDir")}),s.jsx("button",{type:"button",className:`crumb ${A===us?"active":""}`,title:N("computer"),onClick:()=>Te(us),children:"💻"}),K.length>0&&s.jsxs("div",{className:"root-picker",children:[s.jsxs("button",{type:"button",className:"crumb root-picker-trigger","aria-haspopup":"menu","aria-expanded":Pe,title:N("workspaceRoots"),onClick:()=>ae(C=>!C),children:[s.jsx(Bt,{}),s.jsx("span",{className:"root-picker-label",children:N("workspaceRoots")}),s.jsx("span",{className:"set-count",children:K.length+1}),"▾"]}),Pe&&s.jsxs("div",{className:"root-picker-menu",role:"menu",children:[s.jsx("div",{className:"root-picker-row",children:s.jsxs("button",{type:"button",role:"menuitem",className:A===""?"root-picker-item active":"root-picker-item",title:X,onClick:()=>{ae(!1),Te("")},children:[N("rootDir"),s.jsx("span",{className:"root-picker-path",children:X})]})}),K.map(C=>s.jsxs("div",{className:"root-picker-row",children:[s.jsx("button",{type:"button",role:"menuitem",className:A===C?"root-picker-item active":"root-picker-item",title:C,onClick:()=>{ae(!1),Te(C)},children:s.jsx("span",{className:"root-picker-path",children:C})}),s.jsx("button",{type:"button",className:"root-picker-remove",title:N("removeWorkspaceRoot"),"aria-label":N("removeWorkspaceRoot"),onClick:()=>Ie(C),children:s.jsx(tt,{})})]},C)),s.jsx("div",{className:"root-picker-hint",children:N("workspaceRootsHint")})]})]}),L.map(C=>s.jsxs("span",{className:"crumb-seg",children:[s.jsx(rs,{}),s.jsx("button",{type:"button",className:`crumb ${C.path===A?"active":""}`,onClick:()=>Te(C.path),children:C.label})]},C.path))]}),s.jsxs("div",{ref:D,className:"panel-body",onScroll:C=>{G.current=C.currentTarget.scrollTop},onContextMenu:C=>_(C,{id:A,kind:"list",label:A===""?N("rootDir"):A===us?N("computer"):A}),onDragOver:C=>{Q(C)&&(C.preventDefault(),C.stopPropagation(),C.dataTransfer.dropEffect="copy",Z(),Ee(oe(C.target)))},onDragLeave:C=>{C.relatedTarget&&C.currentTarget.contains(C.relatedTarget)||V()},onDrop:C=>{if(V(),!Q(C))return;C.preventDefault(),C.stopPropagation(),Z();const S=Array.from(C.dataTransfer?.files??[]);if(S.length===0){u("warning",N("foldersNotSupported"));return}Be(oe(C.target),S)},onDragEnd:V,children:[s.jsx("input",{ref:Ae,type:"file",multiple:!0,hidden:!0,onChange:Le}),ce&&s.jsx("div",{className:"panel-empty",children:N("loading")}),!ce&&t&&t.path===A&&s.jsxs(s.Fragment,{children:[t.parent!=null&&s.jsxs("button",{type:"button",className:"file-item dir",onClick:Re,children:[s.jsx(Bt,{className:"file-icon"}),s.jsx("span",{className:"file-name",children:".."})]}),t.entries.map(C=>C.type==="dir"?s.jsxs("div",{className:"file-item dir","data-type":"dir","data-path":C.path,onContextMenu:S=>_(S,{id:C.path,kind:"dir",label:C.name}),children:[s.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>Fe(C.path),children:[s.jsx(Bt,{className:"file-icon"}),s.jsx("span",{className:"file-name",children:C.name})]}),s.jsx("button",{type:"button",className:"file-attach ref","data-tip":N("linkFolderTip"),"aria-label":N("linkFolderTip"),onClick:()=>o(C.path,C.name,"reference",!0),children:s.jsx(Ia,{})}),s.jsx("button",{type:"button",className:`file-attach copy${se===`name:${C.path}`?" copied":""}`,"data-tip":N("copyName"),"aria-label":N("copyName"),onClick:()=>ue(C.name,`name:${C.path}`),children:se===`name:${C.path}`?s.jsx(Lt,{}):s.jsx(Dt,{})}),s.jsx("button",{type:"button",className:`file-attach copy${se===`path:${C.path}`?" copied":""}`,"data-tip":N("copyPath"),"aria-label":N("copyPath"),onClick:()=>ue(pe(C.path),`path:${C.path}`),children:se===`path:${C.path}`?s.jsx(Lt,{}):s.jsx(Pi,{})})]},C.path):s.jsxs("div",{className:"file-item file","data-type":"file","data-path":C.path,onContextMenu:S=>_(S,{id:C.path,kind:"file",label:C.name}),children:[s.jsxs("button",{type:"button",className:"file-name",title:`${C.path} — ${N("previewFile")}`,onClick:()=>l(C.path,C.name),children:[s.jsx(Hu,{className:"file-icon"}),s.jsx("span",{className:"file-name-text",children:C.name})]}),s.jsx("button",{type:"button",className:"file-attach download","data-tip":N("downloadFile"),onClick:()=>{vp(C.path,C.name).then(S=>{S.ok||S.cancelled||u("error",N("downloadFailed",{error:S.error===sl?N("fileNotFoundShort"):S.error}))})},children:s.jsx(ss,{})}),s.jsx("button",{type:"button",className:"file-attach inline","data-tip":N("attachInlineTip"),onClick:()=>o(C.path,C.name,"inline"),children:s.jsx(kt,{})}),s.jsx("button",{type:"button",className:"file-attach ref","data-tip":N("referenceTip"),"aria-label":N("referenceTip"),onClick:()=>o(C.path,C.name,"reference"),children:s.jsx(Ia,{})}),s.jsx("button",{type:"button",className:`file-attach copy${se===`name:${C.path}`?" copied":""}`,"data-tip":N("copyName"),"aria-label":N("copyName"),onClick:()=>ue(C.name,`name:${C.path}`),children:se===`name:${C.path}`?s.jsx(Lt,{}):s.jsx(Dt,{})}),s.jsx("button",{type:"button",className:`file-attach copy${se===`path:${C.path}`?" copied":""}`,"data-tip":N("copyPath"),"aria-label":N("copyPath"),onClick:()=>ue(pe(C.path),`path:${C.path}`),children:se===`path:${C.path}`?s.jsx(Lt,{}):s.jsx(Pi,{})})]},C.path)),t.truncated&&s.jsx("div",{className:"panel-empty files-truncated",children:N("filesTruncated")})]}),!ce&&!t&&s.jsx("div",{className:"panel-empty",children:N("noFiles")})]})]})}],...De]})}),F&&s.jsx("div",{className:"rp-sash",onPointerDown:T,onDoubleClick:()=>j({...ba}),title:N("dragToResize")}),F&&s.jsx("div",{className:"panel-widgets",style:{flexGrow:J.widgets,minHeight:fr},children:a.filter(C=>C.lines.length>0).map(C=>s.jsxs("div",{className:"widget",children:[s.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:N("widgetExpand"),onClick:()=>$(C.key),children:[s.jsx("span",{children:C.key}),s.jsx(Lu,{})]}),s.jsx("pre",{className:"widget-lines",children:C.lines.join(`
319
- `)})]},C.key))}),I&&(()=>{const C=a.find(S=>S.key===I);return C?s.jsx("div",{className:"modal-backdrop",onClick:()=>$(null),children:s.jsxs("div",{className:"widget-expand",onClick:S=>S.stopPropagation(),children:[s.jsxs("div",{className:"widget-expand-head",children:[s.jsx("span",{className:"widget-expand-title",children:C.key}),s.jsx("button",{type:"button",className:"btn",title:N("close"),onClick:()=>$(null),children:s.jsx(tt,{})})]}),s.jsx("pre",{className:"widget-expand-lines",children:C.lines.join(`
320
- `)})]})}):null})()]})});var Jn=Eo();function Op(e){eu(e,[/\r?\n|\r/g,Mp])}function Mp(){return{type:"break"}}function Bp(){return function(e){Op(e)}}function Fp(e){const t=String(e),n=[];return{toOffset:i,toPoint:a};function a(o){if(typeof o=="number"&&o>-1&&o<=t.length){let l=0;for(;;){let u=n[l];if(u===void 0){const p=gr(t,n[l-1]);u=p===-1?t.length+1:p+1,n[l]=u}if(u>o)return{line:l+1,column:o-(l>0?n[l-1]:0)+1,offset:o};l++}}}function i(o){if(o&&typeof o.line=="number"&&typeof o.column=="number"&&!Number.isNaN(o.line)&&!Number.isNaN(o.column)){for(;n.length<o.line;){const u=n[n.length-1],p=gr(t,u),h=p===-1?t.length+1:p+1;if(u===h)break;n.push(h)}const l=(o.line>1?n[o.line-2]:0)+o.column-1;if(l<n[o.line-1])return l}}}function gr(e,t){const n=e.indexOf("\r",t),a=e.indexOf(`
321
- `,t);return a===-1?n:n===-1||n+1===a?a:n<a?n:a}const il={}.hasOwnProperty,Hp=Object.prototype;function Up(e,t){const n=t||{};return oi({file:n.file||void 0,location:!1,schema:n.space==="svg"?zn:ii,verbose:n.verbose||!1},e)}function oi(e,t){let n;switch(t.nodeName){case"#comment":{const a=t;return n={type:"comment",value:a.data},bn(e,a,n),n}case"#document":case"#document-fragment":{const a=t,i="mode"in a?a.mode==="quirks"||a.mode==="limited-quirks":!1;if(n={type:"root",children:rl(e,t.childNodes),data:{quirksMode:i}},e.file&&e.location){const o=String(e.file),l=Fp(o),u=l.toPoint(0),p=l.toPoint(o.length);n.position={start:u,end:p}}return n}case"#documentType":{const a=t;return n={type:"doctype"},bn(e,a,n),n}case"#text":{const a=t;return n={type:"text",value:a.value},bn(e,a,n),n}default:return n=$p(e,t),n}}function rl(e,t){let n=-1;const a=[];for(;++n<t.length;){const i=oi(e,t[n]);a.push(i)}return a}function $p(e,t){const n=e.schema;e.schema=t.namespaceURI===Xt.svg?zn:ii;let a=-1;const i={};for(;++a<t.attrs.length;){const u=t.attrs[a],p=(u.prefix?u.prefix+":":"")+u.name;il.call(Hp,p)||(i[p]=u.value)}const l=(e.schema.space==="svg"?tu:su)(t.tagName,i,rl(e,t.childNodes));if(bn(e,t,l),l.tagName==="template"){const u=t,p=u.sourceCodeLocation,h=p&&p.startTag&&ms(p.startTag),b=p&&p.endTag&&ms(p.endTag),m=oi(e,u.content);h&&b&&e.file&&(m.position={start:h.end,end:b.start}),l.content=m}return e.schema=n,l}function bn(e,t,n){if("sourceCodeLocation"in t&&t.sourceCodeLocation&&e.file){const a=qp(e,n,t.sourceCodeLocation);a&&(e.location=!0,n.position=a)}}function qp(e,t,n){const a=ms(n);if(t.type==="element"){const i=t.children[t.children.length-1];if(a&&!n.endTag&&i&&i.position&&i.position.end&&(a.end=Object.assign({},i.position.end)),e.verbose){const o={};let l;if(n.attrs)for(l in n.attrs)il.call(n.attrs,l)&&(o[mo(e.schema,l).property]=ms(n.attrs[l]));Sa(n.startTag);const u=ms(n.startTag),p=n.endTag?ms(n.endTag):void 0,h={opening:u};p&&(h.closing=p),h.properties=o,t.data={position:h}}}return a}function ms(e){const t=br({line:e.startLine,column:e.startCol,offset:e.startOffset}),n=br({line:e.endLine,column:e.endCol,offset:e.endOffset});return t||n?{start:t,end:n}:void 0}function br(e){return e.line&&e.column?e:void 0}const Wp={},Kp={}.hasOwnProperty,ol=ho("type",{handlers:{root:Gp,element:Jp,text:Qp,comment:Xp,doctype:Vp}});function Yp(e,t){const a=(t||Wp).space;return ol(e,a==="svg"?zn:ii)}function Gp(e,t){const n={nodeName:"#document",mode:(e.data||{}).quirksMode?"quirks":"no-quirks",childNodes:[]};return n.childNodes=li(e.children,n,t),Ts(e,n),n}function zp(e,t){const n={nodeName:"#document-fragment",childNodes:[]};return n.childNodes=li(e.children,n,t),Ts(e,n),n}function Vp(e){const t={nodeName:"#documentType",name:"html",publicId:"",systemId:"",parentNode:null};return Ts(e,t),t}function Qp(e){const t={nodeName:"#text",value:e.value,parentNode:null};return Ts(e,t),t}function Xp(e){const t={nodeName:"#comment",data:e.value,parentNode:null};return Ts(e,t),t}function Jp(e,t){const n=t;let a=n;e.type==="element"&&e.tagName.toLowerCase()==="svg"&&n.space==="html"&&(a=zn);const i=[];let o;if(e.properties){for(o in e.properties)if(o!=="children"&&Kp.call(e.properties,o)){const p=Zp(a,o,e.properties[o]);p&&i.push(p)}}const l=a.space,u={nodeName:e.tagName,tagName:e.tagName,attrs:i,namespaceURI:Xt[l],childNodes:[],parentNode:null};return u.childNodes=li(e.children,u,a),Ts(e,u),e.tagName==="template"&&e.content&&(u.content=zp(e.content,a)),u}function Zp(e,t,n){const a=mo(e,t);if(n===!1||n===null||n===void 0||typeof n=="number"&&Number.isNaN(n)||!n&&a.boolean)return;Array.isArray(n)&&(n=a.commaSeparated?nu(n):au(n));const i={name:a.attribute,value:n===!0?"":String(n)};if(a.space&&a.space!=="html"&&a.space!=="svg"){const o=i.name.indexOf(":");o<0?i.prefix="":(i.name=i.name.slice(o+1),i.prefix=a.attribute.slice(0,o)),i.namespace=Xt[a.space]}return i}function li(e,t,n){let a=-1;const i=[];if(e)for(;++a<e.length;){const o=ol(e[a],n);o.parentNode=t,i.push(o)}return i}function Ts(e,t){const n=e.position;n&&n.start&&n.end&&(Sa(typeof n.start.offset=="number"),Sa(typeof n.end.offset=="number"),t.sourceCodeLocation={startLine:n.start.line,startCol:n.start.column,startOffset:n.start.offset,endLine:n.end.line,endCol:n.end.column,endOffset:n.end.offset})}const em=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","keygen","link","meta","param","source","track","wbr"],tm=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),et="�";var g;(function(e){e[e.EOF=-1]="EOF",e[e.NULL=0]="NULL",e[e.TABULATION=9]="TABULATION",e[e.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",e[e.LINE_FEED=10]="LINE_FEED",e[e.FORM_FEED=12]="FORM_FEED",e[e.SPACE=32]="SPACE",e[e.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",e[e.QUOTATION_MARK=34]="QUOTATION_MARK",e[e.AMPERSAND=38]="AMPERSAND",e[e.APOSTROPHE=39]="APOSTROPHE",e[e.HYPHEN_MINUS=45]="HYPHEN_MINUS",e[e.SOLIDUS=47]="SOLIDUS",e[e.DIGIT_0=48]="DIGIT_0",e[e.DIGIT_9=57]="DIGIT_9",e[e.SEMICOLON=59]="SEMICOLON",e[e.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",e[e.EQUALS_SIGN=61]="EQUALS_SIGN",e[e.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.LATIN_CAPITAL_A=65]="LATIN_CAPITAL_A",e[e.LATIN_CAPITAL_Z=90]="LATIN_CAPITAL_Z",e[e.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",e[e.GRAVE_ACCENT=96]="GRAVE_ACCENT",e[e.LATIN_SMALL_A=97]="LATIN_SMALL_A",e[e.LATIN_SMALL_Z=122]="LATIN_SMALL_Z"})(g||(g={}));const ht={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function ll(e){return e>=55296&&e<=57343}function sm(e){return e>=56320&&e<=57343}function nm(e,t){return(e-55296)*1024+9216+t}function cl(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function ul(e){return e>=64976&&e<=65007||tm.has(e)}var z;(function(e){e.controlCharacterInInputStream="control-character-in-input-stream",e.noncharacterInInputStream="noncharacter-in-input-stream",e.surrogateInInputStream="surrogate-in-input-stream",e.nonVoidHtmlElementStartTagWithTrailingSolidus="non-void-html-element-start-tag-with-trailing-solidus",e.endTagWithAttributes="end-tag-with-attributes",e.endTagWithTrailingSolidus="end-tag-with-trailing-solidus",e.unexpectedSolidusInTag="unexpected-solidus-in-tag",e.unexpectedNullCharacter="unexpected-null-character",e.unexpectedQuestionMarkInsteadOfTagName="unexpected-question-mark-instead-of-tag-name",e.invalidFirstCharacterOfTagName="invalid-first-character-of-tag-name",e.unexpectedEqualsSignBeforeAttributeName="unexpected-equals-sign-before-attribute-name",e.missingEndTagName="missing-end-tag-name",e.unexpectedCharacterInAttributeName="unexpected-character-in-attribute-name",e.unknownNamedCharacterReference="unknown-named-character-reference",e.missingSemicolonAfterCharacterReference="missing-semicolon-after-character-reference",e.unexpectedCharacterAfterDoctypeSystemIdentifier="unexpected-character-after-doctype-system-identifier",e.unexpectedCharacterInUnquotedAttributeValue="unexpected-character-in-unquoted-attribute-value",e.eofBeforeTagName="eof-before-tag-name",e.eofInTag="eof-in-tag",e.missingAttributeValue="missing-attribute-value",e.missingWhitespaceBetweenAttributes="missing-whitespace-between-attributes",e.missingWhitespaceAfterDoctypePublicKeyword="missing-whitespace-after-doctype-public-keyword",e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers="missing-whitespace-between-doctype-public-and-system-identifiers",e.missingWhitespaceAfterDoctypeSystemKeyword="missing-whitespace-after-doctype-system-keyword",e.missingQuoteBeforeDoctypePublicIdentifier="missing-quote-before-doctype-public-identifier",e.missingQuoteBeforeDoctypeSystemIdentifier="missing-quote-before-doctype-system-identifier",e.missingDoctypePublicIdentifier="missing-doctype-public-identifier",e.missingDoctypeSystemIdentifier="missing-doctype-system-identifier",e.abruptDoctypePublicIdentifier="abrupt-doctype-public-identifier",e.abruptDoctypeSystemIdentifier="abrupt-doctype-system-identifier",e.cdataInHtmlContent="cdata-in-html-content",e.incorrectlyOpenedComment="incorrectly-opened-comment",e.eofInScriptHtmlCommentLikeText="eof-in-script-html-comment-like-text",e.eofInDoctype="eof-in-doctype",e.nestedComment="nested-comment",e.abruptClosingOfEmptyComment="abrupt-closing-of-empty-comment",e.eofInComment="eof-in-comment",e.incorrectlyClosedComment="incorrectly-closed-comment",e.eofInCdata="eof-in-cdata",e.absenceOfDigitsInNumericCharacterReference="absence-of-digits-in-numeric-character-reference",e.nullCharacterReference="null-character-reference",e.surrogateCharacterReference="surrogate-character-reference",e.characterReferenceOutsideUnicodeRange="character-reference-outside-unicode-range",e.controlCharacterReference="control-character-reference",e.noncharacterCharacterReference="noncharacter-character-reference",e.missingWhitespaceBeforeDoctypeName="missing-whitespace-before-doctype-name",e.missingDoctypeName="missing-doctype-name",e.invalidCharacterSequenceAfterDoctypeName="invalid-character-sequence-after-doctype-name",e.duplicateAttribute="duplicate-attribute",e.nonConformingDoctype="non-conforming-doctype",e.missingDoctype="missing-doctype",e.misplacedDoctype="misplaced-doctype",e.endTagWithoutMatchingOpenElement="end-tag-without-matching-open-element",e.closingOfElementWithOpenChildElements="closing-of-element-with-open-child-elements",e.disallowedContentInNoscriptInHead="disallowed-content-in-noscript-in-head",e.openElementsLeftAfterEof="open-elements-left-after-eof",e.abandonedHeadElementChild="abandoned-head-element-child",e.misplacedStartTagForHeadElement="misplaced-start-tag-for-head-element",e.nestedNoscriptInHead="nested-noscript-in-head",e.eofInElementThatCanContainOnlyText="eof-in-element-that-can-contain-only-text"})(z||(z={}));const am=65536;class im{constructor(t){this.handler=t,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=!1,this.lastChunkWritten=!1,this.endOfChunkHit=!1,this.bufferWaterline=am,this.isEol=!1,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1}get col(){return this.pos-this.lineStartPos+ +(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(t,n){const{line:a,col:i,offset:o}=this,l=i+n,u=o+n;return{code:t,startLine:a,endLine:a,startCol:l,endCol:l,startOffset:u,endOffset:u}}_err(t){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(t,0)))}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos}_processSurrogate(t){if(this.pos!==this.html.length-1){const n=this.html.charCodeAt(this.pos+1);if(sm(n))return this.pos++,this._addGap(),nm(t,n)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,g.EOF;return this._err(z.surrogateInInputStream),t}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0)}write(t,n){this.html.length>0?this.html+=t:this.html=t,this.endOfChunkHit=!1,this.lastChunkWritten=n}insertHtmlAtCurrentPos(t){this.html=this.html.substring(0,this.pos+1)+t+this.html.substring(this.pos+1),this.endOfChunkHit=!1}startsWith(t,n){if(this.pos+t.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,!1;if(n)return this.html.startsWith(t,this.pos);for(let a=0;a<t.length;a++)if((this.html.charCodeAt(this.pos+a)|32)!==t.charCodeAt(a))return!1;return!0}peek(t){const n=this.pos+t;if(n>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,g.EOF;const a=this.html.charCodeAt(n);return a===g.CARRIAGE_RETURN?g.LINE_FEED:a}advance(){if(this.pos++,this.isEol&&(this.isEol=!1,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,g.EOF;let t=this.html.charCodeAt(this.pos);return t===g.CARRIAGE_RETURN?(this.isEol=!0,this.skipNextNewLine=!0,g.LINE_FEED):t===g.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance()):(this.skipNextNewLine=!1,ll(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===g.LINE_FEED||t===g.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){cl(t)?this._err(z.controlCharacterInInputStream):ul(t)&&this._err(z.noncharacterInInputStream)}retreat(t){for(this.pos-=t;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=!1}}var Ue;(function(e){e[e.CHARACTER=0]="CHARACTER",e[e.NULL_CHARACTER=1]="NULL_CHARACTER",e[e.WHITESPACE_CHARACTER=2]="WHITESPACE_CHARACTER",e[e.START_TAG=3]="START_TAG",e[e.END_TAG=4]="END_TAG",e[e.COMMENT=5]="COMMENT",e[e.DOCTYPE=6]="DOCTYPE",e[e.EOF=7]="EOF",e[e.HIBERNATION=8]="HIBERNATION"})(Ue||(Ue={}));function dl(e,t){for(let n=e.attrs.length-1;n>=0;n--)if(e.attrs[n].name===t)return e.attrs[n].value;return null}const rm=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms„‹•˜¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(e=>e.charCodeAt(0))),om=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]);function lm(e){var t;return e>=55296&&e<=57343||e>1114111?65533:(t=om.get(e))!==null&&t!==void 0?t:e}var ot;(function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"})(ot||(ot={}));const cm=32;var Gt;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"})(Gt||(Gt={}));function $a(e){return e>=ot.ZERO&&e<=ot.NINE}function um(e){return e>=ot.UPPER_A&&e<=ot.UPPER_F||e>=ot.LOWER_A&&e<=ot.LOWER_F}function dm(e){return e>=ot.UPPER_A&&e<=ot.UPPER_Z||e>=ot.LOWER_A&&e<=ot.LOWER_Z||$a(e)}function pm(e){return e===ot.EQUALS||dm(e)}var rt;(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(rt||(rt={}));var Mt;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(Mt||(Mt={}));class mm{constructor(t,n,a){this.decodeTree=t,this.emitCodePoint=n,this.errors=a,this.state=rt.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=Mt.Strict}startEntity(t){this.decodeMode=t,this.state=rt.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(t,n){switch(this.state){case rt.EntityStart:return t.charCodeAt(n)===ot.NUM?(this.state=rt.NumericStart,this.consumed+=1,this.stateNumericStart(t,n+1)):(this.state=rt.NamedEntity,this.stateNamedEntity(t,n));case rt.NumericStart:return this.stateNumericStart(t,n);case rt.NumericDecimal:return this.stateNumericDecimal(t,n);case rt.NumericHex:return this.stateNumericHex(t,n);case rt.NamedEntity:return this.stateNamedEntity(t,n)}}stateNumericStart(t,n){return n>=t.length?-1:(t.charCodeAt(n)|cm)===ot.LOWER_X?(this.state=rt.NumericHex,this.consumed+=1,this.stateNumericHex(t,n+1)):(this.state=rt.NumericDecimal,this.stateNumericDecimal(t,n))}addToNumericResult(t,n,a,i){if(n!==a){const o=a-n;this.result=this.result*Math.pow(i,o)+Number.parseInt(t.substr(n,o),i),this.consumed+=o}}stateNumericHex(t,n){const a=n;for(;n<t.length;){const i=t.charCodeAt(n);if($a(i)||um(i))n+=1;else return this.addToNumericResult(t,a,n,16),this.emitNumericEntity(i,3)}return this.addToNumericResult(t,a,n,16),-1}stateNumericDecimal(t,n){const a=n;for(;n<t.length;){const i=t.charCodeAt(n);if($a(i))n+=1;else return this.addToNumericResult(t,a,n,10),this.emitNumericEntity(i,2)}return this.addToNumericResult(t,a,n,10),-1}emitNumericEntity(t,n){var a;if(this.consumed<=n)return(a=this.errors)===null||a===void 0||a.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(t===ot.SEMI)this.consumed+=1;else if(this.decodeMode===Mt.Strict)return 0;return this.emitCodePoint(lm(this.result),this.consumed),this.errors&&(t!==ot.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,n){const{decodeTree:a}=this;let i=a[this.treeIndex],o=(i&Gt.VALUE_LENGTH)>>14;for(;n<t.length;n++,this.excess++){const l=t.charCodeAt(n);if(this.treeIndex=hm(a,i,this.treeIndex+Math.max(1,o),l),this.treeIndex<0)return this.result===0||this.decodeMode===Mt.Attribute&&(o===0||pm(l))?0:this.emitNotTerminatedNamedEntity();if(i=a[this.treeIndex],o=(i&Gt.VALUE_LENGTH)>>14,o!==0){if(l===ot.SEMI)return this.emitNamedEntityData(this.treeIndex,o,this.consumed+this.excess);this.decodeMode!==Mt.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var t;const{result:n,decodeTree:a}=this,i=(a[n]&Gt.VALUE_LENGTH)>>14;return this.emitNamedEntityData(n,i,this.consumed),(t=this.errors)===null||t===void 0||t.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,n,a){const{decodeTree:i}=this;return this.emitCodePoint(n===1?i[t]&~Gt.VALUE_LENGTH:i[t+1],a),n===3&&this.emitCodePoint(i[t+2],a),a}end(){var t;switch(this.state){case rt.NamedEntity:return this.result!==0&&(this.decodeMode!==Mt.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case rt.NumericDecimal:return this.emitNumericEntity(0,2);case rt.NumericHex:return this.emitNumericEntity(0,3);case rt.NumericStart:return(t=this.errors)===null||t===void 0||t.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case rt.EntityStart:return 0}}}function hm(e,t,n,a){const i=(t&Gt.BRANCH_LENGTH)>>7,o=t&Gt.JUMP_TABLE;if(i===0)return o!==0&&a===o?n:-1;if(o){const p=a-o;return p<0||p>=i?-1:e[n+p]-1}let l=n,u=l+i-1;for(;l<=u;){const p=l+u>>>1,h=e[p];if(h<a)l=p+1;else if(h>a)u=p-1;else return e[p+i]}return-1}var ne;(function(e){e.HTML="http://www.w3.org/1999/xhtml",e.MATHML="http://www.w3.org/1998/Math/MathML",e.SVG="http://www.w3.org/2000/svg",e.XLINK="http://www.w3.org/1999/xlink",e.XML="http://www.w3.org/XML/1998/namespace",e.XMLNS="http://www.w3.org/2000/xmlns/"})(ne||(ne={}));var ns;(function(e){e.TYPE="type",e.ACTION="action",e.ENCODING="encoding",e.PROMPT="prompt",e.NAME="name",e.COLOR="color",e.FACE="face",e.SIZE="size"})(ns||(ns={}));var yt;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks"})(yt||(yt={}));var M;(function(e){e.A="a",e.ADDRESS="address",e.ANNOTATION_XML="annotation-xml",e.APPLET="applet",e.AREA="area",e.ARTICLE="article",e.ASIDE="aside",e.B="b",e.BASE="base",e.BASEFONT="basefont",e.BGSOUND="bgsound",e.BIG="big",e.BLOCKQUOTE="blockquote",e.BODY="body",e.BR="br",e.BUTTON="button",e.CAPTION="caption",e.CENTER="center",e.CODE="code",e.COL="col",e.COLGROUP="colgroup",e.DD="dd",e.DESC="desc",e.DETAILS="details",e.DIALOG="dialog",e.DIR="dir",e.DIV="div",e.DL="dl",e.DT="dt",e.EM="em",e.EMBED="embed",e.FIELDSET="fieldset",e.FIGCAPTION="figcaption",e.FIGURE="figure",e.FONT="font",e.FOOTER="footer",e.FOREIGN_OBJECT="foreignObject",e.FORM="form",e.FRAME="frame",e.FRAMESET="frameset",e.H1="h1",e.H2="h2",e.H3="h3",e.H4="h4",e.H5="h5",e.H6="h6",e.HEAD="head",e.HEADER="header",e.HGROUP="hgroup",e.HR="hr",e.HTML="html",e.I="i",e.IMG="img",e.IMAGE="image",e.INPUT="input",e.IFRAME="iframe",e.KEYGEN="keygen",e.LABEL="label",e.LI="li",e.LINK="link",e.LISTING="listing",e.MAIN="main",e.MALIGNMARK="malignmark",e.MARQUEE="marquee",e.MATH="math",e.MENU="menu",e.META="meta",e.MGLYPH="mglyph",e.MI="mi",e.MO="mo",e.MN="mn",e.MS="ms",e.MTEXT="mtext",e.NAV="nav",e.NOBR="nobr",e.NOFRAMES="noframes",e.NOEMBED="noembed",e.NOSCRIPT="noscript",e.OBJECT="object",e.OL="ol",e.OPTGROUP="optgroup",e.OPTION="option",e.P="p",e.PARAM="param",e.PLAINTEXT="plaintext",e.PRE="pre",e.RB="rb",e.RP="rp",e.RT="rt",e.RTC="rtc",e.RUBY="ruby",e.S="s",e.SCRIPT="script",e.SEARCH="search",e.SECTION="section",e.SELECT="select",e.SOURCE="source",e.SMALL="small",e.SPAN="span",e.STRIKE="strike",e.STRONG="strong",e.STYLE="style",e.SUB="sub",e.SUMMARY="summary",e.SUP="sup",e.TABLE="table",e.TBODY="tbody",e.TEMPLATE="template",e.TEXTAREA="textarea",e.TFOOT="tfoot",e.TD="td",e.TH="th",e.THEAD="thead",e.TITLE="title",e.TR="tr",e.TRACK="track",e.TT="tt",e.U="u",e.UL="ul",e.SVG="svg",e.VAR="var",e.WBR="wbr",e.XMP="xmp"})(M||(M={}));var r;(function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.A=1]="A",e[e.ADDRESS=2]="ADDRESS",e[e.ANNOTATION_XML=3]="ANNOTATION_XML",e[e.APPLET=4]="APPLET",e[e.AREA=5]="AREA",e[e.ARTICLE=6]="ARTICLE",e[e.ASIDE=7]="ASIDE",e[e.B=8]="B",e[e.BASE=9]="BASE",e[e.BASEFONT=10]="BASEFONT",e[e.BGSOUND=11]="BGSOUND",e[e.BIG=12]="BIG",e[e.BLOCKQUOTE=13]="BLOCKQUOTE",e[e.BODY=14]="BODY",e[e.BR=15]="BR",e[e.BUTTON=16]="BUTTON",e[e.CAPTION=17]="CAPTION",e[e.CENTER=18]="CENTER",e[e.CODE=19]="CODE",e[e.COL=20]="COL",e[e.COLGROUP=21]="COLGROUP",e[e.DD=22]="DD",e[e.DESC=23]="DESC",e[e.DETAILS=24]="DETAILS",e[e.DIALOG=25]="DIALOG",e[e.DIR=26]="DIR",e[e.DIV=27]="DIV",e[e.DL=28]="DL",e[e.DT=29]="DT",e[e.EM=30]="EM",e[e.EMBED=31]="EMBED",e[e.FIELDSET=32]="FIELDSET",e[e.FIGCAPTION=33]="FIGCAPTION",e[e.FIGURE=34]="FIGURE",e[e.FONT=35]="FONT",e[e.FOOTER=36]="FOOTER",e[e.FOREIGN_OBJECT=37]="FOREIGN_OBJECT",e[e.FORM=38]="FORM",e[e.FRAME=39]="FRAME",e[e.FRAMESET=40]="FRAMESET",e[e.H1=41]="H1",e[e.H2=42]="H2",e[e.H3=43]="H3",e[e.H4=44]="H4",e[e.H5=45]="H5",e[e.H6=46]="H6",e[e.HEAD=47]="HEAD",e[e.HEADER=48]="HEADER",e[e.HGROUP=49]="HGROUP",e[e.HR=50]="HR",e[e.HTML=51]="HTML",e[e.I=52]="I",e[e.IMG=53]="IMG",e[e.IMAGE=54]="IMAGE",e[e.INPUT=55]="INPUT",e[e.IFRAME=56]="IFRAME",e[e.KEYGEN=57]="KEYGEN",e[e.LABEL=58]="LABEL",e[e.LI=59]="LI",e[e.LINK=60]="LINK",e[e.LISTING=61]="LISTING",e[e.MAIN=62]="MAIN",e[e.MALIGNMARK=63]="MALIGNMARK",e[e.MARQUEE=64]="MARQUEE",e[e.MATH=65]="MATH",e[e.MENU=66]="MENU",e[e.META=67]="META",e[e.MGLYPH=68]="MGLYPH",e[e.MI=69]="MI",e[e.MO=70]="MO",e[e.MN=71]="MN",e[e.MS=72]="MS",e[e.MTEXT=73]="MTEXT",e[e.NAV=74]="NAV",e[e.NOBR=75]="NOBR",e[e.NOFRAMES=76]="NOFRAMES",e[e.NOEMBED=77]="NOEMBED",e[e.NOSCRIPT=78]="NOSCRIPT",e[e.OBJECT=79]="OBJECT",e[e.OL=80]="OL",e[e.OPTGROUP=81]="OPTGROUP",e[e.OPTION=82]="OPTION",e[e.P=83]="P",e[e.PARAM=84]="PARAM",e[e.PLAINTEXT=85]="PLAINTEXT",e[e.PRE=86]="PRE",e[e.RB=87]="RB",e[e.RP=88]="RP",e[e.RT=89]="RT",e[e.RTC=90]="RTC",e[e.RUBY=91]="RUBY",e[e.S=92]="S",e[e.SCRIPT=93]="SCRIPT",e[e.SEARCH=94]="SEARCH",e[e.SECTION=95]="SECTION",e[e.SELECT=96]="SELECT",e[e.SOURCE=97]="SOURCE",e[e.SMALL=98]="SMALL",e[e.SPAN=99]="SPAN",e[e.STRIKE=100]="STRIKE",e[e.STRONG=101]="STRONG",e[e.STYLE=102]="STYLE",e[e.SUB=103]="SUB",e[e.SUMMARY=104]="SUMMARY",e[e.SUP=105]="SUP",e[e.TABLE=106]="TABLE",e[e.TBODY=107]="TBODY",e[e.TEMPLATE=108]="TEMPLATE",e[e.TEXTAREA=109]="TEXTAREA",e[e.TFOOT=110]="TFOOT",e[e.TD=111]="TD",e[e.TH=112]="TH",e[e.THEAD=113]="THEAD",e[e.TITLE=114]="TITLE",e[e.TR=115]="TR",e[e.TRACK=116]="TRACK",e[e.TT=117]="TT",e[e.U=118]="U",e[e.UL=119]="UL",e[e.SVG=120]="SVG",e[e.VAR=121]="VAR",e[e.WBR=122]="WBR",e[e.XMP=123]="XMP"})(r||(r={}));const fm=new Map([[M.A,r.A],[M.ADDRESS,r.ADDRESS],[M.ANNOTATION_XML,r.ANNOTATION_XML],[M.APPLET,r.APPLET],[M.AREA,r.AREA],[M.ARTICLE,r.ARTICLE],[M.ASIDE,r.ASIDE],[M.B,r.B],[M.BASE,r.BASE],[M.BASEFONT,r.BASEFONT],[M.BGSOUND,r.BGSOUND],[M.BIG,r.BIG],[M.BLOCKQUOTE,r.BLOCKQUOTE],[M.BODY,r.BODY],[M.BR,r.BR],[M.BUTTON,r.BUTTON],[M.CAPTION,r.CAPTION],[M.CENTER,r.CENTER],[M.CODE,r.CODE],[M.COL,r.COL],[M.COLGROUP,r.COLGROUP],[M.DD,r.DD],[M.DESC,r.DESC],[M.DETAILS,r.DETAILS],[M.DIALOG,r.DIALOG],[M.DIR,r.DIR],[M.DIV,r.DIV],[M.DL,r.DL],[M.DT,r.DT],[M.EM,r.EM],[M.EMBED,r.EMBED],[M.FIELDSET,r.FIELDSET],[M.FIGCAPTION,r.FIGCAPTION],[M.FIGURE,r.FIGURE],[M.FONT,r.FONT],[M.FOOTER,r.FOOTER],[M.FOREIGN_OBJECT,r.FOREIGN_OBJECT],[M.FORM,r.FORM],[M.FRAME,r.FRAME],[M.FRAMESET,r.FRAMESET],[M.H1,r.H1],[M.H2,r.H2],[M.H3,r.H3],[M.H4,r.H4],[M.H5,r.H5],[M.H6,r.H6],[M.HEAD,r.HEAD],[M.HEADER,r.HEADER],[M.HGROUP,r.HGROUP],[M.HR,r.HR],[M.HTML,r.HTML],[M.I,r.I],[M.IMG,r.IMG],[M.IMAGE,r.IMAGE],[M.INPUT,r.INPUT],[M.IFRAME,r.IFRAME],[M.KEYGEN,r.KEYGEN],[M.LABEL,r.LABEL],[M.LI,r.LI],[M.LINK,r.LINK],[M.LISTING,r.LISTING],[M.MAIN,r.MAIN],[M.MALIGNMARK,r.MALIGNMARK],[M.MARQUEE,r.MARQUEE],[M.MATH,r.MATH],[M.MENU,r.MENU],[M.META,r.META],[M.MGLYPH,r.MGLYPH],[M.MI,r.MI],[M.MO,r.MO],[M.MN,r.MN],[M.MS,r.MS],[M.MTEXT,r.MTEXT],[M.NAV,r.NAV],[M.NOBR,r.NOBR],[M.NOFRAMES,r.NOFRAMES],[M.NOEMBED,r.NOEMBED],[M.NOSCRIPT,r.NOSCRIPT],[M.OBJECT,r.OBJECT],[M.OL,r.OL],[M.OPTGROUP,r.OPTGROUP],[M.OPTION,r.OPTION],[M.P,r.P],[M.PARAM,r.PARAM],[M.PLAINTEXT,r.PLAINTEXT],[M.PRE,r.PRE],[M.RB,r.RB],[M.RP,r.RP],[M.RT,r.RT],[M.RTC,r.RTC],[M.RUBY,r.RUBY],[M.S,r.S],[M.SCRIPT,r.SCRIPT],[M.SEARCH,r.SEARCH],[M.SECTION,r.SECTION],[M.SELECT,r.SELECT],[M.SOURCE,r.SOURCE],[M.SMALL,r.SMALL],[M.SPAN,r.SPAN],[M.STRIKE,r.STRIKE],[M.STRONG,r.STRONG],[M.STYLE,r.STYLE],[M.SUB,r.SUB],[M.SUMMARY,r.SUMMARY],[M.SUP,r.SUP],[M.TABLE,r.TABLE],[M.TBODY,r.TBODY],[M.TEMPLATE,r.TEMPLATE],[M.TEXTAREA,r.TEXTAREA],[M.TFOOT,r.TFOOT],[M.TD,r.TD],[M.TH,r.TH],[M.THEAD,r.THEAD],[M.TITLE,r.TITLE],[M.TR,r.TR],[M.TRACK,r.TRACK],[M.TT,r.TT],[M.U,r.U],[M.UL,r.UL],[M.SVG,r.SVG],[M.VAR,r.VAR],[M.WBR,r.WBR],[M.XMP,r.XMP]]);function xs(e){var t;return(t=fm.get(e))!==null&&t!==void 0?t:r.UNKNOWN}const re=r,gm={[ne.HTML]:new Set([re.ADDRESS,re.APPLET,re.AREA,re.ARTICLE,re.ASIDE,re.BASE,re.BASEFONT,re.BGSOUND,re.BLOCKQUOTE,re.BODY,re.BR,re.BUTTON,re.CAPTION,re.CENTER,re.COL,re.COLGROUP,re.DD,re.DETAILS,re.DIR,re.DIV,re.DL,re.DT,re.EMBED,re.FIELDSET,re.FIGCAPTION,re.FIGURE,re.FOOTER,re.FORM,re.FRAME,re.FRAMESET,re.H1,re.H2,re.H3,re.H4,re.H5,re.H6,re.HEAD,re.HEADER,re.HGROUP,re.HR,re.HTML,re.IFRAME,re.IMG,re.INPUT,re.LI,re.LINK,re.LISTING,re.MAIN,re.MARQUEE,re.MENU,re.META,re.NAV,re.NOEMBED,re.NOFRAMES,re.NOSCRIPT,re.OBJECT,re.OL,re.P,re.PARAM,re.PLAINTEXT,re.PRE,re.SCRIPT,re.SECTION,re.SELECT,re.SOURCE,re.STYLE,re.SUMMARY,re.TABLE,re.TBODY,re.TD,re.TEMPLATE,re.TEXTAREA,re.TFOOT,re.TH,re.THEAD,re.TITLE,re.TR,re.TRACK,re.UL,re.WBR,re.XMP]),[ne.MATHML]:new Set([re.MI,re.MO,re.MN,re.MS,re.MTEXT,re.ANNOTATION_XML]),[ne.SVG]:new Set([re.TITLE,re.FOREIGN_OBJECT,re.DESC]),[ne.XLINK]:new Set,[ne.XML]:new Set,[ne.XMLNS]:new Set},qa=new Set([re.H1,re.H2,re.H3,re.H4,re.H5,re.H6]);M.STYLE,M.SCRIPT,M.XMP,M.IFRAME,M.NOEMBED,M.NOFRAMES,M.PLAINTEXT;var E;(function(e){e[e.DATA=0]="DATA",e[e.RCDATA=1]="RCDATA",e[e.RAWTEXT=2]="RAWTEXT",e[e.SCRIPT_DATA=3]="SCRIPT_DATA",e[e.PLAINTEXT=4]="PLAINTEXT",e[e.TAG_OPEN=5]="TAG_OPEN",e[e.END_TAG_OPEN=6]="END_TAG_OPEN",e[e.TAG_NAME=7]="TAG_NAME",e[e.RCDATA_LESS_THAN_SIGN=8]="RCDATA_LESS_THAN_SIGN",e[e.RCDATA_END_TAG_OPEN=9]="RCDATA_END_TAG_OPEN",e[e.RCDATA_END_TAG_NAME=10]="RCDATA_END_TAG_NAME",e[e.RAWTEXT_LESS_THAN_SIGN=11]="RAWTEXT_LESS_THAN_SIGN",e[e.RAWTEXT_END_TAG_OPEN=12]="RAWTEXT_END_TAG_OPEN",e[e.RAWTEXT_END_TAG_NAME=13]="RAWTEXT_END_TAG_NAME",e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]="SCRIPT_DATA_LESS_THAN_SIGN",e[e.SCRIPT_DATA_END_TAG_OPEN=15]="SCRIPT_DATA_END_TAG_OPEN",e[e.SCRIPT_DATA_END_TAG_NAME=16]="SCRIPT_DATA_END_TAG_NAME",e[e.SCRIPT_DATA_ESCAPE_START=17]="SCRIPT_DATA_ESCAPE_START",e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]="SCRIPT_DATA_ESCAPE_START_DASH",e[e.SCRIPT_DATA_ESCAPED=19]="SCRIPT_DATA_ESCAPED",e[e.SCRIPT_DATA_ESCAPED_DASH=20]="SCRIPT_DATA_ESCAPED_DASH",e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]="SCRIPT_DATA_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START",e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]="SCRIPT_DATA_DOUBLE_ESCAPED",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END",e[e.BEFORE_ATTRIBUTE_NAME=31]="BEFORE_ATTRIBUTE_NAME",e[e.ATTRIBUTE_NAME=32]="ATTRIBUTE_NAME",e[e.AFTER_ATTRIBUTE_NAME=33]="AFTER_ATTRIBUTE_NAME",e[e.BEFORE_ATTRIBUTE_VALUE=34]="BEFORE_ATTRIBUTE_VALUE",e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED",e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED",e[e.ATTRIBUTE_VALUE_UNQUOTED=37]="ATTRIBUTE_VALUE_UNQUOTED",e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]="AFTER_ATTRIBUTE_VALUE_QUOTED",e[e.SELF_CLOSING_START_TAG=39]="SELF_CLOSING_START_TAG",e[e.BOGUS_COMMENT=40]="BOGUS_COMMENT",e[e.MARKUP_DECLARATION_OPEN=41]="MARKUP_DECLARATION_OPEN",e[e.COMMENT_START=42]="COMMENT_START",e[e.COMMENT_START_DASH=43]="COMMENT_START_DASH",e[e.COMMENT=44]="COMMENT",e[e.COMMENT_LESS_THAN_SIGN=45]="COMMENT_LESS_THAN_SIGN",e[e.COMMENT_LESS_THAN_SIGN_BANG=46]="COMMENT_LESS_THAN_SIGN_BANG",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH",e[e.COMMENT_END_DASH=49]="COMMENT_END_DASH",e[e.COMMENT_END=50]="COMMENT_END",e[e.COMMENT_END_BANG=51]="COMMENT_END_BANG",e[e.DOCTYPE=52]="DOCTYPE",e[e.BEFORE_DOCTYPE_NAME=53]="BEFORE_DOCTYPE_NAME",e[e.DOCTYPE_NAME=54]="DOCTYPE_NAME",e[e.AFTER_DOCTYPE_NAME=55]="AFTER_DOCTYPE_NAME",e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD",e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER",e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER",e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS",e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD",e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER",e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER",e[e.BOGUS_DOCTYPE=67]="BOGUS_DOCTYPE",e[e.CDATA_SECTION=68]="CDATA_SECTION",e[e.CDATA_SECTION_BRACKET=69]="CDATA_SECTION_BRACKET",e[e.CDATA_SECTION_END=70]="CDATA_SECTION_END",e[e.CHARACTER_REFERENCE=71]="CHARACTER_REFERENCE",e[e.AMBIGUOUS_AMPERSAND=72]="AMBIGUOUS_AMPERSAND"})(E||(E={}));const st={DATA:E.DATA,RCDATA:E.RCDATA,RAWTEXT:E.RAWTEXT,SCRIPT_DATA:E.SCRIPT_DATA,PLAINTEXT:E.PLAINTEXT,CDATA_SECTION:E.CDATA_SECTION};function bm(e){return e>=g.DIGIT_0&&e<=g.DIGIT_9}function Ls(e){return e>=g.LATIN_CAPITAL_A&&e<=g.LATIN_CAPITAL_Z}function Em(e){return e>=g.LATIN_SMALL_A&&e<=g.LATIN_SMALL_Z}function Wt(e){return Em(e)||Ls(e)}function Er(e){return Wt(e)||bm(e)}function on(e){return e+32}function pl(e){return e===g.SPACE||e===g.LINE_FEED||e===g.TABULATION||e===g.FORM_FEED}function Tr(e){return pl(e)||e===g.SOLIDUS||e===g.GREATER_THAN_SIGN}function Tm(e){return e===g.NULL?z.nullCharacterReference:e>1114111?z.characterReferenceOutsideUnicodeRange:ll(e)?z.surrogateCharacterReference:ul(e)?z.noncharacterCharacterReference:cl(e)||e===g.CARRIAGE_RETURN?z.controlCharacterReference:null}class xm{constructor(t,n){this.options=t,this.handler=n,this.paused=!1,this.inLoop=!1,this.inForeignNode=!1,this.lastStartTagName="",this.active=!1,this.state=E.DATA,this.returnState=E.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new im(n),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new mm(rm,(a,i)=>{this.preprocessor.pos=this.entityStartPos+i-1,this._flushCodePointConsumedAsCharacterReference(a)},n.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(z.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:a=>{this._err(z.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+a)},validateNumericCharacterReference:a=>{const i=Tm(a);i&&this._err(i,1)}}:void 0)}_err(t,n=0){var a,i;(i=(a=this.handler).onParseError)===null||i===void 0||i.call(a,this.preprocessor.getError(t,n))}getCurrentLocation(t){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-t,startOffset:this.preprocessor.offset-t,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=!0;this.active&&!this.paused;){this.consumedAfterSnapshot=0;const t=this._consume();this._ensureHibernation()||this._callState(t)}this.inLoop=!1}}pause(){this.paused=!0}resume(t){if(!this.paused)throw new Error("Parser was already resumed");this.paused=!1,!this.inLoop&&(this._runParsingLoop(),this.paused||t?.())}write(t,n,a){this.active=!0,this.preprocessor.write(t,n),this._runParsingLoop(),this.paused||a?.()}insertHtmlAtCurrentPos(t){this.active=!0,this.preprocessor.insertHtmlAtCurrentPos(t),this._runParsingLoop()}_ensureHibernation(){return this.preprocessor.endOfChunkHit?(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=!1,!0):!1}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(t){this.consumedAfterSnapshot+=t;for(let n=0;n<t;n++)this.preprocessor.advance()}_consumeSequenceIfMatch(t,n){return this.preprocessor.startsWith(t,n)?(this._advanceBy(t.length-1),!0):!1}_createStartTagToken(){this.currentToken={type:Ue.START_TAG,tagName:"",tagID:r.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:Ue.END_TAG,tagName:"",tagID:r.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(2)}}_createCommentToken(t){this.currentToken={type:Ue.COMMENT,data:"",location:this.getCurrentLocation(t)}}_createDoctypeToken(t){this.currentToken={type:Ue.DOCTYPE,name:t,forceQuirks:!1,publicId:null,systemId:null,location:this.currentLocation}}_createCharacterToken(t,n){this.currentCharacterToken={type:t,chars:n,location:this.currentLocation}}_createAttr(t){this.currentAttr={name:t,value:""},this.currentLocation=this.getCurrentLocation(0)}_leaveAttrName(){var t,n;const a=this.currentToken;if(dl(a,this.currentAttr.name)===null){if(a.attrs.push(this.currentAttr),a.location&&this.currentLocation){const i=(t=(n=a.location).attrs)!==null&&t!==void 0?t:n.attrs=Object.create(null);i[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue()}}else this._err(z.duplicateAttribute)}_leaveAttrValue(){this.currentLocation&&(this.currentLocation.endLine=this.preprocessor.line,this.currentLocation.endCol=this.preprocessor.col,this.currentLocation.endOffset=this.preprocessor.offset)}prepareToken(t){this._emitCurrentCharacterToken(t.location),this.currentToken=null,t.location&&(t.location.endLine=this.preprocessor.line,t.location.endCol=this.preprocessor.col+1,t.location.endOffset=this.preprocessor.offset+1),this.currentLocation=this.getCurrentLocation(-1)}emitCurrentTagToken(){const t=this.currentToken;this.prepareToken(t),t.tagID=xs(t.tagName),t.type===Ue.START_TAG?(this.lastStartTagName=t.tagName,this.handler.onStartTag(t)):(t.attrs.length>0&&this._err(z.endTagWithAttributes),t.selfClosing&&this._err(z.endTagWithTrailingSolidus),this.handler.onEndTag(t)),this.preprocessor.dropParsedChunk()}emitCurrentComment(t){this.prepareToken(t),this.handler.onComment(t),this.preprocessor.dropParsedChunk()}emitCurrentDoctype(t){this.prepareToken(t),this.handler.onDoctype(t),this.preprocessor.dropParsedChunk()}_emitCurrentCharacterToken(t){if(this.currentCharacterToken){switch(t&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=t.startLine,this.currentCharacterToken.location.endCol=t.startCol,this.currentCharacterToken.location.endOffset=t.startOffset),this.currentCharacterToken.type){case Ue.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case Ue.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case Ue.WHITESPACE_CHARACTER:{this.handler.onWhitespaceCharacter(this.currentCharacterToken);break}}this.currentCharacterToken=null}}_emitEOFToken(){const t=this.getCurrentLocation(0);t&&(t.endLine=t.startLine,t.endCol=t.startCol,t.endOffset=t.startOffset),this._emitCurrentCharacterToken(t),this.handler.onEof({type:Ue.EOF,location:t}),this.active=!1}_appendCharToCurrentCharacterToken(t,n){if(this.currentCharacterToken)if(this.currentCharacterToken.type===t){this.currentCharacterToken.chars+=n;return}else this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk();this._createCharacterToken(t,n)}_emitCodePoint(t){const n=pl(t)?Ue.WHITESPACE_CHARACTER:t===g.NULL?Ue.NULL_CHARACTER:Ue.CHARACTER;this._appendCharToCurrentCharacterToken(n,String.fromCodePoint(t))}_emitChars(t){this._appendCharToCurrentCharacterToken(Ue.CHARACTER,t)}_startCharacterReference(){this.returnState=this.state,this.state=E.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?Mt.Attribute:Mt.Legacy)}_isCharacterReferenceInAttribute(){return this.returnState===E.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===E.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===E.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t)}_callState(t){switch(this.state){case E.DATA:{this._stateData(t);break}case E.RCDATA:{this._stateRcdata(t);break}case E.RAWTEXT:{this._stateRawtext(t);break}case E.SCRIPT_DATA:{this._stateScriptData(t);break}case E.PLAINTEXT:{this._statePlaintext(t);break}case E.TAG_OPEN:{this._stateTagOpen(t);break}case E.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case E.TAG_NAME:{this._stateTagName(t);break}case E.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case E.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case E.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case E.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case E.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case E.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case E.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case E.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case E.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case E.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case E.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case E.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case E.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case E.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case E.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case E.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case E.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case E.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case E.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case E.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case E.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case E.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case E.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case E.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case E.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case E.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case E.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case E.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case E.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case E.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case E.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case E.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case E.BOGUS_COMMENT:{this._stateBogusComment(t);break}case E.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case E.COMMENT_START:{this._stateCommentStart(t);break}case E.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case E.COMMENT:{this._stateComment(t);break}case E.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case E.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case E.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case E.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case E.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case E.COMMENT_END:{this._stateCommentEnd(t);break}case E.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case E.DOCTYPE:{this._stateDoctype(t);break}case E.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case E.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case E.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case E.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case E.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case E.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case E.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case E.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case E.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case E.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case E.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case E.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case E.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case E.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case E.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case E.CDATA_SECTION:{this._stateCdataSection(t);break}case E.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case E.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case E.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case E.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case g.LESS_THAN_SIGN:{this.state=E.TAG_OPEN;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.NULL:{this._err(z.unexpectedNullCharacter),this._emitCodePoint(t);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRcdata(t){switch(t){case g.AMPERSAND:{this._startCharacterReference();break}case g.LESS_THAN_SIGN:{this.state=E.RCDATA_LESS_THAN_SIGN;break}case g.NULL:{this._err(z.unexpectedNullCharacter),this._emitChars(et);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRawtext(t){switch(t){case g.LESS_THAN_SIGN:{this.state=E.RAWTEXT_LESS_THAN_SIGN;break}case g.NULL:{this._err(z.unexpectedNullCharacter),this._emitChars(et);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptData(t){switch(t){case g.LESS_THAN_SIGN:{this.state=E.SCRIPT_DATA_LESS_THAN_SIGN;break}case g.NULL:{this._err(z.unexpectedNullCharacter),this._emitChars(et);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_statePlaintext(t){switch(t){case g.NULL:{this._err(z.unexpectedNullCharacter),this._emitChars(et);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateTagOpen(t){if(Wt(t))this._createStartTagToken(),this.state=E.TAG_NAME,this._stateTagName(t);else switch(t){case g.EXCLAMATION_MARK:{this.state=E.MARKUP_DECLARATION_OPEN;break}case g.SOLIDUS:{this.state=E.END_TAG_OPEN;break}case g.QUESTION_MARK:{this._err(z.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=E.BOGUS_COMMENT,this._stateBogusComment(t);break}case g.EOF:{this._err(z.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(z.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=E.DATA,this._stateData(t)}}_stateEndTagOpen(t){if(Wt(t))this._createEndTagToken(),this.state=E.TAG_NAME,this._stateTagName(t);else switch(t){case g.GREATER_THAN_SIGN:{this._err(z.missingEndTagName),this.state=E.DATA;break}case g.EOF:{this._err(z.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(z.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=E.BOGUS_COMMENT,this._stateBogusComment(t)}}_stateTagName(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=E.BEFORE_ATTRIBUTE_NAME;break}case g.SOLIDUS:{this.state=E.SELF_CLOSING_START_TAG;break}case g.GREATER_THAN_SIGN:{this.state=E.DATA,this.emitCurrentTagToken();break}case g.NULL:{this._err(z.unexpectedNullCharacter),n.tagName+=et;break}case g.EOF:{this._err(z.eofInTag),this._emitEOFToken();break}default:n.tagName+=String.fromCodePoint(Ls(t)?on(t):t)}}_stateRcdataLessThanSign(t){t===g.SOLIDUS?this.state=E.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=E.RCDATA,this._stateRcdata(t))}_stateRcdataEndTagOpen(t){Wt(t)?(this.state=E.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=E.RCDATA,this._stateRcdata(t))}handleSpecialEndTag(t){if(!this.preprocessor.startsWith(this.lastStartTagName,!1))return!this._ensureHibernation();this._createEndTagToken();const n=this.currentToken;switch(n.tagName=this.lastStartTagName,this.preprocessor.peek(this.lastStartTagName.length)){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=E.BEFORE_ATTRIBUTE_NAME,!1;case g.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=E.SELF_CLOSING_START_TAG,!1;case g.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=E.DATA,!1;default:return!this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=E.RCDATA,this._stateRcdata(t))}_stateRawtextLessThanSign(t){t===g.SOLIDUS?this.state=E.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=E.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagOpen(t){Wt(t)?(this.state=E.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=E.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=E.RAWTEXT,this._stateRawtext(t))}_stateScriptDataLessThanSign(t){switch(t){case g.SOLIDUS:{this.state=E.SCRIPT_DATA_END_TAG_OPEN;break}case g.EXCLAMATION_MARK:{this.state=E.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=E.SCRIPT_DATA,this._stateScriptData(t)}}_stateScriptDataEndTagOpen(t){Wt(t)?(this.state=E.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=E.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=E.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStart(t){t===g.HYPHEN_MINUS?(this.state=E.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=E.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStartDash(t){t===g.HYPHEN_MINUS?(this.state=E.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=E.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscaped(t){switch(t){case g.HYPHEN_MINUS:{this.state=E.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=E.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case g.NULL:{this._err(z.unexpectedNullCharacter),this._emitChars(et);break}case g.EOF:{this._err(z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataEscapedDash(t){switch(t){case g.HYPHEN_MINUS:{this.state=E.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=E.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case g.NULL:{this._err(z.unexpectedNullCharacter),this.state=E.SCRIPT_DATA_ESCAPED,this._emitChars(et);break}case g.EOF:{this._err(z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=E.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedDashDash(t){switch(t){case g.HYPHEN_MINUS:{this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=E.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case g.GREATER_THAN_SIGN:{this.state=E.SCRIPT_DATA,this._emitChars(">");break}case g.NULL:{this._err(z.unexpectedNullCharacter),this.state=E.SCRIPT_DATA_ESCAPED,this._emitChars(et);break}case g.EOF:{this._err(z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=E.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedLessThanSign(t){t===g.SOLIDUS?this.state=E.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:Wt(t)?(this._emitChars("<"),this.state=E.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=E.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagOpen(t){Wt(t)?(this.state=E.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=E.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=E.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith(ht.SCRIPT,!1)&&Tr(this.preprocessor.peek(ht.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<ht.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED}else this._ensureHibernation()||(this.state=E.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscaped(t){switch(t){case g.HYPHEN_MINUS:{this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case g.NULL:{this._err(z.unexpectedNullCharacter),this._emitChars(et);break}case g.EOF:{this._err(z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDash(t){switch(t){case g.HYPHEN_MINUS:{this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case g.NULL:{this._err(z.unexpectedNullCharacter),this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(et);break}case g.EOF:{this._err(z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case g.HYPHEN_MINUS:{this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case g.GREATER_THAN_SIGN:{this.state=E.SCRIPT_DATA,this._emitChars(">");break}case g.NULL:{this._err(z.unexpectedNullCharacter),this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(et);break}case g.EOF:{this._err(z.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedLessThanSign(t){t===g.SOLIDUS?(this.state=E.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(ht.SCRIPT,!1)&&Tr(this.preprocessor.peek(ht.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<ht.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=E.SCRIPT_DATA_ESCAPED}else this._ensureHibernation()||(this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateBeforeAttributeName(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.SOLIDUS:case g.GREATER_THAN_SIGN:case g.EOF:{this.state=E.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case g.EQUALS_SIGN:{this._err(z.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=E.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=E.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateAttributeName(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:case g.SOLIDUS:case g.GREATER_THAN_SIGN:case g.EOF:{this._leaveAttrName(),this.state=E.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case g.EQUALS_SIGN:{this._leaveAttrName(),this.state=E.BEFORE_ATTRIBUTE_VALUE;break}case g.QUOTATION_MARK:case g.APOSTROPHE:case g.LESS_THAN_SIGN:{this._err(z.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case g.NULL:{this._err(z.unexpectedNullCharacter),this.currentAttr.name+=et;break}default:this.currentAttr.name+=String.fromCodePoint(Ls(t)?on(t):t)}}_stateAfterAttributeName(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.SOLIDUS:{this.state=E.SELF_CLOSING_START_TAG;break}case g.EQUALS_SIGN:{this.state=E.BEFORE_ATTRIBUTE_VALUE;break}case g.GREATER_THAN_SIGN:{this.state=E.DATA,this.emitCurrentTagToken();break}case g.EOF:{this._err(z.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=E.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateBeforeAttributeValue(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.QUOTATION_MARK:{this.state=E.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this.state=E.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(z.missingAttributeValue),this.state=E.DATA,this.emitCurrentTagToken();break}default:this.state=E.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t)}}_stateAttributeValueDoubleQuoted(t){switch(t){case g.QUOTATION_MARK:{this.state=E.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.NULL:{this._err(z.unexpectedNullCharacter),this.currentAttr.value+=et;break}case g.EOF:{this._err(z.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueSingleQuoted(t){switch(t){case g.APOSTROPHE:{this.state=E.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.NULL:{this._err(z.unexpectedNullCharacter),this.currentAttr.value+=et;break}case g.EOF:{this._err(z.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueUnquoted(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this._leaveAttrValue(),this.state=E.BEFORE_ATTRIBUTE_NAME;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=E.DATA,this.emitCurrentTagToken();break}case g.NULL:{this._err(z.unexpectedNullCharacter),this.currentAttr.value+=et;break}case g.QUOTATION_MARK:case g.APOSTROPHE:case g.LESS_THAN_SIGN:case g.EQUALS_SIGN:case g.GRAVE_ACCENT:{this._err(z.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case g.EOF:{this._err(z.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAfterAttributeValueQuoted(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this._leaveAttrValue(),this.state=E.BEFORE_ATTRIBUTE_NAME;break}case g.SOLIDUS:{this._leaveAttrValue(),this.state=E.SELF_CLOSING_START_TAG;break}case g.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=E.DATA,this.emitCurrentTagToken();break}case g.EOF:{this._err(z.eofInTag),this._emitEOFToken();break}default:this._err(z.missingWhitespaceBetweenAttributes),this.state=E.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateSelfClosingStartTag(t){switch(t){case g.GREATER_THAN_SIGN:{const n=this.currentToken;n.selfClosing=!0,this.state=E.DATA,this.emitCurrentTagToken();break}case g.EOF:{this._err(z.eofInTag),this._emitEOFToken();break}default:this._err(z.unexpectedSolidusInTag),this.state=E.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateBogusComment(t){const n=this.currentToken;switch(t){case g.GREATER_THAN_SIGN:{this.state=E.DATA,this.emitCurrentComment(n);break}case g.EOF:{this.emitCurrentComment(n),this._emitEOFToken();break}case g.NULL:{this._err(z.unexpectedNullCharacter),n.data+=et;break}default:n.data+=String.fromCodePoint(t)}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(ht.DASH_DASH,!0)?(this._createCommentToken(ht.DASH_DASH.length+1),this.state=E.COMMENT_START):this._consumeSequenceIfMatch(ht.DOCTYPE,!1)?(this.currentLocation=this.getCurrentLocation(ht.DOCTYPE.length+1),this.state=E.DOCTYPE):this._consumeSequenceIfMatch(ht.CDATA_START,!0)?this.inForeignNode?this.state=E.CDATA_SECTION:(this._err(z.cdataInHtmlContent),this._createCommentToken(ht.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=E.BOGUS_COMMENT):this._ensureHibernation()||(this._err(z.incorrectlyOpenedComment),this._createCommentToken(2),this.state=E.BOGUS_COMMENT,this._stateBogusComment(t))}_stateCommentStart(t){switch(t){case g.HYPHEN_MINUS:{this.state=E.COMMENT_START_DASH;break}case g.GREATER_THAN_SIGN:{this._err(z.abruptClosingOfEmptyComment),this.state=E.DATA;const n=this.currentToken;this.emitCurrentComment(n);break}default:this.state=E.COMMENT,this._stateComment(t)}}_stateCommentStartDash(t){const n=this.currentToken;switch(t){case g.HYPHEN_MINUS:{this.state=E.COMMENT_END;break}case g.GREATER_THAN_SIGN:{this._err(z.abruptClosingOfEmptyComment),this.state=E.DATA,this.emitCurrentComment(n);break}case g.EOF:{this._err(z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=E.COMMENT,this._stateComment(t)}}_stateComment(t){const n=this.currentToken;switch(t){case g.HYPHEN_MINUS:{this.state=E.COMMENT_END_DASH;break}case g.LESS_THAN_SIGN:{n.data+="<",this.state=E.COMMENT_LESS_THAN_SIGN;break}case g.NULL:{this._err(z.unexpectedNullCharacter),n.data+=et;break}case g.EOF:{this._err(z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+=String.fromCodePoint(t)}}_stateCommentLessThanSign(t){const n=this.currentToken;switch(t){case g.EXCLAMATION_MARK:{n.data+="!",this.state=E.COMMENT_LESS_THAN_SIGN_BANG;break}case g.LESS_THAN_SIGN:{n.data+="<";break}default:this.state=E.COMMENT,this._stateComment(t)}}_stateCommentLessThanSignBang(t){t===g.HYPHEN_MINUS?this.state=E.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=E.COMMENT,this._stateComment(t))}_stateCommentLessThanSignBangDash(t){t===g.HYPHEN_MINUS?this.state=E.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=E.COMMENT_END_DASH,this._stateCommentEndDash(t))}_stateCommentLessThanSignBangDashDash(t){t!==g.GREATER_THAN_SIGN&&t!==g.EOF&&this._err(z.nestedComment),this.state=E.COMMENT_END,this._stateCommentEnd(t)}_stateCommentEndDash(t){const n=this.currentToken;switch(t){case g.HYPHEN_MINUS:{this.state=E.COMMENT_END;break}case g.EOF:{this._err(z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=E.COMMENT,this._stateComment(t)}}_stateCommentEnd(t){const n=this.currentToken;switch(t){case g.GREATER_THAN_SIGN:{this.state=E.DATA,this.emitCurrentComment(n);break}case g.EXCLAMATION_MARK:{this.state=E.COMMENT_END_BANG;break}case g.HYPHEN_MINUS:{n.data+="-";break}case g.EOF:{this._err(z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--",this.state=E.COMMENT,this._stateComment(t)}}_stateCommentEndBang(t){const n=this.currentToken;switch(t){case g.HYPHEN_MINUS:{n.data+="--!",this.state=E.COMMENT_END_DASH;break}case g.GREATER_THAN_SIGN:{this._err(z.incorrectlyClosedComment),this.state=E.DATA,this.emitCurrentComment(n);break}case g.EOF:{this._err(z.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--!",this.state=E.COMMENT,this._stateComment(t)}}_stateDoctype(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=E.BEFORE_DOCTYPE_NAME;break}case g.GREATER_THAN_SIGN:{this.state=E.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case g.EOF:{this._err(z.eofInDoctype),this._createDoctypeToken(null);const n=this.currentToken;n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(z.missingWhitespaceBeforeDoctypeName),this.state=E.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t)}}_stateBeforeDoctypeName(t){if(Ls(t))this._createDoctypeToken(String.fromCharCode(on(t))),this.state=E.DOCTYPE_NAME;else switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.NULL:{this._err(z.unexpectedNullCharacter),this._createDoctypeToken(et),this.state=E.DOCTYPE_NAME;break}case g.GREATER_THAN_SIGN:{this._err(z.missingDoctypeName),this._createDoctypeToken(null);const n=this.currentToken;n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.EOF:{this._err(z.eofInDoctype),this._createDoctypeToken(null);const n=this.currentToken;n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(t)),this.state=E.DOCTYPE_NAME}}_stateDoctypeName(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=E.AFTER_DOCTYPE_NAME;break}case g.GREATER_THAN_SIGN:{this.state=E.DATA,this.emitCurrentDoctype(n);break}case g.NULL:{this._err(z.unexpectedNullCharacter),n.name+=et;break}case g.EOF:{this._err(z.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.name+=String.fromCodePoint(Ls(t)?on(t):t)}}_stateAfterDoctypeName(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.GREATER_THAN_SIGN:{this.state=E.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(z.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(ht.PUBLIC,!1)?this.state=E.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(ht.SYSTEM,!1)?this.state=E.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(z.invalidCharacterSequenceAfterDoctypeName),n.forceQuirks=!0,this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t))}}_stateAfterDoctypePublicKeyword(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=E.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case g.QUOTATION_MARK:{this._err(z.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=E.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err(z.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=E.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(z.missingDoctypePublicIdentifier),n.forceQuirks=!0,this.state=E.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(z.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(z.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=!0,this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypePublicIdentifier(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.QUOTATION_MARK:{n.publicId="",this.state=E.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{n.publicId="",this.state=E.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(z.missingDoctypePublicIdentifier),n.forceQuirks=!0,this.state=E.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(z.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(z.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=!0,this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypePublicIdentifierDoubleQuoted(t){const n=this.currentToken;switch(t){case g.QUOTATION_MARK:{this.state=E.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case g.NULL:{this._err(z.unexpectedNullCharacter),n.publicId+=et;break}case g.GREATER_THAN_SIGN:{this._err(z.abruptDoctypePublicIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.EOF:{this._err(z.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.publicId+=String.fromCodePoint(t)}}_stateDoctypePublicIdentifierSingleQuoted(t){const n=this.currentToken;switch(t){case g.APOSTROPHE:{this.state=E.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case g.NULL:{this._err(z.unexpectedNullCharacter),n.publicId+=et;break}case g.GREATER_THAN_SIGN:{this._err(z.abruptDoctypePublicIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.EOF:{this._err(z.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.publicId+=String.fromCodePoint(t)}}_stateAfterDoctypePublicIdentifier(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=E.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case g.GREATER_THAN_SIGN:{this.state=E.DATA,this.emitCurrentDoctype(n);break}case g.QUOTATION_MARK:{this._err(z.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err(z.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.EOF:{this._err(z.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(z.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.QUOTATION_MARK:{n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.EOF:{this._err(z.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(z.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateAfterDoctypeSystemKeyword(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=E.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case g.QUOTATION_MARK:{this._err(z.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err(z.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(z.missingDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=E.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(z.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(z.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypeSystemIdentifier(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.QUOTATION_MARK:{n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(z.missingDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=E.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(z.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(z.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypeSystemIdentifierDoubleQuoted(t){const n=this.currentToken;switch(t){case g.QUOTATION_MARK:{this.state=E.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case g.NULL:{this._err(z.unexpectedNullCharacter),n.systemId+=et;break}case g.GREATER_THAN_SIGN:{this._err(z.abruptDoctypeSystemIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.EOF:{this._err(z.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.systemId+=String.fromCodePoint(t)}}_stateDoctypeSystemIdentifierSingleQuoted(t){const n=this.currentToken;switch(t){case g.APOSTROPHE:{this.state=E.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case g.NULL:{this._err(z.unexpectedNullCharacter),n.systemId+=et;break}case g.GREATER_THAN_SIGN:{this._err(z.abruptDoctypeSystemIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.EOF:{this._err(z.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.systemId+=String.fromCodePoint(t)}}_stateAfterDoctypeSystemIdentifier(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.EOF:{this._err(z.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(z.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBogusDoctype(t){const n=this.currentToken;switch(t){case g.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.NULL:{this._err(z.unexpectedNullCharacter);break}case g.EOF:{this.emitCurrentDoctype(n),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case g.RIGHT_SQUARE_BRACKET:{this.state=E.CDATA_SECTION_BRACKET;break}case g.EOF:{this._err(z.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateCdataSectionBracket(t){t===g.RIGHT_SQUARE_BRACKET?this.state=E.CDATA_SECTION_END:(this._emitChars("]"),this.state=E.CDATA_SECTION,this._stateCdataSection(t))}_stateCdataSectionEnd(t){switch(t){case g.GREATER_THAN_SIGN:{this.state=E.DATA;break}case g.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=E.CDATA_SECTION,this._stateCdataSection(t)}}_stateCharacterReference(){let t=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(t<0)if(this.preprocessor.lastChunkWritten)t=this.entityDecoder.end();else{this.active=!1,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,this.preprocessor.endOfChunkHit=!0;return}t===0?(this.preprocessor.pos=this.entityStartPos,this._flushCodePointConsumedAsCharacterReference(g.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&Er(this.preprocessor.peek(1))?E.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState}_stateAmbiguousAmpersand(t){Er(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===g.SEMICOLON&&this._err(z.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t))}}const ml=new Set([r.DD,r.DT,r.LI,r.OPTGROUP,r.OPTION,r.P,r.RB,r.RP,r.RT,r.RTC]),xr=new Set([...ml,r.CAPTION,r.COLGROUP,r.TBODY,r.TD,r.TFOOT,r.TH,r.THEAD,r.TR]),Mn=new Set([r.APPLET,r.CAPTION,r.HTML,r.MARQUEE,r.OBJECT,r.TABLE,r.TD,r.TEMPLATE,r.TH]),ym=new Set([...Mn,r.OL,r.UL]),km=new Set([...Mn,r.BUTTON]),yr=new Set([r.ANNOTATION_XML,r.MI,r.MN,r.MO,r.MS,r.MTEXT]),kr=new Set([r.DESC,r.FOREIGN_OBJECT,r.TITLE]),Nm=new Set([r.TR,r.TEMPLATE,r.HTML]),vm=new Set([r.TBODY,r.TFOOT,r.THEAD,r.TEMPLATE,r.HTML]),Cm=new Set([r.TABLE,r.TEMPLATE,r.HTML]),wm=new Set([r.TD,r.TH]);class Sm{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,n,a){this.treeAdapter=n,this.handler=a,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=r.UNKNOWN,this.current=t}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===r.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===ne.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop]}push(t,n){this.stackTop++,this.items[this.stackTop]=t,this.current=t,this.tagIDs[this.stackTop]=n,this.currentTagId=n,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(t,n,!0)}pop(){const t=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,!0)}replace(t,n){const a=this._indexOf(t);this.items[a]=n,a===this.stackTop&&(this.current=n)}insertAfter(t,n,a){const i=this._indexOf(t)+1;this.items.splice(i,0,n),this.tagIDs.splice(i,0,a),this.stackTop++,i===this.stackTop&&this._updateCurrentElement(),this.current&&this.currentTagId!==void 0&&this.handler.onItemPush(this.current,this.currentTagId,i===this.stackTop)}popUntilTagNamePopped(t){let n=this.stackTop+1;do n=this.tagIDs.lastIndexOf(t,n-1);while(n>0&&this.treeAdapter.getNamespaceURI(this.items[n])!==ne.HTML);this.shortenToLength(Math.max(n,0))}shortenToLength(t){for(;this.stackTop>=t;){const n=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(n,this.stackTop<t)}}popUntilElementPopped(t){const n=this._indexOf(t);this.shortenToLength(Math.max(n,0))}popUntilPopped(t,n){const a=this._indexOfTagNames(t,n);this.shortenToLength(Math.max(a,0))}popUntilNumberedHeaderPopped(){this.popUntilPopped(qa,ne.HTML)}popUntilTableCellPopped(){this.popUntilPopped(wm,ne.HTML)}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1)}_indexOfTagNames(t,n){for(let a=this.stackTop;a>=0;a--)if(t.has(this.tagIDs[a])&&this.treeAdapter.getNamespaceURI(this.items[a])===n)return a;return-1}clearBackTo(t,n){const a=this._indexOfTagNames(t,n);this.shortenToLength(a+1)}clearBackToTableContext(){this.clearBackTo(Cm,ne.HTML)}clearBackToTableBodyContext(){this.clearBackTo(vm,ne.HTML)}clearBackToTableRowContext(){this.clearBackTo(Nm,ne.HTML)}remove(t){const n=this._indexOf(t);n>=0&&(n===this.stackTop?this.pop():(this.items.splice(n,1),this.tagIDs.splice(n,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,!1)))}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===r.BODY?this.items[1]:null}contains(t){return this._indexOf(t)>-1}getCommonAncestor(t){const n=this._indexOf(t)-1;return n>=0?this.items[n]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===r.HTML}hasInDynamicScope(t,n){for(let a=this.stackTop;a>=0;a--){const i=this.tagIDs[a];switch(this.treeAdapter.getNamespaceURI(this.items[a])){case ne.HTML:{if(i===t)return!0;if(n.has(i))return!1;break}case ne.SVG:{if(kr.has(i))return!1;break}case ne.MATHML:{if(yr.has(i))return!1;break}}}return!0}hasInScope(t){return this.hasInDynamicScope(t,Mn)}hasInListItemScope(t){return this.hasInDynamicScope(t,ym)}hasInButtonScope(t){return this.hasInDynamicScope(t,km)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){const n=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case ne.HTML:{if(qa.has(n))return!0;if(Mn.has(n))return!1;break}case ne.SVG:{if(kr.has(n))return!1;break}case ne.MATHML:{if(yr.has(n))return!1;break}}}return!0}hasInTableScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===ne.HTML)switch(this.tagIDs[n]){case t:return!0;case r.TABLE:case r.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===ne.HTML)switch(this.tagIDs[t]){case r.TBODY:case r.THEAD:case r.TFOOT:return!0;case r.TABLE:case r.HTML:return!1}return!0}hasInSelectScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===ne.HTML)switch(this.tagIDs[n]){case t:return!0;case r.OPTION:case r.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&ml.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&xr.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&xr.has(this.currentTagId);)this.pop()}}const Ea=3;var jt;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element"})(jt||(jt={}));const Nr={type:jt.Marker};class _m{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(t,n){const a=[],i=n.length,o=this.treeAdapter.getTagName(t),l=this.treeAdapter.getNamespaceURI(t);for(let u=0;u<this.entries.length;u++){const p=this.entries[u];if(p.type===jt.Marker)break;const{element:h}=p;if(this.treeAdapter.getTagName(h)===o&&this.treeAdapter.getNamespaceURI(h)===l){const b=this.treeAdapter.getAttrList(h);b.length===i&&a.push({idx:u,attrs:b})}}return a}_ensureNoahArkCondition(t){if(this.entries.length<Ea)return;const n=this.treeAdapter.getAttrList(t),a=this._getNoahArkConditionCandidates(t,n);if(a.length<Ea)return;const i=new Map(n.map(l=>[l.name,l.value]));let o=0;for(let l=0;l<a.length;l++){const u=a[l];u.attrs.every(p=>i.get(p.name)===p.value)&&(o+=1,o>=Ea&&this.entries.splice(u.idx,1))}}insertMarker(){this.entries.unshift(Nr)}pushElement(t,n){this._ensureNoahArkCondition(t),this.entries.unshift({type:jt.Element,element:t,token:n})}insertElementAfterBookmark(t,n){const a=this.entries.indexOf(this.bookmark);this.entries.splice(a,0,{type:jt.Element,element:t,token:n})}removeEntry(t){const n=this.entries.indexOf(t);n!==-1&&this.entries.splice(n,1)}clearToLastMarker(){const t=this.entries.indexOf(Nr);t===-1?this.entries.length=0:this.entries.splice(0,t+1)}getElementEntryInScopeWithTagName(t){const n=this.entries.find(a=>a.type===jt.Marker||this.treeAdapter.getTagName(a.element)===t);return n&&n.type===jt.Element?n:null}getElementEntry(t){return this.entries.find(n=>n.type===jt.Element&&n.element===t)}}const Kt={createDocument(){return{nodeName:"#document",mode:yt.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return{nodeName:"#document-fragment",childNodes:[]}},createElement(e,t,n){return{nodeName:e,tagName:e,attrs:n,namespaceURI:t,childNodes:[],parentNode:null}},createCommentNode(e){return{nodeName:"#comment",data:e,parentNode:null}},createTextNode(e){return{nodeName:"#text",value:e,parentNode:null}},appendChild(e,t){e.childNodes.push(t),t.parentNode=e},insertBefore(e,t,n){const a=e.childNodes.indexOf(n);e.childNodes.splice(a,0,t),t.parentNode=e},setTemplateContent(e,t){e.content=t},getTemplateContent(e){return e.content},setDocumentType(e,t,n,a){const i=e.childNodes.find(o=>o.nodeName==="#documentType");if(i)i.name=t,i.publicId=n,i.systemId=a;else{const o={nodeName:"#documentType",name:t,publicId:n,systemId:a,parentNode:null};Kt.appendChild(e,o)}},setDocumentMode(e,t){e.mode=t},getDocumentMode(e){return e.mode},detachNode(e){if(e.parentNode){const t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null}},insertText(e,t){if(e.childNodes.length>0){const n=e.childNodes[e.childNodes.length-1];if(Kt.isTextNode(n)){n.value+=t;return}}Kt.appendChild(e,Kt.createTextNode(t))},insertTextBefore(e,t,n){const a=e.childNodes[e.childNodes.indexOf(n)-1];a&&Kt.isTextNode(a)?a.value+=t:Kt.insertBefore(e,Kt.createTextNode(t),n)},adoptAttributes(e,t){const n=new Set(e.attrs.map(a=>a.name));for(let a=0;a<t.length;a++)n.has(t[a].name)||e.attrs.push(t[a])},getFirstChild(e){return e.childNodes[0]},getChildNodes(e){return e.childNodes},getParentNode(e){return e.parentNode},getAttrList(e){return e.attrs},getTagName(e){return e.tagName},getNamespaceURI(e){return e.namespaceURI},getTextNodeContent(e){return e.value},getCommentNodeContent(e){return e.data},getDocumentTypeNodeName(e){return e.name},getDocumentTypeNodePublicId(e){return e.publicId},getDocumentTypeNodeSystemId(e){return e.systemId},isTextNode(e){return e.nodeName==="#text"},isCommentNode(e){return e.nodeName==="#comment"},isDocumentTypeNode(e){return e.nodeName==="#documentType"},isElementNode(e){return Object.prototype.hasOwnProperty.call(e,"tagName")},setNodeSourceCodeLocation(e,t){e.sourceCodeLocation=t},getNodeSourceCodeLocation(e){return e.sourceCodeLocation},updateNodeSourceCodeLocation(e,t){e.sourceCodeLocation={...e.sourceCodeLocation,...t}}},hl="html",Am="about:legacy-compat",Im="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",fl=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"],jm=[...fl,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],Rm=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),gl=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],Lm=[...gl,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function vr(e,t){return t.some(n=>e.startsWith(n))}function Dm(e){return e.name===hl&&e.publicId===null&&(e.systemId===null||e.systemId===Am)}function Pm(e){if(e.name!==hl)return yt.QUIRKS;const{systemId:t}=e;if(t&&t.toLowerCase()===Im)return yt.QUIRKS;let{publicId:n}=e;if(n!==null){if(n=n.toLowerCase(),Rm.has(n))return yt.QUIRKS;let a=t===null?jm:fl;if(vr(n,a))return yt.QUIRKS;if(a=t===null?gl:Lm,vr(n,a))return yt.LIMITED_QUIRKS}return yt.NO_QUIRKS}const Cr={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},Om="definitionurl",Mm="definitionURL",Bm=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e])),Fm=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:ne.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:ne.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:ne.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:ne.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:ne.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:ne.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:ne.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:ne.XML}],["xml:space",{prefix:"xml",name:"space",namespace:ne.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:ne.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:ne.XMLNS}]]),Hm=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),Um=new Set([r.B,r.BIG,r.BLOCKQUOTE,r.BODY,r.BR,r.CENTER,r.CODE,r.DD,r.DIV,r.DL,r.DT,r.EM,r.EMBED,r.H1,r.H2,r.H3,r.H4,r.H5,r.H6,r.HEAD,r.HR,r.I,r.IMG,r.LI,r.LISTING,r.MENU,r.META,r.NOBR,r.OL,r.P,r.PRE,r.RUBY,r.S,r.SMALL,r.SPAN,r.STRONG,r.STRIKE,r.SUB,r.SUP,r.TABLE,r.TT,r.U,r.UL,r.VAR]);function $m(e){const t=e.tagID;return t===r.FONT&&e.attrs.some(({name:a})=>a===ns.COLOR||a===ns.SIZE||a===ns.FACE)||Um.has(t)}function bl(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===Om){e.attrs[t].name=Mm;break}}function El(e){for(let t=0;t<e.attrs.length;t++){const n=Bm.get(e.attrs[t].name);n!=null&&(e.attrs[t].name=n)}}function ci(e){for(let t=0;t<e.attrs.length;t++){const n=Fm.get(e.attrs[t].name);n&&(e.attrs[t].prefix=n.prefix,e.attrs[t].name=n.name,e.attrs[t].namespace=n.namespace)}}function qm(e){const t=Hm.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=xs(e.tagName))}function Wm(e,t){return t===ne.MATHML&&(e===r.MI||e===r.MO||e===r.MN||e===r.MS||e===r.MTEXT)}function Km(e,t,n){if(t===ne.MATHML&&e===r.ANNOTATION_XML){for(let a=0;a<n.length;a++)if(n[a].name===ns.ENCODING){const i=n[a].value.toLowerCase();return i===Cr.TEXT_HTML||i===Cr.APPLICATION_XML}}return t===ne.SVG&&(e===r.FOREIGN_OBJECT||e===r.DESC||e===r.TITLE)}function Ym(e,t,n,a){return(!a||a===ne.HTML)&&Km(e,t,n)||(!a||a===ne.MATHML)&&Wm(e,t)}const Gm="hidden",zm=8,Vm=3;var k;(function(e){e[e.INITIAL=0]="INITIAL",e[e.BEFORE_HTML=1]="BEFORE_HTML",e[e.BEFORE_HEAD=2]="BEFORE_HEAD",e[e.IN_HEAD=3]="IN_HEAD",e[e.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",e[e.AFTER_HEAD=5]="AFTER_HEAD",e[e.IN_BODY=6]="IN_BODY",e[e.TEXT=7]="TEXT",e[e.IN_TABLE=8]="IN_TABLE",e[e.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",e[e.IN_CAPTION=10]="IN_CAPTION",e[e.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",e[e.IN_TABLE_BODY=12]="IN_TABLE_BODY",e[e.IN_ROW=13]="IN_ROW",e[e.IN_CELL=14]="IN_CELL",e[e.IN_SELECT=15]="IN_SELECT",e[e.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",e[e.IN_TEMPLATE=17]="IN_TEMPLATE",e[e.AFTER_BODY=18]="AFTER_BODY",e[e.IN_FRAMESET=19]="IN_FRAMESET",e[e.AFTER_FRAMESET=20]="AFTER_FRAMESET",e[e.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",e[e.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET"})(k||(k={}));const Qm={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},Tl=new Set([r.TABLE,r.TBODY,r.TFOOT,r.THEAD,r.TR]),wr={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:Kt,onParseError:null};class Sr{constructor(t,n,a=null,i=null){this.fragmentContext=a,this.scriptHandler=i,this.currentToken=null,this.stopped=!1,this.insertionMode=k.INITIAL,this.originalInsertionMode=k.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=!1,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=!1,this.framesetOk=!0,this.skipNextNewLine=!1,this.fosterParentingEnabled=!1,this.options={...wr,...t},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=!0),this.document=n??this.treeAdapter.createDocument(),this.tokenizer=new xm(this.options,this),this.activeFormattingElements=new _m(this.treeAdapter),this.fragmentContextID=a?xs(this.treeAdapter.getTagName(a)):r.UNKNOWN,this._setContextModes(a??this.document,this.fragmentContextID),this.openElements=new Sm(this.document,this.treeAdapter,this)}static parse(t,n){const a=new this(n);return a.tokenizer.write(t,!0),a.document}static getFragmentParser(t,n){const a={...wr,...n};t??(t=a.treeAdapter.createElement(M.TEMPLATE,ne.HTML,[]));const i=a.treeAdapter.createElement("documentmock",ne.HTML,[]),o=new this(a,i,t);return o.fragmentContextID===r.TEMPLATE&&o.tmplInsertionModeStack.unshift(k.IN_TEMPLATE),o._initTokenizerForFragmentParsing(),o._insertFakeRootElement(),o._resetInsertionMode(),o._findFormInFragmentContext(),o}getFragment(){const t=this.treeAdapter.getFirstChild(this.document),n=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,n),n}_err(t,n,a){var i;if(!this.onParseError)return;const o=(i=t.location)!==null&&i!==void 0?i:Qm,l={code:n,startLine:o.startLine,startCol:o.startCol,startOffset:o.startOffset,endLine:a?o.startLine:o.endLine,endCol:a?o.startCol:o.endCol,endOffset:a?o.startOffset:o.endOffset};this.onParseError(l)}onItemPush(t,n,a){var i,o;(o=(i=this.treeAdapter).onItemPush)===null||o===void 0||o.call(i,t),a&&this.openElements.stackTop>0&&this._setContextModes(t,n)}onItemPop(t,n){var a,i;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(i=(a=this.treeAdapter).onItemPop)===null||i===void 0||i.call(a,t,this.openElements.current),n){let o,l;this.openElements.stackTop===0&&this.fragmentContext?(o=this.fragmentContext,l=this.fragmentContextID):{current:o,currentTagId:l}=this.openElements,this._setContextModes(o,l)}}_setContextModes(t,n){const a=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===ne.HTML;this.currentNotInHTML=!a,this.tokenizer.inForeignNode=!a&&t!==void 0&&n!==void 0&&!this._isIntegrationPoint(n,t)}_switchToTextParsing(t,n){this._insertElement(t,ne.HTML),this.tokenizer.state=n,this.originalInsertionMode=this.insertionMode,this.insertionMode=k.TEXT}switchToPlaintextParsing(){this.insertionMode=k.TEXT,this.originalInsertionMode=k.IN_BODY,this.tokenizer.state=st.PLAINTEXT}_getAdjustedCurrentElement(){return this.openElements.stackTop===0&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let t=this.fragmentContext;for(;t;){if(this.treeAdapter.getTagName(t)===M.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t)}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==ne.HTML))switch(this.fragmentContextID){case r.TITLE:case r.TEXTAREA:{this.tokenizer.state=st.RCDATA;break}case r.STYLE:case r.XMP:case r.IFRAME:case r.NOEMBED:case r.NOFRAMES:case r.NOSCRIPT:{this.tokenizer.state=st.RAWTEXT;break}case r.SCRIPT:{this.tokenizer.state=st.SCRIPT_DATA;break}case r.PLAINTEXT:{this.tokenizer.state=st.PLAINTEXT;break}}}_setDocumentType(t){const n=t.name||"",a=t.publicId||"",i=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,n,a,i),t.location){const l=this.treeAdapter.getChildNodes(this.document).find(u=>this.treeAdapter.isDocumentTypeNode(u));l&&this.treeAdapter.setNodeSourceCodeLocation(l,t.location)}}_attachElementToTree(t,n){if(this.options.sourceCodeLocationInfo){const a=n&&{...n,startTag:n};this.treeAdapter.setNodeSourceCodeLocation(t,a)}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else{const a=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(a??this.document,t)}}_appendElement(t,n){const a=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(a,t.location)}_insertElement(t,n){const a=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(a,t.location),this.openElements.push(a,t.tagID)}_insertFakeElement(t,n){const a=this.treeAdapter.createElement(t,ne.HTML,[]);this._attachElementToTree(a,null),this.openElements.push(a,n)}_insertTemplate(t){const n=this.treeAdapter.createElement(t.tagName,ne.HTML,t.attrs),a=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(n,a),this._attachElementToTree(n,t.location),this.openElements.push(n,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(a,null)}_insertFakeRootElement(){const t=this.treeAdapter.createElement(M.HTML,ne.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,r.HTML)}_appendCommentNode(t,n){const a=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(n,a),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(a,t.location)}_insertCharacters(t){let n,a;if(this._shouldFosterParentOnInsertion()?({parent:n,beforeElement:a}=this._findFosterParentingLocation(),a?this.treeAdapter.insertTextBefore(n,t.chars,a):this.treeAdapter.insertText(n,t.chars)):(n=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(n,t.chars)),!t.location)return;const i=this.treeAdapter.getChildNodes(n),o=a?i.lastIndexOf(a):i.length,l=i[o-1];if(this.treeAdapter.getNodeSourceCodeLocation(l)){const{endLine:p,endCol:h,endOffset:b}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(l,{endLine:p,endCol:h,endOffset:b})}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(l,t.location)}_adoptNodes(t,n){for(let a=this.treeAdapter.getFirstChild(t);a;a=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(a),this.treeAdapter.appendChild(n,a)}_setEndLocation(t,n){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&n.location){const a=n.location,i=this.treeAdapter.getTagName(t),o=n.type===Ue.END_TAG&&i===n.tagName?{endTag:{...a},endLine:a.endLine,endCol:a.endCol,endOffset:a.endOffset}:{endLine:a.startLine,endCol:a.startCol,endOffset:a.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,o)}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return!1;let n,a;return this.openElements.stackTop===0&&this.fragmentContext?(n=this.fragmentContext,a=this.fragmentContextID):{current:n,currentTagId:a}=this.openElements,t.tagID===r.SVG&&this.treeAdapter.getTagName(n)===M.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(n)===ne.MATHML?!1:this.tokenizer.inForeignNode||(t.tagID===r.MGLYPH||t.tagID===r.MALIGNMARK)&&a!==void 0&&!this._isIntegrationPoint(a,n,ne.HTML)}_processToken(t){switch(t.type){case Ue.CHARACTER:{this.onCharacter(t);break}case Ue.NULL_CHARACTER:{this.onNullCharacter(t);break}case Ue.COMMENT:{this.onComment(t);break}case Ue.DOCTYPE:{this.onDoctype(t);break}case Ue.START_TAG:{this._processStartTag(t);break}case Ue.END_TAG:{this.onEndTag(t);break}case Ue.EOF:{this.onEof(t);break}case Ue.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,n,a){const i=this.treeAdapter.getNamespaceURI(n),o=this.treeAdapter.getAttrList(n);return Ym(t,i,o,a)}_reconstructActiveFormattingElements(){const t=this.activeFormattingElements.entries.length;if(t){const n=this.activeFormattingElements.entries.findIndex(i=>i.type===jt.Marker||this.openElements.contains(i.element)),a=n===-1?t-1:n-1;for(let i=a;i>=0;i--){const o=this.activeFormattingElements.entries[i];this._insertElement(o.token,this.treeAdapter.getNamespaceURI(o.element)),o.element=this.openElements.current}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=k.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(r.P),this.openElements.popUntilTagNamePopped(r.P)}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case r.TR:{this.insertionMode=k.IN_ROW;return}case r.TBODY:case r.THEAD:case r.TFOOT:{this.insertionMode=k.IN_TABLE_BODY;return}case r.CAPTION:{this.insertionMode=k.IN_CAPTION;return}case r.COLGROUP:{this.insertionMode=k.IN_COLUMN_GROUP;return}case r.TABLE:{this.insertionMode=k.IN_TABLE;return}case r.BODY:{this.insertionMode=k.IN_BODY;return}case r.FRAMESET:{this.insertionMode=k.IN_FRAMESET;return}case r.SELECT:{this._resetInsertionModeForSelect(t);return}case r.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case r.HTML:{this.insertionMode=this.headElement?k.AFTER_HEAD:k.BEFORE_HEAD;return}case r.TD:case r.TH:{if(t>0){this.insertionMode=k.IN_CELL;return}break}case r.HEAD:{if(t>0){this.insertionMode=k.IN_HEAD;return}break}}this.insertionMode=k.IN_BODY}_resetInsertionModeForSelect(t){if(t>0)for(let n=t-1;n>0;n--){const a=this.openElements.tagIDs[n];if(a===r.TEMPLATE)break;if(a===r.TABLE){this.insertionMode=k.IN_SELECT_IN_TABLE;return}}this.insertionMode=k.IN_SELECT}_isElementCausesFosterParenting(t){return Tl.has(t)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&this.openElements.currentTagId!==void 0&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let t=this.openElements.stackTop;t>=0;t--){const n=this.openElements.items[t];switch(this.openElements.tagIDs[t]){case r.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(n)===ne.HTML)return{parent:this.treeAdapter.getTemplateContent(n),beforeElement:null};break}case r.TABLE:{const a=this.treeAdapter.getParentNode(n);return a?{parent:a,beforeElement:n}:{parent:this.openElements.items[t-1],beforeElement:null}}}}return{parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(t){const n=this._findFosterParentingLocation();n.beforeElement?this.treeAdapter.insertBefore(n.parent,t,n.beforeElement):this.treeAdapter.appendChild(n.parent,t)}_isSpecialElement(t,n){const a=this.treeAdapter.getNamespaceURI(t);return gm[a].has(n)}onCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){Sf(this,t);return}switch(this.insertionMode){case k.INITIAL:{ws(this,t);break}case k.BEFORE_HTML:{Ms(this,t);break}case k.BEFORE_HEAD:{Bs(this,t);break}case k.IN_HEAD:{Fs(this,t);break}case k.IN_HEAD_NO_SCRIPT:{Hs(this,t);break}case k.AFTER_HEAD:{Us(this,t);break}case k.IN_BODY:case k.IN_CAPTION:case k.IN_CELL:case k.IN_TEMPLATE:{yl(this,t);break}case k.TEXT:case k.IN_SELECT:case k.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case k.IN_TABLE:case k.IN_TABLE_BODY:case k.IN_ROW:{Ta(this,t);break}case k.IN_TABLE_TEXT:{Sl(this,t);break}case k.IN_COLUMN_GROUP:{Bn(this,t);break}case k.AFTER_BODY:{Fn(this,t);break}case k.AFTER_AFTER_BODY:{En(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){wf(this,t);return}switch(this.insertionMode){case k.INITIAL:{ws(this,t);break}case k.BEFORE_HTML:{Ms(this,t);break}case k.BEFORE_HEAD:{Bs(this,t);break}case k.IN_HEAD:{Fs(this,t);break}case k.IN_HEAD_NO_SCRIPT:{Hs(this,t);break}case k.AFTER_HEAD:{Us(this,t);break}case k.TEXT:{this._insertCharacters(t);break}case k.IN_TABLE:case k.IN_TABLE_BODY:case k.IN_ROW:{Ta(this,t);break}case k.IN_COLUMN_GROUP:{Bn(this,t);break}case k.AFTER_BODY:{Fn(this,t);break}case k.AFTER_AFTER_BODY:{En(this,t);break}}}onComment(t){if(this.skipNextNewLine=!1,this.currentNotInHTML){Wa(this,t);return}switch(this.insertionMode){case k.INITIAL:case k.BEFORE_HTML:case k.BEFORE_HEAD:case k.IN_HEAD:case k.IN_HEAD_NO_SCRIPT:case k.AFTER_HEAD:case k.IN_BODY:case k.IN_TABLE:case k.IN_CAPTION:case k.IN_COLUMN_GROUP:case k.IN_TABLE_BODY:case k.IN_ROW:case k.IN_CELL:case k.IN_SELECT:case k.IN_SELECT_IN_TABLE:case k.IN_TEMPLATE:case k.IN_FRAMESET:case k.AFTER_FRAMESET:{Wa(this,t);break}case k.IN_TABLE_TEXT:{Ss(this,t);break}case k.AFTER_BODY:{nh(this,t);break}case k.AFTER_AFTER_BODY:case k.AFTER_AFTER_FRAMESET:{ah(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=!1,this.insertionMode){case k.INITIAL:{ih(this,t);break}case k.BEFORE_HEAD:case k.IN_HEAD:case k.IN_HEAD_NO_SCRIPT:case k.AFTER_HEAD:{this._err(t,z.misplacedDoctype);break}case k.IN_TABLE_TEXT:{Ss(this,t);break}}}onStartTag(t){this.skipNextNewLine=!1,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,z.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?_f(this,t):this._startTagOutsideForeignContent(t)}_startTagOutsideForeignContent(t){switch(this.insertionMode){case k.INITIAL:{ws(this,t);break}case k.BEFORE_HTML:{rh(this,t);break}case k.BEFORE_HEAD:{lh(this,t);break}case k.IN_HEAD:{_t(this,t);break}case k.IN_HEAD_NO_SCRIPT:{dh(this,t);break}case k.AFTER_HEAD:{mh(this,t);break}case k.IN_BODY:{ct(this,t);break}case k.IN_TABLE:{bs(this,t);break}case k.IN_TABLE_TEXT:{Ss(this,t);break}case k.IN_CAPTION:{uf(this,t);break}case k.IN_COLUMN_GROUP:{pi(this,t);break}case k.IN_TABLE_BODY:{ta(this,t);break}case k.IN_ROW:{sa(this,t);break}case k.IN_CELL:{mf(this,t);break}case k.IN_SELECT:{Il(this,t);break}case k.IN_SELECT_IN_TABLE:{ff(this,t);break}case k.IN_TEMPLATE:{bf(this,t);break}case k.AFTER_BODY:{Tf(this,t);break}case k.IN_FRAMESET:{xf(this,t);break}case k.AFTER_FRAMESET:{kf(this,t);break}case k.AFTER_AFTER_BODY:{vf(this,t);break}case k.AFTER_AFTER_FRAMESET:{Cf(this,t);break}}}onEndTag(t){this.skipNextNewLine=!1,this.currentToken=t,this.currentNotInHTML?Af(this,t):this._endTagOutsideForeignContent(t)}_endTagOutsideForeignContent(t){switch(this.insertionMode){case k.INITIAL:{ws(this,t);break}case k.BEFORE_HTML:{oh(this,t);break}case k.BEFORE_HEAD:{ch(this,t);break}case k.IN_HEAD:{uh(this,t);break}case k.IN_HEAD_NO_SCRIPT:{ph(this,t);break}case k.AFTER_HEAD:{hh(this,t);break}case k.IN_BODY:{ea(this,t);break}case k.TEXT:{Zh(this,t);break}case k.IN_TABLE:{zs(this,t);break}case k.IN_TABLE_TEXT:{Ss(this,t);break}case k.IN_CAPTION:{df(this,t);break}case k.IN_COLUMN_GROUP:{pf(this,t);break}case k.IN_TABLE_BODY:{Ka(this,t);break}case k.IN_ROW:{Al(this,t);break}case k.IN_CELL:{hf(this,t);break}case k.IN_SELECT:{jl(this,t);break}case k.IN_SELECT_IN_TABLE:{gf(this,t);break}case k.IN_TEMPLATE:{Ef(this,t);break}case k.AFTER_BODY:{Ll(this,t);break}case k.IN_FRAMESET:{yf(this,t);break}case k.AFTER_FRAMESET:{Nf(this,t);break}case k.AFTER_AFTER_BODY:{En(this,t);break}}}onEof(t){switch(this.insertionMode){case k.INITIAL:{ws(this,t);break}case k.BEFORE_HTML:{Ms(this,t);break}case k.BEFORE_HEAD:{Bs(this,t);break}case k.IN_HEAD:{Fs(this,t);break}case k.IN_HEAD_NO_SCRIPT:{Hs(this,t);break}case k.AFTER_HEAD:{Us(this,t);break}case k.IN_BODY:case k.IN_TABLE:case k.IN_CAPTION:case k.IN_COLUMN_GROUP:case k.IN_TABLE_BODY:case k.IN_ROW:case k.IN_CELL:case k.IN_SELECT:case k.IN_SELECT_IN_TABLE:{Cl(this,t);break}case k.TEXT:{ef(this,t);break}case k.IN_TABLE_TEXT:{Ss(this,t);break}case k.IN_TEMPLATE:{Rl(this,t);break}case k.AFTER_BODY:case k.IN_FRAMESET:case k.AFTER_FRAMESET:case k.AFTER_AFTER_BODY:case k.AFTER_AFTER_FRAMESET:{di(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=!1,t.chars.charCodeAt(0)===g.LINE_FEED)){if(t.chars.length===1)return;t.chars=t.chars.substr(1)}if(this.tokenizer.inForeignNode){this._insertCharacters(t);return}switch(this.insertionMode){case k.IN_HEAD:case k.IN_HEAD_NO_SCRIPT:case k.AFTER_HEAD:case k.TEXT:case k.IN_COLUMN_GROUP:case k.IN_SELECT:case k.IN_SELECT_IN_TABLE:case k.IN_FRAMESET:case k.AFTER_FRAMESET:{this._insertCharacters(t);break}case k.IN_BODY:case k.IN_CAPTION:case k.IN_CELL:case k.IN_TEMPLATE:case k.AFTER_BODY:case k.AFTER_AFTER_BODY:case k.AFTER_AFTER_FRAMESET:{xl(this,t);break}case k.IN_TABLE:case k.IN_TABLE_BODY:case k.IN_ROW:{Ta(this,t);break}case k.IN_TABLE_TEXT:{wl(this,t);break}}}}function Xm(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return n?e.openElements.contains(n.element)?e.openElements.hasInScope(t.tagID)||(n=null):(e.activeFormattingElements.removeEntry(n),n=null):vl(e,t),n}function Jm(e,t){let n=null,a=e.openElements.stackTop;for(;a>=0;a--){const i=e.openElements.items[a];if(i===t.element)break;e._isSpecialElement(i,e.openElements.tagIDs[a])&&(n=i)}return n||(e.openElements.shortenToLength(Math.max(a,0)),e.activeFormattingElements.removeEntry(t)),n}function Zm(e,t,n){let a=t,i=e.openElements.getCommonAncestor(t);for(let o=0,l=i;l!==n;o++,l=i){i=e.openElements.getCommonAncestor(l);const u=e.activeFormattingElements.getElementEntry(l),p=u&&o>=Vm;!u||p?(p&&e.activeFormattingElements.removeEntry(u),e.openElements.remove(l)):(l=eh(e,u),a===t&&(e.activeFormattingElements.bookmark=u),e.treeAdapter.detachNode(a),e.treeAdapter.appendChild(l,a),a=l)}return a}function eh(e,t){const n=e.treeAdapter.getNamespaceURI(t.element),a=e.treeAdapter.createElement(t.token.tagName,n,t.token.attrs);return e.openElements.replace(t.element,a),t.element=a,a}function th(e,t,n){const a=e.treeAdapter.getTagName(t),i=xs(a);if(e._isElementCausesFosterParenting(i))e._fosterParentElement(n);else{const o=e.treeAdapter.getNamespaceURI(t);i===r.TEMPLATE&&o===ne.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,n)}}function sh(e,t,n){const a=e.treeAdapter.getNamespaceURI(n.element),{token:i}=n,o=e.treeAdapter.createElement(i.tagName,a,i.attrs);e._adoptNodes(t,o),e.treeAdapter.appendChild(t,o),e.activeFormattingElements.insertElementAfterBookmark(o,i),e.activeFormattingElements.removeEntry(n),e.openElements.remove(n.element),e.openElements.insertAfter(t,o,i.tagID)}function ui(e,t){for(let n=0;n<zm;n++){const a=Xm(e,t);if(!a)break;const i=Jm(e,a);if(!i)break;e.activeFormattingElements.bookmark=a;const o=Zm(e,i,a.element),l=e.openElements.getCommonAncestor(a.element);e.treeAdapter.detachNode(o),l&&th(e,l,o),sh(e,i,a)}}function Wa(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode)}function nh(e,t){e._appendCommentNode(t,e.openElements.items[0])}function ah(e,t){e._appendCommentNode(t,e.document)}function di(e,t){if(e.stopped=!0,t.location){const n=e.fragmentContext?0:2;for(let a=e.openElements.stackTop;a>=n;a--)e._setEndLocation(e.openElements.items[a],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){const a=e.openElements.items[0],i=e.treeAdapter.getNodeSourceCodeLocation(a);if(i&&!i.endTag&&(e._setEndLocation(a,t),e.openElements.stackTop>=1)){const o=e.openElements.items[1],l=e.treeAdapter.getNodeSourceCodeLocation(o);l&&!l.endTag&&e._setEndLocation(o,t)}}}}function ih(e,t){e._setDocumentType(t);const n=t.forceQuirks?yt.QUIRKS:Pm(t);Dm(t)||e._err(t,z.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,n),e.insertionMode=k.BEFORE_HTML}function ws(e,t){e._err(t,z.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,yt.QUIRKS),e.insertionMode=k.BEFORE_HTML,e._processToken(t)}function rh(e,t){t.tagID===r.HTML?(e._insertElement(t,ne.HTML),e.insertionMode=k.BEFORE_HEAD):Ms(e,t)}function oh(e,t){const n=t.tagID;(n===r.HTML||n===r.HEAD||n===r.BODY||n===r.BR)&&Ms(e,t)}function Ms(e,t){e._insertFakeRootElement(),e.insertionMode=k.BEFORE_HEAD,e._processToken(t)}function lh(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.HEAD:{e._insertElement(t,ne.HTML),e.headElement=e.openElements.current,e.insertionMode=k.IN_HEAD;break}default:Bs(e,t)}}function ch(e,t){const n=t.tagID;n===r.HEAD||n===r.BODY||n===r.HTML||n===r.BR?Bs(e,t):e._err(t,z.endTagWithoutMatchingOpenElement)}function Bs(e,t){e._insertFakeElement(M.HEAD,r.HEAD),e.headElement=e.openElements.current,e.insertionMode=k.IN_HEAD,e._processToken(t)}function _t(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.BASE:case r.BASEFONT:case r.BGSOUND:case r.LINK:case r.META:{e._appendElement(t,ne.HTML),t.ackSelfClosing=!0;break}case r.TITLE:{e._switchToTextParsing(t,st.RCDATA);break}case r.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,st.RAWTEXT):(e._insertElement(t,ne.HTML),e.insertionMode=k.IN_HEAD_NO_SCRIPT);break}case r.NOFRAMES:case r.STYLE:{e._switchToTextParsing(t,st.RAWTEXT);break}case r.SCRIPT:{e._switchToTextParsing(t,st.SCRIPT_DATA);break}case r.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=!1,e.insertionMode=k.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(k.IN_TEMPLATE);break}case r.HEAD:{e._err(t,z.misplacedStartTagForHeadElement);break}default:Fs(e,t)}}function uh(e,t){switch(t.tagID){case r.HEAD:{e.openElements.pop(),e.insertionMode=k.AFTER_HEAD;break}case r.BODY:case r.BR:case r.HTML:{Fs(e,t);break}case r.TEMPLATE:{os(e,t);break}default:e._err(t,z.endTagWithoutMatchingOpenElement)}}function os(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==r.TEMPLATE&&e._err(t,z.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(r.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,z.endTagWithoutMatchingOpenElement)}function Fs(e,t){e.openElements.pop(),e.insertionMode=k.AFTER_HEAD,e._processToken(t)}function dh(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.BASEFONT:case r.BGSOUND:case r.HEAD:case r.LINK:case r.META:case r.NOFRAMES:case r.STYLE:{_t(e,t);break}case r.NOSCRIPT:{e._err(t,z.nestedNoscriptInHead);break}default:Hs(e,t)}}function ph(e,t){switch(t.tagID){case r.NOSCRIPT:{e.openElements.pop(),e.insertionMode=k.IN_HEAD;break}case r.BR:{Hs(e,t);break}default:e._err(t,z.endTagWithoutMatchingOpenElement)}}function Hs(e,t){const n=t.type===Ue.EOF?z.openElementsLeftAfterEof:z.disallowedContentInNoscriptInHead;e._err(t,n),e.openElements.pop(),e.insertionMode=k.IN_HEAD,e._processToken(t)}function mh(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.BODY:{e._insertElement(t,ne.HTML),e.framesetOk=!1,e.insertionMode=k.IN_BODY;break}case r.FRAMESET:{e._insertElement(t,ne.HTML),e.insertionMode=k.IN_FRAMESET;break}case r.BASE:case r.BASEFONT:case r.BGSOUND:case r.LINK:case r.META:case r.NOFRAMES:case r.SCRIPT:case r.STYLE:case r.TEMPLATE:case r.TITLE:{e._err(t,z.abandonedHeadElementChild),e.openElements.push(e.headElement,r.HEAD),_t(e,t),e.openElements.remove(e.headElement);break}case r.HEAD:{e._err(t,z.misplacedStartTagForHeadElement);break}default:Us(e,t)}}function hh(e,t){switch(t.tagID){case r.BODY:case r.HTML:case r.BR:{Us(e,t);break}case r.TEMPLATE:{os(e,t);break}default:e._err(t,z.endTagWithoutMatchingOpenElement)}}function Us(e,t){e._insertFakeElement(M.BODY,r.BODY),e.insertionMode=k.IN_BODY,Zn(e,t)}function Zn(e,t){switch(t.type){case Ue.CHARACTER:{yl(e,t);break}case Ue.WHITESPACE_CHARACTER:{xl(e,t);break}case Ue.COMMENT:{Wa(e,t);break}case Ue.START_TAG:{ct(e,t);break}case Ue.END_TAG:{ea(e,t);break}case Ue.EOF:{Cl(e,t);break}}}function xl(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function yl(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function fh(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function gh(e,t){const n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e.openElements.tmplCount===0&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(n,t.attrs))}function bh(e,t){const n=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&n&&(e.treeAdapter.detachNode(n),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,ne.HTML),e.insertionMode=k.IN_FRAMESET)}function Eh(e,t){e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._insertElement(t,ne.HTML)}function Th(e,t){e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&qa.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,ne.HTML)}function xh(e,t){e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._insertElement(t,ne.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function yh(e,t){const n=e.openElements.tmplCount>0;(!e.formElement||n)&&(e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._insertElement(t,ne.HTML),n||(e.formElement=e.openElements.current))}function kh(e,t){e.framesetOk=!1;const n=t.tagID;for(let a=e.openElements.stackTop;a>=0;a--){const i=e.openElements.tagIDs[a];if(n===r.LI&&i===r.LI||(n===r.DD||n===r.DT)&&(i===r.DD||i===r.DT)){e.openElements.generateImpliedEndTagsWithExclusion(i),e.openElements.popUntilTagNamePopped(i);break}if(i!==r.ADDRESS&&i!==r.DIV&&i!==r.P&&e._isSpecialElement(e.openElements.items[a],i))break}e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._insertElement(t,ne.HTML)}function Nh(e,t){e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._insertElement(t,ne.HTML),e.tokenizer.state=st.PLAINTEXT}function vh(e,t){e.openElements.hasInScope(r.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.framesetOk=!1}function Ch(e,t){const n=e.activeFormattingElements.getElementEntryInScopeWithTagName(M.A);n&&(ui(e,t),e.openElements.remove(n.element),e.activeFormattingElements.removeEntry(n)),e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function wh(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function Sh(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(r.NOBR)&&(ui(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function _h(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function Ah(e,t){e.treeAdapter.getDocumentMode(e.document)!==yt.QUIRKS&&e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._insertElement(t,ne.HTML),e.framesetOk=!1,e.insertionMode=k.IN_TABLE}function kl(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,ne.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function Nl(e){const t=dl(e,ns.TYPE);return t!=null&&t.toLowerCase()===Gm}function Ih(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,ne.HTML),Nl(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function jh(e,t){e._appendElement(t,ne.HTML),t.ackSelfClosing=!0}function Rh(e,t){e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._appendElement(t,ne.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function Lh(e,t){t.tagName=M.IMG,t.tagID=r.IMG,kl(e,t)}function Dh(e,t){e._insertElement(t,ne.HTML),e.skipNextNewLine=!0,e.tokenizer.state=st.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=!1,e.insertionMode=k.TEXT}function Ph(e,t){e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,st.RAWTEXT)}function Oh(e,t){e.framesetOk=!1,e._switchToTextParsing(t,st.RAWTEXT)}function _r(e,t){e._switchToTextParsing(t,st.RAWTEXT)}function Mh(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.framesetOk=!1,e.insertionMode=e.insertionMode===k.IN_TABLE||e.insertionMode===k.IN_CAPTION||e.insertionMode===k.IN_TABLE_BODY||e.insertionMode===k.IN_ROW||e.insertionMode===k.IN_CELL?k.IN_SELECT_IN_TABLE:k.IN_SELECT}function Bh(e,t){e.openElements.currentTagId===r.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML)}function Fh(e,t){e.openElements.hasInScope(r.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,ne.HTML)}function Hh(e,t){e.openElements.hasInScope(r.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(r.RTC),e._insertElement(t,ne.HTML)}function Uh(e,t){e._reconstructActiveFormattingElements(),bl(t),ci(t),t.selfClosing?e._appendElement(t,ne.MATHML):e._insertElement(t,ne.MATHML),t.ackSelfClosing=!0}function $h(e,t){e._reconstructActiveFormattingElements(),El(t),ci(t),t.selfClosing?e._appendElement(t,ne.SVG):e._insertElement(t,ne.SVG),t.ackSelfClosing=!0}function Ar(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML)}function ct(e,t){switch(t.tagID){case r.I:case r.S:case r.B:case r.U:case r.EM:case r.TT:case r.BIG:case r.CODE:case r.FONT:case r.SMALL:case r.STRIKE:case r.STRONG:{wh(e,t);break}case r.A:{Ch(e,t);break}case r.H1:case r.H2:case r.H3:case r.H4:case r.H5:case r.H6:{Th(e,t);break}case r.P:case r.DL:case r.OL:case r.UL:case r.DIV:case r.DIR:case r.NAV:case r.MAIN:case r.MENU:case r.ASIDE:case r.CENTER:case r.FIGURE:case r.FOOTER:case r.HEADER:case r.HGROUP:case r.DIALOG:case r.DETAILS:case r.ADDRESS:case r.ARTICLE:case r.SEARCH:case r.SECTION:case r.SUMMARY:case r.FIELDSET:case r.BLOCKQUOTE:case r.FIGCAPTION:{Eh(e,t);break}case r.LI:case r.DD:case r.DT:{kh(e,t);break}case r.BR:case r.IMG:case r.WBR:case r.AREA:case r.EMBED:case r.KEYGEN:{kl(e,t);break}case r.HR:{Rh(e,t);break}case r.RB:case r.RTC:{Fh(e,t);break}case r.RT:case r.RP:{Hh(e,t);break}case r.PRE:case r.LISTING:{xh(e,t);break}case r.XMP:{Ph(e,t);break}case r.SVG:{$h(e,t);break}case r.HTML:{fh(e,t);break}case r.BASE:case r.LINK:case r.META:case r.STYLE:case r.TITLE:case r.SCRIPT:case r.BGSOUND:case r.BASEFONT:case r.TEMPLATE:{_t(e,t);break}case r.BODY:{gh(e,t);break}case r.FORM:{yh(e,t);break}case r.NOBR:{Sh(e,t);break}case r.MATH:{Uh(e,t);break}case r.TABLE:{Ah(e,t);break}case r.INPUT:{Ih(e,t);break}case r.PARAM:case r.TRACK:case r.SOURCE:{jh(e,t);break}case r.IMAGE:{Lh(e,t);break}case r.BUTTON:{vh(e,t);break}case r.APPLET:case r.OBJECT:case r.MARQUEE:{_h(e,t);break}case r.IFRAME:{Oh(e,t);break}case r.SELECT:{Mh(e,t);break}case r.OPTION:case r.OPTGROUP:{Bh(e,t);break}case r.NOEMBED:case r.NOFRAMES:{_r(e,t);break}case r.FRAMESET:{bh(e,t);break}case r.TEXTAREA:{Dh(e,t);break}case r.NOSCRIPT:{e.options.scriptingEnabled?_r(e,t):Ar(e,t);break}case r.PLAINTEXT:{Nh(e,t);break}case r.COL:case r.TH:case r.TD:case r.TR:case r.HEAD:case r.FRAME:case r.TBODY:case r.TFOOT:case r.THEAD:case r.CAPTION:case r.COLGROUP:break;default:Ar(e,t)}}function qh(e,t){if(e.openElements.hasInScope(r.BODY)&&(e.insertionMode=k.AFTER_BODY,e.options.sourceCodeLocationInfo)){const n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e._setEndLocation(n,t)}}function Wh(e,t){e.openElements.hasInScope(r.BODY)&&(e.insertionMode=k.AFTER_BODY,Ll(e,t))}function Kh(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n))}function Yh(e){const t=e.openElements.tmplCount>0,{formElement:n}=e;t||(e.formElement=null),(n||t)&&e.openElements.hasInScope(r.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(r.FORM):n&&e.openElements.remove(n))}function Gh(e){e.openElements.hasInButtonScope(r.P)||e._insertFakeElement(M.P,r.P),e._closePElement()}function zh(e){e.openElements.hasInListItemScope(r.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(r.LI),e.openElements.popUntilTagNamePopped(r.LI))}function Vh(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n))}function Qh(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function Xh(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker())}function Jh(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(M.BR,r.BR),e.openElements.pop(),e.framesetOk=!1}function vl(e,t){const n=t.tagName,a=t.tagID;for(let i=e.openElements.stackTop;i>0;i--){const o=e.openElements.items[i],l=e.openElements.tagIDs[i];if(a===l&&(a!==r.UNKNOWN||e.treeAdapter.getTagName(o)===n)){e.openElements.generateImpliedEndTagsWithExclusion(a),e.openElements.stackTop>=i&&e.openElements.shortenToLength(i);break}if(e._isSpecialElement(o,l))break}}function ea(e,t){switch(t.tagID){case r.A:case r.B:case r.I:case r.S:case r.U:case r.EM:case r.TT:case r.BIG:case r.CODE:case r.FONT:case r.NOBR:case r.SMALL:case r.STRIKE:case r.STRONG:{ui(e,t);break}case r.P:{Gh(e);break}case r.DL:case r.UL:case r.OL:case r.DIR:case r.DIV:case r.NAV:case r.PRE:case r.MAIN:case r.MENU:case r.ASIDE:case r.BUTTON:case r.CENTER:case r.FIGURE:case r.FOOTER:case r.HEADER:case r.HGROUP:case r.DIALOG:case r.ADDRESS:case r.ARTICLE:case r.DETAILS:case r.SEARCH:case r.SECTION:case r.SUMMARY:case r.LISTING:case r.FIELDSET:case r.BLOCKQUOTE:case r.FIGCAPTION:{Kh(e,t);break}case r.LI:{zh(e);break}case r.DD:case r.DT:{Vh(e,t);break}case r.H1:case r.H2:case r.H3:case r.H4:case r.H5:case r.H6:{Qh(e);break}case r.BR:{Jh(e);break}case r.BODY:{qh(e,t);break}case r.HTML:{Wh(e,t);break}case r.FORM:{Yh(e);break}case r.APPLET:case r.OBJECT:case r.MARQUEE:{Xh(e,t);break}case r.TEMPLATE:{os(e,t);break}default:vl(e,t)}}function Cl(e,t){e.tmplInsertionModeStack.length>0?Rl(e,t):di(e,t)}function Zh(e,t){var n;t.tagID===r.SCRIPT&&((n=e.scriptHandler)===null||n===void 0||n.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode}function ef(e,t){e._err(t,z.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function Ta(e,t){if(e.openElements.currentTagId!==void 0&&Tl.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=!1,e.originalInsertionMode=e.insertionMode,e.insertionMode=k.IN_TABLE_TEXT,t.type){case Ue.CHARACTER:{Sl(e,t);break}case Ue.WHITESPACE_CHARACTER:{wl(e,t);break}}else Xs(e,t)}function tf(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,ne.HTML),e.insertionMode=k.IN_CAPTION}function sf(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,ne.HTML),e.insertionMode=k.IN_COLUMN_GROUP}function nf(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(M.COLGROUP,r.COLGROUP),e.insertionMode=k.IN_COLUMN_GROUP,pi(e,t)}function af(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,ne.HTML),e.insertionMode=k.IN_TABLE_BODY}function rf(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(M.TBODY,r.TBODY),e.insertionMode=k.IN_TABLE_BODY,ta(e,t)}function of(e,t){e.openElements.hasInTableScope(r.TABLE)&&(e.openElements.popUntilTagNamePopped(r.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function lf(e,t){Nl(t)?e._appendElement(t,ne.HTML):Xs(e,t),t.ackSelfClosing=!0}function cf(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,ne.HTML),e.formElement=e.openElements.current,e.openElements.pop())}function bs(e,t){switch(t.tagID){case r.TD:case r.TH:case r.TR:{rf(e,t);break}case r.STYLE:case r.SCRIPT:case r.TEMPLATE:{_t(e,t);break}case r.COL:{nf(e,t);break}case r.FORM:{cf(e,t);break}case r.TABLE:{of(e,t);break}case r.TBODY:case r.TFOOT:case r.THEAD:{af(e,t);break}case r.INPUT:{lf(e,t);break}case r.CAPTION:{tf(e,t);break}case r.COLGROUP:{sf(e,t);break}default:Xs(e,t)}}function zs(e,t){switch(t.tagID){case r.TABLE:{e.openElements.hasInTableScope(r.TABLE)&&(e.openElements.popUntilTagNamePopped(r.TABLE),e._resetInsertionMode());break}case r.TEMPLATE:{os(e,t);break}case r.BODY:case r.CAPTION:case r.COL:case r.COLGROUP:case r.HTML:case r.TBODY:case r.TD:case r.TFOOT:case r.TH:case r.THEAD:case r.TR:break;default:Xs(e,t)}}function Xs(e,t){const n=e.fosterParentingEnabled;e.fosterParentingEnabled=!0,Zn(e,t),e.fosterParentingEnabled=n}function wl(e,t){e.pendingCharacterTokens.push(t)}function Sl(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=!0}function Ss(e,t){let n=0;if(e.hasNonWhitespacePendingCharacterToken)for(;n<e.pendingCharacterTokens.length;n++)Xs(e,e.pendingCharacterTokens[n]);else for(;n<e.pendingCharacterTokens.length;n++)e._insertCharacters(e.pendingCharacterTokens[n]);e.insertionMode=e.originalInsertionMode,e._processToken(t)}const _l=new Set([r.CAPTION,r.COL,r.COLGROUP,r.TBODY,r.TD,r.TFOOT,r.TH,r.THEAD,r.TR]);function uf(e,t){const n=t.tagID;_l.has(n)?e.openElements.hasInTableScope(r.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=k.IN_TABLE,bs(e,t)):ct(e,t)}function df(e,t){const n=t.tagID;switch(n){case r.CAPTION:case r.TABLE:{e.openElements.hasInTableScope(r.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=k.IN_TABLE,n===r.TABLE&&zs(e,t));break}case r.BODY:case r.COL:case r.COLGROUP:case r.HTML:case r.TBODY:case r.TD:case r.TFOOT:case r.TH:case r.THEAD:case r.TR:break;default:ea(e,t)}}function pi(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.COL:{e._appendElement(t,ne.HTML),t.ackSelfClosing=!0;break}case r.TEMPLATE:{_t(e,t);break}default:Bn(e,t)}}function pf(e,t){switch(t.tagID){case r.COLGROUP:{e.openElements.currentTagId===r.COLGROUP&&(e.openElements.pop(),e.insertionMode=k.IN_TABLE);break}case r.TEMPLATE:{os(e,t);break}case r.COL:break;default:Bn(e,t)}}function Bn(e,t){e.openElements.currentTagId===r.COLGROUP&&(e.openElements.pop(),e.insertionMode=k.IN_TABLE,e._processToken(t))}function ta(e,t){switch(t.tagID){case r.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,ne.HTML),e.insertionMode=k.IN_ROW;break}case r.TH:case r.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(M.TR,r.TR),e.insertionMode=k.IN_ROW,sa(e,t);break}case r.CAPTION:case r.COL:case r.COLGROUP:case r.TBODY:case r.TFOOT:case r.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=k.IN_TABLE,bs(e,t));break}default:bs(e,t)}}function Ka(e,t){const n=t.tagID;switch(t.tagID){case r.TBODY:case r.TFOOT:case r.THEAD:{e.openElements.hasInTableScope(n)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=k.IN_TABLE);break}case r.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=k.IN_TABLE,zs(e,t));break}case r.BODY:case r.CAPTION:case r.COL:case r.COLGROUP:case r.HTML:case r.TD:case r.TH:case r.TR:break;default:zs(e,t)}}function sa(e,t){switch(t.tagID){case r.TH:case r.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,ne.HTML),e.insertionMode=k.IN_CELL,e.activeFormattingElements.insertMarker();break}case r.CAPTION:case r.COL:case r.COLGROUP:case r.TBODY:case r.TFOOT:case r.THEAD:case r.TR:{e.openElements.hasInTableScope(r.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=k.IN_TABLE_BODY,ta(e,t));break}default:bs(e,t)}}function Al(e,t){switch(t.tagID){case r.TR:{e.openElements.hasInTableScope(r.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=k.IN_TABLE_BODY);break}case r.TABLE:{e.openElements.hasInTableScope(r.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=k.IN_TABLE_BODY,Ka(e,t));break}case r.TBODY:case r.TFOOT:case r.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(r.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=k.IN_TABLE_BODY,Ka(e,t));break}case r.BODY:case r.CAPTION:case r.COL:case r.COLGROUP:case r.HTML:case r.TD:case r.TH:break;default:zs(e,t)}}function mf(e,t){const n=t.tagID;_l.has(n)?(e.openElements.hasInTableScope(r.TD)||e.openElements.hasInTableScope(r.TH))&&(e._closeTableCell(),sa(e,t)):ct(e,t)}function hf(e,t){const n=t.tagID;switch(n){case r.TD:case r.TH:{e.openElements.hasInTableScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=k.IN_ROW);break}case r.TABLE:case r.TBODY:case r.TFOOT:case r.THEAD:case r.TR:{e.openElements.hasInTableScope(n)&&(e._closeTableCell(),Al(e,t));break}case r.BODY:case r.CAPTION:case r.COL:case r.COLGROUP:case r.HTML:break;default:ea(e,t)}}function Il(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.OPTION:{e.openElements.currentTagId===r.OPTION&&e.openElements.pop(),e._insertElement(t,ne.HTML);break}case r.OPTGROUP:{e.openElements.currentTagId===r.OPTION&&e.openElements.pop(),e.openElements.currentTagId===r.OPTGROUP&&e.openElements.pop(),e._insertElement(t,ne.HTML);break}case r.HR:{e.openElements.currentTagId===r.OPTION&&e.openElements.pop(),e.openElements.currentTagId===r.OPTGROUP&&e.openElements.pop(),e._appendElement(t,ne.HTML),t.ackSelfClosing=!0;break}case r.INPUT:case r.KEYGEN:case r.TEXTAREA:case r.SELECT:{e.openElements.hasInSelectScope(r.SELECT)&&(e.openElements.popUntilTagNamePopped(r.SELECT),e._resetInsertionMode(),t.tagID!==r.SELECT&&e._processStartTag(t));break}case r.SCRIPT:case r.TEMPLATE:{_t(e,t);break}}}function jl(e,t){switch(t.tagID){case r.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===r.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===r.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===r.OPTGROUP&&e.openElements.pop();break}case r.OPTION:{e.openElements.currentTagId===r.OPTION&&e.openElements.pop();break}case r.SELECT:{e.openElements.hasInSelectScope(r.SELECT)&&(e.openElements.popUntilTagNamePopped(r.SELECT),e._resetInsertionMode());break}case r.TEMPLATE:{os(e,t);break}}}function ff(e,t){const n=t.tagID;n===r.CAPTION||n===r.TABLE||n===r.TBODY||n===r.TFOOT||n===r.THEAD||n===r.TR||n===r.TD||n===r.TH?(e.openElements.popUntilTagNamePopped(r.SELECT),e._resetInsertionMode(),e._processStartTag(t)):Il(e,t)}function gf(e,t){const n=t.tagID;n===r.CAPTION||n===r.TABLE||n===r.TBODY||n===r.TFOOT||n===r.THEAD||n===r.TR||n===r.TD||n===r.TH?e.openElements.hasInTableScope(n)&&(e.openElements.popUntilTagNamePopped(r.SELECT),e._resetInsertionMode(),e.onEndTag(t)):jl(e,t)}function bf(e,t){switch(t.tagID){case r.BASE:case r.BASEFONT:case r.BGSOUND:case r.LINK:case r.META:case r.NOFRAMES:case r.SCRIPT:case r.STYLE:case r.TEMPLATE:case r.TITLE:{_t(e,t);break}case r.CAPTION:case r.COLGROUP:case r.TBODY:case r.TFOOT:case r.THEAD:{e.tmplInsertionModeStack[0]=k.IN_TABLE,e.insertionMode=k.IN_TABLE,bs(e,t);break}case r.COL:{e.tmplInsertionModeStack[0]=k.IN_COLUMN_GROUP,e.insertionMode=k.IN_COLUMN_GROUP,pi(e,t);break}case r.TR:{e.tmplInsertionModeStack[0]=k.IN_TABLE_BODY,e.insertionMode=k.IN_TABLE_BODY,ta(e,t);break}case r.TD:case r.TH:{e.tmplInsertionModeStack[0]=k.IN_ROW,e.insertionMode=k.IN_ROW,sa(e,t);break}default:e.tmplInsertionModeStack[0]=k.IN_BODY,e.insertionMode=k.IN_BODY,ct(e,t)}}function Ef(e,t){t.tagID===r.TEMPLATE&&os(e,t)}function Rl(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(r.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):di(e,t)}function Tf(e,t){t.tagID===r.HTML?ct(e,t):Fn(e,t)}function Ll(e,t){var n;if(t.tagID===r.HTML){if(e.fragmentContext||(e.insertionMode=k.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===r.HTML){e._setEndLocation(e.openElements.items[0],t);const a=e.openElements.items[1];a&&!(!((n=e.treeAdapter.getNodeSourceCodeLocation(a))===null||n===void 0)&&n.endTag)&&e._setEndLocation(a,t)}}else Fn(e,t)}function Fn(e,t){e.insertionMode=k.IN_BODY,Zn(e,t)}function xf(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.FRAMESET:{e._insertElement(t,ne.HTML);break}case r.FRAME:{e._appendElement(t,ne.HTML),t.ackSelfClosing=!0;break}case r.NOFRAMES:{_t(e,t);break}}}function yf(e,t){t.tagID===r.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==r.FRAMESET&&(e.insertionMode=k.AFTER_FRAMESET))}function kf(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.NOFRAMES:{_t(e,t);break}}}function Nf(e,t){t.tagID===r.HTML&&(e.insertionMode=k.AFTER_AFTER_FRAMESET)}function vf(e,t){t.tagID===r.HTML?ct(e,t):En(e,t)}function En(e,t){e.insertionMode=k.IN_BODY,Zn(e,t)}function Cf(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.NOFRAMES:{_t(e,t);break}}}function wf(e,t){t.chars=et,e._insertCharacters(t)}function Sf(e,t){e._insertCharacters(t),e.framesetOk=!1}function Dl(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==ne.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop()}function _f(e,t){if($m(t))Dl(e),e._startTagOutsideForeignContent(t);else{const n=e._getAdjustedCurrentElement(),a=e.treeAdapter.getNamespaceURI(n);a===ne.MATHML?bl(t):a===ne.SVG&&(qm(t),El(t)),ci(t),t.selfClosing?e._appendElement(t,a):e._insertElement(t,a),t.ackSelfClosing=!0}}function Af(e,t){if(t.tagID===r.P||t.tagID===r.BR){Dl(e),e._endTagOutsideForeignContent(t);return}for(let n=e.openElements.stackTop;n>0;n--){const a=e.openElements.items[n];if(e.treeAdapter.getNamespaceURI(a)===ne.HTML){e._endTagOutsideForeignContent(t);break}const i=e.treeAdapter.getTagName(a);if(i.toLowerCase()===t.tagName){t.tagName=i,e.openElements.shortenToLength(n);break}}}M.AREA,M.BASE,M.BASEFONT,M.BGSOUND,M.BR,M.COL,M.EMBED,M.FRAME,M.HR,M.IMG,M.INPUT,M.KEYGEN,M.LINK,M.META,M.PARAM,M.SOURCE,M.TRACK,M.WBR;const If=/<(\/?)(iframe|noembed|noframes|plaintext|script|style|textarea|title|xmp)(?=[\t\n\f\r />])/gi,jf=new Set(["mdxFlowExpression","mdxJsxFlowElement","mdxJsxTextElement","mdxTextExpression","mdxjsEsm"]),Ir={sourceCodeLocationInfo:!0,scriptingEnabled:!1};function Pl(e,t){const n=Uf(e),a=ho("type",{handlers:{root:Rf,element:Lf,text:Df,comment:Ml,doctype:Pf,raw:Mf},unknown:Bf}),i={parser:n?new Sr(Ir):Sr.getFragmentParser(void 0,Ir),handle(u){a(u,i)},stitches:!1,options:t||{}};a(e,i),ys(i,is());const o=n?i.parser.document:i.parser.getFragment(),l=Up(o,{file:i.options.file});return i.stitches&&iu(l,"comment",function(u,p,h){const b=u;if(b.value.stitch&&h&&p!==void 0){const m=h.children;return m[p]=b.value.stitch,p}}),l.type==="root"&&l.children.length===1&&l.children[0].type===e.type?l.children[0]:l}function Ol(e,t){let n=-1;if(e)for(;++n<e.length;)t.handle(e[n])}function Rf(e,t){Ol(e.children,t)}function Lf(e,t){Ff(e,t),Ol(e.children,t),Hf(e,t)}function Df(e,t){t.parser.tokenizer.state>4&&(t.parser.tokenizer.state=0);const n={type:Ue.CHARACTER,chars:e.value,location:Js(e)};ys(t,is(e)),t.parser.currentToken=n,t.parser._processToken(t.parser.currentToken)}function Pf(e,t){const n={type:Ue.DOCTYPE,name:"html",forceQuirks:!1,publicId:"",systemId:"",location:Js(e)};ys(t,is(e)),t.parser.currentToken=n,t.parser._processToken(t.parser.currentToken)}function Of(e,t){t.stitches=!0;const n=$f(e);if("children"in e&&"children"in n){const a=Pl({type:"root",children:e.children},t.options);n.children=a.children}Ml({type:"comment",value:{stitch:n}},t)}function Ml(e,t){const n=e.value,a={type:Ue.COMMENT,data:n,location:Js(e)};ys(t,is(e)),t.parser.currentToken=a,t.parser._processToken(t.parser.currentToken)}function Mf(e,t){if(t.parser.tokenizer.preprocessor.html="",t.parser.tokenizer.preprocessor.pos=-1,t.parser.tokenizer.preprocessor.lastGapPos=-2,t.parser.tokenizer.preprocessor.gapStack=[],t.parser.tokenizer.preprocessor.skipNextNewLine=!1,t.parser.tokenizer.preprocessor.lastChunkWritten=!1,t.parser.tokenizer.preprocessor.endOfChunkHit=!1,t.parser.tokenizer.preprocessor.isEol=!1,Bl(t,is(e)),t.parser.tokenizer.write(t.options.tagfilter?e.value.replace(If,"&lt;$1$2"):e.value,!1),t.parser.tokenizer._runParsingLoop(),t.parser.tokenizer.state===72||t.parser.tokenizer.state===78){t.parser.tokenizer.preprocessor.lastChunkWritten=!0;const n=t.parser.tokenizer._consume();t.parser.tokenizer._callState(n)}}function Bf(e,t){const n=e;if(t.options.passThrough&&t.options.passThrough.includes(n.type))Of(n,t);else{let a="";throw jf.has(n.type)&&(a=". It looks like you are using MDX nodes with `hast-util-raw` (or `rehype-raw`). If you use this because you are using remark or rehype plugins that inject `'html'` nodes, then please raise an issue with that plugin, as its a bad and slow idea. If you use this because you are using markdown syntax, then you have to configure this utility (or plugin) to pass through these nodes (see `passThrough` in docs), but you can also migrate to use the MDX syntax"),new Error("Cannot compile `"+n.type+"` node"+a)}}function ys(e,t){Bl(e,t);const n=e.parser.tokenizer.currentCharacterToken;n&&n.location&&(n.location.endLine=e.parser.tokenizer.preprocessor.line,n.location.endCol=e.parser.tokenizer.preprocessor.col+1,n.location.endOffset=e.parser.tokenizer.preprocessor.offset+1,e.parser.currentToken=n,e.parser._processToken(e.parser.currentToken)),e.parser.tokenizer.paused=!1,e.parser.tokenizer.inLoop=!1,e.parser.tokenizer.active=!1,e.parser.tokenizer.returnState=st.DATA,e.parser.tokenizer.charRefCode=-1,e.parser.tokenizer.consumedAfterSnapshot=-1,e.parser.tokenizer.currentLocation=null,e.parser.tokenizer.currentCharacterToken=null,e.parser.tokenizer.currentToken=null,e.parser.tokenizer.currentAttr={name:"",value:""}}function Bl(e,t){if(t&&t.offset!==void 0){const n={startLine:t.line,startCol:t.column,startOffset:t.offset,endLine:-1,endCol:-1,endOffset:-1};e.parser.tokenizer.preprocessor.lineStartPos=-t.column+1,e.parser.tokenizer.preprocessor.droppedBufferSize=t.offset,e.parser.tokenizer.preprocessor.line=t.line,e.parser.tokenizer.currentLocation=n}}function Ff(e,t){const n=e.tagName.toLowerCase();if(t.parser.tokenizer.state===st.PLAINTEXT)return;ys(t,is(e));const a=t.parser.openElements.current;let i="namespaceURI"in a?a.namespaceURI:Xt.html;i===Xt.html&&n==="svg"&&(i=Xt.svg);const o=Yp({...e,children:[]},{space:i===Xt.svg?"svg":"html"}),l={type:Ue.START_TAG,tagName:n,tagID:xs(n),selfClosing:!1,ackSelfClosing:!1,attrs:"attrs"in o?o.attrs:[],location:Js(e)};t.parser.currentToken=l,t.parser._processToken(t.parser.currentToken),t.parser.tokenizer.lastStartTagName=n}function Hf(e,t){const n=e.tagName.toLowerCase();if(!t.parser.tokenizer.inForeignNode&&em.includes(n)||t.parser.tokenizer.state===st.PLAINTEXT)return;ys(t,fo(e));const a={type:Ue.END_TAG,tagName:n,tagID:xs(n),selfClosing:!1,ackSelfClosing:!1,attrs:[],location:Js(e)};t.parser.currentToken=a,t.parser._processToken(t.parser.currentToken),n===t.parser.tokenizer.lastStartTagName&&(t.parser.tokenizer.state===st.RCDATA||t.parser.tokenizer.state===st.RAWTEXT||t.parser.tokenizer.state===st.SCRIPT_DATA)&&(t.parser.tokenizer.state=st.DATA)}function Uf(e){const t=e.type==="root"?e.children[0]:e;return!!(t&&(t.type==="doctype"||t.type==="element"&&t.tagName.toLowerCase()==="html"))}function Js(e){const t=is(e)||{line:void 0,column:void 0,offset:void 0},n=fo(e)||{line:void 0,column:void 0,offset:void 0};return{startLine:t.line,startCol:t.column,startOffset:t.offset,endLine:n.line,endCol:n.column,endOffset:n.offset}}function $f(e){return"children"in e?Ni({...e,children:[]}):Ni(e)}function qf(e){return function(t,n){return Pl(t,{...e,file:n})}}const Hn=c.memo(function({text:t}){const n=Me(),[a,i]=c.useState(!1);return t?s.jsx("button",{type:"button",className:"copy-btn",title:n("copy"),onClick:()=>{navigator.clipboard.writeText(t).then(()=>{i(!0),setTimeout(()=>i(!1),1200)})},children:a?s.jsx(Lt,{}):s.jsx(Dt,{})}):null});function Wf(e){const t=a=>{if(typeof a=="string"||typeof a=="number"){const i=String(a);return i===""?[[]]:i.split(`
322
- `).map(o=>o===""?[]:[o])}if(Array.isArray(a)){let i=[];for(const o of a){const l=t(o);if(i.length===0)i=l;else{const u=l[0]??[];i[i.length-1].push(...u),i.push(...l.slice(1))}}return i}if(a&&typeof a=="object"&&"props"in a){const i=a,o=i.props?.children,l={...i.props,children:void 0},u=o==null?[]:t(o);return u.length===0?[[c.createElement(i.type,l)]]:u.map(p=>[c.createElement(i.type,l,...p)])}return[[a]]},n=t(e);return n.length>1&&n[n.length-1].length===0&&n.pop(),n}function Ya(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Ya).join("");if(e&&typeof e=="object"&&"props"in e){const t=e.props;return Ya(t?.children)}return""}function Kf(e){const t=Array.isArray(e)?e[0]:e;return!t||typeof t!="object"||!("props"in t)?null:t}function Yf(e){const n=Kf(e)?.props?.className;if(typeof n!="string")return null;const a=n.match(/(?:^|\s)language-([A-Za-z0-9_+\-]+)(?:\s|$)/);return a?a[1]:null}const jr="pi-web-ui:plugin-data";let $s=new Map,qs=new Map,gs=new Set,Ga=-1,Fl=0;const za=new Set;function Gf(){Fl++;for(const e of za)e()}function zf(e){return za.add(e),()=>{za.delete(e)}}function Rr(){return Fl}let Hl=null;function Vf(e){Hl=e}function Qf(e,t){t!==Ga&&(Ga=t,qs.clear(),gs.clear());const n=new Map;for(const i of e)if(!(i.error||!i.renderers))for(const o of i.renderers)n.has(o)||n.set(o,i.id);let a=n.size!==$s.size;if(!a){for(const[i,o]of n)if($s.get(i)!==o){a=!0;break}}if(a){for(const i of qs.keys())n.has(i)||qs.delete(i);for(const i of gs)n.has(i)||gs.delete(i);$s=n,Gf()}}async function Xf(e,t){const n=$s.get(e);if(!n)return null;let a=qs.get(e);if(!a&&!gs.has(e))try{const l=(await import(lt(`/plugins/${encodeURIComponent(n)}/client/entry.mjs?e=${Ga}`))).default?.renderers?.[e];typeof l=="function"?(a={pluginId:n,renderer:l},qs.set(e,a)):(gs.add(e),console.error(`[plugin:${n}] entry.mjs 未提供 renderers["${e}"]`))}catch(o){gs.add(e),console.error(`[plugin:${n}] renderer 加载失败(${e}):`,o)}if(!a)return null;const i={pluginId:a.pluginId,send:o=>{Hl?.({type:"plugin_message",pluginId:a.pluginId,payload:o})},onData:o=>{const l=u=>{const p=u.detail;p.pluginId===a.pluginId&&o(p.payload)};return window.addEventListener(jr,l),()=>window.removeEventListener(jr,l)}};try{const o=await a.renderer(t,i);return o instanceof HTMLElement?o:null}catch(o){return console.error(`[plugin:${a.pluginId}] renderer("${e}") 执行失败:`,o),null}}function Jf(e){return $s.has(e)}const Va="pi-web-ui:theme",Ul="dark",Lr="theme-stylesheet",zt="pi-web-ui:theme-change";function $l(){try{const e=localStorage.getItem(Va);if(e&&e!==Ul)return e}catch{}return null}function Zf(e){try{e?localStorage.setItem(Va,e):localStorage.removeItem(Va)}catch{}}function ql(e){let t=document.getElementById(Lr);if(!e){t?.remove(),window.dispatchEvent(new CustomEvent(zt));return}t||(t=document.createElement("link"),t.id=Lr,t.rel="stylesheet",document.head.appendChild(t)),t.href=lt(`/themes/${encodeURIComponent(e)}.css`),t.onload=()=>window.dispatchEvent(new CustomEvent(zt))}async function e0(){try{const e=await fetch(Ft(lt("/api/themes")));if(!e.ok)return[];const t=await e.json();return Array.isArray(t.themes)?t.themes:[]}catch{return[]}}function t0(){const[e,t]=c.useState([]),[n,a]=c.useState(()=>$l());return c.useEffect(()=>{let o=!1;return e0().then(l=>{o||t(l)}),()=>{o=!0}},[]),c.useEffect(()=>{ql(n),Zf(n)},[n]),{themes:e,theme:n,switchTheme:o=>a(o===Ul?null:o)}}function f1(){const e=getComputedStyle(document.documentElement),t=(n,a)=>e.getPropertyValue(n).trim()||a;return{background:t("--term-bg","#0b0d12"),foreground:t("--term-fg","#e6e8ef"),cursor:t("--term-cursor","#8b5cf6"),cursorAccent:t("--term-cursor-accent","#0b0d12"),selectionBackground:t("--term-selection","rgba(139, 92, 246, 0.35)"),black:t("--term-black","#1a1d26"),red:t("--term-red","#f87171"),green:t("--term-green","#34d399"),yellow:t("--term-yellow","#fbbf24"),blue:t("--term-blue","#60a5fa"),magenta:t("--term-magenta","#c084fc"),cyan:t("--term-cyan","#22d3ee"),white:t("--term-white","#e6e8ef"),brightBlack:t("--term-bright-black","#6b7284"),brightRed:t("--term-bright-red","#f87171"),brightGreen:t("--term-bright-green","#34d399"),brightYellow:t("--term-bright-yellow","#fbbf24"),brightBlue:t("--term-bright-blue","#60a5fa"),brightMagenta:t("--term-bright-magenta","#c084fc"),brightCyan:t("--term-bright-cyan","#22d3ee"),brightWhite:t("--term-bright-white","#ffffff")}}function s0({lang:e,code:t}){const n=c.useRef(null),a=c.useRef(null),i=c.useRef(0),o=c.useRef(new WeakMap),[l,u]=c.useState(null);return c.useEffect(()=>{const p=()=>{const h=++i.current,b=a.current;b&&(b.dispatchEvent(new CustomEvent(zt)),o.current.set(b,h))};return window.addEventListener(zt,p),()=>window.removeEventListener(zt,p)},[]),c.useEffect(()=>{let p=!1;const h=i.current;return u(null),Xf(e,t).then(b=>{p||(b&&o.current.set(b,h),u(b))}),()=>{p=!0}},[e,t]),c.useEffect(()=>{a.current=l;const p=n.current;return p&&(p.replaceChildren(),l&&(p.appendChild(l),(o.current.get(l)??i.current)<i.current&&(l.dispatchEvent(new CustomEvent(zt)),o.current.set(l,i.current)))),()=>{a.current===l&&(a.current=null)}},[l]),l?s.jsx("div",{className:"plugin-fence",ref:n}):s.jsxs("div",{className:"codeblock",children:[s.jsx(Hn,{text:t}),s.jsx("pre",{children:s.jsx("code",{children:t})})]})}const n0=[go,bo],a0=[go,Bp,bo],Dr=[[ou,{strict:!1,throwOnError:!1}],[lu,{detect:!0,ignoreMissing:!0}]];function mi({text:e,rawHtml:t=!1,hardBreaks:n=!1}){const a=t?[qf,...Dr]:Dr;return s.jsx(ru,{remarkPlugins:n?a0:n0,rehypePlugins:a,components:{pre:r0,a:i0},children:e})}const dt=c.memo(function({text:t,rawHtml:n=!1,hardBreaks:a=!1}){return s.jsx("div",{className:"md",children:s.jsx(mi,{text:t,rawHtml:n,hardBreaks:a})})});function i0({href:e,children:t,...n}){const a=String(e??"");return/^(https?:|mailto:|tel:)/i.test(a)?s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",...n,children:t}):s.jsx("a",{href:e,...n,children:t})}function r0({children:e,...t}){c.useSyncExternalStore(zf,Rr,Rr);const n=Yf(e);return n&&Jf(n)?s.jsx(s0,{lang:n,code:Ya(e)}):s.jsx(o0,{children:e,...t})}function o0({children:e,...t}){const n=e&&typeof e=="object"&&"props"in e?e.props?.children:e,a=Wf(n),i=a.length>1,o=i?`${String(a.length).length+1}ch`:void 0;return s.jsxs("div",{className:"codeblock",children:[s.jsx(Hn,{text:Qa(e)}),s.jsx("pre",{...t,children:a.map((l,u)=>s.jsxs("div",{className:"code-line",children:[i&&s.jsx("span",{className:"code-num",style:o?{width:o}:void 0,children:u+1}),s.jsx("code",{className:"code-line-body hljs",children:l})]},u))})]})}function Qa(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Qa).join("");if(e&&typeof e=="object"&&"props"in e){const t=e.props;return Qa(t?.children)}return""}const l0=/^\s{0,3}(`{3,}|~{3,})/,c0=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function xa(e){return e.trim()===""}function Pr(e){const t=l0.exec(e);return t?t[1]:null}function u0(e){const t=e.split(`
323
- `),n=[];let a=[],i=null;for(let o=0;o<t.length;o++){const l=t[o];if(i!==null){const p=Pr(l);p&&p[0]===i[0]&&p.length>=i.length&&(i=null),a.push(l);continue}const u=Pr(l);if(u&&!xa(l)){i=u,a.push(l);continue}if(xa(l)){let p=o;for(;p<t.length&&xa(t[p]);)p++;if(!(p<t.length&&c0.test(t[p]))&&a.length>0){n.push(a.join(`
316
+ It only opens after you confirm.`,settingsExtensions:"Extensions",settingsUiPlugins:"UI plugins",noUiPlugins:"No UI plugins installed (<dataDir>/plugins/)",dshPatches:"DSH user patches",dshPatchesDesc:"Cordis patches loaded at runtime boot, in filename order (<dataDir>/dsh-patches/*.yml). New/edited files take effect after 'Rescan' restarts the runtime; broken files are skipped and logged to runtime stderr.",dshPatchesRescan:"Rescan",dshPatchesRescanHint:"Re-scan the patch directory and restart the DSH runtime so new patches take effect",dshPatchesEmpty:"No patch files yet",dshPatchesPath:"Patch directory: ",uiPluginNoSource:"Installed manually — no recorded source, online update unavailable",uiPluginPerms:"Permissions",pluginSettingsSave:"Save plugin settings",pluginSettingsSaving:"Saving…",pluginSettingsReset:"Reset defaults",settingsPresets:"Presets",settingsSubagentTemplates:"Subagent templates",settingsSubagentTemplatesDesc:"Presets for spawned subagents (role system prompt + skills/extensions whitelist + optional model and thinking level). AI may pick a template (subagent_spawn template param) or spawn without one; disabled templates stay in the panel but are invisible to AI tools.",noSubagentTemplates:"No subagent templates yet. AI can pick a template when spawning a subagent (role prompt + skills/extensions whitelist + optional model and thinking level), or spawn without a template param for default config.",subagentTemplateNew:"New template",subagentTemplateEdit:"Edit",subagentTemplateClosed:"Disabled",tplDefaultBadge:"Built-in",subagentDefaultModelLabel:"Default subagent model",subagentFollowMain:"Follow the main conversation's current model",subagentDefaultModelHint:"Fallback model for all subagents (a template's own model and the subagent_spawn model param take priority); does not change the main conversation's model.",subagentNoModels:"No usable models yet (configure a provider API key first) — subagents will follow the main conversation's model.",subagentTemplateOffHint:"Disabled templates stay in the panel and can be re-enabled, but AI tools can't see or pick them",subagentTemplateEnable:"Enable",subagentTemplateDisable:"Disable",tplNamePlaceholder:"Template name (referenced by AI via subagent_spawn's template param)…",tplDescriptionPlaceholder:"Description (AI uses it to judge when to pick this template)…",tplDescriptionEnPlaceholder:"English description (shown to AI under English UI; falls back to the description above)…",tplPromptModeLabel:"System prompt mode",tplModelLabel:"Model (empty = follow main conversation)",tplThinkingLabel:"Thinking level",tplThinkingFollowMain:"Follow the main conversation's current thinking level",tplThinkingHint:"Empty = follow the main conversation's current thinking level (same idea as the model fallback); unsupported levels are clamped to the nearest one the model supports.",tplSystemPromptLabel:"System prompt",tplSystemPromptPlaceholder:"Template role system prompt… (may be empty in append mode)",tplSystemPromptEnPlaceholder:"English system prompt… (used under English UI; falls back to the prompt above)",tplWhitelistHint:"Whitelist: checked = the subagent only gets these; none checked = follow the main session settings",tplSkillsLabel:"Skills whitelist",tplExtensionsLabel:"Extensions whitelist",tplSave:"Save template",tplCancel:"Cancel edit",tplDelete:"Delete template",tplInherit:"Follow main session",settingsEnabled:"Enabled",settingsDisabled:"Disabled",presetNamePlaceholder:"Preset name…",saveAsPreset:"Save as preset",applyPreset:"Apply",deletePreset:"Delete preset",noSkills:"No skills",noExtensions:"No extensions",noPresets:"No presets yet (tune the settings above, then save them as a preset)",loadingSession:"Loading session…",connectingServer:"Connecting to pi-web-ui server…",localePacks:"Language packs",localeGetMore:"Get more languages",localeInstalled:"Installed",localeInstall:"Download",localeRemove:"Remove",localeDownloading:"Downloading…",localeRemoving:"Removing…",localeInstallFailed:"Download failed: {error}",localeListFailed:"Couldn't load language packs: {error}",localeRemoveHint:"You can re-download it anytime",wallpaperTitle:"Chat wallpaper",wallpaperDesc:"Show a full-window background image (side panels, top and bottom bars included): a theme-provided image applies automatically, a URL here takes precedence; use dim and blur to keep text readable.",wallpaperUrlPh:"Image URL (https://…, empty = off)",wallpaperDim:"Dim",wallpaperBlur:"Blur",wallpaperClear:"Clear",wallpaperUpload:"Upload image",wallpaperUploadFailed:"Couldn't read the image (or it's too big) — try another one",skillFullTextLabel:"Inject full skill text",skillFullTextDesc:"Expand skill file contents inline into the system prompt (8KB per file, 32KB total cap); otherwise only a catalog is listed and the model reads files on demand",skillFullTextShort:"Full",delegateOpenSubagent:"Open subagent",delegateSecTask:"Task",delegateSecExpected:"Expected outcome",delegateSecTools:"Required tools",delegateSecMustDo:"Must do",delegateSecMustNotDo:"Must not do",delegateSecContext:"Context"},sd=[{code:"zh",nativeName:"中文"},{code:"en",nativeName:"English"}],Ds={};function nd(e){return!e||typeof e.code!="string"||!e.code||e.code==="zh"||e.code==="en"||!e.strings||typeof e.strings!="object"?!1:(Ds[e.code]=e,!0)}function ad(e){delete Ds[e]}function id(e){return e==="zh"?"中文":e.toUpperCase()}function rd(e){return e==="zh"?"zh-CN":e==="pt"?"pt-BR":e}async function Mi(e){const t=await fetch(Ft(lt(e)));if(!t.ok)throw new Error(`HTTP ${t.status} for ${e}`);return await t.json()}const Lo=c.createContext(null);function Do(){try{return localStorage.getItem(Pa)}catch{return null}}function od(){return Da(Do(),typeof navigator<"u"?navigator.languages:[],null)}function ld({children:e}){const[t,n]=c.useState(od),[a,i]=c.useState(0),o=c.useRef(t);o.current=t;const l=c.useCallback(m=>{n(m);try{localStorage.setItem(Pa,m)}catch{}try{window.dispatchEvent(new CustomEvent("pi-web-ui:locale",{detail:m}))}catch{}},[]),u=c.useCallback(async()=>{let m,f=null;try{const x=await Mi("/api/locales");m=x.packs??[],f=x.defaultLocale??null}catch{return null}return await Promise.all(m.filter(x=>x.installed).map(async x=>{try{const v=await Mi(`/api/locales/${x.code}`);nd({code:v.code||x.code,nativeName:v.nativeName||x.nativeName,strings:v.strings})}catch{}})),i(x=>x+1),f},[]);c.useEffect(()=>{u().then(m=>{if(!Do()?.trim()){const x=Da(null,typeof navigator<"u"?navigator.languages:[],m);x!==o.current&&(o.current=x,n(x))}const f=o.current;if(f!=="zh"&&f!=="en"&&!Ds[f]){const x=Da(null,typeof navigator<"u"?navigator.languages:[],m,["zh","en"]);o.current=x,n(x);try{localStorage.setItem(Pa,x)}catch{}}})},[u]);const p=c.useMemo(()=>[...sd,...Object.values(Ds).map(m=>({code:m.code,nativeName:m.nativeName}))],[a]),h=c.useCallback((m,f)=>{let x=Ds[t]?.strings[m]??(t==="zh"?ed[m]:td[m]);if(f)for(const[v,N]of Object.entries(f))x=x.replaceAll(`{${v}}`,String(N));return x},[t,a]);c.useEffect(()=>{document.documentElement.lang=rd(t)},[t]);const b=c.useMemo(()=>({locale:t,setLocale:l,t:h,packs:p,reloadPacks:u}),[t,l,h,p,u]);return s.jsx(Lo.Provider,{value:b,children:e})}function Ut(){const e=c.useContext(Lo);if(!e)throw new Error("useI18n must be used within LanguageProvider");return e}function Pe(){return Ut().t}const cd=[{kind:"question",labelKey:"sound.question",descKey:"sound.question.desc"},{kind:"done",labelKey:"sound.done",descKey:"sound.done.desc"},{kind:"start",labelKey:"sound.start",descKey:"sound.start.desc"},{kind:"error",labelKey:"sound.error",descKey:"sound.error.desc"}];function Bi({settings:e,onChange:t,onPreview:n}){const a=Pe(),i=o=>t({...e,...o});return s.jsxs("div",{className:"sound-menu",children:[s.jsx("div",{className:"dd-header",children:a("soundHeader")}),s.jsxs("label",{className:"sound-row sound-master",children:[s.jsxs("span",{className:"sound-label",children:[s.jsx(No,{className:"sound-icon"}),s.jsx("span",{children:a("enableSound")})]}),s.jsx("input",{type:"checkbox",checked:e.enabled,onChange:o=>i({enabled:o.target.checked})})]}),cd.map(({kind:o,labelKey:l,descKey:u})=>s.jsxs("label",{className:`sound-row ${e.enabled?"":"disabled"}`,children:[s.jsxs("span",{className:"sound-label",children:[s.jsx("span",{className:"sound-name",children:a(l)}),s.jsx("span",{className:"sound-desc",children:a(u)})]}),s.jsxs("span",{className:"sound-right",children:[s.jsx("button",{type:"button",className:"sound-preview",title:a("preview"),disabled:!e.enabled,onClick:p=>{p.preventDefault(),n(o)},children:a("preview")}),s.jsx("input",{type:"checkbox",checked:e[o],disabled:!e.enabled,onChange:p=>i({[o]:p.target.checked})})]})]},o)),s.jsxs("div",{className:`sound-volume ${e.enabled?"":"disabled"}`,children:[s.jsx("span",{className:"sound-name",children:a("volume")}),s.jsx("input",{type:"range",min:0,max:100,step:5,value:e.volume,disabled:!e.enabled,onChange:o=>i({volume:Number(o.target.value)})}),s.jsxs("span",{className:"sound-vol-num",children:[e.volume,"%"]})]})]})}function Po(e){const t=typeof window>"u"?void 0:window;if(!t)return!1;if(t.piDesktop?.isDesktop===!0)return!0;const n=t.navigator?.userAgent;return typeof n=="string"&&n.includes("Electron/")}const ud="https://github.com/xing-shuyin/pi-web-ui/releases/latest/download/page-picker-extension.zip",Oo=()=>window.__piWebUiHost?.pageCall?.bind(window.__piWebUiHost);async function dd(){if(Po())return{available:!1,pages:[],desktop:!0,error:"桌面版不支持浏览器操作:窗口里没有 Chrome 扩展运行时,请改用系统浏览器打开同一个地址(网页版)"};const e=Oo();if(!e)return{available:!1,pages:[],error:"宿主页面桥不可用:这个 pi-web-ui 页面还没装上扩展桥(装/启用 page-picker 后刷新本页)"};try{const t=await e({op:"status",timeoutMs:5e3});if(!t.ok)return{available:!1,pages:[],error:t.error??"扩展没有返回状态"};const n=t.result??{};return{available:n.installed===!0,aiControl:n.aiControl===!0,allowEval:n.allowEval===!0,pages:Array.isArray(n.pages)?n.pages:[]}}catch(t){return{available:!1,pages:[],error:t instanceof Error?t.message:String(t)}}}function pd(e){return e.length===1?e[0]:null}function md(e){return{path:e.origin,name:e.title?.trim()||e.origin,mode:"page",key:`page:${e.origin}`}}async function hd(){const e=Oo();if(!e)return!1;try{return(await e({op:"openOptions",timeoutMs:5e3})).ok===!0}catch{return!1}}function fd(e=45e3){const[t,n]=c.useState(null),a=c.useRef(!0),i=c.useCallback(async o=>{const l=await dd();a.current&&(n(l),o&&!l.available&&setTimeout(()=>{a.current&&i(!1)},1500))},[]);return c.useEffect(()=>{a.current=!0,i(!0);const o=setInterval(()=>void i(!1),Math.max(5e3,e));return()=>{a.current=!1,clearInterval(o)}},[i,e]),{status:t,refresh:()=>void i(!0)}}let Ln=null,Dn=null;function Fi(e){Ln=e}function Hi(e){Dn=e}function gd(){return!!(Ln||Dn)}function Mo(e){const t=typeof e?.text=="string"?e.text:"",n=Array.isArray(e?.attachments)?e.attachments:[],a=t.trim()!=="",i=n.length>0;return!a&&!i||a&&!Ln||i&&!Dn?!1:(i&&Dn?.(n),a&&Ln?.(t),!0)}function bd(){const e=Pe(),{status:t,refresh:n}=fd(),[a,i]=c.useState(!1),[o,l]=c.useState(null),u=c.useRef(null),p=t?.pages??[],h=t?.available===!0&&(p.length===0||t.aiControl===!1),b=pd(p),m=v=>{l(v),u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>l(null),2600)},f=v=>{const N=Mo({attachments:[md(v)]});m(e(N?"browserControlCited":"browserControlCiteFailed"))},x=()=>{i(!0),n()};return s.jsxs("span",{className:"bc-anchor",children:[b?s.jsxs("span",{className:"browser-control-split",children:[s.jsxs("button",{type:"button",className:`chip browser-control single${h?" attention":""}`,title:e("browserControlSingleTip",{name:b.title||b.origin}),onClick:()=>f(b),children:[s.jsx(Ia,{size:14,"aria-hidden":!0}),s.jsx("span",{className:"bc-chip-label",children:b.title||b.origin})]}),s.jsx("button",{type:"button",className:"chip browser-control caret",title:e("browserControlOpenPanel"),"aria-label":e("browserControlOpenPanel"),onClick:x,children:"▾"})]}):s.jsxs("button",{type:"button",className:`chip browser-control${h?" attention":""}`,title:t?.error??e(h?"browserControlEmpty":"browserControlTip"),onClick:x,children:[s.jsx(Ia,{size:14,"aria-hidden":!0}),s.jsxs("span",{children:[e("browserControl"),p.length>0?` · ${p.length}`:""]})]}),o&&s.jsx("span",{className:"bc-flash",children:o}),a&&s.jsx(Ed,{status:t,onRefresh:n,onCite:f,onClose:()=>i(!1)})]})}function Ed({status:e,onRefresh:t,onCite:n,onClose:a}){const i=Pe(),[o,l]=c.useState(!1),u=e?.pages??[],p=async()=>{l(!0);try{await hd()||t()}finally{l(!1)}};return s.jsx("div",{className:"modal-backdrop",onClick:a,children:s.jsxs("div",{className:"modal browser-control-modal",onClick:h=>h.stopPropagation(),children:[s.jsx("button",{type:"button",className:"modal-close","aria-label":i("close"),onClick:a,children:"✕"}),s.jsxs("div",{className:"modal-head",children:[s.jsx(Ia,{size:16,"aria-hidden":!0}),s.jsx("h2",{children:i("browserControl")})]}),s.jsx("div",{className:"modal-desc",children:i("browserControlTip")}),e===null&&s.jsx("div",{className:"bc-note",children:i("browserControlChecking")}),e?.available===!1&&!e.desktop&&s.jsx("div",{className:"bc-note warn",children:i("browserControlOffline")}),e?.desktop===!0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"bc-note warn",children:i("browserControlDesktop")}),s.jsx("div",{className:"bc-note",children:i("browserControlDesktopLead")}),s.jsx("div",{className:"bc-actions",style:{marginTop:0},children:s.jsx("a",{className:"btn primary",href:window.location.href,target:"_blank",rel:"noreferrer noopener",children:i("browserControlOpenInBrowser")})})]}),e?.available===!1&&!e.desktop&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"bc-section",children:i("browserControlInstall")}),s.jsx("div",{className:"bc-note",children:i("browserControlInstallLead")}),s.jsx("div",{className:"bc-actions",style:{marginTop:0},children:s.jsx("a",{className:"btn primary",href:ud,target:"_blank",rel:"noreferrer noopener",children:i("browserControlInstallDownload")})}),s.jsxs("ol",{className:"bc-steps",children:[s.jsx("li",{children:i("browserControlInstallStep1")}),s.jsx("li",{children:i("browserControlInstallStep2")}),s.jsx("li",{children:i("browserControlInstallStep3")}),s.jsx("li",{children:i("browserControlInstallStep4")})]})]}),e?.available===!0&&e.aiControl===!1&&s.jsx("div",{className:"bc-note warn",children:i("browserControlDisabled")}),e?.available===!0&&u.length===0&&s.jsx("div",{className:"bc-note warn",children:i("browserControlEmpty")}),u.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"bc-section",children:i("browserControlPages")}),s.jsx("ul",{className:"bc-pages",children:u.map(h=>s.jsxs("li",{children:[s.jsx("span",{className:"bc-title",title:h.title,children:h.title}),s.jsx("span",{className:"bc-origin",title:h.origin,children:h.origin}),s.jsx("span",{className:`bc-open${h.open?" on":""}`,children:h.open?i("browserControlPageOpen"):i("browserControlPageClosed")}),s.jsx("button",{type:"button",className:"bc-cite",title:i("browserControlCiteTip",{name:h.title||h.origin}),onClick:()=>n(h),children:i("browserControlCite")})]},h.origin))}),s.jsx("div",{className:"bc-note",children:i("browserControlCiteNote")})]}),e?.desktop!==!0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"bc-section",children:i("browserControlExamples")}),s.jsxs("ul",{className:"bc-examples",children:[s.jsx("li",{children:i("browserControlExample1")}),s.jsx("li",{children:i("browserControlExample2")})]})]}),s.jsxs("div",{className:"bc-actions",children:[e?.desktop!==!0&&s.jsx("button",{type:"button",className:"primary",disabled:o,onClick:()=>void p(),children:i("browserControlOpenOptions")}),s.jsx("button",{type:"button",onClick:t,children:i("browserControlRefresh")})]})]})})}const Bo=["terminal_create","terminal_list","terminal_close","terminal_input","terminal_key","terminal_read","terminal_wait"],Fo=["subagent_spawn","subagent_get_result","subagent_steer","subagent_list","subagent_stop","subagent_wait_all","subagent_templates"],hn="edit_soft",fn="delegate_task",gn="ask_user_question",bn="todo_list",Ps="browser_page",Td=[...Bo.map(e=>({name:e,group:"terminal",defaultOn:!1,dshVisible:!0})),...Fo.map(e=>({name:e,group:"subagent",defaultOn:!0,dshVisible:!1})),{name:hn,group:"other",defaultOn:!1,dshVisible:!1},{name:fn,group:"other",defaultOn:!0,dshVisible:!1},{name:gn,group:"other",defaultOn:!0,dshVisible:!0},{name:bn,group:"other",defaultOn:!0,dshVisible:!0},{name:Ps,group:"other",defaultOn:!1,dshVisible:!1}];new Set(Td.map(e=>e.name));const Ho="pi-web-notify",ha={enabled:!1};function Uo(){try{const e=localStorage.getItem(Ho);if(!e)return{...ha};const t=JSON.parse(e);return{enabled:typeof t.enabled=="boolean"?t.enabled:ha.enabled}}catch{return{...ha}}}function Ui(e){try{localStorage.setItem(Ho,JSON.stringify(e))}catch{}}function Qs(){return typeof window<"u"&&"Notification"in window}function xd(){return Qs()?null:typeof window<"u"&&window.isSecureContext===!1?"insecure":"unsupported"}const yd=12e4;function kd(e){const{screenX:t,screenY:n,outerWidth:a,outerHeight:i}=e;return Number.isFinite(t)&&$i(t)||Number.isFinite(n)&&$i(n)?!0:a>0&&a<=400&&i>0&&i<=40}function $i(e){return e<=-1e4}function Nd(e){return!(e.visibility!=="visible"||e.minimized||!e.hasFocus||e.windows&&e.idleMs>yd)}let $o=Date.now(),qi=!1;function Wi(){$o=Date.now()}function vd(){return Math.max(0,Date.now()-$o)}function Cd(){if(qi||typeof window>"u")return;qi=!0;const e={passive:!0,capture:!0};for(const t of["pointerdown","pointermove","keydown","wheel","touchstart","focus","scroll"])window.addEventListener(t,Wi,e);typeof document<"u"&&document.addEventListener("visibilitychange",Wi,e)}function qo(){return typeof navigator>"u"?!1:/windows/i.test(navigator.userAgent??"")}function wd(){return Cd(),typeof window>"u"||typeof document>"u"?{hasFocus:!0,visibility:"visible",minimized:!1,idleMs:0,windows:!1}:{hasFocus:typeof document.hasFocus=="function"?document.hasFocus():!0,visibility:document.visibilityState??"",minimized:kd({screenX:window.screenX,screenY:window.screenY,outerWidth:window.outerWidth,outerHeight:window.outerHeight}),idleMs:vd(),windows:qo()}}function Ki(){return Qs()?Notification.permission:"denied"}async function Sd(){if(!Qs())return"denied";try{return await Notification.requestPermission()}catch{return"denied"}}function Yi(e){return e instanceof Error?`${e.name}: ${e.message}`:String(e)}function _d(e,t=!1){return{body:e,requireInteraction:t,icon:lt("/icons/icon-192.png"),badge:lt("/icons/icon-192.png"),data:{url:typeof location<"u"?location.href:lt("/")}}}async function Ad(e,t,n=!1){if(!Qs())return{path:"none",error:"unsupported"};if(Notification.permission!=="granted")return{path:"none",error:`permission: ${Notification.permission}`};const a=_d(t,n);let i;try{const o=await navigator.serviceWorker?.getRegistration();if(o?.active&&typeof o.showNotification=="function")return await o.showNotification(e,a),{path:"sw"};i=o?"service worker not active":"no service worker registration"}catch(o){i=Yi(o)}try{return new Notification(e,a),{path:"page",error:i}}catch(o){return{path:"none",error:`${i}; page: ${Yi(o)}`}}}async function cn(e,t){Qs()&&(Nd(wd())||Uo().enabled&&await Ad(e,t))}const Id=!1;function Gi(){const e=Pe(),[t,n]=c.useState(Uo),[a,i]=c.useState(()=>Ki()),[o,l]=c.useState(null),u=xd(),p=u!==null,h=qo();c.useEffect(()=>{const m=()=>i(Ki());return window.addEventListener("focus",m),document.addEventListener("visibilitychange",m),()=>{window.removeEventListener("focus",m),document.removeEventListener("visibilitychange",m)}},[]);const b=async m=>{const f={...t,enabled:m};if(n(f),Ui(f),m){const x=await Sd();if(i(x),x!=="granted"){const v={...f,enabled:!1};n(v),Ui(v)}}};return s.jsxs("div",{className:"sound-menu notify-menu",children:[s.jsx("div",{className:"dd-header",children:e("notifyHeader")}),s.jsxs("label",{className:`sound-row sound-master${p?" disabled":""}`,children:[s.jsxs("span",{className:"sound-label",children:[s.jsx(Wu,{className:"sound-icon"}),s.jsx("span",{children:e("notifyEnable")})]}),s.jsx("input",{type:"checkbox",checked:t.enabled&&!p,disabled:p,onChange:m=>b(m.target.checked)})]}),s.jsx("div",{className:"sound-hint",children:e("notifyEnableDesc")}),u==="insecure"&&s.jsx("div",{className:"sound-hint",children:e("notifyInsecure")}),u==="unsupported"&&s.jsx("div",{className:"sound-hint",children:e("notifyUnsupported")}),!p&&a==="denied"&&s.jsx("div",{className:"sound-hint",children:e("notifyDenied")}),!p&&h&&s.jsx("div",{className:"sound-hint",children:e("notifyWindowsHint")}),Id]})}let Pn=null;const Oa=new Set;function Wo(){for(const e of Oa)e()}function ea(e){Pn={x:Number.isFinite(e.x)?e.x:0,y:Number.isFinite(e.y)?e.y:0,slot:e.slot,target:e.target??{id:""},entries:Array.isArray(e.entries)?e.entries:[],...typeof e.onHostAction=="function"?{onHostAction:e.onHostAction}:{}},Wo()}function qt(){Pn!==null&&(Pn=null,Wo())}function jd(e){return Oa.add(e),()=>{Oa.delete(e)}}function zi(){return Pn}function Rd(){return c.useSyncExternalStore(jd,zi,zi)}const Ot=8;function ls(e){return Number.isFinite(e)?e:0}function Ld(e,t,n,a,i,o){const l=Math.max(0,ls(n)),u=Math.max(0,ls(a)),p=Math.max(Ot,ls(i)-l-Ot),h=Math.max(Ot,ls(o)-u-Ot);return{x:Math.min(Math.max(Ot,ls(e)),p),y:Math.min(Math.max(Ot,ls(t)),h)}}function En(e){return e?(e.when??[]).some(n=>n==="disabled"||typeof n=="string"&&n.startsWith("!")):!0}function On(e){if(!Array.isArray(e)||e.length===0)return[];const t=e.filter(m=>m&&m.hidden!==!0),n=t.filter(m=>m.kind!=="divider"),a=new Map,i=new Map;n.forEach((m,f)=>{const x=m.group??"";a.has(x)||a.set(x,f);const v=Number.isFinite(m.order)?m.order:100,N=i.get(x);(N===void 0||v<N)&&i.set(x,v)});const o=[...a.keys()].sort((m,f)=>{const x=i.get(m)??100,v=i.get(f)??100;return x!==v?x-v:(a.get(m)??0)-(a.get(f)??0)}),l=new Map(o.map((m,f)=>[m,f])),u=new Map;n.forEach((m,f)=>u.set(m,f));const p=[...n].sort((m,f)=>{const x=l.get(m.group??"")??0,v=l.get(f.group??"")??0;if(x!==v)return x-v;const N=Number.isFinite(m.order)?m.order:100,B=Number.isFinite(f.order)?f.order:100;return N!==B?N-B:(u.get(m)??0)-(u.get(f)??0)}),h=new Map;t.forEach((m,f)=>{if(m.kind!=="divider")return;const x=t.slice(f+1).find(N=>N.kind!=="divider");if(!x)return;const v=h.get(x)??[];v.push(m),h.set(x,v)});const b=[];for(const m of p){for(const f of h.get(m)??[])b.push(f);b.push(m)}return b}function Vi(e){const t=[];let n=null,a=!1;return e.forEach((i,o)=>{if(!i||i.kind==="divider"){a=!0;return}const l=i.group??"";n!==null&&(a||l!==n)&&t.push({kind:"sep",key:`sep:${o}`}),t.push({kind:"item",key:`${i.id}#${o}`,index:o,entry:i}),n=l,a=!1}),t}function Dd(e){return!e||e.kind==="divider"||e.hidden===!0?!1:!En(e)}function Qi(e,t,n){const a=Array.isArray(e)?e.length:0;if(a===0)return-1;const i=n>=0?1:-1;let o=Number.isFinite(t)?Math.trunc(t):-1;(o<0||o>=a)&&(o=i>0?-1:a);for(let l=0;l<a;l++)if(o=(o+i+a)%a,Dd(e[o]))return o;return-1}const Pd={menu:"☰",folder:"📁",plus:"+",chat:"💬",terminal:"▙",git:"⎇",search:"🔍",browser:"🌐",layers:"🗂",settings:"⚙",sound:"🔊",globe:"🌍",sun:"☀",download:"⤓",github:"⌗",x:"✕",upload:"⬆",copy:"⧉",edit:"✎",dot:"●",cpu:"▣",gauge:"▤",coins:"◉",database:"▥",message:"✉",activity:"〜"};function Od(e){const t=(e??"").trim();if(!t)return"";const n=Pd[t.toLowerCase()];return n||(/[^\p{L}\p{N}\s]/u.test(t)&&t.length<=4?t:"")}const Md={engine:"pi",managed:!1,status:"connecting",ready:!1,cwd:"",workspaceRoots:[]};let hs=Md;const Ma=new Set;function Xi(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,a)=>n===t[a])}function Bd(e,t){return e.engine===t.engine&&e.managed===t.managed&&e.appVersion===t.appVersion&&e.serverVersion===t.serverVersion&&e.status===t.status&&e.ready===t.ready&&e.cwd===t.cwd&&Xi(e.workspaceRoots,t.workspaceRoots)&&Xi(e.tabs,t.tabs)&&e.service?.name===t.service?.name&&e.service?.supervisor===t.service?.supervisor}function Ji(e){const t={...hs,...e};if(!Bd(hs,t)){hs=t;for(const n of Ma)n()}}function Ko(e){return Ma.add(e),()=>{Ma.delete(e)}}function Zi(){return hs}function oi(){return c.useSyncExternalStore(Ko,Zi,Zi)}function wt(e){return c.useSyncExternalStore(Ko,()=>hs[e],()=>hs[e])}function Yo(){return wt("engine")==="dsh"}function Go(){return wt("managed")}function Fd(){return wt("service")}let Ba=null;function Hd(e){Ba=e}const ie=e=>Ba?Ba(e):!1;function Ud({onClose:e}){const t=Pe(),{locale:n,setLocale:a,reloadPacks:i}=Ut(),[o,l]=c.useState(null),[u,p]=c.useState(""),[h,b]=c.useState("");async function m(){try{const v=await fetch(Ft(lt("/api/locales")));if(!v.ok)throw new Error(`HTTP ${v.status}`);const N=await v.json();l(N.packs??[]),p("")}catch(v){p(t("localeListFailed",{error:v instanceof Error?v.message:String(v)}))}}c.useEffect(()=>{m()},[]);async function f(v){b(v),p("");try{const N=await fetch(Ft(lt(`/api/locales/${v}/install`)),{method:"POST"});if(!N.ok){let B=`HTTP ${N.status}`;try{B=(await N.json()).error??B}catch{}throw new Error(B)}await i(),await m()}catch(N){p(t("localeInstallFailed",{error:N instanceof Error?N.message:String(N)}))}finally{b("")}}async function x(v){b(v),p("");try{const N=await fetch(Ft(lt(`/api/locales/${v}`)),{method:"DELETE"});if(!N.ok)throw new Error(`HTTP ${N.status}`);ad(v),n===v&&a("zh"),await i(),await m()}catch(N){p(t("localeInstallFailed",{error:N instanceof Error?N.message:String(N)}))}finally{b("")}}return s.jsx("div",{className:"modal-backdrop",onClick:e,children:s.jsxs("div",{className:"bg-task-modal",onClick:v=>v.stopPropagation(),children:[s.jsxs("div",{className:"bg-task-head",children:[s.jsxs("span",{className:"bg-task-title",children:[s.jsx(Co,{})," ",t("localePacks")]}),s.jsx("button",{type:"button",className:"btn",title:t("close"),onClick:e,children:s.jsx(tt,{})})]}),u&&s.jsx("div",{className:"bg-task-empty",children:u}),o===null&&!u?s.jsx("div",{className:"bg-task-empty",children:t("loading")}):s.jsx("ul",{className:"bg-task-list",children:(o??[]).map(v=>{const N=h===v.code;return s.jsxs("li",{className:"bg-task-item",children:[s.jsxs("div",{className:"bg-task-info",children:[s.jsxs("div",{className:"bg-task-line1",children:[s.jsx("span",{className:"bg-task-port",children:v.nativeName}),v.installed&&v.version&&s.jsxs("span",{className:"bg-task-name",children:["v",v.version]})]}),s.jsxs("div",{className:"bg-task-line2",children:[s.jsx("span",{children:v.code}),v.installed?s.jsxs("span",{children:[t("localeInstalled")," · ",t("localeRemoveHint")]}):s.jsx("span",{children:t("localeGetMore")})]})]}),v.installed?s.jsxs("button",{type:"button",className:"btn bg-task-stop",disabled:N,title:t("localeRemove"),onClick:()=>void x(v.code),children:[s.jsx(dt,{}),s.jsx("span",{children:t(N?"localeRemoving":"localeRemove")})]}):s.jsxs("button",{type:"button",className:"btn",disabled:N,title:t("localeInstall"),onClick:()=>void f(v.code),children:[s.jsx(ss,{}),s.jsx("span",{children:t(N?"localeDownloading":"localeInstall")})]})]},v.code)})}),s.jsx("div",{className:"bg-task-foot",children:s.jsxs("button",{type:"button",className:"btn",title:t("bgTaskRefresh"),onClick:()=>void m(),children:[s.jsx(jt,{}),s.jsx("span",{children:t("bgTaskRefresh")})]})})]})})}function $d({chat:e,terminal:t,view:n,plugins:a,uiPrimary:i,uiOverflow:o,uiContextTopbar:l,onUiAction:u,onViewChange:p,onOpenPanel:h,onOpenSettings:b,onOpenBgTasks:m,onOpenGlobalSearch:f,sound:x,onSoundChange:v,onSoundPreview:N,themes:B,theme:V,onThemeChange:W,reloadThemes:I}){const{locale:j,setLocale:X,t:w,packs:ce}=Ut(),[be,$]=c.useState(!1),K=4,J=new Set((i??[]).filter(R=>R.source==="host").map(R=>R.id)),L=(i??[]).filter(R=>R.source!=="host"),H=L.slice(0,K),T=[...L.slice(K),...o??[]],F=R=>z(R)&&(i===void 0||J.has(`host:${R}`)),Y=R=>{if(R.source!=="host")return!1;switch(R.id){case"host:history":return h("left"),!0;case"host:files":return h("right"),!0;case"host:new-chat":return ie({type:"new_chat"}),!0;case"host:search":return f(),!0;case"host:tasks":return m(),!0;case"host:settings":return b(),!0;default:return!1}},D=(R,He,C)=>{R.preventDefault(),ea({x:R.clientX,y:R.clientY,slot:"contextmenu.topbar",target:{id:He,label:C},entries:l??[]})},{appVersion:ae}=oi(),ee=Go(),ve=Fd(),[S,de]=c.useState(!1);c.useEffect(()=>{S&&e.status==="open"&&de(!1)},[S,e.status]);const[ue,pe]=c.useState(!1),[ke,Oe]=c.useState(!1),[ye,we]=c.useState(!1),[Ce,qe]=c.useState(!1),[Be,se]=c.useState(!1),[Te,De]=c.useState(!1),Re=e.ready?w("connected"):e.status==="closed"?w("reconnecting"):w("connecting"),Ye=e.ready?"ok":"busy",A=()=>{if(!e.ready)return;const R=w("updateTabTitle"),He={name:R,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},C=e.terminals.find(_=>_.title===R);C?(t.restart(C.id),ie({type:"run_command",terminalId:C.id,conversationId:C.conversationId,command:He,cols:80,rows:24})):t.create({id:St(),conversationId:e.activeConversationId||e.state?.conversationId||"",title:R,cwd:e.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:He}),qe(!1),se(!1),p("terminal")},Q=(R,He)=>{if(!e.ready||R.length===0)return;const C={name:He,command:zu(R),cwd:"${pwd}"},_=e.terminals.find(me=>me.title===He);_?(t.restart(_.id),ie({type:"run_command",terminalId:_.id,conversationId:_.conversationId,command:C,cols:80,rows:24})):t.create({id:St(),conversationId:e.activeConversationId||e.state?.conversationId||"",title:He,cwd:e.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:C}),qe(!1),se(!1),p("terminal")},z=R=>!e.tabs||R==="chat"||e.tabs.includes(R),ge=e.updatesAll??[],oe=ge.filter(R=>!R.upToDate&&!R.error).length,Z=ge.filter(R=>!R.upToDate&&!R.error&&R.kind!=="webui"),y=()=>s.jsxs("div",{className:"dd-updates-all",children:[s.jsx("div",{className:"dd-header",children:w("updatesAllTitle")}),e.updatesAll===null?s.jsx("div",{className:"dd-note",children:w("checkingUpdate")}):ge.length===0?s.jsx("div",{className:"dd-note",children:w("updatesAllUpToDate")}):s.jsx("ul",{className:"dd-all-list",children:ge.map(R=>s.jsxs("li",{className:`dd-all-item${R.error?" err":R.upToDate?"":" warn"}`,children:[s.jsx("span",{className:"dd-all-name",title:R.name,children:R.name}),s.jsx("span",{className:"dd-all-kind",children:R.kind==="webui"?w("kindWebUi"):R.kind==="pi-core"?w("kindPiCore"):w("kindPackage")}),s.jsx("span",{className:"dd-all-vers",children:R.error?w("updateCheckFailed"):R.upToDate?`v${R.current}`:s.jsxs(s.Fragment,{children:["v",R.current," → v",R.latest]})}),R.kind!=="webui"&&!R.upToDate&&!R.error&&s.jsx("button",{type:"button",className:"dd-update-btn",onClick:()=>Q([R],w("updatePkgTabTitle",{name:R.name})),children:w("updateBtn")})]},`${R.kind}:${R.name}`))}),s.jsxs("div",{className:"dd-actions",children:[Z.length>0&&s.jsx("button",{type:"button",className:"dd-refresh accent",style:{flex:1},onClick:()=>Q(Z,w("updateAllTabTitle")),children:w("updateAllBtn")}),s.jsx("button",{type:"button",className:"dd-refresh",style:Z.length>0?{flex:1}:void 0,onClick:()=>ie({type:"check_updates_all",force:!0}),children:w("updatesAllRefresh")})]})]}),P=()=>s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"dd-update",children:[s.jsxs("div",{className:"dd-row",children:[s.jsx("span",{children:w("currentVersion")}),s.jsxs("b",{children:["v",e.update?.current??"…"]})]}),s.jsxs("div",{className:"dd-row",children:[s.jsx("span",{children:w("latestVersion")}),s.jsx("b",{children:e.update===null?w("checkingUpdate"):e.update.error?e.update.error:e.update.latest?`v${e.update.latest}`:w("checkingUpdate")})]}),e.update&&e.update.upToDate&&s.jsx("div",{className:"dd-note ok",children:w("upToDate")}),e.update&&!e.update.upToDate&&e.update.latest&&s.jsx("div",{className:"dd-note warn",children:w("updateAvailable",{version:e.update.latest})}),e.update?.latestPublishedAt&&Date.now()-new Date(e.update.latestPublishedAt).getTime()<30*6e4&&s.jsx("div",{className:"dd-note warn",children:w("updateJustPublished",{version:e.update.latest??""})}),e.update&&!e.update.upToDate&&e.update.latest&&s.jsx("div",{className:"dd-note",children:w("updateTerminalHint")})]}),s.jsxs("div",{className:"dd-actions",children:[s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>ie({type:"check_update"}),children:e.update===null?w("checkingUpdate"):w("checkUpdate")}),e.update&&!e.update.upToDate&&e.update.latest&&s.jsx("button",{type:"button",className:"dd-refresh accent",onClick:A,children:w("updateNow")}),ve&&s.jsx("button",{type:"button",className:"dd-refresh accent",disabled:S,title:w("restartServiceTip",{name:ve.name}),onClick:()=>{S||(de(!0),ie({type:"restart_service"}))},children:w(S?"restartingService":"restartService")})]})]}),le={"host:search":s.jsxs("button",{type:"button",className:"chip",title:w("searchGlobalTip"),onClick:f,children:[s.jsx(An,{}),s.jsx("span",{className:"chip-sub",children:w("searchGlobal")})]}),"host:browser":e.settings?.disabledAgentTools?.includes(Ps)??!1?null:s.jsx(bd,{}),"host:tasks":s.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":w("bgTasksTip"),onClick:m,children:[s.jsx(In,{}),s.jsx("span",{className:"chip-sub",children:w("bgTasks")}),e.bgServers.length>0&&s.jsx("span",{className:"bg-task-badge",children:e.bgServers.length})]}),"host:settings":s.jsxs("button",{type:"button",className:"chip",title:w("settingsTitle"),onClick:b,children:[s.jsx(_n,{}),s.jsx("span",{className:"chip-sub",children:w("settings")})]}),"host:sound":s.jsxs(Yt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(No,{}),s.jsx("span",{className:"chip-sub",children:w("sound")})]}),open:ue,onOpenChange:pe,children:[s.jsx(Bi,{settings:x,onChange:v,onPreview:N}),s.jsx(Gi,{})]}),"host:language":s.jsxs(Yt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(Co,{}),s.jsx("span",{className:"chip-sub",children:id(j)})]}),open:ke,onOpenChange:Oe,children:[s.jsx("div",{className:"dd-header",children:w("language")}),ce.map(R=>s.jsx(ft,{active:j===R.code,onClick:()=>{X(R.code),Oe(!1)},children:R.nativeName},R.code)),s.jsxs(ft,{onClick:()=>{Oe(!1),De(!0)},children:[s.jsx(ss,{})," ",w("localeGetMore")]})]}),"host:theme":s.jsxs(Yt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(wu,{}),s.jsx("span",{className:"chip-sub",children:w("theme")})]}),open:ye,onOpenChange:R=>{we(R),R&&B.length===0&&I()},children:[s.jsx("div",{className:"dd-header",children:w("theme")}),s.jsx(ft,{active:V===null,onClick:()=>{W(null),we(!1)},children:w("themeDefault")}),B.map(R=>s.jsx(ft,{active:V===R.id,onClick:()=>{W(R.id),we(!1)},children:j==="zh"?R.name:R.nameEn??R.name},R.id))]}),"host:update":ee?s.jsxs("span",{className:"chip",title:w("updatesManaged"),children:[s.jsx(ss,{}),s.jsxs("span",{className:"chip-sub",children:["v",ae??e.update?.current??"…"]})]}):s.jsxs(Yt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(ss,{}),s.jsxs("span",{className:"chip-sub",children:["v",e.update?.current??"…"]}),e.update&&!e.update.upToDate&&s.jsx("span",{className:"update-dot",title:w("updateAvailable",{version:e.update.latest??""})}),oe>0&&s.jsx("span",{className:"update-badge",children:w("updatesAllBadge",{n:oe})})]}),open:Ce,onOpenChange:R=>{qe(R),R&&(ie({type:"check_update"}),ie({type:"check_updates_all"}))},fit:!0,children:[s.jsx("div",{className:"dd-header",children:w("update")}),P(),y()]}),"host:github":s.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:w("githubRepo"),children:s.jsx(Di,{})})},Ee=["host:search","host:browser","host:tasks","host:settings","host:sound","host:language","host:theme","host:update","host:github"],Ae=new Set(["host:search","host:tasks","host:settings"]),Me=new Set(["host:sound","host:language","host:theme","host:update","host:github","host:browser"]),Le=new Set(Ee),Ge=i===void 0?Ee.filter(R=>z(R.slice(5))):i.filter(R=>R.source==="host"&&Le.has(R.id)).filter(R=>Ae.has(R.id)?z(R.id.slice(5)):!0).map(R=>R.id);return s.jsxs("header",{className:"topbar",children:[s.jsxs("div",{className:"brand",children:[n==="chat"&&F("history")&&s.jsx("button",{type:"button",className:"panel-toggle",title:w("openHistory"),onClick:()=>h("left"),children:s.jsx(Ru,{})}),s.jsx("span",{className:"brand-logo",children:"π"}),s.jsx("span",{className:"brand-name",children:"pi-web-ui"}),s.jsx("span",{className:`conn-dot ${Ye}`,title:Re}),s.jsx("span",{className:"conn-label",children:Re})]}),s.jsxs("div",{className:"topbar-actions",children:[s.jsxs("div",{className:"view-switch",role:"tablist","aria-label":w("viewSwitch"),children:[s.jsxs("button",{type:"button",role:"tab","aria-selected":n==="chat",className:n==="chat"?"active":"",onClick:()=>p("chat"),children:[s.jsx(ts,{}),s.jsx("span",{children:w("chat")})]}),F("terminal")&&s.jsxs("button",{type:"button",role:"tab","aria-selected":n==="terminal",className:n==="terminal"?"active":"",onClick:()=>p("terminal"),children:[s.jsx(Jn,{}),s.jsx("span",{children:w("terminal")})]}),F("git")&&s.jsxs("button",{type:"button",role:"tab","aria-selected":n==="git",className:n==="git"?"active":"",onClick:()=>p("git"),children:[s.jsx(mn,{}),s.jsx("span",{children:w("scmTab")})]}),(z("plugins")?a:[]).filter(R=>R.view!==!1).map(R=>{const He=R.error?`${R.name}: ${R.error}`:R.description?`${R.name} — ${R.description}`:R.name;return s.jsxs("button",{type:"button",role:"tab","aria-selected":n===`plugin:${R.id}`,className:`plugin-tab${n===`plugin:${R.id}`?" active":""}${R.error?" broken":""}`,title:He,onClick:()=>p(`plugin:${R.id}`),children:[R.icon?s.jsx("span",{"aria-hidden":!0,children:R.icon}):null,s.jsx("span",{children:R.name})]},R.id)}),H.map(R=>s.jsxs("button",{type:"button",className:"plugin-topbar-item",title:R.hint??R.label,onClick:()=>u?.(R),onContextMenu:He=>D(He,R.id,R.label),children:[R.icon?s.jsx("span",{"aria-hidden":!0,children:R.icon}):null,s.jsx("span",{children:R.label})]},R.id)),T.length>0&&s.jsxs("div",{className:"plugin-topbar-more",children:[s.jsx("button",{type:"button",className:"plugin-topbar-item","aria-haspopup":"menu","aria-expanded":be,title:w("pluginTopbarMore"),onClick:()=>$(R=>!R),children:"⋯"}),be&&s.jsx("div",{className:"plugin-topbar-menu",role:"menu",children:T.map(R=>{const He=R.source==="host"&&Me.has(R.id)?le[R.id]:void 0;return He!==void 0?s.jsx(c.Fragment,{children:He},R.id):s.jsxs("button",{type:"button",role:"menuitem",title:R.hint??R.label,onClick:()=>{$(!1),Y(R)||u?.(R)},children:[R.icon&&!/[a-z]/i.test(R.icon)?`${R.icon} `:"",R.label]},R.id)})})]})," "]}),s.jsx("div",{className:"topbar-desktop",children:Ge.map(R=>s.jsx(c.Fragment,{children:le[R]??null},R))}),F("new-chat")&&s.jsxs("button",{type:"button",className:"chip newchat","data-tip":w("newChatTip"),onClick:()=>ie({type:"new_chat"}),children:[s.jsx(yt,{}),s.jsx("span",{children:w("newChat")})]}),s.jsx("div",{className:"topbar-more",children:s.jsxs(Yt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(Au,{}),s.jsx("span",{className:"chip-sub",children:w("more")}),!ee&&e.update&&!e.update.upToDate&&s.jsx("span",{className:"update-dot"})]}),open:Be,onOpenChange:R=>{se(R),R&&B.length===0&&I(),R&&!ee&&(ie({type:"check_update"}),ie({type:"check_updates_all"}))},children:[s.jsx("div",{className:"dd-header",children:w("sound")}),s.jsx("div",{className:"dd-header",children:w("settings")}),s.jsxs(ft,{onClick:()=>{se(!1),b()},children:[s.jsx(_n,{})," ",w("settingsTitle")]}),s.jsxs(ft,{onClick:()=>{se(!1),f()},children:[s.jsx(An,{})," ",w("searchGlobal")]}),s.jsxs(ft,{onClick:()=>{se(!1),m()},children:[s.jsx(In,{})," ",w("bgTasks"),e.bgServers.length>0&&s.jsx("em",{className:"bg-task-badge",children:e.bgServers.length})]}),s.jsx(Bi,{settings:x,onChange:v,onPreview:N}),s.jsx(Gi,{}),s.jsx("div",{className:"dd-header",children:w("language")}),ce.map(R=>s.jsx(ft,{active:j===R.code,onClick:()=>X(R.code),children:R.nativeName},R.code)),s.jsx("div",{className:"dd-header",children:w("theme")}),s.jsx(ft,{active:V===null,onClick:()=>{W(null),se(!1)},children:w("themeDefault")}),B.map(R=>s.jsx(ft,{active:V===R.id,onClick:()=>{W(R.id),se(!1)},children:j==="zh"?R.name:R.nameEn??R.name},R.id)),s.jsx("div",{className:"dd-header",children:w("update")}),P(),y(),s.jsxs("a",{className:"dd-refresh dd-more-link",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",children:[s.jsx(Di,{})," ",w("githubRepo")]})]})})]}),n==="chat"&&F("files")&&s.jsx("button",{type:"button",className:"panel-toggle",title:w("openFiles"),onClick:()=>h("right"),children:s.jsx(Bt,{})}),Te&&s.jsx(Ud,{onClose:()=>De(!1)})]})}function zo(e,t){const n={...t};if(!e)return n;try{const a=JSON.parse(e);if(a&&typeof a=="object"&&!Array.isArray(a))for(const i of Object.keys(t)){const o=a[i];typeof o=="number"&&Number.isFinite(o)&&o>0&&(n[i]=o)}}catch{}return n}function Vo(e){const t=e.start.above+e.start.below,n=Math.max(1,e.availablePx),a=e.totalWeight>0?e.totalWeight:1,i=n/a,o=e.minAbovePx/i,l=e.minBelowPx/i;if(o+l>=t){const p=e.minAbovePx+e.minBelowPx||1,h=t*e.minAbovePx/p;return{above:h,below:t-h}}const u=Math.min(t-l,Math.max(o,e.start.above+e.deltaPx/i));return{above:u,below:t-u}}function qd(e,t,n){const a=new Map(e.map(h=>[h.id,h])),i=h=>h.parentId?a.get(h.parentId)?.cwd??h.cwd:h.cwd,o=e.find(h=>h.id===n),l=o?i(o):t,u=new Map;for(const h of e){const b=i(h),m=u.get(b)??[];m.push(h),u.set(b,m)}const p=[...u.entries()].map(([h,b])=>({cwd:h,isCurrent:h===l,convs:b}));return p.sort((h,b)=>h.isCurrent?-1:b.isCurrent?1:h.cwd<b.cwd?-1:h.cwd>b.cwd?1:0),p}function er(e){const t=new Date(e),n=new Date;return t.toDateString()===n.toDateString()?`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`:`${t.getMonth()+1}/${t.getDate()}`}function Wd(e){const t=e instanceof HTMLElement?e:null;if(!t)return!1;const n=t.tagName;return n==="INPUT"||n==="TEXTAREA"||n==="SELECT"?!0:t.isContentEditable}const Kd="pi-web-ui:lp-collapse-projects",Yd="pi-web-ui:lp-collapse-convs",Gd="pi-web-ui:lp-collapse-sessions";function fa(e,t=!1){const[n,a]=c.useState(()=>{try{const o=localStorage.getItem(e);if(o==="1")return!0;if(o==="0")return!1}catch{}return t}),i=c.useCallback(()=>{a(o=>{const l=!o;try{localStorage.setItem(e,l?"1":"0")}catch{}return l})},[e]);return[n,i]}const Qo="pi-web-ui:lp-sizes",Mn={projects:1,convs:1,sessions:1},zd=32,tr=72;function Vd(){try{return zo(localStorage.getItem(Qo),Mn)}catch{return{...Mn}}}const Qd=c.memo(function({sessionFile:t,conversations:n,elsewhere:a,sessions:i,projects:o,activeConversationId:l,panelSend:u,active:p,collapsible:h,onToggleCollapse:b,uiContextSession:m}){const f=Pe(),x=t,v=wt("ready"),N=wt("status"),B=wt("cwd"),V=B,[W,I]=c.useState(null),[j,X]=c.useState(null),[w,ce]=c.useState(""),[be,$]=fa(Kd,!1),[K,J]=fa(Yd,!1),[L,H]=fa(Gd,!1),T=c.useCallback((A,Q)=>{if(!Q)return A.filter(oe=>oe.isSubagent&&!oe.isStreaming&&oe.id!==l).length;const z=new Map(A.map(oe=>[oe.id,oe])),ge=oe=>{if(oe.id===Q)return(z.get(Q)?.isSubagent??!1)&&!oe.isStreaming&&oe.id!==l;let Z=oe;const y=new Set;for(;Z?.parentId;){if(Z.parentId===Q)return!0;if(y.has(Z.parentId)||(y.add(Z.parentId),Z=z.get(Z.parentId),!Z))return!1}return!1};return A.filter(oe=>oe.isSubagent&&!oe.isStreaming&&oe.id!==l&&ge(oe)).length},[l]),F=c.useCallback((A,Q)=>{if(!Q)return A.filter(oe=>oe.isSubagent).length;const z=new Map(A.map(oe=>[oe.id,oe])),ge=oe=>{if(oe.id===Q)return z.get(Q)?.isSubagent??!1;let Z=oe;const y=new Set;for(;Z?.parentId;){if(Z.parentId===Q)return!0;if(y.has(Z.parentId)||(y.add(Z.parentId),Z=z.get(Z.parentId),!Z))return!1}return!1};return A.filter(oe=>oe.isSubagent&&ge(oe)).length},[]),Y=c.useCallback((A,Q)=>{if(!Q)return 0;const z=new Map(A.map(oe=>[oe.id,oe])),ge=oe=>{let Z=oe;const y=new Set;for(;Z?.parentId;){if(Z.parentId===Q)return!0;if(y.has(Z.parentId)||(y.add(Z.parentId),Z=z.get(Z.parentId),!Z))return!1}return!1};return A.filter(oe=>oe.isSubagent&&oe.isStreaming&&ge(oe)).length},[]),D=c.useRef(null),ae=c.useRef(null),ee=c.useRef(()=>{}),ve=On(m??[]).length>0,S=c.useCallback((A,Q,z)=>{D.current={x:A,y:Q,target:z};const ge=z.kind==="running"?z.id:void 0,oe=T(n,ge),Z=oe===0?f("noFinishedSubagents"):ge?f("dismissFinishedSubagentsScoped",{n:oe}):f("dismissFinishedSubagents",{n:oe}),y=!!ge&&ae.current===ge,P=(m??[]).map(le=>le.source!=="host"?le:le.id==="host:conv-dismiss-subagents"?{...le,label:Z,...oe===0?{when:[...le.when??[],"disabled"]}:{}}:le.id==="host:conv-force-dismiss"?ge?{...le,...y?{label:f("forceDismissConfirm")}:{}}:{...le,hidden:!0}:le);ea({x:A,y:Q,slot:"contextmenu.session",target:z,entries:P,onHostAction:(le,Ee)=>ee.current(le,Ee)})},[m,n,T,f]),de=c.useCallback((A,Q)=>{const z=Q.kind==="running"?Q.id:void 0;if(A.id==="host:conv-dismiss-subagents"){u(z?{type:"dismiss_finished_subagents",parentId:z}:{type:"dismiss_finished_subagents"});return}if(A.id!=="host:conv-force-dismiss")return;const ge=D.current;if(!(!z||!ge)){if(ae.current!==z)return ae.current=z,S(ge.x,ge.y,ge.target),!0;ae.current=null,u({type:"dismiss_conversation",id:z,force:!0})}},[u,S]);ee.current=de;const ue=c.useCallback((A,Q)=>{Wd(A.target)||ve&&(A.preventDefault(),A.stopPropagation(),ae.current=null,S(A.clientX,A.clientY,Q))},[ve,S]),pe=c.useRef(null),[ke,Oe]=c.useState(()=>Vd());c.useEffect(()=>{try{localStorage.setItem(Qo,JSON.stringify(ke))}catch{}},[ke]);const ye=[...n,...a.map((A,Q)=>({id:`elsewhere:${A.cwd}:${A.title}:${Q}`,title:A.title,cwd:A.cwd,messageCount:0,isStreaming:A.isStreaming,isSubagent:!1,elsewhere:!0}))],we=c.useCallback((A,Q)=>z=>{z.preventDefault();const ge=z.currentTarget,oe=z.clientY,Z={...ke},y=pe.current;if(!y)return;const P=[{key:"projects",visible:o.length>0,collapsed:be},{key:"convs",visible:ye.length>0,collapsed:K},{key:"sessions",visible:!0,collapsed:L}].filter(R=>R.visible),le=P.filter(R=>R.collapsed).length,Ae=P.filter(R=>!R.collapsed).map(R=>R.key).reduce((R,He)=>R+(Z[He]??1),0)||1,Me=Math.max(120,y.clientHeight-le*zd);ge.classList.add("dragging"),document.body.classList.add("lp-resizing");const Le=R=>{const{above:He,below:C}=Vo({start:{above:Z[A]??1,below:Z[Q]??1},deltaPx:R.clientY-oe,availablePx:Me,totalWeight:Ae,minAbovePx:tr,minBelowPx:tr});Oe(_=>({..._,[A]:He,[Q]:C}))},Ge=()=>{window.removeEventListener("pointermove",Le),window.removeEventListener("pointerup",Ge),ge.classList.remove("dragging"),document.body.classList.remove("lp-resizing")};window.addEventListener("pointermove",Le),window.addEventListener("pointerup",Ge)},[ke,o.length,ye.length,be,K,L]);c.useEffect(()=>{!p||!v||N!=="open"||B&&(u({type:"list_sessions"}),u({type:"list_projects"}))},[p,v,N,B,u]);const Ce=A=>{const Q=A.name||A.firstMessage.trim();return Q.length>0?Q:f("emptyChat")},qe=A=>A.split(/[\\/]/).pop()||A,Be=(A,Q,z,ge,oe)=>{const Z=W===A;return s.jsx("button",{type:"button",className:`lp-del ${Z?"confirm":""}`,title:Z?z:Q,onClick:y=>{y.stopPropagation(),Z?(I(null),ge()):I(A)},children:Z?s.jsx(Rt,{}):oe??s.jsx(dt,{})})},se=(A,Q,z,ge)=>s.jsxs("button",{type:"button",className:"lp-section-title panel-section-title",onClick:z,title:f(Q?"expandSection":"collapseSection"),children:[s.jsxs("span",{className:"lp-section-title-text",children:[A,ge!==void 0?` (${ge})`:""]}),s.jsx("span",{className:"lp-section-chevron",children:Q?s.jsx(Vt,{}):s.jsx(Zn,{})})]}),De=[{key:"projects",visible:o.length>0,collapsed:be},{key:"convs",visible:ye.length>0,collapsed:K},{key:"sessions",visible:!0,collapsed:L}].filter(A=>A.visible).filter(A=>!A.collapsed),Re=De.reduce((A,Q)=>A+(ke[Q.key]??1),0)||1,Ye=A=>De.length<=1?1:(ke[A]??1)/Re*De.length;return s.jsxs("aside",{ref:pe,className:"panel panel-left lp-panel",children:[h&&b&&s.jsx("button",{type:"button",className:"panel-collapse-btn",title:f("collapsePanel"),onClick:b,children:s.jsx(_o,{})}),o.length>0&&s.jsxs("div",{className:`lp-section panel-projects ${be?"collapsed":""}`,style:be?void 0:{flex:`${Ye("projects")} 1 0px`},children:[se(f("recentProjects"),be,$,o.length),!be&&s.jsx("div",{className:"lp-section-body projects-scroll",children:o.map(A=>{const Q=V===A.path;return s.jsxs("div",{className:"lp-row",onMouseLeave:()=>I(z=>z===`proj:${A.path}`?null:z),children:[s.jsxs("button",{type:"button",className:`project-item ${Q?"active":""}`,title:A.path,onClick:()=>{Q||u({type:"set_cwd",path:A.path})},children:[s.jsx(Bt,{className:"project-icon"}),s.jsxs("span",{className:"project-info",children:[s.jsx("span",{className:"project-name",children:qe(A.path)}),s.jsx("span",{className:"project-path",children:A.path})]}),s.jsx("span",{className:"project-time",children:er(A.lastUsed)})]}),Be(`proj:${A.path}`,f("deleteProject"),f("deleteProjectConfirm"),()=>u({type:"remove_project",path:A.path}))]},A.path)})})]}),o.length>0&&!be&&(ye.length>0?!K:!L)&&s.jsx("div",{className:"lp-sash",onPointerDown:we("projects",ye.length>0?"convs":"sessions"),onDoubleClick:()=>Oe({...Mn}),title:f("dragToResize")}),ye.length>0&&s.jsxs("div",{className:`lp-section lp-section-convs panel-convs ${K?"collapsed":""}`,style:K?void 0:{flex:`${Ye("convs")} 1 0px`},onContextMenu:A=>ue(A,{id:"",kind:"section",label:f("runningConversations")}),children:[se(f("runningConversations"),K,J,ye.length),!K&&s.jsx("div",{className:"lp-section-body convs-scroll",children:qd(ye,B,l).map(A=>s.jsxs("div",{className:"panel-conv-group",children:[!A.isCurrent&&s.jsx("div",{className:"panel-conv-group-title",title:A.cwd,children:qe(A.cwd)}),(()=>{const Q=new Map(A.convs.map(P=>[P.id,P])),z=new Map,ge=[];for(const P of A.convs)if(P.parentId&&Q.has(P.parentId)){const le=z.get(P.parentId)??[];le.push(P),z.set(P.parentId,le)}else ge.push(P);const oe=[],Z=new Set,y=(P,le)=>{if(!Z.has(P.id)){Z.add(P.id),oe.push({c:P,depth:le});for(const Ee of z.get(P.id)??[])y(Ee,le+1)}};for(const P of ge)y(P,0);for(const P of A.convs)y(P,0);return oe.map(({c:P,depth:le})=>{if(P.elsewhere)return s.jsx("div",{className:"lp-row",children:s.jsxs("div",{className:"session-item elsewhere-item",title:`${f("elsewhereTip")}
317
+ ${P.cwd}`,children:[s.jsx(ts,{className:"session-icon"}),s.jsxs("span",{className:"session-info",children:[s.jsxs("span",{className:"session-title",children:[s.jsx("span",{className:"elsewhere-badge",children:f("elsewhereBadge")}),P.title]}),s.jsx("span",{className:"session-sub",children:qe(P.cwd)})]}),P.isStreaming&&s.jsx("span",{className:"conv-streaming",title:f("streaming")})]})},P.id);const Ee=l===P.id;return s.jsxs("div",{className:`lp-row${le>0?" lp-sub":""}`,style:le>0?{marginLeft:le*18}:void 0,onMouseLeave:()=>I(Ae=>Ae===`conv:${P.id}`?null:Ae),onContextMenu:Ae=>ue(Ae,{id:P.id,kind:"running",label:P.title}),children:[s.jsxs("button",{type:"button",className:`session-item ${Ee?"active":""}`,title:`${P.title}${A.isCurrent?"":` — ${A.cwd}`}`,onClick:()=>{Ee||u({type:"switch_conversation",id:P.id})},children:[s.jsx(ts,{className:"session-icon"}),s.jsxs("span",{className:"session-info",children:[j===`conv:${P.id}`?s.jsx("input",{autoFocus:!0,className:"session-rename-input",value:w,placeholder:f("renameSessionPlaceholder"),onClick:Ae=>Ae.stopPropagation(),onChange:Ae=>ce(Ae.target.value),onKeyDown:Ae=>{if(Ae.stopPropagation(),Ae.key==="Enter"&&!Ae.nativeEvent.isComposing){const Me=w.trim();Me&&u({type:"rename_conversation",id:P.id,name:Me}),X(null)}else Ae.key==="Escape"&&X(null)},onBlur:()=>X(null)}):s.jsxs("span",{className:"session-title",children:[P.isSubagent&&s.jsx("span",{className:"subagent-badge",children:f("subagentBadge")}),P.title,P.error&&s.jsx("span",{className:"conv-error-badge",title:f("convErrorBadge",{error:P.error})})]}),j===`conv:${P.id}`?null:s.jsx("span",{className:"session-sub",children:Ee?f("current"):f("messageCount",{n:P.messageCount})})]}),P.isStreaming&&s.jsx("span",{className:"conv-streaming",title:f("streaming")})]}),s.jsx("button",{type:"button",className:"lp-del lp-rename",title:f("renameSession"),onClick:Ae=>{Ae.stopPropagation(),I(null),ce(P.title),X(`conv:${P.id}`)},children:s.jsx(Rn,{})}),(()=>{const Ae=`conv:${P.id}`,Me=W===Ae,Le=T(n,P.id),Ge=Y(n,P.id),R=F(n,P.id);return R===0&&!P.isStreaming?Be(Ae,f("dismissConversation"),f("dismissConversationConfirm"),()=>u({type:"dismiss_conversation",id:P.id}),s.jsx(tt,{})):R===0?Be(Ae,f("dismissConversation"),f("dismissStreamingConfirm"),()=>u({type:"dismiss_conversation",id:P.id,force:!0}),s.jsx(tt,{})):Me?s.jsxs("span",{className:"lp-del-group",children:[Le>0&&s.jsx("button",{type:"button",className:"lp-del-opt",title:f("dismissFinishedSubagentsScoped",{n:Le}),onClick:He=>{He.stopPropagation(),I(null),u({type:"dismiss_finished_subagents",parentId:P.id})},children:f("dismissFinishedOnly",{n:Le})}),s.jsx("button",{type:"button",className:"lp-del-opt danger",title:f("forceDismissTitle",{n:R,m:Ge}),onClick:He=>{He.stopPropagation(),I(null),u({type:"dismiss_conversation",id:P.id,force:!0})},children:f("dismissForceAll",{n:R})})]}):s.jsx("button",{type:"button",className:"lp-del",title:f("dismissConversation"),onClick:He=>{He.stopPropagation(),I(Ae)},children:s.jsx(tt,{})})})(),P.isStreaming&&s.jsx("span",{className:"lp-row-stalled",title:f("streaming"),style:{position:"absolute",right:28,top:"50%",transform:"translateY(-50%)"}})]},P.id)})})()]},A.cwd))})]}),ye.length>0&&!K&&!L&&s.jsx("div",{className:"lp-sash",onPointerDown:we("convs","sessions"),onDoubleClick:()=>Oe({...Mn}),title:f("dragToResize")}),s.jsxs("div",{className:`lp-section lp-section-sessions panel-sessions ${L?"collapsed":""}`,style:L?void 0:{flex:`${Ye("sessions")} 1 0px`},children:[se(f("historySessions"),L,H,i.length),!L&&s.jsxs("div",{className:"lp-section-body sessions-scroll",children:[i.length===0&&s.jsx("div",{className:"panel-empty",children:f("noHistory")}),i.map(A=>{const Q=x===A.path;return s.jsxs("div",{className:"lp-row",onMouseLeave:()=>I(z=>z===`sess:${A.path}`?null:z),onContextMenu:z=>ue(z,{id:A.path,kind:"history",label:Ce(A)}),children:[s.jsxs("button",{type:"button",className:`session-item ${Q?"active":""}`,title:A.path,onClick:()=>{j||Q||u({type:"switch_session",path:A.path})},children:[s.jsx(ts,{className:"session-icon"}),s.jsxs("span",{className:"session-info",children:[j===A.path?s.jsx("input",{autoFocus:!0,className:"session-rename-input",value:w,placeholder:f("renameSessionPlaceholder"),onClick:z=>z.stopPropagation(),onChange:z=>ce(z.target.value),onKeyDown:z=>{if(z.stopPropagation(),z.key==="Enter"&&!z.nativeEvent.isComposing){const ge=w.trim();ge&&u({type:"rename_session",path:A.path,name:ge}),X(null)}else z.key==="Escape"&&X(null)},onBlur:()=>X(null)}):s.jsx("span",{className:"session-title",children:Ce(A)}),j===A.path?null:s.jsxs("span",{className:"session-sub",children:[Q?f("current"):f("messageCount",{n:A.messageCount}),A.source==="tui"&&s.jsx("span",{className:"session-src",title:f("tuiTip"),children:"TUI"})]})]}),s.jsx("span",{className:"session-time",children:er(A.modified)})]}),s.jsx("button",{type:"button",className:"lp-del lp-rename",title:f("renameSession"),onClick:z=>{z.stopPropagation(),I(null),ce(A.name??""),X(A.path)},children:s.jsx(Rn,{})}),Be(`sess:${A.path}`,f("deleteSession"),f("deleteSessionConfirm"),()=>u({type:"delete_session",path:A.path}))]},A.path)})]})]})]})});function Xd(e,t){const n=t.assistantMessageEvent,a=e.stats.tokens,i=t.usage!==null?{...a,...t.usage}:a,o=i===a?e.stats:{...e.stats,tokens:i};if(n.type!=="text_delta"&&n.type!=="thinking_delta")return o===e.stats?e:{...e,stats:o};const l=n.delta??"";if(!l)return o===e.stats?e:{...e,stats:o};const u=e.streamingMessage??null,p=u&&u.id===t.messageId?u:{id:t.messageId,content:[]},h=[...p.content],b=n.type==="thinking_delta"?"thinking":"text",m=n.contentIndex??h.length-1;return m>=0&&m<h.length&&h[m].type===b?h[m]=b==="thinking"?{type:"thinking",thinking:(h[m].thinking??"")+l}:{type:"text",text:(h[m].text??"")+l}:h.push(b==="thinking"?{type:"thinking",thinking:l}:{type:"text",text:l}),{...e,stats:o,streamingMessage:{...p,id:t.messageId,content:h}}}function Jd(e){const{current:t,source:n,snapshot:a,answered:i}=e;return a&&a.id&&!i.has(a.id)?t?.id===a.id?{changed:!1,question:t,source:n}:{changed:!0,question:a,source:"snapshot"}:!a&&t&&n==="snapshot"?{changed:!0,question:null,source:"live"}:{changed:!1,question:t,source:n}}const sr="__piWebUiHost",Zd=6,Xo=e=>new Promise(t=>setTimeout(t,e));async function ep(e=3e3){const t=Date.now()+e;for(;;){const n=window.__piBridge;if(n&&typeof n.call=="function")return n;if(Date.now()>=t)return null;await Xo(100)}}function tp(e){const t=Math.max(1,Number(e.pollMs??100)),n=Math.max(t,Number(e.timeoutMs??8e3)),a=async o=>{const l=Date.now()+n;for(;;){if(o())return!0;if(Date.now()>=l)return o();await Xo(t)}},i=async(o,l)=>{const u=String(l.cwd??"").trim();if(u&&e.getCwd()!==u&&(e.send({type:"set_cwd",path:u}),await a(()=>e.getCwd()===u)),l.newChat!==!1){const p=e.getConversationId();e.send({type:"new_chat"}),await a(()=>e.getConversationId()!==p||e.isConversationBlank())}e.send({type:"prompt",text:o})};return{version:Zd,setView(o){const l=String(o??"").trim();l&&e.setView(l)},startChat(o){const l=String(o?.prompt??"").trim();return!l||!e.isReady()?!1:(i(l,o??{}).catch(()=>{}),!0)},compose(o){return gd()?Mo({text:typeof o?.text=="string"?o.text:void 0,attachments:Array.isArray(o?.attachments)?o.attachments:void 0}):!1},async openSession(o){const l=Array.isArray(o?.folders)?o.folders.filter(N=>typeof N=="string"&&N.trim().length>0).map(N=>N.trim()):[],u=Array.isArray(o?.roots)?o.roots.filter(N=>typeof N=="string"&&N.trim().length>0).map(N=>N.trim()):[],p=String(o?.cwd??"").trim(),h=[...new Set([...l,...u])],b=p||h[0]||"";if(!b)return{ok:!1,error:"openSession 需要 cwd / folders / roots(绝对路径)"};if(!e.isReady())return{ok:!1,error:"尚未连接到服务器(还没有快照)"};const m=h.filter(N=>N!==b).slice(0,7),f=new Set([...e.listProjects?.()??[],...e.grantedPaths?.()??[]]);for(const N of[b,...m]){if(f.has(N))continue;if(!(e.confirm?await e.confirm({path:N}).catch(()=>!1):!1))return{ok:!1,error:`用户拒绝了该目录的访问:${N}`};e.grantPath?.(N)}if(e.getCwd()!==b&&(e.send({type:"set_cwd",path:b}),!await a(()=>e.getCwd()===b)))return{ok:!1,error:`切换工作目录失败或超时:${b}`};(m.length>0||e.getWorkspaceRoots().length>0)&&e.send({type:"set_workspace_roots",roots:m});let x=e.getConversationId()??void 0;if(o?.newChat!==!1){const N=x;e.send({type:"new_chat"}),await a(()=>e.getConversationId()!==N||e.isConversationBlank()),x=e.getConversationId()??void 0}const v=String(o?.prompt??"").trim();return v&&e.send({type:"prompt",text:v}),{ok:!0,...x?{sessionId:x}:{}}},sessions:{list:()=>e.listSessions(),async open(o){const l=String(o??"").trim();if(!l)return{ok:!1,error:"sessions.open 需要一个会话 id(先调 list)"};if(!e.isReady())return{ok:!1,error:"尚未连接到服务器(还没有快照)"};const u=e.listSessions().find(b=>b.id===l);if(!u)return{ok:!1,error:`找不到会话:${l}`};if(u.cwd&&u.cwd!==e.getCwd()){if(!new Set([...e.listProjects?.()??[],...e.grantedPaths?.()??[]]).has(u.cwd)){if(!(e.confirm?await e.confirm({path:u.cwd}).catch(()=>!1):!1))return{ok:!1,error:`用户拒绝了该目录的访问:${u.cwd}`};e.grantPath?.(u.cwd)}if(e.send({type:"set_cwd",path:u.cwd}),!await a(()=>e.getCwd()===u.cwd))return{ok:!1,error:`切换工作目录失败或超时:${u.cwd}`}}const p=e.getConversationId();return u.kind==="running"?e.send({type:"switch_conversation",id:u.id}):e.send({type:"switch_session",path:u.id}),await a(()=>e.getConversationId()!==p)?{ok:!0,sessionId:e.getConversationId()??void 0}:{ok:!1,error:`切换会话超时:${u.title}`}}},async reloadCatalog(o,l){const u=String(o??"").trim();if(!u)return{ok:!1,error:"reloadCatalog 需要一个目录来源(http(s) URL 或本地文件路径)"};if(!e.isReady())return{ok:!1,error:"尚未连接到服务器(还没有快照)"};const p=St();return new Promise(h=>{const b=setTimeout(()=>{Bn.delete(p),h({ok:!1,error:"目录同步超时(服务端未在等待窗口内回执)"})},Math.max(1e3,Number(e.catalogTimeoutMs??18e4)));Bn.set(p,m=>{clearTimeout(b),h(m)}),e.send({type:"plugin_catalog_sync",requestId:p,source:u,...l?.install?{install:!0}:{},...l?.replace?{replace:!0}:{}})})},onUiAction(o,l){return ar(Os,String(o??"").trim(),l)},onTopbarAction(o,l){return ar(Os,String(o??"").trim(),l)},async pageCall(o){const l=String(o?.op??"").trim();if(!l)return{ok:!1,error:"pageCall 需要一个动作名(op)"};if(Po())return{ok:!1,error:"桌面版(Electron 外壳)不支持 browser_page:窗口里没有 Chrome 扩展运行时。请让用户改用系统浏览器打开同一个 pi-web-ui 地址(网页版)再试。/ The desktop app cannot run browser_page (no Chrome extension runtime); ask the user to open the same pi-web-ui address in a regular browser instead."};const u=await ep(e.bridgeWaitMs??3e3);if(!u)return{ok:!1,error:"浏览器扩展的页面桥没就绪:确认已安装并启用 page-picker 扩展、本页地址已绑定,然后刷新本页"};try{const p=await u.call({op:l,...o.args===void 0?{}:{args:o.args},...o.target?{to:o.target}:{},...o.timeoutMs?{timeoutMs:o.timeoutMs}:{}});return p===void 0?{ok:!0}:{ok:!0,result:p}}catch(p){return{ok:!1,error:p instanceof Error?p.message:String(p)}}}}}function nr(e){try{const t=window;e?t[sr]=e:delete t[sr]}catch{}}const Tn=new Map;let Os=null;async function Jo(e,t){const n=Os;Os=e;try{return await t()}finally{Os=n}}function ar(e,t,n){if(!t||typeof n!="function")return()=>{};const a=e?`${e}:${t}`:t;let i=Tn.get(a);i||(i=new Set,Tn.set(a,i));const o=i;return o.add(n),()=>{o.delete(n),o.size===0&&Tn.delete(a)}}async function sp(e,t,n,a){const i=o=>{const l=Tn.get(o);if(!l||l.size===0)return!1;for(const u of[...l])try{u(n)}catch(p){console.error(`[plugin:${e}] 顶栏动作 ${t} 抛错:`,p)}return!0};if(i(`${e}:${t}`)||i(t))return!0;if(a?.loadBundle&&await a.loadBundle(e).catch(()=>!1)){const l=Date.now()+Math.max(100,Number(a.waitMs??1500));for(;;){if(i(`${e}:${t}`)||i(t))return!0;if(Date.now()>=l)break;await new Promise(u=>setTimeout(u,100))}}return!1}const Bn=new Map;function np(e){const t=Bn.get(e.requestId);if(t){if(Bn.delete(e.requestId),!e.ok){t({ok:!1,error:e.error??"目录同步失败"});return}t({ok:!0,...e.entries?{entries:e.entries}:{},...e.installed?{installed:e.installed}:{}})}}const Fa="pi-web-ui:plugin-data";function ap(e,t){window.dispatchEvent(new CustomEvent(Fa,{detail:{pluginId:e,payload:t}}))}function ip(e){const t=n=>{const a=n.detail;e(a.pluginId,a.payload)};return window.addEventListener(Fa,t),()=>window.removeEventListener(Fa,t)}const Jt=new Map,Ha=new Set,Zt=new Set;let ir=-1;function Zo(){return[...Jt.values()]}function el(){const e=Zo();for(const t of Ha)t(e)}function rp(e){return Ha.add(e),e(Zo()),()=>Ha.delete(e)}async function tl(e,t){try{const a=(await Jo(e.id,()=>import(lt(`/plugins/${encodeURIComponent(e.id)}/client/entry.mjs?e=${t}`)))).default;return a&&typeof a.mount=="function"?(Jt.set(e.id,{info:e,module:a}),!0):(Zt.add(e.id),console.error(`[plugin:${e.id}] entry.mjs 缺少 default.mount`),!1)}catch(n){return Zt.add(e.id),console.error(`[plugin:${e.id}] 客户端加载失败:`,n),!1}}async function Ua(e,t){if(Jt.has(e.id))return!0;if(Zt.has(e.id)||!e.hasClient)return!1;const n=await tl(e,t);return el(),n}async function op(e,t){t!==ir&&(ir=t,Jt.clear(),Zt.clear());const n=new Set(e.map(a=>a.id));for(const a of[...Jt.keys()])n.has(a)||Jt.delete(a);for(const a of[...Zt])n.has(a)||Zt.delete(a);await Promise.all(e.filter(a=>a.hasClient&&a.view!==!1&&!a.error&&!Jt.has(a.id)&&!Zt.has(a.id)).map(a=>tl(a,t))),el()}function sl(e,t){return{pluginId:e,send:n=>t({type:"plugin_message",pluginId:e,payload:n}),onData:n=>ip((a,i)=>{a===e&&n(i)})}}const lp=15,cp="pi-web-ui:lang";function rr(){try{return(localStorage.getItem(cp)??"").trim()}catch{return""}}const or="pi-web-ui:locale",ga=2e5,up=2e5,dp="LIVE_OMIT",pp={conversationId:null,goal:null,reviewModel:null,maxRounds:3,locked:!0,reviewing:!1,round:0,status:"",verdict:"pending",wizard:{active:!1,draft:"",model:null,step:0,maxSteps:6,status:""}};function mp(){const e=new Map,t=new Map,n=(a,i)=>`${a}:${i}`;return{write(a,i,o){const l=n(a,i),u=e.get(l);if(u&&u.size>0){for(const b of u)try{b.write(o)}catch{}return}const p=t.get(l)??"",h=p.length+o.length>up?o:p+o;t.set(l,h)},register(a,i,o){const l=n(a,i);let u=e.get(l);u||(u=new Set,e.set(l,u)),u.add(o);const p=t.get(l);if(p){try{o.write(p)}catch{}t.delete(l)}return()=>{const h=e.get(l);h&&(h.delete(o),h.size===0&&e.delete(l)),t.delete(l)}},clear(){e.clear(),t.clear()}}}function lr(e,t){const n=new Set;for(const i of t.messages)i.role==="toolResult"&&i.toolCallId&&n.add(i.toolCallId),i.role==="bashExecution"&&n.add(`bash-${i.id}`);let a=!1;for(const i of e.keys())n.has(i)&&(e.delete(i),a=!0);return a?new Map(e):e}function cr(e,t){if(e.size===0)return e;const n=new Set;for(const i of t.messages)i.role==="toolResult"&&i.toolCallId&&n.add(i.toolCallId);let a=!1;for(const i of e.keys())n.has(i)&&(e.delete(i),a=!0);return a?new Map(e):e}function hp(e,t){switch(t.type){case"status":return{...e,status:t.status,ready:t.status==="open"?e.ready:!1,terminals:t.status==="closed"?[]:e.terminals};case"ready":return{...e,serverVersion:t.serverVersion,engine:t.engine,appVersion:t.appVersion,managed:t.managed===!0,tabs:t.tabs,ready:!0,protocolMismatch:t.protocolVersion!==void 0&&t.protocolVersion!==lp};case"snapshot":return{...e,ready:!0,state:t.state,activeConversationId:t.state.conversationId,liveOutputs:lr(e.liveOutputs,t.state),toolStatuses:cr(e.toolStatuses,t.state)};case"snapshot_delta":{const n=e.state,a=t.msg;if(!n||n.conversationId!==a.conversationId||n.rev!==a.baseRev)return e;const i={...n,...a.state,messages:a.appended.length>0?[...n.messages,...a.appended]:n.messages};return{...e,ready:!0,state:i,activeConversationId:i.conversationId,liveOutputs:lr(e.liveOutputs,i),toolStatuses:cr(e.toolStatuses,i)}}case"tool_delta":{const a=(e.liveOutputs.get(t.toolCallId)?.text??"")+t.delta,i=a.length>ga?`…[${dp}:${a.length-ga}]…
318
+ `+a.slice(a.length-ga):a,o=new Map(e.liveOutputs);return o.set(t.toolCallId,{toolName:t.toolName,text:i}),{...e,liveOutputs:o}}case"message_delta":{const n=e.state;return!n||n.conversationId!==t.msg.conversationId?e:{...e,state:Xd(n,t.msg)}}case"tool_status":return{...e,toolStatuses:new Map(e.toolStatuses).set(t.status.toolCallId,t.status)};case"notice":return{...e,notices:[...e.notices,t.notice].slice(-6)};case"dismiss_notice":return{...e,notices:e.notices.filter(n=>n.id!==t.id)};case"sessions":return{...e,sessions:t.sessions};case"conversations":return{...e,conversations:t.conversations,elsewhere:t.elsewhere??[],activeConversationId:t.activeId};case"projects":return{...e,projects:t.projects};case"files":return{...e,files:t.files};case"file_changed":return{...e,fileChanged:{path:t.path}};case"file_content":return{...e,fileContent:t.content};case"models":return{...e,models:t.models,modelsLoading:t.loading};case"models_config":return{...e,modelsConfig:t.providers};case"providers_status":return{...e,providers:t.providers};case"provider_keys":return{...e,providerKeys:t.keys};case"fetch_models_result":return{...e,fetchModelsResult:t.result};case"refresh_provider_result":return{...e,refreshProviderResult:t.result};case"clone_provider_result":return{...e,cloneProviderResult:t.result};case"install_result":return{...e,installResult:t.result};case"scm_data":return{...e,scmData:t.data};case"file_search_result":return{...e,fileSearch:t.result};case"session_search_result":return{...e,sessionSearch:t.result};case"scm_changed":return{...e,scmDirty:e.scmDirty+1};case"path_completions":return{...e,pathCompletions:t.completions};case"update_status":return{...e,update:t.status};case"update_status_all":return{...e,updatesAll:t.items};case"updates_check_started":return{...e,updatesAll:null};case"widgets":return{...e,widgets:t.widgets};case"statuses":return{...e,statuses:t.statuses};case"dialog":return{...e,dialog:t.dialog};case"question":return{...e,question:t.question};case"commands":return{...e,commands:t.commands,commandsPath:t.path};case"slash_commands":return{...e,slashCommands:t.commands};case"goal_status":return{...e,goal:t.status};case"settings":return{...e,settings:t.settings};case"bg_servers":return{...e,bgServers:t.servers};case"plugins":return{...e,plugins:t.plugins,pluginsEpoch:t.epoch};case"plugin_catalog":return{...e,pluginCatalog:t.entries,pluginCatalogEpoch:t.epoch};case"plugin_grants":return{...e,pluginGrants:t.grants};case"plugin_path_request":return{...e,pathRequests:[...e.pathRequests.filter(n=>n.id!==t.req.id),t.req]};case"plugin_path_resolved":return{...e,pathRequests:e.pathRequests.filter(n=>n.id!==t.id)};case"plugin_job":{const n=e.pluginJobs[t.job.jobId],a=t.line?[...n?.lines??[],t.line].slice(-40):n?.lines??[],i={...n,...t.job,lines:a,startedAt:n?.startedAt??Date.now()};return{...e,pluginJobs:{...e.pluginJobs,[t.job.jobId]:i}}}case"dsh_patches":return{...e,dshPatches:{patchDir:t.patchDir,files:t.files}};case"terminal_add":return{...e,terminals:[...e.terminals,t.meta]};case"terminal_remove":return{...e,terminals:e.terminals.filter(n=>n.id!==t.id)};case"terminal_exit":return t.conversationId&&(e.activeConversationId||e.state?.conversationId)&&t.conversationId!==(e.activeConversationId||e.state?.conversationId)?e:{...e,terminals:e.terminals.map(n=>n.id===t.terminalId?{...n,running:!1,exitCode:t.exitCode}:n)};case"terminal_restart":return{...e,terminals:e.terminals.map(n=>n.id===t.terminalId?{...n,running:!0,exitCode:null}:n)};case"terminal_list":return t.conversationId&&(e.activeConversationId||e.state?.conversationId)&&t.conversationId!==(e.activeConversationId||e.state?.conversationId)?e:{...e,terminals:t.terminals.map(n=>({...n,conversationId:t.conversationId??e.state?.conversationId??""}))};case"terminal_active":return{...e,terminalActiveId:t.id};default:return e}}const ur="pi-web-client-id";let ba=null;function Fn(){if(ba)return ba;let e=null;try{e=sessionStorage.getItem(ur),e||(e=St(),sessionStorage.setItem(ur,e))}catch{e=e??St()}return ba=e,e}const nl="pi-web-last-cwd";function fp(){try{return localStorage.getItem(nl)}catch{return null}}function gp(e){try{localStorage.setItem(nl,e)}catch{}}function bp(){const e=location.protocol==="https:"?"wss:":"ws:";return Ft(`${e}//${location.host}${lt("/ws")}`)}function Ep(){const[e,t]=c.useReducer(hp,{status:"connecting",ready:!1,state:null,liveOutputs:new Map,toolStatuses:new Map,notices:[],sessions:[],conversations:[],elsewhere:[],activeConversationId:"",projects:[],files:null,fileChanged:null,fileContent:null,models:[],modelsLoading:!1,modelsConfig:[],providers:[],providerKeys:{},installResult:null,pathCompletions:[],update:null,updatesAll:null,widgets:[],statuses:[],dialog:null,question:null,commands:[],commandsPath:"",slashCommands:[],terminals:[],terminalActiveId:null,goal:pp,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,sessionSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,pluginCatalog:[],pluginCatalogEpoch:0,pluginJobs:{},pluginGrants:[],pathRequests:[],dshPatches:null,protocolMismatch:!1}),n=c.useRef(null),a=c.useRef(mp()),i=c.useRef(0),o=c.useRef(null),l=c.useRef(!0),u=c.useRef(0),p=c.useRef(0),h=c.useRef(new Map),b=c.useRef(null),m=c.useRef(!1),f=c.useRef(null),x=c.useRef(new Set),v=c.useRef("live"),N=()=>{b.current||(b.current=setTimeout(()=>{b.current=null;const L=n.current;L&&L.readyState===WebSocket.OPEN&&L.send(JSON.stringify({type:"get_state"}))},300))},B=(L,H)=>{const T=h.current,F=T.get(L);if(F!==void 0&&H!==F+1){const Y=J.current.chat,D=Y.activeConversationId||Y.state?.conversationId;L===D&&N()}T.set(L,H)},V=c.useCallback((L,H)=>{const T=++p.current;t({type:"notice",notice:{id:T,level:L,text:H}})},[]),W=c.useCallback(L=>{const H=n.current;if(H&&H.readyState===WebSocket.OPEN){if(L.type==="check_updates_all"&&L.force===!0&&t({type:"updates_check_started"}),H.send(JSON.stringify(L)),L.type==="question_answer"){if(x.current.add(L.id),x.current.size>64){const T=x.current.values().next().value;T!==void 0&&x.current.delete(T)}v.current="live",t({type:"question",question:null})}return!0}return!1},[]),I=c.useCallback(L=>{const H=Jd({current:J.current.chat.question,source:v.current,snapshot:L,answered:x.current});H.changed&&(v.current=H.source,t({type:"question",question:H.question}))},[]);Hd(W);const j=c.useCallback(()=>{if(!l.current)return;t({type:"status",status:"connecting"});const L=new WebSocket(bp());n.current=L,L.onopen=()=>{n.current===L&&(t({type:"status",status:"open"}),i.current=0,u.current=Date.now(),L.send(JSON.stringify({type:"hello",clientId:Fn(),locale:rr()})))},L.onmessage=H=>{if(n.current!==L)return;u.current=Date.now();let T;try{T=JSON.parse(H.data)}catch{return}switch(T.type){case"ready":{const F="20260915T02381";if((J.current.chat.settings?.autoReload??!0)&&T.buildId&&F&&T.buildId!==F){const D=`pi-web-ui-reloaded-${T.buildId}`;if(!sessionStorage.getItem(D)){sessionStorage.setItem(D,"1"),location.reload();return}}Ji({engine:T.engine??"pi",managed:!!T.managed,tabs:T.tabs,appVersion:T.appVersion,serverVersion:T.serverVersion,service:T.service}),t({type:"ready",serverVersion:T.serverVersion,protocolVersion:T.protocolVersion,engine:T.engine,appVersion:T.appVersion,managed:T.managed,tabs:T.tabs,service:T.service}),L.send(JSON.stringify({type:"get_state"})),L.send(JSON.stringify({type:"list_files"})),L.send(JSON.stringify({type:"list_models"})),L.send(JSON.stringify({type:"list_commands"})),L.send(JSON.stringify({type:"get_commands"})),T.managed||(L.send(JSON.stringify({type:"check_update"})),L.send(JSON.stringify({type:"check_updates_all"})));break}case"snapshot":h.current=new Map,t({type:"snapshot",state:T.state}),I(T.state.pendingQuestion);break;case"snapshot_delta":{const F=J.current.chat.state;(!F||F.conversationId!==T.conversationId||F.rev!==T.baseRev)&&N(),t({type:"snapshot_delta",msg:T}),I(T.state.pendingQuestion);break}case"tool_delta":B(T.conversationId,T.seq),t({type:"tool_delta",toolCallId:T.toolCallId,toolName:T.toolName,delta:T.delta});break;case"tool_status":t({type:"tool_status",status:T});break;case"message_delta":{B(T.conversationId,T.seq),t({type:"message_delta",msg:T});break}case"notice":{const F=++p.current;t({type:"notice",notice:{id:F,level:T.level,text:T.text,textEn:T.textEn}});break}case"sessions":t({type:"sessions",sessions:T.sessions});break;case"conversations":t({type:"conversations",conversations:T.conversations,activeId:T.activeId,elsewhere:T.elsewhere});break;case"projects":t({type:"projects",projects:T.projects});break;case"files":t({type:"files",files:T});break;case"file_changed":t({type:"file_changed",path:T.path});break;case"file_content":t({type:"file_content",content:T});break;case"models":t({type:"models",models:T.models,loading:!1});break;case"models_config":t({type:"models_config",providers:T.providers});break;case"providers_status":t({type:"providers_status",providers:T.providers});break;case"provider_keys":t({type:"provider_keys",keys:T.keys});break;case"fetch_models_result":t({type:"fetch_models_result",result:{reqId:T.reqId,ok:T.ok,models:T.models,error:T.error}});break;case"refresh_provider_result":t({type:"refresh_provider_result",result:{reqId:T.reqId,ok:T.ok,added:T.added,total:T.total,error:T.error}});break;case"clone_provider_result":t({type:"clone_provider_result",result:{reqId:T.reqId,ok:T.ok,config:T.config,configs:T.configs,error:T.error}});break;case"scm_data":t({type:"scm_data",data:T});break;case"search_files_result":t({type:"file_search_result",result:{reqId:T.reqId,ok:T.ok,results:T.results,truncated:T.truncated}});break;case"session_search_results":t({type:"session_search_result",result:{reqId:T.reqId,ok:T.ok,results:T.results}});break;case"scm_changed":t({type:"scm_changed"});break;case"install_result":t({type:"install_result",result:T});break;case"path_completions":t({type:"path_completions",completions:T.completions});break;case"update_status":t({type:"update_status",status:T});break;case"update_status_all":t({type:"update_status_all",items:T.items});break;case"widgets":t({type:"widgets",widgets:T.widgets});break;case"statuses":t({type:"statuses",statuses:T.statuses});break;case"dialog":t({type:"dialog",dialog:{id:T.id,kind:T.kind,title:T.title,args:T.args}});break;case"dialog_closed":t({type:"dialog",dialog:null});break;case"question_pending":v.current="live",t({type:"question",question:{id:T.id,...T.deadline!==void 0?{deadline:T.deadline}:{},questions:T.questions}});break;case"page_request":{(async()=>{const F=window.__piWebUiHost;let Y;if(!F?.pageCall)Y={ok:!1,error:"宿主页面桥不可用(页面版本过旧?)—— 刷新本页后再试"};else try{Y=await F.pageCall({op:T.op,...T.args===void 0?{}:{args:T.args},...T.target?{target:T.target}:{},timeoutMs:T.timeoutMs})}catch(D){Y={ok:!1,error:D instanceof Error?D.message:String(D)}}W({type:"page_response",id:T.id,ok:Y.ok===!0,...Y.ok===!0?Y.result===void 0?{}:{result:Y.result}:{error:Y.error??"页面操作失败"}})})();break}case"terminal_output":a.current.write(T.conversationId??J.current.chat.activeConversationId,T.terminalId,T.data);break;case"terminal_exit":t({type:"terminal_exit",conversationId:T.conversationId,terminalId:T.terminalId,exitCode:T.exitCode});break;case"terminal_list":t({type:"terminal_list",conversationId:T.conversationId,terminals:T.terminals});break;case"commands":t({type:"commands",commands:T.commands,path:T.path});break;case"slash_commands":t({type:"slash_commands",commands:T.commands});break;case"goal_status":t({type:"goal_status",status:T.status});break;case"settings_state":t({type:"settings",settings:T.settings});break;case"bg_servers":t({type:"bg_servers",servers:T.servers});break;case"plugins":t({type:"plugins",plugins:T.plugins,epoch:T.epoch});break;case"plugin_catalog":t({type:"plugin_catalog",entries:T.entries,epoch:T.epoch});break;case"plugin_grants":t({type:"plugin_grants",grants:T.grants});break;case"plugin_path_request":t({type:"plugin_path_request",req:{id:T.id,pluginId:T.pluginId,path:T.path,...T.reason?{reason:T.reason}:{}}});break;case"plugin_job":t({type:"plugin_job",job:{jobId:T.jobId,action:T.action,pluginId:T.pluginId,phase:T.phase,...T.ok===void 0?{}:{ok:T.ok},...T.error?{error:T.error}:{},...T.output?{output:T.output}:{}},...T.line?{line:T.line}:{}});break;case"plugin_catalog_sync_result":np(T);break;case"dsh_patches":t({type:"dsh_patches",patchDir:T.patchDir,files:T.files});break;case"plugin_data":ap(T.pluginId,T.payload);break}},L.onclose=()=>{if(n.current===L&&(n.current=null),a.current.clear(),!l.current||n.current&&n.current!==L)return;t({type:"status",status:"closed"});const H=Math.min(1e3*2**i.current,1e4);i.current+=1,o.current=setTimeout(()=>{o.current=null,j()},H)},L.onerror=()=>{}},[]);c.useEffect(()=>{const L=H=>{const T=H.detail??rr();T&&W({type:"set_locale",locale:T})};return window.addEventListener(or,L),()=>window.removeEventListener(or,L)},[W]),c.useEffect(()=>{l.current=!0,j();const L=setInterval(()=>{if(!l.current)return;const H=n.current;H&&H.readyState===WebSocket.OPEN&&Date.now()-u.current>3e4&&H.close()},5e3);return()=>{l.current=!1,clearInterval(L),o.current&&(clearTimeout(o.current),o.current=null),n.current?.close(),n.current=null}},[j]),c.useEffect(()=>{const L=e.state?.cwd;if(L){if(!m.current){m.current=!0;const H=fp();if(H&&H!==L){W({type:"set_cwd",path:H});return}}f.current!==L&&(f.current=L,gp(L))}},[e.state?.cwd,W]),c.useEffect(()=>{Ji({ready:e.ready,status:e.status,cwd:e.state?.cwd??"",workspaceRoots:e.state?.workspaceRoots??[]})},[e.ready,e.status,e.state?.cwd,e.state?.workspaceRoots]);const X=c.useCallback(L=>t({type:"dismiss_notice",id:L}),[]),w=c.useCallback(L=>t({type:"terminal_add",meta:L}),[]),ce=c.useCallback(L=>t({type:"terminal_remove",id:L}),[]),be=c.useCallback(L=>t({type:"terminal_restart",terminalId:L}),[]),$=c.useCallback(L=>t({type:"terminal_active",id:L}),[]),K=c.useCallback((L,H,T)=>a.current.register(L,H,T),[]),J=c.useRef({chat:e,send:W,pushNotice:V,dismissNotice:X,terminal:{create:w,close:ce,register:K,restart:be,select:$}});return J.current={chat:e,send:W,pushNotice:V,dismissNotice:X,terminal:{create:w,close:ce,register:K,restart:be,select:$}},J.current}const Tp=200*1024*1024,xp=/windows/i.test(navigator.userAgent),yp=/[<>:"/\\|?*\u0000-\u001f]/g,kp=/[. ]+$/,Np=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function vp(e){const t=e.replace(yp,"_").replace(kp,"");return t?Np.test(t)?`_${t}`:t:"_"}function dr(e,t=!0){const n=new URLSearchParams({clientId:Fn(),path:e,...t?{download:"1"}:{}});return Ft(lt(`/api/file?${n}`))}const al="FILE_NOT_FOUND";async function Cp(e,t){const n=xp?vp(t):t;try{const a=await fetch(dr(e));if(!a.ok)return{ok:!1,cancelled:!1,error:await a.text().catch(()=>"")||(a.status===404?al:`HTTP ${a.status}`)};if(Number(a.headers.get("content-length")??"0")>Tp)return window.location.assign(dr(e)),{ok:!0};const o=await a.blob();return window.showSaveFilePicker&&window.isSecureContext?wp(o,n):$a(o,n)}catch(a){return{ok:!1,cancelled:!1,error:a instanceof Error?a.message:String(a)}}}async function wp(e,t){let n;const a=window.showSaveFilePicker;if(!a)return $a(e,t);try{n=await a({suggestedName:t})}catch(i){return i instanceof DOMException&&i.name==="AbortError"?{ok:!1,cancelled:!0}:$a(e,t)}try{const i=await n.createWritable();return await i.write(e),await i.close(),{ok:!0}}catch(i){return{ok:!1,cancelled:!1,error:i instanceof Error?i.message:String(i)}}}function $a(e,t){const n=URL.createObjectURL(e),a=document.createElement("a");return a.href=n,a.download=t,document.body.appendChild(a),a.click(),a.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4),{ok:!0}}function Sp(e){return e instanceof Error?e.message:String(e)}function _p(e,t,n,a){const i=n==="zh";switch(e.kind){case"no-client":return i?`插件 ${t} 没有客户端脚本(client/entry.mjs),无法显示这一页。`:`Plugin ${t} ships no client bundle (client/entry.mjs), so this page cannot be shown.`;case"load":return i?`插件 ${t} 的页面脚本加载失败:${e.detail}`:`Failed to load plugin ${t}'s page bundle: ${e.detail}`;case"mount":return`${a("pluginMountFailed",{name:t})}:${e.detail}`}}function il({plugin:e,epoch:t,send:n,className:a}){const i=c.useRef(null),{locale:o}=Ut(),l=Pe(),[u,p]=c.useState(null),h=c.useRef(n);c.useEffect(()=>{h.current=n},[n]),c.useEffect(()=>{const m=i.current;if(!m)return;let f=!1,x,v=!1;if(p(null),!e.hasClient){p({kind:"no-client"});return}return(async()=>{try{if(await Ua(e,t),f)return;const N=await Jo(e.id,()=>import(lt(`/plugins/${encodeURIComponent(e.id)}/client/entry.mjs?e=${t}`)));if(f)return;const B=N.default;if(!B||typeof B.mount!="function")throw new Error("client/entry.mjs 没有导出 default.mount()");v=!0,x=B.mount(m,sl(e.id,V=>h.current(V)))}catch(N){if(f)return;console.error(`[plugin:${e.id}] 页面${v?"挂载":"加载"}失败:`,N),p({kind:v?"mount":"load",detail:Sp(N)})}})(),()=>{if(f=!0,typeof x=="function")try{x()}catch(N){console.error(`[plugin:${e.id}] cleanup 失败:`,N)}m.textContent=""}},[e.id,e.hasClient,t]);const b=a?`plugin-page ${a}`:"plugin-page";return s.jsxs("div",{className:b,children:[s.jsx("div",{className:"plugin-page-host",ref:i}),u&&s.jsx("div",{className:"plugin-page-error",role:"alert",children:_p(u,e.name,o,l)})]})}function rl(e){return`pi-web-ui:${e}:tab`}function Ap(e,t){try{const n=localStorage.getItem(rl(e));return n&&t.some(a=>a.id===n)?n:null}catch{return null}}function pr(e,t){try{localStorage.setItem(rl(e),t)}catch{}}function Ip(e){return e.length>0&&!/[a-z]/i.test(e)}function mr(e){if(e.label)return e.label;const t=e.pluginPage;return t?.entry.label||t?.plugin.name||e.id}function jp({storageKey:e,tabs:t,epoch:n,send:a,extra:i,className:o}){const l=c.useId(),[u,p]=c.useState(()=>Ap(e,t)??t[0]?.id??""),h=c.useRef([]),b=c.useRef(""),m=t.findIndex(W=>W.id===u),f=m>=0?t[m]:t[0],x=f?t.indexOf(f):-1;c.useEffect(()=>{if(!f)return;u!==f.id&&p(f.id);const W=`${e}:${f.id}`;b.current!==W&&(b.current=W,pr(e,f.id))},[f,u,e]);const v=W=>{p(W.id),b.current=`${e}:${W.id}`,pr(e,W.id)},N=(W,I)=>{const j=t.length;let X=-1;if(W.key==="ArrowRight")X=(I+1)%j;else if(W.key==="ArrowLeft")X=(I-1+j)%j;else if(W.key==="Home")X=0;else if(W.key==="End")X=j-1;else return;const w=t[X];w&&(W.preventDefault(),v(w),h.current[X]?.focus())};if(!f)return null;const B=`${l}-panel-${x}`,V=o?`slot-tabs ${o}`:"slot-tabs";return s.jsxs("div",{className:V,children:[s.jsxs("div",{className:"slot-tabs-bar",role:"tablist",children:[t.map((W,I)=>{const j=I===x;return s.jsxs("button",{type:"button",role:"tab",id:`${l}-tab-${I}`,className:j?"slot-tab active":"slot-tab",title:W.hint??mr(W),"aria-selected":j,"aria-controls":`${l}-panel-${I}`,tabIndex:j?0:-1,ref:X=>{h.current[I]=X},onClick:()=>v(W),onKeyDown:X=>N(X,I),children:[W.icon&&Ip(W.icon)?s.jsx("span",{className:"slot-tab-icon",children:W.icon}):null,s.jsx("span",{className:"slot-tab-label",children:mr(W)})]},W.id)}),i?s.jsx("div",{className:"slot-tabs-extra",children:i}):null]}),s.jsx("div",{className:"slot-tabs-body",id:B,role:"tabpanel","aria-labelledby":`${l}-tab-${x}`,children:f.pluginPage?s.jsx(il,{plugin:f.pluginPage.plugin,epoch:n,send:a}):f.element??null})]})}const cs="@root",hr="pi-web-ui:rp-sizes",Ea={files:4,widgets:1},fr=120,gr=56;function Rp(e,t){return t?Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top):32}const Lp="files",Dp=[],Pp=()=>{},Op=c.memo(function({files:t,fileChanged:n,widgets:a,panelSend:i,onAttach:o,onPreview:l,onNotice:u,collapsible:p,onToggleCollapse:h,uiRightPanelTabs:b,uiContextFile:m,plugins:f,pluginsEpoch:x,send:v}){const N=Pe(),B=f??Dp,V=wt("cwd"),W=wt("workspaceRoots"),[I,j]=c.useState(""),[X,w]=c.useState(null),[ce,be]=c.useState(!1),$=c.useRef(null),K=c.useRef(null),[J,L]=c.useState(()=>{try{return zo(localStorage.getItem(hr),Ea)}catch{return{...Ea}}});c.useEffect(()=>{try{localStorage.setItem(hr,JSON.stringify(J))}catch{}},[J]);const H=a.some(C=>C.lines.length>0),T=c.useCallback(C=>{C.preventDefault();const _=$.current;if(!_)return;const me=C.currentTarget,Ne=C.clientY,$e={above:J.files,below:J.widgets},Ie=Math.max(120,_.clientHeight-Rp(_,K.current));me.classList.add("dragging"),document.body.classList.add("rp-resizing");const Qe=ut=>{const{above:Dt,below:Pt}=Vo({start:$e,deltaPx:ut.clientY-Ne,availablePx:Ie,totalWeight:$e.above+$e.below,minAbovePx:fr,minBelowPx:gr});L({files:Dt,widgets:Pt})},gt=()=>{window.removeEventListener("pointermove",Qe),window.removeEventListener("pointerup",gt),me.classList.remove("dragging"),document.body.classList.remove("rp-resizing")};window.addEventListener("pointermove",Qe),window.addEventListener("pointerup",gt)},[J.files,J.widgets]),F=c.useRef(null),Y=c.useRef(0),D=c.useCallback(C=>{F.current=C,C&&(C.scrollTop=Y.current)},[]),[ae,ee]=c.useState(null),ve=c.useRef(null);c.useEffect(()=>()=>{ve.current&&clearTimeout(ve.current)},[]);const S=c.useCallback(C=>{ee(C),ve.current&&clearTimeout(ve.current),ve.current=setTimeout(()=>ee(null),1200)},[]),de=C=>{try{const _=document.createElement("textarea");_.value=C,_.style.position="fixed",_.style.opacity="0",document.body.appendChild(_),_.select();const me=document.execCommand("copy");return document.body.removeChild(_),me}catch{return!1}},ue=c.useCallback((C,_)=>{if(!C)return;const me=()=>S(_),Ne=()=>u("error",N("slashCopyFailed")),$e=navigator;$e.clipboard?.writeText?$e.clipboard.writeText(C).then(me,()=>{de(C)?me():Ne()}):de(C)?me():Ne()},[S,u,N]),pe=c.useCallback(C=>{if(!C)return V;if(/^[A-Za-z]:$/.test(C))return`${C}/`;if(C.startsWith("/")||/^[A-Za-z]:([/]|$)/.test(C))return C;const _=V.replace(/\\/g,"/").replace(/\/+$/,"");return _?`${_}/${C}`:C},[V]),ke=c.useCallback(C=>!C||C===cs?null:C.startsWith("/")||/^[A-Za-z]:([/]|$)/.test(C)?C:`${V.replace(/\\/g,"/").replace(/\/+$/,"")}/${C}`,[V]),Oe=c.useCallback((C,_)=>{for(const me of _){const Ne=new FileReader;Ne.onload=()=>{const $e=Ne.result,Ie=$e.slice($e.indexOf(",")+1);Ie&&i({type:"upload_file",dirPath:C,name:me.name,data:Ie})},Ne.readAsDataURL(me)}},[i]),ye=c.useRef(null),we=c.useRef(null),Ce=c.useCallback(()=>{const C=ye.current?.project;C&&i({type:"set_cwd",path:C.path})},[i]),qe=c.useCallback(()=>{we.current&&(we.current.value=""),we.current?.click()},[]),[Be,se]=c.useState(!1);c.useEffect(()=>{if(!Be)return;const C=me=>{me.target?.closest(".root-picker")||se(!1)},_=me=>{me.key==="Escape"&&se(!1)};return window.addEventListener("mousedown",C,!0),window.addEventListener("keydown",_),()=>{window.removeEventListener("mousedown",C,!0),window.removeEventListener("keydown",_)}},[Be]);const Te=c.useCallback(C=>{i({type:"set_workspace_roots",roots:C})},[i]),De=c.useCallback(()=>{const C=ye.current?.target;if(!C||C.kind!=="dir")return;const _=ke(C.id);!_||W.includes(_)||Te([...W,_])},[W,ke,Te]),Re=c.useCallback(C=>{Oe(ye.current?.dir??I,Array.from(C.target.files??[]))},[Oe,I]),Ye=c.useCallback(C=>{C.id==="host:file-open-project"?Ce():C.id==="host:file-upload"?qe():C.id==="host:file-add-root"&&De()},[Ce,qe,De]),A=c.useCallback((C,_)=>{const me=_.kind==="dir"?ke(_.id):null,Ne={target:_,dir:_.kind==="dir"?_.id:I,project:me?{path:me,name:_.label}:null},$e=(m??[]).map(Ie=>Ie.source!=="host"?Ie:Ie.id==="host:file-upload"?{...Ie,label:Ne.dir===I?N("uploadToCurrentDir"):N("uploadToFolder")}:Ie.id==="host:file-open-project"?me?Ie:{...Ie,hidden:!0}:Ie.id==="host:file-add-root"?!!me&&me!==V&&!W.includes(me)?Ie:{...Ie,hidden:!0}:Ie);On($e).length!==0&&(C.preventDefault(),C.stopPropagation(),ye.current=Ne,ea({x:C.clientX,y:C.clientY,slot:"contextmenu.file",target:_,entries:$e,onHostAction:Ye}))},[m,I,ke,N,Ye,V,W]),Q=C=>Array.from(C.dataTransfer?.types??[]).includes("Files"),z=c.useCallback(()=>{F.current?.querySelectorAll(".file-item.drop-target").forEach(C=>C.classList.remove("drop-target")),F.current?.classList.remove("drop-root")},[]),ge=c.useCallback(C=>{if(z(),C==null)return;const _=F.current?.querySelector(`.file-item[data-path="${CSS.escape(C)}"]`);_?_.classList.add("drop-target"):F.current?.classList.add("drop-root")},[z]),oe=C=>{const _=C instanceof Element?C.closest(".file-item"):null;return _?.dataset.type==="dir"?_.dataset.path??I:I},Z=c.useCallback(()=>{const C=document.querySelector(".app");C&&C.dispatchEvent(new DragEvent("dragleave",{bubbles:!0}))},[]),y=1e4,P=c.useRef(0),le=c.useRef(void 0),Ee=c.useCallback((C,_)=>{const me=++P.current;j(C),_?.silent||be(!0),i({type:"list_files",path:C===""?void 0:C})||P.current===me&&be(!1)},[i]),Ae=c.useCallback(C=>{const _=W.filter(me=>me!==C);Te(_),(I===C||I.startsWith(`${C}/`))&&Ee("")},[W,Te,I,Ee]);c.useEffect(()=>{t&&t.path===I&&be(!1)},[t,I]),c.useEffect(()=>{if(V!==le.current){le.current=V,Ee("",{silent:!0});return}const C=setInterval(()=>{document.visibilityState!=="hidden"&&Ee(I,{silent:!0})},y);return()=>clearInterval(C)},[V,I,Ee]),c.useEffect(()=>{n&&n.path===I&&Ee(I,{silent:!0})},[n,I,Ee]);const Me=C=>Ee(C),Le=()=>{t?.parent!==null&&t?.parent!==void 0&&Ee(t.parent)},Ge=(()=>{if(I===""||I===cs)return[];const C=I.split("/").filter(_=>!!_&&_!==cs);return I.startsWith("/")?C.map((_,me)=>({label:me===0?"/":C[me],path:"/"+C.slice(0,me+1).join("/")})):C.map((_,me)=>({label:C[me],path:C.slice(0,me+1).join("/")}))})(),R=[];for(const C of b??[]){if(C.source==="host"||C.hidden||C.kind==="divider")continue;const _=B.find(me=>me.id===C.source.slice(7));_&&R.push({id:C.id,label:C.label,icon:C.icon,hint:C.hint,pluginPage:{plugin:_,entry:C}})}const He=(b??[]).some(C=>C.id==="host:right-files"&&C.hidden);return s.jsxs("aside",{className:"panel panel-right",ref:$,children:[p&&h&&s.jsx("button",{type:"button",className:"panel-collapse-btn",title:N("collapsePanel"),onClick:h,children:s.jsx(So,{})}),s.jsx("div",{ref:K,style:{display:"flex",flexDirection:"column",flex:H?`${J.files} 1 0`:"1 1 0",minHeight:H?fr:0},children:s.jsx(jp,{storageKey:"rightpanel",epoch:x??0,send:v??Pp,tabs:[...He?[]:[{id:Lp,label:N("openFiles"),element:s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"panel-crumbs",children:[s.jsx("button",{type:"button",className:`crumb ${I===""?"active":""}`,onClick:()=>Ee(""),children:N("rootDir")}),s.jsx("button",{type:"button",className:`crumb ${I===cs?"active":""}`,title:N("computer"),onClick:()=>Ee(cs),children:"💻"}),W.length>0&&s.jsxs("div",{className:"root-picker",children:[s.jsxs("button",{type:"button",className:"crumb root-picker-trigger","aria-haspopup":"menu","aria-expanded":Be,title:N("workspaceRoots"),onClick:()=>se(C=>!C),children:[s.jsx(Bt,{}),s.jsx("span",{className:"root-picker-label",children:N("workspaceRoots")}),s.jsx("span",{className:"set-count",children:W.length+1}),"▾"]}),Be&&s.jsxs("div",{className:"root-picker-menu",role:"menu",children:[s.jsx("div",{className:"root-picker-row",children:s.jsxs("button",{type:"button",role:"menuitem",className:I===""?"root-picker-item active":"root-picker-item",title:V,onClick:()=>{se(!1),Ee("")},children:[N("rootDir"),s.jsx("span",{className:"root-picker-path",children:V})]})}),W.map(C=>s.jsxs("div",{className:"root-picker-row",children:[s.jsx("button",{type:"button",role:"menuitem",className:I===C?"root-picker-item active":"root-picker-item",title:C,onClick:()=>{se(!1),Ee(C)},children:s.jsx("span",{className:"root-picker-path",children:C})}),s.jsx("button",{type:"button",className:"root-picker-remove",title:N("removeWorkspaceRoot"),"aria-label":N("removeWorkspaceRoot"),onClick:()=>Ae(C),children:s.jsx(tt,{})})]},C)),s.jsx("div",{className:"root-picker-hint",children:N("workspaceRootsHint")})]})]}),Ge.map(C=>s.jsxs("span",{className:"crumb-seg",children:[s.jsx(rs,{}),s.jsx("button",{type:"button",className:`crumb ${C.path===I?"active":""}`,onClick:()=>Ee(C.path),children:C.label})]},C.path))]}),s.jsxs("div",{ref:D,className:"panel-body",onScroll:C=>{Y.current=C.currentTarget.scrollTop},onContextMenu:C=>A(C,{id:I,kind:"list",label:I===""?N("rootDir"):I===cs?N("computer"):I}),onDragOver:C=>{Q(C)&&(C.preventDefault(),C.stopPropagation(),C.dataTransfer.dropEffect="copy",Z(),ge(oe(C.target)))},onDragLeave:C=>{C.relatedTarget&&C.currentTarget.contains(C.relatedTarget)||z()},onDrop:C=>{if(z(),!Q(C))return;C.preventDefault(),C.stopPropagation(),Z();const _=Array.from(C.dataTransfer?.files??[]);if(_.length===0){u("warning",N("foldersNotSupported"));return}Oe(oe(C.target),_)},onDragEnd:z,children:[s.jsx("input",{ref:we,type:"file",multiple:!0,hidden:!0,onChange:Re}),ce&&s.jsx("div",{className:"panel-empty",children:N("loading")}),!ce&&t&&t.path===I&&s.jsxs(s.Fragment,{children:[t.parent!=null&&s.jsxs("button",{type:"button",className:"file-item dir",onClick:Le,children:[s.jsx(Bt,{className:"file-icon"}),s.jsx("span",{className:"file-name",children:".."})]}),t.entries.map(C=>C.type==="dir"?s.jsxs("div",{className:"file-item dir","data-type":"dir","data-path":C.path,onContextMenu:_=>A(_,{id:C.path,kind:"dir",label:C.name}),children:[s.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>Me(C.path),children:[s.jsx(Bt,{className:"file-icon"}),s.jsx("span",{className:"file-name",children:C.name})]}),s.jsx("button",{type:"button",className:"file-attach ref","data-tip":N("linkFolderTip"),"aria-label":N("linkFolderTip"),onClick:()=>o(C.path,C.name,"reference",!0),children:s.jsx(ja,{})}),s.jsx("button",{type:"button",className:`file-attach copy${ae===`name:${C.path}`?" copied":""}`,"data-tip":N("copyName"),"aria-label":N("copyName"),onClick:()=>ue(C.name,`name:${C.path}`),children:ae===`name:${C.path}`?s.jsx(Rt,{}):s.jsx(Lt,{})}),s.jsx("button",{type:"button",className:`file-attach copy${ae===`path:${C.path}`?" copied":""}`,"data-tip":N("copyPath"),"aria-label":N("copyPath"),onClick:()=>ue(pe(C.path),`path:${C.path}`),children:ae===`path:${C.path}`?s.jsx(Rt,{}):s.jsx(Oi,{})})]},C.path):s.jsxs("div",{className:"file-item file","data-type":"file","data-path":C.path,onContextMenu:_=>A(_,{id:C.path,kind:"file",label:C.name}),children:[s.jsxs("button",{type:"button",className:"file-name",title:`${C.path} — ${N("previewFile")}`,onClick:()=>l(C.path,C.name),children:[s.jsx(Uu,{className:"file-icon"}),s.jsx("span",{className:"file-name-text",children:C.name})]}),s.jsx("button",{type:"button",className:"file-attach download","data-tip":N("downloadFile"),onClick:()=>{Cp(C.path,C.name).then(_=>{_.ok||_.cancelled||u("error",N("downloadFailed",{error:_.error===al?N("fileNotFoundShort"):_.error}))})},children:s.jsx(ss,{})}),s.jsx("button",{type:"button",className:"file-attach inline","data-tip":N("attachInlineTip"),onClick:()=>o(C.path,C.name,"inline"),children:s.jsx(yt,{})}),s.jsx("button",{type:"button",className:"file-attach ref","data-tip":N("referenceTip"),"aria-label":N("referenceTip"),onClick:()=>o(C.path,C.name,"reference"),children:s.jsx(ja,{})}),s.jsx("button",{type:"button",className:`file-attach copy${ae===`name:${C.path}`?" copied":""}`,"data-tip":N("copyName"),"aria-label":N("copyName"),onClick:()=>ue(C.name,`name:${C.path}`),children:ae===`name:${C.path}`?s.jsx(Rt,{}):s.jsx(Lt,{})}),s.jsx("button",{type:"button",className:`file-attach copy${ae===`path:${C.path}`?" copied":""}`,"data-tip":N("copyPath"),"aria-label":N("copyPath"),onClick:()=>ue(pe(C.path),`path:${C.path}`),children:ae===`path:${C.path}`?s.jsx(Rt,{}):s.jsx(Oi,{})})]},C.path)),t.truncated&&s.jsx("div",{className:"panel-empty files-truncated",children:N("filesTruncated")})]}),!ce&&!t&&s.jsx("div",{className:"panel-empty",children:N("noFiles")})]})]})}],...R]})}),H&&s.jsx("div",{className:"rp-sash",onPointerDown:T,onDoubleClick:()=>L({...Ea}),title:N("dragToResize")}),H&&s.jsx("div",{className:"panel-widgets",style:{flexGrow:J.widgets,minHeight:gr},children:a.filter(C=>C.lines.length>0).map(C=>s.jsxs("div",{className:"widget",children:[s.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:N("widgetExpand"),onClick:()=>w(C.key),children:[s.jsx("span",{children:C.key}),s.jsx(Du,{})]}),s.jsx("pre",{className:"widget-lines",children:C.lines.join(`
319
+ `)})]},C.key))}),X&&(()=>{const C=a.find(_=>_.key===X);return C?s.jsx("div",{className:"modal-backdrop",onClick:()=>w(null),children:s.jsxs("div",{className:"widget-expand",onClick:_=>_.stopPropagation(),children:[s.jsxs("div",{className:"widget-expand-head",children:[s.jsx("span",{className:"widget-expand-title",children:C.key}),s.jsx("button",{type:"button",className:"btn",title:N("close"),onClick:()=>w(null),children:s.jsx(tt,{})})]}),s.jsx("pre",{className:"widget-expand-lines",children:C.lines.join(`
320
+ `)})]})}):null})()]})});var ta=xo();function Mp(e){tu(e,[/\r?\n|\r/g,Bp])}function Bp(){return{type:"break"}}function Fp(){return function(e){Mp(e)}}function Hp(e){const t=String(e),n=[];return{toOffset:i,toPoint:a};function a(o){if(typeof o=="number"&&o>-1&&o<=t.length){let l=0;for(;;){let u=n[l];if(u===void 0){const p=br(t,n[l-1]);u=p===-1?t.length+1:p+1,n[l]=u}if(u>o)return{line:l+1,column:o-(l>0?n[l-1]:0)+1,offset:o};l++}}}function i(o){if(o&&typeof o.line=="number"&&typeof o.column=="number"&&!Number.isNaN(o.line)&&!Number.isNaN(o.column)){for(;n.length<o.line;){const u=n[n.length-1],p=br(t,u),h=p===-1?t.length+1:p+1;if(u===h)break;n.push(h)}const l=(o.line>1?n[o.line-2]:0)+o.column-1;if(l<n[o.line-1])return l}}}function br(e,t){const n=e.indexOf("\r",t),a=e.indexOf(`
321
+ `,t);return a===-1?n:n===-1||n+1===a?a:n<a?n:a}const ol={}.hasOwnProperty,Up=Object.prototype;function $p(e,t){const n=t||{};return li({file:n.file||void 0,location:!1,schema:n.space==="svg"?Xn:ri,verbose:n.verbose||!1},e)}function li(e,t){let n;switch(t.nodeName){case"#comment":{const a=t;return n={type:"comment",value:a.data},xn(e,a,n),n}case"#document":case"#document-fragment":{const a=t,i="mode"in a?a.mode==="quirks"||a.mode==="limited-quirks":!1;if(n={type:"root",children:ll(e,t.childNodes),data:{quirksMode:i}},e.file&&e.location){const o=String(e.file),l=Hp(o),u=l.toPoint(0),p=l.toPoint(o.length);n.position={start:u,end:p}}return n}case"#documentType":{const a=t;return n={type:"doctype"},xn(e,a,n),n}case"#text":{const a=t;return n={type:"text",value:a.value},xn(e,a,n),n}default:return n=qp(e,t),n}}function ll(e,t){let n=-1;const a=[];for(;++n<t.length;){const i=li(e,t[n]);a.push(i)}return a}function qp(e,t){const n=e.schema;e.schema=t.namespaceURI===Xt.svg?Xn:ri;let a=-1;const i={};for(;++a<t.attrs.length;){const u=t.attrs[a],p=(u.prefix?u.prefix+":":"")+u.name;ol.call(Up,p)||(i[p]=u.value)}const l=(e.schema.space==="svg"?su:nu)(t.tagName,i,ll(e,t.childNodes));if(xn(e,t,l),l.tagName==="template"){const u=t,p=u.sourceCodeLocation,h=p&&p.startTag&&ps(p.startTag),b=p&&p.endTag&&ps(p.endTag),m=li(e,u.content);h&&b&&e.file&&(m.position={start:h.end,end:b.start}),l.content=m}return e.schema=n,l}function xn(e,t,n){if("sourceCodeLocation"in t&&t.sourceCodeLocation&&e.file){const a=Wp(e,n,t.sourceCodeLocation);a&&(e.location=!0,n.position=a)}}function Wp(e,t,n){const a=ps(n);if(t.type==="element"){const i=t.children[t.children.length-1];if(a&&!n.endTag&&i&&i.position&&i.position.end&&(a.end=Object.assign({},i.position.end)),e.verbose){const o={};let l;if(n.attrs)for(l in n.attrs)ol.call(n.attrs,l)&&(o[fo(e.schema,l).property]=ps(n.attrs[l]));_a(n.startTag);const u=ps(n.startTag),p=n.endTag?ps(n.endTag):void 0,h={opening:u};p&&(h.closing=p),h.properties=o,t.data={position:h}}}return a}function ps(e){const t=Er({line:e.startLine,column:e.startCol,offset:e.startOffset}),n=Er({line:e.endLine,column:e.endCol,offset:e.endOffset});return t||n?{start:t,end:n}:void 0}function Er(e){return e.line&&e.column?e:void 0}const Kp={},Yp={}.hasOwnProperty,cl=go("type",{handlers:{root:zp,element:Zp,text:Xp,comment:Jp,doctype:Qp}});function Gp(e,t){const a=(t||Kp).space;return cl(e,a==="svg"?Xn:ri)}function zp(e,t){const n={nodeName:"#document",mode:(e.data||{}).quirksMode?"quirks":"no-quirks",childNodes:[]};return n.childNodes=ci(e.children,n,t),Es(e,n),n}function Vp(e,t){const n={nodeName:"#document-fragment",childNodes:[]};return n.childNodes=ci(e.children,n,t),Es(e,n),n}function Qp(e){const t={nodeName:"#documentType",name:"html",publicId:"",systemId:"",parentNode:null};return Es(e,t),t}function Xp(e){const t={nodeName:"#text",value:e.value,parentNode:null};return Es(e,t),t}function Jp(e){const t={nodeName:"#comment",data:e.value,parentNode:null};return Es(e,t),t}function Zp(e,t){const n=t;let a=n;e.type==="element"&&e.tagName.toLowerCase()==="svg"&&n.space==="html"&&(a=Xn);const i=[];let o;if(e.properties){for(o in e.properties)if(o!=="children"&&Yp.call(e.properties,o)){const p=em(a,o,e.properties[o]);p&&i.push(p)}}const l=a.space,u={nodeName:e.tagName,tagName:e.tagName,attrs:i,namespaceURI:Xt[l],childNodes:[],parentNode:null};return u.childNodes=ci(e.children,u,a),Es(e,u),e.tagName==="template"&&e.content&&(u.content=Vp(e.content,a)),u}function em(e,t,n){const a=fo(e,t);if(n===!1||n===null||n===void 0||typeof n=="number"&&Number.isNaN(n)||!n&&a.boolean)return;Array.isArray(n)&&(n=a.commaSeparated?au(n):iu(n));const i={name:a.attribute,value:n===!0?"":String(n)};if(a.space&&a.space!=="html"&&a.space!=="svg"){const o=i.name.indexOf(":");o<0?i.prefix="":(i.name=i.name.slice(o+1),i.prefix=a.attribute.slice(0,o)),i.namespace=Xt[a.space]}return i}function ci(e,t,n){let a=-1;const i=[];if(e)for(;++a<e.length;){const o=cl(e[a],n);o.parentNode=t,i.push(o)}return i}function Es(e,t){const n=e.position;n&&n.start&&n.end&&(_a(typeof n.start.offset=="number"),_a(typeof n.end.offset=="number"),t.sourceCodeLocation={startLine:n.start.line,startCol:n.start.column,startOffset:n.start.offset,endLine:n.end.line,endCol:n.end.column,endOffset:n.end.offset})}const tm=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","keygen","link","meta","param","source","track","wbr"],sm=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),et="�";var g;(function(e){e[e.EOF=-1]="EOF",e[e.NULL=0]="NULL",e[e.TABULATION=9]="TABULATION",e[e.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",e[e.LINE_FEED=10]="LINE_FEED",e[e.FORM_FEED=12]="FORM_FEED",e[e.SPACE=32]="SPACE",e[e.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",e[e.QUOTATION_MARK=34]="QUOTATION_MARK",e[e.AMPERSAND=38]="AMPERSAND",e[e.APOSTROPHE=39]="APOSTROPHE",e[e.HYPHEN_MINUS=45]="HYPHEN_MINUS",e[e.SOLIDUS=47]="SOLIDUS",e[e.DIGIT_0=48]="DIGIT_0",e[e.DIGIT_9=57]="DIGIT_9",e[e.SEMICOLON=59]="SEMICOLON",e[e.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",e[e.EQUALS_SIGN=61]="EQUALS_SIGN",e[e.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.LATIN_CAPITAL_A=65]="LATIN_CAPITAL_A",e[e.LATIN_CAPITAL_Z=90]="LATIN_CAPITAL_Z",e[e.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",e[e.GRAVE_ACCENT=96]="GRAVE_ACCENT",e[e.LATIN_SMALL_A=97]="LATIN_SMALL_A",e[e.LATIN_SMALL_Z=122]="LATIN_SMALL_Z"})(g||(g={}));const ht={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function ul(e){return e>=55296&&e<=57343}function nm(e){return e>=56320&&e<=57343}function am(e,t){return(e-55296)*1024+9216+t}function dl(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function pl(e){return e>=64976&&e<=65007||sm.has(e)}var G;(function(e){e.controlCharacterInInputStream="control-character-in-input-stream",e.noncharacterInInputStream="noncharacter-in-input-stream",e.surrogateInInputStream="surrogate-in-input-stream",e.nonVoidHtmlElementStartTagWithTrailingSolidus="non-void-html-element-start-tag-with-trailing-solidus",e.endTagWithAttributes="end-tag-with-attributes",e.endTagWithTrailingSolidus="end-tag-with-trailing-solidus",e.unexpectedSolidusInTag="unexpected-solidus-in-tag",e.unexpectedNullCharacter="unexpected-null-character",e.unexpectedQuestionMarkInsteadOfTagName="unexpected-question-mark-instead-of-tag-name",e.invalidFirstCharacterOfTagName="invalid-first-character-of-tag-name",e.unexpectedEqualsSignBeforeAttributeName="unexpected-equals-sign-before-attribute-name",e.missingEndTagName="missing-end-tag-name",e.unexpectedCharacterInAttributeName="unexpected-character-in-attribute-name",e.unknownNamedCharacterReference="unknown-named-character-reference",e.missingSemicolonAfterCharacterReference="missing-semicolon-after-character-reference",e.unexpectedCharacterAfterDoctypeSystemIdentifier="unexpected-character-after-doctype-system-identifier",e.unexpectedCharacterInUnquotedAttributeValue="unexpected-character-in-unquoted-attribute-value",e.eofBeforeTagName="eof-before-tag-name",e.eofInTag="eof-in-tag",e.missingAttributeValue="missing-attribute-value",e.missingWhitespaceBetweenAttributes="missing-whitespace-between-attributes",e.missingWhitespaceAfterDoctypePublicKeyword="missing-whitespace-after-doctype-public-keyword",e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers="missing-whitespace-between-doctype-public-and-system-identifiers",e.missingWhitespaceAfterDoctypeSystemKeyword="missing-whitespace-after-doctype-system-keyword",e.missingQuoteBeforeDoctypePublicIdentifier="missing-quote-before-doctype-public-identifier",e.missingQuoteBeforeDoctypeSystemIdentifier="missing-quote-before-doctype-system-identifier",e.missingDoctypePublicIdentifier="missing-doctype-public-identifier",e.missingDoctypeSystemIdentifier="missing-doctype-system-identifier",e.abruptDoctypePublicIdentifier="abrupt-doctype-public-identifier",e.abruptDoctypeSystemIdentifier="abrupt-doctype-system-identifier",e.cdataInHtmlContent="cdata-in-html-content",e.incorrectlyOpenedComment="incorrectly-opened-comment",e.eofInScriptHtmlCommentLikeText="eof-in-script-html-comment-like-text",e.eofInDoctype="eof-in-doctype",e.nestedComment="nested-comment",e.abruptClosingOfEmptyComment="abrupt-closing-of-empty-comment",e.eofInComment="eof-in-comment",e.incorrectlyClosedComment="incorrectly-closed-comment",e.eofInCdata="eof-in-cdata",e.absenceOfDigitsInNumericCharacterReference="absence-of-digits-in-numeric-character-reference",e.nullCharacterReference="null-character-reference",e.surrogateCharacterReference="surrogate-character-reference",e.characterReferenceOutsideUnicodeRange="character-reference-outside-unicode-range",e.controlCharacterReference="control-character-reference",e.noncharacterCharacterReference="noncharacter-character-reference",e.missingWhitespaceBeforeDoctypeName="missing-whitespace-before-doctype-name",e.missingDoctypeName="missing-doctype-name",e.invalidCharacterSequenceAfterDoctypeName="invalid-character-sequence-after-doctype-name",e.duplicateAttribute="duplicate-attribute",e.nonConformingDoctype="non-conforming-doctype",e.missingDoctype="missing-doctype",e.misplacedDoctype="misplaced-doctype",e.endTagWithoutMatchingOpenElement="end-tag-without-matching-open-element",e.closingOfElementWithOpenChildElements="closing-of-element-with-open-child-elements",e.disallowedContentInNoscriptInHead="disallowed-content-in-noscript-in-head",e.openElementsLeftAfterEof="open-elements-left-after-eof",e.abandonedHeadElementChild="abandoned-head-element-child",e.misplacedStartTagForHeadElement="misplaced-start-tag-for-head-element",e.nestedNoscriptInHead="nested-noscript-in-head",e.eofInElementThatCanContainOnlyText="eof-in-element-that-can-contain-only-text"})(G||(G={}));const im=65536;class rm{constructor(t){this.handler=t,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=!1,this.lastChunkWritten=!1,this.endOfChunkHit=!1,this.bufferWaterline=im,this.isEol=!1,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1}get col(){return this.pos-this.lineStartPos+ +(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(t,n){const{line:a,col:i,offset:o}=this,l=i+n,u=o+n;return{code:t,startLine:a,endLine:a,startCol:l,endCol:l,startOffset:u,endOffset:u}}_err(t){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(t,0)))}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos}_processSurrogate(t){if(this.pos!==this.html.length-1){const n=this.html.charCodeAt(this.pos+1);if(nm(n))return this.pos++,this._addGap(),am(t,n)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,g.EOF;return this._err(G.surrogateInInputStream),t}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0)}write(t,n){this.html.length>0?this.html+=t:this.html=t,this.endOfChunkHit=!1,this.lastChunkWritten=n}insertHtmlAtCurrentPos(t){this.html=this.html.substring(0,this.pos+1)+t+this.html.substring(this.pos+1),this.endOfChunkHit=!1}startsWith(t,n){if(this.pos+t.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,!1;if(n)return this.html.startsWith(t,this.pos);for(let a=0;a<t.length;a++)if((this.html.charCodeAt(this.pos+a)|32)!==t.charCodeAt(a))return!1;return!0}peek(t){const n=this.pos+t;if(n>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,g.EOF;const a=this.html.charCodeAt(n);return a===g.CARRIAGE_RETURN?g.LINE_FEED:a}advance(){if(this.pos++,this.isEol&&(this.isEol=!1,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,g.EOF;let t=this.html.charCodeAt(this.pos);return t===g.CARRIAGE_RETURN?(this.isEol=!0,this.skipNextNewLine=!0,g.LINE_FEED):t===g.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance()):(this.skipNextNewLine=!1,ul(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===g.LINE_FEED||t===g.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){dl(t)?this._err(G.controlCharacterInInputStream):pl(t)&&this._err(G.noncharacterInInputStream)}retreat(t){for(this.pos-=t;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=!1}}var Ue;(function(e){e[e.CHARACTER=0]="CHARACTER",e[e.NULL_CHARACTER=1]="NULL_CHARACTER",e[e.WHITESPACE_CHARACTER=2]="WHITESPACE_CHARACTER",e[e.START_TAG=3]="START_TAG",e[e.END_TAG=4]="END_TAG",e[e.COMMENT=5]="COMMENT",e[e.DOCTYPE=6]="DOCTYPE",e[e.EOF=7]="EOF",e[e.HIBERNATION=8]="HIBERNATION"})(Ue||(Ue={}));function ml(e,t){for(let n=e.attrs.length-1;n>=0;n--)if(e.attrs[n].name===t)return e.attrs[n].value;return null}const om=new Uint16Array('ᵁ<Õıʊҝջאٵ۞ޢߖࠏ੊ઑඡ๭༉༦჊ረዡᐕᒝᓃᓟᔥ\0\0\0\0\0\0ᕫᛍᦍᰒᷝ὾⁠↰⊍⏀⏻⑂⠤⤒ⴈ⹈⿎〖㊺㘹㞬㣾㨨㩱㫠㬮ࠀEMabcfglmnoprstu\\bfms„‹•˜¦³¹ÈÏlig耻Æ䃆P耻&䀦cute耻Á䃁reve;䄂Āiyx}rc耻Â䃂;䐐r;쀀𝔄rave耻À䃀pha;䎑acr;䄀d;橓Āgp¡on;䄄f;쀀𝔸plyFunction;恡ing耻Å䃅Ācs¾Ãr;쀀𝒜ign;扔ilde耻Ã䃃ml耻Ä䃄ЀaceforsuåûþėĜĢħĪĀcrêòkslash;或Ŷöø;櫧ed;挆y;䐑ƀcrtąċĔause;戵noullis;愬a;䎒r;쀀𝔅pf;쀀𝔹eve;䋘còēmpeq;扎܀HOacdefhilorsuōőŖƀƞƢƵƷƺǜȕɳɸɾcy;䐧PY耻©䂩ƀcpyŝŢźute;䄆Ā;iŧŨ拒talDifferentialD;慅leys;愭ȀaeioƉƎƔƘron;䄌dil耻Ç䃇rc;䄈nint;戰ot;䄊ĀdnƧƭilla;䂸terDot;䂷òſi;䎧rcleȀDMPTLJNjǑǖot;抙inus;抖lus;投imes;抗oĀcsǢǸkwiseContourIntegral;戲eCurlyĀDQȃȏoubleQuote;思uote;怙ȀlnpuȞȨɇɕonĀ;eȥȦ户;橴ƀgitȯȶȺruent;扡nt;戯ourIntegral;戮ĀfrɌɎ;愂oduct;成nterClockwiseContourIntegral;戳oss;樯cr;쀀𝒞pĀ;Cʄʅ拓ap;才րDJSZacefiosʠʬʰʴʸˋ˗ˡ˦̳ҍĀ;oŹʥtrahd;椑cy;䐂cy;䐅cy;䐏ƀgrsʿ˄ˇger;怡r;憡hv;櫤Āayː˕ron;䄎;䐔lĀ;t˝˞戇a;䎔r;쀀𝔇Āaf˫̧Ācm˰̢riticalȀADGT̖̜̀̆cute;䂴oŴ̋̍;䋙bleAcute;䋝rave;䁠ilde;䋜ond;拄ferentialD;慆Ѱ̽\0\0\0͔͂\0Ѕf;쀀𝔻ƀ;DE͈͉͍䂨ot;惜qual;扐blèCDLRUVͣͲ΂ϏϢϸontourIntegraìȹoɴ͹\0\0ͻ»͉nArrow;懓Āeo·ΤftƀARTΐΖΡrrow;懐ightArrow;懔eåˊngĀLRΫτeftĀARγιrrow;柸ightArrow;柺ightArrow;柹ightĀATϘϞrrow;懒ee;抨pɁϩ\0\0ϯrrow;懑ownArrow;懕erticalBar;戥ǹABLRTaВЪаўѿͼrrowƀ;BUНОТ憓ar;椓pArrow;懵reve;䌑eft˒к\0ц\0ѐightVector;楐eeVector;楞ectorĀ;Bљњ憽ar;楖ightǔѧ\0ѱeeVector;楟ectorĀ;BѺѻ懁ar;楗eeĀ;A҆҇护rrow;憧ĀctҒҗr;쀀𝒟rok;䄐ࠀNTacdfglmopqstuxҽӀӄӋӞӢӧӮӵԡԯԶՒ՝ՠեG;䅊H耻Ð䃐cute耻É䃉ƀaiyӒӗӜron;䄚rc耻Ê䃊;䐭ot;䄖r;쀀𝔈rave耻È䃈ement;戈ĀapӺӾcr;䄒tyɓԆ\0\0ԒmallSquare;旻erySmallSquare;斫ĀgpԦԪon;䄘f;쀀𝔼silon;䎕uĀaiԼՉlĀ;TՂՃ橵ilde;扂librium;懌Āci՗՚r;愰m;橳a;䎗ml耻Ë䃋Āipժկsts;戃onentialE;慇ʀcfiosօֈ֍ֲ׌y;䐤r;쀀𝔉lledɓ֗\0\0֣mallSquare;旼erySmallSquare;斪Ͱֺ\0ֿ\0\0ׄf;쀀𝔽All;戀riertrf;愱cò׋؀JTabcdfgorstר׬ׯ׺؀ؒؖ؛؝أ٬ٲcy;䐃耻>䀾mmaĀ;d׷׸䎓;䏜reve;䄞ƀeiy؇،ؐdil;䄢rc;䄜;䐓ot;䄠r;쀀𝔊;拙pf;쀀𝔾eater̀EFGLSTصلَٖٛ٦qualĀ;Lؾؿ扥ess;招ullEqual;执reater;檢ess;扷lantEqual;橾ilde;扳cr;쀀𝒢;扫ЀAacfiosuڅڋږڛڞڪھۊRDcy;䐪Āctڐڔek;䋇;䁞irc;䄤r;愌lbertSpace;愋ǰگ\0ڲf;愍izontalLine;攀Āctۃۅòکrok;䄦mpńېۘownHumðįqual;扏܀EJOacdfgmnostuۺ۾܃܇܎ܚܞܡܨ݄ݸދޏޕcy;䐕lig;䄲cy;䐁cute耻Í䃍Āiyܓܘrc耻Î䃎;䐘ot;䄰r;愑rave耻Ì䃌ƀ;apܠܯܿĀcgܴܷr;䄪inaryI;慈lieóϝǴ݉\0ݢĀ;eݍݎ戬Āgrݓݘral;戫section;拂isibleĀCTݬݲomma;恣imes;恢ƀgptݿރވon;䄮f;쀀𝕀a;䎙cr;愐ilde;䄨ǫޚ\0ޞcy;䐆l耻Ï䃏ʀcfosuެ޷޼߂ߐĀiyޱ޵rc;䄴;䐙r;쀀𝔍pf;쀀𝕁ǣ߇\0ߌr;쀀𝒥rcy;䐈kcy;䐄΀HJacfosߤߨ߽߬߱ࠂࠈcy;䐥cy;䐌ppa;䎚Āey߶߻dil;䄶;䐚r;쀀𝔎pf;쀀𝕂cr;쀀𝒦րJTaceflmostࠥࠩࠬࡐࡣ঳সে্਷ੇcy;䐉耻<䀼ʀcmnpr࠷࠼ࡁࡄࡍute;䄹bda;䎛g;柪lacetrf;愒r;憞ƀaeyࡗ࡜ࡡron;䄽dil;䄻;䐛Āfsࡨ॰tԀACDFRTUVarࡾࢩࢱࣦ࣠ࣼयज़ΐ४Ānrࢃ࢏gleBracket;柨rowƀ;BR࢙࢚࢞憐ar;懤ightArrow;懆eiling;挈oǵࢷ\0ࣃbleBracket;柦nǔࣈ\0࣒eeVector;楡ectorĀ;Bࣛࣜ懃ar;楙loor;挊ightĀAV࣯ࣵrrow;憔ector;楎Āerँगeƀ;AVउऊऐ抣rrow;憤ector;楚iangleƀ;BEतथऩ抲ar;槏qual;抴pƀDTVषूौownVector;楑eeVector;楠ectorĀ;Bॖॗ憿ar;楘ectorĀ;B॥०憼ar;楒ightáΜs̀EFGLSTॾঋকঝঢভqualGreater;拚ullEqual;扦reater;扶ess;檡lantEqual;橽ilde;扲r;쀀𝔏Ā;eঽা拘ftarrow;懚idot;䄿ƀnpw৔ਖਛgȀLRlr৞৷ਂਐeftĀAR০৬rrow;柵ightArrow;柷ightArrow;柶eftĀarγਊightáοightáϊf;쀀𝕃erĀLRਢਬeftArrow;憙ightArrow;憘ƀchtਾੀੂòࡌ;憰rok;䅁;扪Ѐacefiosuਗ਼੝੠੷੼અઋ઎p;椅y;䐜Ādl੥੯iumSpace;恟lintrf;愳r;쀀𝔐nusPlus;戓pf;쀀𝕄cò੶;䎜ҀJacefostuણધભીଔଙඑ඗ඞcy;䐊cute;䅃ƀaey઴હાron;䅇dil;䅅;䐝ƀgswે૰଎ativeƀMTV૓૟૨ediumSpace;怋hiĀcn૦૘ë૙eryThiî૙tedĀGL૸ଆreaterGreateòٳessLesóੈLine;䀊r;쀀𝔑ȀBnptଢନଷ଺reak;恠BreakingSpace;䂠f;愕ڀ;CDEGHLNPRSTV୕ୖ୪୼஡௫ఄ౞಄ದ೘ൡඅ櫬Āou୛୤ngruent;扢pCap;扭oubleVerticalBar;戦ƀlqxஃஊ஛ement;戉ualĀ;Tஒஓ扠ilde;쀀≂̸ists;戄reater΀;EFGLSTஶஷ஽௉௓௘௥扯qual;扱ullEqual;쀀≧̸reater;쀀≫̸ess;批lantEqual;쀀⩾̸ilde;扵umpń௲௽ownHump;쀀≎̸qual;쀀≏̸eĀfsఊధtTriangleƀ;BEచఛడ拪ar;쀀⧏̸qual;括s̀;EGLSTవశ఼ౄోౘ扮qual;扰reater;扸ess;쀀≪̸lantEqual;쀀⩽̸ilde;扴estedĀGL౨౹reaterGreater;쀀⪢̸essLess;쀀⪡̸recedesƀ;ESಒಓಛ技qual;쀀⪯̸lantEqual;拠ĀeiಫಹverseElement;戌ghtTriangleƀ;BEೋೌ೒拫ar;쀀⧐̸qual;拭ĀquೝഌuareSuĀbp೨೹setĀ;E೰ೳ쀀⊏̸qual;拢ersetĀ;Eഃആ쀀⊐̸qual;拣ƀbcpഓതൎsetĀ;Eഛഞ쀀⊂⃒qual;抈ceedsȀ;ESTലള഻െ抁qual;쀀⪰̸lantEqual;拡ilde;쀀≿̸ersetĀ;E൘൛쀀⊃⃒qual;抉ildeȀ;EFT൮൯൵ൿ扁qual;扄ullEqual;扇ilde;扉erticalBar;戤cr;쀀𝒩ilde耻Ñ䃑;䎝܀Eacdfgmoprstuvලෂ෉෕ෛ෠෧෼ขภยา฿ไlig;䅒cute耻Ó䃓Āiy෎ීrc耻Ô䃔;䐞blac;䅐r;쀀𝔒rave耻Ò䃒ƀaei෮ෲ෶cr;䅌ga;䎩cron;䎟pf;쀀𝕆enCurlyĀDQฎบoubleQuote;怜uote;怘;橔Āclวฬr;쀀𝒪ash耻Ø䃘iŬื฼de耻Õ䃕es;樷ml耻Ö䃖erĀBP๋๠Āar๐๓r;怾acĀek๚๜;揞et;掴arenthesis;揜Ҁacfhilors๿ງຊຏຒດຝະ໼rtialD;戂y;䐟r;쀀𝔓i;䎦;䎠usMinus;䂱Āipຢອncareplanåڝf;愙Ȁ;eio຺ູ໠໤檻cedesȀ;EST່້໏໚扺qual;檯lantEqual;扼ilde;找me;怳Ādp໩໮uct;戏ortionĀ;aȥ໹l;戝Āci༁༆r;쀀𝒫;䎨ȀUfos༑༖༛༟OT耻"䀢r;쀀𝔔pf;愚cr;쀀𝒬؀BEacefhiorsu༾གྷཇའཱིྦྷྪྭ႖ႩႴႾarr;椐G耻®䂮ƀcnrཎནབute;䅔g;柫rĀ;tཛྷཝ憠l;椖ƀaeyཧཬཱron;䅘dil;䅖;䐠Ā;vླྀཹ愜erseĀEUྂྙĀlq྇ྎement;戋uilibrium;懋pEquilibrium;楯r»ཹo;䎡ghtЀACDFTUVa࿁࿫࿳ဢဨၛႇϘĀnr࿆࿒gleBracket;柩rowƀ;BL࿜࿝࿡憒ar;懥eftArrow;懄eiling;按oǵ࿹\0စbleBracket;柧nǔည\0နeeVector;楝ectorĀ;Bဝသ懂ar;楕loor;挋Āerိ၃eƀ;AVဵံြ抢rrow;憦ector;楛iangleƀ;BEၐၑၕ抳ar;槐qual;抵pƀDTVၣၮၸownVector;楏eeVector;楜ectorĀ;Bႂႃ憾ar;楔ectorĀ;B႑႒懀ar;楓Āpuႛ႞f;愝ndImplies;楰ightarrow;懛ĀchႹႼr;愛;憱leDelayed;槴ڀHOacfhimoqstuფჱჷჽᄙᄞᅑᅖᅡᅧᆵᆻᆿĀCcჩხHcy;䐩y;䐨FTcy;䐬cute;䅚ʀ;aeiyᄈᄉᄎᄓᄗ檼ron;䅠dil;䅞rc;䅜;䐡r;쀀𝔖ortȀDLRUᄪᄴᄾᅉownArrow»ОeftArrow»࢚ightArrow»࿝pArrow;憑gma;䎣allCircle;战pf;쀀𝕊ɲᅭ\0\0ᅰt;戚areȀ;ISUᅻᅼᆉᆯ斡ntersection;抓uĀbpᆏᆞsetĀ;Eᆗᆘ抏qual;抑ersetĀ;Eᆨᆩ抐qual;抒nion;抔cr;쀀𝒮ar;拆ȀbcmpᇈᇛሉላĀ;sᇍᇎ拐etĀ;Eᇍᇕqual;抆ĀchᇠህeedsȀ;ESTᇭᇮᇴᇿ扻qual;檰lantEqual;扽ilde;承Tháྌ;我ƀ;esሒሓሣ拑rsetĀ;Eሜም抃qual;抇et»ሓրHRSacfhiorsሾቄ቉ቕ቞ቱቶኟዂወዑORN耻Þ䃞ADE;愢ĀHc቎ቒcy;䐋y;䐦Ābuቚቜ;䀉;䎤ƀaeyብቪቯron;䅤dil;䅢;䐢r;쀀𝔗Āeiቻ኉Dzኀ\0ኇefore;戴a;䎘Ācn኎ኘkSpace;쀀  Space;怉ldeȀ;EFTካኬኲኼ戼qual;扃ullEqual;扅ilde;扈pf;쀀𝕋ipleDot;惛Āctዖዛr;쀀𝒯rok;䅦ૡዷጎጚጦ\0ጬጱ\0\0\0\0\0ጸጽ፷ᎅ\0᏿ᐄᐊᐐĀcrዻጁute耻Ú䃚rĀ;oጇገ憟cir;楉rǣጓ\0጖y;䐎ve;䅬Āiyጞጣrc耻Û䃛;䐣blac;䅰r;쀀𝔘rave耻Ù䃙acr;䅪Ādiፁ፩erĀBPፈ፝Āarፍፐr;䁟acĀekፗፙ;揟et;掵arenthesis;揝onĀ;P፰፱拃lus;抎Āgp፻፿on;䅲f;쀀𝕌ЀADETadps᎕ᎮᎸᏄϨᏒᏗᏳrrowƀ;BDᅐᎠᎤar;椒ownArrow;懅ownArrow;憕quilibrium;楮eeĀ;AᏋᏌ报rrow;憥ownáϳerĀLRᏞᏨeftArrow;憖ightArrow;憗iĀ;lᏹᏺ䏒on;䎥ing;䅮cr;쀀𝒰ilde;䅨ml耻Ü䃜ҀDbcdefosvᐧᐬᐰᐳᐾᒅᒊᒐᒖash;披ar;櫫y;䐒ashĀ;lᐻᐼ抩;櫦Āerᑃᑅ;拁ƀbtyᑌᑐᑺar;怖Ā;iᑏᑕcalȀBLSTᑡᑥᑪᑴar;戣ine;䁼eparator;杘ilde;所ThinSpace;怊r;쀀𝔙pf;쀀𝕍cr;쀀𝒱dash;抪ʀcefosᒧᒬᒱᒶᒼirc;䅴dge;拀r;쀀𝔚pf;쀀𝕎cr;쀀𝒲Ȁfiosᓋᓐᓒᓘr;쀀𝔛;䎞pf;쀀𝕏cr;쀀𝒳ҀAIUacfosuᓱᓵᓹᓽᔄᔏᔔᔚᔠcy;䐯cy;䐇cy;䐮cute耻Ý䃝Āiyᔉᔍrc;䅶;䐫r;쀀𝔜pf;쀀𝕐cr;쀀𝒴ml;䅸ЀHacdefosᔵᔹᔿᕋᕏᕝᕠᕤcy;䐖cute;䅹Āayᕄᕉron;䅽;䐗ot;䅻Dzᕔ\0ᕛoWidtè૙a;䎖r;愨pf;愤cr;쀀𝒵௡ᖃᖊᖐ\0ᖰᖶᖿ\0\0\0\0ᗆᗛᗫᙟ᙭\0ᚕ᚛ᚲᚹ\0ᚾcute耻á䃡reve;䄃̀;Ediuyᖜᖝᖡᖣᖨᖭ戾;쀀∾̳;房rc耻â䃢te肻´̆;䐰lig耻æ䃦Ā;r²ᖺ;쀀𝔞rave耻à䃠ĀepᗊᗖĀfpᗏᗔsym;愵èᗓha;䎱ĀapᗟcĀclᗤᗧr;䄁g;樿ɤᗰ\0\0ᘊʀ;adsvᗺᗻᗿᘁᘇ戧nd;橕;橜lope;橘;橚΀;elmrszᘘᘙᘛᘞᘿᙏᙙ戠;榤e»ᘙsdĀ;aᘥᘦ戡ѡᘰᘲᘴᘶᘸᘺᘼᘾ;榨;榩;榪;榫;榬;榭;榮;榯tĀ;vᙅᙆ戟bĀ;dᙌᙍ抾;榝Āptᙔᙗh;戢»¹arr;捼Āgpᙣᙧon;䄅f;쀀𝕒΀;Eaeiop዁ᙻᙽᚂᚄᚇᚊ;橰cir;橯;扊d;手s;䀧roxĀ;e዁ᚒñᚃing耻å䃥ƀctyᚡᚦᚨr;쀀𝒶;䀪mpĀ;e዁ᚯñʈilde耻ã䃣ml耻ä䃤Āciᛂᛈoninôɲnt;樑ࠀNabcdefiklnoprsu᛭ᛱᜰ᜼ᝃᝈ᝸᝽០៦ᠹᡐᜍ᤽᥈ᥰot;櫭Ācrᛶ᜞kȀcepsᜀᜅᜍᜓong;扌psilon;䏶rime;怵imĀ;e᜚᜛戽q;拍Ŷᜢᜦee;抽edĀ;gᜬᜭ挅e»ᜭrkĀ;t፜᜷brk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓ᝛ᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯ᝱ᝳ;䎲;愶een;扬r;쀀𝔟g΀costuvwឍឝឳេ៕៛៞ƀaiuបពរðݠrc;旯p»፱ƀdptឤឨឭot;樀lus;樁imes;樂ɱឹ\0\0ើcup;樆ar;昅riangleĀdu៍្own;施p;斳plus;樄eåᑄåᒭarow;植ƀako៭ᠦᠵĀcn៲ᠣkƀlst៺֫᠂ozenge;槫riangleȀ;dlr᠒᠓᠘᠝斴own;斾eft;旂ight;斸k;搣Ʊᠫ\0ᠳƲᠯ\0ᠱ;斒;斑4;斓ck;斈ĀeoᠾᡍĀ;qᡃᡆ쀀=⃥uiv;쀀≡⃥t;挐Ȁptwxᡙᡞᡧᡬf;쀀𝕓Ā;tᏋᡣom»Ꮜtie;拈؀DHUVbdhmptuvᢅᢖᢪᢻᣗᣛᣬ᣿ᤅᤊᤐᤡȀLRlrᢎᢐᢒᢔ;敗;敔;敖;敓ʀ;DUduᢡᢢᢤᢦᢨ敐;敦;敩;敤;敧ȀLRlrᢳᢵᢷᢹ;敝;敚;敜;教΀;HLRhlrᣊᣋᣍᣏᣑᣓᣕ救;敬;散;敠;敫;敢;敟ox;槉ȀLRlrᣤᣦᣨᣪ;敕;敒;攐;攌ʀ;DUduڽ᣷᣹᣻᣽;敥;敨;攬;攴inus;抟lus;択imes;抠ȀLRlrᤙᤛᤝ᤟;敛;敘;攘;攔΀;HLRhlrᤰᤱᤳᤵᤷ᤻᤹攂;敪;敡;敞;攼;攤;攜Āevģ᥂bar耻¦䂦Ȁceioᥑᥖᥚᥠr;쀀𝒷mi;恏mĀ;e᜚᜜lƀ;bhᥨᥩᥫ䁜;槅sub;柈Ŭᥴ᥾lĀ;e᥹᥺怢t»᥺pƀ;Eeįᦅᦇ;檮Ā;qۜۛೡᦧ\0᧨ᨑᨕᨲ\0ᨷᩐ\0\0᪴\0\0᫁\0\0ᬡᬮ᭍᭒\0᯽\0ᰌƀcpr᦭ᦲ᧝ute;䄇̀;abcdsᦿᧀᧄ᧊᧕᧙戩nd;橄rcup;橉Āau᧏᧒p;橋p;橇ot;橀;쀀∩︀Āeo᧢᧥t;恁îړȀaeiu᧰᧻ᨁᨅǰ᧵\0᧸s;橍on;䄍dil耻ç䃧rc;䄉psĀ;sᨌᨍ橌m;橐ot;䄋ƀdmnᨛᨠᨦil肻¸ƭptyv;榲t脀¢;eᨭᨮ䂢räƲr;쀀𝔠ƀceiᨽᩀᩍy;䑇ckĀ;mᩇᩈ朓ark»ᩈ;䏇r΀;Ecefms᩟᩠ᩢᩫ᪤᪪᪮旋;槃ƀ;elᩩᩪᩭ䋆q;扗eɡᩴ\0\0᪈rrowĀlr᩼᪁eft;憺ight;憻ʀRSacd᪒᪔᪖᪚᪟»ཇ;擈st;抛irc;抚ash;抝nint;樐id;櫯cir;槂ubsĀ;u᪻᪼晣it»᪼ˬ᫇᫔᫺\0ᬊonĀ;eᫍᫎ䀺Ā;qÇÆɭ᫙\0\0᫢aĀ;t᫞᫟䀬;䁀ƀ;fl᫨᫩᫫戁îᅠeĀmx᫱᫶ent»᫩eóɍǧ᫾\0ᬇĀ;dኻᬂot;橭nôɆƀfryᬐᬔᬗ;쀀𝕔oäɔ脀©;sŕᬝr;愗Āaoᬥᬩrr;憵ss;朗Ācuᬲᬷr;쀀𝒸Ābpᬼ᭄Ā;eᭁᭂ櫏;櫑Ā;eᭉᭊ櫐;櫒dot;拯΀delprvw᭠᭬᭷ᮂᮬᯔ᯹arrĀlr᭨᭪;椸;椵ɰ᭲\0\0᭵r;拞c;拟arrĀ;p᭿ᮀ憶;椽̀;bcdosᮏᮐᮖᮡᮥᮨ截rcap;橈Āauᮛᮞp;橆p;橊ot;抍r;橅;쀀∪︀Ȁalrv᮵ᮿᯞᯣrrĀ;mᮼᮽ憷;椼yƀevwᯇᯔᯘqɰᯎ\0\0ᯒreã᭳uã᭵ee;拎edge;拏en耻¤䂤earrowĀlrᯮ᯳eft»ᮀight»ᮽeäᯝĀciᰁᰇoninôǷnt;戱lcty;挭ঀAHabcdefhijlorstuwz᰸᰻᰿ᱝᱩᱵᲊᲞᲬᲷ᳻᳿ᴍᵻᶑᶫᶻ᷆᷍rò΁ar;楥Ȁglrs᱈ᱍ᱒᱔ger;怠eth;愸òᄳhĀ;vᱚᱛ怐»ऊūᱡᱧarow;椏aã̕Āayᱮᱳron;䄏;䐴ƀ;ao̲ᱼᲄĀgrʿᲁr;懊tseq;橷ƀglmᲑᲔᲘ耻°䂰ta;䎴ptyv;榱ĀirᲣᲨsht;楿;쀀𝔡arĀlrᲳᲵ»ࣜ»သʀaegsv᳂͸᳖᳜᳠mƀ;oș᳊᳔ndĀ;ș᳑uit;晦amma;䏝in;拲ƀ;io᳧᳨᳸䃷de脀÷;o᳧ᳰntimes;拇nø᳷cy;䑒cɯᴆ\0\0ᴊrn;挞op;挍ʀlptuwᴘᴝᴢᵉᵕlar;䀤f;쀀𝕕ʀ;emps̋ᴭᴷᴽᵂqĀ;d͒ᴳot;扑inus;戸lus;戔quare;抡blebarwedgåúnƀadhᄮᵝᵧownarrowóᲃarpoonĀlrᵲᵶefôᲴighôᲶŢᵿᶅkaro÷གɯᶊ\0\0ᶎrn;挟op;挌ƀcotᶘᶣᶦĀryᶝᶡ;쀀𝒹;䑕l;槶rok;䄑Ādrᶰᶴot;拱iĀ;fᶺ᠖斿Āah᷀᷃ròЩaòྦangle;榦Āci᷒ᷕy;䑟grarr;柿ऀDacdefglmnopqrstuxḁḉḙḸոḼṉṡṾấắẽỡἪἷὄ὎὚ĀDoḆᴴoôᲉĀcsḎḔute耻é䃩ter;橮ȀaioyḢḧḱḶron;䄛rĀ;cḭḮ扖耻ê䃪lon;払;䑍ot;䄗ĀDrṁṅot;扒;쀀𝔢ƀ;rsṐṑṗ檚ave耻è䃨Ā;dṜṝ檖ot;檘Ȁ;ilsṪṫṲṴ檙nters;揧;愓Ā;dṹṺ檕ot;檗ƀapsẅẉẗcr;䄓tyƀ;svẒẓẕ戅et»ẓpĀ1;ẝẤijạả;怄;怅怃ĀgsẪẬ;䅋p;怂ĀgpẴẸon;䄙f;쀀𝕖ƀalsỄỎỒrĀ;sỊị拕l;槣us;橱iƀ;lvỚớở䎵on»ớ;䏵ȀcsuvỪỳἋἣĀioữḱrc»Ḯɩỹ\0\0ỻíՈantĀglἂἆtr»ṝess»Ṻƀaeiἒ἖Ἒls;䀽st;扟vĀ;DȵἠD;橸parsl;槥ĀDaἯἳot;打rr;楱ƀcdiἾὁỸr;愯oô͒ĀahὉὋ;䎷耻ð䃰Āmrὓὗl耻ë䃫o;悬ƀcipὡὤὧl;䀡sôծĀeoὬὴctatioîՙnentialåչৡᾒ\0ᾞ\0ᾡᾧ\0\0ῆῌ\0ΐ\0ῦῪ \0 ⁚llingdotseñṄy;䑄male;晀ƀilrᾭᾳ῁lig;耀ffiɩᾹ\0\0᾽g;耀ffig;耀ffl;쀀𝔣lig;耀filig;쀀fjƀaltῙ῜ῡt;晭ig;耀flns;斱of;䆒ǰ΅\0ῳf;쀀𝕗ĀakֿῷĀ;vῼ´拔;櫙artint;樍Āao‌⁕Ācs‑⁒ႉ‸⁅⁈\0⁐β•‥‧‪‬\0‮耻½䂽;慓耻¼䂼;慕;慙;慛Ƴ‴\0‶;慔;慖ʴ‾⁁\0\0⁃耻¾䂾;慗;慜5;慘ƶ⁌\0⁎;慚;慝8;慞l;恄wn;挢cr;쀀𝒻ࢀEabcdefgijlnorstv₂₉₟₥₰₴⃰⃵⃺⃿℃ℒℸ̗ℾ⅒↞Ā;lٍ₇;檌ƀcmpₐₕ₝ute;䇵maĀ;dₜ᳚䎳;檆reve;䄟Āiy₪₮rc;䄝;䐳ot;䄡Ȁ;lqsؾق₽⃉ƀ;qsؾٌ⃄lanô٥Ȁ;cdl٥⃒⃥⃕c;檩otĀ;o⃜⃝檀Ā;l⃢⃣檂;檄Ā;e⃪⃭쀀⋛︀s;檔r;쀀𝔤Ā;gٳ؛mel;愷cy;䑓Ȁ;Eajٚℌℎℐ;檒;檥;檤ȀEaesℛℝ℩ℴ;扩pĀ;p℣ℤ檊rox»ℤĀ;q℮ℯ檈Ā;q℮ℛim;拧pf;쀀𝕘Āci⅃ⅆr;愊mƀ;el٫ⅎ⅐;檎;檐茀>;cdlqr׮ⅠⅪⅮⅳⅹĀciⅥⅧ;檧r;橺ot;拗Par;榕uest;橼ʀadelsↄⅪ←ٖ↛ǰ↉\0↎proø₞r;楸qĀlqؿ↖lesó₈ií٫Āen↣↭rtneqq;쀀≩︀Å↪ԀAabcefkosy⇄⇇⇱⇵⇺∘∝∯≨≽ròΠȀilmr⇐⇔⇗⇛rsðᒄf»․ilôکĀdr⇠⇤cy;䑊ƀ;cwࣴ⇫⇯ir;楈;憭ar;意irc;䄥ƀalr∁∎∓rtsĀ;u∉∊晥it»∊lip;怦con;抹r;쀀𝔥sĀew∣∩arow;椥arow;椦ʀamopr∺∾≃≞≣rr;懿tht;戻kĀlr≉≓eftarrow;憩ightarrow;憪f;쀀𝕙bar;怕ƀclt≯≴≸r;쀀𝒽asè⇴rok;䄧Ābp⊂⊇ull;恃hen»ᱛૡ⊣\0⊪\0⊸⋅⋎\0⋕⋳\0\0⋸⌢⍧⍢⍿\0⎆⎪⎴cute耻í䃭ƀ;iyݱ⊰⊵rc耻î䃮;䐸Ācx⊼⊿y;䐵cl耻¡䂡ĀfrΟ⋉;쀀𝔦rave耻ì䃬Ȁ;inoܾ⋝⋩⋮Āin⋢⋦nt;樌t;戭fin;槜ta;愩lig;䄳ƀaop⋾⌚⌝ƀcgt⌅⌈⌗r;䄫ƀelpܟ⌏⌓inåގarôܠh;䄱f;抷ed;䆵ʀ;cfotӴ⌬⌱⌽⍁are;愅inĀ;t⌸⌹戞ie;槝doô⌙ʀ;celpݗ⍌⍐⍛⍡al;抺Āgr⍕⍙eróᕣã⍍arhk;樗rod;樼Ȁcgpt⍯⍲⍶⍻y;䑑on;䄯f;쀀𝕚a;䎹uest耻¿䂿Āci⎊⎏r;쀀𝒾nʀ;EdsvӴ⎛⎝⎡ӳ;拹ot;拵Ā;v⎦⎧拴;拳Ā;iݷ⎮lde;䄩ǫ⎸\0⎼cy;䑖l耻ï䃯̀cfmosu⏌⏗⏜⏡⏧⏵Āiy⏑⏕rc;䄵;䐹r;쀀𝔧ath;䈷pf;쀀𝕛ǣ⏬\0⏱r;쀀𝒿rcy;䑘kcy;䑔Ѐacfghjos␋␖␢␧␭␱␵␻ppaĀ;v␓␔䎺;䏰Āey␛␠dil;䄷;䐺r;쀀𝔨reen;䄸cy;䑅cy;䑜pf;쀀𝕜cr;쀀𝓀஀ABEHabcdefghjlmnoprstuv⑰⒁⒆⒍⒑┎┽╚▀♎♞♥♹♽⚚⚲⛘❝❨➋⟀⠁⠒ƀart⑷⑺⑼rò৆òΕail;椛arr;椎Ā;gঔ⒋;檋ar;楢ॣ⒥\0⒪\0⒱\0\0\0\0\0⒵Ⓔ\0ⓆⓈⓍ\0⓹ute;䄺mptyv;榴raîࡌbda;䎻gƀ;dlࢎⓁⓃ;榑åࢎ;檅uo耻«䂫rЀ;bfhlpst࢙ⓞⓦⓩ⓫⓮⓱⓵Ā;f࢝ⓣs;椟s;椝ë≒p;憫l;椹im;楳l;憢ƀ;ae⓿─┄檫il;椙Ā;s┉┊檭;쀀⪭︀ƀabr┕┙┝rr;椌rk;杲Āak┢┬cĀek┨┪;䁻;䁛Āes┱┳;榋lĀdu┹┻;榏;榍Ȁaeuy╆╋╖╘ron;䄾Ādi═╔il;䄼ìࢰâ┩;䐻Ȁcqrs╣╦╭╽a;椶uoĀ;rนᝆĀdu╲╷har;楧shar;楋h;憲ʀ;fgqs▋▌উ◳◿扤tʀahlrt▘▤▷◂◨rrowĀ;t࢙□aé⓶arpoonĀdu▯▴own»њp»०eftarrows;懇ightƀahs◍◖◞rrowĀ;sࣴࢧarpoonó྘quigarro÷⇰hreetimes;拋ƀ;qs▋ও◺lanôবʀ;cdgsব☊☍☝☨c;檨otĀ;o☔☕橿Ā;r☚☛檁;檃Ā;e☢☥쀀⋚︀s;檓ʀadegs☳☹☽♉♋pproøⓆot;拖qĀgq♃♅ôউgtò⒌ôছiíলƀilr♕࣡♚sht;楼;쀀𝔩Ā;Eজ♣;檑š♩♶rĀdu▲♮Ā;l॥♳;楪lk;斄cy;䑙ʀ;achtੈ⚈⚋⚑⚖rò◁orneòᴈard;楫ri;旺Āio⚟⚤dot;䅀ustĀ;a⚬⚭掰che»⚭ȀEaes⚻⚽⛉⛔;扨pĀ;p⛃⛄檉rox»⛄Ā;q⛎⛏檇Ā;q⛎⚻im;拦Ѐabnoptwz⛩⛴⛷✚✯❁❇❐Ānr⛮⛱g;柬r;懽rëࣁgƀlmr⛿✍✔eftĀar০✇ightá৲apsto;柼ightá৽parrowĀlr✥✩efô⓭ight;憬ƀafl✶✹✽r;榅;쀀𝕝us;樭imes;樴š❋❏st;戗áፎƀ;ef❗❘᠀旊nge»❘arĀ;l❤❥䀨t;榓ʀachmt❳❶❼➅➇ròࢨorneòᶌarĀ;d྘➃;業;怎ri;抿̀achiqt➘➝ੀ➢➮➻quo;怹r;쀀𝓁mƀ;egল➪➬;檍;檏Ābu┪➳oĀ;rฟ➹;怚rok;䅂萀<;cdhilqrࠫ⟒☹⟜⟠⟥⟪⟰Āci⟗⟙;檦r;橹reå◲mes;拉arr;楶uest;橻ĀPi⟵⟹ar;榖ƀ;ef⠀भ᠛旃rĀdu⠇⠍shar;楊har;楦Āen⠗⠡rtneqq;쀀≨︀Å⠞܀Dacdefhilnopsu⡀⡅⢂⢎⢓⢠⢥⢨⣚⣢⣤ઃ⣳⤂Dot;戺Ȁclpr⡎⡒⡣⡽r耻¯䂯Āet⡗⡙;時Ā;e⡞⡟朠se»⡟Ā;sျ⡨toȀ;dluျ⡳⡷⡻owîҌefôएðᏑker;斮Āoy⢇⢌mma;権;䐼ash;怔asuredangle»ᘦr;쀀𝔪o;愧ƀcdn⢯⢴⣉ro耻µ䂵Ȁ;acdᑤ⢽⣀⣄sôᚧir;櫰ot肻·Ƶusƀ;bd⣒ᤃ⣓戒Ā;uᴼ⣘;横ţ⣞⣡p;櫛ò−ðઁĀdp⣩⣮els;抧f;쀀𝕞Āct⣸⣽r;쀀𝓂pos»ᖝƀ;lm⤉⤊⤍䎼timap;抸ఀGLRVabcdefghijlmoprstuvw⥂⥓⥾⦉⦘⧚⧩⨕⨚⩘⩝⪃⪕⪤⪨⬄⬇⭄⭿⮮ⰴⱧⱼ⳩Āgt⥇⥋;쀀⋙̸Ā;v⥐௏쀀≫⃒ƀelt⥚⥲⥶ftĀar⥡⥧rrow;懍ightarrow;懎;쀀⋘̸Ā;v⥻ే쀀≪⃒ightarrow;懏ĀDd⦎⦓ash;抯ash;抮ʀbcnpt⦣⦧⦬⦱⧌la»˞ute;䅄g;쀀∠⃒ʀ;Eiop඄⦼⧀⧅⧈;쀀⩰̸d;쀀≋̸s;䅉roø඄urĀ;a⧓⧔普lĀ;s⧓ସdz⧟\0⧣p肻 ଷmpĀ;e௹ఀʀaeouy⧴⧾⨃⨐⨓ǰ⧹\0⧻;橃on;䅈dil;䅆ngĀ;dൾ⨊ot;쀀⩭̸p;橂;䐽ash;怓΀;Aadqsxஒ⨩⨭⨻⩁⩅⩐rr;懗rĀhr⨳⨶k;椤Ā;oᏲᏰot;쀀≐̸uiöୣĀei⩊⩎ar;椨í஘istĀ;s஠டr;쀀𝔫ȀEest௅⩦⩹⩼ƀ;qs஼⩭௡ƀ;qs஼௅⩴lanô௢ií௪Ā;rஶ⪁»ஷƀAap⪊⪍⪑rò⥱rr;憮ar;櫲ƀ;svྍ⪜ྌĀ;d⪡⪢拼;拺cy;䑚΀AEadest⪷⪺⪾⫂⫅⫶⫹rò⥦;쀀≦̸rr;憚r;急Ȁ;fqs఻⫎⫣⫯tĀar⫔⫙rro÷⫁ightarro÷⪐ƀ;qs఻⪺⫪lanôౕĀ;sౕ⫴»శiíౝĀ;rవ⫾iĀ;eచథiäඐĀpt⬌⬑f;쀀𝕟膀¬;in⬙⬚⬶䂬nȀ;Edvஉ⬤⬨⬮;쀀⋹̸ot;쀀⋵̸ǡஉ⬳⬵;拷;拶iĀ;vಸ⬼ǡಸ⭁⭃;拾;拽ƀaor⭋⭣⭩rȀ;ast୻⭕⭚⭟lleì୻l;쀀⫽⃥;쀀∂̸lint;樔ƀ;ceಒ⭰⭳uåಥĀ;cಘ⭸Ā;eಒ⭽ñಘȀAait⮈⮋⮝⮧rò⦈rrƀ;cw⮔⮕⮙憛;쀀⤳̸;쀀↝̸ghtarrow»⮕riĀ;eೋೖ΀chimpqu⮽⯍⯙⬄୸⯤⯯Ȁ;cerല⯆ഷ⯉uå൅;쀀𝓃ortɭ⬅\0\0⯖ará⭖mĀ;e൮⯟Ā;q൴൳suĀbp⯫⯭å೸åഋƀbcp⯶ⰑⰙȀ;Ees⯿ⰀഢⰄ抄;쀀⫅̸etĀ;eഛⰋqĀ;qണⰀcĀ;eലⰗñസȀ;EesⰢⰣൟⰧ抅;쀀⫆̸etĀ;e൘ⰮqĀ;qൠⰣȀgilrⰽⰿⱅⱇìௗlde耻ñ䃱çృiangleĀlrⱒⱜeftĀ;eచⱚñదightĀ;eೋⱥñ೗Ā;mⱬⱭ䎽ƀ;esⱴⱵⱹ䀣ro;愖p;怇ҀDHadgilrsⲏⲔⲙⲞⲣⲰⲶⳓⳣash;抭arr;椄p;쀀≍⃒ash;抬ĀetⲨⲬ;쀀≥⃒;쀀>⃒nfin;槞ƀAetⲽⳁⳅrr;椂;쀀≤⃒Ā;rⳊⳍ쀀<⃒ie;쀀⊴⃒ĀAtⳘⳜrr;椃rie;쀀⊵⃒im;쀀∼⃒ƀAan⳰⳴ⴂrr;懖rĀhr⳺⳽k;椣Ā;oᏧᏥear;椧ቓ᪕\0\0\0\0\0\0\0\0\0\0\0\0\0ⴭ\0ⴸⵈⵠⵥ⵲ⶄᬇ\0\0ⶍⶫ\0ⷈⷎ\0ⷜ⸙⸫⸾⹃Ācsⴱ᪗ute耻ó䃳ĀiyⴼⵅrĀ;c᪞ⵂ耻ô䃴;䐾ʀabios᪠ⵒⵗLjⵚlac;䅑v;樸old;榼lig;䅓Ācr⵩⵭ir;榿;쀀𝔬ͯ⵹\0\0⵼\0ⶂn;䋛ave耻ò䃲;槁Ābmⶈ෴ar;榵Ȁacitⶕ⶘ⶥⶨrò᪀Āir⶝ⶠr;榾oss;榻nå๒;槀ƀaeiⶱⶵⶹcr;䅍ga;䏉ƀcdnⷀⷅǍron;䎿;榶pf;쀀𝕠ƀaelⷔ⷗ǒr;榷rp;榹΀;adiosvⷪⷫⷮ⸈⸍⸐⸖戨rò᪆Ȁ;efmⷷⷸ⸂⸅橝rĀ;oⷾⷿ愴f»ⷿ耻ª䂪耻º䂺gof;抶r;橖lope;橗;橛ƀclo⸟⸡⸧ò⸁ash耻ø䃸l;折iŬⸯ⸴de耻õ䃵esĀ;aǛ⸺s;樶ml耻ö䃶bar;挽ૡ⹞\0⹽\0⺀⺝\0⺢⺹\0\0⻋ຜ\0⼓\0\0⼫⾼\0⿈rȀ;astЃ⹧⹲຅脀¶;l⹭⹮䂶leìЃɩ⹸\0\0⹻m;櫳;櫽y;䐿rʀcimpt⺋⺏⺓ᡥ⺗nt;䀥od;䀮il;怰enk;怱r;쀀𝔭ƀimo⺨⺰⺴Ā;v⺭⺮䏆;䏕maô੶ne;明ƀ;tv⺿⻀⻈䏀chfork»´;䏖Āau⻏⻟nĀck⻕⻝kĀ;h⇴⻛;愎ö⇴sҀ;abcdemst⻳⻴ᤈ⻹⻽⼄⼆⼊⼎䀫cir;樣ir;樢Āouᵀ⼂;樥;橲n肻±ຝim;樦wo;樧ƀipu⼙⼠⼥ntint;樕f;쀀𝕡nd耻£䂣Ԁ;Eaceinosu່⼿⽁⽄⽇⾁⾉⾒⽾⾶;檳p;檷uå໙Ā;c໎⽌̀;acens່⽙⽟⽦⽨⽾pproø⽃urlyeñ໙ñ໎ƀaes⽯⽶⽺pprox;檹qq;檵im;拨iíໟmeĀ;s⾈ຮ怲ƀEas⽸⾐⽺ð⽵ƀdfp໬⾙⾯ƀals⾠⾥⾪lar;挮ine;挒urf;挓Ā;t໻⾴ï໻rel;抰Āci⿀⿅r;쀀𝓅;䏈ncsp;怈̀fiopsu⿚⋢⿟⿥⿫⿱r;쀀𝔮pf;쀀𝕢rime;恗cr;쀀𝓆ƀaeo⿸〉〓tĀei⿾々rnionóڰnt;樖stĀ;e【】䀿ñἙô༔઀ABHabcdefhilmnoprstux぀けさすムㄎㄫㅇㅢㅲㆎ㈆㈕㈤㈩㉘㉮㉲㊐㊰㊷ƀartぇおがròႳòϝail;検aròᱥar;楤΀cdenqrtとふへみわゔヌĀeuねぱ;쀀∽̱te;䅕iãᅮmptyv;榳gȀ;del࿑らるろ;榒;榥å࿑uo耻»䂻rր;abcfhlpstw࿜ガクシスゼゾダッデナp;極Ā;f࿠ゴs;椠;椳s;椞ë≝ð✮l;楅im;楴l;憣;憝Āaiパフil;椚oĀ;nホボ戶aló༞ƀabrョリヮrò៥rk;杳ĀakンヽcĀekヹ・;䁽;䁝Āes㄂㄄;榌lĀduㄊㄌ;榎;榐Ȁaeuyㄗㄜㄧㄩron;䅙Ādiㄡㄥil;䅗ì࿲âヺ;䑀Ȁclqsㄴㄷㄽㅄa;椷dhar;楩uoĀ;rȎȍh;憳ƀacgㅎㅟངlȀ;ipsླྀㅘㅛႜnåႻarôྩt;断ƀilrㅩဣㅮsht;楽;쀀𝔯ĀaoㅷㆆrĀduㅽㅿ»ѻĀ;l႑ㆄ;楬Ā;vㆋㆌ䏁;䏱ƀgns㆕ㇹㇼht̀ahlrstㆤㆰ㇂㇘㇤㇮rrowĀ;t࿜ㆭaéトarpoonĀduㆻㆿowîㅾp»႒eftĀah㇊㇐rrowó࿪arpoonóՑightarrows;應quigarro÷ニhreetimes;拌g;䋚ingdotseñἲƀahm㈍㈐㈓rò࿪aòՑ;怏oustĀ;a㈞㈟掱che»㈟mid;櫮Ȁabpt㈲㈽㉀㉒Ānr㈷㈺g;柭r;懾rëဃƀafl㉇㉊㉎r;榆;쀀𝕣us;樮imes;樵Āap㉝㉧rĀ;g㉣㉤䀩t;榔olint;樒arò㇣Ȁachq㉻㊀Ⴜ㊅quo;怺r;쀀𝓇Ābu・㊊oĀ;rȔȓƀhir㊗㊛㊠reåㇸmes;拊iȀ;efl㊪ၙᠡ㊫方tri;槎luhar;楨;愞ൡ㋕㋛㋟㌬㌸㍱\0㍺㎤\0\0㏬㏰\0㐨㑈㑚㒭㒱㓊㓱\0㘖\0\0㘳cute;䅛quï➺Ԁ;Eaceinpsyᇭ㋳㋵㋿㌂㌋㌏㌟㌦㌩;檴ǰ㋺\0㋼;檸on;䅡uåᇾĀ;dᇳ㌇il;䅟rc;䅝ƀEas㌖㌘㌛;檶p;檺im;择olint;樓iíሄ;䑁otƀ;be㌴ᵇ㌵担;橦΀Aacmstx㍆㍊㍗㍛㍞㍣㍭rr;懘rĀhr㍐㍒ë∨Ā;oਸ਼਴t耻§䂧i;䀻war;椩mĀin㍩ðnuóñt;朶rĀ;o㍶⁕쀀𝔰Ȁacoy㎂㎆㎑㎠rp;景Āhy㎋㎏cy;䑉;䑈rtɭ㎙\0\0㎜iäᑤaraì⹯耻­䂭Āgm㎨㎴maƀ;fv㎱㎲㎲䏃;䏂Ѐ;deglnprካ㏅㏉㏎㏖㏞㏡㏦ot;橪Ā;q኱ኰĀ;E㏓㏔檞;檠Ā;E㏛㏜檝;檟e;扆lus;樤arr;楲aròᄽȀaeit㏸㐈㐏㐗Āls㏽㐄lsetmé㍪hp;樳parsl;槤Ādlᑣ㐔e;挣Ā;e㐜㐝檪Ā;s㐢㐣檬;쀀⪬︀ƀflp㐮㐳㑂tcy;䑌Ā;b㐸㐹䀯Ā;a㐾㐿槄r;挿f;쀀𝕤aĀdr㑍ЂesĀ;u㑔㑕晠it»㑕ƀcsu㑠㑹㒟Āau㑥㑯pĀ;sᆈ㑫;쀀⊓︀pĀ;sᆴ㑵;쀀⊔︀uĀbp㑿㒏ƀ;esᆗᆜ㒆etĀ;eᆗ㒍ñᆝƀ;esᆨᆭ㒖etĀ;eᆨ㒝ñᆮƀ;afᅻ㒦ְrť㒫ֱ»ᅼaròᅈȀcemt㒹㒾㓂㓅r;쀀𝓈tmîñiì㐕aræᆾĀar㓎㓕rĀ;f㓔ឿ昆Āan㓚㓭ightĀep㓣㓪psiloîỠhé⺯s»⡒ʀbcmnp㓻㕞ሉ㖋㖎Ҁ;Edemnprs㔎㔏㔑㔕㔞㔣㔬㔱㔶抂;櫅ot;檽Ā;dᇚ㔚ot;櫃ult;櫁ĀEe㔨㔪;櫋;把lus;檿arr;楹ƀeiu㔽㕒㕕tƀ;en㔎㕅㕋qĀ;qᇚ㔏eqĀ;q㔫㔨m;櫇Ābp㕚㕜;櫕;櫓c̀;acensᇭ㕬㕲㕹㕻㌦pproø㋺urlyeñᇾñᇳƀaes㖂㖈㌛pproø㌚qñ㌗g;晪ڀ123;Edehlmnps㖩㖬㖯ሜ㖲㖴㗀㗉㗕㗚㗟㗨㗭耻¹䂹耻²䂲耻³䂳;櫆Āos㖹㖼t;檾ub;櫘Ā;dሢ㗅ot;櫄sĀou㗏㗒l;柉b;櫗arr;楻ult;櫂ĀEe㗤㗦;櫌;抋lus;櫀ƀeiu㗴㘉㘌tƀ;enሜ㗼㘂qĀ;qሢ㖲eqĀ;q㗧㗤m;櫈Ābp㘑㘓;櫔;櫖ƀAan㘜㘠㘭rr;懙rĀhr㘦㘨ë∮Ā;oਫ਩war;椪lig耻ß䃟௡㙑㙝㙠ዎ㙳㙹\0㙾㛂\0\0\0\0\0㛛㜃\0㜉㝬\0\0\0㞇ɲ㙖\0\0㙛get;挖;䏄rë๟ƀaey㙦㙫㙰ron;䅥dil;䅣;䑂lrec;挕r;쀀𝔱Ȁeiko㚆㚝㚵㚼Dz㚋\0㚑eĀ4fኄኁaƀ;sv㚘㚙㚛䎸ym;䏑Ācn㚢㚲kĀas㚨㚮pproø዁im»ኬsðኞĀas㚺㚮ð዁rn耻þ䃾Ǭ̟㛆⋧es膀×;bd㛏㛐㛘䃗Ā;aᤏ㛕r;樱;樰ƀeps㛡㛣㜀á⩍Ȁ;bcf҆㛬㛰㛴ot;挶ir;櫱Ā;o㛹㛼쀀𝕥rk;櫚á㍢rime;怴ƀaip㜏㜒㝤dåቈ΀adempst㜡㝍㝀㝑㝗㝜㝟ngleʀ;dlqr㜰㜱㜶㝀㝂斵own»ᶻeftĀ;e⠀㜾ñम;扜ightĀ;e㊪㝋ñၚot;旬inus;樺lus;樹b;槍ime;樻ezium;揢ƀcht㝲㝽㞁Āry㝷㝻;쀀𝓉;䑆cy;䑛rok;䅧Āio㞋㞎xô᝷headĀlr㞗㞠eftarro÷ࡏightarrow»ཝऀAHabcdfghlmoprstuw㟐㟓㟗㟤㟰㟼㠎㠜㠣㠴㡑㡝㡫㢩㣌㣒㣪㣶ròϭar;楣Ācr㟜㟢ute耻ú䃺òᅐrǣ㟪\0㟭y;䑞ve;䅭Āiy㟵㟺rc耻û䃻;䑃ƀabh㠃㠆㠋ròᎭlac;䅱aòᏃĀir㠓㠘sht;楾;쀀𝔲rave耻ù䃹š㠧㠱rĀlr㠬㠮»ॗ»ႃlk;斀Āct㠹㡍ɯ㠿\0\0㡊rnĀ;e㡅㡆挜r»㡆op;挏ri;旸Āal㡖㡚cr;䅫肻¨͉Āgp㡢㡦on;䅳f;쀀𝕦̀adhlsuᅋ㡸㡽፲㢑㢠ownáᎳarpoonĀlr㢈㢌efô㠭ighô㠯iƀ;hl㢙㢚㢜䏅»ᏺon»㢚parrows;懈ƀcit㢰㣄㣈ɯ㢶\0\0㣁rnĀ;e㢼㢽挝r»㢽op;挎ng;䅯ri;旹cr;쀀𝓊ƀdir㣙㣝㣢ot;拰lde;䅩iĀ;f㜰㣨»᠓Āam㣯㣲rò㢨l耻ü䃼angle;榧ހABDacdeflnoprsz㤜㤟㤩㤭㦵㦸㦽㧟㧤㧨㧳㧹㧽㨁㨠ròϷarĀ;v㤦㤧櫨;櫩asèϡĀnr㤲㤷grt;榜΀eknprst㓣㥆㥋㥒㥝㥤㦖appá␕othinçẖƀhir㓫⻈㥙opô⾵Ā;hᎷ㥢ïㆍĀiu㥩㥭gmá㎳Ābp㥲㦄setneqĀ;q㥽㦀쀀⊊︀;쀀⫋︀setneqĀ;q㦏㦒쀀⊋︀;쀀⫌︀Āhr㦛㦟etá㚜iangleĀlr㦪㦯eft»थight»ၑy;䐲ash»ံƀelr㧄㧒㧗ƀ;beⷪ㧋㧏ar;抻q;扚lip;拮Ābt㧜ᑨaòᑩr;쀀𝔳tré㦮suĀbp㧯㧱»ജ»൙pf;쀀𝕧roð໻tré㦴Ācu㨆㨋r;쀀𝓋Ābp㨐㨘nĀEe㦀㨖»㥾nĀEe㦒㨞»㦐igzag;榚΀cefoprs㨶㨻㩖㩛㩔㩡㩪irc;䅵Ādi㩀㩑Ābg㩅㩉ar;機eĀ;qᗺ㩏;扙erp;愘r;쀀𝔴pf;쀀𝕨Ā;eᑹ㩦atèᑹcr;쀀𝓌ૣណ㪇\0㪋\0㪐㪛\0\0㪝㪨㪫㪯\0\0㫃㫎\0㫘ៜ៟tré៑r;쀀𝔵ĀAa㪔㪗ròσrò৶;䎾ĀAa㪡㪤ròθrò৫að✓is;拻ƀdptឤ㪵㪾Āfl㪺ឩ;쀀𝕩imåឲĀAa㫇㫊ròώròਁĀcq㫒ីr;쀀𝓍Āpt៖㫜ré។Ѐacefiosu㫰㫽㬈㬌㬑㬕㬛㬡cĀuy㫶㫻te耻ý䃽;䑏Āiy㬂㬆rc;䅷;䑋n耻¥䂥r;쀀𝔶cy;䑗pf;쀀𝕪cr;쀀𝓎Ācm㬦㬩y;䑎l耻ÿ䃿Ԁacdefhiosw㭂㭈㭔㭘㭤㭩㭭㭴㭺㮀cute;䅺Āay㭍㭒ron;䅾;䐷ot;䅼Āet㭝㭡træᕟa;䎶r;쀀𝔷cy;䐶grarr;懝pf;쀀𝕫cr;쀀𝓏Ājn㮅㮇;怍j;怌'.split("").map(e=>e.charCodeAt(0))),lm=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]);function cm(e){var t;return e>=55296&&e<=57343||e>1114111?65533:(t=lm.get(e))!==null&&t!==void 0?t:e}var ot;(function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"})(ot||(ot={}));const um=32;var Gt;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"})(Gt||(Gt={}));function qa(e){return e>=ot.ZERO&&e<=ot.NINE}function dm(e){return e>=ot.UPPER_A&&e<=ot.UPPER_F||e>=ot.LOWER_A&&e<=ot.LOWER_F}function pm(e){return e>=ot.UPPER_A&&e<=ot.UPPER_Z||e>=ot.LOWER_A&&e<=ot.LOWER_Z||qa(e)}function mm(e){return e===ot.EQUALS||pm(e)}var rt;(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(rt||(rt={}));var Mt;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(Mt||(Mt={}));class hm{constructor(t,n,a){this.decodeTree=t,this.emitCodePoint=n,this.errors=a,this.state=rt.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=Mt.Strict}startEntity(t){this.decodeMode=t,this.state=rt.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(t,n){switch(this.state){case rt.EntityStart:return t.charCodeAt(n)===ot.NUM?(this.state=rt.NumericStart,this.consumed+=1,this.stateNumericStart(t,n+1)):(this.state=rt.NamedEntity,this.stateNamedEntity(t,n));case rt.NumericStart:return this.stateNumericStart(t,n);case rt.NumericDecimal:return this.stateNumericDecimal(t,n);case rt.NumericHex:return this.stateNumericHex(t,n);case rt.NamedEntity:return this.stateNamedEntity(t,n)}}stateNumericStart(t,n){return n>=t.length?-1:(t.charCodeAt(n)|um)===ot.LOWER_X?(this.state=rt.NumericHex,this.consumed+=1,this.stateNumericHex(t,n+1)):(this.state=rt.NumericDecimal,this.stateNumericDecimal(t,n))}addToNumericResult(t,n,a,i){if(n!==a){const o=a-n;this.result=this.result*Math.pow(i,o)+Number.parseInt(t.substr(n,o),i),this.consumed+=o}}stateNumericHex(t,n){const a=n;for(;n<t.length;){const i=t.charCodeAt(n);if(qa(i)||dm(i))n+=1;else return this.addToNumericResult(t,a,n,16),this.emitNumericEntity(i,3)}return this.addToNumericResult(t,a,n,16),-1}stateNumericDecimal(t,n){const a=n;for(;n<t.length;){const i=t.charCodeAt(n);if(qa(i))n+=1;else return this.addToNumericResult(t,a,n,10),this.emitNumericEntity(i,2)}return this.addToNumericResult(t,a,n,10),-1}emitNumericEntity(t,n){var a;if(this.consumed<=n)return(a=this.errors)===null||a===void 0||a.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(t===ot.SEMI)this.consumed+=1;else if(this.decodeMode===Mt.Strict)return 0;return this.emitCodePoint(cm(this.result),this.consumed),this.errors&&(t!==ot.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,n){const{decodeTree:a}=this;let i=a[this.treeIndex],o=(i&Gt.VALUE_LENGTH)>>14;for(;n<t.length;n++,this.excess++){const l=t.charCodeAt(n);if(this.treeIndex=fm(a,i,this.treeIndex+Math.max(1,o),l),this.treeIndex<0)return this.result===0||this.decodeMode===Mt.Attribute&&(o===0||mm(l))?0:this.emitNotTerminatedNamedEntity();if(i=a[this.treeIndex],o=(i&Gt.VALUE_LENGTH)>>14,o!==0){if(l===ot.SEMI)return this.emitNamedEntityData(this.treeIndex,o,this.consumed+this.excess);this.decodeMode!==Mt.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var t;const{result:n,decodeTree:a}=this,i=(a[n]&Gt.VALUE_LENGTH)>>14;return this.emitNamedEntityData(n,i,this.consumed),(t=this.errors)===null||t===void 0||t.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,n,a){const{decodeTree:i}=this;return this.emitCodePoint(n===1?i[t]&~Gt.VALUE_LENGTH:i[t+1],a),n===3&&this.emitCodePoint(i[t+2],a),a}end(){var t;switch(this.state){case rt.NamedEntity:return this.result!==0&&(this.decodeMode!==Mt.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case rt.NumericDecimal:return this.emitNumericEntity(0,2);case rt.NumericHex:return this.emitNumericEntity(0,3);case rt.NumericStart:return(t=this.errors)===null||t===void 0||t.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case rt.EntityStart:return 0}}}function fm(e,t,n,a){const i=(t&Gt.BRANCH_LENGTH)>>7,o=t&Gt.JUMP_TABLE;if(i===0)return o!==0&&a===o?n:-1;if(o){const p=a-o;return p<0||p>=i?-1:e[n+p]-1}let l=n,u=l+i-1;for(;l<=u;){const p=l+u>>>1,h=e[p];if(h<a)l=p+1;else if(h>a)u=p-1;else return e[p+i]}return-1}var ne;(function(e){e.HTML="http://www.w3.org/1999/xhtml",e.MATHML="http://www.w3.org/1998/Math/MathML",e.SVG="http://www.w3.org/2000/svg",e.XLINK="http://www.w3.org/1999/xlink",e.XML="http://www.w3.org/XML/1998/namespace",e.XMLNS="http://www.w3.org/2000/xmlns/"})(ne||(ne={}));var ns;(function(e){e.TYPE="type",e.ACTION="action",e.ENCODING="encoding",e.PROMPT="prompt",e.NAME="name",e.COLOR="color",e.FACE="face",e.SIZE="size"})(ns||(ns={}));var xt;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks"})(xt||(xt={}));var M;(function(e){e.A="a",e.ADDRESS="address",e.ANNOTATION_XML="annotation-xml",e.APPLET="applet",e.AREA="area",e.ARTICLE="article",e.ASIDE="aside",e.B="b",e.BASE="base",e.BASEFONT="basefont",e.BGSOUND="bgsound",e.BIG="big",e.BLOCKQUOTE="blockquote",e.BODY="body",e.BR="br",e.BUTTON="button",e.CAPTION="caption",e.CENTER="center",e.CODE="code",e.COL="col",e.COLGROUP="colgroup",e.DD="dd",e.DESC="desc",e.DETAILS="details",e.DIALOG="dialog",e.DIR="dir",e.DIV="div",e.DL="dl",e.DT="dt",e.EM="em",e.EMBED="embed",e.FIELDSET="fieldset",e.FIGCAPTION="figcaption",e.FIGURE="figure",e.FONT="font",e.FOOTER="footer",e.FOREIGN_OBJECT="foreignObject",e.FORM="form",e.FRAME="frame",e.FRAMESET="frameset",e.H1="h1",e.H2="h2",e.H3="h3",e.H4="h4",e.H5="h5",e.H6="h6",e.HEAD="head",e.HEADER="header",e.HGROUP="hgroup",e.HR="hr",e.HTML="html",e.I="i",e.IMG="img",e.IMAGE="image",e.INPUT="input",e.IFRAME="iframe",e.KEYGEN="keygen",e.LABEL="label",e.LI="li",e.LINK="link",e.LISTING="listing",e.MAIN="main",e.MALIGNMARK="malignmark",e.MARQUEE="marquee",e.MATH="math",e.MENU="menu",e.META="meta",e.MGLYPH="mglyph",e.MI="mi",e.MO="mo",e.MN="mn",e.MS="ms",e.MTEXT="mtext",e.NAV="nav",e.NOBR="nobr",e.NOFRAMES="noframes",e.NOEMBED="noembed",e.NOSCRIPT="noscript",e.OBJECT="object",e.OL="ol",e.OPTGROUP="optgroup",e.OPTION="option",e.P="p",e.PARAM="param",e.PLAINTEXT="plaintext",e.PRE="pre",e.RB="rb",e.RP="rp",e.RT="rt",e.RTC="rtc",e.RUBY="ruby",e.S="s",e.SCRIPT="script",e.SEARCH="search",e.SECTION="section",e.SELECT="select",e.SOURCE="source",e.SMALL="small",e.SPAN="span",e.STRIKE="strike",e.STRONG="strong",e.STYLE="style",e.SUB="sub",e.SUMMARY="summary",e.SUP="sup",e.TABLE="table",e.TBODY="tbody",e.TEMPLATE="template",e.TEXTAREA="textarea",e.TFOOT="tfoot",e.TD="td",e.TH="th",e.THEAD="thead",e.TITLE="title",e.TR="tr",e.TRACK="track",e.TT="tt",e.U="u",e.UL="ul",e.SVG="svg",e.VAR="var",e.WBR="wbr",e.XMP="xmp"})(M||(M={}));var r;(function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.A=1]="A",e[e.ADDRESS=2]="ADDRESS",e[e.ANNOTATION_XML=3]="ANNOTATION_XML",e[e.APPLET=4]="APPLET",e[e.AREA=5]="AREA",e[e.ARTICLE=6]="ARTICLE",e[e.ASIDE=7]="ASIDE",e[e.B=8]="B",e[e.BASE=9]="BASE",e[e.BASEFONT=10]="BASEFONT",e[e.BGSOUND=11]="BGSOUND",e[e.BIG=12]="BIG",e[e.BLOCKQUOTE=13]="BLOCKQUOTE",e[e.BODY=14]="BODY",e[e.BR=15]="BR",e[e.BUTTON=16]="BUTTON",e[e.CAPTION=17]="CAPTION",e[e.CENTER=18]="CENTER",e[e.CODE=19]="CODE",e[e.COL=20]="COL",e[e.COLGROUP=21]="COLGROUP",e[e.DD=22]="DD",e[e.DESC=23]="DESC",e[e.DETAILS=24]="DETAILS",e[e.DIALOG=25]="DIALOG",e[e.DIR=26]="DIR",e[e.DIV=27]="DIV",e[e.DL=28]="DL",e[e.DT=29]="DT",e[e.EM=30]="EM",e[e.EMBED=31]="EMBED",e[e.FIELDSET=32]="FIELDSET",e[e.FIGCAPTION=33]="FIGCAPTION",e[e.FIGURE=34]="FIGURE",e[e.FONT=35]="FONT",e[e.FOOTER=36]="FOOTER",e[e.FOREIGN_OBJECT=37]="FOREIGN_OBJECT",e[e.FORM=38]="FORM",e[e.FRAME=39]="FRAME",e[e.FRAMESET=40]="FRAMESET",e[e.H1=41]="H1",e[e.H2=42]="H2",e[e.H3=43]="H3",e[e.H4=44]="H4",e[e.H5=45]="H5",e[e.H6=46]="H6",e[e.HEAD=47]="HEAD",e[e.HEADER=48]="HEADER",e[e.HGROUP=49]="HGROUP",e[e.HR=50]="HR",e[e.HTML=51]="HTML",e[e.I=52]="I",e[e.IMG=53]="IMG",e[e.IMAGE=54]="IMAGE",e[e.INPUT=55]="INPUT",e[e.IFRAME=56]="IFRAME",e[e.KEYGEN=57]="KEYGEN",e[e.LABEL=58]="LABEL",e[e.LI=59]="LI",e[e.LINK=60]="LINK",e[e.LISTING=61]="LISTING",e[e.MAIN=62]="MAIN",e[e.MALIGNMARK=63]="MALIGNMARK",e[e.MARQUEE=64]="MARQUEE",e[e.MATH=65]="MATH",e[e.MENU=66]="MENU",e[e.META=67]="META",e[e.MGLYPH=68]="MGLYPH",e[e.MI=69]="MI",e[e.MO=70]="MO",e[e.MN=71]="MN",e[e.MS=72]="MS",e[e.MTEXT=73]="MTEXT",e[e.NAV=74]="NAV",e[e.NOBR=75]="NOBR",e[e.NOFRAMES=76]="NOFRAMES",e[e.NOEMBED=77]="NOEMBED",e[e.NOSCRIPT=78]="NOSCRIPT",e[e.OBJECT=79]="OBJECT",e[e.OL=80]="OL",e[e.OPTGROUP=81]="OPTGROUP",e[e.OPTION=82]="OPTION",e[e.P=83]="P",e[e.PARAM=84]="PARAM",e[e.PLAINTEXT=85]="PLAINTEXT",e[e.PRE=86]="PRE",e[e.RB=87]="RB",e[e.RP=88]="RP",e[e.RT=89]="RT",e[e.RTC=90]="RTC",e[e.RUBY=91]="RUBY",e[e.S=92]="S",e[e.SCRIPT=93]="SCRIPT",e[e.SEARCH=94]="SEARCH",e[e.SECTION=95]="SECTION",e[e.SELECT=96]="SELECT",e[e.SOURCE=97]="SOURCE",e[e.SMALL=98]="SMALL",e[e.SPAN=99]="SPAN",e[e.STRIKE=100]="STRIKE",e[e.STRONG=101]="STRONG",e[e.STYLE=102]="STYLE",e[e.SUB=103]="SUB",e[e.SUMMARY=104]="SUMMARY",e[e.SUP=105]="SUP",e[e.TABLE=106]="TABLE",e[e.TBODY=107]="TBODY",e[e.TEMPLATE=108]="TEMPLATE",e[e.TEXTAREA=109]="TEXTAREA",e[e.TFOOT=110]="TFOOT",e[e.TD=111]="TD",e[e.TH=112]="TH",e[e.THEAD=113]="THEAD",e[e.TITLE=114]="TITLE",e[e.TR=115]="TR",e[e.TRACK=116]="TRACK",e[e.TT=117]="TT",e[e.U=118]="U",e[e.UL=119]="UL",e[e.SVG=120]="SVG",e[e.VAR=121]="VAR",e[e.WBR=122]="WBR",e[e.XMP=123]="XMP"})(r||(r={}));const gm=new Map([[M.A,r.A],[M.ADDRESS,r.ADDRESS],[M.ANNOTATION_XML,r.ANNOTATION_XML],[M.APPLET,r.APPLET],[M.AREA,r.AREA],[M.ARTICLE,r.ARTICLE],[M.ASIDE,r.ASIDE],[M.B,r.B],[M.BASE,r.BASE],[M.BASEFONT,r.BASEFONT],[M.BGSOUND,r.BGSOUND],[M.BIG,r.BIG],[M.BLOCKQUOTE,r.BLOCKQUOTE],[M.BODY,r.BODY],[M.BR,r.BR],[M.BUTTON,r.BUTTON],[M.CAPTION,r.CAPTION],[M.CENTER,r.CENTER],[M.CODE,r.CODE],[M.COL,r.COL],[M.COLGROUP,r.COLGROUP],[M.DD,r.DD],[M.DESC,r.DESC],[M.DETAILS,r.DETAILS],[M.DIALOG,r.DIALOG],[M.DIR,r.DIR],[M.DIV,r.DIV],[M.DL,r.DL],[M.DT,r.DT],[M.EM,r.EM],[M.EMBED,r.EMBED],[M.FIELDSET,r.FIELDSET],[M.FIGCAPTION,r.FIGCAPTION],[M.FIGURE,r.FIGURE],[M.FONT,r.FONT],[M.FOOTER,r.FOOTER],[M.FOREIGN_OBJECT,r.FOREIGN_OBJECT],[M.FORM,r.FORM],[M.FRAME,r.FRAME],[M.FRAMESET,r.FRAMESET],[M.H1,r.H1],[M.H2,r.H2],[M.H3,r.H3],[M.H4,r.H4],[M.H5,r.H5],[M.H6,r.H6],[M.HEAD,r.HEAD],[M.HEADER,r.HEADER],[M.HGROUP,r.HGROUP],[M.HR,r.HR],[M.HTML,r.HTML],[M.I,r.I],[M.IMG,r.IMG],[M.IMAGE,r.IMAGE],[M.INPUT,r.INPUT],[M.IFRAME,r.IFRAME],[M.KEYGEN,r.KEYGEN],[M.LABEL,r.LABEL],[M.LI,r.LI],[M.LINK,r.LINK],[M.LISTING,r.LISTING],[M.MAIN,r.MAIN],[M.MALIGNMARK,r.MALIGNMARK],[M.MARQUEE,r.MARQUEE],[M.MATH,r.MATH],[M.MENU,r.MENU],[M.META,r.META],[M.MGLYPH,r.MGLYPH],[M.MI,r.MI],[M.MO,r.MO],[M.MN,r.MN],[M.MS,r.MS],[M.MTEXT,r.MTEXT],[M.NAV,r.NAV],[M.NOBR,r.NOBR],[M.NOFRAMES,r.NOFRAMES],[M.NOEMBED,r.NOEMBED],[M.NOSCRIPT,r.NOSCRIPT],[M.OBJECT,r.OBJECT],[M.OL,r.OL],[M.OPTGROUP,r.OPTGROUP],[M.OPTION,r.OPTION],[M.P,r.P],[M.PARAM,r.PARAM],[M.PLAINTEXT,r.PLAINTEXT],[M.PRE,r.PRE],[M.RB,r.RB],[M.RP,r.RP],[M.RT,r.RT],[M.RTC,r.RTC],[M.RUBY,r.RUBY],[M.S,r.S],[M.SCRIPT,r.SCRIPT],[M.SEARCH,r.SEARCH],[M.SECTION,r.SECTION],[M.SELECT,r.SELECT],[M.SOURCE,r.SOURCE],[M.SMALL,r.SMALL],[M.SPAN,r.SPAN],[M.STRIKE,r.STRIKE],[M.STRONG,r.STRONG],[M.STYLE,r.STYLE],[M.SUB,r.SUB],[M.SUMMARY,r.SUMMARY],[M.SUP,r.SUP],[M.TABLE,r.TABLE],[M.TBODY,r.TBODY],[M.TEMPLATE,r.TEMPLATE],[M.TEXTAREA,r.TEXTAREA],[M.TFOOT,r.TFOOT],[M.TD,r.TD],[M.TH,r.TH],[M.THEAD,r.THEAD],[M.TITLE,r.TITLE],[M.TR,r.TR],[M.TRACK,r.TRACK],[M.TT,r.TT],[M.U,r.U],[M.UL,r.UL],[M.SVG,r.SVG],[M.VAR,r.VAR],[M.WBR,r.WBR],[M.XMP,r.XMP]]);function Ts(e){var t;return(t=gm.get(e))!==null&&t!==void 0?t:r.UNKNOWN}const re=r,bm={[ne.HTML]:new Set([re.ADDRESS,re.APPLET,re.AREA,re.ARTICLE,re.ASIDE,re.BASE,re.BASEFONT,re.BGSOUND,re.BLOCKQUOTE,re.BODY,re.BR,re.BUTTON,re.CAPTION,re.CENTER,re.COL,re.COLGROUP,re.DD,re.DETAILS,re.DIR,re.DIV,re.DL,re.DT,re.EMBED,re.FIELDSET,re.FIGCAPTION,re.FIGURE,re.FOOTER,re.FORM,re.FRAME,re.FRAMESET,re.H1,re.H2,re.H3,re.H4,re.H5,re.H6,re.HEAD,re.HEADER,re.HGROUP,re.HR,re.HTML,re.IFRAME,re.IMG,re.INPUT,re.LI,re.LINK,re.LISTING,re.MAIN,re.MARQUEE,re.MENU,re.META,re.NAV,re.NOEMBED,re.NOFRAMES,re.NOSCRIPT,re.OBJECT,re.OL,re.P,re.PARAM,re.PLAINTEXT,re.PRE,re.SCRIPT,re.SECTION,re.SELECT,re.SOURCE,re.STYLE,re.SUMMARY,re.TABLE,re.TBODY,re.TD,re.TEMPLATE,re.TEXTAREA,re.TFOOT,re.TH,re.THEAD,re.TITLE,re.TR,re.TRACK,re.UL,re.WBR,re.XMP]),[ne.MATHML]:new Set([re.MI,re.MO,re.MN,re.MS,re.MTEXT,re.ANNOTATION_XML]),[ne.SVG]:new Set([re.TITLE,re.FOREIGN_OBJECT,re.DESC]),[ne.XLINK]:new Set,[ne.XML]:new Set,[ne.XMLNS]:new Set},Wa=new Set([re.H1,re.H2,re.H3,re.H4,re.H5,re.H6]);M.STYLE,M.SCRIPT,M.XMP,M.IFRAME,M.NOEMBED,M.NOFRAMES,M.PLAINTEXT;var E;(function(e){e[e.DATA=0]="DATA",e[e.RCDATA=1]="RCDATA",e[e.RAWTEXT=2]="RAWTEXT",e[e.SCRIPT_DATA=3]="SCRIPT_DATA",e[e.PLAINTEXT=4]="PLAINTEXT",e[e.TAG_OPEN=5]="TAG_OPEN",e[e.END_TAG_OPEN=6]="END_TAG_OPEN",e[e.TAG_NAME=7]="TAG_NAME",e[e.RCDATA_LESS_THAN_SIGN=8]="RCDATA_LESS_THAN_SIGN",e[e.RCDATA_END_TAG_OPEN=9]="RCDATA_END_TAG_OPEN",e[e.RCDATA_END_TAG_NAME=10]="RCDATA_END_TAG_NAME",e[e.RAWTEXT_LESS_THAN_SIGN=11]="RAWTEXT_LESS_THAN_SIGN",e[e.RAWTEXT_END_TAG_OPEN=12]="RAWTEXT_END_TAG_OPEN",e[e.RAWTEXT_END_TAG_NAME=13]="RAWTEXT_END_TAG_NAME",e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]="SCRIPT_DATA_LESS_THAN_SIGN",e[e.SCRIPT_DATA_END_TAG_OPEN=15]="SCRIPT_DATA_END_TAG_OPEN",e[e.SCRIPT_DATA_END_TAG_NAME=16]="SCRIPT_DATA_END_TAG_NAME",e[e.SCRIPT_DATA_ESCAPE_START=17]="SCRIPT_DATA_ESCAPE_START",e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]="SCRIPT_DATA_ESCAPE_START_DASH",e[e.SCRIPT_DATA_ESCAPED=19]="SCRIPT_DATA_ESCAPED",e[e.SCRIPT_DATA_ESCAPED_DASH=20]="SCRIPT_DATA_ESCAPED_DASH",e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]="SCRIPT_DATA_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START",e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]="SCRIPT_DATA_DOUBLE_ESCAPED",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END",e[e.BEFORE_ATTRIBUTE_NAME=31]="BEFORE_ATTRIBUTE_NAME",e[e.ATTRIBUTE_NAME=32]="ATTRIBUTE_NAME",e[e.AFTER_ATTRIBUTE_NAME=33]="AFTER_ATTRIBUTE_NAME",e[e.BEFORE_ATTRIBUTE_VALUE=34]="BEFORE_ATTRIBUTE_VALUE",e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED",e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED",e[e.ATTRIBUTE_VALUE_UNQUOTED=37]="ATTRIBUTE_VALUE_UNQUOTED",e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]="AFTER_ATTRIBUTE_VALUE_QUOTED",e[e.SELF_CLOSING_START_TAG=39]="SELF_CLOSING_START_TAG",e[e.BOGUS_COMMENT=40]="BOGUS_COMMENT",e[e.MARKUP_DECLARATION_OPEN=41]="MARKUP_DECLARATION_OPEN",e[e.COMMENT_START=42]="COMMENT_START",e[e.COMMENT_START_DASH=43]="COMMENT_START_DASH",e[e.COMMENT=44]="COMMENT",e[e.COMMENT_LESS_THAN_SIGN=45]="COMMENT_LESS_THAN_SIGN",e[e.COMMENT_LESS_THAN_SIGN_BANG=46]="COMMENT_LESS_THAN_SIGN_BANG",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH",e[e.COMMENT_END_DASH=49]="COMMENT_END_DASH",e[e.COMMENT_END=50]="COMMENT_END",e[e.COMMENT_END_BANG=51]="COMMENT_END_BANG",e[e.DOCTYPE=52]="DOCTYPE",e[e.BEFORE_DOCTYPE_NAME=53]="BEFORE_DOCTYPE_NAME",e[e.DOCTYPE_NAME=54]="DOCTYPE_NAME",e[e.AFTER_DOCTYPE_NAME=55]="AFTER_DOCTYPE_NAME",e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD",e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER",e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER",e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS",e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD",e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER",e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER",e[e.BOGUS_DOCTYPE=67]="BOGUS_DOCTYPE",e[e.CDATA_SECTION=68]="CDATA_SECTION",e[e.CDATA_SECTION_BRACKET=69]="CDATA_SECTION_BRACKET",e[e.CDATA_SECTION_END=70]="CDATA_SECTION_END",e[e.CHARACTER_REFERENCE=71]="CHARACTER_REFERENCE",e[e.AMBIGUOUS_AMPERSAND=72]="AMBIGUOUS_AMPERSAND"})(E||(E={}));const st={DATA:E.DATA,RCDATA:E.RCDATA,RAWTEXT:E.RAWTEXT,SCRIPT_DATA:E.SCRIPT_DATA,PLAINTEXT:E.PLAINTEXT,CDATA_SECTION:E.CDATA_SECTION};function Em(e){return e>=g.DIGIT_0&&e<=g.DIGIT_9}function Ls(e){return e>=g.LATIN_CAPITAL_A&&e<=g.LATIN_CAPITAL_Z}function Tm(e){return e>=g.LATIN_SMALL_A&&e<=g.LATIN_SMALL_Z}function Wt(e){return Tm(e)||Ls(e)}function Tr(e){return Wt(e)||Em(e)}function un(e){return e+32}function hl(e){return e===g.SPACE||e===g.LINE_FEED||e===g.TABULATION||e===g.FORM_FEED}function xr(e){return hl(e)||e===g.SOLIDUS||e===g.GREATER_THAN_SIGN}function xm(e){return e===g.NULL?G.nullCharacterReference:e>1114111?G.characterReferenceOutsideUnicodeRange:ul(e)?G.surrogateCharacterReference:pl(e)?G.noncharacterCharacterReference:dl(e)||e===g.CARRIAGE_RETURN?G.controlCharacterReference:null}class ym{constructor(t,n){this.options=t,this.handler=n,this.paused=!1,this.inLoop=!1,this.inForeignNode=!1,this.lastStartTagName="",this.active=!1,this.state=E.DATA,this.returnState=E.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new rm(n),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new hm(om,(a,i)=>{this.preprocessor.pos=this.entityStartPos+i-1,this._flushCodePointConsumedAsCharacterReference(a)},n.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(G.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:a=>{this._err(G.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+a)},validateNumericCharacterReference:a=>{const i=xm(a);i&&this._err(i,1)}}:void 0)}_err(t,n=0){var a,i;(i=(a=this.handler).onParseError)===null||i===void 0||i.call(a,this.preprocessor.getError(t,n))}getCurrentLocation(t){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-t,startOffset:this.preprocessor.offset-t,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=!0;this.active&&!this.paused;){this.consumedAfterSnapshot=0;const t=this._consume();this._ensureHibernation()||this._callState(t)}this.inLoop=!1}}pause(){this.paused=!0}resume(t){if(!this.paused)throw new Error("Parser was already resumed");this.paused=!1,!this.inLoop&&(this._runParsingLoop(),this.paused||t?.())}write(t,n,a){this.active=!0,this.preprocessor.write(t,n),this._runParsingLoop(),this.paused||a?.()}insertHtmlAtCurrentPos(t){this.active=!0,this.preprocessor.insertHtmlAtCurrentPos(t),this._runParsingLoop()}_ensureHibernation(){return this.preprocessor.endOfChunkHit?(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=!1,!0):!1}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(t){this.consumedAfterSnapshot+=t;for(let n=0;n<t;n++)this.preprocessor.advance()}_consumeSequenceIfMatch(t,n){return this.preprocessor.startsWith(t,n)?(this._advanceBy(t.length-1),!0):!1}_createStartTagToken(){this.currentToken={type:Ue.START_TAG,tagName:"",tagID:r.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:Ue.END_TAG,tagName:"",tagID:r.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(2)}}_createCommentToken(t){this.currentToken={type:Ue.COMMENT,data:"",location:this.getCurrentLocation(t)}}_createDoctypeToken(t){this.currentToken={type:Ue.DOCTYPE,name:t,forceQuirks:!1,publicId:null,systemId:null,location:this.currentLocation}}_createCharacterToken(t,n){this.currentCharacterToken={type:t,chars:n,location:this.currentLocation}}_createAttr(t){this.currentAttr={name:t,value:""},this.currentLocation=this.getCurrentLocation(0)}_leaveAttrName(){var t,n;const a=this.currentToken;if(ml(a,this.currentAttr.name)===null){if(a.attrs.push(this.currentAttr),a.location&&this.currentLocation){const i=(t=(n=a.location).attrs)!==null&&t!==void 0?t:n.attrs=Object.create(null);i[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue()}}else this._err(G.duplicateAttribute)}_leaveAttrValue(){this.currentLocation&&(this.currentLocation.endLine=this.preprocessor.line,this.currentLocation.endCol=this.preprocessor.col,this.currentLocation.endOffset=this.preprocessor.offset)}prepareToken(t){this._emitCurrentCharacterToken(t.location),this.currentToken=null,t.location&&(t.location.endLine=this.preprocessor.line,t.location.endCol=this.preprocessor.col+1,t.location.endOffset=this.preprocessor.offset+1),this.currentLocation=this.getCurrentLocation(-1)}emitCurrentTagToken(){const t=this.currentToken;this.prepareToken(t),t.tagID=Ts(t.tagName),t.type===Ue.START_TAG?(this.lastStartTagName=t.tagName,this.handler.onStartTag(t)):(t.attrs.length>0&&this._err(G.endTagWithAttributes),t.selfClosing&&this._err(G.endTagWithTrailingSolidus),this.handler.onEndTag(t)),this.preprocessor.dropParsedChunk()}emitCurrentComment(t){this.prepareToken(t),this.handler.onComment(t),this.preprocessor.dropParsedChunk()}emitCurrentDoctype(t){this.prepareToken(t),this.handler.onDoctype(t),this.preprocessor.dropParsedChunk()}_emitCurrentCharacterToken(t){if(this.currentCharacterToken){switch(t&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=t.startLine,this.currentCharacterToken.location.endCol=t.startCol,this.currentCharacterToken.location.endOffset=t.startOffset),this.currentCharacterToken.type){case Ue.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case Ue.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case Ue.WHITESPACE_CHARACTER:{this.handler.onWhitespaceCharacter(this.currentCharacterToken);break}}this.currentCharacterToken=null}}_emitEOFToken(){const t=this.getCurrentLocation(0);t&&(t.endLine=t.startLine,t.endCol=t.startCol,t.endOffset=t.startOffset),this._emitCurrentCharacterToken(t),this.handler.onEof({type:Ue.EOF,location:t}),this.active=!1}_appendCharToCurrentCharacterToken(t,n){if(this.currentCharacterToken)if(this.currentCharacterToken.type===t){this.currentCharacterToken.chars+=n;return}else this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk();this._createCharacterToken(t,n)}_emitCodePoint(t){const n=hl(t)?Ue.WHITESPACE_CHARACTER:t===g.NULL?Ue.NULL_CHARACTER:Ue.CHARACTER;this._appendCharToCurrentCharacterToken(n,String.fromCodePoint(t))}_emitChars(t){this._appendCharToCurrentCharacterToken(Ue.CHARACTER,t)}_startCharacterReference(){this.returnState=this.state,this.state=E.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?Mt.Attribute:Mt.Legacy)}_isCharacterReferenceInAttribute(){return this.returnState===E.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===E.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===E.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t)}_callState(t){switch(this.state){case E.DATA:{this._stateData(t);break}case E.RCDATA:{this._stateRcdata(t);break}case E.RAWTEXT:{this._stateRawtext(t);break}case E.SCRIPT_DATA:{this._stateScriptData(t);break}case E.PLAINTEXT:{this._statePlaintext(t);break}case E.TAG_OPEN:{this._stateTagOpen(t);break}case E.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case E.TAG_NAME:{this._stateTagName(t);break}case E.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case E.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case E.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case E.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case E.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case E.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case E.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case E.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case E.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case E.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case E.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case E.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case E.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case E.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case E.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case E.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case E.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case E.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case E.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case E.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case E.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case E.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case E.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case E.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case E.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case E.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case E.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case E.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case E.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case E.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case E.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case E.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case E.BOGUS_COMMENT:{this._stateBogusComment(t);break}case E.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case E.COMMENT_START:{this._stateCommentStart(t);break}case E.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case E.COMMENT:{this._stateComment(t);break}case E.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case E.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case E.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case E.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case E.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case E.COMMENT_END:{this._stateCommentEnd(t);break}case E.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case E.DOCTYPE:{this._stateDoctype(t);break}case E.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case E.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case E.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case E.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case E.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case E.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case E.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case E.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case E.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case E.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case E.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case E.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case E.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case E.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case E.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case E.CDATA_SECTION:{this._stateCdataSection(t);break}case E.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case E.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case E.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case E.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case g.LESS_THAN_SIGN:{this.state=E.TAG_OPEN;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.NULL:{this._err(G.unexpectedNullCharacter),this._emitCodePoint(t);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRcdata(t){switch(t){case g.AMPERSAND:{this._startCharacterReference();break}case g.LESS_THAN_SIGN:{this.state=E.RCDATA_LESS_THAN_SIGN;break}case g.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(et);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRawtext(t){switch(t){case g.LESS_THAN_SIGN:{this.state=E.RAWTEXT_LESS_THAN_SIGN;break}case g.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(et);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptData(t){switch(t){case g.LESS_THAN_SIGN:{this.state=E.SCRIPT_DATA_LESS_THAN_SIGN;break}case g.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(et);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_statePlaintext(t){switch(t){case g.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(et);break}case g.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateTagOpen(t){if(Wt(t))this._createStartTagToken(),this.state=E.TAG_NAME,this._stateTagName(t);else switch(t){case g.EXCLAMATION_MARK:{this.state=E.MARKUP_DECLARATION_OPEN;break}case g.SOLIDUS:{this.state=E.END_TAG_OPEN;break}case g.QUESTION_MARK:{this._err(G.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=E.BOGUS_COMMENT,this._stateBogusComment(t);break}case g.EOF:{this._err(G.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(G.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=E.DATA,this._stateData(t)}}_stateEndTagOpen(t){if(Wt(t))this._createEndTagToken(),this.state=E.TAG_NAME,this._stateTagName(t);else switch(t){case g.GREATER_THAN_SIGN:{this._err(G.missingEndTagName),this.state=E.DATA;break}case g.EOF:{this._err(G.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(G.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=E.BOGUS_COMMENT,this._stateBogusComment(t)}}_stateTagName(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=E.BEFORE_ATTRIBUTE_NAME;break}case g.SOLIDUS:{this.state=E.SELF_CLOSING_START_TAG;break}case g.GREATER_THAN_SIGN:{this.state=E.DATA,this.emitCurrentTagToken();break}case g.NULL:{this._err(G.unexpectedNullCharacter),n.tagName+=et;break}case g.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:n.tagName+=String.fromCodePoint(Ls(t)?un(t):t)}}_stateRcdataLessThanSign(t){t===g.SOLIDUS?this.state=E.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=E.RCDATA,this._stateRcdata(t))}_stateRcdataEndTagOpen(t){Wt(t)?(this.state=E.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=E.RCDATA,this._stateRcdata(t))}handleSpecialEndTag(t){if(!this.preprocessor.startsWith(this.lastStartTagName,!1))return!this._ensureHibernation();this._createEndTagToken();const n=this.currentToken;switch(n.tagName=this.lastStartTagName,this.preprocessor.peek(this.lastStartTagName.length)){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=E.BEFORE_ATTRIBUTE_NAME,!1;case g.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=E.SELF_CLOSING_START_TAG,!1;case g.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=E.DATA,!1;default:return!this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=E.RCDATA,this._stateRcdata(t))}_stateRawtextLessThanSign(t){t===g.SOLIDUS?this.state=E.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=E.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagOpen(t){Wt(t)?(this.state=E.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=E.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=E.RAWTEXT,this._stateRawtext(t))}_stateScriptDataLessThanSign(t){switch(t){case g.SOLIDUS:{this.state=E.SCRIPT_DATA_END_TAG_OPEN;break}case g.EXCLAMATION_MARK:{this.state=E.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=E.SCRIPT_DATA,this._stateScriptData(t)}}_stateScriptDataEndTagOpen(t){Wt(t)?(this.state=E.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=E.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=E.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStart(t){t===g.HYPHEN_MINUS?(this.state=E.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=E.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStartDash(t){t===g.HYPHEN_MINUS?(this.state=E.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=E.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscaped(t){switch(t){case g.HYPHEN_MINUS:{this.state=E.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=E.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case g.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(et);break}case g.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataEscapedDash(t){switch(t){case g.HYPHEN_MINUS:{this.state=E.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=E.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case g.NULL:{this._err(G.unexpectedNullCharacter),this.state=E.SCRIPT_DATA_ESCAPED,this._emitChars(et);break}case g.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=E.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedDashDash(t){switch(t){case g.HYPHEN_MINUS:{this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=E.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case g.GREATER_THAN_SIGN:{this.state=E.SCRIPT_DATA,this._emitChars(">");break}case g.NULL:{this._err(G.unexpectedNullCharacter),this.state=E.SCRIPT_DATA_ESCAPED,this._emitChars(et);break}case g.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=E.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedLessThanSign(t){t===g.SOLIDUS?this.state=E.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:Wt(t)?(this._emitChars("<"),this.state=E.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=E.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagOpen(t){Wt(t)?(this.state=E.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=E.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=E.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith(ht.SCRIPT,!1)&&xr(this.preprocessor.peek(ht.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<ht.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED}else this._ensureHibernation()||(this.state=E.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscaped(t){switch(t){case g.HYPHEN_MINUS:{this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case g.NULL:{this._err(G.unexpectedNullCharacter),this._emitChars(et);break}case g.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDash(t){switch(t){case g.HYPHEN_MINUS:{this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case g.NULL:{this._err(G.unexpectedNullCharacter),this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(et);break}case g.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case g.HYPHEN_MINUS:{this._emitChars("-");break}case g.LESS_THAN_SIGN:{this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case g.GREATER_THAN_SIGN:{this.state=E.SCRIPT_DATA,this._emitChars(">");break}case g.NULL:{this._err(G.unexpectedNullCharacter),this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(et);break}case g.EOF:{this._err(G.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedLessThanSign(t){t===g.SOLIDUS?(this.state=E.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(ht.SCRIPT,!1)&&xr(this.preprocessor.peek(ht.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<ht.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=E.SCRIPT_DATA_ESCAPED}else this._ensureHibernation()||(this.state=E.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateBeforeAttributeName(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.SOLIDUS:case g.GREATER_THAN_SIGN:case g.EOF:{this.state=E.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case g.EQUALS_SIGN:{this._err(G.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=E.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=E.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateAttributeName(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:case g.SOLIDUS:case g.GREATER_THAN_SIGN:case g.EOF:{this._leaveAttrName(),this.state=E.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case g.EQUALS_SIGN:{this._leaveAttrName(),this.state=E.BEFORE_ATTRIBUTE_VALUE;break}case g.QUOTATION_MARK:case g.APOSTROPHE:case g.LESS_THAN_SIGN:{this._err(G.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case g.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.name+=et;break}default:this.currentAttr.name+=String.fromCodePoint(Ls(t)?un(t):t)}}_stateAfterAttributeName(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.SOLIDUS:{this.state=E.SELF_CLOSING_START_TAG;break}case g.EQUALS_SIGN:{this.state=E.BEFORE_ATTRIBUTE_VALUE;break}case g.GREATER_THAN_SIGN:{this.state=E.DATA,this.emitCurrentTagToken();break}case g.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=E.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateBeforeAttributeValue(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.QUOTATION_MARK:{this.state=E.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this.state=E.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(G.missingAttributeValue),this.state=E.DATA,this.emitCurrentTagToken();break}default:this.state=E.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t)}}_stateAttributeValueDoubleQuoted(t){switch(t){case g.QUOTATION_MARK:{this.state=E.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.value+=et;break}case g.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueSingleQuoted(t){switch(t){case g.APOSTROPHE:{this.state=E.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.value+=et;break}case g.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueUnquoted(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this._leaveAttrValue(),this.state=E.BEFORE_ATTRIBUTE_NAME;break}case g.AMPERSAND:{this._startCharacterReference();break}case g.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=E.DATA,this.emitCurrentTagToken();break}case g.NULL:{this._err(G.unexpectedNullCharacter),this.currentAttr.value+=et;break}case g.QUOTATION_MARK:case g.APOSTROPHE:case g.LESS_THAN_SIGN:case g.EQUALS_SIGN:case g.GRAVE_ACCENT:{this._err(G.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case g.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAfterAttributeValueQuoted(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this._leaveAttrValue(),this.state=E.BEFORE_ATTRIBUTE_NAME;break}case g.SOLIDUS:{this._leaveAttrValue(),this.state=E.SELF_CLOSING_START_TAG;break}case g.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=E.DATA,this.emitCurrentTagToken();break}case g.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this._err(G.missingWhitespaceBetweenAttributes),this.state=E.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateSelfClosingStartTag(t){switch(t){case g.GREATER_THAN_SIGN:{const n=this.currentToken;n.selfClosing=!0,this.state=E.DATA,this.emitCurrentTagToken();break}case g.EOF:{this._err(G.eofInTag),this._emitEOFToken();break}default:this._err(G.unexpectedSolidusInTag),this.state=E.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateBogusComment(t){const n=this.currentToken;switch(t){case g.GREATER_THAN_SIGN:{this.state=E.DATA,this.emitCurrentComment(n);break}case g.EOF:{this.emitCurrentComment(n),this._emitEOFToken();break}case g.NULL:{this._err(G.unexpectedNullCharacter),n.data+=et;break}default:n.data+=String.fromCodePoint(t)}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(ht.DASH_DASH,!0)?(this._createCommentToken(ht.DASH_DASH.length+1),this.state=E.COMMENT_START):this._consumeSequenceIfMatch(ht.DOCTYPE,!1)?(this.currentLocation=this.getCurrentLocation(ht.DOCTYPE.length+1),this.state=E.DOCTYPE):this._consumeSequenceIfMatch(ht.CDATA_START,!0)?this.inForeignNode?this.state=E.CDATA_SECTION:(this._err(G.cdataInHtmlContent),this._createCommentToken(ht.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=E.BOGUS_COMMENT):this._ensureHibernation()||(this._err(G.incorrectlyOpenedComment),this._createCommentToken(2),this.state=E.BOGUS_COMMENT,this._stateBogusComment(t))}_stateCommentStart(t){switch(t){case g.HYPHEN_MINUS:{this.state=E.COMMENT_START_DASH;break}case g.GREATER_THAN_SIGN:{this._err(G.abruptClosingOfEmptyComment),this.state=E.DATA;const n=this.currentToken;this.emitCurrentComment(n);break}default:this.state=E.COMMENT,this._stateComment(t)}}_stateCommentStartDash(t){const n=this.currentToken;switch(t){case g.HYPHEN_MINUS:{this.state=E.COMMENT_END;break}case g.GREATER_THAN_SIGN:{this._err(G.abruptClosingOfEmptyComment),this.state=E.DATA,this.emitCurrentComment(n);break}case g.EOF:{this._err(G.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=E.COMMENT,this._stateComment(t)}}_stateComment(t){const n=this.currentToken;switch(t){case g.HYPHEN_MINUS:{this.state=E.COMMENT_END_DASH;break}case g.LESS_THAN_SIGN:{n.data+="<",this.state=E.COMMENT_LESS_THAN_SIGN;break}case g.NULL:{this._err(G.unexpectedNullCharacter),n.data+=et;break}case g.EOF:{this._err(G.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+=String.fromCodePoint(t)}}_stateCommentLessThanSign(t){const n=this.currentToken;switch(t){case g.EXCLAMATION_MARK:{n.data+="!",this.state=E.COMMENT_LESS_THAN_SIGN_BANG;break}case g.LESS_THAN_SIGN:{n.data+="<";break}default:this.state=E.COMMENT,this._stateComment(t)}}_stateCommentLessThanSignBang(t){t===g.HYPHEN_MINUS?this.state=E.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=E.COMMENT,this._stateComment(t))}_stateCommentLessThanSignBangDash(t){t===g.HYPHEN_MINUS?this.state=E.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=E.COMMENT_END_DASH,this._stateCommentEndDash(t))}_stateCommentLessThanSignBangDashDash(t){t!==g.GREATER_THAN_SIGN&&t!==g.EOF&&this._err(G.nestedComment),this.state=E.COMMENT_END,this._stateCommentEnd(t)}_stateCommentEndDash(t){const n=this.currentToken;switch(t){case g.HYPHEN_MINUS:{this.state=E.COMMENT_END;break}case g.EOF:{this._err(G.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=E.COMMENT,this._stateComment(t)}}_stateCommentEnd(t){const n=this.currentToken;switch(t){case g.GREATER_THAN_SIGN:{this.state=E.DATA,this.emitCurrentComment(n);break}case g.EXCLAMATION_MARK:{this.state=E.COMMENT_END_BANG;break}case g.HYPHEN_MINUS:{n.data+="-";break}case g.EOF:{this._err(G.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--",this.state=E.COMMENT,this._stateComment(t)}}_stateCommentEndBang(t){const n=this.currentToken;switch(t){case g.HYPHEN_MINUS:{n.data+="--!",this.state=E.COMMENT_END_DASH;break}case g.GREATER_THAN_SIGN:{this._err(G.incorrectlyClosedComment),this.state=E.DATA,this.emitCurrentComment(n);break}case g.EOF:{this._err(G.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--!",this.state=E.COMMENT,this._stateComment(t)}}_stateDoctype(t){switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=E.BEFORE_DOCTYPE_NAME;break}case g.GREATER_THAN_SIGN:{this.state=E.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case g.EOF:{this._err(G.eofInDoctype),this._createDoctypeToken(null);const n=this.currentToken;n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(G.missingWhitespaceBeforeDoctypeName),this.state=E.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t)}}_stateBeforeDoctypeName(t){if(Ls(t))this._createDoctypeToken(String.fromCharCode(un(t))),this.state=E.DOCTYPE_NAME;else switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.NULL:{this._err(G.unexpectedNullCharacter),this._createDoctypeToken(et),this.state=E.DOCTYPE_NAME;break}case g.GREATER_THAN_SIGN:{this._err(G.missingDoctypeName),this._createDoctypeToken(null);const n=this.currentToken;n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.EOF:{this._err(G.eofInDoctype),this._createDoctypeToken(null);const n=this.currentToken;n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._createDoctypeToken(String.fromCodePoint(t)),this.state=E.DOCTYPE_NAME}}_stateDoctypeName(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=E.AFTER_DOCTYPE_NAME;break}case g.GREATER_THAN_SIGN:{this.state=E.DATA,this.emitCurrentDoctype(n);break}case g.NULL:{this._err(G.unexpectedNullCharacter),n.name+=et;break}case g.EOF:{this._err(G.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.name+=String.fromCodePoint(Ls(t)?un(t):t)}}_stateAfterDoctypeName(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.GREATER_THAN_SIGN:{this.state=E.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(G.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(ht.PUBLIC,!1)?this.state=E.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(ht.SYSTEM,!1)?this.state=E.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(G.invalidCharacterSequenceAfterDoctypeName),n.forceQuirks=!0,this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t))}}_stateAfterDoctypePublicKeyword(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=E.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case g.QUOTATION_MARK:{this._err(G.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=E.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err(G.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=E.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(G.missingDoctypePublicIdentifier),n.forceQuirks=!0,this.state=E.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(G.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=!0,this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypePublicIdentifier(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.QUOTATION_MARK:{n.publicId="",this.state=E.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{n.publicId="",this.state=E.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(G.missingDoctypePublicIdentifier),n.forceQuirks=!0,this.state=E.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(G.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=!0,this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypePublicIdentifierDoubleQuoted(t){const n=this.currentToken;switch(t){case g.QUOTATION_MARK:{this.state=E.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case g.NULL:{this._err(G.unexpectedNullCharacter),n.publicId+=et;break}case g.GREATER_THAN_SIGN:{this._err(G.abruptDoctypePublicIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.EOF:{this._err(G.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.publicId+=String.fromCodePoint(t)}}_stateDoctypePublicIdentifierSingleQuoted(t){const n=this.currentToken;switch(t){case g.APOSTROPHE:{this.state=E.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case g.NULL:{this._err(G.unexpectedNullCharacter),n.publicId+=et;break}case g.GREATER_THAN_SIGN:{this._err(G.abruptDoctypePublicIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.EOF:{this._err(G.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.publicId+=String.fromCodePoint(t)}}_stateAfterDoctypePublicIdentifier(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=E.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case g.GREATER_THAN_SIGN:{this.state=E.DATA,this.emitCurrentDoctype(n);break}case g.QUOTATION_MARK:{this._err(G.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err(G.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.EOF:{this._err(G.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.QUOTATION_MARK:{n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.EOF:{this._err(G.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateAfterDoctypeSystemKeyword(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:{this.state=E.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case g.QUOTATION_MARK:{this._err(G.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{this._err(G.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(G.missingDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=E.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(G.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypeSystemIdentifier(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.QUOTATION_MARK:{n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case g.APOSTROPHE:{n.systemId="",this.state=E.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case g.GREATER_THAN_SIGN:{this._err(G.missingDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=E.DATA,this.emitCurrentDoctype(n);break}case g.EOF:{this._err(G.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(G.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypeSystemIdentifierDoubleQuoted(t){const n=this.currentToken;switch(t){case g.QUOTATION_MARK:{this.state=E.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case g.NULL:{this._err(G.unexpectedNullCharacter),n.systemId+=et;break}case g.GREATER_THAN_SIGN:{this._err(G.abruptDoctypeSystemIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.EOF:{this._err(G.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.systemId+=String.fromCodePoint(t)}}_stateDoctypeSystemIdentifierSingleQuoted(t){const n=this.currentToken;switch(t){case g.APOSTROPHE:{this.state=E.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case g.NULL:{this._err(G.unexpectedNullCharacter),n.systemId+=et;break}case g.GREATER_THAN_SIGN:{this._err(G.abruptDoctypeSystemIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.EOF:{this._err(G.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.systemId+=String.fromCodePoint(t)}}_stateAfterDoctypeSystemIdentifier(t){const n=this.currentToken;switch(t){case g.SPACE:case g.LINE_FEED:case g.TABULATION:case g.FORM_FEED:break;case g.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.EOF:{this._err(G.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(G.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=E.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBogusDoctype(t){const n=this.currentToken;switch(t){case g.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=E.DATA;break}case g.NULL:{this._err(G.unexpectedNullCharacter);break}case g.EOF:{this.emitCurrentDoctype(n),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case g.RIGHT_SQUARE_BRACKET:{this.state=E.CDATA_SECTION_BRACKET;break}case g.EOF:{this._err(G.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateCdataSectionBracket(t){t===g.RIGHT_SQUARE_BRACKET?this.state=E.CDATA_SECTION_END:(this._emitChars("]"),this.state=E.CDATA_SECTION,this._stateCdataSection(t))}_stateCdataSectionEnd(t){switch(t){case g.GREATER_THAN_SIGN:{this.state=E.DATA;break}case g.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=E.CDATA_SECTION,this._stateCdataSection(t)}}_stateCharacterReference(){let t=this.entityDecoder.write(this.preprocessor.html,this.preprocessor.pos);if(t<0)if(this.preprocessor.lastChunkWritten)t=this.entityDecoder.end();else{this.active=!1,this.preprocessor.pos=this.preprocessor.html.length-1,this.consumedAfterSnapshot=0,this.preprocessor.endOfChunkHit=!0;return}t===0?(this.preprocessor.pos=this.entityStartPos,this._flushCodePointConsumedAsCharacterReference(g.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&Tr(this.preprocessor.peek(1))?E.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState}_stateAmbiguousAmpersand(t){Tr(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===g.SEMICOLON&&this._err(G.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t))}}const fl=new Set([r.DD,r.DT,r.LI,r.OPTGROUP,r.OPTION,r.P,r.RB,r.RP,r.RT,r.RTC]),yr=new Set([...fl,r.CAPTION,r.COLGROUP,r.TBODY,r.TD,r.TFOOT,r.TH,r.THEAD,r.TR]),Hn=new Set([r.APPLET,r.CAPTION,r.HTML,r.MARQUEE,r.OBJECT,r.TABLE,r.TD,r.TEMPLATE,r.TH]),km=new Set([...Hn,r.OL,r.UL]),Nm=new Set([...Hn,r.BUTTON]),kr=new Set([r.ANNOTATION_XML,r.MI,r.MN,r.MO,r.MS,r.MTEXT]),Nr=new Set([r.DESC,r.FOREIGN_OBJECT,r.TITLE]),vm=new Set([r.TR,r.TEMPLATE,r.HTML]),Cm=new Set([r.TBODY,r.TFOOT,r.THEAD,r.TEMPLATE,r.HTML]),wm=new Set([r.TABLE,r.TEMPLATE,r.HTML]),Sm=new Set([r.TD,r.TH]);class _m{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,n,a){this.treeAdapter=n,this.handler=a,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=r.UNKNOWN,this.current=t}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===r.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===ne.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop]}push(t,n){this.stackTop++,this.items[this.stackTop]=t,this.current=t,this.tagIDs[this.stackTop]=n,this.currentTagId=n,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(t,n,!0)}pop(){const t=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,!0)}replace(t,n){const a=this._indexOf(t);this.items[a]=n,a===this.stackTop&&(this.current=n)}insertAfter(t,n,a){const i=this._indexOf(t)+1;this.items.splice(i,0,n),this.tagIDs.splice(i,0,a),this.stackTop++,i===this.stackTop&&this._updateCurrentElement(),this.current&&this.currentTagId!==void 0&&this.handler.onItemPush(this.current,this.currentTagId,i===this.stackTop)}popUntilTagNamePopped(t){let n=this.stackTop+1;do n=this.tagIDs.lastIndexOf(t,n-1);while(n>0&&this.treeAdapter.getNamespaceURI(this.items[n])!==ne.HTML);this.shortenToLength(Math.max(n,0))}shortenToLength(t){for(;this.stackTop>=t;){const n=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(n,this.stackTop<t)}}popUntilElementPopped(t){const n=this._indexOf(t);this.shortenToLength(Math.max(n,0))}popUntilPopped(t,n){const a=this._indexOfTagNames(t,n);this.shortenToLength(Math.max(a,0))}popUntilNumberedHeaderPopped(){this.popUntilPopped(Wa,ne.HTML)}popUntilTableCellPopped(){this.popUntilPopped(Sm,ne.HTML)}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1)}_indexOfTagNames(t,n){for(let a=this.stackTop;a>=0;a--)if(t.has(this.tagIDs[a])&&this.treeAdapter.getNamespaceURI(this.items[a])===n)return a;return-1}clearBackTo(t,n){const a=this._indexOfTagNames(t,n);this.shortenToLength(a+1)}clearBackToTableContext(){this.clearBackTo(wm,ne.HTML)}clearBackToTableBodyContext(){this.clearBackTo(Cm,ne.HTML)}clearBackToTableRowContext(){this.clearBackTo(vm,ne.HTML)}remove(t){const n=this._indexOf(t);n>=0&&(n===this.stackTop?this.pop():(this.items.splice(n,1),this.tagIDs.splice(n,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,!1)))}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===r.BODY?this.items[1]:null}contains(t){return this._indexOf(t)>-1}getCommonAncestor(t){const n=this._indexOf(t)-1;return n>=0?this.items[n]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===r.HTML}hasInDynamicScope(t,n){for(let a=this.stackTop;a>=0;a--){const i=this.tagIDs[a];switch(this.treeAdapter.getNamespaceURI(this.items[a])){case ne.HTML:{if(i===t)return!0;if(n.has(i))return!1;break}case ne.SVG:{if(Nr.has(i))return!1;break}case ne.MATHML:{if(kr.has(i))return!1;break}}}return!0}hasInScope(t){return this.hasInDynamicScope(t,Hn)}hasInListItemScope(t){return this.hasInDynamicScope(t,km)}hasInButtonScope(t){return this.hasInDynamicScope(t,Nm)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){const n=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case ne.HTML:{if(Wa.has(n))return!0;if(Hn.has(n))return!1;break}case ne.SVG:{if(Nr.has(n))return!1;break}case ne.MATHML:{if(kr.has(n))return!1;break}}}return!0}hasInTableScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===ne.HTML)switch(this.tagIDs[n]){case t:return!0;case r.TABLE:case r.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===ne.HTML)switch(this.tagIDs[t]){case r.TBODY:case r.THEAD:case r.TFOOT:return!0;case r.TABLE:case r.HTML:return!1}return!0}hasInSelectScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===ne.HTML)switch(this.tagIDs[n]){case t:return!0;case r.OPTION:case r.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&fl.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&yr.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&yr.has(this.currentTagId);)this.pop()}}const Ta=3;var It;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element"})(It||(It={}));const vr={type:It.Marker};class Am{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(t,n){const a=[],i=n.length,o=this.treeAdapter.getTagName(t),l=this.treeAdapter.getNamespaceURI(t);for(let u=0;u<this.entries.length;u++){const p=this.entries[u];if(p.type===It.Marker)break;const{element:h}=p;if(this.treeAdapter.getTagName(h)===o&&this.treeAdapter.getNamespaceURI(h)===l){const b=this.treeAdapter.getAttrList(h);b.length===i&&a.push({idx:u,attrs:b})}}return a}_ensureNoahArkCondition(t){if(this.entries.length<Ta)return;const n=this.treeAdapter.getAttrList(t),a=this._getNoahArkConditionCandidates(t,n);if(a.length<Ta)return;const i=new Map(n.map(l=>[l.name,l.value]));let o=0;for(let l=0;l<a.length;l++){const u=a[l];u.attrs.every(p=>i.get(p.name)===p.value)&&(o+=1,o>=Ta&&this.entries.splice(u.idx,1))}}insertMarker(){this.entries.unshift(vr)}pushElement(t,n){this._ensureNoahArkCondition(t),this.entries.unshift({type:It.Element,element:t,token:n})}insertElementAfterBookmark(t,n){const a=this.entries.indexOf(this.bookmark);this.entries.splice(a,0,{type:It.Element,element:t,token:n})}removeEntry(t){const n=this.entries.indexOf(t);n!==-1&&this.entries.splice(n,1)}clearToLastMarker(){const t=this.entries.indexOf(vr);t===-1?this.entries.length=0:this.entries.splice(0,t+1)}getElementEntryInScopeWithTagName(t){const n=this.entries.find(a=>a.type===It.Marker||this.treeAdapter.getTagName(a.element)===t);return n&&n.type===It.Element?n:null}getElementEntry(t){return this.entries.find(n=>n.type===It.Element&&n.element===t)}}const Kt={createDocument(){return{nodeName:"#document",mode:xt.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return{nodeName:"#document-fragment",childNodes:[]}},createElement(e,t,n){return{nodeName:e,tagName:e,attrs:n,namespaceURI:t,childNodes:[],parentNode:null}},createCommentNode(e){return{nodeName:"#comment",data:e,parentNode:null}},createTextNode(e){return{nodeName:"#text",value:e,parentNode:null}},appendChild(e,t){e.childNodes.push(t),t.parentNode=e},insertBefore(e,t,n){const a=e.childNodes.indexOf(n);e.childNodes.splice(a,0,t),t.parentNode=e},setTemplateContent(e,t){e.content=t},getTemplateContent(e){return e.content},setDocumentType(e,t,n,a){const i=e.childNodes.find(o=>o.nodeName==="#documentType");if(i)i.name=t,i.publicId=n,i.systemId=a;else{const o={nodeName:"#documentType",name:t,publicId:n,systemId:a,parentNode:null};Kt.appendChild(e,o)}},setDocumentMode(e,t){e.mode=t},getDocumentMode(e){return e.mode},detachNode(e){if(e.parentNode){const t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null}},insertText(e,t){if(e.childNodes.length>0){const n=e.childNodes[e.childNodes.length-1];if(Kt.isTextNode(n)){n.value+=t;return}}Kt.appendChild(e,Kt.createTextNode(t))},insertTextBefore(e,t,n){const a=e.childNodes[e.childNodes.indexOf(n)-1];a&&Kt.isTextNode(a)?a.value+=t:Kt.insertBefore(e,Kt.createTextNode(t),n)},adoptAttributes(e,t){const n=new Set(e.attrs.map(a=>a.name));for(let a=0;a<t.length;a++)n.has(t[a].name)||e.attrs.push(t[a])},getFirstChild(e){return e.childNodes[0]},getChildNodes(e){return e.childNodes},getParentNode(e){return e.parentNode},getAttrList(e){return e.attrs},getTagName(e){return e.tagName},getNamespaceURI(e){return e.namespaceURI},getTextNodeContent(e){return e.value},getCommentNodeContent(e){return e.data},getDocumentTypeNodeName(e){return e.name},getDocumentTypeNodePublicId(e){return e.publicId},getDocumentTypeNodeSystemId(e){return e.systemId},isTextNode(e){return e.nodeName==="#text"},isCommentNode(e){return e.nodeName==="#comment"},isDocumentTypeNode(e){return e.nodeName==="#documentType"},isElementNode(e){return Object.prototype.hasOwnProperty.call(e,"tagName")},setNodeSourceCodeLocation(e,t){e.sourceCodeLocation=t},getNodeSourceCodeLocation(e){return e.sourceCodeLocation},updateNodeSourceCodeLocation(e,t){e.sourceCodeLocation={...e.sourceCodeLocation,...t}}},gl="html",Im="about:legacy-compat",jm="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",bl=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"],Rm=[...bl,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],Lm=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),El=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],Dm=[...El,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function Cr(e,t){return t.some(n=>e.startsWith(n))}function Pm(e){return e.name===gl&&e.publicId===null&&(e.systemId===null||e.systemId===Im)}function Om(e){if(e.name!==gl)return xt.QUIRKS;const{systemId:t}=e;if(t&&t.toLowerCase()===jm)return xt.QUIRKS;let{publicId:n}=e;if(n!==null){if(n=n.toLowerCase(),Lm.has(n))return xt.QUIRKS;let a=t===null?Rm:bl;if(Cr(n,a))return xt.QUIRKS;if(a=t===null?El:Dm,Cr(n,a))return xt.LIMITED_QUIRKS}return xt.NO_QUIRKS}const wr={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},Mm="definitionurl",Bm="definitionURL",Fm=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e])),Hm=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:ne.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:ne.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:ne.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:ne.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:ne.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:ne.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:ne.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:ne.XML}],["xml:space",{prefix:"xml",name:"space",namespace:ne.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:ne.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:ne.XMLNS}]]),Um=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),$m=new Set([r.B,r.BIG,r.BLOCKQUOTE,r.BODY,r.BR,r.CENTER,r.CODE,r.DD,r.DIV,r.DL,r.DT,r.EM,r.EMBED,r.H1,r.H2,r.H3,r.H4,r.H5,r.H6,r.HEAD,r.HR,r.I,r.IMG,r.LI,r.LISTING,r.MENU,r.META,r.NOBR,r.OL,r.P,r.PRE,r.RUBY,r.S,r.SMALL,r.SPAN,r.STRONG,r.STRIKE,r.SUB,r.SUP,r.TABLE,r.TT,r.U,r.UL,r.VAR]);function qm(e){const t=e.tagID;return t===r.FONT&&e.attrs.some(({name:a})=>a===ns.COLOR||a===ns.SIZE||a===ns.FACE)||$m.has(t)}function Tl(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===Mm){e.attrs[t].name=Bm;break}}function xl(e){for(let t=0;t<e.attrs.length;t++){const n=Fm.get(e.attrs[t].name);n!=null&&(e.attrs[t].name=n)}}function ui(e){for(let t=0;t<e.attrs.length;t++){const n=Hm.get(e.attrs[t].name);n&&(e.attrs[t].prefix=n.prefix,e.attrs[t].name=n.name,e.attrs[t].namespace=n.namespace)}}function Wm(e){const t=Um.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=Ts(e.tagName))}function Km(e,t){return t===ne.MATHML&&(e===r.MI||e===r.MO||e===r.MN||e===r.MS||e===r.MTEXT)}function Ym(e,t,n){if(t===ne.MATHML&&e===r.ANNOTATION_XML){for(let a=0;a<n.length;a++)if(n[a].name===ns.ENCODING){const i=n[a].value.toLowerCase();return i===wr.TEXT_HTML||i===wr.APPLICATION_XML}}return t===ne.SVG&&(e===r.FOREIGN_OBJECT||e===r.DESC||e===r.TITLE)}function Gm(e,t,n,a){return(!a||a===ne.HTML)&&Ym(e,t,n)||(!a||a===ne.MATHML)&&Km(e,t)}const zm="hidden",Vm=8,Qm=3;var k;(function(e){e[e.INITIAL=0]="INITIAL",e[e.BEFORE_HTML=1]="BEFORE_HTML",e[e.BEFORE_HEAD=2]="BEFORE_HEAD",e[e.IN_HEAD=3]="IN_HEAD",e[e.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",e[e.AFTER_HEAD=5]="AFTER_HEAD",e[e.IN_BODY=6]="IN_BODY",e[e.TEXT=7]="TEXT",e[e.IN_TABLE=8]="IN_TABLE",e[e.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",e[e.IN_CAPTION=10]="IN_CAPTION",e[e.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",e[e.IN_TABLE_BODY=12]="IN_TABLE_BODY",e[e.IN_ROW=13]="IN_ROW",e[e.IN_CELL=14]="IN_CELL",e[e.IN_SELECT=15]="IN_SELECT",e[e.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",e[e.IN_TEMPLATE=17]="IN_TEMPLATE",e[e.AFTER_BODY=18]="AFTER_BODY",e[e.IN_FRAMESET=19]="IN_FRAMESET",e[e.AFTER_FRAMESET=20]="AFTER_FRAMESET",e[e.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",e[e.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET"})(k||(k={}));const Xm={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},yl=new Set([r.TABLE,r.TBODY,r.TFOOT,r.THEAD,r.TR]),Sr={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:Kt,onParseError:null};class _r{constructor(t,n,a=null,i=null){this.fragmentContext=a,this.scriptHandler=i,this.currentToken=null,this.stopped=!1,this.insertionMode=k.INITIAL,this.originalInsertionMode=k.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=!1,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=!1,this.framesetOk=!0,this.skipNextNewLine=!1,this.fosterParentingEnabled=!1,this.options={...Sr,...t},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=!0),this.document=n??this.treeAdapter.createDocument(),this.tokenizer=new ym(this.options,this),this.activeFormattingElements=new Am(this.treeAdapter),this.fragmentContextID=a?Ts(this.treeAdapter.getTagName(a)):r.UNKNOWN,this._setContextModes(a??this.document,this.fragmentContextID),this.openElements=new _m(this.document,this.treeAdapter,this)}static parse(t,n){const a=new this(n);return a.tokenizer.write(t,!0),a.document}static getFragmentParser(t,n){const a={...Sr,...n};t??(t=a.treeAdapter.createElement(M.TEMPLATE,ne.HTML,[]));const i=a.treeAdapter.createElement("documentmock",ne.HTML,[]),o=new this(a,i,t);return o.fragmentContextID===r.TEMPLATE&&o.tmplInsertionModeStack.unshift(k.IN_TEMPLATE),o._initTokenizerForFragmentParsing(),o._insertFakeRootElement(),o._resetInsertionMode(),o._findFormInFragmentContext(),o}getFragment(){const t=this.treeAdapter.getFirstChild(this.document),n=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,n),n}_err(t,n,a){var i;if(!this.onParseError)return;const o=(i=t.location)!==null&&i!==void 0?i:Xm,l={code:n,startLine:o.startLine,startCol:o.startCol,startOffset:o.startOffset,endLine:a?o.startLine:o.endLine,endCol:a?o.startCol:o.endCol,endOffset:a?o.startOffset:o.endOffset};this.onParseError(l)}onItemPush(t,n,a){var i,o;(o=(i=this.treeAdapter).onItemPush)===null||o===void 0||o.call(i,t),a&&this.openElements.stackTop>0&&this._setContextModes(t,n)}onItemPop(t,n){var a,i;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(i=(a=this.treeAdapter).onItemPop)===null||i===void 0||i.call(a,t,this.openElements.current),n){let o,l;this.openElements.stackTop===0&&this.fragmentContext?(o=this.fragmentContext,l=this.fragmentContextID):{current:o,currentTagId:l}=this.openElements,this._setContextModes(o,l)}}_setContextModes(t,n){const a=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===ne.HTML;this.currentNotInHTML=!a,this.tokenizer.inForeignNode=!a&&t!==void 0&&n!==void 0&&!this._isIntegrationPoint(n,t)}_switchToTextParsing(t,n){this._insertElement(t,ne.HTML),this.tokenizer.state=n,this.originalInsertionMode=this.insertionMode,this.insertionMode=k.TEXT}switchToPlaintextParsing(){this.insertionMode=k.TEXT,this.originalInsertionMode=k.IN_BODY,this.tokenizer.state=st.PLAINTEXT}_getAdjustedCurrentElement(){return this.openElements.stackTop===0&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let t=this.fragmentContext;for(;t;){if(this.treeAdapter.getTagName(t)===M.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t)}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==ne.HTML))switch(this.fragmentContextID){case r.TITLE:case r.TEXTAREA:{this.tokenizer.state=st.RCDATA;break}case r.STYLE:case r.XMP:case r.IFRAME:case r.NOEMBED:case r.NOFRAMES:case r.NOSCRIPT:{this.tokenizer.state=st.RAWTEXT;break}case r.SCRIPT:{this.tokenizer.state=st.SCRIPT_DATA;break}case r.PLAINTEXT:{this.tokenizer.state=st.PLAINTEXT;break}}}_setDocumentType(t){const n=t.name||"",a=t.publicId||"",i=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,n,a,i),t.location){const l=this.treeAdapter.getChildNodes(this.document).find(u=>this.treeAdapter.isDocumentTypeNode(u));l&&this.treeAdapter.setNodeSourceCodeLocation(l,t.location)}}_attachElementToTree(t,n){if(this.options.sourceCodeLocationInfo){const a=n&&{...n,startTag:n};this.treeAdapter.setNodeSourceCodeLocation(t,a)}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else{const a=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(a??this.document,t)}}_appendElement(t,n){const a=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(a,t.location)}_insertElement(t,n){const a=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(a,t.location),this.openElements.push(a,t.tagID)}_insertFakeElement(t,n){const a=this.treeAdapter.createElement(t,ne.HTML,[]);this._attachElementToTree(a,null),this.openElements.push(a,n)}_insertTemplate(t){const n=this.treeAdapter.createElement(t.tagName,ne.HTML,t.attrs),a=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(n,a),this._attachElementToTree(n,t.location),this.openElements.push(n,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(a,null)}_insertFakeRootElement(){const t=this.treeAdapter.createElement(M.HTML,ne.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,r.HTML)}_appendCommentNode(t,n){const a=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(n,a),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(a,t.location)}_insertCharacters(t){let n,a;if(this._shouldFosterParentOnInsertion()?({parent:n,beforeElement:a}=this._findFosterParentingLocation(),a?this.treeAdapter.insertTextBefore(n,t.chars,a):this.treeAdapter.insertText(n,t.chars)):(n=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(n,t.chars)),!t.location)return;const i=this.treeAdapter.getChildNodes(n),o=a?i.lastIndexOf(a):i.length,l=i[o-1];if(this.treeAdapter.getNodeSourceCodeLocation(l)){const{endLine:p,endCol:h,endOffset:b}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(l,{endLine:p,endCol:h,endOffset:b})}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(l,t.location)}_adoptNodes(t,n){for(let a=this.treeAdapter.getFirstChild(t);a;a=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(a),this.treeAdapter.appendChild(n,a)}_setEndLocation(t,n){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&n.location){const a=n.location,i=this.treeAdapter.getTagName(t),o=n.type===Ue.END_TAG&&i===n.tagName?{endTag:{...a},endLine:a.endLine,endCol:a.endCol,endOffset:a.endOffset}:{endLine:a.startLine,endCol:a.startCol,endOffset:a.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,o)}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return!1;let n,a;return this.openElements.stackTop===0&&this.fragmentContext?(n=this.fragmentContext,a=this.fragmentContextID):{current:n,currentTagId:a}=this.openElements,t.tagID===r.SVG&&this.treeAdapter.getTagName(n)===M.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(n)===ne.MATHML?!1:this.tokenizer.inForeignNode||(t.tagID===r.MGLYPH||t.tagID===r.MALIGNMARK)&&a!==void 0&&!this._isIntegrationPoint(a,n,ne.HTML)}_processToken(t){switch(t.type){case Ue.CHARACTER:{this.onCharacter(t);break}case Ue.NULL_CHARACTER:{this.onNullCharacter(t);break}case Ue.COMMENT:{this.onComment(t);break}case Ue.DOCTYPE:{this.onDoctype(t);break}case Ue.START_TAG:{this._processStartTag(t);break}case Ue.END_TAG:{this.onEndTag(t);break}case Ue.EOF:{this.onEof(t);break}case Ue.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,n,a){const i=this.treeAdapter.getNamespaceURI(n),o=this.treeAdapter.getAttrList(n);return Gm(t,i,o,a)}_reconstructActiveFormattingElements(){const t=this.activeFormattingElements.entries.length;if(t){const n=this.activeFormattingElements.entries.findIndex(i=>i.type===It.Marker||this.openElements.contains(i.element)),a=n===-1?t-1:n-1;for(let i=a;i>=0;i--){const o=this.activeFormattingElements.entries[i];this._insertElement(o.token,this.treeAdapter.getNamespaceURI(o.element)),o.element=this.openElements.current}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=k.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(r.P),this.openElements.popUntilTagNamePopped(r.P)}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case r.TR:{this.insertionMode=k.IN_ROW;return}case r.TBODY:case r.THEAD:case r.TFOOT:{this.insertionMode=k.IN_TABLE_BODY;return}case r.CAPTION:{this.insertionMode=k.IN_CAPTION;return}case r.COLGROUP:{this.insertionMode=k.IN_COLUMN_GROUP;return}case r.TABLE:{this.insertionMode=k.IN_TABLE;return}case r.BODY:{this.insertionMode=k.IN_BODY;return}case r.FRAMESET:{this.insertionMode=k.IN_FRAMESET;return}case r.SELECT:{this._resetInsertionModeForSelect(t);return}case r.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case r.HTML:{this.insertionMode=this.headElement?k.AFTER_HEAD:k.BEFORE_HEAD;return}case r.TD:case r.TH:{if(t>0){this.insertionMode=k.IN_CELL;return}break}case r.HEAD:{if(t>0){this.insertionMode=k.IN_HEAD;return}break}}this.insertionMode=k.IN_BODY}_resetInsertionModeForSelect(t){if(t>0)for(let n=t-1;n>0;n--){const a=this.openElements.tagIDs[n];if(a===r.TEMPLATE)break;if(a===r.TABLE){this.insertionMode=k.IN_SELECT_IN_TABLE;return}}this.insertionMode=k.IN_SELECT}_isElementCausesFosterParenting(t){return yl.has(t)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&this.openElements.currentTagId!==void 0&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let t=this.openElements.stackTop;t>=0;t--){const n=this.openElements.items[t];switch(this.openElements.tagIDs[t]){case r.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(n)===ne.HTML)return{parent:this.treeAdapter.getTemplateContent(n),beforeElement:null};break}case r.TABLE:{const a=this.treeAdapter.getParentNode(n);return a?{parent:a,beforeElement:n}:{parent:this.openElements.items[t-1],beforeElement:null}}}}return{parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(t){const n=this._findFosterParentingLocation();n.beforeElement?this.treeAdapter.insertBefore(n.parent,t,n.beforeElement):this.treeAdapter.appendChild(n.parent,t)}_isSpecialElement(t,n){const a=this.treeAdapter.getNamespaceURI(t);return bm[a].has(n)}onCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){_f(this,t);return}switch(this.insertionMode){case k.INITIAL:{ws(this,t);break}case k.BEFORE_HTML:{Ms(this,t);break}case k.BEFORE_HEAD:{Bs(this,t);break}case k.IN_HEAD:{Fs(this,t);break}case k.IN_HEAD_NO_SCRIPT:{Hs(this,t);break}case k.AFTER_HEAD:{Us(this,t);break}case k.IN_BODY:case k.IN_CAPTION:case k.IN_CELL:case k.IN_TEMPLATE:{Nl(this,t);break}case k.TEXT:case k.IN_SELECT:case k.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case k.IN_TABLE:case k.IN_TABLE_BODY:case k.IN_ROW:{xa(this,t);break}case k.IN_TABLE_TEXT:{Al(this,t);break}case k.IN_COLUMN_GROUP:{Un(this,t);break}case k.AFTER_BODY:{$n(this,t);break}case k.AFTER_AFTER_BODY:{yn(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){Sf(this,t);return}switch(this.insertionMode){case k.INITIAL:{ws(this,t);break}case k.BEFORE_HTML:{Ms(this,t);break}case k.BEFORE_HEAD:{Bs(this,t);break}case k.IN_HEAD:{Fs(this,t);break}case k.IN_HEAD_NO_SCRIPT:{Hs(this,t);break}case k.AFTER_HEAD:{Us(this,t);break}case k.TEXT:{this._insertCharacters(t);break}case k.IN_TABLE:case k.IN_TABLE_BODY:case k.IN_ROW:{xa(this,t);break}case k.IN_COLUMN_GROUP:{Un(this,t);break}case k.AFTER_BODY:{$n(this,t);break}case k.AFTER_AFTER_BODY:{yn(this,t);break}}}onComment(t){if(this.skipNextNewLine=!1,this.currentNotInHTML){Ka(this,t);return}switch(this.insertionMode){case k.INITIAL:case k.BEFORE_HTML:case k.BEFORE_HEAD:case k.IN_HEAD:case k.IN_HEAD_NO_SCRIPT:case k.AFTER_HEAD:case k.IN_BODY:case k.IN_TABLE:case k.IN_CAPTION:case k.IN_COLUMN_GROUP:case k.IN_TABLE_BODY:case k.IN_ROW:case k.IN_CELL:case k.IN_SELECT:case k.IN_SELECT_IN_TABLE:case k.IN_TEMPLATE:case k.IN_FRAMESET:case k.AFTER_FRAMESET:{Ka(this,t);break}case k.IN_TABLE_TEXT:{Ss(this,t);break}case k.AFTER_BODY:{ah(this,t);break}case k.AFTER_AFTER_BODY:case k.AFTER_AFTER_FRAMESET:{ih(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=!1,this.insertionMode){case k.INITIAL:{rh(this,t);break}case k.BEFORE_HEAD:case k.IN_HEAD:case k.IN_HEAD_NO_SCRIPT:case k.AFTER_HEAD:{this._err(t,G.misplacedDoctype);break}case k.IN_TABLE_TEXT:{Ss(this,t);break}}}onStartTag(t){this.skipNextNewLine=!1,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,G.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?Af(this,t):this._startTagOutsideForeignContent(t)}_startTagOutsideForeignContent(t){switch(this.insertionMode){case k.INITIAL:{ws(this,t);break}case k.BEFORE_HTML:{oh(this,t);break}case k.BEFORE_HEAD:{ch(this,t);break}case k.IN_HEAD:{_t(this,t);break}case k.IN_HEAD_NO_SCRIPT:{ph(this,t);break}case k.AFTER_HEAD:{hh(this,t);break}case k.IN_BODY:{ct(this,t);break}case k.IN_TABLE:{gs(this,t);break}case k.IN_TABLE_TEXT:{Ss(this,t);break}case k.IN_CAPTION:{df(this,t);break}case k.IN_COLUMN_GROUP:{mi(this,t);break}case k.IN_TABLE_BODY:{aa(this,t);break}case k.IN_ROW:{ia(this,t);break}case k.IN_CELL:{hf(this,t);break}case k.IN_SELECT:{Rl(this,t);break}case k.IN_SELECT_IN_TABLE:{gf(this,t);break}case k.IN_TEMPLATE:{Ef(this,t);break}case k.AFTER_BODY:{xf(this,t);break}case k.IN_FRAMESET:{yf(this,t);break}case k.AFTER_FRAMESET:{Nf(this,t);break}case k.AFTER_AFTER_BODY:{Cf(this,t);break}case k.AFTER_AFTER_FRAMESET:{wf(this,t);break}}}onEndTag(t){this.skipNextNewLine=!1,this.currentToken=t,this.currentNotInHTML?If(this,t):this._endTagOutsideForeignContent(t)}_endTagOutsideForeignContent(t){switch(this.insertionMode){case k.INITIAL:{ws(this,t);break}case k.BEFORE_HTML:{lh(this,t);break}case k.BEFORE_HEAD:{uh(this,t);break}case k.IN_HEAD:{dh(this,t);break}case k.IN_HEAD_NO_SCRIPT:{mh(this,t);break}case k.AFTER_HEAD:{fh(this,t);break}case k.IN_BODY:{na(this,t);break}case k.TEXT:{ef(this,t);break}case k.IN_TABLE:{zs(this,t);break}case k.IN_TABLE_TEXT:{Ss(this,t);break}case k.IN_CAPTION:{pf(this,t);break}case k.IN_COLUMN_GROUP:{mf(this,t);break}case k.IN_TABLE_BODY:{Ya(this,t);break}case k.IN_ROW:{jl(this,t);break}case k.IN_CELL:{ff(this,t);break}case k.IN_SELECT:{Ll(this,t);break}case k.IN_SELECT_IN_TABLE:{bf(this,t);break}case k.IN_TEMPLATE:{Tf(this,t);break}case k.AFTER_BODY:{Pl(this,t);break}case k.IN_FRAMESET:{kf(this,t);break}case k.AFTER_FRAMESET:{vf(this,t);break}case k.AFTER_AFTER_BODY:{yn(this,t);break}}}onEof(t){switch(this.insertionMode){case k.INITIAL:{ws(this,t);break}case k.BEFORE_HTML:{Ms(this,t);break}case k.BEFORE_HEAD:{Bs(this,t);break}case k.IN_HEAD:{Fs(this,t);break}case k.IN_HEAD_NO_SCRIPT:{Hs(this,t);break}case k.AFTER_HEAD:{Us(this,t);break}case k.IN_BODY:case k.IN_TABLE:case k.IN_CAPTION:case k.IN_COLUMN_GROUP:case k.IN_TABLE_BODY:case k.IN_ROW:case k.IN_CELL:case k.IN_SELECT:case k.IN_SELECT_IN_TABLE:{Sl(this,t);break}case k.TEXT:{tf(this,t);break}case k.IN_TABLE_TEXT:{Ss(this,t);break}case k.IN_TEMPLATE:{Dl(this,t);break}case k.AFTER_BODY:case k.IN_FRAMESET:case k.AFTER_FRAMESET:case k.AFTER_AFTER_BODY:case k.AFTER_AFTER_FRAMESET:{pi(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=!1,t.chars.charCodeAt(0)===g.LINE_FEED)){if(t.chars.length===1)return;t.chars=t.chars.substr(1)}if(this.tokenizer.inForeignNode){this._insertCharacters(t);return}switch(this.insertionMode){case k.IN_HEAD:case k.IN_HEAD_NO_SCRIPT:case k.AFTER_HEAD:case k.TEXT:case k.IN_COLUMN_GROUP:case k.IN_SELECT:case k.IN_SELECT_IN_TABLE:case k.IN_FRAMESET:case k.AFTER_FRAMESET:{this._insertCharacters(t);break}case k.IN_BODY:case k.IN_CAPTION:case k.IN_CELL:case k.IN_TEMPLATE:case k.AFTER_BODY:case k.AFTER_AFTER_BODY:case k.AFTER_AFTER_FRAMESET:{kl(this,t);break}case k.IN_TABLE:case k.IN_TABLE_BODY:case k.IN_ROW:{xa(this,t);break}case k.IN_TABLE_TEXT:{_l(this,t);break}}}}function Jm(e,t){let n=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return n?e.openElements.contains(n.element)?e.openElements.hasInScope(t.tagID)||(n=null):(e.activeFormattingElements.removeEntry(n),n=null):wl(e,t),n}function Zm(e,t){let n=null,a=e.openElements.stackTop;for(;a>=0;a--){const i=e.openElements.items[a];if(i===t.element)break;e._isSpecialElement(i,e.openElements.tagIDs[a])&&(n=i)}return n||(e.openElements.shortenToLength(Math.max(a,0)),e.activeFormattingElements.removeEntry(t)),n}function eh(e,t,n){let a=t,i=e.openElements.getCommonAncestor(t);for(let o=0,l=i;l!==n;o++,l=i){i=e.openElements.getCommonAncestor(l);const u=e.activeFormattingElements.getElementEntry(l),p=u&&o>=Qm;!u||p?(p&&e.activeFormattingElements.removeEntry(u),e.openElements.remove(l)):(l=th(e,u),a===t&&(e.activeFormattingElements.bookmark=u),e.treeAdapter.detachNode(a),e.treeAdapter.appendChild(l,a),a=l)}return a}function th(e,t){const n=e.treeAdapter.getNamespaceURI(t.element),a=e.treeAdapter.createElement(t.token.tagName,n,t.token.attrs);return e.openElements.replace(t.element,a),t.element=a,a}function sh(e,t,n){const a=e.treeAdapter.getTagName(t),i=Ts(a);if(e._isElementCausesFosterParenting(i))e._fosterParentElement(n);else{const o=e.treeAdapter.getNamespaceURI(t);i===r.TEMPLATE&&o===ne.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,n)}}function nh(e,t,n){const a=e.treeAdapter.getNamespaceURI(n.element),{token:i}=n,o=e.treeAdapter.createElement(i.tagName,a,i.attrs);e._adoptNodes(t,o),e.treeAdapter.appendChild(t,o),e.activeFormattingElements.insertElementAfterBookmark(o,i),e.activeFormattingElements.removeEntry(n),e.openElements.remove(n.element),e.openElements.insertAfter(t,o,i.tagID)}function di(e,t){for(let n=0;n<Vm;n++){const a=Jm(e,t);if(!a)break;const i=Zm(e,a);if(!i)break;e.activeFormattingElements.bookmark=a;const o=eh(e,i,a.element),l=e.openElements.getCommonAncestor(a.element);e.treeAdapter.detachNode(o),l&&sh(e,l,o),nh(e,i,a)}}function Ka(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode)}function ah(e,t){e._appendCommentNode(t,e.openElements.items[0])}function ih(e,t){e._appendCommentNode(t,e.document)}function pi(e,t){if(e.stopped=!0,t.location){const n=e.fragmentContext?0:2;for(let a=e.openElements.stackTop;a>=n;a--)e._setEndLocation(e.openElements.items[a],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){const a=e.openElements.items[0],i=e.treeAdapter.getNodeSourceCodeLocation(a);if(i&&!i.endTag&&(e._setEndLocation(a,t),e.openElements.stackTop>=1)){const o=e.openElements.items[1],l=e.treeAdapter.getNodeSourceCodeLocation(o);l&&!l.endTag&&e._setEndLocation(o,t)}}}}function rh(e,t){e._setDocumentType(t);const n=t.forceQuirks?xt.QUIRKS:Om(t);Pm(t)||e._err(t,G.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,n),e.insertionMode=k.BEFORE_HTML}function ws(e,t){e._err(t,G.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,xt.QUIRKS),e.insertionMode=k.BEFORE_HTML,e._processToken(t)}function oh(e,t){t.tagID===r.HTML?(e._insertElement(t,ne.HTML),e.insertionMode=k.BEFORE_HEAD):Ms(e,t)}function lh(e,t){const n=t.tagID;(n===r.HTML||n===r.HEAD||n===r.BODY||n===r.BR)&&Ms(e,t)}function Ms(e,t){e._insertFakeRootElement(),e.insertionMode=k.BEFORE_HEAD,e._processToken(t)}function ch(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.HEAD:{e._insertElement(t,ne.HTML),e.headElement=e.openElements.current,e.insertionMode=k.IN_HEAD;break}default:Bs(e,t)}}function uh(e,t){const n=t.tagID;n===r.HEAD||n===r.BODY||n===r.HTML||n===r.BR?Bs(e,t):e._err(t,G.endTagWithoutMatchingOpenElement)}function Bs(e,t){e._insertFakeElement(M.HEAD,r.HEAD),e.headElement=e.openElements.current,e.insertionMode=k.IN_HEAD,e._processToken(t)}function _t(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.BASE:case r.BASEFONT:case r.BGSOUND:case r.LINK:case r.META:{e._appendElement(t,ne.HTML),t.ackSelfClosing=!0;break}case r.TITLE:{e._switchToTextParsing(t,st.RCDATA);break}case r.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,st.RAWTEXT):(e._insertElement(t,ne.HTML),e.insertionMode=k.IN_HEAD_NO_SCRIPT);break}case r.NOFRAMES:case r.STYLE:{e._switchToTextParsing(t,st.RAWTEXT);break}case r.SCRIPT:{e._switchToTextParsing(t,st.SCRIPT_DATA);break}case r.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=!1,e.insertionMode=k.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(k.IN_TEMPLATE);break}case r.HEAD:{e._err(t,G.misplacedStartTagForHeadElement);break}default:Fs(e,t)}}function dh(e,t){switch(t.tagID){case r.HEAD:{e.openElements.pop(),e.insertionMode=k.AFTER_HEAD;break}case r.BODY:case r.BR:case r.HTML:{Fs(e,t);break}case r.TEMPLATE:{os(e,t);break}default:e._err(t,G.endTagWithoutMatchingOpenElement)}}function os(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==r.TEMPLATE&&e._err(t,G.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(r.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,G.endTagWithoutMatchingOpenElement)}function Fs(e,t){e.openElements.pop(),e.insertionMode=k.AFTER_HEAD,e._processToken(t)}function ph(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.BASEFONT:case r.BGSOUND:case r.HEAD:case r.LINK:case r.META:case r.NOFRAMES:case r.STYLE:{_t(e,t);break}case r.NOSCRIPT:{e._err(t,G.nestedNoscriptInHead);break}default:Hs(e,t)}}function mh(e,t){switch(t.tagID){case r.NOSCRIPT:{e.openElements.pop(),e.insertionMode=k.IN_HEAD;break}case r.BR:{Hs(e,t);break}default:e._err(t,G.endTagWithoutMatchingOpenElement)}}function Hs(e,t){const n=t.type===Ue.EOF?G.openElementsLeftAfterEof:G.disallowedContentInNoscriptInHead;e._err(t,n),e.openElements.pop(),e.insertionMode=k.IN_HEAD,e._processToken(t)}function hh(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.BODY:{e._insertElement(t,ne.HTML),e.framesetOk=!1,e.insertionMode=k.IN_BODY;break}case r.FRAMESET:{e._insertElement(t,ne.HTML),e.insertionMode=k.IN_FRAMESET;break}case r.BASE:case r.BASEFONT:case r.BGSOUND:case r.LINK:case r.META:case r.NOFRAMES:case r.SCRIPT:case r.STYLE:case r.TEMPLATE:case r.TITLE:{e._err(t,G.abandonedHeadElementChild),e.openElements.push(e.headElement,r.HEAD),_t(e,t),e.openElements.remove(e.headElement);break}case r.HEAD:{e._err(t,G.misplacedStartTagForHeadElement);break}default:Us(e,t)}}function fh(e,t){switch(t.tagID){case r.BODY:case r.HTML:case r.BR:{Us(e,t);break}case r.TEMPLATE:{os(e,t);break}default:e._err(t,G.endTagWithoutMatchingOpenElement)}}function Us(e,t){e._insertFakeElement(M.BODY,r.BODY),e.insertionMode=k.IN_BODY,sa(e,t)}function sa(e,t){switch(t.type){case Ue.CHARACTER:{Nl(e,t);break}case Ue.WHITESPACE_CHARACTER:{kl(e,t);break}case Ue.COMMENT:{Ka(e,t);break}case Ue.START_TAG:{ct(e,t);break}case Ue.END_TAG:{na(e,t);break}case Ue.EOF:{Sl(e,t);break}}}function kl(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function Nl(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function gh(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function bh(e,t){const n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e.openElements.tmplCount===0&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(n,t.attrs))}function Eh(e,t){const n=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&n&&(e.treeAdapter.detachNode(n),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,ne.HTML),e.insertionMode=k.IN_FRAMESET)}function Th(e,t){e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._insertElement(t,ne.HTML)}function xh(e,t){e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&Wa.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,ne.HTML)}function yh(e,t){e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._insertElement(t,ne.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function kh(e,t){const n=e.openElements.tmplCount>0;(!e.formElement||n)&&(e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._insertElement(t,ne.HTML),n||(e.formElement=e.openElements.current))}function Nh(e,t){e.framesetOk=!1;const n=t.tagID;for(let a=e.openElements.stackTop;a>=0;a--){const i=e.openElements.tagIDs[a];if(n===r.LI&&i===r.LI||(n===r.DD||n===r.DT)&&(i===r.DD||i===r.DT)){e.openElements.generateImpliedEndTagsWithExclusion(i),e.openElements.popUntilTagNamePopped(i);break}if(i!==r.ADDRESS&&i!==r.DIV&&i!==r.P&&e._isSpecialElement(e.openElements.items[a],i))break}e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._insertElement(t,ne.HTML)}function vh(e,t){e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._insertElement(t,ne.HTML),e.tokenizer.state=st.PLAINTEXT}function Ch(e,t){e.openElements.hasInScope(r.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.framesetOk=!1}function wh(e,t){const n=e.activeFormattingElements.getElementEntryInScopeWithTagName(M.A);n&&(di(e,t),e.openElements.remove(n.element),e.activeFormattingElements.removeEntry(n)),e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function Sh(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function _h(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(r.NOBR)&&(di(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,ne.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function Ah(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function Ih(e,t){e.treeAdapter.getDocumentMode(e.document)!==xt.QUIRKS&&e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._insertElement(t,ne.HTML),e.framesetOk=!1,e.insertionMode=k.IN_TABLE}function vl(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,ne.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function Cl(e){const t=ml(e,ns.TYPE);return t!=null&&t.toLowerCase()===zm}function jh(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,ne.HTML),Cl(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function Rh(e,t){e._appendElement(t,ne.HTML),t.ackSelfClosing=!0}function Lh(e,t){e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._appendElement(t,ne.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function Dh(e,t){t.tagName=M.IMG,t.tagID=r.IMG,vl(e,t)}function Ph(e,t){e._insertElement(t,ne.HTML),e.skipNextNewLine=!0,e.tokenizer.state=st.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=!1,e.insertionMode=k.TEXT}function Oh(e,t){e.openElements.hasInButtonScope(r.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,st.RAWTEXT)}function Mh(e,t){e.framesetOk=!1,e._switchToTextParsing(t,st.RAWTEXT)}function Ar(e,t){e._switchToTextParsing(t,st.RAWTEXT)}function Bh(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML),e.framesetOk=!1,e.insertionMode=e.insertionMode===k.IN_TABLE||e.insertionMode===k.IN_CAPTION||e.insertionMode===k.IN_TABLE_BODY||e.insertionMode===k.IN_ROW||e.insertionMode===k.IN_CELL?k.IN_SELECT_IN_TABLE:k.IN_SELECT}function Fh(e,t){e.openElements.currentTagId===r.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML)}function Hh(e,t){e.openElements.hasInScope(r.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,ne.HTML)}function Uh(e,t){e.openElements.hasInScope(r.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(r.RTC),e._insertElement(t,ne.HTML)}function $h(e,t){e._reconstructActiveFormattingElements(),Tl(t),ui(t),t.selfClosing?e._appendElement(t,ne.MATHML):e._insertElement(t,ne.MATHML),t.ackSelfClosing=!0}function qh(e,t){e._reconstructActiveFormattingElements(),xl(t),ui(t),t.selfClosing?e._appendElement(t,ne.SVG):e._insertElement(t,ne.SVG),t.ackSelfClosing=!0}function Ir(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ne.HTML)}function ct(e,t){switch(t.tagID){case r.I:case r.S:case r.B:case r.U:case r.EM:case r.TT:case r.BIG:case r.CODE:case r.FONT:case r.SMALL:case r.STRIKE:case r.STRONG:{Sh(e,t);break}case r.A:{wh(e,t);break}case r.H1:case r.H2:case r.H3:case r.H4:case r.H5:case r.H6:{xh(e,t);break}case r.P:case r.DL:case r.OL:case r.UL:case r.DIV:case r.DIR:case r.NAV:case r.MAIN:case r.MENU:case r.ASIDE:case r.CENTER:case r.FIGURE:case r.FOOTER:case r.HEADER:case r.HGROUP:case r.DIALOG:case r.DETAILS:case r.ADDRESS:case r.ARTICLE:case r.SEARCH:case r.SECTION:case r.SUMMARY:case r.FIELDSET:case r.BLOCKQUOTE:case r.FIGCAPTION:{Th(e,t);break}case r.LI:case r.DD:case r.DT:{Nh(e,t);break}case r.BR:case r.IMG:case r.WBR:case r.AREA:case r.EMBED:case r.KEYGEN:{vl(e,t);break}case r.HR:{Lh(e,t);break}case r.RB:case r.RTC:{Hh(e,t);break}case r.RT:case r.RP:{Uh(e,t);break}case r.PRE:case r.LISTING:{yh(e,t);break}case r.XMP:{Oh(e,t);break}case r.SVG:{qh(e,t);break}case r.HTML:{gh(e,t);break}case r.BASE:case r.LINK:case r.META:case r.STYLE:case r.TITLE:case r.SCRIPT:case r.BGSOUND:case r.BASEFONT:case r.TEMPLATE:{_t(e,t);break}case r.BODY:{bh(e,t);break}case r.FORM:{kh(e,t);break}case r.NOBR:{_h(e,t);break}case r.MATH:{$h(e,t);break}case r.TABLE:{Ih(e,t);break}case r.INPUT:{jh(e,t);break}case r.PARAM:case r.TRACK:case r.SOURCE:{Rh(e,t);break}case r.IMAGE:{Dh(e,t);break}case r.BUTTON:{Ch(e,t);break}case r.APPLET:case r.OBJECT:case r.MARQUEE:{Ah(e,t);break}case r.IFRAME:{Mh(e,t);break}case r.SELECT:{Bh(e,t);break}case r.OPTION:case r.OPTGROUP:{Fh(e,t);break}case r.NOEMBED:case r.NOFRAMES:{Ar(e,t);break}case r.FRAMESET:{Eh(e,t);break}case r.TEXTAREA:{Ph(e,t);break}case r.NOSCRIPT:{e.options.scriptingEnabled?Ar(e,t):Ir(e,t);break}case r.PLAINTEXT:{vh(e,t);break}case r.COL:case r.TH:case r.TD:case r.TR:case r.HEAD:case r.FRAME:case r.TBODY:case r.TFOOT:case r.THEAD:case r.CAPTION:case r.COLGROUP:break;default:Ir(e,t)}}function Wh(e,t){if(e.openElements.hasInScope(r.BODY)&&(e.insertionMode=k.AFTER_BODY,e.options.sourceCodeLocationInfo)){const n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e._setEndLocation(n,t)}}function Kh(e,t){e.openElements.hasInScope(r.BODY)&&(e.insertionMode=k.AFTER_BODY,Pl(e,t))}function Yh(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n))}function Gh(e){const t=e.openElements.tmplCount>0,{formElement:n}=e;t||(e.formElement=null),(n||t)&&e.openElements.hasInScope(r.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(r.FORM):n&&e.openElements.remove(n))}function zh(e){e.openElements.hasInButtonScope(r.P)||e._insertFakeElement(M.P,r.P),e._closePElement()}function Vh(e){e.openElements.hasInListItemScope(r.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(r.LI),e.openElements.popUntilTagNamePopped(r.LI))}function Qh(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n))}function Xh(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function Jh(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker())}function Zh(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(M.BR,r.BR),e.openElements.pop(),e.framesetOk=!1}function wl(e,t){const n=t.tagName,a=t.tagID;for(let i=e.openElements.stackTop;i>0;i--){const o=e.openElements.items[i],l=e.openElements.tagIDs[i];if(a===l&&(a!==r.UNKNOWN||e.treeAdapter.getTagName(o)===n)){e.openElements.generateImpliedEndTagsWithExclusion(a),e.openElements.stackTop>=i&&e.openElements.shortenToLength(i);break}if(e._isSpecialElement(o,l))break}}function na(e,t){switch(t.tagID){case r.A:case r.B:case r.I:case r.S:case r.U:case r.EM:case r.TT:case r.BIG:case r.CODE:case r.FONT:case r.NOBR:case r.SMALL:case r.STRIKE:case r.STRONG:{di(e,t);break}case r.P:{zh(e);break}case r.DL:case r.UL:case r.OL:case r.DIR:case r.DIV:case r.NAV:case r.PRE:case r.MAIN:case r.MENU:case r.ASIDE:case r.BUTTON:case r.CENTER:case r.FIGURE:case r.FOOTER:case r.HEADER:case r.HGROUP:case r.DIALOG:case r.ADDRESS:case r.ARTICLE:case r.DETAILS:case r.SEARCH:case r.SECTION:case r.SUMMARY:case r.LISTING:case r.FIELDSET:case r.BLOCKQUOTE:case r.FIGCAPTION:{Yh(e,t);break}case r.LI:{Vh(e);break}case r.DD:case r.DT:{Qh(e,t);break}case r.H1:case r.H2:case r.H3:case r.H4:case r.H5:case r.H6:{Xh(e);break}case r.BR:{Zh(e);break}case r.BODY:{Wh(e,t);break}case r.HTML:{Kh(e,t);break}case r.FORM:{Gh(e);break}case r.APPLET:case r.OBJECT:case r.MARQUEE:{Jh(e,t);break}case r.TEMPLATE:{os(e,t);break}default:wl(e,t)}}function Sl(e,t){e.tmplInsertionModeStack.length>0?Dl(e,t):pi(e,t)}function ef(e,t){var n;t.tagID===r.SCRIPT&&((n=e.scriptHandler)===null||n===void 0||n.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode}function tf(e,t){e._err(t,G.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function xa(e,t){if(e.openElements.currentTagId!==void 0&&yl.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=!1,e.originalInsertionMode=e.insertionMode,e.insertionMode=k.IN_TABLE_TEXT,t.type){case Ue.CHARACTER:{Al(e,t);break}case Ue.WHITESPACE_CHARACTER:{_l(e,t);break}}else Xs(e,t)}function sf(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,ne.HTML),e.insertionMode=k.IN_CAPTION}function nf(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,ne.HTML),e.insertionMode=k.IN_COLUMN_GROUP}function af(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(M.COLGROUP,r.COLGROUP),e.insertionMode=k.IN_COLUMN_GROUP,mi(e,t)}function rf(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,ne.HTML),e.insertionMode=k.IN_TABLE_BODY}function of(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(M.TBODY,r.TBODY),e.insertionMode=k.IN_TABLE_BODY,aa(e,t)}function lf(e,t){e.openElements.hasInTableScope(r.TABLE)&&(e.openElements.popUntilTagNamePopped(r.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function cf(e,t){Cl(t)?e._appendElement(t,ne.HTML):Xs(e,t),t.ackSelfClosing=!0}function uf(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,ne.HTML),e.formElement=e.openElements.current,e.openElements.pop())}function gs(e,t){switch(t.tagID){case r.TD:case r.TH:case r.TR:{of(e,t);break}case r.STYLE:case r.SCRIPT:case r.TEMPLATE:{_t(e,t);break}case r.COL:{af(e,t);break}case r.FORM:{uf(e,t);break}case r.TABLE:{lf(e,t);break}case r.TBODY:case r.TFOOT:case r.THEAD:{rf(e,t);break}case r.INPUT:{cf(e,t);break}case r.CAPTION:{sf(e,t);break}case r.COLGROUP:{nf(e,t);break}default:Xs(e,t)}}function zs(e,t){switch(t.tagID){case r.TABLE:{e.openElements.hasInTableScope(r.TABLE)&&(e.openElements.popUntilTagNamePopped(r.TABLE),e._resetInsertionMode());break}case r.TEMPLATE:{os(e,t);break}case r.BODY:case r.CAPTION:case r.COL:case r.COLGROUP:case r.HTML:case r.TBODY:case r.TD:case r.TFOOT:case r.TH:case r.THEAD:case r.TR:break;default:Xs(e,t)}}function Xs(e,t){const n=e.fosterParentingEnabled;e.fosterParentingEnabled=!0,sa(e,t),e.fosterParentingEnabled=n}function _l(e,t){e.pendingCharacterTokens.push(t)}function Al(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=!0}function Ss(e,t){let n=0;if(e.hasNonWhitespacePendingCharacterToken)for(;n<e.pendingCharacterTokens.length;n++)Xs(e,e.pendingCharacterTokens[n]);else for(;n<e.pendingCharacterTokens.length;n++)e._insertCharacters(e.pendingCharacterTokens[n]);e.insertionMode=e.originalInsertionMode,e._processToken(t)}const Il=new Set([r.CAPTION,r.COL,r.COLGROUP,r.TBODY,r.TD,r.TFOOT,r.TH,r.THEAD,r.TR]);function df(e,t){const n=t.tagID;Il.has(n)?e.openElements.hasInTableScope(r.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=k.IN_TABLE,gs(e,t)):ct(e,t)}function pf(e,t){const n=t.tagID;switch(n){case r.CAPTION:case r.TABLE:{e.openElements.hasInTableScope(r.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=k.IN_TABLE,n===r.TABLE&&zs(e,t));break}case r.BODY:case r.COL:case r.COLGROUP:case r.HTML:case r.TBODY:case r.TD:case r.TFOOT:case r.TH:case r.THEAD:case r.TR:break;default:na(e,t)}}function mi(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.COL:{e._appendElement(t,ne.HTML),t.ackSelfClosing=!0;break}case r.TEMPLATE:{_t(e,t);break}default:Un(e,t)}}function mf(e,t){switch(t.tagID){case r.COLGROUP:{e.openElements.currentTagId===r.COLGROUP&&(e.openElements.pop(),e.insertionMode=k.IN_TABLE);break}case r.TEMPLATE:{os(e,t);break}case r.COL:break;default:Un(e,t)}}function Un(e,t){e.openElements.currentTagId===r.COLGROUP&&(e.openElements.pop(),e.insertionMode=k.IN_TABLE,e._processToken(t))}function aa(e,t){switch(t.tagID){case r.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,ne.HTML),e.insertionMode=k.IN_ROW;break}case r.TH:case r.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(M.TR,r.TR),e.insertionMode=k.IN_ROW,ia(e,t);break}case r.CAPTION:case r.COL:case r.COLGROUP:case r.TBODY:case r.TFOOT:case r.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=k.IN_TABLE,gs(e,t));break}default:gs(e,t)}}function Ya(e,t){const n=t.tagID;switch(t.tagID){case r.TBODY:case r.TFOOT:case r.THEAD:{e.openElements.hasInTableScope(n)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=k.IN_TABLE);break}case r.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=k.IN_TABLE,zs(e,t));break}case r.BODY:case r.CAPTION:case r.COL:case r.COLGROUP:case r.HTML:case r.TD:case r.TH:case r.TR:break;default:zs(e,t)}}function ia(e,t){switch(t.tagID){case r.TH:case r.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,ne.HTML),e.insertionMode=k.IN_CELL,e.activeFormattingElements.insertMarker();break}case r.CAPTION:case r.COL:case r.COLGROUP:case r.TBODY:case r.TFOOT:case r.THEAD:case r.TR:{e.openElements.hasInTableScope(r.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=k.IN_TABLE_BODY,aa(e,t));break}default:gs(e,t)}}function jl(e,t){switch(t.tagID){case r.TR:{e.openElements.hasInTableScope(r.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=k.IN_TABLE_BODY);break}case r.TABLE:{e.openElements.hasInTableScope(r.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=k.IN_TABLE_BODY,Ya(e,t));break}case r.TBODY:case r.TFOOT:case r.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(r.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=k.IN_TABLE_BODY,Ya(e,t));break}case r.BODY:case r.CAPTION:case r.COL:case r.COLGROUP:case r.HTML:case r.TD:case r.TH:break;default:zs(e,t)}}function hf(e,t){const n=t.tagID;Il.has(n)?(e.openElements.hasInTableScope(r.TD)||e.openElements.hasInTableScope(r.TH))&&(e._closeTableCell(),ia(e,t)):ct(e,t)}function ff(e,t){const n=t.tagID;switch(n){case r.TD:case r.TH:{e.openElements.hasInTableScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=k.IN_ROW);break}case r.TABLE:case r.TBODY:case r.TFOOT:case r.THEAD:case r.TR:{e.openElements.hasInTableScope(n)&&(e._closeTableCell(),jl(e,t));break}case r.BODY:case r.CAPTION:case r.COL:case r.COLGROUP:case r.HTML:break;default:na(e,t)}}function Rl(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.OPTION:{e.openElements.currentTagId===r.OPTION&&e.openElements.pop(),e._insertElement(t,ne.HTML);break}case r.OPTGROUP:{e.openElements.currentTagId===r.OPTION&&e.openElements.pop(),e.openElements.currentTagId===r.OPTGROUP&&e.openElements.pop(),e._insertElement(t,ne.HTML);break}case r.HR:{e.openElements.currentTagId===r.OPTION&&e.openElements.pop(),e.openElements.currentTagId===r.OPTGROUP&&e.openElements.pop(),e._appendElement(t,ne.HTML),t.ackSelfClosing=!0;break}case r.INPUT:case r.KEYGEN:case r.TEXTAREA:case r.SELECT:{e.openElements.hasInSelectScope(r.SELECT)&&(e.openElements.popUntilTagNamePopped(r.SELECT),e._resetInsertionMode(),t.tagID!==r.SELECT&&e._processStartTag(t));break}case r.SCRIPT:case r.TEMPLATE:{_t(e,t);break}}}function Ll(e,t){switch(t.tagID){case r.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===r.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===r.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===r.OPTGROUP&&e.openElements.pop();break}case r.OPTION:{e.openElements.currentTagId===r.OPTION&&e.openElements.pop();break}case r.SELECT:{e.openElements.hasInSelectScope(r.SELECT)&&(e.openElements.popUntilTagNamePopped(r.SELECT),e._resetInsertionMode());break}case r.TEMPLATE:{os(e,t);break}}}function gf(e,t){const n=t.tagID;n===r.CAPTION||n===r.TABLE||n===r.TBODY||n===r.TFOOT||n===r.THEAD||n===r.TR||n===r.TD||n===r.TH?(e.openElements.popUntilTagNamePopped(r.SELECT),e._resetInsertionMode(),e._processStartTag(t)):Rl(e,t)}function bf(e,t){const n=t.tagID;n===r.CAPTION||n===r.TABLE||n===r.TBODY||n===r.TFOOT||n===r.THEAD||n===r.TR||n===r.TD||n===r.TH?e.openElements.hasInTableScope(n)&&(e.openElements.popUntilTagNamePopped(r.SELECT),e._resetInsertionMode(),e.onEndTag(t)):Ll(e,t)}function Ef(e,t){switch(t.tagID){case r.BASE:case r.BASEFONT:case r.BGSOUND:case r.LINK:case r.META:case r.NOFRAMES:case r.SCRIPT:case r.STYLE:case r.TEMPLATE:case r.TITLE:{_t(e,t);break}case r.CAPTION:case r.COLGROUP:case r.TBODY:case r.TFOOT:case r.THEAD:{e.tmplInsertionModeStack[0]=k.IN_TABLE,e.insertionMode=k.IN_TABLE,gs(e,t);break}case r.COL:{e.tmplInsertionModeStack[0]=k.IN_COLUMN_GROUP,e.insertionMode=k.IN_COLUMN_GROUP,mi(e,t);break}case r.TR:{e.tmplInsertionModeStack[0]=k.IN_TABLE_BODY,e.insertionMode=k.IN_TABLE_BODY,aa(e,t);break}case r.TD:case r.TH:{e.tmplInsertionModeStack[0]=k.IN_ROW,e.insertionMode=k.IN_ROW,ia(e,t);break}default:e.tmplInsertionModeStack[0]=k.IN_BODY,e.insertionMode=k.IN_BODY,ct(e,t)}}function Tf(e,t){t.tagID===r.TEMPLATE&&os(e,t)}function Dl(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(r.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):pi(e,t)}function xf(e,t){t.tagID===r.HTML?ct(e,t):$n(e,t)}function Pl(e,t){var n;if(t.tagID===r.HTML){if(e.fragmentContext||(e.insertionMode=k.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===r.HTML){e._setEndLocation(e.openElements.items[0],t);const a=e.openElements.items[1];a&&!(!((n=e.treeAdapter.getNodeSourceCodeLocation(a))===null||n===void 0)&&n.endTag)&&e._setEndLocation(a,t)}}else $n(e,t)}function $n(e,t){e.insertionMode=k.IN_BODY,sa(e,t)}function yf(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.FRAMESET:{e._insertElement(t,ne.HTML);break}case r.FRAME:{e._appendElement(t,ne.HTML),t.ackSelfClosing=!0;break}case r.NOFRAMES:{_t(e,t);break}}}function kf(e,t){t.tagID===r.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==r.FRAMESET&&(e.insertionMode=k.AFTER_FRAMESET))}function Nf(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.NOFRAMES:{_t(e,t);break}}}function vf(e,t){t.tagID===r.HTML&&(e.insertionMode=k.AFTER_AFTER_FRAMESET)}function Cf(e,t){t.tagID===r.HTML?ct(e,t):yn(e,t)}function yn(e,t){e.insertionMode=k.IN_BODY,sa(e,t)}function wf(e,t){switch(t.tagID){case r.HTML:{ct(e,t);break}case r.NOFRAMES:{_t(e,t);break}}}function Sf(e,t){t.chars=et,e._insertCharacters(t)}function _f(e,t){e._insertCharacters(t),e.framesetOk=!1}function Ol(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==ne.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop()}function Af(e,t){if(qm(t))Ol(e),e._startTagOutsideForeignContent(t);else{const n=e._getAdjustedCurrentElement(),a=e.treeAdapter.getNamespaceURI(n);a===ne.MATHML?Tl(t):a===ne.SVG&&(Wm(t),xl(t)),ui(t),t.selfClosing?e._appendElement(t,a):e._insertElement(t,a),t.ackSelfClosing=!0}}function If(e,t){if(t.tagID===r.P||t.tagID===r.BR){Ol(e),e._endTagOutsideForeignContent(t);return}for(let n=e.openElements.stackTop;n>0;n--){const a=e.openElements.items[n];if(e.treeAdapter.getNamespaceURI(a)===ne.HTML){e._endTagOutsideForeignContent(t);break}const i=e.treeAdapter.getTagName(a);if(i.toLowerCase()===t.tagName){t.tagName=i,e.openElements.shortenToLength(n);break}}}M.AREA,M.BASE,M.BASEFONT,M.BGSOUND,M.BR,M.COL,M.EMBED,M.FRAME,M.HR,M.IMG,M.INPUT,M.KEYGEN,M.LINK,M.META,M.PARAM,M.SOURCE,M.TRACK,M.WBR;const jf=/<(\/?)(iframe|noembed|noframes|plaintext|script|style|textarea|title|xmp)(?=[\t\n\f\r />])/gi,Rf=new Set(["mdxFlowExpression","mdxJsxFlowElement","mdxJsxTextElement","mdxTextExpression","mdxjsEsm"]),jr={sourceCodeLocationInfo:!0,scriptingEnabled:!1};function Ml(e,t){const n=$f(e),a=go("type",{handlers:{root:Lf,element:Df,text:Pf,comment:Fl,doctype:Of,raw:Bf},unknown:Ff}),i={parser:n?new _r(jr):_r.getFragmentParser(void 0,jr),handle(u){a(u,i)},stitches:!1,options:t||{}};a(e,i),xs(i,is());const o=n?i.parser.document:i.parser.getFragment(),l=$p(o,{file:i.options.file});return i.stitches&&ru(l,"comment",function(u,p,h){const b=u;if(b.value.stitch&&h&&p!==void 0){const m=h.children;return m[p]=b.value.stitch,p}}),l.type==="root"&&l.children.length===1&&l.children[0].type===e.type?l.children[0]:l}function Bl(e,t){let n=-1;if(e)for(;++n<e.length;)t.handle(e[n])}function Lf(e,t){Bl(e.children,t)}function Df(e,t){Hf(e,t),Bl(e.children,t),Uf(e,t)}function Pf(e,t){t.parser.tokenizer.state>4&&(t.parser.tokenizer.state=0);const n={type:Ue.CHARACTER,chars:e.value,location:Js(e)};xs(t,is(e)),t.parser.currentToken=n,t.parser._processToken(t.parser.currentToken)}function Of(e,t){const n={type:Ue.DOCTYPE,name:"html",forceQuirks:!1,publicId:"",systemId:"",location:Js(e)};xs(t,is(e)),t.parser.currentToken=n,t.parser._processToken(t.parser.currentToken)}function Mf(e,t){t.stitches=!0;const n=qf(e);if("children"in e&&"children"in n){const a=Ml({type:"root",children:e.children},t.options);n.children=a.children}Fl({type:"comment",value:{stitch:n}},t)}function Fl(e,t){const n=e.value,a={type:Ue.COMMENT,data:n,location:Js(e)};xs(t,is(e)),t.parser.currentToken=a,t.parser._processToken(t.parser.currentToken)}function Bf(e,t){if(t.parser.tokenizer.preprocessor.html="",t.parser.tokenizer.preprocessor.pos=-1,t.parser.tokenizer.preprocessor.lastGapPos=-2,t.parser.tokenizer.preprocessor.gapStack=[],t.parser.tokenizer.preprocessor.skipNextNewLine=!1,t.parser.tokenizer.preprocessor.lastChunkWritten=!1,t.parser.tokenizer.preprocessor.endOfChunkHit=!1,t.parser.tokenizer.preprocessor.isEol=!1,Hl(t,is(e)),t.parser.tokenizer.write(t.options.tagfilter?e.value.replace(jf,"&lt;$1$2"):e.value,!1),t.parser.tokenizer._runParsingLoop(),t.parser.tokenizer.state===72||t.parser.tokenizer.state===78){t.parser.tokenizer.preprocessor.lastChunkWritten=!0;const n=t.parser.tokenizer._consume();t.parser.tokenizer._callState(n)}}function Ff(e,t){const n=e;if(t.options.passThrough&&t.options.passThrough.includes(n.type))Mf(n,t);else{let a="";throw Rf.has(n.type)&&(a=". It looks like you are using MDX nodes with `hast-util-raw` (or `rehype-raw`). If you use this because you are using remark or rehype plugins that inject `'html'` nodes, then please raise an issue with that plugin, as its a bad and slow idea. If you use this because you are using markdown syntax, then you have to configure this utility (or plugin) to pass through these nodes (see `passThrough` in docs), but you can also migrate to use the MDX syntax"),new Error("Cannot compile `"+n.type+"` node"+a)}}function xs(e,t){Hl(e,t);const n=e.parser.tokenizer.currentCharacterToken;n&&n.location&&(n.location.endLine=e.parser.tokenizer.preprocessor.line,n.location.endCol=e.parser.tokenizer.preprocessor.col+1,n.location.endOffset=e.parser.tokenizer.preprocessor.offset+1,e.parser.currentToken=n,e.parser._processToken(e.parser.currentToken)),e.parser.tokenizer.paused=!1,e.parser.tokenizer.inLoop=!1,e.parser.tokenizer.active=!1,e.parser.tokenizer.returnState=st.DATA,e.parser.tokenizer.charRefCode=-1,e.parser.tokenizer.consumedAfterSnapshot=-1,e.parser.tokenizer.currentLocation=null,e.parser.tokenizer.currentCharacterToken=null,e.parser.tokenizer.currentToken=null,e.parser.tokenizer.currentAttr={name:"",value:""}}function Hl(e,t){if(t&&t.offset!==void 0){const n={startLine:t.line,startCol:t.column,startOffset:t.offset,endLine:-1,endCol:-1,endOffset:-1};e.parser.tokenizer.preprocessor.lineStartPos=-t.column+1,e.parser.tokenizer.preprocessor.droppedBufferSize=t.offset,e.parser.tokenizer.preprocessor.line=t.line,e.parser.tokenizer.currentLocation=n}}function Hf(e,t){const n=e.tagName.toLowerCase();if(t.parser.tokenizer.state===st.PLAINTEXT)return;xs(t,is(e));const a=t.parser.openElements.current;let i="namespaceURI"in a?a.namespaceURI:Xt.html;i===Xt.html&&n==="svg"&&(i=Xt.svg);const o=Gp({...e,children:[]},{space:i===Xt.svg?"svg":"html"}),l={type:Ue.START_TAG,tagName:n,tagID:Ts(n),selfClosing:!1,ackSelfClosing:!1,attrs:"attrs"in o?o.attrs:[],location:Js(e)};t.parser.currentToken=l,t.parser._processToken(t.parser.currentToken),t.parser.tokenizer.lastStartTagName=n}function Uf(e,t){const n=e.tagName.toLowerCase();if(!t.parser.tokenizer.inForeignNode&&tm.includes(n)||t.parser.tokenizer.state===st.PLAINTEXT)return;xs(t,bo(e));const a={type:Ue.END_TAG,tagName:n,tagID:Ts(n),selfClosing:!1,ackSelfClosing:!1,attrs:[],location:Js(e)};t.parser.currentToken=a,t.parser._processToken(t.parser.currentToken),n===t.parser.tokenizer.lastStartTagName&&(t.parser.tokenizer.state===st.RCDATA||t.parser.tokenizer.state===st.RAWTEXT||t.parser.tokenizer.state===st.SCRIPT_DATA)&&(t.parser.tokenizer.state=st.DATA)}function $f(e){const t=e.type==="root"?e.children[0]:e;return!!(t&&(t.type==="doctype"||t.type==="element"&&t.tagName.toLowerCase()==="html"))}function Js(e){const t=is(e)||{line:void 0,column:void 0,offset:void 0},n=bo(e)||{line:void 0,column:void 0,offset:void 0};return{startLine:t.line,startCol:t.column,startOffset:t.offset,endLine:n.line,endCol:n.column,endOffset:n.offset}}function qf(e){return"children"in e?vi({...e,children:[]}):vi(e)}function Wf(e){return function(t,n){return Ml(t,{...e,file:n})}}const qn=c.memo(function({text:t}){const n=Pe(),[a,i]=c.useState(!1);return t?s.jsx("button",{type:"button",className:"copy-btn",title:n("copy"),onClick:()=>{navigator.clipboard.writeText(t).then(()=>{i(!0),setTimeout(()=>i(!1),1200)})},children:a?s.jsx(Rt,{}):s.jsx(Lt,{})}):null});function Kf(e){const t=a=>{if(typeof a=="string"||typeof a=="number"){const i=String(a);return i===""?[[]]:i.split(`
322
+ `).map(o=>o===""?[]:[o])}if(Array.isArray(a)){let i=[];for(const o of a){const l=t(o);if(i.length===0)i=l;else{const u=l[0]??[];i[i.length-1].push(...u),i.push(...l.slice(1))}}return i}if(a&&typeof a=="object"&&"props"in a){const i=a,o=i.props?.children,l={...i.props,children:void 0},u=o==null?[]:t(o);return u.length===0?[[c.createElement(i.type,l)]]:u.map(p=>[c.createElement(i.type,l,...p)])}return[[a]]},n=t(e);return n.length>1&&n[n.length-1].length===0&&n.pop(),n}function Ga(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Ga).join("");if(e&&typeof e=="object"&&"props"in e){const t=e.props;return Ga(t?.children)}return""}function Yf(e){const t=Array.isArray(e)?e[0]:e;return!t||typeof t!="object"||!("props"in t)?null:t}function Gf(e){const n=Yf(e)?.props?.className;if(typeof n!="string")return null;const a=n.match(/(?:^|\s)language-([A-Za-z0-9_+\-]+)(?:\s|$)/);return a?a[1]:null}const Rr="pi-web-ui:plugin-data";let $s=new Map,qs=new Map,fs=new Set,za=-1,Ul=0;const Va=new Set;function zf(){Ul++;for(const e of Va)e()}function Vf(e){return Va.add(e),()=>{Va.delete(e)}}function Lr(){return Ul}let $l=null;function Qf(e){$l=e}function Xf(e,t){t!==za&&(za=t,qs.clear(),fs.clear());const n=new Map;for(const i of e)if(!(i.error||!i.renderers))for(const o of i.renderers)n.has(o)||n.set(o,i.id);let a=n.size!==$s.size;if(!a){for(const[i,o]of n)if($s.get(i)!==o){a=!0;break}}if(a){for(const i of qs.keys())n.has(i)||qs.delete(i);for(const i of fs)n.has(i)||fs.delete(i);$s=n,zf()}}async function Jf(e,t){const n=$s.get(e);if(!n)return null;let a=qs.get(e);if(!a&&!fs.has(e))try{const l=(await import(lt(`/plugins/${encodeURIComponent(n)}/client/entry.mjs?e=${za}`))).default?.renderers?.[e];typeof l=="function"?(a={pluginId:n,renderer:l},qs.set(e,a)):(fs.add(e),console.error(`[plugin:${n}] entry.mjs 未提供 renderers["${e}"]`))}catch(o){fs.add(e),console.error(`[plugin:${n}] renderer 加载失败(${e}):`,o)}if(!a)return null;const i={pluginId:a.pluginId,send:o=>{$l?.({type:"plugin_message",pluginId:a.pluginId,payload:o})},onData:o=>{const l=u=>{const p=u.detail;p.pluginId===a.pluginId&&o(p.payload)};return window.addEventListener(Rr,l),()=>window.removeEventListener(Rr,l)}};try{const o=await a.renderer(t,i);return o instanceof HTMLElement?o:null}catch(o){return console.error(`[plugin:${a.pluginId}] renderer("${e}") 执行失败:`,o),null}}function Zf(e){return $s.has(e)}const Qa="pi-web-ui:theme",ql="dark",Dr="theme-stylesheet",zt="pi-web-ui:theme-change";function Wl(){try{const e=localStorage.getItem(Qa);if(e&&e!==ql)return e}catch{}return null}function e0(e){try{e?localStorage.setItem(Qa,e):localStorage.removeItem(Qa)}catch{}}function Kl(e){let t=document.getElementById(Dr);if(!e){t?.remove(),window.dispatchEvent(new CustomEvent(zt));return}t||(t=document.createElement("link"),t.id=Dr,t.rel="stylesheet",document.head.appendChild(t)),t.href=lt(`/themes/${encodeURIComponent(e)}.css`),t.onload=()=>window.dispatchEvent(new CustomEvent(zt))}async function Pr(){try{const e=await fetch(Ft(lt("/api/themes")));if(!e.ok)return[];const t=await e.json();return Array.isArray(t.themes)?t.themes:[]}catch{return[]}}function t0(){const[e,t]=c.useState([]),[n,a]=c.useState(()=>Wl());c.useEffect(()=>{let l=!1;return Pr().then(u=>{l||t(u)}),()=>{l=!0}},[]);const i=c.useCallback(()=>{Pr().then(t)},[]);return c.useEffect(()=>{Kl(n),e0(n)},[n]),{themes:e,theme:n,switchTheme:l=>a(l===ql?null:l),reloadThemes:i}}function f1(){const e=getComputedStyle(document.documentElement),t=(n,a)=>e.getPropertyValue(n).trim()||a;return{background:t("--term-bg","#0b0d12"),foreground:t("--term-fg","#e6e8ef"),cursor:t("--term-cursor","#8b5cf6"),cursorAccent:t("--term-cursor-accent","#0b0d12"),selectionBackground:t("--term-selection","rgba(139, 92, 246, 0.35)"),black:t("--term-black","#1a1d26"),red:t("--term-red","#f87171"),green:t("--term-green","#34d399"),yellow:t("--term-yellow","#fbbf24"),blue:t("--term-blue","#60a5fa"),magenta:t("--term-magenta","#c084fc"),cyan:t("--term-cyan","#22d3ee"),white:t("--term-white","#e6e8ef"),brightBlack:t("--term-bright-black","#6b7284"),brightRed:t("--term-bright-red","#f87171"),brightGreen:t("--term-bright-green","#34d399"),brightYellow:t("--term-bright-yellow","#fbbf24"),brightBlue:t("--term-bright-blue","#60a5fa"),brightMagenta:t("--term-bright-magenta","#c084fc"),brightCyan:t("--term-bright-cyan","#22d3ee"),brightWhite:t("--term-bright-white","#ffffff")}}function s0({lang:e,code:t}){const n=c.useRef(null),a=c.useRef(null),i=c.useRef(0),o=c.useRef(new WeakMap),[l,u]=c.useState(null);return c.useEffect(()=>{const p=()=>{const h=++i.current,b=a.current;b&&(b.dispatchEvent(new CustomEvent(zt)),o.current.set(b,h))};return window.addEventListener(zt,p),()=>window.removeEventListener(zt,p)},[]),c.useEffect(()=>{let p=!1;const h=i.current;return u(null),Jf(e,t).then(b=>{p||(b&&o.current.set(b,h),u(b))}),()=>{p=!0}},[e,t]),c.useEffect(()=>{a.current=l;const p=n.current;return p&&(p.replaceChildren(),l&&(p.appendChild(l),(o.current.get(l)??i.current)<i.current&&(l.dispatchEvent(new CustomEvent(zt)),o.current.set(l,i.current)))),()=>{a.current===l&&(a.current=null)}},[l]),l?s.jsx("div",{className:"plugin-fence",ref:n}):s.jsxs("div",{className:"codeblock",children:[s.jsx(qn,{text:t}),s.jsx("pre",{children:s.jsx("code",{children:t})})]})}const n0=[Eo,To],a0=[Eo,Fp,To],Or=[[lu,{strict:!1,throwOnError:!1}],[cu,{detect:!0,ignoreMissing:!0}]];function hi({text:e,rawHtml:t=!1,hardBreaks:n=!1}){const a=t?[Wf,...Or]:Or;return s.jsx(ou,{remarkPlugins:n?a0:n0,rehypePlugins:a,components:{pre:r0,a:i0},children:e})}const pt=c.memo(function({text:t,rawHtml:n=!1,hardBreaks:a=!1}){return s.jsx("div",{className:"md",children:s.jsx(hi,{text:t,rawHtml:n,hardBreaks:a})})});function i0({href:e,children:t,...n}){const a=String(e??"");return/^(https?:|mailto:|tel:)/i.test(a)?s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",...n,children:t}):s.jsx("a",{href:e,...n,children:t})}function r0({children:e,...t}){c.useSyncExternalStore(Vf,Lr,Lr);const n=Gf(e);return n&&Zf(n)?s.jsx(s0,{lang:n,code:Ga(e)}):s.jsx(o0,{children:e,...t})}function o0({children:e,...t}){const n=e&&typeof e=="object"&&"props"in e?e.props?.children:e,a=Kf(n),i=a.length>1,o=i?`${String(a.length).length+1}ch`:void 0;return s.jsxs("div",{className:"codeblock",children:[s.jsx(qn,{text:Xa(e)}),s.jsx("pre",{...t,children:a.map((l,u)=>s.jsxs("div",{className:"code-line",children:[i&&s.jsx("span",{className:"code-num",style:o?{width:o}:void 0,children:u+1}),s.jsx("code",{className:"code-line-body hljs",children:l})]},u))})]})}function Xa(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Xa).join("");if(e&&typeof e=="object"&&"props"in e){const t=e.props;return Xa(t?.children)}return""}const l0=/^\s{0,3}(`{3,}|~{3,})/,c0=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function ya(e){return e.trim()===""}function Mr(e){const t=l0.exec(e);return t?t[1]:null}function u0(e){const t=e.split(`
323
+ `),n=[];let a=[],i=null;for(let o=0;o<t.length;o++){const l=t[o];if(i!==null){const p=Mr(l);p&&p[0]===i[0]&&p.length>=i.length&&(i=null),a.push(l);continue}const u=Mr(l);if(u&&!ya(l)){i=u,a.push(l);continue}if(ya(l)){let p=o;for(;p<t.length&&ya(t[p]);)p++;if(!(p<t.length&&c0.test(t[p]))&&a.length>0){n.push(a.join(`
324
324
  `)),a=[];continue}a.push(l);continue}a.push(l)}return{frozen:n,active:a.join(`
325
- `),inFence:i!==null}}const d0=c.memo(function({text:t}){return s.jsx(mi,{text:t})}),Or=200;function p0({text:e,inFence:t}){const[n,a]=c.useState(e),i=c.useRef(0),o=c.useRef(null);return c.useEffect(()=>{if(t)return;const l=Date.now()-i.current,u=()=>{i.current=Date.now(),a(e)};if(l>=Or){u();return}return o.current=setTimeout(u,Or-l),()=>{o.current&&clearTimeout(o.current)}},[e,t]),t?s.jsx("div",{className:"codeblock",children:s.jsx("pre",{children:s.jsx("code",{children:e})})}):s.jsx(mi,{text:n})}const m0=c.memo(function({text:t}){const{frozen:n,active:a,inFence:i}=c.useMemo(()=>u0(t),[t]);return s.jsxs("div",{className:"md",children:[n.map((o,l)=>s.jsx(d0,{text:o},l)),a.length>0&&s.jsx(p0,{text:a,inFence:i},n.length)]})});function h0({thinking:e,streaming:t,wrap:n=!0,forceOpen:a=!1}){const i=Me(),[o,l]=c.useState(null),u=o??n,p=u||a,h=t?e.trimEnd().slice(-80):e.split(`
326
- `)[0].slice(0,80),[b,m]=c.useState(!1),f=()=>{navigator.clipboard.writeText(e),m(!0),window.setTimeout(()=>m(!1),1200)};return s.jsxs("div",{className:`thinking ${p?"open":""} ${t?"live":""}`,children:[s.jsxs("div",{className:"chead thinking-head",role:"button",tabIndex:0,"aria-expanded":p,title:i(p?"collapseMsg":"expandMsg"),onClick:()=>l(!u),onKeyDown:x=>{x.target===x.currentTarget&&(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l(!u))},children:[s.jsx("button",{type:"button",className:"chead-toggle thinking-toggle",title:i(p?"collapseMsg":"expandMsg"),"aria-label":i(p?"collapseMsg":"expandMsg"),"aria-expanded":p,onClick:x=>{x.stopPropagation(),l(!u)},children:p?s.jsx(Vt,{}):s.jsx(rs,{})}),s.jsx("span",{className:"chead-icon thinking-icon",children:s.jsx(Gs,{})}),s.jsx("span",{className:"chead-title thinking-label",children:t&&p?s.jsxs("span",{className:"thinking-live-label",children:[i("thinkingNow"),s.jsx("span",{className:"dots"})]}):p?i("thinking"):i("thinkingPreview",{preview:h})}),s.jsx("button",{type:"button",className:"chead-copy toolcall-copy thinking-copy",title:i(b?"copied":"copyMessage"),"aria-label":i("copyMessage"),onClick:x=>{x.stopPropagation(),f()},children:b?s.jsx(Es,{}):s.jsx(Dt,{})})]}),p&&s.jsx("div",{className:"thinking-body",children:e})]})}const Un=256*1024,$n=300,f0=/"(path|file_path|filePath|filename|file)"\s*:\s*"((?:[^"\\\n]|\\.){0,4000})"/,g0=/"agent"\s*:\s*"((?:[^"\\\n]|\\.){0,200})"/,b0=/"(timeout|timeoutSeconds|timeout_seconds|timeoutSec|timeoutMs|timeout_ms|timeoutMilliseconds)"\s*:\s*(-?\d+(?:\.\d+)?)(?![0-9eE.])/,E0=1e9;function T0(e){if(!e)return{};const t=e.length>Un?e.slice(0,Un):e;return{path:v0(t),timeout:C0(t),command:w0(e),agent:x0(t)}}function x0(e){const t=g0.exec(e);if(!t)return;const n=t[1].replace(/[\u0000-\u001f\u007f]/g,"").trim();if(n)return n.length>$n?`${n.slice(0,$n)}…`:n}const y0=["task","expected_outcome","required_tools","must_do","must_not_do","context"];function k0(e){if(!e||e.length>Un)return{};try{const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return{};const n=t,a={};for(const i of[...y0,"agent","model"])typeof n[i]=="string"&&n[i].trim()&&(a[i]=n[i]);return a}catch{return{}}}function N0(e,t=56){if(e.length<=t)return e;const n=e.split(/[\\/]+/).filter(Boolean),a=n[n.length-1];if(!a||n.length<=1)return`…${e.slice(-(t-1))}`;let i=a;for(let o=n.length-2;o>=0;o--){const l=`${n[o]}/${i}`;if(l.length+2>t)break;i=l}return`…/${i}`}function v0(e){const t=f0.exec(e);if(!t)return;const a=S0(t[2]).replace(/[\u0000-\u001f\u007f]/g," ").replace(/\s+/g," ").trim();if(a)return a.length>$n?`${a.slice(0,$n-1)}…`:a}function C0(e){const t=b0.exec(e);if(!t)return;const n=Number(t[2]);if(!Number.isFinite(n)||n<=0||n>E0)return;const a=t[1].toLowerCase();return!a.endsWith("ms")&&!a.endsWith("milliseconds")?`${n}s`:n<1e3?`${n}ms`:`${Math.round(n/100)/10}s`}function w0(e){if(!(e.length>Un))try{const t=JSON.parse(e);return!t||typeof t!="object"||Array.isArray(t)?void 0:typeof t.command=="string"&&t.command.trim()?t.command:void 0}catch{return}}function S0(e){try{const t=JSON.parse(`"${e}"`);return typeof t=="string"?t:e}catch{return e}}const _0={bash:"$",delegate_task:"◈",read:"📄",write:"✍️",edit:"✏️",edit_soft:"✏️",grep:"🔍",find:"🧭",ls:"📂"};function A0(e){return _0[e]??"🛠"}const I0=c.memo(function({block:t,view:n,onKillBash:a,wrap:i=!0,forceOpen:o=!1}){const l=Me(),[u,p]=c.useState(null),h=u??i,b=h||o,[m,f]=c.useState(!1),x=!n.result&&n.streaming&&!n.status,v=t.name==="bash"&&x,N=n.result!==void 0,B=!n.result&&!!n.status,X=n.result?.isError??n.status?.isError??!1,K=n.result?n.result.content.map(G=>G.type==="text"?G.text:"").join(""):n.liveOutput??"",A=K.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(G,D)=>l("liveOutputOmitted",{n:D})),R=t.name==="delegate_task",I=R?k0(t.argumentsText):{},$=R&&n.result&&typeof n.result.details=="object"&&n.result.details!==null?n.result.details.convId:void 0,ce=typeof $=="string"&&$?$:/sa-[0-9a-f]{8}/.exec(K)?.[0],ge=X?"err":N?"ok":x||B?"run":"idle";let q=l(X?"error":N?"done":x?"running":B?"toolDoneWaitingModel":"toolQueued");const Y=B&&n.status?.durationMs!==void 0?D0(n.status.durationMs):"";B&&Y&&(q=`${q} · ${Y}`);const J=B&&n.status?.exitCode!==void 0?`exit ${n.status.exitCode}`:"",j=T0(t.argumentsText),F=t.name==="bash"?j.command:void 0,T=!b&&F?L0(F):void 0,U=()=>{t.argumentsText&&(navigator.clipboard.writeText(t.argumentsText),f(!0),setTimeout(()=>f(!1),1200))};return s.jsxs("div",{className:`toolcall ${ge}`,children:[s.jsxs("div",{className:"chead toolcall-head",role:"button",tabIndex:0,"aria-expanded":b,title:l(b?"collapseMsg":"expandMsg"),onClick:()=>p(!h),onKeyDown:G=>{G.target===G.currentTarget&&(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),p(!h))},children:[s.jsx("button",{type:"button",className:"chead-toggle toolcall-toggle",title:l(b?"collapseMsg":"expandMsg"),"aria-label":l(b?"collapseMsg":"expandMsg"),"aria-expanded":b,onClick:G=>{G.stopPropagation(),p(!h)},children:b?s.jsx(Vt,{}):s.jsx(rs,{})}),s.jsx("span",{className:"chead-icon toolcall-icon",children:A0(t.name)}),s.jsx("span",{className:"chead-title toolcall-name",children:t.name}),s.jsx("span",{className:"toolcall-status",title:J?`${q} · ${J}`:q,"aria-label":J?`${q} · ${J}`:q,children:X?s.jsx(tt,{}):N?s.jsx(Lt,{}):x?s.jsx(Pu,{}):B?s.jsx(ja,{}):s.jsx(Au,{})}),T&&s.jsxs("span",{className:"toolcall-cmd",title:F,children:["$ ",T]}),j.path&&s.jsx("span",{className:"toolcall-path",title:j.path,children:N0(j.path)}),j.timeout&&s.jsxs("span",{className:"toolcall-timeout",children:["⏱ ",j.timeout]}),R&&j.agent&&s.jsxs("span",{className:"toolcall-agent",title:j.agent,children:["◈ ",j.agent]}),s.jsx("span",{className:"toolcall-spacer"}),v&&a&&s.jsxs("button",{type:"button",className:"toolcall-kill",title:l("stopBashTip"),onClick:G=>{G.stopPropagation(),a?.()},children:[s.jsx(vn,{}),s.jsx("span",{children:l("stopBash")})]}),R&&N&&ce&&s.jsxs("button",{type:"button",className:"toolcall-open",title:l("delegateOpenSubagent"),onClick:G=>{G.stopPropagation(),window.dispatchEvent(new CustomEvent("pi-web-ui:switch-conversation",{detail:ce}))},children:[s.jsx(Wu,{}),s.jsx("span",{children:l("delegateOpenSubagent")})]}),s.jsx("button",{type:"button",className:"chead-copy toolcall-copy",title:l("copyArgs"),onClick:G=>{G.stopPropagation(),U()},children:m?s.jsx(Es,{}):s.jsx(Dt,{})})]}),b&&s.jsxs("div",{className:"toolcall-body",children:[R?s.jsx(R0,{args:I}):t.argumentsText&&s.jsx("div",{className:"toolcall-args",children:F?s.jsx(j0,{command:F}):s.jsx("pre",{children:t.argumentsText})}),A.length>0&&s.jsxs("div",{className:"toolcall-output",children:[s.jsxs("div",{className:"toolcall-output-label",children:[l(X?"errorOutput":"output"),(x||B)&&s.jsx("span",{className:"cursor"})]}),s.jsx("pre",{children:A})]}),x&&A.length===0&&s.jsxs("div",{className:"toolcall-waiting",children:[s.jsx("span",{className:"cursor"})," ",l("waitingOutput")]}),B&&A.length===0&&s.jsxs("div",{className:"toolcall-waiting",children:[s.jsx("span",{className:"cursor"})," ",l("waitingModel")]})]})]})});function j0({command:e}){return s.jsxs("div",{className:"termline",children:[s.jsx(Vn,{className:"termline-icon"}),s.jsx("code",{children:e})]})}function R0({args:e}){const t=Me(),a=[{field:"task",label:t("delegateSecTask")},{field:"expected_outcome",label:t("delegateSecExpected")},{field:"required_tools",label:t("delegateSecTools")},{field:"must_do",label:t("delegateSecMustDo")},{field:"must_not_do",label:t("delegateSecMustNotDo")},{field:"context",label:t("delegateSecContext")}].filter(({field:i})=>e[i]?.trim());return a.length===0?null:s.jsx("div",{className:"delegate-brief",children:a.map(({field:i,label:o})=>s.jsxs("div",{className:"delegate-sec",children:[s.jsx("div",{className:"delegate-sec-label",children:o}),s.jsx("div",{className:"delegate-sec-text",children:e[i]})]},i))})}function L0(e){const t=e.split(`
327
- `),n=t[0].replace(/\s+/g," ").trim();if(!n)return;const a=t.length-1,i=n.length>80?`${n.slice(0,80)}…`:n;return a>0?`${i} +${a}`:i}function D0(e){if(e===void 0)return"";const t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;const n=Math.floor(t/60),a=Math.round(t%60);return`${n}m ${String(a).padStart(2,"0")}s`}const P0=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function hi(e){const t=e.match(P0);return t?{name:t[1],location:t[2],content:t[3],userMessage:t[4]?.trim()||void 0}:null}const O0=1568,M0=2*1024*1024;function Ht(e){return e.startsWith("image/")&&e!=="image/svg+xml"&&e!=="image/svg"}async function fi(e){if(!e.type.startsWith("image/"))return null;let t;try{t=await createImageBitmap(e,{imageOrientation:"from-image"})}catch{return null}try{const n=Math.min(1,O0/Math.max(t.width,t.height)),a=Math.max(1,Math.round(t.width*n)),i=Math.max(1,Math.round(t.height*n)),o=e.type==="image/jpeg"||e.type==="image/jpg"?[["image/jpeg",.85],["image/jpeg",.6],["image/webp",.8]]:[["image/png",1],["image/jpeg",.85],["image/jpeg",.6]];let l=null;for(const[u,p]of o){const h=document.createElement("canvas");h.width=a,h.height=i;const b=h.getContext("2d");if(!b)continue;u!=="image/png"&&(b.fillStyle="#ffffff",b.fillRect(0,0,a,i)),b.drawImage(t,0,0,a,i);const m=h.toDataURL(u,p),f=m.match(/^data:([^;]+);base64,/),x=f?f[1]:u,v=m.replace(/^data:[^;]*;base64,/,""),N=Math.floor(v.length*3/4);if(l={data:v,mimeType:x,name:e.name,size:N},N<=M0)return l}return l}finally{t.close()}}const B0=20*1024*1024;function as(e){return e.type==="text"&&typeof e.text=="string"?e:null}function Wl(e){return e.type==="thinking"&&typeof e.thinking=="string"?e:null}function Kl(e){return e.type==="toolCall"&&typeof e.id=="string"&&typeof e.name=="string"?e:null}function Yl(e){return e.type==="image"&&typeof e.dataUrl=="string"?e:null}function Gl(e){return e.type==="bash"&&typeof e.command=="string"?e:null}function F0(e){return e.imageData?"image":e.uploadPath?"upload":e.fileData?"file":"path"}function H0(e,t){if(e.imageData)return t("attachImage",{name:e.name??"image"});if(e.uploadPath)return t("attachFile",{name:e.name??e.uploadPath});if(e.fileData)return t("attachFile",{name:e.name??"file"});const n=e.path.split("/").pop()??e.path;return e.mode==="lines"&&e.lines?t("attachLines",{path:n,start:e.lines.start,end:e.lines.end}):e.mode==="page"?t("attachPage",{name:e.name??e.path}):e.mode==="reference"?t("refOnly",{path:n}):t("attachContent",{path:n})}const U0={edit:s.jsx(Ys,{}),copy:s.jsx(Dt,{}),x:s.jsx(tt,{})};function Mr(e){const t=(e??"").trim();if(!t)return s.jsx(hs,{});const n=U0[t.toLowerCase()];return n||(!/[\p{L}\p{N}]/u.test(t)&&t.length<=4?s.jsx("span",{className:"msg-action-glyph",children:t}):s.jsx(hs,{}))}function $0(e,t){const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}…`:n}const Br=c.memo(function({message:t,toolResults:n,liveOutputs:a,toolStatuses:i,streaming:o,isLast:l,onEdit:u,onKillBash:p,onRetry:h,onCollapse:b,questionAttachments:m,qnIndex:f,qnActive:x,onJump:v,thinkingWrap:N,toolsWrap:B,searchActive:X,autoExpand:K,uiMessageActions:A,uiContextMessage:R,onUiAction:I}){const $=Me(),[ce,ge]=c.useState(!1),[q,Y]=c.useState(""),[J,j]=c.useState([]),[F,T]=c.useState(!1),[U,G]=c.useState(null),D=_=>{G(_),window.setTimeout(()=>G(Q=>Q===_?null:Q),4e3)};if(t.role==="toolResult")return null;if(t.role==="compactionSummary")return s.jsx(K0,{message:t,forceOpen:X,autoExpand:K});const se=t.role==="custom"&&t.customType==="file",ee=t.content.map(_=>as(_)?.text??"").filter(Boolean).join(`
328
- `),Ne=t.content.map(_=>as(_)?.text??"").filter(Boolean).join(" "),w=t.role==="user"?hi(ee):null,de=w?w.userMessage??`skill:${w.name}`:ee.split(`
329
- `).join(" ").trim(),ue=o&&l&&t.content.length===0,pe=t.role==="user"&&!o&&!ue&&!!u,ke=async _=>{const Q=[];for(const V of _){if(!Ht(V.type))continue;const Ee=await fi(V);Ee&&Q.push({path:"",imageData:Ee.data,mimeType:Ee.mimeType,name:Ee.name})}Q.length>0&&j(V=>[...V,...Q])},Be=async _=>{if(_.size>B0){D($("fileTooLarge",{name:_.name,size:20}));return}let Q;try{Q=(await new Promise((Ee,oe)=>{const Z=new FileReader;Z.onload=()=>Ee(Z.result),Z.onerror=()=>oe(Z.error??new Error("read failed")),Z.readAsDataURL(_)})).replace(/^data:[^;]*;base64,/,"")}catch{D($("fileLoadFailed",{name:_.name}));return}j(V=>[...V,{path:"",fileData:Q,name:_.name,size:_.size,mimeType:_.type||void 0}])},ye=async _=>{const Q=[];for(const V of _)Ht(V.type)?Q.push(V):Be(V);Q.length>0&&await ke(Q)},Ae=()=>{Y(w?`/skill:${w.name}${w.userMessage?` ${w.userMessage}`:""}`:t.content.map(_=>as(_)?.text??"").filter(Boolean).join(`
330
- `)),j(m??[]),ge(!0)},ve=()=>{const _=q.trim();_&&(u?.(t.id,_,J.length>0?J:void 0),ge(!1))},Ye=A?A.some(_=>_?.id==="host:msg-copy"&&_.hidden!==!0):!0,Pe=$0(Ne,40)||Xa(t.role,$),ae=(R??[]).some(_=>_&&_.hidden!==!0&&_.kind!=="divider"),be=_=>{if(!ae)return;const Q=_.target;if(Q instanceof Element&&Q.closest("pre, code, a, input, textarea, [contenteditable='true']"))return;const V=window.getSelection?.();V&&!V.isCollapsed&&V.toString().trim().length>0||(_.preventDefault(),Xn({x:_.clientX,y:_.clientY,slot:"contextmenu.message",target:{id:t.id,kind:"message",label:Pe},entries:R??[]}))},Oe=()=>{if(!A)return pe?s.jsx("div",{className:"msg-actions",children:s.jsxs("button",{type:"button",className:"msg-action",title:$("editReaskTip"),onClick:Ae,children:[s.jsx(Ys,{})," ",$("editReask")]})}):null;const _=[];return A.forEach((Q,V)=>{if(!Q||Q.hidden===!0||Q.id==="host:msg-copy")return;const Ee=`${Q.id}#${V}`,oe=Q.label||Q.id;if(Q.id==="host:msg-edit-reask"){if(!pe)return;_.push(s.jsxs("button",{type:"button",className:"msg-action",title:$("editReaskTip"),onClick:Ae,children:[Mr(Q.icon)," ",oe]},Ee));return}if(Q.kind==="divider"){_.push(s.jsx("span",{className:"msg-action-divider","aria-hidden":"true"},Ee));return}if(Q.kind==="badge"){_.push(s.jsx("span",{className:"msg-action-badge",title:oe,children:Q.badge??oe},Ee));return}_.push(s.jsxs("button",{type:"button",className:"msg-action",title:oe,"aria-label":oe,onClick:()=>I?.(Q),children:[Mr(Q.icon)," ",oe,Q.badge?s.jsx("span",{className:"msg-action-count",children:Q.badge}):null]},Ee))}),_.length===0?null:s.jsx("div",{className:"msg-actions",children:_})},Le=t.role==="custom"&&(t.customType==="goal-review"||t.customType==="goal-wizard"),We=t.role==="custom"&&t.customType==="goal-wizard";return s.jsxs("div",{className:`msg msg-${t.role}${Le?" msg-goal-review":""}`,"data-role":t.role,"data-msg-id":t.id,onContextMenu:be,children:[s.jsxs("div",{className:"msg-meta",children:[s.jsx("span",{className:"msg-role",children:t.role==="custom"?We?$("goalWizardCard"):Le?$("goalBarTitle"):t.customType==="file"?$("attachment"):`${$("plugin")} · ${t.customType??$("unknown")}`:Xa(t.role,$)}),t.model&&s.jsx("span",{className:"msg-model",children:t.model}),t.timestamp&&s.jsx("span",{className:"msg-time",children:zl(t.timestamp)}),b&&s.jsxs("button",{type:"button",className:"msg-collapse-btn",title:$("collapseMsg"),onClick:()=>b(t.id),children:[s.jsx(Qn,{})," ",$("collapseMsg")]}),f!==void 0&&v&&s.jsxs("button",{type:"button",className:`qn-tag ${x?"active":""}`,title:`${f+1}. ${de}`,"aria-label":`${f+1}. ${de}`,onClick:()=>v(t.id),children:[s.jsx("span",{className:"qn-tag-bar"}),s.jsx("span",{className:"qn-tag-idx",children:f+1})]})]}),s.jsx("div",{className:"msg-body",children:ce?s.jsxs("div",{className:`msg-editor${F?" drag-over":""}`,onDragOver:_=>{_.preventDefault(),_.stopPropagation(),T(!0)},onDragLeave:_=>{_.currentTarget.contains(_.relatedTarget)||T(!1)},onDrop:_=>{_.preventDefault(),_.stopPropagation(),T(!1),ye(Array.from(_.dataTransfer?.files??[]))},children:[J.length>0&&s.jsx("div",{className:"msg-editor-images",children:J.map((_,Q)=>{const V=F0(_);return s.jsxs("span",{className:`msg-editor-img ${V==="image"?"":"file-chip"}`,title:H0(_,$),children:[V==="image"?s.jsx("img",{src:`data:${_.mimeType??"image/png"};base64,${_.imageData}`,alt:_.name}):s.jsxs("span",{className:"msg-editor-file",children:[s.jsx("span",{className:"msg-editor-file-icon",children:V==="path"?_.mode==="page"?"🌐":_.mode==="reference"?"🔗":"📎":"📄"}),s.jsx("span",{className:"msg-editor-file-name",children:_.name??_.path?.split("/").pop()})]}),s.jsx("button",{type:"button",className:"msg-editor-img-remove",title:$("removeAttachment"),onClick:()=>j(Ee=>Ee.filter((oe,Z)=>Z!==Q)),children:s.jsx(tt,{})})]},`${_.name??_.path??"att"}-${Q}`)})}),U&&s.jsx("div",{className:"msg-editor-notice",children:U}),s.jsx("textarea",{className:"msg-editor-input",value:q,autoFocus:!0,placeholder:$("editPlaceholder"),rows:Math.max(2,Math.min(10,q.split(`
331
- `).length+1)),onChange:_=>Y(_.target.value),onPaste:_=>{const Q=[];for(const V of _.clipboardData?.items??[])if(V.kind==="file"&&Ht(V.type)){const Ee=V.getAsFile();Ee&&Q.push(Ee)}Q.length!==0&&(_.preventDefault(),ke(Q))},onKeyDown:_=>{_.key==="Enter"&&(_.metaKey||_.ctrlKey)?(_.preventDefault(),ve()):_.key==="Escape"&&ge(!1)}}),s.jsxs("div",{className:"msg-editor-actions",children:[s.jsxs("span",{className:"msg-editor-hint",children:[s.jsx(Bu,{})," ",$("editAttachmentHint")]}),s.jsx("button",{type:"button",className:"chip",onClick:()=>ge(!1),children:$("cancel")}),s.jsxs("button",{type:"button",className:"chip primary",disabled:!q.trim(),title:$("reaskFromHere"),onClick:ve,children:[s.jsx(Ys,{})," ",$("reaskFromHere")]})]})]}):s.jsxs(s.Fragment,{children:[t.errorMessage&&s.jsxs("div",{className:"msg-error",children:[s.jsx("span",{className:"msg-error-text",children:t.errorMessage}),l&&!o&&h&&s.jsxs("button",{type:"button",className:"msg-retry-btn",title:$("retryLastTip"),onClick:h,children:[s.jsx(Rt,{})," ",$("retryNow")]})]}),se?s.jsx(q0,{message:t,forceOpen:X}):w?s.jsxs(s.Fragment,{children:[s.jsx(Y0,{block:w,forceOpen:X}),w.userMessage&&s.jsx("div",{className:"msg-text",children:s.jsx(dt,{text:w.userMessage,hardBreaks:!0})}),t.content.map((_,Q)=>_.type==="text"?null:s.jsx(Hr,{block:_,toolResults:n,liveOutputs:a,toolStatuses:i,streaming:o,isLast:l,onKillBash:p,toolsWrap:B,thinkingWrap:N,searchActive:X,role:t.role,showCopy:Ye},`${t.id}-${Q}`))]}):t.content.map((_,Q)=>s.jsx(Hr,{block:_,toolResults:n,liveOutputs:a,toolStatuses:i,streaming:o,isLast:l,onKillBash:p,toolsWrap:B,thinkingWrap:N,searchActive:X,role:t.role,showCopy:Ye},`${t.id}-${Q}`)),ue&&s.jsxs("div",{className:"thinking-wait",children:[$("thinkingWait"),s.jsx("span",{className:"dot"})]}),o&&l&&!ue&&s.jsx("span",{className:"stream-cursor"})]})}),!ce&&Oe()]})});function q0({message:e,forceOpen:t=!1}){const n=Me(),[a,i]=c.useState(!1),[o,l]=c.useState(!1),u=a||t,p=e.details??{},h=p.name??p.path??n("attachment"),b=p.type==="folder",m=p.mode==="reference",f=p.mode==="bridged",x=p.mode==="page",v=e.content.filter(A=>A.type==="text").map(A=>A.text).join(`
332
- `),N=W0(v),B=e.content.find(A=>A.type==="image"),X=N.split(`
333
- `).length,K=!m&&!x&&N.length>0;return s.jsxs("div",{className:`attachcard ${m?"reference":""}${x?" page":""}`,children:[s.jsxs("div",{className:"chead attachcard-head",role:"button",tabIndex:0,"aria-expanded":u,title:n(u?"collapseMsg":"expandMsg"),onClick:()=>i(A=>t?!0:!A),onKeyDown:A=>{A.target===A.currentTarget&&(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),i(R=>t?!0:!R))},children:[!m&&!x&&s.jsx("span",{className:"chead-toggle",children:u?s.jsx(Vt,{}):s.jsx(rs,{})}),s.jsx("span",{className:"chead-icon attachcard-icon",children:b?"📁":x?"🌐":"📎"}),s.jsx("span",{className:"chead-title attachcard-name",children:h}),p.path&&(x?s.jsx("a",{className:"attachcard-path attachcard-link",href:p.path,target:"_blank",rel:"noreferrer",children:p.path}):s.jsx("span",{className:"attachcard-path",children:p.path})),s.jsx("span",{className:`attachcard-mode ${p.mode==="lines"?"lines":m?"ref":x?"page":f?"bridged":"inline"}`,children:x?n("attachPageShort"):m?b?n("folderRefShort"):`${n("refOnlyShort")} · ${Fr(p.size)}`:f?n("bridgedVision"):B?n("image"):p.mode==="lines"?n("inlineLinesRange",{start:p.startLine??1,end:p.endLine??p.lines??1}):n("inlineLines",{n:p.lines??X})}),K&&s.jsx("button",{type:"button",className:"chead-copy",title:n(o?"copied":"copyMessage"),"aria-label":n("copyMessage"),onClick:A=>{A.stopPropagation(),navigator.clipboard.writeText(N),l(!0),window.setTimeout(()=>l(!1),1200)},children:o?s.jsx(Es,{}):s.jsx(Dt,{})})]}),!m&&u&&(f?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"attachcard-bridgenote",children:n("bridgedVisionDetail")}),B?.dataUrl&&s.jsx("div",{className:"attachcard-image",children:s.jsx("img",{src:B.dataUrl,alt:h})}),N&&s.jsx("pre",{className:"attachcard-content",children:N})]}):B?.dataUrl?s.jsx("div",{className:"attachcard-image",children:s.jsx("img",{src:B.dataUrl,alt:h})}):s.jsx("pre",{className:"attachcard-content",children:N})),m&&s.jsx("div",{className:"attachcard-refnote",children:b?n("folderNotExpanded"):n("fileNotExpanded",{size:Fr(p.size)})})]})}function Fr(e){return e===void 0?"":e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function W0(e){const t=e.match(/^\s*<file path="[^"]*"(?:\s+lines="[^"]*")?>\s*```\s*\n?([\s\S]*?)\n?```\s*<\/file>\s*$/);if(t)return t[1].trim();const n=e.match(/^\s*<vision-bridge>\s*([\s\S]*?)\s*<\/vision-bridge>\s*$/);return n?n[1].trim():e.trim()}function K0({message:e,forceOpen:t=!1,autoExpand:n=!1}){const a=Me(),[i,o]=c.useState(!1),[l,u]=c.useState(!1),[p,h]=c.useState(n);n!==p&&(h(n),n&&o(!0));const b=i||t,m=e.content.map(x=>as(x)?.text??"").filter(Boolean).join(`
334
- `),f=typeof e.tokensBefore=="number"?e.tokensBefore.toLocaleString():null;return s.jsxs("div",{className:"msg msg-compactionSummary","data-role":e.role,"data-msg-id":e.id,children:[s.jsxs("div",{className:"msg-meta",children:[s.jsx("span",{className:"msg-role",children:a("role.compaction")}),e.timestamp&&s.jsx("span",{className:"msg-time",children:zl(e.timestamp)})]}),s.jsxs("div",{className:`compaction-card${i?" expanded":""}`,children:[s.jsxs("div",{className:"chead compaction-head",role:"button",tabIndex:0,"aria-expanded":b,title:a(b?"collapseMsg":"expandMsg"),onClick:()=>o(x=>t?!0:!x),onKeyDown:x=>{x.target===x.currentTarget&&(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),o(v=>t?!0:!v))},children:[s.jsx("span",{className:"chead-toggle",children:b?s.jsx(Vt,{}):s.jsx(rs,{})}),s.jsx("span",{className:"chead-icon compaction-icon",children:s.jsx(_o,{})}),s.jsx("span",{className:"chead-title compaction-title",children:f?a("compactionFrom",{tokens:f}):a("role.compaction")}),m&&s.jsx("button",{type:"button",className:"chead-copy",title:a(l?"copied":"copyMessage"),"aria-label":a("copyMessage"),onClick:x=>{x.stopPropagation(),navigator.clipboard.writeText(m),u(!0),window.setTimeout(()=>u(!1),1200)},children:l?s.jsx(Es,{}):s.jsx(Dt,{})})]}),b&&s.jsxs("div",{className:"compaction-body",children:[s.jsx(dt,{text:m}),s.jsx("div",{className:"compaction-hint",children:a("compactionKeptHint")})]})]})]})}function Y0({block:e,forceOpen:t=!1}){const n=Me(),[a,i]=c.useState(!1),[o,l]=c.useState(!1),u=a||t;return s.jsxs("div",{className:`skillcard${a?" expanded":""}`,children:[s.jsxs("div",{className:"chead skillcard-head",role:"button",tabIndex:0,"aria-expanded":u,title:e.location,onClick:()=>i(p=>t?!0:!p),onKeyDown:p=>{p.target===p.currentTarget&&(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),i(h=>t?!0:!h))},children:[s.jsx("span",{className:"chead-toggle",children:u?s.jsx(Vt,{}):s.jsx(rs,{})}),s.jsx("span",{className:"chead-icon skillcard-icon",children:s.jsx($u,{})}),s.jsx("span",{className:"chead-title skillcard-name",children:e.name}),s.jsx("span",{className:"skillcard-path",children:e.location}),s.jsx("button",{type:"button",className:"chead-copy",title:n(o?"copied":"copyMessage"),"aria-label":n("copyMessage"),onClick:p=>{p.stopPropagation(),navigator.clipboard.writeText(e.content),l(!0),window.setTimeout(()=>l(!1),1200)},children:o?s.jsx(Es,{}):s.jsx(Dt,{})})]}),u&&s.jsx("div",{className:"skillcard-body",children:s.jsx(dt,{text:e.content})})]})}function Hr({block:e,toolResults:t,liveOutputs:n,toolStatuses:a,streaming:i,isLast:o,onKillBash:l,thinkingWrap:u,toolsWrap:p,searchActive:h,role:b,showCopy:m}){const f=Me(),[x,v]=c.useState(!1),N=as(e);if(N){const R=i&&o,I=(b==="assistant"||b==="user")&&m!==!1,$=I&&!N.text.includes(`
335
- `)&&!N.truncated,ce=b==="user"?s.jsx(dt,{text:N.text,hardBreaks:!0}):R?s.jsx(m0,{text:N.text}):s.jsx(dt,{text:N.text});return s.jsxs("div",{className:`msg-text${$?" single":""}`,children:[$?s.jsx("div",{className:"msg-text-main",children:ce}):s.jsxs(s.Fragment,{children:[ce,N.truncated&&s.jsx("div",{className:"trunc-note",children:f("truncated")})]}),I?s.jsx("button",{type:"button",className:"msg-text-copy",title:f(x?"copied":"copyMessage"),"aria-label":f("copyMessage"),onClick:()=>{navigator.clipboard.writeText(N.text),v(!0),window.setTimeout(()=>v(!1),1200)},children:x?s.jsx(Es,{}):s.jsx(Dt,{})}):null]})}const B=Wl(e);if(B)return s.jsx(h0,{thinking:B.thinking,streaming:i&&o,wrap:u,forceOpen:h});const X=Kl(e);if(X){const R=t.get(X.id),I=n.get(X.id),$={result:R,liveOutput:I?.text,streaming:i,status:a.get(X.id)};return s.jsx(I0,{block:X,view:$,onKillBash:l,wrap:p,forceOpen:h})}const K=Yl(e);if(K&&K.dataUrl)return s.jsx("div",{className:"msg-image",children:s.jsx("img",{src:K.dataUrl,alt:"attachment"})});const A=Gl(e);return A?s.jsxs("div",{className:"bashblock",children:[s.jsxs("div",{className:"bashblock-command",children:[s.jsx("span",{className:"bashblock-prompt",children:"$"}),s.jsx("code",{children:A.command}),A.exitCode!==void 0&&s.jsx("span",{className:`bashblock-exit ${A.exitCode===0?"ok":"err"}`,children:f("exitCode",{code:A.exitCode})}),A.cancelled&&s.jsx("span",{className:"bashblock-exit err",children:f("cancelled")})]}),A.output&&s.jsx("pre",{className:"bashblock-output",children:A.output}),A.truncated&&s.jsx("div",{className:"trunc-note",children:f("outputTruncated")})]}):null}function Xa(e,t){switch(e){case"user":return t("role.user");case"assistant":return t("role.assistant");case"toolResult":return t("role.tool");case"bashExecution":return t("role.bash");case"branchSummary":return t("role.branch");case"compactionSummary":return t("role.compaction");default:return e}}function zl(e){const t=new Date(e),n=String(t.getHours()).padStart(2,"0"),a=String(t.getMinutes()).padStart(2,"0");return`${n}:${a}`}function Ur(e,t,n){let a=!1;for(const i of t){const o=i;if(o.type!=="image"||typeof o.dataUrl!="string"||!o.dataUrl.startsWith("data:"))continue;const l=o.dataUrl.match(/^data:([^;]*);base64,(.+)$/);l&&(a=!0,e.push({path:"",imageData:l[2],mimeType:l[1]||"image/png",name:n??`image.${(l[1]||"image/png").split("/")[1]??"png"}`}))}return a}function G0(e){const t=new Map;for(let n=0;n<e.length;n++){const a=e[n];if(a.role!=="user"||!a.id)continue;const i=[];Ur(i,a.content);for(let o=n+1;o<e.length&&e[o].role==="custom"&&e[o].customType==="file";o++){const l=e[o].details??{};if(!Ur(i,e[o].content,l.name)){if(l.upload&&l.path){i.push({path:"",uploadPath:l.path,name:l.name??l.path,size:l.size});continue}if(l.mode==="page"&&l.path){i.push({path:l.path,mode:"page",name:l.name??l.path});continue}if(l.path&&l.mode){const u=l.mode==="inline"||l.mode==="lines"?l.mode:"reference",p={path:l.path,mode:u};l.mode==="lines"&&typeof l.startLine=="number"&&typeof l.endLine=="number"&&(p.lines={start:l.startLine,end:l.endLine}),i.push(p)}}}i.length>0&&t.set(a.id,i)}return t}const z0=c.memo(function({message:t,onExpand:n}){const a=Me();let i="";for(const m of t.content){const f=as(m);if(f&&f.text.trim()){const x=hi(f.text);x?i=`skill:${x.name}`+(x.userMessage?` · ${x.userMessage.replace(/\s+/g," ").trim()}`:""):i=f.text.replace(/\s+/g," ").trim();break}}if(!i&&t.role==="custom"&&t.customType==="file"){const m=t.details??{};i=m.name??m.path??""}i.length>90&&(i=`${i.slice(0,90)}…`);let l=0,u=0,p=0,h=0;for(const m of t.content)Wl(m)?l++:Kl(m)?u++:Gl(m)?p++:Yl(m)&&h++;const b=[];return l&&b.push(`${a("thinking")} ${l}`),u&&b.push(`${a("toolCalls")} ${u}`),p&&b.push(`${a("bashRuns")} ${p}`),h&&b.push(`${a("images")} ${h}`),s.jsxs("div",{role:"button",tabIndex:0,className:"msg-collapsed","data-msg-id":t.id,title:`${a("expandMsg")} · ${i||b.join(" · ")||t.role}`,onClick:()=>n(t.id),onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),n(t.id))},children:[s.jsx("span",{className:`msg-collapsed-role role-${t.role}`,children:t.role==="custom"&&t.customType==="file"?a("attachment"):Xa(t.role,a)}),s.jsxs("span",{className:"msg-collapsed-body",children:[i&&s.jsx("span",{className:"msg-collapsed-preview",children:i}),b.length>0&&s.jsx("span",{className:"msg-collapsed-chips",children:b.map((m,f)=>s.jsx("span",{className:"msg-collapsed-chip",children:m},f))})]}),t.timestamp?s.jsx("span",{className:"msg-collapsed-time",children:V0(t.timestamp)}):null,s.jsxs("span",{className:"msg-collapsed-action",children:[s.jsx(rs,{})," ",a("expandMsg")]})]})});function V0(e){const t=new Date(e),n=String(t.getHours()).padStart(2,"0"),a=String(t.getMinutes()).padStart(2,"0");return`${n}:${a}`}const Q0=c.memo(function({id:t,show:n,height:a,containerRef:i,onMeasured:o,lazyRef:l,children:u}){const p=c.useRef(null),h=c.useRef(null);return c.useLayoutEffect(()=>{const b=h.current;if(h.current=n,!n||b!==!1)return;const m=p.current,f=i.current;if(!m||!f)return;const x=m.offsetHeight;o?.(t,x);const v=x-a;if(v!==0){const N=m.parentElement;N&&N.getBoundingClientRect().bottom<=f.getBoundingClientRect().top&&(f.scrollTop+=v)}},[n]),n?s.jsx("div",{ref:l,"data-lazy-id":t,children:s.jsx("div",{ref:p,children:u})}):s.jsx("div",{ref:l,className:"msg-lazy-ph","data-msg-id":t,"data-lazy-id":t,style:{height:a},"aria-hidden":"true"})});function X0(e,t,n,a){const i=[],o=[];let l=0;for(const u of e){if(n.has(u.id))continue;u.top<t.bottom&&u.bottom>t.top?a.has(u.id)&&i.push(u.id):a.has(u.id)||(o.push(u.id),u.bottom<=t.top&&(l+=u.bottom-u.top))}return{show:i,hide:o,shrinkAbove:l}}function J0(e,t){if(t.show.length===0&&t.hide.length===0)return e;const n=new Set(e);for(const a of t.show)n.delete(a);for(const a of t.hide)n.add(a);return n}function Z0(e,t,n){const a=new Set;let i=0;for(let o=e.length-1;o>=0&&!(o<e.length-1&&i>=n);o--){const l=e[o];a.add(l.id),i+=t.get(l.id)??Vl(l.role,l.customType)}return a}function Vl(e,t){switch(e){case"user":return 72;case"assistant":return 280;case"toolResult":return 8;case"custom":return t==="file"?96:72;default:return 60}}const eg=["text","thinking","argumentsText","output","command"];function tg(e){let t=0;for(const n of e.content){n.type==="image"&&(t+=1);for(const a of eg){const i=n[a];typeof i=="string"&&(t+=i.length)}}return t}function sg(e,t,n,a){const i=n.get(e);return i&&i.len===t?i.h:a}function ng(e){const t=[];for(const n of e.content)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
325
+ `),inFence:i!==null}}const d0=c.memo(function({text:t}){return s.jsx(hi,{text:t})}),Br=200;function p0({text:e,inFence:t}){const[n,a]=c.useState(e),i=c.useRef(0),o=c.useRef(null);return c.useEffect(()=>{if(t)return;const l=Date.now()-i.current,u=()=>{i.current=Date.now(),a(e)};if(l>=Br){u();return}return o.current=setTimeout(u,Br-l),()=>{o.current&&clearTimeout(o.current)}},[e,t]),t?s.jsx("div",{className:"codeblock",children:s.jsx("pre",{children:s.jsx("code",{children:e})})}):s.jsx(hi,{text:n})}const m0=c.memo(function({text:t}){const{frozen:n,active:a,inFence:i}=c.useMemo(()=>u0(t),[t]);return s.jsxs("div",{className:"md",children:[n.map((o,l)=>s.jsx(d0,{text:o},l)),a.length>0&&s.jsx(p0,{text:a,inFence:i},n.length)]})});function h0({thinking:e,streaming:t,wrap:n=!0,forceOpen:a=!1}){const i=Pe(),[o,l]=c.useState(null),u=o??n,p=u||a,h=t?e.trimEnd().slice(-80):e.split(`
326
+ `)[0].slice(0,80),[b,m]=c.useState(!1),f=()=>{navigator.clipboard.writeText(e),m(!0),window.setTimeout(()=>m(!1),1200)};return s.jsxs("div",{className:`thinking ${p?"open":""} ${t?"live":""}`,children:[s.jsxs("div",{className:"chead thinking-head",role:"button",tabIndex:0,"aria-expanded":p,title:i(p?"collapseMsg":"expandMsg"),onClick:()=>l(!u),onKeyDown:x=>{x.target===x.currentTarget&&(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l(!u))},children:[s.jsx("button",{type:"button",className:"chead-toggle thinking-toggle",title:i(p?"collapseMsg":"expandMsg"),"aria-label":i(p?"collapseMsg":"expandMsg"),"aria-expanded":p,onClick:x=>{x.stopPropagation(),l(!u)},children:p?s.jsx(Vt,{}):s.jsx(rs,{})}),s.jsx("span",{className:"chead-icon thinking-icon",children:s.jsx(Gs,{})}),s.jsx("span",{className:"chead-title thinking-label",children:t&&p?s.jsxs("span",{className:"thinking-live-label",children:[i("thinkingNow"),s.jsx("span",{className:"dots"})]}):p?i("thinking"):i("thinkingPreview",{preview:h})}),s.jsx("button",{type:"button",className:"chead-copy toolcall-copy thinking-copy",title:i(b?"copied":"copyMessage"),"aria-label":i("copyMessage"),onClick:x=>{x.stopPropagation(),f()},children:b?s.jsx(bs,{}):s.jsx(Lt,{})})]}),p&&s.jsx("div",{className:"thinking-body",children:e})]})}const Wn=256*1024,Kn=300,f0=/"(path|file_path|filePath|filename|file)"\s*:\s*"((?:[^"\\\n]|\\.){0,4000})"/,g0=/"agent"\s*:\s*"((?:[^"\\\n]|\\.){0,200})"/,b0=/"(timeout|timeoutSeconds|timeout_seconds|timeoutSec|timeoutMs|timeout_ms|timeoutMilliseconds)"\s*:\s*(-?\d+(?:\.\d+)?)(?![0-9eE.])/,E0=1e9;function T0(e){if(!e)return{};const t=e.length>Wn?e.slice(0,Wn):e;return{path:v0(t),timeout:C0(t),command:w0(e),agent:x0(t)}}function x0(e){const t=g0.exec(e);if(!t)return;const n=t[1].replace(/[\u0000-\u001f\u007f]/g,"").trim();if(n)return n.length>Kn?`${n.slice(0,Kn)}…`:n}const y0=["task","expected_outcome","required_tools","must_do","must_not_do","context"];function k0(e){if(!e||e.length>Wn)return{};try{const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return{};const n=t,a={};for(const i of[...y0,"agent","model"])typeof n[i]=="string"&&n[i].trim()&&(a[i]=n[i]);return a}catch{return{}}}function N0(e,t=56){if(e.length<=t)return e;const n=e.split(/[\\/]+/).filter(Boolean),a=n[n.length-1];if(!a||n.length<=1)return`…${e.slice(-(t-1))}`;let i=a;for(let o=n.length-2;o>=0;o--){const l=`${n[o]}/${i}`;if(l.length+2>t)break;i=l}return`…/${i}`}function v0(e){const t=f0.exec(e);if(!t)return;const a=S0(t[2]).replace(/[\u0000-\u001f\u007f]/g," ").replace(/\s+/g," ").trim();if(a)return a.length>Kn?`${a.slice(0,Kn-1)}…`:a}function C0(e){const t=b0.exec(e);if(!t)return;const n=Number(t[2]);if(!Number.isFinite(n)||n<=0||n>E0)return;const a=t[1].toLowerCase();return!a.endsWith("ms")&&!a.endsWith("milliseconds")?`${n}s`:n<1e3?`${n}ms`:`${Math.round(n/100)/10}s`}function w0(e){if(!(e.length>Wn))try{const t=JSON.parse(e);return!t||typeof t!="object"||Array.isArray(t)?void 0:typeof t.command=="string"&&t.command.trim()?t.command:void 0}catch{return}}function S0(e){try{const t=JSON.parse(`"${e}"`);return typeof t=="string"?t:e}catch{return e}}const _0={bash:"$",delegate_task:"◈",read:"📄",write:"✍️",edit:"✏️",edit_soft:"✏️",grep:"🔍",find:"🧭",ls:"📂"};function A0(e){return _0[e]??"🛠"}const I0=c.memo(function({block:t,view:n,onKillBash:a,wrap:i=!0,forceOpen:o=!1}){const l=Pe(),[u,p]=c.useState(null),h=u??i,b=h||o,[m,f]=c.useState(!1),x=!n.result&&n.streaming&&!n.status,v=t.name==="bash"&&x,N=n.result!==void 0,B=!n.result&&!!n.status,V=n.result?.isError??n.status?.isError??!1,W=n.result?n.result.content.map(Y=>Y.type==="text"?Y.text:"").join(""):n.liveOutput??"",I=W.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(Y,D)=>l("liveOutputOmitted",{n:D})),j=t.name==="delegate_task",X=j?k0(t.argumentsText):{},w=j&&n.result&&typeof n.result.details=="object"&&n.result.details!==null?n.result.details.convId:void 0,ce=typeof w=="string"&&w?w:/sa-[0-9a-f]{8}/.exec(W)?.[0],be=V?"err":N?"ok":x||B?"run":"idle";let $=l(V?"error":N?"done":x?"running":B?"toolDoneWaitingModel":"toolQueued");const K=B&&n.status?.durationMs!==void 0?D0(n.status.durationMs):"";B&&K&&($=`${$} · ${K}`);const J=B&&n.status?.exitCode!==void 0?`exit ${n.status.exitCode}`:"",L=T0(t.argumentsText),H=t.name==="bash"?L.command:void 0,T=!b&&H?L0(H):void 0,F=()=>{t.argumentsText&&(navigator.clipboard.writeText(t.argumentsText),f(!0),setTimeout(()=>f(!1),1200))};return s.jsxs("div",{className:`toolcall ${be}`,children:[s.jsxs("div",{className:"chead toolcall-head",role:"button",tabIndex:0,"aria-expanded":b,title:l(b?"collapseMsg":"expandMsg"),onClick:()=>p(!h),onKeyDown:Y=>{Y.target===Y.currentTarget&&(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),p(!h))},children:[s.jsx("button",{type:"button",className:"chead-toggle toolcall-toggle",title:l(b?"collapseMsg":"expandMsg"),"aria-label":l(b?"collapseMsg":"expandMsg"),"aria-expanded":b,onClick:Y=>{Y.stopPropagation(),p(!h)},children:b?s.jsx(Vt,{}):s.jsx(rs,{})}),s.jsx("span",{className:"chead-icon toolcall-icon",children:A0(t.name)}),s.jsx("span",{className:"chead-title toolcall-name",children:t.name}),s.jsx("span",{className:"toolcall-status",title:J?`${$} · ${J}`:$,"aria-label":J?`${$} · ${J}`:$,children:V?s.jsx(tt,{}):N?s.jsx(Rt,{}):x?s.jsx(Ou,{}):B?s.jsx(Ra,{}):s.jsx(Iu,{})}),T&&s.jsxs("span",{className:"toolcall-cmd",title:H,children:["$ ",T]}),L.path&&s.jsx("span",{className:"toolcall-path",title:L.path,children:N0(L.path)}),L.timeout&&s.jsxs("span",{className:"toolcall-timeout",children:["⏱ ",L.timeout]}),j&&L.agent&&s.jsxs("span",{className:"toolcall-agent",title:L.agent,children:["◈ ",L.agent]}),s.jsx("span",{className:"toolcall-spacer"}),v&&a&&s.jsxs("button",{type:"button",className:"toolcall-kill",title:l("stopBashTip"),onClick:Y=>{Y.stopPropagation(),a?.()},children:[s.jsx(Sn,{}),s.jsx("span",{children:l("stopBash")})]}),j&&N&&ce&&s.jsxs("button",{type:"button",className:"toolcall-open",title:l("delegateOpenSubagent"),onClick:Y=>{Y.stopPropagation(),window.dispatchEvent(new CustomEvent("pi-web-ui:switch-conversation",{detail:ce}))},children:[s.jsx(Ku,{}),s.jsx("span",{children:l("delegateOpenSubagent")})]}),s.jsx("button",{type:"button",className:"chead-copy toolcall-copy",title:l("copyArgs"),onClick:Y=>{Y.stopPropagation(),F()},children:m?s.jsx(bs,{}):s.jsx(Lt,{})})]}),b&&s.jsxs("div",{className:"toolcall-body",children:[j?s.jsx(R0,{args:X}):t.argumentsText&&s.jsx("div",{className:"toolcall-args",children:H?s.jsx(j0,{command:H}):s.jsx("pre",{children:t.argumentsText})}),I.length>0&&s.jsxs("div",{className:"toolcall-output",children:[s.jsxs("div",{className:"toolcall-output-label",children:[l(V?"errorOutput":"output"),(x||B)&&s.jsx("span",{className:"cursor"})]}),s.jsx("pre",{children:I})]}),x&&I.length===0&&s.jsxs("div",{className:"toolcall-waiting",children:[s.jsx("span",{className:"cursor"})," ",l("waitingOutput")]}),B&&I.length===0&&s.jsxs("div",{className:"toolcall-waiting",children:[s.jsx("span",{className:"cursor"})," ",l("waitingModel")]})]})]})});function j0({command:e}){return s.jsxs("div",{className:"termline",children:[s.jsx(Jn,{className:"termline-icon"}),s.jsx("code",{children:e})]})}function R0({args:e}){const t=Pe(),a=[{field:"task",label:t("delegateSecTask")},{field:"expected_outcome",label:t("delegateSecExpected")},{field:"required_tools",label:t("delegateSecTools")},{field:"must_do",label:t("delegateSecMustDo")},{field:"must_not_do",label:t("delegateSecMustNotDo")},{field:"context",label:t("delegateSecContext")}].filter(({field:i})=>e[i]?.trim());return a.length===0?null:s.jsx("div",{className:"delegate-brief",children:a.map(({field:i,label:o})=>s.jsxs("div",{className:"delegate-sec",children:[s.jsx("div",{className:"delegate-sec-label",children:o}),s.jsx("div",{className:"delegate-sec-text",children:e[i]})]},i))})}function L0(e){const t=e.split(`
327
+ `),n=t[0].replace(/\s+/g," ").trim();if(!n)return;const a=t.length-1,i=n.length>80?`${n.slice(0,80)}…`:n;return a>0?`${i} +${a}`:i}function D0(e){if(e===void 0)return"";const t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;const n=Math.floor(t/60),a=Math.round(t%60);return`${n}m ${String(a).padStart(2,"0")}s`}const P0=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function fi(e){const t=e.match(P0);return t?{name:t[1],location:t[2],content:t[3],userMessage:t[4]?.trim()||void 0}:null}const O0=1568,M0=2*1024*1024;function Ht(e){return e.startsWith("image/")&&e!=="image/svg+xml"&&e!=="image/svg"}async function gi(e){if(!e.type.startsWith("image/"))return null;let t;try{t=await createImageBitmap(e,{imageOrientation:"from-image"})}catch{return null}try{const n=Math.min(1,O0/Math.max(t.width,t.height)),a=Math.max(1,Math.round(t.width*n)),i=Math.max(1,Math.round(t.height*n)),o=e.type==="image/jpeg"||e.type==="image/jpg"?[["image/jpeg",.85],["image/jpeg",.6],["image/webp",.8]]:[["image/png",1],["image/jpeg",.85],["image/jpeg",.6]];let l=null;for(const[u,p]of o){const h=document.createElement("canvas");h.width=a,h.height=i;const b=h.getContext("2d");if(!b)continue;u!=="image/png"&&(b.fillStyle="#ffffff",b.fillRect(0,0,a,i)),b.drawImage(t,0,0,a,i);const m=h.toDataURL(u,p),f=m.match(/^data:([^;]+);base64,/),x=f?f[1]:u,v=m.replace(/^data:[^;]*;base64,/,""),N=Math.floor(v.length*3/4);if(l={data:v,mimeType:x,name:e.name,size:N},N<=M0)return l}return l}finally{t.close()}}const B0=20*1024*1024;function as(e){return e.type==="text"&&typeof e.text=="string"?e:null}function Yl(e){return e.type==="thinking"&&typeof e.thinking=="string"?e:null}function Gl(e){return e.type==="toolCall"&&typeof e.id=="string"&&typeof e.name=="string"?e:null}function zl(e){return e.type==="image"&&typeof e.dataUrl=="string"?e:null}function Vl(e){return e.type==="bash"&&typeof e.command=="string"?e:null}function F0(e){return e.imageData?"image":e.uploadPath?"upload":e.fileData?"file":"path"}function H0(e,t){if(e.imageData)return t("attachImage",{name:e.name??"image"});if(e.uploadPath)return t("attachFile",{name:e.name??e.uploadPath});if(e.fileData)return t("attachFile",{name:e.name??"file"});const n=e.path.split("/").pop()??e.path;return e.mode==="lines"&&e.lines?t("attachLines",{path:n,start:e.lines.start,end:e.lines.end}):e.mode==="page"?t("attachPage",{name:e.name??e.path}):e.mode==="reference"?t("refOnly",{path:n}):t("attachContent",{path:n})}const U0={edit:s.jsx(Ys,{}),copy:s.jsx(Lt,{}),x:s.jsx(tt,{})};function Fr(e){const t=(e??"").trim();if(!t)return s.jsx(ms,{});const n=U0[t.toLowerCase()];return n||(!/[\p{L}\p{N}]/u.test(t)&&t.length<=4?s.jsx("span",{className:"msg-action-glyph",children:t}):s.jsx(ms,{}))}function $0(e,t){const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}…`:n}const Hr=c.memo(function({message:t,toolResults:n,liveOutputs:a,toolStatuses:i,streaming:o,isLast:l,onEdit:u,onKillBash:p,onRetry:h,onCollapse:b,questionAttachments:m,qnIndex:f,qnActive:x,onJump:v,thinkingWrap:N,toolsWrap:B,searchActive:V,autoExpand:W,uiMessageActions:I,uiContextMessage:j,onUiAction:X}){const w=Pe(),[ce,be]=c.useState(!1),[$,K]=c.useState(""),[J,L]=c.useState([]),[H,T]=c.useState(!1),[F,Y]=c.useState(null),D=A=>{Y(A),window.setTimeout(()=>Y(Q=>Q===A?null:Q),4e3)};if(t.role==="toolResult")return null;if(t.role==="compactionSummary")return s.jsx(K0,{message:t,forceOpen:V,autoExpand:W});const ae=t.role==="custom"&&t.customType==="file",ee=t.content.map(A=>as(A)?.text??"").filter(Boolean).join(`
328
+ `),ve=t.content.map(A=>as(A)?.text??"").filter(Boolean).join(" "),S=t.role==="user"?fi(ee):null,de=S?S.userMessage??`skill:${S.name}`:ee.split(`
329
+ `).join(" ").trim(),ue=o&&l&&t.content.length===0,pe=t.role==="user"&&!o&&!ue&&!!u,ke=async A=>{const Q=[];for(const z of A){if(!Ht(z.type))continue;const ge=await gi(z);ge&&Q.push({path:"",imageData:ge.data,mimeType:ge.mimeType,name:ge.name})}Q.length>0&&L(z=>[...z,...Q])},Oe=async A=>{if(A.size>B0){D(w("fileTooLarge",{name:A.name,size:20}));return}let Q;try{Q=(await new Promise((ge,oe)=>{const Z=new FileReader;Z.onload=()=>ge(Z.result),Z.onerror=()=>oe(Z.error??new Error("read failed")),Z.readAsDataURL(A)})).replace(/^data:[^;]*;base64,/,"")}catch{D(w("fileLoadFailed",{name:A.name}));return}L(z=>[...z,{path:"",fileData:Q,name:A.name,size:A.size,mimeType:A.type||void 0}])},ye=async A=>{const Q=[];for(const z of A)Ht(z.type)?Q.push(z):Oe(z);Q.length>0&&await ke(Q)},we=()=>{K(S?`/skill:${S.name}${S.userMessage?` ${S.userMessage}`:""}`:t.content.map(A=>as(A)?.text??"").filter(Boolean).join(`
330
+ `)),L(m??[]),be(!0)},Ce=()=>{const A=$.trim();A&&(u?.(t.id,A,J.length>0?J:void 0),be(!1))},qe=I?I.some(A=>A?.id==="host:msg-copy"&&A.hidden!==!0):!0,Be=$0(ve,40)||Ja(t.role,w),se=(j??[]).some(A=>A&&A.hidden!==!0&&A.kind!=="divider"),Te=A=>{if(!se)return;const Q=A.target;if(Q instanceof Element&&Q.closest("pre, code, a, input, textarea, [contenteditable='true']"))return;const z=window.getSelection?.();z&&!z.isCollapsed&&z.toString().trim().length>0||(A.preventDefault(),ea({x:A.clientX,y:A.clientY,slot:"contextmenu.message",target:{id:t.id,kind:"message",label:Be},entries:j??[]}))},De=()=>{if(!I)return pe?s.jsx("div",{className:"msg-actions",children:s.jsxs("button",{type:"button",className:"msg-action",title:w("editReaskTip"),onClick:we,children:[s.jsx(Ys,{})," ",w("editReask")]})}):null;const A=[];return I.forEach((Q,z)=>{if(!Q||Q.hidden===!0||Q.id==="host:msg-copy")return;const ge=`${Q.id}#${z}`,oe=Q.label||Q.id;if(Q.id==="host:msg-edit-reask"){if(!pe)return;A.push(s.jsxs("button",{type:"button",className:"msg-action",title:w("editReaskTip"),onClick:we,children:[Fr(Q.icon)," ",oe]},ge));return}if(Q.kind==="divider"){A.push(s.jsx("span",{className:"msg-action-divider","aria-hidden":"true"},ge));return}if(Q.kind==="badge"){A.push(s.jsx("span",{className:"msg-action-badge",title:oe,children:Q.badge??oe},ge));return}A.push(s.jsxs("button",{type:"button",className:"msg-action",title:oe,"aria-label":oe,onClick:()=>X?.(Q),children:[Fr(Q.icon)," ",oe,Q.badge?s.jsx("span",{className:"msg-action-count",children:Q.badge}):null]},ge))}),A.length===0?null:s.jsx("div",{className:"msg-actions",children:A})},Re=t.role==="custom"&&(t.customType==="goal-review"||t.customType==="goal-wizard"),Ye=t.role==="custom"&&t.customType==="goal-wizard";return s.jsxs("div",{className:`msg msg-${t.role}${Re?" msg-goal-review":""}`,"data-role":t.role,"data-msg-id":t.id,onContextMenu:Te,children:[s.jsxs("div",{className:"msg-meta",children:[s.jsx("span",{className:"msg-role",children:t.role==="custom"?Ye?w("goalWizardCard"):Re?w("goalBarTitle"):t.customType==="file"?w("attachment"):`${w("plugin")} · ${t.customType??w("unknown")}`:Ja(t.role,w)}),t.model&&s.jsx("span",{className:"msg-model",children:t.model}),t.timestamp&&s.jsx("span",{className:"msg-time",children:Ql(t.timestamp)}),b&&s.jsxs("button",{type:"button",className:"msg-collapse-btn",title:w("collapseMsg"),onClick:()=>b(t.id),children:[s.jsx(Zn,{})," ",w("collapseMsg")]}),f!==void 0&&v&&s.jsxs("button",{type:"button",className:`qn-tag ${x?"active":""}`,title:`${f+1}. ${de}`,"aria-label":`${f+1}. ${de}`,onClick:()=>v(t.id),children:[s.jsx("span",{className:"qn-tag-bar"}),s.jsx("span",{className:"qn-tag-idx",children:f+1})]})]}),s.jsx("div",{className:"msg-body",children:ce?s.jsxs("div",{className:`msg-editor${H?" drag-over":""}`,onDragOver:A=>{A.preventDefault(),A.stopPropagation(),T(!0)},onDragLeave:A=>{A.currentTarget.contains(A.relatedTarget)||T(!1)},onDrop:A=>{A.preventDefault(),A.stopPropagation(),T(!1),ye(Array.from(A.dataTransfer?.files??[]))},children:[J.length>0&&s.jsx("div",{className:"msg-editor-images",children:J.map((A,Q)=>{const z=F0(A);return s.jsxs("span",{className:`msg-editor-img ${z==="image"?"":"file-chip"}`,title:H0(A,w),children:[z==="image"?s.jsx("img",{src:`data:${A.mimeType??"image/png"};base64,${A.imageData}`,alt:A.name}):s.jsxs("span",{className:"msg-editor-file",children:[s.jsx("span",{className:"msg-editor-file-icon",children:z==="path"?A.mode==="page"?"🌐":A.mode==="reference"?"🔗":"📎":"📄"}),s.jsx("span",{className:"msg-editor-file-name",children:A.name??A.path?.split("/").pop()})]}),s.jsx("button",{type:"button",className:"msg-editor-img-remove",title:w("removeAttachment"),onClick:()=>L(ge=>ge.filter((oe,Z)=>Z!==Q)),children:s.jsx(tt,{})})]},`${A.name??A.path??"att"}-${Q}`)})}),F&&s.jsx("div",{className:"msg-editor-notice",children:F}),s.jsx("textarea",{className:"msg-editor-input",value:$,autoFocus:!0,placeholder:w("editPlaceholder"),rows:Math.max(2,Math.min(10,$.split(`
331
+ `).length+1)),onChange:A=>K(A.target.value),onPaste:A=>{const Q=[];for(const z of A.clipboardData?.items??[])if(z.kind==="file"&&Ht(z.type)){const ge=z.getAsFile();ge&&Q.push(ge)}Q.length!==0&&(A.preventDefault(),ke(Q))},onKeyDown:A=>{A.key==="Enter"&&(A.metaKey||A.ctrlKey)?(A.preventDefault(),Ce()):A.key==="Escape"&&be(!1)}}),s.jsxs("div",{className:"msg-editor-actions",children:[s.jsxs("span",{className:"msg-editor-hint",children:[s.jsx(Fu,{})," ",w("editAttachmentHint")]}),s.jsx("button",{type:"button",className:"chip",onClick:()=>be(!1),children:w("cancel")}),s.jsxs("button",{type:"button",className:"chip primary",disabled:!$.trim(),title:w("reaskFromHere"),onClick:Ce,children:[s.jsx(Ys,{})," ",w("reaskFromHere")]})]})]}):s.jsxs(s.Fragment,{children:[t.errorMessage&&s.jsxs("div",{className:"msg-error",children:[s.jsx("span",{className:"msg-error-text",children:t.errorMessage}),l&&!o&&h&&s.jsxs("button",{type:"button",className:"msg-retry-btn",title:w("retryLastTip"),onClick:h,children:[s.jsx(jt,{})," ",w("retryNow")]})]}),ae?s.jsx(q0,{message:t,forceOpen:V}):S?s.jsxs(s.Fragment,{children:[s.jsx(Y0,{block:S,forceOpen:V}),S.userMessage&&s.jsx("div",{className:"msg-text",children:s.jsx(pt,{text:S.userMessage,hardBreaks:!0})}),t.content.map((A,Q)=>A.type==="text"?null:s.jsx($r,{block:A,toolResults:n,liveOutputs:a,toolStatuses:i,streaming:o,isLast:l,onKillBash:p,toolsWrap:B,thinkingWrap:N,searchActive:V,role:t.role,showCopy:qe},`${t.id}-${Q}`))]}):t.content.map((A,Q)=>s.jsx($r,{block:A,toolResults:n,liveOutputs:a,toolStatuses:i,streaming:o,isLast:l,onKillBash:p,toolsWrap:B,thinkingWrap:N,searchActive:V,role:t.role,showCopy:qe},`${t.id}-${Q}`)),ue&&s.jsxs("div",{className:"thinking-wait",children:[w("thinkingWait"),s.jsx("span",{className:"dot"})]}),o&&l&&!ue&&s.jsx("span",{className:"stream-cursor"})]})}),!ce&&De()]})});function q0({message:e,forceOpen:t=!1}){const n=Pe(),[a,i]=c.useState(!1),[o,l]=c.useState(!1),u=a||t,p=e.details??{},h=p.name??p.path??n("attachment"),b=p.type==="folder",m=p.mode==="reference",f=p.mode==="bridged",x=p.mode==="page",v=e.content.filter(I=>I.type==="text").map(I=>I.text).join(`
332
+ `),N=W0(v),B=e.content.find(I=>I.type==="image"),V=N.split(`
333
+ `).length,W=!m&&!x&&N.length>0;return s.jsxs("div",{className:`attachcard ${m?"reference":""}${x?" page":""}`,children:[s.jsxs("div",{className:"chead attachcard-head",role:"button",tabIndex:0,"aria-expanded":u,title:n(u?"collapseMsg":"expandMsg"),onClick:()=>i(I=>t?!0:!I),onKeyDown:I=>{I.target===I.currentTarget&&(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),i(j=>t?!0:!j))},children:[!m&&!x&&s.jsx("span",{className:"chead-toggle",children:u?s.jsx(Vt,{}):s.jsx(rs,{})}),s.jsx("span",{className:"chead-icon attachcard-icon",children:b?"📁":x?"🌐":"📎"}),s.jsx("span",{className:"chead-title attachcard-name",children:h}),p.path&&(x?s.jsx("a",{className:"attachcard-path attachcard-link",href:p.path,target:"_blank",rel:"noreferrer",children:p.path}):s.jsx("span",{className:"attachcard-path",children:p.path})),s.jsx("span",{className:`attachcard-mode ${p.mode==="lines"?"lines":m?"ref":x?"page":f?"bridged":"inline"}`,children:x?n("attachPageShort"):m?b?n("folderRefShort"):`${n("refOnlyShort")} · ${Ur(p.size)}`:f?n("bridgedVision"):B?n("image"):p.mode==="lines"?n("inlineLinesRange",{start:p.startLine??1,end:p.endLine??p.lines??1}):n("inlineLines",{n:p.lines??V})}),W&&s.jsx("button",{type:"button",className:"chead-copy",title:n(o?"copied":"copyMessage"),"aria-label":n("copyMessage"),onClick:I=>{I.stopPropagation(),navigator.clipboard.writeText(N),l(!0),window.setTimeout(()=>l(!1),1200)},children:o?s.jsx(bs,{}):s.jsx(Lt,{})})]}),!m&&u&&(f?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"attachcard-bridgenote",children:n("bridgedVisionDetail")}),B?.dataUrl&&s.jsx("div",{className:"attachcard-image",children:s.jsx("img",{src:B.dataUrl,alt:h})}),N&&s.jsx("pre",{className:"attachcard-content",children:N})]}):B?.dataUrl?s.jsx("div",{className:"attachcard-image",children:s.jsx("img",{src:B.dataUrl,alt:h})}):s.jsx("pre",{className:"attachcard-content",children:N})),m&&s.jsx("div",{className:"attachcard-refnote",children:b?n("folderNotExpanded"):n("fileNotExpanded",{size:Ur(p.size)})})]})}function Ur(e){return e===void 0?"":e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function W0(e){const t=e.match(/^\s*<file path="[^"]*"(?:\s+lines="[^"]*")?>\s*```\s*\n?([\s\S]*?)\n?```\s*<\/file>\s*$/);if(t)return t[1].trim();const n=e.match(/^\s*<vision-bridge>\s*([\s\S]*?)\s*<\/vision-bridge>\s*$/);return n?n[1].trim():e.trim()}function K0({message:e,forceOpen:t=!1,autoExpand:n=!1}){const a=Pe(),[i,o]=c.useState(!1),[l,u]=c.useState(!1),[p,h]=c.useState(n);n!==p&&(h(n),n&&o(!0));const b=i||t,m=e.content.map(x=>as(x)?.text??"").filter(Boolean).join(`
334
+ `),f=typeof e.tokensBefore=="number"?e.tokensBefore.toLocaleString():null;return s.jsxs("div",{className:"msg msg-compactionSummary","data-role":e.role,"data-msg-id":e.id,children:[s.jsxs("div",{className:"msg-meta",children:[s.jsx("span",{className:"msg-role",children:a("role.compaction")}),e.timestamp&&s.jsx("span",{className:"msg-time",children:Ql(e.timestamp)})]}),s.jsxs("div",{className:`compaction-card${i?" expanded":""}`,children:[s.jsxs("div",{className:"chead compaction-head",role:"button",tabIndex:0,"aria-expanded":b,title:a(b?"collapseMsg":"expandMsg"),onClick:()=>o(x=>t?!0:!x),onKeyDown:x=>{x.target===x.currentTarget&&(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),o(v=>t?!0:!v))},children:[s.jsx("span",{className:"chead-toggle",children:b?s.jsx(Vt,{}):s.jsx(rs,{})}),s.jsx("span",{className:"chead-icon compaction-icon",children:s.jsx(Io,{})}),s.jsx("span",{className:"chead-title compaction-title",children:f?a("compactionFrom",{tokens:f}):a("role.compaction")}),m&&s.jsx("button",{type:"button",className:"chead-copy",title:a(l?"copied":"copyMessage"),"aria-label":a("copyMessage"),onClick:x=>{x.stopPropagation(),navigator.clipboard.writeText(m),u(!0),window.setTimeout(()=>u(!1),1200)},children:l?s.jsx(bs,{}):s.jsx(Lt,{})})]}),b&&s.jsxs("div",{className:"compaction-body",children:[s.jsx(pt,{text:m}),s.jsx("div",{className:"compaction-hint",children:a("compactionKeptHint")})]})]})]})}function Y0({block:e,forceOpen:t=!1}){const n=Pe(),[a,i]=c.useState(!1),[o,l]=c.useState(!1),u=a||t;return s.jsxs("div",{className:`skillcard${a?" expanded":""}`,children:[s.jsxs("div",{className:"chead skillcard-head",role:"button",tabIndex:0,"aria-expanded":u,title:e.location,onClick:()=>i(p=>t?!0:!p),onKeyDown:p=>{p.target===p.currentTarget&&(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),i(h=>t?!0:!h))},children:[s.jsx("span",{className:"chead-toggle",children:u?s.jsx(Vt,{}):s.jsx(rs,{})}),s.jsx("span",{className:"chead-icon skillcard-icon",children:s.jsx(qu,{})}),s.jsx("span",{className:"chead-title skillcard-name",children:e.name}),s.jsx("span",{className:"skillcard-path",children:e.location}),s.jsx("button",{type:"button",className:"chead-copy",title:n(o?"copied":"copyMessage"),"aria-label":n("copyMessage"),onClick:p=>{p.stopPropagation(),navigator.clipboard.writeText(e.content),l(!0),window.setTimeout(()=>l(!1),1200)},children:o?s.jsx(bs,{}):s.jsx(Lt,{})})]}),u&&s.jsx("div",{className:"skillcard-body",children:s.jsx(pt,{text:e.content})})]})}function $r({block:e,toolResults:t,liveOutputs:n,toolStatuses:a,streaming:i,isLast:o,onKillBash:l,thinkingWrap:u,toolsWrap:p,searchActive:h,role:b,showCopy:m}){const f=Pe(),[x,v]=c.useState(!1),N=as(e);if(N){const j=i&&o,X=(b==="assistant"||b==="user")&&m!==!1,w=X&&!N.text.includes(`
335
+ `)&&!N.truncated,ce=b==="user"?s.jsx(pt,{text:N.text,hardBreaks:!0}):j?s.jsx(m0,{text:N.text}):s.jsx(pt,{text:N.text});return s.jsxs("div",{className:`msg-text${w?" single":""}`,children:[w?s.jsx("div",{className:"msg-text-main",children:ce}):s.jsxs(s.Fragment,{children:[ce,N.truncated&&s.jsx("div",{className:"trunc-note",children:f("truncated")})]}),X?s.jsx("button",{type:"button",className:"msg-text-copy",title:f(x?"copied":"copyMessage"),"aria-label":f("copyMessage"),onClick:()=>{navigator.clipboard.writeText(N.text),v(!0),window.setTimeout(()=>v(!1),1200)},children:x?s.jsx(bs,{}):s.jsx(Lt,{})}):null]})}const B=Yl(e);if(B)return s.jsx(h0,{thinking:B.thinking,streaming:i&&o,wrap:u,forceOpen:h});const V=Gl(e);if(V){const j=t.get(V.id),X=n.get(V.id),w={result:j,liveOutput:X?.text,streaming:i,status:a.get(V.id)};return s.jsx(I0,{block:V,view:w,onKillBash:l,wrap:p,forceOpen:h})}const W=zl(e);if(W&&W.dataUrl)return s.jsx("div",{className:"msg-image",children:s.jsx("img",{src:W.dataUrl,alt:"attachment"})});const I=Vl(e);return I?s.jsxs("div",{className:"bashblock",children:[s.jsxs("div",{className:"bashblock-command",children:[s.jsx("span",{className:"bashblock-prompt",children:"$"}),s.jsx("code",{children:I.command}),I.exitCode!==void 0&&s.jsx("span",{className:`bashblock-exit ${I.exitCode===0?"ok":"err"}`,children:f("exitCode",{code:I.exitCode})}),I.cancelled&&s.jsx("span",{className:"bashblock-exit err",children:f("cancelled")})]}),I.output&&s.jsx("pre",{className:"bashblock-output",children:I.output}),I.truncated&&s.jsx("div",{className:"trunc-note",children:f("outputTruncated")})]}):null}function Ja(e,t){switch(e){case"user":return t("role.user");case"assistant":return t("role.assistant");case"toolResult":return t("role.tool");case"bashExecution":return t("role.bash");case"branchSummary":return t("role.branch");case"compactionSummary":return t("role.compaction");default:return e}}function Ql(e){const t=new Date(e),n=String(t.getHours()).padStart(2,"0"),a=String(t.getMinutes()).padStart(2,"0");return`${n}:${a}`}function qr(e,t,n){let a=!1;for(const i of t){const o=i;if(o.type!=="image"||typeof o.dataUrl!="string"||!o.dataUrl.startsWith("data:"))continue;const l=o.dataUrl.match(/^data:([^;]*);base64,(.+)$/);l&&(a=!0,e.push({path:"",imageData:l[2],mimeType:l[1]||"image/png",name:n??`image.${(l[1]||"image/png").split("/")[1]??"png"}`}))}return a}function G0(e){const t=new Map;for(let n=0;n<e.length;n++){const a=e[n];if(a.role!=="user"||!a.id)continue;const i=[];qr(i,a.content);for(let o=n+1;o<e.length&&e[o].role==="custom"&&e[o].customType==="file";o++){const l=e[o].details??{};if(!qr(i,e[o].content,l.name)){if(l.upload&&l.path){i.push({path:"",uploadPath:l.path,name:l.name??l.path,size:l.size});continue}if(l.mode==="page"&&l.path){i.push({path:l.path,mode:"page",name:l.name??l.path});continue}if(l.path&&l.mode){const u=l.mode==="inline"||l.mode==="lines"?l.mode:"reference",p={path:l.path,mode:u};l.mode==="lines"&&typeof l.startLine=="number"&&typeof l.endLine=="number"&&(p.lines={start:l.startLine,end:l.endLine}),i.push(p)}}}i.length>0&&t.set(a.id,i)}return t}const z0=c.memo(function({message:t,onExpand:n}){const a=Pe();let i="";for(const m of t.content){const f=as(m);if(f&&f.text.trim()){const x=fi(f.text);x?i=`skill:${x.name}`+(x.userMessage?` · ${x.userMessage.replace(/\s+/g," ").trim()}`:""):i=f.text.replace(/\s+/g," ").trim();break}}if(!i&&t.role==="custom"&&t.customType==="file"){const m=t.details??{};i=m.name??m.path??""}i.length>90&&(i=`${i.slice(0,90)}…`);let l=0,u=0,p=0,h=0;for(const m of t.content)Yl(m)?l++:Gl(m)?u++:Vl(m)?p++:zl(m)&&h++;const b=[];return l&&b.push(`${a("thinking")} ${l}`),u&&b.push(`${a("toolCalls")} ${u}`),p&&b.push(`${a("bashRuns")} ${p}`),h&&b.push(`${a("images")} ${h}`),s.jsxs("div",{role:"button",tabIndex:0,className:"msg-collapsed","data-msg-id":t.id,title:`${a("expandMsg")} · ${i||b.join(" · ")||t.role}`,onClick:()=>n(t.id),onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),n(t.id))},children:[s.jsx("span",{className:`msg-collapsed-role role-${t.role}`,children:t.role==="custom"&&t.customType==="file"?a("attachment"):Ja(t.role,a)}),s.jsxs("span",{className:"msg-collapsed-body",children:[i&&s.jsx("span",{className:"msg-collapsed-preview",children:i}),b.length>0&&s.jsx("span",{className:"msg-collapsed-chips",children:b.map((m,f)=>s.jsx("span",{className:"msg-collapsed-chip",children:m},f))})]}),t.timestamp?s.jsx("span",{className:"msg-collapsed-time",children:V0(t.timestamp)}):null,s.jsxs("span",{className:"msg-collapsed-action",children:[s.jsx(rs,{})," ",a("expandMsg")]})]})});function V0(e){const t=new Date(e),n=String(t.getHours()).padStart(2,"0"),a=String(t.getMinutes()).padStart(2,"0");return`${n}:${a}`}const Q0=c.memo(function({id:t,show:n,height:a,containerRef:i,onMeasured:o,lazyRef:l,children:u}){const p=c.useRef(null),h=c.useRef(null);return c.useLayoutEffect(()=>{const b=h.current;if(h.current=n,!n||b!==!1)return;const m=p.current,f=i.current;if(!m||!f)return;const x=m.offsetHeight;o?.(t,x);const v=x-a;if(v!==0){const N=m.parentElement;N&&N.getBoundingClientRect().bottom<=f.getBoundingClientRect().top&&(f.scrollTop+=v)}},[n]),n?s.jsx("div",{ref:l,"data-lazy-id":t,children:s.jsx("div",{ref:p,children:u})}):s.jsx("div",{ref:l,className:"msg-lazy-ph","data-msg-id":t,"data-lazy-id":t,style:{height:a},"aria-hidden":"true"})});function X0(e,t,n,a){const i=[],o=[];let l=0;for(const u of e){if(n.has(u.id))continue;u.top<t.bottom&&u.bottom>t.top?a.has(u.id)&&i.push(u.id):a.has(u.id)||(o.push(u.id),u.bottom<=t.top&&(l+=u.bottom-u.top))}return{show:i,hide:o,shrinkAbove:l}}function J0(e,t){if(t.show.length===0&&t.hide.length===0)return e;const n=new Set(e);for(const a of t.show)n.delete(a);for(const a of t.hide)n.add(a);return n}function Z0(e,t,n){const a=new Set;let i=0;for(let o=e.length-1;o>=0&&!(o<e.length-1&&i>=n);o--){const l=e[o];a.add(l.id),i+=t.get(l.id)??Xl(l.role,l.customType)}return a}function Xl(e,t){switch(e){case"user":return 72;case"assistant":return 280;case"toolResult":return 8;case"custom":return t==="file"?96:72;default:return 60}}const eg=["text","thinking","argumentsText","output","command"];function tg(e){let t=0;for(const n of e.content){n.type==="image"&&(t+=1);for(const a of eg){const i=n[a];typeof i=="string"&&(t+=i.length)}}return t}function sg(e,t,n,a){const i=n.get(e);return i&&i.len===t?i.h:a}function ng(e){const t=[];for(const n of e.content)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
336
336
  `)}function ag(e,t){const n=[];for(const a of e.content)if(a.type==="text"&&typeof a.text=="string")n.push(a.text);else if(a.type==="thinking"&&typeof a.thinking=="string")n.push(a.thinking);else if(a.type==="toolCall"){if(typeof a.name=="string"&&n.push(a.name),typeof a.argumentsText=="string"&&n.push(a.argumentsText),typeof a.id=="string"){const i=t.get(a.id);if(i){const o=ng(i);o&&n.push(o)}}}else a.type==="bash"&&(typeof a.command=="string"&&n.push(a.command),typeof a.output=="string"&&n.push(a.output));return n.join(`
337
- `)}function ig(e,t){let n=0,a=e.indexOf(t);for(;a!==-1;)n++,a=e.indexOf(t,a+t.length);return n}function rg(e,t,n,a){const i=new Map,o=n.toLowerCase();if(!o)return i;for(const l of e){if(!t.has(l.id))continue;const u=ig(ag(l,a).toLowerCase(),o);u>0&&i.set(l.id,u)}return i}function og(e,t){const n=[],a=t.toLowerCase();if(!a)return n;const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(o){const l=o.parentElement;return!l||l.closest(".search-bar")||l.closest(".msg-collapsed")?NodeFilter.FILTER_REJECT:(o.textContent??"").toLowerCase().includes(a)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let o=i.nextNode();o;o=i.nextNode()){const l=(o.textContent??"").toLowerCase();if(!o.parentElement?.closest("[data-msg-id]"))continue;let u=l.indexOf(a);for(;u!==-1;){const p=document.createRange();p.setStart(o,u),p.setEnd(o,u+a.length),n.push(p),u=l.indexOf(a,u+a.length)}}return n}function lg(e,t,n,a,i){const o=rg(n,a,t,i),l=new Map;for(const p of og(e,t)){const h=p.startContainer.parentElement?.closest("[data-msg-id]");if(!h?.dataset.msgId)continue;const b=l.get(h.dataset.msgId);b?b.push(p):l.set(h.dataset.msgId,[p])}const u=[];for(const p of n){const h=l.get(p.id);if(h)for(let m=0;m<h.length;m++)u.push({kind:"dom",range:h[m],msgId:p.id,k:m});const b=o.get(p.id);if(b)for(let m=0;m<b;m++)u.push({kind:"folded",msgId:p.id,k:m})}return u}function ya(e,t){return e.findIndex(n=>n.msgId===t.msgId&&n.k===t.k)}function Nt(e,t){const n=CSS;if(!n.highlights)return;if(t.length===0){n.highlights.delete(e);return}const a=window.Highlight;a&&n.highlights.set(e,new a(...t))}function cg(e,t){const n=[];let a=e;for(;a&&a!==t;){const i=getComputedStyle(a);/(auto|scroll|hidden)/.test(i.overflowY+i.overflowX)&&(a.scrollHeight>a.clientHeight||a.scrollWidth>a.clientWidth)&&n.push(a),a=a.parentElement}return n}function ug(e,t){const n=t.startContainer.parentElement;for(const u of cg(n,e)){const p=t.getBoundingClientRect(),h=u.getBoundingClientRect();if(p.height<=0||p.width<=0)return;p.top>=h.top+4&&p.bottom<=h.bottom-4||(u.scrollTop+=p.top-h.top-(u.clientHeight-p.height)/2),p.left>=h.left+4&&p.right<=h.right-4||(u.scrollLeft+=p.left-h.left-(u.clientWidth-p.width)/2)}const a=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(a.height<=0||a.width<=0)return;const o=a.top>=i.top+6&&a.bottom<=i.bottom-6,l=a.left>=i.left+6&&a.right<=i.right-6;o&&l||(o||(e.scrollTop+=a.top-i.top-(i.height-a.height)/2),l||(e.scrollLeft+=a.left-i.left-(i.width-a.width)/2))}function dg({containerRef:e,messages:t,collapsedIds:n,toolResults:a,onExpand:i,onProgrammaticScroll:o,open:l,onClose:u}){const p=Me(),h=c.useRef(null),[b,m]=c.useState(""),[f,x]=c.useState(null),[v,N]=c.useState(0),[,B]=c.useState(0),X=c.useDeferredValue(b),K=l?X.trim():"",A=c.useRef(null);A.current=f;const R=c.useRef([]),I=c.useRef({key:null}),$=c.useRef("");c.useEffect(()=>{l&&(x(null),requestAnimationFrame(()=>h.current?.select()))},[l]),c.useEffect(()=>{if(!l)return;const q=Y=>{Y.key==="Escape"&&(Y.preventDefault(),Y.stopPropagation(),u())};return window.addEventListener("keydown",q,!0),()=>window.removeEventListener("keydown",q,!0)},[l,u]),c.useEffect(()=>(l||(Nt("msg-search",[]),Nt("msg-search-active",[])),()=>{Nt("msg-search",[]),Nt("msg-search-active",[])}),[l]),c.useLayoutEffect(()=>{const q=()=>{N(0),x(null),B(0),R.current=[],Nt("msg-search",[]),Nt("msg-search-active",[]),I.current={key:null},$.current=""};if(!l||!K){q();return}const Y=e.current;if(!Y)return;let J=!1,j=0;return j=requestAnimationFrame(()=>{if(J)return;const F=lg(Y,K,t,n,a);R.current=F;const T=F.length;if(N(T),T===0){x(null),B(0),Nt("msg-search",[]),Nt("msg-search-active",[]),I.current={key:null},$.current=K;return}const U=A.current;let G;if(U){if(G=ya(F,U),G===-1){const w=[];for(let de=0;de<F.length;de++)F[de].msgId===U.msgId&&w.push(de);if(w.length>0){const de=Math.min(U.k,w.length-1);G=w[de]}else G=0}}else G=0;G<0&&(G=0),G>=T&&(G=T-1),(!U||U.msgId!==F[G].msgId||U.k!==F[G].k)&&x({msgId:F[G].msgId,k:F[G].k}),B(G);const D=F[G],se=I.current,ee=se.key?.msgId!==D.msgId||se.key?.k!==D.k||se.kind==="folded"&&D.kind==="dom"||K!==$.current;I.current={key:{msgId:D.msgId,k:D.k},kind:D.kind},$.current=K;const Ne=F.filter(w=>w.kind==="dom").map(w=>w.range);if(Nt("msg-search",Ne),D.kind==="folded"){Nt("msg-search-active",[]),ee&&i(D.msgId);return}Nt("msg-search-active",[D.range]),ee&&(o?.(),ug(Y,D.range))}),()=>{J=!0,cancelAnimationFrame(j)}},[l,K,t,e,f,n,a,i,o]);const ce=c.useCallback(q=>{const Y=R.current,J=Y.length;if(J===0)return;const j=A.current,F=j?ya(Y,j):0,T=Y[(F+q+J)%J];x(T.kind==="dom"||T.kind==="folded"?{msgId:T.msgId,k:T.k}:null)},[]);if(!l)return null;const ge=f?(()=>{const q=ya(R.current,f);return q===-1?0:q})():0;return s.jsxs("div",{className:"search-bar",role:"search",children:[s.jsx("input",{ref:h,className:"search-input",type:"text",value:b,placeholder:p("searchPlaceholder"),onChange:q=>{m(q.target.value)},onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),ce(q.shiftKey?-1:1))}}),s.jsx("span",{className:`search-count ${v===0?"empty":""}`,children:v===0?p("searchNoResults"):`${Math.min(ge+1,v)}/${v}`}),s.jsx("button",{type:"button",className:"search-btn",title:p("searchPrev"),disabled:v===0,onClick:()=>ce(-1),children:s.jsx(Qn,{})}),s.jsx("button",{type:"button",className:"search-btn",title:p("searchNext"),disabled:v===0,onClick:()=>ce(1),children:s.jsx(Vt,{})}),s.jsx("button",{type:"button",className:"search-btn",title:p("searchClose"),onClick:u,children:s.jsx(tt,{})})]})}function pg(e){const{dSt:t,dSh:n,escaped:a,graceActive:i,stuck:o}=e;return i?{flipEscape:!1,reassert:!1}:t>=-4||t<=-500?{flipEscape:!1,reassert:!1}:n<0?{flipEscape:!1,reassert:o&&!a}:{flipEscape:!0,reassert:!1}}const Ql="pi-web-model-usage";function mg(e){if(!e||typeof e!="object")return{};const t={};for(const[n,a]of Object.entries(e)){const i=typeof a=="number"?Math.floor(a):0;Number.isFinite(i)&&i>0&&(t[n]=i)}return t}function hg(e,t){return t?{...e,[t]:(e[t]??0)+1}:e}function fg(e,t){const n=t;return e.map((a,i)=>({m:a,i,count:n[a.id]??0})).sort((a,i)=>i.count-a.count||a.i-i.i).map(a=>a.m)}function Xl(){try{const e=localStorage.getItem(Ql);return e?mg(JSON.parse(e)):{}}catch{return{}}}function gg(e){try{localStorage.setItem(Ql,JSON.stringify(e))}catch{}}function qn(e){const t=hg(Xl(),e);return gg(t),t}const Jl=[{id:"setup-matt-pocock-skills",icon:"🛠",titleKey:"tpl.sk.setup",descKey:"tpl.sk.setup.desc",promptKey:"tpl.sk.setup.prompt"},{id:"ask-matt",icon:"🧭",titleKey:"tpl.sk.ask",descKey:"tpl.sk.ask.desc",promptKey:"tpl.sk.ask.prompt"},{id:"grill-with-docs",icon:"🗣",titleKey:"tpl.sk.grilldocs",descKey:"tpl.sk.grilldocs.desc",promptKey:"tpl.sk.grilldocs.prompt"},{id:"to-spec",icon:"📝",titleKey:"tpl.sk.tospec",descKey:"tpl.sk.tospec.desc",promptKey:"tpl.sk.tospec.prompt"},{id:"to-tickets",icon:"🎫",titleKey:"tpl.sk.totickets",descKey:"tpl.sk.totickets.desc",promptKey:"tpl.sk.totickets.prompt"},{id:"implement",icon:"🏗",titleKey:"tpl.sk.implement",descKey:"tpl.sk.implement.desc",promptKey:"tpl.sk.implement.prompt"},{id:"code-review",icon:"🧹",titleKey:"tpl.sk.codeview",descKey:"tpl.sk.codeview.desc",promptKey:"tpl.sk.codeview.prompt"},{id:"wayfinder",icon:"🗺",titleKey:"tpl.sk.wayfinder",descKey:"tpl.sk.wayfinder.desc",promptKey:"tpl.sk.wayfinder.prompt"},{id:"prototype",icon:"🔬",titleKey:"tpl.sk.prototype",descKey:"tpl.sk.prototype.desc",promptKey:"tpl.sk.prototype.prompt"},{id:"research",icon:"📚",titleKey:"tpl.sk.research",descKey:"tpl.sk.research.desc",promptKey:"tpl.sk.research.prompt"},{id:"improve-codebase-architecture",icon:"🏛",titleKey:"tpl.sk.arch",descKey:"tpl.sk.arch.desc",promptKey:"tpl.sk.arch.prompt"},{id:"diagnosing-bugs",icon:"🐛",titleKey:"tpl.sk.debug",descKey:"tpl.sk.debug.desc",promptKey:"tpl.sk.debug.prompt"},{id:"resolving-merge-conflicts",icon:"🔀",titleKey:"tpl.sk.merge",descKey:"tpl.sk.merge.desc",promptKey:"tpl.sk.merge.prompt"},{id:"triage",icon:"🗂",titleKey:"tpl.sk.triage",descKey:"tpl.sk.triage.desc",promptKey:"tpl.sk.triage.prompt"},{id:"wizard",icon:"✨",titleKey:"tpl.sk.wizard",descKey:"tpl.sk.wizard.desc",promptKey:"tpl.sk.wizard.prompt"},{id:"grill-me",icon:"🔍",titleKey:"tpl.sk.grillme",descKey:"tpl.sk.grillme.desc",promptKey:"tpl.sk.grillme.prompt"},{id:"handoff",icon:"🤝",titleKey:"tpl.sk.handoff",descKey:"tpl.sk.handoff.desc",promptKey:"tpl.sk.handoff.prompt"},{id:"to-questionnaire",icon:"📋",titleKey:"tpl.sk.questionnaire",descKey:"tpl.sk.questionnaire.desc",promptKey:"tpl.sk.questionnaire.prompt"},{id:"teach",icon:"🎓",titleKey:"tpl.sk.teach",descKey:"tpl.sk.teach.desc",promptKey:"tpl.sk.teach.prompt"},{id:"wait-what",icon:"💬",titleKey:"tpl.sk.ww",descKey:"tpl.sk.ww.desc",promptKey:"tpl.sk.ww.prompt"},{id:"writing-for-agents",icon:"📄",titleKey:"tpl.sk.wfa",descKey:"tpl.sk.wfa.desc",promptKey:"tpl.sk.wfa.prompt"},{id:"codebase-design",icon:"🧱",titleKey:"tpl.sk.codesign",descKey:"tpl.sk.codesign.desc",promptKey:"tpl.sk.codesign.prompt"},{id:"domain-modeling",icon:"🏷",titleKey:"tpl.sk.domain",descKey:"tpl.sk.domain.desc",promptKey:"tpl.sk.domain.prompt"},{id:"grilling",icon:"🔥",titleKey:"tpl.sk.grilling",descKey:"tpl.sk.grilling.desc",promptKey:"tpl.sk.grilling.prompt"},{id:"tdd",icon:"🧪",titleKey:"tpl.sk.tdd",descKey:"tpl.sk.tdd.desc",promptKey:"tpl.sk.tdd.prompt"}],Zl="pi-web-ui:prompt-templates";function bg(){try{const e=localStorage.getItem(Zl);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>!!n&&typeof n=="object"&&typeof n.id=="string"):[]}catch{return[]}}function $r(e){return Jl.some(t=>t.id===e)}function ln(e){return typeof e.title=="string"}const ec=c.createContext(null);function tc(){const e=c.useContext(ec);if(!e)throw new Error("useTemplates must be used within TemplateProvider");return e}function Eg({children:e,currentModelId:t}){const n=Me(),[a,i]=c.useState(bg),[o,l]=c.useState(!1),[u,p]=c.useState(null),[h,b]=c.useState(!1),[m,f]=c.useState(!1),[x,v]=c.useState(!1);c.useEffect(()=>{try{localStorage.setItem(Zl,JSON.stringify(a))}catch{}},[a]);const N=c.useMemo(()=>{const F=new Map,T=new Set;for(const D of a)D.hidden?T.add(D.id):(ln(D)&&!$r(D.id)||ln(D))&&F.set(D.id,D);const U=Jl.filter(D=>!T.has(D.id)).map(D=>{const se=F.get(D.id);return{id:D.id,icon:se?.icon??D.icon,title:se?.title??n(D.titleKey),desc:se?.desc??n(D.descKey),prompt:se?.prompt??n(D.promptKey),builtin:!0}}),G=a.filter(D=>ln(D)&&!$r(D.id)).map(D=>({id:D.id,icon:D.icon??"📌",title:D.title??"",desc:D.desc??"",prompt:D.prompt??""}));return[...U,...G]},[a,n]),B=c.useCallback(()=>l(!0),[]),X=c.useCallback(F=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:F}))},[]),K=c.useCallback((F,T=!1)=>{v(T),F?(b(!1),p({...F})):(b(!0),p({id:St(),icon:"📌",title:"",desc:"",prompt:""}))},[]),A=c.useCallback(()=>{l(!1),p(null),v(!1)},[]),R=c.useCallback(()=>{m?(i([]),f(!1)):(f(!0),setTimeout(()=>f(!1),5e3))},[m]),I=c.useCallback(F=>{l(!1),X(F.prompt)},[X]),$=c.useCallback(F=>{l(!1),K(F,!0)},[K]),ce=c.useCallback(()=>{l(!1),K(void 0,!0)},[K]),ge=c.useCallback(F=>{i(T=>{const U=T.findIndex(G=>G.id===F.id);if(U>=0){const G=[...T];return G[U]=F,G}return[...T,F]}),p(null),x&&(l(!0),v(!1))},[x]),q=c.useCallback(F=>{i(T=>F.builtin?[...T.filter(G=>G.id!==F.id),{id:F.id,hidden:!0}]:T.filter(U=>U.id!==F.id)),p(null),x&&(l(!0),v(!1))},[x]),Y=c.useCallback(F=>{i(T=>T.filter(U=>U.id!==F.id||U.hidden)),p(null),x&&(l(!0),v(!1))},[x]),J=c.useMemo(()=>({templates:N,fill:X,openPicker:B,openEdit:K,resetConfirm:m,toggleReset:R}),[N,X,B,K,m,R]),j=u?a.some(F=>F.id===u.id&&!F.hidden&&ln(F)):!1;return s.jsxs(ec.Provider,{value:J,children:[e,o&&s.jsx(xg,{templates:N,resetConfirm:m,onFill:I,onEditTpl:$,onNew:ce,onResetToggle:R,onClose:A}),u&&s.jsx(yg,{editing:u,isNew:h,hasOverride:j,onDraft:p,onSave:ge,onRestore:()=>Y(u),onRemove:()=>q(u),onFill:()=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:u.prompt})),A()},onSend:()=>{const F=u.prompt.trim();F&&ie({type:"prompt",text:F,queue:!1})&&(t&&qn(t),A())},onClose:A})]})}function Tg(){const e=Me(),{templates:t,fill:n,openEdit:a,toggleReset:i,resetConfirm:o}=tc();return s.jsxs("div",{className:"empty-templates",children:[s.jsxs("div",{className:"empty-templates-head",children:[s.jsx("span",{className:"empty-templates-title",children:e("tpl.title")}),s.jsx("span",{className:"empty-templates-hint",children:e("tpl.hint")})]}),s.jsxs("div",{className:"empty-templates-grid",children:[t.map(l=>s.jsx(sc,{tpl:l,title:e("tpl.clickCard"),onFill:()=>n(l.prompt),onEdit:()=>a(l),editTitle:e("tpl.editTpl")},l.id)),s.jsxs("button",{type:"button",className:"empty-template add",onClick:()=>a(),title:e("tpl.add"),children:[s.jsx("span",{className:"empty-template-icon",children:s.jsx(kt,{})}),s.jsxs("span",{className:"empty-template-main",children:[s.jsx("span",{className:"empty-template-title",children:e("tpl.add")}),s.jsx("span",{className:"empty-template-desc",children:e("tpl.addDesc")})]})]})]}),s.jsx("div",{className:"empty-templates-foot",children:s.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:i,children:[s.jsx(ko,{}),e(o?"tpl.resetConfirm":"tpl.reset")]})})]})}function sc({tpl:e,title:t,onFill:n,onEdit:a,editTitle:i}){const o=Me();return s.jsxs("button",{type:"button",className:"empty-template",title:t,onClick:n,children:[s.jsx("span",{className:"empty-template-icon",children:e.icon}),s.jsxs("span",{className:"empty-template-main",children:[s.jsx("span",{className:"empty-template-title",children:e.title}),s.jsx("span",{className:"empty-template-desc",children:e.desc})]}),s.jsx("span",{className:"template-card-ops",role:"button",title:i??o("tpl.editTpl"),onClick:l=>{l.stopPropagation(),a()},children:s.jsx(An,{})})]})}function xg({templates:e,resetConfirm:t,onFill:n,onEditTpl:a,onNew:i,onResetToggle:o,onClose:l}){const u=Me();return c.useEffect(()=>{const p=h=>{h.key==="Escape"&&l()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[l]),s.jsx("div",{className:"modal-backdrop",onClick:l,children:s.jsxs("div",{className:"modal template-picker",onClick:p=>p.stopPropagation(),children:[s.jsxs("div",{className:"template-picker-top",children:[s.jsxs("div",{className:"template-picker-head",children:[s.jsx("span",{className:"template-picker-title",children:u("tpl.pickerTitle")}),s.jsx("button",{type:"button",className:"btn template-modal-close",title:u("close"),onClick:l,children:s.jsx(tt,{})})]}),s.jsx("div",{className:"template-picker-hint",children:u("tpl.pickerHint")})]}),s.jsx("div",{className:"template-picker-scroll",children:s.jsxs("div",{className:"template-picker-grid",children:[e.map(p=>s.jsx(sc,{tpl:p,title:u("tpl.clickCard"),onFill:()=>n(p),onEdit:()=>a(p),editTitle:u("tpl.editTpl")},p.id)),s.jsxs("button",{type:"button",className:"empty-template add",onClick:i,title:u("tpl.add"),children:[s.jsx("span",{className:"empty-template-icon",children:s.jsx(kt,{})}),s.jsxs("span",{className:"empty-template-main",children:[s.jsx("span",{className:"empty-template-title",children:u("tpl.add")}),s.jsx("span",{className:"empty-template-desc",children:u("tpl.addDesc")})]})]})]})}),s.jsx("div",{className:"template-picker-foot",children:s.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:o,children:[s.jsx(ko,{}),u(t?"tpl.resetConfirm":"tpl.reset")]})})]})})}function yg({editing:e,isNew:t,hasOverride:n,onDraft:a,onSave:i,onRestore:o,onRemove:l,onFill:u,onSend:p,onClose:h}){const b=Me(),m=c.useRef(null);c.useEffect(()=>{const v=N=>{N.key==="Escape"&&h()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[h]),c.useEffect(()=>{const v=m.current;if(!v)return;v.style.height="auto";const N=v.scrollHeight>300;v.style.height=`${Math.min(v.scrollHeight,300)}px`,v.style.overflowY=N?"auto":"hidden"},[e.prompt]);const f=()=>{const v=e.title.trim(),N=e.prompt.trim();if(!v||!N){a({...e,error:b("tpl.required")});return}i({id:e.id,icon:e.icon.trim()||"📌",title:v,desc:e.desc.trim(),prompt:N})},x=!!e.builtin&&!t;return s.jsx("div",{className:"modal-backdrop",onClick:h,children:s.jsxs("div",{className:"modal template-modal",onClick:v=>v.stopPropagation(),children:[s.jsxs("div",{className:"template-modal-head",children:[s.jsx("span",{className:"template-modal-icon",children:e.icon}),s.jsx("span",{className:"template-modal-badge",children:b(x?"tpl.builtin":"tpl.custom")}),s.jsx("span",{className:"template-modal-title",children:b(t?"tpl.newTitle":"tpl.editTitle")}),s.jsx("button",{type:"button",className:"btn template-modal-close",title:b("close"),onClick:h,children:s.jsx(tt,{})})]}),s.jsxs("div",{className:"template-modal-body",children:[s.jsxs("label",{className:"template-field",children:[s.jsx("span",{className:"template-field-label",children:b("tpl.fieldIcon")}),s.jsx("input",{className:"template-field-input icon",value:e.icon,maxLength:4,onChange:v=>a({...e,icon:v.target.value})})]}),s.jsxs("label",{className:"template-field",children:[s.jsx("span",{className:"template-field-label",children:b("tpl.fieldTitle")}),s.jsx("input",{className:"template-field-input",value:e.title,placeholder:b("tpl.fieldTitlePh"),onChange:v=>a({...e,title:v.target.value})})]}),s.jsxs("label",{className:"template-field",children:[s.jsx("span",{className:"template-field-label",children:b("tpl.fieldDesc")}),s.jsx("input",{className:"template-field-input",value:e.desc,placeholder:b("tpl.fieldDescPh"),onChange:v=>a({...e,desc:v.target.value})})]}),s.jsxs("label",{className:"template-field",children:[s.jsx("span",{className:"template-field-label",children:b("tpl.fieldPrompt")}),s.jsx("textarea",{ref:m,className:"template-field-prompt",value:e.prompt,placeholder:b("tpl.fieldPromptPh"),onChange:v=>a({...e,prompt:v.target.value})})]})]}),e.error&&s.jsx("div",{className:"template-error",children:e.error}),s.jsxs("div",{className:"template-modal-actions",children:[s.jsxs("div",{className:"template-modal-actions-left",children:[!t&&x&&n&&s.jsx("button",{type:"button",className:"btn template-btn ghost",title:b("tpl.restoreTip"),onClick:o,children:b("tpl.restore")}),!t&&x&&s.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:b("tpl.removeTip"),onClick:l,children:[s.jsx(ut,{})," ",b("tpl.remove")]}),!t&&!x&&s.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:b("tpl.deleteTip"),onClick:l,children:[s.jsx(ut,{})," ",b("tpl.delete")]})]}),s.jsxs("div",{className:"template-modal-actions-right",children:[s.jsx("button",{type:"button",className:"btn template-btn",onClick:f,children:b("tpl.save")}),s.jsx("button",{type:"button",className:"btn template-btn fill",onClick:u,title:b("tpl.fillTip"),children:b("tpl.fill")}),s.jsxs("button",{type:"button",className:"btn template-btn send",onClick:p,title:b("tpl.sendTip"),children:[s.jsx(_a,{})," ",b("tpl.sendNow")]})]})]})]})})}const qr=new Map,kg=15,Wr=30,ka=250,Kr=1200,Ng=1600;function Yr({kind:e,text:t,onRemoveQueued:n,onRecallQueued:a}){const i=Me();return s.jsxs("div",{className:"msg msg-user msg-queued","data-role":"user",children:[s.jsxs("div",{className:"msg-meta",children:[s.jsx("span",{className:"msg-role",children:i("role.user")}),s.jsx("span",{className:`queued-tag ${e==="steer"?"steer":"follow"}`,children:i(e==="steer"?"queueSteerTag":"queueFollowTag")}),s.jsxs("div",{className:"msg-queued-actions",children:[a&&s.jsx("button",{type:"button",className:"msg-queued-recall",title:i("queueRecallTip"),"aria-label":i("queueRecallTip"),onClick:()=>a(e,t),children:"↩"}),n&&s.jsx("button",{type:"button",className:"msg-queued-remove",title:i("queueRemoveTip"),"aria-label":i("queueRemoveTip"),onClick:()=>n(e,t),children:"✕"})]})]}),s.jsx("div",{className:"msg-body",children:s.jsx("div",{className:"msg-text",children:s.jsx(dt,{text:t,hardBreaks:!0})})})]})}function vg({compaction:e}){const t=Me(),[,n]=c.useState(0);c.useEffect(()=>{const o=setInterval(()=>n(l=>l+1),1e3);return()=>clearInterval(o)},[]);const a=Math.max(0,Math.floor((Date.now()-e.startedAt)/1e3)),i=e.reason==="manual"?t("compactingReasonManual"):e.reason==="overflow"?t("compactingReasonOverflow"):t("compactingReasonThreshold");return s.jsxs("div",{className:"compact-notice",role:"status",children:[s.jsx("span",{className:"compact-pulse"}),s.jsxs("span",{className:"compact-text",children:[t("compactingContext")," · ",a,"s"]}),s.jsx("span",{className:"compact-reason",children:i})]})}function Gr(e){return e.content.some(t=>t.type==="toolCall")}function Cg({state:e,liveOutputs:t,toolStatuses:n,onEdit:a,onKillBash:i,onRetry:o,onRemoveQueued:l,onRecallQueued:u,thinkingWrap:p,toolsWrap:h,jumpTarget:b,onJumpDone:m,uiMessageActions:f,uiContextMessage:x,onUiAction:v}){const N=Me(),B=c.useRef(null),[X,K]=c.useState(!0),A=c.useRef(!0),R=c.useRef(0),I=c.useRef(0),$=c.useRef(!1),ce=c.useRef(0),[ge,q]=c.useState(()=>new Set),[Y,J]=c.useState(!1),j=e.streamingMessage?[...e.messages,e.streamingMessage]:e.messages,F=c.useMemo(()=>{const H=new Map;for(const te of e.messages)te.role==="toolResult"&&te.toolCallId&&H.set(te.toolCallId,te);return H},[e.messages]),T=c.useMemo(()=>G0(e.messages),[e.messages]),U=j.length>0?j[j.length-1].id:null,G=e.messages.length>Wr?Math.max(0,e.messages.length-kg):0,D=c.useMemo(()=>{const H=new Set;for(let te=0;te<G;te++){const _e=e.messages[te];_e.role!=="toolResult"&&(ge.has(_e.id)||H.add(_e.id))}return H},[e.messages,G,ge]),[se,ee]=c.useState(()=>new Set),[Ne,w]=c.useState(()=>new Set),de=c.useRef(new Map),ue=c.useRef(new Map),pe=c.useRef(new Map),ke=c.useRef(0),Be=c.useMemo(()=>{const H=new Map;for(const te of e.messages)H.set(te.id,tg(te));return H},[e.messages]),ye=c.useRef(Be);ye.current=Be;const Ae=c.useRef(se);Ae.current=se;const ve=e.messages.length>Wr&&!Y,Ye=c.useRef(ve);Ye.current=ve;const Pe=Z0(e.messages,de.current,Ng),ae=c.useRef(Pe);ae.current=Pe;const be=c.useCallback(()=>{const H=B.current;if(!H)return;if(!Ye.current){ee(ze=>ze.size?new Set:ze);return}const te=H.getBoundingClientRect(),_e={top:te.top-Kr,bottom:te.bottom+Kr},je=[];for(const[ze,pt]of pe.current){const It=pt.getBoundingClientRect();je.push({id:ze,top:It.top,bottom:It.bottom}),Ae.current.has(ze)||We(ze,It.bottom-It.top,ye.current.get(ze))}const Ke=X0(je,_e,ae.current,Ae.current);for(const ze of Ke.hide){const pt=pe.current.get(ze);pt&&We(ze,pt.offsetHeight,ye.current.get(ze))}ee(ze=>J0(ze,Ke))},[]),Oe=c.useCallback(()=>{ke.current||(ke.current=requestAnimationFrame(()=>{ke.current=0,be()}))},[be]);c.useLayoutEffect(()=>{be()},[be]);const Le=c.useRef(Y);c.useLayoutEffect(()=>{Le.current&&!Y&&be(),Le.current=Y},[Y,be]);const We=c.useCallback((H,te,_e)=>{_e!==void 0&&(ue.current.set(H,{h:te,len:_e}),de.current.set(H,te))},[]),_=c.useCallback((H,te)=>{We(H,te,ye.current.get(H))},[We]),Q=c.useCallback(H=>{H&&pe.current.set(H.dataset.lazyId??"",H)},[]);c.useEffect(()=>{const H=new Set(e.messages.map(te=>te.id));for(const te of pe.current.keys())H.has(te)||(pe.current.delete(te),de.current.delete(te),ue.current.delete(te));ee(te=>{let _e=!1;const je=new Set;for(const Ke of te)H.has(Ke)?je.add(Ke):_e=!0;return _e?je:te})},[e.messages,ge]),c.useEffect(()=>()=>cancelAnimationFrame(ke.current),[]);const V=c.useMemo(()=>{const H=[];for(const te of e.messages){if(te.role!=="user")continue;const _e=te.content.map(ze=>as(ze)?.text??"").filter(Boolean).join(" "),je=hi(_e),Ke=je?je.userMessage??`skill:${je.name}`:_e.trim();Ke&&H.push({id:te.id,text:Ke})}return H},[e.messages]),Ee=c.useMemo(()=>{const H=new Map;return V.forEach((te,_e)=>H.set(te.id,_e)),H},[V]),[oe,Z]=c.useState(-1),y=c.useRef(-1),P=c.useRef(V);c.useEffect(()=>{P.current=V},[V]);const le=c.useCallback(()=>{const H=B.current,te=P.current;if(!H||te.length===0)return;const _e=H.getBoundingClientRect().top,je=140;let Ke=-1;for(let ze=0;ze<te.length;ze++){const pt=H.querySelector(`[data-msg-id="${te[ze].id}"]`);if(pt)if(pt.getBoundingClientRect().top<=_e+je)Ke=ze;else break}Ke!==y.current&&(y.current=Ke,Z(Ke))},[]);c.useEffect(()=>{le()},[V,le]);const Te=c.useCallback(H=>{q(te=>te.has(H)?te:new Set(te).add(H))},[]);c.useEffect(()=>{const H=te=>{if(!(te.ctrlKey||te.metaKey)||te.key.toLowerCase()!=="f")return;const _e=te.target;_e&&(_e.tagName==="INPUT"||_e.tagName==="TEXTAREA"||_e.isContentEditable)||(te.preventDefault(),J(!0))};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[]);const Ie=c.useCallback(H=>{q(te=>{if(!te.has(H))return te;const _e=new Set(te);return _e.delete(H),_e})},[]),Fe=c.useCallback(H=>{const te=e.messages.findIndex(je=>je.id===H);Jn.flushSync(()=>{te>=0&&te<G&&!ge.has(H)&&Te(H),w(je=>je.has(H)?je:new Set(je).add(H))});const _e=P.current.findIndex(je=>je.id===H);y.current=_e,Z(_e),requestAnimationFrame(()=>{const je=B.current?.querySelector(`[data-msg-id="${H}"]`);je&&(B.current?.querySelectorAll(".msg-flash").forEach(Ke=>Ke.classList.remove("msg-flash")),je.scrollIntoView({block:"start"}),je.classList.remove("msg-flash"),je.offsetWidth,je.classList.add("msg-flash"),je!==B.current?.lastElementChild&&($.current=!0))})},[e.messages,G,ge,Te]),[Re,L]=c.useState(null),De=c.useRef(null),Ge=c.useRef(null);c.useEffect(()=>{const H=De.current;if(!H||H.convId!==e.conversationId){De.current={convId:e.conversationId,ids:new Set(e.messages.filter(te=>te.role==="compactionSummary").map(te=>te.id))},Ge.current=null,L(null);return}for(const te of e.messages)if(te.role==="compactionSummary"&&!H.ids.has(te.id)){H.ids.add(te.id),L(te.id);break}},[e.messages,e.conversationId]),c.useEffect(()=>{!Re||Ge.current===Re||(Ge.current=Re,Fe(Re))},[Re,Fe]);const C=c.useMemo(()=>b?e.messages.find(H=>H.role===b.role&&H.timestamp===b.timestamp)?.id??null:null,[e.messages,b]);c.useEffect(()=>{if(b){if(C){Fe(C),m?.();return}e.sessionFile===b.path&&e.messages.length>0&&m?.()}},[C,Fe,m,b,e.sessionFile,e.messages.length]);const S=c.useCallback(()=>{const H=B.current;if(!H)return;const te=H.scrollTop-R.current,_e=H.scrollHeight-I.current;R.current=H.scrollTop,I.current=H.scrollHeight;const je=H.scrollHeight-H.scrollTop-H.clientHeight<80,Ke=Date.now()<ce.current,ze=pg({dSt:te,dSh:_e,escaped:$.current,graceActive:Ke,stuck:A.current});ze.reassert&&(ce.current=Date.now()+ka,H.scrollTop=H.scrollHeight),ze.flipEscape&&($.current=!0),je&&te>=0&&($.current=!1),Ke||(te<0?A.current=je&&!$.current:je&&(A.current=!0)),K(A.current),le(),Oe()},[le,Oe]),he=c.useRef(!1);c.useEffect(()=>{const H=he.current;if(he.current=!!e.isStreaming,H&&!e.isStreaming&&!$.current){const te=()=>{const je=B.current;je&&!$.current&&(je.scrollTop=je.scrollHeight,A.current=!0,K(!0))};requestAnimationFrame(()=>requestAnimationFrame(te));const _e=setTimeout(te,180);return()=>clearTimeout(_e)}},[e.isStreaming]),c.useEffect(()=>{const H=B.current;H&&A.current&&(H.scrollTop=H.scrollHeight)},[j,e.isStreaming,t]);const Ce=e.queue.steering.join("\0")+""+e.queue.followUp.join("\0");c.useEffect(()=>{const H=B.current;H&&A.current&&(H.scrollTop=H.scrollHeight)},[Ce]),c.useEffect(()=>{const H=B.current;if(!H||typeof ResizeObserver>"u")return;let te=H.clientHeight;const _e=new ResizeObserver(()=>{const je=H.clientHeight,Ke=je-te;te=je,Ke>0&&(H.scrollTop=Math.min(H.scrollTop,H.scrollHeight-H.clientHeight))});return _e.observe(H),()=>_e.disconnect()},[]),c.useEffect(()=>{const H=B.current;if(!H||typeof MutationObserver>"u")return;let te=!1;const _e=new MutationObserver(()=>{te||(te=!0,requestAnimationFrame(()=>{te=!1;const je=B.current;je&&A.current&&!$.current&&(je.scrollTop=je.scrollHeight,K(!0))}))});return _e.observe(H,{childList:!0,subtree:!0,characterData:!0}),()=>_e.disconnect()},[]);const $e=c.useCallback(()=>{if(!B.current)return;A.current=!0,$.current=!1,K(!0),ce.current=Date.now()+ka;const te=()=>{const _e=B.current;!_e||!A.current||$.current||(ce.current=Date.now()+ka,_e.scrollTop=_e.scrollHeight)};te(),requestAnimationFrame(()=>requestAnimationFrame(te)),setTimeout(te,120),setTimeout(te,300),setTimeout(te,600)},[]),we=c.useRef(null);c.useEffect(()=>{const H=we.current,te=B.current;if(!H||!te)return;const _e=je=>{je.preventDefault();const Ke=H.querySelector(".qn-list");if(Ke&&Ke.contains(je.target)&&Ke.scrollHeight>Ke.clientHeight){Ke.scrollTop+=je.deltaY;return}te.scrollTop+=je.deltaY};return H.addEventListener("wheel",_e,{passive:!1}),()=>H.removeEventListener("wheel",_e)},[]);const[Je,gt]=c.useState(0);c.useEffect(()=>{const H=()=>{gt(B.current?.clientHeight??0),Oe()};return H(),window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[Oe]);const bt=V.length,At=c.useMemo(()=>bt===0?27:Math.max(4,Math.min(27,Math.floor(((Je||600)-16)/bt)-3)),[bt,Je]),$t=At<20;return s.jsxs("div",{className:"messages-wrap",children:[s.jsxs("div",{className:`messages${Y||X?"":" anchor-live"}`,ref:B,onScroll:S,children:[e.messages.length===0&&!e.streamingMessage&&s.jsx("div",{className:"empty-state",children:s.jsx(Tg,{})}),e.messages.map((H,te)=>{const _e=te<G,je=_e&&ge.has(H.id);if(_e&&!je)return H.role==="toolResult"?null:s.jsx(z0,{message:H,onExpand:Te},H.id);const Ke=H.role==="user"?Ee.get(H.id):void 0,ze=!ve||Pe.has(H.id)||Ne.has(H.id)||!se.has(H.id);return s.jsx(Q0,{id:H.id,show:ze,height:sg(H.id,Be.get(H.id)??-1,ue.current,Vl(H.role,H.customType)),containerRef:B,onMeasured:_,lazyRef:Q,children:s.jsx(Br,{uiMessageActions:f,uiContextMessage:x,onUiAction:v,message:H,qnIndex:Ke,qnActive:Ke!==void 0?Ke===oe:void 0,onJump:Fe,toolResults:F,liveOutputs:Gr(H)?t:qr,toolStatuses:n,streaming:e.isStreaming,onKillBash:i,onRetry:H.id===U?o:void 0,toolsWrap:h,thinkingWrap:p,isLast:H.id===U,onEdit:a,questionAttachments:T.get(H.id),onCollapse:je?Ie:void 0,searchActive:Y,autoExpand:H.id===Re},H.id)},H.id)}),e.streamingMessage&&s.jsx(Br,{uiMessageActions:f,uiContextMessage:x,onUiAction:v,message:e.streamingMessage,toolResults:F,liveOutputs:Gr(e.streamingMessage)?t:qr,toolStatuses:n,streaming:!0,isLast:!0,onEdit:a,onKillBash:i,toolsWrap:h,thinkingWrap:p,searchActive:Y},e.streamingMessage.id),e.retry&&e.isStreaming&&s.jsxs("div",{className:"retry-notice",role:"status",title:e.retry.errorMessage||void 0,children:[s.jsx("span",{className:"retry-pulse"}),s.jsx("span",{className:"retry-text",children:e.retry.maxAttempts>0?N("retryingApi",{attempt:Math.max(1,e.retry.attempt),max:e.retry.maxAttempts,error:e.retry.errorMessage}):N("retryingApiSoon",{error:e.retry.errorMessage})})]}),e.compaction&&s.jsx(vg,{compaction:e.compaction}),e.isStreaming&&j.length===0&&s.jsx("div",{className:"streaming-wait",children:N("waitingResponse")}),e.queue.steering.map((H,te)=>s.jsx(Yr,{kind:"steer",text:H,onRemoveQueued:l,onRecallQueued:u},`q-steer-${te}`)),e.queue.followUp.map((H,te)=>s.jsx(Yr,{kind:"followUp",text:H,onRemoveQueued:l,onRecallQueued:u},`q-fu-${te}`))]}),!X&&s.jsxs("button",{type:"button",className:"scroll-bottom",onClick:$e,children:[s.jsx(So,{})," ",N("backToBottom")]}),s.jsx(dg,{containerRef:B,messages:j,collapsedIds:D,toolResults:F,onExpand:Te,onProgrammaticScroll:()=>{$.current=!0,A.current=!1,K(!1)},open:Y,onClose:()=>J(!1)}),V.length>0&&s.jsxs("div",{className:`qn-rail ${$t?"many":""}`,ref:we,"aria-label":N("questionNavTitle"),style:{"--rail-gap":`${At}px`},children:[V.map((H,te)=>s.jsx("button",{type:"button",className:`qn-bar ${te===oe?"active":""}`,"aria-label":`${te+1}. ${H.text}`,onClick:()=>Fe(H.id),children:s.jsxs("span",{className:"qn-bar-text",children:[te+1,". ",H.text]})},H.id)),$t&&s.jsx("div",{className:"qn-list",children:V.map((H,te)=>s.jsxs("button",{type:"button",className:`qn-list-item ${te===oe?"active":""}`,"aria-label":`${te+1}. ${H.text}`,onClick:()=>Fe(H.id),children:[s.jsx("span",{className:"qn-list-idx",children:te+1}),s.jsx("span",{className:"qn-list-text",children:H.text})]},H.id))})]})]})}function zr(e,t){return t?e.trim()?`${e.replace(/\s+$/,"")}
338
- ${t}`:t:e}function Vr(e){return e.key?`key:${e.key}`:e.path?`${e.path}|${e.mode}|${e.lines?`${e.lines.start}-${e.lines.end}`:""}`:null}function wg(e,t){if(t.length===0)return e;if(e.length===0)return[...t];const n=new Set(e.map(Vr).filter(i=>i!==null)),a=[...e];for(const i of t){const o=Vr(i);if(o!==null){if(n.has(o))continue;n.add(o)}a.push(i)}return a}const Sg=1,_g="​";function Ag(e,t,n=Sg){return{first:e<=n,last:Math.abs(t-e)<=n}}function Ig(e,t){return{first:!e.slice(0,t).includes(`
337
+ `)}function ig(e,t){let n=0,a=e.indexOf(t);for(;a!==-1;)n++,a=e.indexOf(t,a+t.length);return n}function rg(e,t,n,a){const i=new Map,o=n.toLowerCase();if(!o)return i;for(const l of e){if(!t.has(l.id))continue;const u=ig(ag(l,a).toLowerCase(),o);u>0&&i.set(l.id,u)}return i}function og(e,t){const n=[],a=t.toLowerCase();if(!a)return n;const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(o){const l=o.parentElement;return!l||l.closest(".search-bar")||l.closest(".msg-collapsed")?NodeFilter.FILTER_REJECT:(o.textContent??"").toLowerCase().includes(a)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let o=i.nextNode();o;o=i.nextNode()){const l=(o.textContent??"").toLowerCase();if(!o.parentElement?.closest("[data-msg-id]"))continue;let u=l.indexOf(a);for(;u!==-1;){const p=document.createRange();p.setStart(o,u),p.setEnd(o,u+a.length),n.push(p),u=l.indexOf(a,u+a.length)}}return n}function lg(e,t,n,a,i){const o=rg(n,a,t,i),l=new Map;for(const p of og(e,t)){const h=p.startContainer.parentElement?.closest("[data-msg-id]");if(!h?.dataset.msgId)continue;const b=l.get(h.dataset.msgId);b?b.push(p):l.set(h.dataset.msgId,[p])}const u=[];for(const p of n){const h=l.get(p.id);if(h)for(let m=0;m<h.length;m++)u.push({kind:"dom",range:h[m],msgId:p.id,k:m});const b=o.get(p.id);if(b)for(let m=0;m<b;m++)u.push({kind:"folded",msgId:p.id,k:m})}return u}function ka(e,t){return e.findIndex(n=>n.msgId===t.msgId&&n.k===t.k)}function Nt(e,t){const n=CSS;if(!n.highlights)return;if(t.length===0){n.highlights.delete(e);return}const a=window.Highlight;a&&n.highlights.set(e,new a(...t))}function cg(e,t){const n=[];let a=e;for(;a&&a!==t;){const i=getComputedStyle(a);/(auto|scroll|hidden)/.test(i.overflowY+i.overflowX)&&(a.scrollHeight>a.clientHeight||a.scrollWidth>a.clientWidth)&&n.push(a),a=a.parentElement}return n}function ug(e,t){const n=t.startContainer.parentElement;for(const u of cg(n,e)){const p=t.getBoundingClientRect(),h=u.getBoundingClientRect();if(p.height<=0||p.width<=0)return;p.top>=h.top+4&&p.bottom<=h.bottom-4||(u.scrollTop+=p.top-h.top-(u.clientHeight-p.height)/2),p.left>=h.left+4&&p.right<=h.right-4||(u.scrollLeft+=p.left-h.left-(u.clientWidth-p.width)/2)}const a=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(a.height<=0||a.width<=0)return;const o=a.top>=i.top+6&&a.bottom<=i.bottom-6,l=a.left>=i.left+6&&a.right<=i.right-6;o&&l||(o||(e.scrollTop+=a.top-i.top-(i.height-a.height)/2),l||(e.scrollLeft+=a.left-i.left-(i.width-a.width)/2))}function dg({containerRef:e,messages:t,collapsedIds:n,toolResults:a,onExpand:i,onProgrammaticScroll:o,open:l,onClose:u}){const p=Pe(),h=c.useRef(null),[b,m]=c.useState(""),[f,x]=c.useState(null),[v,N]=c.useState(0),[,B]=c.useState(0),V=c.useDeferredValue(b),W=l?V.trim():"",I=c.useRef(null);I.current=f;const j=c.useRef([]),X=c.useRef({key:null}),w=c.useRef("");c.useEffect(()=>{l&&(x(null),requestAnimationFrame(()=>h.current?.select()))},[l]),c.useEffect(()=>{if(!l)return;const $=K=>{K.key==="Escape"&&(K.preventDefault(),K.stopPropagation(),u())};return window.addEventListener("keydown",$,!0),()=>window.removeEventListener("keydown",$,!0)},[l,u]),c.useEffect(()=>(l||(Nt("msg-search",[]),Nt("msg-search-active",[])),()=>{Nt("msg-search",[]),Nt("msg-search-active",[])}),[l]),c.useLayoutEffect(()=>{const $=()=>{N(0),x(null),B(0),j.current=[],Nt("msg-search",[]),Nt("msg-search-active",[]),X.current={key:null},w.current=""};if(!l||!W){$();return}const K=e.current;if(!K)return;let J=!1,L=0;return L=requestAnimationFrame(()=>{if(J)return;const H=lg(K,W,t,n,a);j.current=H;const T=H.length;if(N(T),T===0){x(null),B(0),Nt("msg-search",[]),Nt("msg-search-active",[]),X.current={key:null},w.current=W;return}const F=I.current;let Y;if(F){if(Y=ka(H,F),Y===-1){const S=[];for(let de=0;de<H.length;de++)H[de].msgId===F.msgId&&S.push(de);if(S.length>0){const de=Math.min(F.k,S.length-1);Y=S[de]}else Y=0}}else Y=0;Y<0&&(Y=0),Y>=T&&(Y=T-1),(!F||F.msgId!==H[Y].msgId||F.k!==H[Y].k)&&x({msgId:H[Y].msgId,k:H[Y].k}),B(Y);const D=H[Y],ae=X.current,ee=ae.key?.msgId!==D.msgId||ae.key?.k!==D.k||ae.kind==="folded"&&D.kind==="dom"||W!==w.current;X.current={key:{msgId:D.msgId,k:D.k},kind:D.kind},w.current=W;const ve=H.filter(S=>S.kind==="dom").map(S=>S.range);if(Nt("msg-search",ve),D.kind==="folded"){Nt("msg-search-active",[]),ee&&i(D.msgId);return}Nt("msg-search-active",[D.range]),ee&&(o?.(),ug(K,D.range))}),()=>{J=!0,cancelAnimationFrame(L)}},[l,W,t,e,f,n,a,i,o]);const ce=c.useCallback($=>{const K=j.current,J=K.length;if(J===0)return;const L=I.current,H=L?ka(K,L):0,T=K[(H+$+J)%J];x(T.kind==="dom"||T.kind==="folded"?{msgId:T.msgId,k:T.k}:null)},[]);if(!l)return null;const be=f?(()=>{const $=ka(j.current,f);return $===-1?0:$})():0;return s.jsxs("div",{className:"search-bar",role:"search",children:[s.jsx("input",{ref:h,className:"search-input",type:"text",value:b,placeholder:p("searchPlaceholder"),onChange:$=>{m($.target.value)},onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),ce($.shiftKey?-1:1))}}),s.jsx("span",{className:`search-count ${v===0?"empty":""}`,children:v===0?p("searchNoResults"):`${Math.min(be+1,v)}/${v}`}),s.jsx("button",{type:"button",className:"search-btn",title:p("searchPrev"),disabled:v===0,onClick:()=>ce(-1),children:s.jsx(Zn,{})}),s.jsx("button",{type:"button",className:"search-btn",title:p("searchNext"),disabled:v===0,onClick:()=>ce(1),children:s.jsx(Vt,{})}),s.jsx("button",{type:"button",className:"search-btn",title:p("searchClose"),onClick:u,children:s.jsx(tt,{})})]})}function pg(e){const{dSt:t,dSh:n,escaped:a,graceActive:i,stuck:o}=e;return i?{flipEscape:!1,reassert:!1}:t>=-4||t<=-500?{flipEscape:!1,reassert:!1}:n<0?{flipEscape:!1,reassert:o&&!a}:{flipEscape:!0,reassert:!1}}const Jl="pi-web-model-usage";function mg(e){if(!e||typeof e!="object")return{};const t={};for(const[n,a]of Object.entries(e)){const i=typeof a=="number"?Math.floor(a):0;Number.isFinite(i)&&i>0&&(t[n]=i)}return t}function hg(e,t){return t?{...e,[t]:(e[t]??0)+1}:e}function fg(e,t){const n=t;return e.map((a,i)=>({m:a,i,count:n[a.id]??0})).sort((a,i)=>i.count-a.count||a.i-i.i).map(a=>a.m)}function Zl(){try{const e=localStorage.getItem(Jl);return e?mg(JSON.parse(e)):{}}catch{return{}}}function gg(e){try{localStorage.setItem(Jl,JSON.stringify(e))}catch{}}function Yn(e){const t=hg(Zl(),e);return gg(t),t}const ec=[{id:"setup-matt-pocock-skills",icon:"🛠",titleKey:"tpl.sk.setup",descKey:"tpl.sk.setup.desc",promptKey:"tpl.sk.setup.prompt"},{id:"ask-matt",icon:"🧭",titleKey:"tpl.sk.ask",descKey:"tpl.sk.ask.desc",promptKey:"tpl.sk.ask.prompt"},{id:"grill-with-docs",icon:"🗣",titleKey:"tpl.sk.grilldocs",descKey:"tpl.sk.grilldocs.desc",promptKey:"tpl.sk.grilldocs.prompt"},{id:"to-spec",icon:"📝",titleKey:"tpl.sk.tospec",descKey:"tpl.sk.tospec.desc",promptKey:"tpl.sk.tospec.prompt"},{id:"to-tickets",icon:"🎫",titleKey:"tpl.sk.totickets",descKey:"tpl.sk.totickets.desc",promptKey:"tpl.sk.totickets.prompt"},{id:"implement",icon:"🏗",titleKey:"tpl.sk.implement",descKey:"tpl.sk.implement.desc",promptKey:"tpl.sk.implement.prompt"},{id:"code-review",icon:"🧹",titleKey:"tpl.sk.codeview",descKey:"tpl.sk.codeview.desc",promptKey:"tpl.sk.codeview.prompt"},{id:"wayfinder",icon:"🗺",titleKey:"tpl.sk.wayfinder",descKey:"tpl.sk.wayfinder.desc",promptKey:"tpl.sk.wayfinder.prompt"},{id:"prototype",icon:"🔬",titleKey:"tpl.sk.prototype",descKey:"tpl.sk.prototype.desc",promptKey:"tpl.sk.prototype.prompt"},{id:"research",icon:"📚",titleKey:"tpl.sk.research",descKey:"tpl.sk.research.desc",promptKey:"tpl.sk.research.prompt"},{id:"improve-codebase-architecture",icon:"🏛",titleKey:"tpl.sk.arch",descKey:"tpl.sk.arch.desc",promptKey:"tpl.sk.arch.prompt"},{id:"diagnosing-bugs",icon:"🐛",titleKey:"tpl.sk.debug",descKey:"tpl.sk.debug.desc",promptKey:"tpl.sk.debug.prompt"},{id:"resolving-merge-conflicts",icon:"🔀",titleKey:"tpl.sk.merge",descKey:"tpl.sk.merge.desc",promptKey:"tpl.sk.merge.prompt"},{id:"triage",icon:"🗂",titleKey:"tpl.sk.triage",descKey:"tpl.sk.triage.desc",promptKey:"tpl.sk.triage.prompt"},{id:"wizard",icon:"✨",titleKey:"tpl.sk.wizard",descKey:"tpl.sk.wizard.desc",promptKey:"tpl.sk.wizard.prompt"},{id:"grill-me",icon:"🔍",titleKey:"tpl.sk.grillme",descKey:"tpl.sk.grillme.desc",promptKey:"tpl.sk.grillme.prompt"},{id:"handoff",icon:"🤝",titleKey:"tpl.sk.handoff",descKey:"tpl.sk.handoff.desc",promptKey:"tpl.sk.handoff.prompt"},{id:"to-questionnaire",icon:"📋",titleKey:"tpl.sk.questionnaire",descKey:"tpl.sk.questionnaire.desc",promptKey:"tpl.sk.questionnaire.prompt"},{id:"teach",icon:"🎓",titleKey:"tpl.sk.teach",descKey:"tpl.sk.teach.desc",promptKey:"tpl.sk.teach.prompt"},{id:"wait-what",icon:"💬",titleKey:"tpl.sk.ww",descKey:"tpl.sk.ww.desc",promptKey:"tpl.sk.ww.prompt"},{id:"writing-for-agents",icon:"📄",titleKey:"tpl.sk.wfa",descKey:"tpl.sk.wfa.desc",promptKey:"tpl.sk.wfa.prompt"},{id:"codebase-design",icon:"🧱",titleKey:"tpl.sk.codesign",descKey:"tpl.sk.codesign.desc",promptKey:"tpl.sk.codesign.prompt"},{id:"domain-modeling",icon:"🏷",titleKey:"tpl.sk.domain",descKey:"tpl.sk.domain.desc",promptKey:"tpl.sk.domain.prompt"},{id:"grilling",icon:"🔥",titleKey:"tpl.sk.grilling",descKey:"tpl.sk.grilling.desc",promptKey:"tpl.sk.grilling.prompt"},{id:"tdd",icon:"🧪",titleKey:"tpl.sk.tdd",descKey:"tpl.sk.tdd.desc",promptKey:"tpl.sk.tdd.prompt"}],tc="pi-web-ui:prompt-templates";function bg(){try{const e=localStorage.getItem(tc);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>!!n&&typeof n=="object"&&typeof n.id=="string"):[]}catch{return[]}}function Wr(e){return ec.some(t=>t.id===e)}function dn(e){return typeof e.title=="string"}const sc=c.createContext(null);function nc(){const e=c.useContext(sc);if(!e)throw new Error("useTemplates must be used within TemplateProvider");return e}function Eg({children:e,currentModelId:t}){const n=Pe(),[a,i]=c.useState(bg),[o,l]=c.useState(!1),[u,p]=c.useState(null),[h,b]=c.useState(!1),[m,f]=c.useState(!1),[x,v]=c.useState(!1);c.useEffect(()=>{try{localStorage.setItem(tc,JSON.stringify(a))}catch{}},[a]);const N=c.useMemo(()=>{const H=new Map,T=new Set;for(const D of a)D.hidden?T.add(D.id):(dn(D)&&!Wr(D.id)||dn(D))&&H.set(D.id,D);const F=ec.filter(D=>!T.has(D.id)).map(D=>{const ae=H.get(D.id);return{id:D.id,icon:ae?.icon??D.icon,title:ae?.title??n(D.titleKey),desc:ae?.desc??n(D.descKey),prompt:ae?.prompt??n(D.promptKey),builtin:!0}}),Y=a.filter(D=>dn(D)&&!Wr(D.id)).map(D=>({id:D.id,icon:D.icon??"📌",title:D.title??"",desc:D.desc??"",prompt:D.prompt??""}));return[...F,...Y]},[a,n]),B=c.useCallback(()=>l(!0),[]),V=c.useCallback(H=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:H}))},[]),W=c.useCallback((H,T=!1)=>{v(T),H?(b(!1),p({...H})):(b(!0),p({id:St(),icon:"📌",title:"",desc:"",prompt:""}))},[]),I=c.useCallback(()=>{l(!1),p(null),v(!1)},[]),j=c.useCallback(()=>{m?(i([]),f(!1)):(f(!0),setTimeout(()=>f(!1),5e3))},[m]),X=c.useCallback(H=>{l(!1),V(H.prompt)},[V]),w=c.useCallback(H=>{l(!1),W(H,!0)},[W]),ce=c.useCallback(()=>{l(!1),W(void 0,!0)},[W]),be=c.useCallback(H=>{i(T=>{const F=T.findIndex(Y=>Y.id===H.id);if(F>=0){const Y=[...T];return Y[F]=H,Y}return[...T,H]}),p(null),x&&(l(!0),v(!1))},[x]),$=c.useCallback(H=>{i(T=>H.builtin?[...T.filter(Y=>Y.id!==H.id),{id:H.id,hidden:!0}]:T.filter(F=>F.id!==H.id)),p(null),x&&(l(!0),v(!1))},[x]),K=c.useCallback(H=>{i(T=>T.filter(F=>F.id!==H.id||F.hidden)),p(null),x&&(l(!0),v(!1))},[x]),J=c.useMemo(()=>({templates:N,fill:V,openPicker:B,openEdit:W,resetConfirm:m,toggleReset:j}),[N,V,B,W,m,j]),L=u?a.some(H=>H.id===u.id&&!H.hidden&&dn(H)):!1;return s.jsxs(sc.Provider,{value:J,children:[e,o&&s.jsx(xg,{templates:N,resetConfirm:m,onFill:X,onEditTpl:w,onNew:ce,onResetToggle:j,onClose:I}),u&&s.jsx(yg,{editing:u,isNew:h,hasOverride:L,onDraft:p,onSave:be,onRestore:()=>K(u),onRemove:()=>$(u),onFill:()=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:u.prompt})),I()},onSend:()=>{const H=u.prompt.trim();H&&ie({type:"prompt",text:H,queue:!1})&&(t&&Yn(t),I())},onClose:I})]})}function Tg(){const e=Pe(),{templates:t,fill:n,openEdit:a,toggleReset:i,resetConfirm:o}=nc();return s.jsxs("div",{className:"empty-templates",children:[s.jsxs("div",{className:"empty-templates-head",children:[s.jsx("span",{className:"empty-templates-title",children:e("tpl.title")}),s.jsx("span",{className:"empty-templates-hint",children:e("tpl.hint")})]}),s.jsxs("div",{className:"empty-templates-grid",children:[t.map(l=>s.jsx(ac,{tpl:l,title:e("tpl.clickCard"),onFill:()=>n(l.prompt),onEdit:()=>a(l),editTitle:e("tpl.editTpl")},l.id)),s.jsxs("button",{type:"button",className:"empty-template add",onClick:()=>a(),title:e("tpl.add"),children:[s.jsx("span",{className:"empty-template-icon",children:s.jsx(yt,{})}),s.jsxs("span",{className:"empty-template-main",children:[s.jsx("span",{className:"empty-template-title",children:e("tpl.add")}),s.jsx("span",{className:"empty-template-desc",children:e("tpl.addDesc")})]})]})]}),s.jsx("div",{className:"empty-templates-foot",children:s.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:i,children:[s.jsx(vo,{}),e(o?"tpl.resetConfirm":"tpl.reset")]})})]})}function ac({tpl:e,title:t,onFill:n,onEdit:a,editTitle:i}){const o=Pe();return s.jsxs("button",{type:"button",className:"empty-template",title:t,onClick:n,children:[s.jsx("span",{className:"empty-template-icon",children:e.icon}),s.jsxs("span",{className:"empty-template-main",children:[s.jsx("span",{className:"empty-template-title",children:e.title}),s.jsx("span",{className:"empty-template-desc",children:e.desc})]}),s.jsx("span",{className:"template-card-ops",role:"button",title:i??o("tpl.editTpl"),onClick:l=>{l.stopPropagation(),a()},children:s.jsx(Rn,{})})]})}function xg({templates:e,resetConfirm:t,onFill:n,onEditTpl:a,onNew:i,onResetToggle:o,onClose:l}){const u=Pe();return c.useEffect(()=>{const p=h=>{h.key==="Escape"&&l()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[l]),s.jsx("div",{className:"modal-backdrop",onClick:l,children:s.jsxs("div",{className:"modal template-picker",onClick:p=>p.stopPropagation(),children:[s.jsxs("div",{className:"template-picker-top",children:[s.jsxs("div",{className:"template-picker-head",children:[s.jsx("span",{className:"template-picker-title",children:u("tpl.pickerTitle")}),s.jsx("button",{type:"button",className:"btn template-modal-close",title:u("close"),onClick:l,children:s.jsx(tt,{})})]}),s.jsx("div",{className:"template-picker-hint",children:u("tpl.pickerHint")})]}),s.jsx("div",{className:"template-picker-scroll",children:s.jsxs("div",{className:"template-picker-grid",children:[e.map(p=>s.jsx(ac,{tpl:p,title:u("tpl.clickCard"),onFill:()=>n(p),onEdit:()=>a(p),editTitle:u("tpl.editTpl")},p.id)),s.jsxs("button",{type:"button",className:"empty-template add",onClick:i,title:u("tpl.add"),children:[s.jsx("span",{className:"empty-template-icon",children:s.jsx(yt,{})}),s.jsxs("span",{className:"empty-template-main",children:[s.jsx("span",{className:"empty-template-title",children:u("tpl.add")}),s.jsx("span",{className:"empty-template-desc",children:u("tpl.addDesc")})]})]})]})}),s.jsx("div",{className:"template-picker-foot",children:s.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:o,children:[s.jsx(vo,{}),u(t?"tpl.resetConfirm":"tpl.reset")]})})]})})}function yg({editing:e,isNew:t,hasOverride:n,onDraft:a,onSave:i,onRestore:o,onRemove:l,onFill:u,onSend:p,onClose:h}){const b=Pe(),m=c.useRef(null);c.useEffect(()=>{const v=N=>{N.key==="Escape"&&h()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[h]),c.useEffect(()=>{const v=m.current;if(!v)return;v.style.height="auto";const N=v.scrollHeight>300;v.style.height=`${Math.min(v.scrollHeight,300)}px`,v.style.overflowY=N?"auto":"hidden"},[e.prompt]);const f=()=>{const v=e.title.trim(),N=e.prompt.trim();if(!v||!N){a({...e,error:b("tpl.required")});return}i({id:e.id,icon:e.icon.trim()||"📌",title:v,desc:e.desc.trim(),prompt:N})},x=!!e.builtin&&!t;return s.jsx("div",{className:"modal-backdrop",onClick:h,children:s.jsxs("div",{className:"modal template-modal",onClick:v=>v.stopPropagation(),children:[s.jsxs("div",{className:"template-modal-head",children:[s.jsx("span",{className:"template-modal-icon",children:e.icon}),s.jsx("span",{className:"template-modal-badge",children:b(x?"tpl.builtin":"tpl.custom")}),s.jsx("span",{className:"template-modal-title",children:b(t?"tpl.newTitle":"tpl.editTitle")}),s.jsx("button",{type:"button",className:"btn template-modal-close",title:b("close"),onClick:h,children:s.jsx(tt,{})})]}),s.jsxs("div",{className:"template-modal-body",children:[s.jsxs("label",{className:"template-field",children:[s.jsx("span",{className:"template-field-label",children:b("tpl.fieldIcon")}),s.jsx("input",{className:"template-field-input icon",value:e.icon,maxLength:4,onChange:v=>a({...e,icon:v.target.value})})]}),s.jsxs("label",{className:"template-field",children:[s.jsx("span",{className:"template-field-label",children:b("tpl.fieldTitle")}),s.jsx("input",{className:"template-field-input",value:e.title,placeholder:b("tpl.fieldTitlePh"),onChange:v=>a({...e,title:v.target.value})})]}),s.jsxs("label",{className:"template-field",children:[s.jsx("span",{className:"template-field-label",children:b("tpl.fieldDesc")}),s.jsx("input",{className:"template-field-input",value:e.desc,placeholder:b("tpl.fieldDescPh"),onChange:v=>a({...e,desc:v.target.value})})]}),s.jsxs("label",{className:"template-field",children:[s.jsx("span",{className:"template-field-label",children:b("tpl.fieldPrompt")}),s.jsx("textarea",{ref:m,className:"template-field-prompt",value:e.prompt,placeholder:b("tpl.fieldPromptPh"),onChange:v=>a({...e,prompt:v.target.value})})]})]}),e.error&&s.jsx("div",{className:"template-error",children:e.error}),s.jsxs("div",{className:"template-modal-actions",children:[s.jsxs("div",{className:"template-modal-actions-left",children:[!t&&x&&n&&s.jsx("button",{type:"button",className:"btn template-btn ghost",title:b("tpl.restoreTip"),onClick:o,children:b("tpl.restore")}),!t&&x&&s.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:b("tpl.removeTip"),onClick:l,children:[s.jsx(dt,{})," ",b("tpl.remove")]}),!t&&!x&&s.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:b("tpl.deleteTip"),onClick:l,children:[s.jsx(dt,{})," ",b("tpl.delete")]})]}),s.jsxs("div",{className:"template-modal-actions-right",children:[s.jsx("button",{type:"button",className:"btn template-btn",onClick:f,children:b("tpl.save")}),s.jsx("button",{type:"button",className:"btn template-btn fill",onClick:u,title:b("tpl.fillTip"),children:b("tpl.fill")}),s.jsxs("button",{type:"button",className:"btn template-btn send",onClick:p,title:b("tpl.sendTip"),children:[s.jsx(Aa,{})," ",b("tpl.sendNow")]})]})]})]})})}const Kr=new Map,kg=15,Yr=30,Na=250,Gr=1200,Ng=1600;function zr({kind:e,text:t,onRemoveQueued:n,onRecallQueued:a}){const i=Pe();return s.jsxs("div",{className:"msg msg-user msg-queued","data-role":"user",children:[s.jsxs("div",{className:"msg-meta",children:[s.jsx("span",{className:"msg-role",children:i("role.user")}),s.jsx("span",{className:`queued-tag ${e==="steer"?"steer":"follow"}`,children:i(e==="steer"?"queueSteerTag":"queueFollowTag")}),s.jsxs("div",{className:"msg-queued-actions",children:[a&&s.jsx("button",{type:"button",className:"msg-queued-recall",title:i("queueRecallTip"),"aria-label":i("queueRecallTip"),onClick:()=>a(e,t),children:"↩"}),n&&s.jsx("button",{type:"button",className:"msg-queued-remove",title:i("queueRemoveTip"),"aria-label":i("queueRemoveTip"),onClick:()=>n(e,t),children:"✕"})]})]}),s.jsx("div",{className:"msg-body",children:s.jsx("div",{className:"msg-text",children:s.jsx(pt,{text:t,hardBreaks:!0})})})]})}function vg({compaction:e}){const t=Pe(),[,n]=c.useState(0);c.useEffect(()=>{const o=setInterval(()=>n(l=>l+1),1e3);return()=>clearInterval(o)},[]);const a=Math.max(0,Math.floor((Date.now()-e.startedAt)/1e3)),i=e.reason==="manual"?t("compactingReasonManual"):e.reason==="overflow"?t("compactingReasonOverflow"):t("compactingReasonThreshold");return s.jsxs("div",{className:"compact-notice",role:"status",children:[s.jsx("span",{className:"compact-pulse"}),s.jsxs("span",{className:"compact-text",children:[t("compactingContext")," · ",a,"s"]}),s.jsx("span",{className:"compact-reason",children:i})]})}function Vr(e){return e.content.some(t=>t.type==="toolCall")}function Cg({state:e,liveOutputs:t,toolStatuses:n,onEdit:a,onKillBash:i,onRetry:o,onRemoveQueued:l,onRecallQueued:u,thinkingWrap:p,toolsWrap:h,jumpTarget:b,onJumpDone:m,uiMessageActions:f,uiContextMessage:x,onUiAction:v}){const N=Pe(),B=c.useRef(null),[V,W]=c.useState(!0),I=c.useRef(!0),j=c.useRef(0),X=c.useRef(0),w=c.useRef(!1),ce=c.useRef(0),[be,$]=c.useState(()=>new Set),[K,J]=c.useState(!1),L=e.streamingMessage?[...e.messages,e.streamingMessage]:e.messages,H=c.useMemo(()=>{const U=new Map;for(const te of e.messages)te.role==="toolResult"&&te.toolCallId&&U.set(te.toolCallId,te);return U},[e.messages]),T=c.useMemo(()=>G0(e.messages),[e.messages]),F=L.length>0?L[L.length-1].id:null,Y=e.messages.length>Yr?Math.max(0,e.messages.length-kg):0,D=c.useMemo(()=>{const U=new Set;for(let te=0;te<Y;te++){const je=e.messages[te];je.role!=="toolResult"&&(be.has(je.id)||U.add(je.id))}return U},[e.messages,Y,be]),[ae,ee]=c.useState(()=>new Set),[ve,S]=c.useState(()=>new Set),de=c.useRef(new Map),ue=c.useRef(new Map),pe=c.useRef(new Map),ke=c.useRef(0),Oe=c.useMemo(()=>{const U=new Map;for(const te of e.messages)U.set(te.id,tg(te));return U},[e.messages]),ye=c.useRef(Oe);ye.current=Oe;const we=c.useRef(ae);we.current=ae;const Ce=e.messages.length>Yr&&!K,qe=c.useRef(Ce);qe.current=Ce;const Be=Z0(e.messages,de.current,Ng),se=c.useRef(Be);se.current=Be;const Te=c.useCallback(()=>{const U=B.current;if(!U)return;if(!qe.current){ee(Ve=>Ve.size?new Set:Ve);return}const te=U.getBoundingClientRect(),je={top:te.top-Gr,bottom:te.bottom+Gr},_e=[];for(const[Ve,bt]of pe.current){const Et=bt.getBoundingClientRect();_e.push({id:Ve,top:Et.top,bottom:Et.bottom}),we.current.has(Ve)||Ye(Ve,Et.bottom-Et.top,ye.current.get(Ve))}const We=X0(_e,je,se.current,we.current);for(const Ve of We.hide){const bt=pe.current.get(Ve);bt&&Ye(Ve,bt.offsetHeight,ye.current.get(Ve))}ee(Ve=>J0(Ve,We))},[]),De=c.useCallback(()=>{ke.current||(ke.current=requestAnimationFrame(()=>{ke.current=0,Te()}))},[Te]);c.useLayoutEffect(()=>{Te()},[Te]);const Re=c.useRef(K);c.useLayoutEffect(()=>{Re.current&&!K&&Te(),Re.current=K},[K,Te]);const Ye=c.useCallback((U,te,je)=>{je!==void 0&&(ue.current.set(U,{h:te,len:je}),de.current.set(U,te))},[]),A=c.useCallback((U,te)=>{Ye(U,te,ye.current.get(U))},[Ye]),Q=c.useCallback(U=>{U&&pe.current.set(U.dataset.lazyId??"",U)},[]);c.useEffect(()=>{const U=new Set(e.messages.map(te=>te.id));for(const te of pe.current.keys())U.has(te)||(pe.current.delete(te),de.current.delete(te),ue.current.delete(te));ee(te=>{let je=!1;const _e=new Set;for(const We of te)U.has(We)?_e.add(We):je=!0;return je?_e:te})},[e.messages,be]),c.useEffect(()=>()=>cancelAnimationFrame(ke.current),[]);const z=c.useMemo(()=>{const U=[];for(const te of e.messages){if(te.role!=="user")continue;const je=te.content.map(Ve=>as(Ve)?.text??"").filter(Boolean).join(" "),_e=fi(je),We=_e?_e.userMessage??`skill:${_e.name}`:je.trim();We&&U.push({id:te.id,text:We})}return U},[e.messages]),ge=c.useMemo(()=>{const U=new Map;return z.forEach((te,je)=>U.set(te.id,je)),U},[z]),[oe,Z]=c.useState(-1),y=c.useRef(-1),P=c.useRef(z);c.useEffect(()=>{P.current=z},[z]);const le=c.useCallback(()=>{const U=B.current,te=P.current;if(!U||te.length===0)return;const je=U.getBoundingClientRect().top,_e=140;let We=-1;for(let Ve=0;Ve<te.length;Ve++){const bt=U.querySelector(`[data-msg-id="${te[Ve].id}"]`);if(bt)if(bt.getBoundingClientRect().top<=je+_e)We=Ve;else break}We!==y.current&&(y.current=We,Z(We))},[]);c.useEffect(()=>{le()},[z,le]);const Ee=c.useCallback(U=>{$(te=>te.has(U)?te:new Set(te).add(U))},[]);c.useEffect(()=>{const U=te=>{if(!(te.ctrlKey||te.metaKey)||te.key.toLowerCase()!=="f")return;const je=te.target;je&&(je.tagName==="INPUT"||je.tagName==="TEXTAREA"||je.isContentEditable)||(te.preventDefault(),J(!0))};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[]);const Ae=c.useCallback(U=>{$(te=>{if(!te.has(U))return te;const je=new Set(te);return je.delete(U),je})},[]),Me=c.useCallback(U=>{const te=e.messages.findIndex(_e=>_e.id===U);ta.flushSync(()=>{te>=0&&te<Y&&!be.has(U)&&Ee(U),S(_e=>_e.has(U)?_e:new Set(_e).add(U))});const je=P.current.findIndex(_e=>_e.id===U);y.current=je,Z(je),requestAnimationFrame(()=>{const _e=B.current?.querySelector(`[data-msg-id="${U}"]`);_e&&(B.current?.querySelectorAll(".msg-flash").forEach(We=>We.classList.remove("msg-flash")),_e.scrollIntoView({block:"start"}),_e.classList.remove("msg-flash"),_e.offsetWidth,_e.classList.add("msg-flash"),_e!==B.current?.lastElementChild&&(w.current=!0))})},[e.messages,Y,be,Ee]),[Le,Ge]=c.useState(null),R=c.useRef(null),He=c.useRef(null);c.useEffect(()=>{const U=R.current;if(!U||U.convId!==e.conversationId){R.current={convId:e.conversationId,ids:new Set(e.messages.filter(te=>te.role==="compactionSummary").map(te=>te.id))},He.current=null,Ge(null);return}for(const te of e.messages)if(te.role==="compactionSummary"&&!U.ids.has(te.id)){U.ids.add(te.id),Ge(te.id);break}},[e.messages,e.conversationId]),c.useEffect(()=>{!Le||He.current===Le||(He.current=Le,Me(Le))},[Le,Me]);const C=c.useMemo(()=>b?e.messages.find(U=>U.role===b.role&&U.timestamp===b.timestamp)?.id??null:null,[e.messages,b]);c.useEffect(()=>{if(b){if(C){Me(C),m?.();return}e.sessionFile===b.path&&e.messages.length>0&&m?.()}},[C,Me,m,b,e.sessionFile,e.messages.length]);const _=c.useCallback(()=>{const U=B.current;if(!U)return;const te=U.scrollTop-j.current,je=U.scrollHeight-X.current;j.current=U.scrollTop,X.current=U.scrollHeight;const _e=U.scrollHeight-U.scrollTop-U.clientHeight<80,We=Date.now()<ce.current,Ve=pg({dSt:te,dSh:je,escaped:w.current,graceActive:We,stuck:I.current});Ve.reassert&&(ce.current=Date.now()+Na,U.scrollTop=U.scrollHeight),Ve.flipEscape&&(w.current=!0),_e&&te>=0&&(w.current=!1),We||(te<0?I.current=_e&&!w.current:_e&&(I.current=!0)),W(I.current),le(),De()},[le,De]),me=c.useRef(!1);c.useEffect(()=>{const U=me.current;if(me.current=!!e.isStreaming,U&&!e.isStreaming&&!w.current){const te=()=>{const _e=B.current;_e&&!w.current&&(_e.scrollTop=_e.scrollHeight,I.current=!0,W(!0))};requestAnimationFrame(()=>requestAnimationFrame(te));const je=setTimeout(te,180);return()=>clearTimeout(je)}},[e.isStreaming]),c.useEffect(()=>{const U=B.current;U&&I.current&&(U.scrollTop=U.scrollHeight)},[L,e.isStreaming,t]);const Ne=e.queue.steering.join("\0")+""+e.queue.followUp.join("\0");c.useEffect(()=>{const U=B.current;U&&I.current&&(U.scrollTop=U.scrollHeight)},[Ne]),c.useEffect(()=>{const U=B.current;if(!U||typeof ResizeObserver>"u")return;let te=U.clientHeight;const je=new ResizeObserver(()=>{const _e=U.clientHeight,We=_e-te;te=_e,We>0&&(U.scrollTop=Math.min(U.scrollTop,U.scrollHeight-U.clientHeight))});return je.observe(U),()=>je.disconnect()},[]),c.useEffect(()=>{const U=B.current;if(!U||typeof MutationObserver>"u")return;let te=!1;const je=new MutationObserver(()=>{te||(te=!0,requestAnimationFrame(()=>{te=!1;const _e=B.current;_e&&I.current&&!w.current&&(_e.scrollTop=_e.scrollHeight,W(!0))}))});return je.observe(U,{childList:!0,subtree:!0,characterData:!0}),()=>je.disconnect()},[]);const $e=c.useCallback(()=>{if(!B.current)return;I.current=!0,w.current=!1,W(!0),ce.current=Date.now()+Na;const te=()=>{const je=B.current;!je||!I.current||w.current||(ce.current=Date.now()+Na,je.scrollTop=je.scrollHeight)};te(),requestAnimationFrame(()=>requestAnimationFrame(te)),setTimeout(te,120),setTimeout(te,300),setTimeout(te,600)},[]),Ie=c.useRef(null);c.useEffect(()=>{const U=Ie.current,te=B.current;if(!U||!te)return;const je=_e=>{_e.preventDefault();const We=U.querySelector(".qn-list");if(We&&We.contains(_e.target)&&We.scrollHeight>We.clientHeight){We.scrollTop+=_e.deltaY;return}te.scrollTop+=_e.deltaY};return U.addEventListener("wheel",je,{passive:!1}),()=>U.removeEventListener("wheel",je)},[]);const[Qe,gt]=c.useState(0);c.useEffect(()=>{const U=()=>{gt(B.current?.clientHeight??0),De()};return U(),window.addEventListener("resize",U),()=>window.removeEventListener("resize",U)},[De]);const ut=z.length,Dt=c.useMemo(()=>ut===0?27:Math.max(4,Math.min(27,Math.floor(((Qe||600)-16)/ut)-3)),[ut,Qe]),Pt=Dt<20;return s.jsxs("div",{className:"messages-wrap",children:[s.jsxs("div",{className:`messages${K||V?"":" anchor-live"}`,ref:B,onScroll:_,children:[e.messages.length===0&&!e.streamingMessage&&s.jsx("div",{className:"empty-state",children:s.jsx(Tg,{})}),e.messages.map((U,te)=>{const je=te<Y,_e=je&&be.has(U.id);if(je&&!_e)return U.role==="toolResult"?null:s.jsx(z0,{message:U,onExpand:Ee},U.id);const We=U.role==="user"?ge.get(U.id):void 0,Ve=!Ce||Be.has(U.id)||ve.has(U.id)||!ae.has(U.id);return s.jsx(Q0,{id:U.id,show:Ve,height:sg(U.id,Oe.get(U.id)??-1,ue.current,Xl(U.role,U.customType)),containerRef:B,onMeasured:A,lazyRef:Q,children:s.jsx(Hr,{uiMessageActions:f,uiContextMessage:x,onUiAction:v,message:U,qnIndex:We,qnActive:We!==void 0?We===oe:void 0,onJump:Me,toolResults:H,liveOutputs:Vr(U)?t:Kr,toolStatuses:n,streaming:e.isStreaming,onKillBash:i,onRetry:U.id===F?o:void 0,toolsWrap:h,thinkingWrap:p,isLast:U.id===F,onEdit:a,questionAttachments:T.get(U.id),onCollapse:_e?Ae:void 0,searchActive:K,autoExpand:U.id===Le},U.id)},U.id)}),e.streamingMessage&&s.jsx(Hr,{uiMessageActions:f,uiContextMessage:x,onUiAction:v,message:e.streamingMessage,toolResults:H,liveOutputs:Vr(e.streamingMessage)?t:Kr,toolStatuses:n,streaming:!0,isLast:!0,onEdit:a,onKillBash:i,toolsWrap:h,thinkingWrap:p,searchActive:K},e.streamingMessage.id),e.retry&&e.isStreaming&&s.jsxs("div",{className:"retry-notice",role:"status",title:e.retry.errorMessage||void 0,children:[s.jsx("span",{className:"retry-pulse"}),s.jsx("span",{className:"retry-text",children:e.retry.maxAttempts>0?N("retryingApi",{attempt:Math.max(1,e.retry.attempt),max:e.retry.maxAttempts,error:e.retry.errorMessage}):N("retryingApiSoon",{error:e.retry.errorMessage})})]}),e.compaction&&s.jsx(vg,{compaction:e.compaction}),e.isStreaming&&L.length===0&&s.jsx("div",{className:"streaming-wait",children:N("waitingResponse")}),e.queue.steering.map((U,te)=>s.jsx(zr,{kind:"steer",text:U,onRemoveQueued:l,onRecallQueued:u},`q-steer-${te}`)),e.queue.followUp.map((U,te)=>s.jsx(zr,{kind:"followUp",text:U,onRemoveQueued:l,onRecallQueued:u},`q-fu-${te}`))]}),!V&&s.jsxs("button",{type:"button",className:"scroll-bottom",onClick:$e,children:[s.jsx(Ao,{})," ",N("backToBottom")]}),s.jsx(dg,{containerRef:B,messages:L,collapsedIds:D,toolResults:H,onExpand:Ee,onProgrammaticScroll:()=>{w.current=!0,I.current=!1,W(!1)},open:K,onClose:()=>J(!1)}),z.length>0&&s.jsxs("div",{className:`qn-rail ${Pt?"many":""}`,ref:Ie,"aria-label":N("questionNavTitle"),style:{"--rail-gap":`${Dt}px`},children:[z.map((U,te)=>s.jsx("button",{type:"button",className:`qn-bar ${te===oe?"active":""}`,"aria-label":`${te+1}. ${U.text}`,onClick:()=>Me(U.id),children:s.jsxs("span",{className:"qn-bar-text",children:[te+1,". ",U.text]})},U.id)),Pt&&s.jsx("div",{className:"qn-list",children:z.map((U,te)=>s.jsxs("button",{type:"button",className:`qn-list-item ${te===oe?"active":""}`,"aria-label":`${te+1}. ${U.text}`,onClick:()=>Me(U.id),children:[s.jsx("span",{className:"qn-list-idx",children:te+1}),s.jsx("span",{className:"qn-list-text",children:U.text})]},U.id))})]})]})}function Qr(e,t){return t?e.trim()?`${e.replace(/\s+$/,"")}
338
+ ${t}`:t:e}function Xr(e){return e.key?`key:${e.key}`:e.path?`${e.path}|${e.mode}|${e.lines?`${e.lines.start}-${e.lines.end}`:""}`:null}function wg(e,t){if(t.length===0)return e;if(e.length===0)return[...t];const n=new Set(e.map(Xr).filter(i=>i!==null)),a=[...e];for(const i of t){const o=Xr(i);if(o!==null){if(n.has(o))continue;n.add(o)}a.push(i)}return a}const Sg=1,_g="​";function Ag(e,t,n=Sg){return{first:e<=n,last:Math.abs(t-e)<=n}}function Ig(e,t){return{first:!e.slice(0,t).includes(`
339
339
  `),last:!e.slice(t).includes(`
340
- `)}}let Na=null;function jg(){if(Na?.isConnected)return Na;const e=document.createElement("div");e.setAttribute("aria-hidden","true"),e.setAttribute("data-caret-mirror","");const t=e.style;return t.position="fixed",t.top="0",t.left="-99999px",t.visibility="hidden",t.pointerEvents="none",t.margin="0",t.padding="0",t.border="0",t.boxSizing="content-box",t.overflow="visible",document.body.appendChild(e),Na=e,e}function Rg(e,t){const n=getComputedStyle(e),a=t.style;a.fontFamily=n.fontFamily,a.fontSize=n.fontSize,a.fontStyle=n.fontStyle,a.fontWeight=n.fontWeight,a.fontVariant=n.fontVariant,a.fontStretch=n.fontStretch,a.lineHeight=n.lineHeight,a.letterSpacing=n.letterSpacing,a.wordSpacing=n.wordSpacing,a.textTransform=n.textTransform,a.textIndent=n.textIndent,a.tabSize=n.tabSize,a.whiteSpace=n.whiteSpace||"pre-wrap",a.overflowWrap=n.overflowWrap||"break-word",a.wordBreak=n.wordBreak||"normal",a.direction=n.direction,a.writingMode=n.writingMode;const i=e.clientWidth-(parseFloat(n.paddingLeft)||0)-(parseFloat(n.paddingRight)||0);return i>0?(a.width=`${i}px`,i):0}function Qr(e,t){e.textContent=t;const n=document.createElement("span");return n.textContent=_g,e.appendChild(n),n.offsetTop}function Lg(e){const t=e.value,n=e.selectionStart;if(n!==e.selectionEnd)return{first:!1,last:!1};const a=Ig(t,n);if(!a.first&&!a.last||typeof document>"u"||typeof getComputedStyle!="function")return a;const i=jg();if(Rg(e,i)<=0)return a;const o=Qr(i,t.slice(0,n)),l=Qr(i,t),u=i.offsetHeight>0;return i.textContent="",!u&&t!==""?a:Ag(o,l)}const gi="pi-web-ui:prompt-history",Dg=100,nc="pi-web-ui:prompt-history-settings",Ja={maxEntries:100,charLimitEnabled:!1,charLimit:2e3};function ac(e){const t=Ja;if(!e||typeof e!="object")return{...t};const n=e;let a=typeof n.maxEntries=="number"?Math.floor(n.maxEntries):t.maxEntries;(!Number.isFinite(a)||a<1)&&(a=1),a>500&&(a=500);let i=typeof n.charLimit=="number"?Math.floor(n.charLimit):t.charLimit;(!Number.isFinite(i)||i<100)&&(i=100),i>2e4&&(i=2e4);const o=typeof n.charLimitEnabled=="boolean"?n.charLimitEnabled:t.charLimitEnabled;return{maxEntries:a,charLimitEnabled:o,charLimit:i}}function ic(){try{const e=localStorage.getItem(nc);return e?ac(JSON.parse(e)):{...Ja}}catch{return{...Ja}}}function va(e){const t=ac(e);try{localStorage.setItem(nc,JSON.stringify(t))}catch{}try{let n=Vs();t.charLimitEnabled&&(n=n.map(a=>a.length>t.charLimit?a.slice(0,t.charLimit):a)),n.length>t.maxEntries&&(n=n.slice(n.length-t.maxEntries)),rc(n)}catch{}}function Pg(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(typeof n!="string")continue;const a=n.trim();a&&t.push(a)}return t}function Og(e,t,n=Dg){const a=t.trim();if(!a||e.length>0&&e[e.length-1]===a)return e;const i=[...e,a];return i.length>n?i.slice(i.length-n):i}function Vs(){try{const e=localStorage.getItem(gi);return e?Pg(JSON.parse(e)):[]}catch{return[]}}function rc(e){let t=e;for(;t;)try{localStorage.setItem(gi,JSON.stringify(t));return}catch(n){if(!(n instanceof DOMException&&(n.name==="QuotaExceededError"||n.code===22))||t.length<=1)return;t=t.slice(Math.ceil(t.length/2))}}function Xr(e){let t=e.trim();if(!t)return;const n=ic();n.charLimitEnabled&&t.length>n.charLimit&&(t=t.slice(0,n.charLimit));const a=Vs(),i=Og(a,t,n.maxEntries);i!==a&&rc(i)}function Mg(){try{localStorage.removeItem(gi)}catch{}}const Jr="skill:";function Bg(e,t){const n=e.toLowerCase();return t==="skill"&&n.startsWith(Jr)?[n,n.slice(Jr.length)]:[n]}function Fg(e,t){const n=t.toLowerCase();return n?e.filter(a=>Bg(a.name,a.source).some(i=>i.startsWith(n))):[...e]}function Hg(e){const t=e.query;if(!t||!t("(pointer: coarse)")||!t("(hover: none)"))return!1;const n=e.userAgent??"";return!(/Windows|CrOS/i.test(n)||/Linux/i.test(n)&&!/Android/i.test(n)||/Macintosh/i.test(n)&&(e.maxTouchPoints??0)<=1)}function Ug(){return typeof window>"u"||typeof navigator>"u"||typeof window.matchMedia!="function"?!1:Hg({query:e=>window.matchMedia(e).matches,userAgent:navigator.userAgent,maxTouchPoints:navigator.maxTouchPoints})}const oc=["off","minimal","low","medium","high","xhigh","max"],$g=c.memo(function({state:t,models:n,modelsLoading:a,onManageModels:i,providerKeys:o,compact:l=!1}){const u=Me(),p=t?.model,h=p?`${p.provider}/${p.id}`:null,[b,m]=c.useState(!1),[f,x]=c.useState(!1),[v,N]=c.useState(""),[B,X]=c.useState(null),[K,A]=c.useState({}),R=c.useRef(null),I=c.useRef(null),[$,ce]=c.useState(null);c.useEffect(()=>{if(!b){ce(null);return}if(n.length===0)return;const D=requestAnimationFrame(()=>{const se=I.current;se&&ce(se.offsetWidth)});return()=>cancelAnimationFrame(D)},[b,n.length]),c.useEffect(()=>{b&&A(Xl())},[b]),c.useEffect(()=>{b||(N(""),X(null))},[b]);const ge=c.useMemo(()=>{const D=new Map;for(const ee of n)D.set(ee.provider,(D.get(ee.provider)??0)+1);const se=[];for(const[ee,Ne]of[...D.entries()].sort((w,de)=>w[0].localeCompare(de[0]))){const w=o[ee];if(w&&w.length>1)for(const de of w)se.push({provider:ee,keyName:de.name,count:Ne});else se.push({provider:ee,keyName:null,count:Ne})}return se},[n,o]),q=c.useMemo(()=>fg(n,K),[n,K]),Y=c.useMemo(()=>{let D=q;B&&(D=D.filter(ee=>ee.provider===B.provider));const se=v.trim().toLowerCase();return se?D.filter(ee=>ee.name.toLowerCase().includes(se)||ee.provider.toLowerCase().includes(se)||ee.id.toLowerCase().includes(se)):D},[q,v,B]),J=c.useMemo(()=>{const D=[];for(const se of Y){const ee=o[se.provider];if(!ee||ee.length<=1){D.push({model:se,key:null});continue}let Ne=ee.find(w=>w.active)??ee[0];if(B?.provider===se.provider&&B.keyName){const w=ee.find(de=>de.name===B.keyName);w&&(Ne=w)}D.push({model:se,key:Ne})}return D},[Y,o,B]),[j,F]=c.useState(!1),T=t?.availableThinkingLevels&&t.availableThinkingLevels.length>0?new Set(t.availableThinkingLevels):null,U=oc.map(D=>({value:D,label:u(`thinking.${D}`),supported:T?T.has(D):!0})),G=D=>U.find(se=>se.value===D)?.label??D;return c.useEffect(()=>{b&&n.length===0&&!j&&!a&&(F(!0),ie({type:"list_models"}))},[b,n.length,j,a]),c.useEffect(()=>{n.length>0&&F(!1)},[n.length]),c.useEffect(()=>{if(!b)return;R.current?.querySelector(".dd-item.active")?.scrollIntoView({block:"nearest"})},[b,h,n.length]),s.jsxs(s.Fragment,{children:[s.jsxs(Yt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(Gs,{}),s.jsx("span",{className:"chip-model",children:p?p.name:u("selectModel")}),!l&&p?.vision&&s.jsx("span",{className:"chip-vision",title:u("vision"),children:"🖼"}),!l&&p&&s.jsx("span",{className:"chip-sub",children:p.provider})]}),open:b,onOpenChange:m,menuClassName:"dd-menu-model",menuRef:I,menuStyle:$!=null?{width:$}:void 0,direction:"up",children:[s.jsx("div",{className:"dd-header",children:u("availableModels")}),s.jsxs("div",{className:"dd-search-row",children:[s.jsx(wn,{}),s.jsx("input",{className:"dd-search",type:"text",placeholder:u("searchModels"),value:v,onChange:D=>N(D.target.value)})]}),s.jsxs("div",{className:"dd-model-body",children:[ge.length>1&&s.jsxs("div",{className:"dd-provider-col",children:[s.jsx("div",{className:"dd-provider-head",children:u("providers")}),s.jsx("button",{type:"button",className:`dd-provider-item ${B===null?"active":""}`,onClick:()=>X(null),children:s.jsx("span",{children:u("allProviders")})}),ge.map(D=>{const se=B?.provider===D.provider&&B?.keyName===D.keyName;return s.jsxs("button",{type:"button",className:`dd-provider-item ${se?"active":""}`,onClick:()=>X(se?null:{provider:D.provider,keyName:D.keyName}),title:D.keyName?`${D.provider} · ${D.keyName}`:`${D.provider} · ${D.count}`,children:[s.jsxs("span",{className:"dd-provider-txt",children:[s.jsx("span",{className:"dd-provider-name",children:D.provider}),D.keyName&&s.jsx("span",{className:"dd-provider-key",children:D.keyName})]}),s.jsx("span",{className:"dd-provider-count",children:D.count})]},D.keyName?`${D.provider}::${D.keyName}`:D.provider)})]}),s.jsxs("div",{className:"dd-model-scroll",ref:R,children:[(j||a)&&s.jsx("div",{className:"dd-loading",children:u("loading")}),n.length===0&&!j&&!a&&s.jsx("div",{className:"dd-loading",children:u("noModels")}),Y.length===0&&n.length>0&&s.jsx("div",{className:"dd-loading",children:u("noModelMatches")}),J.map(D=>{const se=D.model,ee=h===se.id&&(!D.key||D.key.active);return s.jsx(ft,{active:ee,onClick:()=>{D.key&&!D.key.active&&ie({type:"activate_provider_key",provider:se.provider,keyName:D.key.name}),h!==se.id&&ie({type:"set_model",modelId:se.id}),m(!1)},children:s.jsxs("span",{className:"dd-model-cell",children:[s.jsx("span",{className:"dd-model-name",children:se.name}),s.jsxs("span",{className:"dd-model-meta",children:[s.jsx("span",{className:"dd-model-provider",children:se.provider}),s.jsx("span",{className:"dd-model-id",children:se.id.split("/").slice(1).join("/")}),D.key&&s.jsxs("span",{className:`dd-model-key ${D.key.active?"active":""}`,children:[D.key.active?"●":"○"," ",D.key.name]}),(K[se.id]??0)>0&&s.jsx("span",{className:"dd-model-usage",children:u("modelUsedCount",{n:K[se.id]})}),(se.reasoning||se.vision)&&s.jsxs("span",{className:"dd-model-badges",children:[se.reasoning&&s.jsx("span",{className:"dd-model-badge",children:u("reasoning")}),se.vision&&s.jsx("span",{className:"dd-model-badge",children:u("vision")})]})]})]})},D.key?`${se.id}::${D.key.name}`:se.id)})]})]}),s.jsxs("div",{className:"dd-footer",children:[s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>ie({type:"list_models"}),children:u("refreshModels")}),s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{m(!1),i()},children:u("manageModels")})]})]}),s.jsxs(Yt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(hs,{}),s.jsx("span",{className:"chip-sub",children:u("thinkingChip",{level:t?G(t.thinkingLevel):"—"})})]}),open:f,onOpenChange:x,direction:"up",children:[s.jsx("div",{className:"dd-header",children:u("thinkingLevel")}),U.map(D=>s.jsx(ft,{active:t?.thinkingLevel===D.value,disabled:!D.supported,title:D.supported?void 0:u("thinkingUnsupported"),onClick:()=>{t?.thinkingLevel!==D.value&&ie({type:"set_thinking",level:D.value}),x(!1)},children:D.label},D.value))]})]})}),Zr=Ug(),qg=c.memo(function({streaming:t,messages:n,slashCommands:a,modelState:i,models:o,modelsLoading:l,attachments:u,onRemoveAttachment:p,onAddImageFiles:h,onAddLocalFiles:b,onNotice:m,onSent:f,onManageModels:x,providerKeys:v,quickPhrases:N,quickPhrasesEnabled:B,recallDrafts:X,composerActions:K,onUiAction:A}){const R=Me(),I=wt("ready"),$=Wo(),{locale:ce}=Ut(),{openPicker:ge}=tc(),q=y=>ce!=="zh"&&y.descriptionEn?y.descriptionEn:y.description??"",Y=y=>ce!=="zh"&&y.argumentHintEn?y.argumentHintEn:y.argumentHint??"",[J,j]=c.useState(""),[F,T]=c.useState(null),[U,G]=c.useState(0),[D,se]=c.useState(!1),[ee,Ne]=c.useState(void 0),w=c.useRef(null),de=c.useRef(null),ue=c.useRef(null),pe=c.useRef(-1),ke=c.useRef(""),Be=c.useRef(0);c.useEffect(()=>{if(!X||X.length===0)return;const y=X.filter(P=>P.text&&P.seq>Be.current);y.length!==0&&(Be.current=y[y.length-1].seq,j(P=>y.reduce((le,Te)=>zr(le,Te.text),P)),pe.current=-1,ke.current="",requestAnimationFrame(()=>{const P=w.current;P&&(P.focus(),P.selectionStart=P.selectionEnd=P.value.length)}))},[X]),c.useEffect(()=>(Bi(y=>{j(P=>zr(P,y)),pe.current=-1,ke.current="",requestAnimationFrame(()=>{const P=w.current;P&&(P.focus(),P.selectionStart=P.selectionEnd=P.value.length)})}),()=>Bi(null)),[]);const ye={builtin:R("slashBuiltin"),extension:R("slashExtension"),prompt:R("slashPrompt"),skill:R("slashSkill"),plugin:R("slashPlugin")},Ae=y=>{const P=y.match(/^\/([^\s]*)$/);if(P&&I){const le=P[1].toLowerCase(),Te=Fg(a,le);T(Te.length>0?Te:null),G(0)}else T(null)};c.useEffect(()=>{ue.current?.querySelector(".slash-item.active")?.scrollIntoView({block:"nearest"})},[U,F]);const ve=y=>{const P=F??[],le=y??P[U%Math.max(P.length,1)];if(!le){T(null);return}const Te=J.match(/^\/([^\s]*)([\s\S]*)$/),Ie=Te?Te[2]:"";j(`/${le.name} ${Ie}`),T(null),w.current?.focus()},Ye=async()=>{const le=[...n].reverse().find(Te=>Te.role==="assistant"&&Te.content.some(Ie=>Ie.type==="text"&&Ie.text))?.content.filter(Te=>Te.type==="text").map(Te=>Te.text).join(`
341
- `);if(!le){m("warning",R("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(le),m("info",R("slashCopied"))}catch{m("error",R("slashCopyFailed"))}},Pe=y=>{if(!y||y.length===0){m("warning",R("foldersNotSupported"));return}const P=Array.from(y).filter(Ie=>Ht(Ie.type)),le=Array.from(y).filter(Ie=>!Ht(Ie.type)),Te=be();P.length>0&&Te?m("warning",Te):P.length>0&&h(P),le.length>0&&b(le)},ae=y=>{const P=y.clipboardData?.items;if(!P)return;const le=[];for(const Ie of P)if(Ie.kind==="file"&&Ht(Ie.type)){const Fe=Ie.getAsFile();Fe&&le.push(Fe)}if(le.length===0)return;y.preventDefault();const Te=be();if(Te){m("warning",Te);return}h(le)},be=()=>{const y=i?.model;if(!y?.id)return null;const P=o.find(le=>le.id===y.id);return P&&P.vision===!1?R("modelNoVision",{name:P.name}):null},Oe=I,Le=c.useRef(J);c.useEffect(()=>{Le.current=J},[J]),c.useEffect(()=>{Ae(Le.current)},[a]),c.useEffect(()=>{const y=P=>{const le=P.detail;j(le),w.current?.focus()};return window.addEventListener("pi-web:fill",y),()=>window.removeEventListener("pi-web:fill",y)},[]),c.useEffect(()=>{if(!D)return;const y=P=>{P.key==="Escape"&&se(!1)};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[D]);const We=c.useRef(null);c.useEffect(()=>{const y=w.current,P=We.current;if(!y||!P)return;const le=y.closest("main")?.querySelector(".messages"),Te=P.getBoundingClientRect().height,Ie=le?.scrollTop??0;y.style.height="auto";const Fe=y.scrollHeight>220;if(y.style.height=`${Math.min(y.scrollHeight,220)}px`,y.style.overflowY=Fe?"auto":"hidden",le){const Re=P.getBoundingClientRect().height-Te;le.scrollTop=Ie+Re}},[J]);const _=()=>u.map(y=>y.imageData?{path:"",imageData:y.imageData,mimeType:y.mimeType,name:y.name}:y.fileData?{path:"",fileData:y.fileData,mimeType:y.mimeType,name:y.name,size:y.size}:{path:y.path,mode:y.mode,...y.lines?{lines:y.lines}:{},...y.mode==="page"?{name:y.name}:{}}),Q=(y=!1)=>{const P=J.trim(),le=u.some(Te=>Te.imageData||Te.fileData);if(!(!Oe||!P&&!le)){if(P==="/help"){const Te=w.current?.closest(".inputbox")?.getBoundingClientRect();Ne(Te?.width),se(!0),j(""),w.current?.focus();return}if(P==="/copy"){j(""),w.current?.focus(),Ye();return}if(ie({type:"prompt",text:P,queue:y,attachments:_()})){P&&Xr(P),pe.current=-1,ke.current="",j(""),f();const Te=i?.model;Te&&qn(`${Te.provider}/${Te.id}`),w.current?.focus()}}},V=y=>{const P=y.trim();if(!(!Oe||!P)&&ie({type:"prompt",text:P,attachments:_()})){P&&Xr(P),pe.current=-1,ke.current="",f();const le=i?.model;le&&qn(`${le.provider}/${le.id}`),Zr||w.current?.focus()}},Ee=y=>{if(!y.nativeEvent.isComposing){if(F&&F.length>0)switch(y.key){case"ArrowDown":y.preventDefault(),G(P=>(P+1)%F.length);return;case"ArrowUp":y.preventDefault(),G(P=>(P-1+F.length)%F.length);return;case"Tab":case"Enter":y.preventDefault(),ve();return;case"Escape":y.preventDefault(),T(null);return}if(y.key==="ArrowUp"||y.key==="ArrowDown"){if(y.ctrlKey||y.metaKey||y.altKey)return;const P=w.current;if(!P)return;const le=y.key==="ArrowUp",Te=Lg(P);if(le&&!Te.first||!le&&!Te.last||!le&&pe.current===-1)return;const Ie=Vs();if(Ie.length===0)return;if(y.preventDefault(),le){if(pe.current===-1){ke.current=J;const Fe=Ie.length-1;pe.current=Fe;const Re=Ie[Fe];j(Re),Ae(Re),requestAnimationFrame(()=>{const L=w.current;L&&(L.selectionStart=L.selectionEnd=Re.length)})}else if(pe.current>0){const Fe=pe.current-1;pe.current=Fe;const Re=Ie[Fe];j(Re),Ae(Re),requestAnimationFrame(()=>{const L=w.current;L&&(L.selectionStart=L.selectionEnd=Re.length)})}}else{const Fe=pe.current+1;if(Fe<Ie.length){pe.current=Fe;const Re=Ie[Fe];j(Re),Ae(Re),requestAnimationFrame(()=>{const L=w.current;L&&(L.selectionStart=L.selectionEnd=Re.length)})}else{pe.current=-1;const Re=ke.current;j(Re),Ae(Re),requestAnimationFrame(()=>{const L=w.current;L&&(L.selectionStart=L.selectionEnd=Re.length)})}}return}if(y.key==="Escape"&&pe.current!==-1){y.preventDefault();const P=ke.current;pe.current=-1,j(P),Ae(P),requestAnimationFrame(()=>{const le=w.current;le&&(le.selectionStart=le.selectionEnd=P.length)});return}if(y.key==="Enter"){if(Zr&&!y.shiftKey&&!(y.ctrlKey||y.metaKey))return;y.shiftKey||(y.preventDefault(),Q())}}},oe=Oe&&(J.trim()!==""||u.some(y=>y.imageData||y.fileData)),Z=()=>s.jsx("div",{className:"inputbox-actions",children:t?oe?s.jsxs("div",{className:`split-send${$?" single":""}`,children:[s.jsx("button",{type:"button",className:"split-queue",title:R("supplementTip"),"aria-label":R("queueFollowTag"),onClick:()=>Q(!0),children:s.jsx(Ou,{})}),!$&&s.jsx("button",{type:"button",className:"split-steer",title:R("steerTip"),"aria-label":R("queueSteerTag"),onClick:()=>Q(),children:s.jsx(Ra,{})})]}):s.jsx("button",{type:"button",className:"btn stop",title:R("stopAgent"),onClick:()=>ie({type:"abort"}),children:s.jsx(vn,{})}):s.jsx("button",{type:"button",className:"btn send",title:R("sendTip"),disabled:!oe,onClick:()=>Q(),children:s.jsx(Ra,{})})});return s.jsxs("div",{ref:We,className:"inputbar",onDragOver:y=>{y.preventDefault()},onDrop:y=>{y.preventDefault(),y.stopPropagation(),Pe(y.dataTransfer?.files??null)},children:[u.length>0&&s.jsxs("div",{className:"attach-row",children:[u.map(y=>s.jsxs("span",{className:`attach-chip ${y.imageData?"image":y.fileData?"file":y.mode}`,title:y.imageData?R("attachImage",{name:y.name}):y.fileData?R("attachFile",{name:y.name}):y.isDir?R("folderRef",{path:y.path}):y.mode==="page"?R("attachPage",{name:y.name}):y.mode==="reference"?R("refOnly",{path:y.path}):y.mode==="lines"&&y.lines?R("attachLines",{path:y.path,start:y.lines.start,end:y.lines.end}):R("attachContent",{path:y.path}),children:[y.imageData?"🖼":y.fileData?"📄":y.isDir?"📁":y.mode==="page"?"🌐":y.mode==="reference"?"🔗":"📎",y.name,y.mode==="lines"&&y.lines&&s.jsxs("span",{className:"attach-range",children:["L",y.lines.start,"-",y.lines.end]}),s.jsx("button",{type:"button",className:"attach-remove",title:R("removeAttachment"),onClick:()=>p(y.key??y.path),children:"×"})]},y.key??`${y.path}|${y.mode}|${y.lines?`${y.lines.start}-${y.lines.end}`:""}`)),s.jsx("span",{className:"attach-hint",children:R("attachHint")})]}),F&&F.length>0&&s.jsxs("div",{className:"slash-menu",role:"listbox",ref:ue,"aria-label":R("slashCommands"),children:[s.jsxs("div",{className:"slash-menu-hint",children:[s.jsx("span",{children:R("slashMenuHint")}),s.jsx("span",{className:"slash-menu-close",onClick:()=>T(null),children:"Esc"})]}),F.map((y,P)=>s.jsxs("button",{type:"button",className:`slash-item${P===U?" active":""}`,onMouseEnter:()=>G(P),onClick:()=>ve(y),children:[s.jsxs("span",{className:"slash-name",children:["/",y.name]}),s.jsx("span",{className:`slash-source ${y.source}`,children:ye[y.source]}),s.jsxs("span",{className:"slash-desc",children:[q(y),y.argumentHint&&s.jsx("span",{className:"slash-hint",children:Y(y)})]})]},y.name))]}),D&&s.jsx("div",{className:"modal-backdrop",onClick:()=>se(!1),children:s.jsxs("div",{className:"slash-help",style:ee?{width:ee}:void 0,onClick:y=>y.stopPropagation(),children:[s.jsxs("div",{className:"slash-help-head",children:[s.jsxs("span",{children:["⚡ ",R("slashHelpTitle")]}),s.jsx("button",{type:"button",className:"btn",onClick:()=>se(!1),children:R("close")})]}),s.jsx("div",{className:"slash-help-body",children:a.length===0?s.jsx("div",{className:"slash-help-empty",children:R("slashLoading")}):a.map(y=>s.jsxs("div",{className:"slash-help-row",children:[s.jsxs("span",{className:"slash-help-cmd",children:["/",y.name]}),s.jsx("span",{className:`slash-source ${y.source}`,children:ye[y.source]}),s.jsxs("span",{className:"slash-help-desc",children:[q(y),y.argumentHint&&s.jsx("span",{className:"slash-hint",children:Y(y)})]})]},y.name))})]})}),B&&N.length>0&&s.jsx("div",{className:"quick-row","aria-label":R("quickPhrases"),children:N.map(y=>s.jsx("button",{type:"button",className:"quick-chip",title:R("quickPhrasesTip",{text:y}),disabled:!Oe,onClick:()=>V(y),children:y},y))}),s.jsxs("div",{className:"inputbox",children:[s.jsx("input",{ref:de,type:"file",multiple:!0,hidden:!0,onChange:y=>{Pe(y.target.files),y.target.value=""}}),s.jsx("textarea",{ref:w,value:J,rows:1,placeholder:R(Oe?t?$?"placeholderStreamingQueued":"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!Oe,onChange:y=>{pe.current=-1,j(y.target.value),Ae(y.target.value)},onKeyDown:Ee,onPaste:ae}),s.jsxs("div",{className:"composer-tools",children:[s.jsxs("div",{className:"composer-tools-left",children:[s.jsx("button",{type:"button",className:"btn attach-img",title:R("uploadFile"),disabled:!Oe,onClick:()=>de.current?.click(),children:s.jsx(Su,{})}),s.jsx("button",{type:"button",className:"btn tpl-open",title:R("tpl.openPicker"),onClick:ge,children:s.jsx(Fu,{})}),s.jsx($g,{state:i,models:o,modelsLoading:l,onManageModels:x,providerKeys:v,compact:!0})]}),(K??[]).filter(y=>y.source!=="host"&&!y.hidden).map(y=>s.jsxs("button",{type:"button",className:"btn composer-plugin-action",title:y.label,onClick:()=>A?.(y),children:[y.icon?`${y.icon} `:"",y.label]},y.id)),s.jsx("div",{className:"composer-tools-right",children:Z()})]})]})]})}),Wg=c.memo(function({goal:t,models:n,modelsLoading:a,activeConversationId:i}){const o=Me(),{locale:l}=Ut(),u=l!=="zh"&&t.statusEn?t.statusEn:t.status||"",p=l!=="zh"&&t.wizard?.statusEn?t.wizard.statusEn:t.wizard?.status||"",h=Wo(),b=!t.conversationId||t.conversationId===i,m=t.goal!==null&&b,[f,x]=c.useState(""),[v,N]=c.useState(t.reviewModel??""),[B,X]=c.useState(t.maxRounds),[K,A]=c.useState(t.locked),[R,I]=c.useState(!1),[$,ce]=c.useState(!1),[ge,q]=c.useState(!0);c.useEffect(()=>{N(t.reviewModel??""),X(t.maxRounds||0),A(t.locked)},[t.goal,t.reviewModel,t.maxRounds,t.locked]),c.useEffect(()=>{R&&n.length===0&&!$&&!a&&(ce(!0),ie({type:"list_models"}))},[R,n.length,$,a]),c.useEffect(()=>{n.length>0&&ce(!1)},[n.length]);const Y=()=>v?n.find(T=>T.id===v)?.name??v:o("goalBarUseMainModel"),J=()=>{const T=f.trim();T&&(ie({type:"set_goal",goal:T,...v?{reviewModel:v}:{},maxRounds:B,locked:K}),x(""),q(!1))},j=()=>{const T=f.trim();T&&(ie({type:"start_goal_wizard",text:T,...v?{wizardModel:v}:{},maxRounds:B,locked:K}),x(""),q(!1))},F=(t.wizard?.active??!1)&&b;return F?s.jsx("div",{className:`goalbar goalbar-active ${F?"wizard":""}`,children:s.jsxs("div",{className:"goalbar-active-row",children:[s.jsx("span",{className:"goalbar-icon",children:s.jsx("span",{className:"goalbar-spin",children:"🔍"})}),s.jsxs("span",{className:"goalbar-text",title:t.wizard?.draft??"",children:[o("goalWizardRunning"),": ",t.wizard?.draft]}),s.jsxs("span",{className:"goalbar-chip reviewing",children:[o("goalBarRound",{n:(t.wizard?.step??0)+1})," / ",t.wizard?.maxSteps??6]}),s.jsx("span",{className:"goalbar-detail",children:p||o("goalBarReviewing")}),s.jsx("button",{type:"button",className:"goalbar-x",title:o("goalBarClear"),onClick:()=>{ie({type:"clear_goal"}),q(!0)},children:s.jsx(tt,{})})]})}):m?s.jsx("div",{className:`goalbar goalbar-active ${t.reviewing?"reviewing":""}`,children:s.jsxs("div",{className:"goalbar-active-row",children:[s.jsx("span",{className:"goalbar-icon",children:t.reviewing?s.jsx("span",{className:"goalbar-spin",children:"◌"}):"🎯"}),s.jsx("span",{className:"goalbar-text",title:t.goal??"",children:t.goal}),t.reviewing?s.jsxs("span",{className:"goalbar-chip reviewing",children:[o("goalBarReviewing")," ",o("goalBarRound",{n:t.round})]}):s.jsx("span",{className:`goalbar-chip ${t.verdict==="pass"?"pass":t.verdict==="fail"?"fail":""}`,children:t.verdict==="pass"?o("goalBarPassed"):t.verdict==="fail"?o("goalBarFailed"):`${o("goalBarRound",{n:t.round||1})} · ${t.locked?o("goalBarLocked"):o("goalBarUnlocked")}`}),s.jsx("span",{className:"goalbar-detail",children:u}),s.jsx("button",{type:"button",className:"goalbar-x",title:o("goalBarClear"),disabled:t.reviewing,onClick:()=>{ie({type:"clear_goal"}),q(!0)},children:s.jsx(tt,{})})]})}):ge?s.jsx("div",{className:"goalbar goalbar-collapsed",children:s.jsxs("button",{type:"button",className:"goalbar-hint",title:o("goalBarPlaceholder"),onClick:()=>q(!1),children:[s.jsx(Ii,{})," ",s.jsx("span",{children:o("goalBarTitle")})]})}):s.jsxs("div",{className:"goalbar",children:[s.jsxs("div",{className:"goalbar-row",children:[s.jsx("span",{className:"goalbar-icon",children:s.jsx(Ii,{})}),s.jsx("input",{className:"goalbar-input",value:f,placeholder:o("goalBarPlaceholder"),onChange:T=>x(T.target.value),onKeyDown:T=>{T.key==="Enter"&&J()}}),s.jsx("button",{type:"button",className:"goalbar-btn",disabled:!f.trim(),onClick:J,children:o("goalBarSet")}),s.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!f.trim(),title:o("goalWizardTip"),onClick:j,children:["🔍 ",o("goalWizardBtn")]}),s.jsx("button",{type:"button",className:"goalbar-icon-btn",title:o(K?"goalBarLocked":"goalBarUnlocked"),onClick:()=>A(T=>(ie({type:"set_goal_prefs",locked:!T}),!T)),children:K?s.jsx(Du,{}):s.jsx(vu,{})}),s.jsx("button",{type:"button",className:"goalbar-icon-btn",title:o("goalBarClear"),onClick:()=>q(!0),children:s.jsx(Qn,{})})]}),s.jsxs("div",{className:"goalbar-opts",children:[h?s.jsx("p",{className:"goalbar-dsh-note",children:o("dshNoReviewModel")}):s.jsxs(Yt,{trigger:s.jsxs("span",{className:"goalbar-opt",children:[o("goalBarReviewModel"),": ",s.jsx("b",{children:Y()})]}),open:R,onOpenChange:I,direction:"up",children:[s.jsx("div",{className:"dd-header",children:o("goalBarReviewModel")}),($||a)&&s.jsx("div",{className:"dd-loading",children:o("loading")}),n.length===0&&!$&&!a&&s.jsx("div",{className:"dd-loading",children:o("noModels")}),s.jsx(ft,{active:v==="",onClick:()=>{N(""),I(!1),ie({type:"set_goal_prefs",reviewModel:""})},children:o("goalBarUseMainModel")}),n.map(T=>s.jsx(ft,{active:v===T.id,onClick:()=>{N(T.id),I(!1),ie({type:"set_goal_prefs",reviewModel:T.id})},children:s.jsxs("span",{className:"dd-model-cell",children:[s.jsx("span",{className:"dd-model-name",children:T.name}),s.jsxs("span",{className:"dd-model-meta",children:[s.jsx("span",{className:"dd-model-provider",children:T.provider}),s.jsx("span",{className:"dd-model-id",children:T.id.split("/").slice(1).join("/")})]})]})},T.id)),s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>ie({type:"list_models"}),children:o("refreshModels")})]}),s.jsxs("label",{className:"goalbar-round",title:o("goalBarMaxRoundsTip"),children:[s.jsx("span",{children:o("goalBarMaxRounds")}),s.jsx("input",{type:"number",min:0,step:1,value:B,placeholder:o("goalBarUnlimitedShort"),onChange:T=>{const U=parseInt(T.target.value,10);if(Number.isNaN(U)||U<0){X(0);return}X(U)},onBlur:()=>ie({type:"set_goal_prefs",maxRounds:B}),onKeyDown:T=>{T.key==="Enter"&&(ie({type:"set_goal_prefs",maxRounds:B}),T.target.blur())}})]}),s.jsx("span",{className:"goalbar-lock-hint",children:o(K?"goalBarLocked":"goalBarUnlocked")})]})]})});function Kg(e){const t=Math.max(0,e.input??0),n=Math.max(0,e.cacheRead??0),a=Math.max(0,e.cacheWrite??0),i=t+n+a;return{totalInput:i,miss:t,read:n,write:a,hitRate:i>0?Math.min(n/i,1):0,writeRate:i>0?Math.min(a/i,1):0}}const lc=2e3;function Yg(e,t,n=lc){return e.filter(a=>t-a.t<=n)}function Gg(e,t=lc){if(e.length<2)return 0;const n=e[e.length-1],a=e.find(o=>o.t>=n.t-t)??e[0],i=(n.t-a.t)/1e3;return i<=0?0:Math.max(0,(n.out-a.out)/i)}function eo(e){if(!e)return 0;let t=0;for(let a=0;a<e.length;a++){const i=e.charCodeAt(a);(i>=12352&&i<=12543||i>=13312&&i<=19903||i>=19968&&i<=40959||i>=63744&&i<=64255||i>=65280&&i<=65519||i===12288)&&t++}const n=e.length-t;return Math.round(t+n/4)}function zg(e){let t=0;for(const n of e)n.type==="text"&&typeof n.text=="string"&&n.text?t+=eo(n.text):n.type==="thinking"&&typeof n.thinking=="string"&&n.thinking&&(t+=eo(n.thinking));return t}const vt="@root",Vg=["host:conn","host:engine","host:ctx","host:cost","host:cache","host:msg-count","host:plugin-status","host:working","host:cwd"];function Qg({chat:e,bottombarItems:t,onUiAction:n}){const a=Me(),{engine:i}=ri(),o=wt("workspaceRoots"),l=e.state,[u,p]=c.useState(!1),[h,b]=c.useState(""),[m,f]=c.useState(""),[x,v]=c.useState(!1),[N,B]=c.useState(""),[X,K]=c.useState(-1),A=c.useRef(null),R=c.useRef(null),I=e.pathCompletions.filter(ae=>ae.type==="dir"),$=ae=>ae.endsWith("/")?ae:ae+"/",ce=ae=>{let be=ae.endsWith("/")&&ae!=="/"?ae.slice(0,-1):ae;if(be===vt||be==="/")return null;const Oe=be.lastIndexOf("/");if(Oe<0)return/^[A-Za-z]:$/.test(be)?vt:null;if(Oe===0)return"/";const Le=be.slice(0,Oe);return/^[A-Za-z]:$/.test(Le)?Le+"/":Le};c.useEffect(()=>{if(!u)return;const ae=setTimeout(()=>{ie({type:"complete_path",path:$(h)})},60);return()=>clearTimeout(ae)},[h,u]),c.useEffect(()=>{if(!u||m===h)return;const ae=setTimeout(()=>{ie({type:"complete_path",path:m})},150);return()=>clearTimeout(ae)},[m,h,u]);const ge=c.useRef([]),q=l?.isStreaming??!1,Y=l?.streamingMessage?zg(l.streamingMessage.content):0;if(c.useEffect(()=>{if(!q){ge.current=[];return}const ae=Date.now(),be=ge.current,Oe=be[be.length-1];Oe&&ae-Oe.t<250||(ge.current=Yg([...be,{t:ae,out:Y}],ae))},[q,Y]),!l)return null;const J=l.stats,j=Kg(J.tokens),F=j.hitRate*100,T=j.totalInput===0?"":j.hitRate>=.7?"ok":j.hitRate>=.4?"mid":"warn",U=j.totalInput>0?`${F.toFixed(1)}%`:"—",G=q?Gg(ge.current):0,D=e.ready?"ok":"busy",se=e.ready?a("connected"):a("connecting"),ee=J.contextUsage,Ne=ee.tokens!==null&&ee.percent!==null?`${ee.estimated?"~":""}${ds(ee.tokens)} / ${ds(ee.contextWindow)}`:"—",w=ee.percent??null,de=w===null?"":w>=80?"warn":w>=50?"mid":"ok",ue=l.queue.steering.length+l.queue.followUp.length,pe=()=>{const ae=l.cwd.replace(/\\/g,"/");f(ae),b(ae),v(!1),B(""),p(!0)},ke=ae=>{const be=ae.trim();be!==vt&&(be&&be!==l.cwd&&ie({type:"set_cwd",path:be}),p(!1))},Be=()=>{const ae=N.trim();ae&&(ie({type:"make_dir",path:`${$(h)}${ae}`}),setTimeout(()=>{ie({type:"complete_path",path:$(h)})},80),B(""),v(!1))},ye=ae=>{if(ae.key==="Escape")ae.stopPropagation(),p(!1);else if(ae.key==="Enter"&&!ae.nativeEvent.isComposing)ke(m);else if(ae.key==="Tab"){if(I.length===0)return;ae.preventDefault();const be=X>=0?(X+1)%I.length:0;K(be),f(I[be].path),b(I[be].path)}},Ae=ce(h),ve={"host:conn":s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`status-dot ${D}`,title:se}),s.jsx("span",{className:"status-item",children:se})]}),"host:engine":i!=="pi"?s.jsx("span",{className:`status-item engine-badge engine-${i}`,title:`${a("engineBadge")}: ${i}`,children:i==="dsh"?"DSH":i}):null,"host:ctx":s.jsxs("span",{className:"status-item status-ctx",title:a("contextUsage"),children:[s.jsx("span",{className:"ctx-label",children:a("context")}),s.jsx("span",{className:`ctx-bar ${de}`,children:w!==null&&s.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(w,100)}%`}})}),Ne]}),"host:cost":s.jsxs("span",{className:"status-item",title:a("cumulativeCost"),children:["$",Xg(J.cost)]}),"host:cache":s.jsxs("span",{className:"status-item status-cache",title:a("cacheHitTip",{read:ds(j.read),write:ds(j.write),miss:ds(j.miss),input:ds(j.totalInput)}),children:[a("cacheHit"),s.jsx("b",{className:`cache-pct ${T}`,children:U})]}),"host:msg-count":s.jsxs("span",{className:"status-item",title:a("sessionMessages"),children:[a("messages")," ",J.totalMessages]}),"host:plugin-status":e.statuses.length>0?s.jsx("span",{className:"status-item ext-status",title:a("pluginStatus"),children:e.statuses.map(ae=>ae.text).join(" · ")}):null,"host:working":l.isStreaming?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"status-item working",children:[s.jsx("span",{className:"working-spin"}),a("working"),ue>0&&s.jsxs("span",{className:"status-queue",children:["⏳ ",ue," ",a("queued")]})]}),s.jsxs("span",{className:"status-item status-rate",title:a("rateTip"),children:[s.jsx("span",{className:"working-spin rate-spin"}),G>0?`${Math.round(G)}${a("tps")}`:"…"]})]}):null,"host:cwd":u?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"status-cwd-backdrop",onClick:()=>p(!1)}),s.jsxs("div",{className:"cwd-picker",children:[s.jsxs("div",{className:"cwd-picker-head",children:[s.jsxs("span",{className:"cwd-picker-title",title:h===vt?a("computer"):h,children:[h===vt?"💻":s.jsx(Bt,{}),s.jsx("span",{children:h===vt?a("computer"):h})]}),s.jsx("button",{type:"button",className:"cwd-up",disabled:h===vt,title:a("computer"),onClick:()=>{b(vt),f(vt),K(-1)},children:"💻"}),s.jsxs("button",{type:"button",className:"cwd-up",disabled:!Ae,title:a("cwdGoUp"),onClick:()=>{Ae&&(b(Ae),f(Ae),K(-1))},children:["↑ ",a("cwdGoUp")]}),(()=>{const ae=Le=>{const We=Le.replace(/\\/g,"/").replace(/\/+$/,"");return/^[A-Za-z]:/.test(We)?We.toLowerCase():We},be=ae(h),Oe=!!h&&h!==vt&&be!==ae(l.cwd)&&!o.some(Le=>ae(Le)===be);return s.jsxs("button",{type:"button",className:"cwd-up",disabled:!Oe,title:a("addWorkspaceRootHint"),onClick:()=>{Oe&&ie({type:"set_workspace_roots",roots:[...o,h]})},children:["+ ",a("addWorkspaceRoot")]})})()]}),s.jsxs("div",{className:"cwd-picker-row",children:[s.jsx("input",{ref:A,className:"status-cwd-input cwd-picker-input",value:m,placeholder:a("enterPath"),spellCheck:!1,onChange:ae=>{f(ae.target.value),K(-1)},onKeyDown:ye}),s.jsx("button",{type:"button",className:"cwd-choose-btn primary",title:a("cwdPickCurrent"),disabled:h===vt,onClick:()=>ke(h),children:a("cwdPickCurrent")})]}),s.jsxs("div",{className:"cwd-list",children:[I.length===0&&s.jsx("div",{className:"cwd-empty",children:a("cwdEmpty")}),I.map(ae=>s.jsxs("div",{className:"cwd-item",children:[s.jsxs("button",{type:"button",className:"cwd-enter",title:`${a("cwdEnter")} ${ae.path}`,onClick:()=>{b(ae.path),f(ae.path),K(-1)},children:[s.jsx(Bt,{}),s.jsx("span",{className:"cwd-name",children:ae.name})]}),s.jsx("button",{type:"button",className:"cwd-choose-btn",title:a("cwdChoose"),onClick:()=>ke(ae.path),children:a("cwdChoose")})]},ae.path))]}),s.jsx("div",{className:"cwd-picker-foot",children:x?s.jsxs("div",{className:"cwd-newrow",children:[s.jsx("input",{ref:R,value:N,autoFocus:!0,spellCheck:!1,placeholder:a("cwdNewName"),onChange:ae=>B(ae.target.value),onKeyDown:ae=>{ae.key==="Enter"&&!ae.nativeEvent.isComposing?(ae.preventDefault(),Be()):ae.key==="Escape"&&(ae.stopPropagation(),v(!1),B(""))}}),s.jsx("button",{type:"button",className:"cwd-choose-btn primary",onClick:Be,children:a("cwdCreate")}),s.jsx("button",{type:"button",className:"cwd-choose-btn",onClick:()=>{v(!1),B("")},children:a("cwdCancel")})]}):s.jsxs("button",{type:"button",className:"cwd-newbtn",onClick:()=>v(!0),children:["+ ",a("cwdNewFolder")]})})]})]}):s.jsxs("button",{type:"button",className:"status-item status-cwd",title:a("cwdTip",{path:l.cwd}),onClick:pe,children:["📁 ",l.cwd]})},Ye=t?t.map(ae=>({id:ae.id,entry:ae})):Vg.map(ae=>({id:ae,entry:null})),Pe=[];for(const{id:ae,entry:be}of Ye)if(!be?.hidden){if(ae.startsWith("host:")){const Oe=ve[ae];Oe&&Pe.push({key:ae,node:Oe});continue}be&&Pe.push({key:ae,node:s.jsxs("button",{type:"button",className:"status-action",title:be.hint??be.label,onClick:()=>n?.(be),children:[be.icon?`${be.icon} `:"",be.label,be.badge?s.jsx("span",{className:"status-badge",children:be.badge}):null]})})}return s.jsx("footer",{className:"statusbar",children:Pe.map((ae,be)=>s.jsxs(c.Fragment,{children:[be>0&&s.jsx("span",{className:"status-sep",children:"·"}),ae.node]},ae.key))})}function ds(e){return e>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(e)}function Xg(e){return e<=0?"0":e<1e-4?"<0.0001":e.toFixed(4).replace(/\.?0+$/,"")}function Jg({dialog:e}){const t=Me(),[n,a]=c.useState(""),[i,o]=c.useState(0),l=h=>{ie({type:"dialog_response",id:e.id,value:h})};c.useEffect(()=>{a(""),o(0);const h=b=>{b.key==="Escape"&&l(null)};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[e.id]);const u=Array.isArray(e.args[0])?e.args[0]:[],p=typeof e.args[0]=="string"?e.args[0]:"";return s.jsxs("div",{className:"dialog-inline","data-dialog-kind":e.kind,children:[s.jsxs("div",{className:"dialog-head",children:[s.jsx("span",{className:"dialog-badge",children:t("pluginRequest")}),e.title&&e.title!==t("pluginRequest")&&s.jsx("span",{className:"dialog-title",children:e.title}),s.jsx("button",{type:"button",className:"dialog-dismiss",title:t("cancel"),onClick:()=>l(null),children:"✕"})]}),e.kind==="select"&&s.jsxs("div",{className:"dialog-options",children:[u.map((h,b)=>s.jsx("button",{type:"button",className:`dialog-option ${b===i?"sel":""}`,onMouseEnter:()=>o(b),onClick:()=>l(h),children:s.jsx(dt,{text:h,rawHtml:!0})},b)),u.length===0&&s.jsx("div",{className:"dialog-hint",children:t("noOptions")})]}),e.kind==="confirm"&&s.jsxs("div",{className:"dialog-body",children:[s.jsx(dt,{text:p,rawHtml:!0}),s.jsxs("div",{className:"dialog-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>l(!1),children:t("cancel")}),s.jsx("button",{type:"button",className:"btn primary",onClick:()=>l(!0),children:t("ok")})]})]}),e.kind==="input"&&s.jsxs("div",{className:"dialog-body",children:[s.jsx("input",{className:"dialog-input",value:n,placeholder:p||t("inputPlaceholder"),autoFocus:!0,onChange:h=>a(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.nativeEvent.isComposing&&l(n)}}),s.jsxs("div",{className:"dialog-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>l(null),children:t("cancel")}),s.jsx("button",{type:"button",className:"btn primary",onClick:()=>l(n),children:t("ok")})]})]})]})}const Ct=8;function cc(e,t,n){let a=e.left-Ct,i=e.bottom+Ct;return a+t.width>n.width-Ct&&(a=Math.max(Ct,e.right+Ct-t.width)),i+t.height>n.height-Ct&&(i=Math.max(Ct,e.top-Ct-t.height)),{left:a,top:i}}function Zg(){return typeof window<"u"&&window.matchMedia?.("(hover: hover) and (pointer: fine)")?.matches===!0}const eb=150;function tb({anchorRef:e,enabled:t=!0,className:n,children:a}){const i=c.useRef(null),o=c.useRef(null),[l,u]=c.useState(!1),[p,h]=c.useState({left:0,top:0}),b=c.useCallback(()=>{o.current!==null&&(clearTimeout(o.current),o.current=null)},[]),m=c.useCallback(()=>{b(),o.current=setTimeout(()=>u(!1),eb)},[b]);return c.useEffect(()=>{const f=e.current;if(!f)return;const x=()=>{b(),u(!0)};f.addEventListener("mouseenter",x);const v=N=>{const B=N.relatedTarget;B&&i.current?.contains(B)||m()};return f.addEventListener("mouseleave",v),t&&(f.addEventListener("focus",x),f.addEventListener("blur",m)),()=>{b(),f.removeEventListener("mouseenter",x),f.removeEventListener("mouseleave",v),f.removeEventListener("focus",x),f.removeEventListener("blur",m)}},[e,t,b,m]),c.useLayoutEffect(()=>{if(!l)return;const f=e.current?.getBoundingClientRect();if(!f)return;const x={left:Math.max(Ct,f.left-Ct),top:f.bottom+Ct};h(v=>v.left===x.left&&v.top===x.top?v:x)},[l,e]),c.useLayoutEffect(()=>{if(!l)return;const f=i.current,x=e.current;if(!f||!x)return;const v=cc(x.getBoundingClientRect(),f.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight});h(N=>N.left===v.left&&N.top===v.top?N:v)},[l,e,a]),c.useEffect(()=>{if(!l)return;const f=()=>u(!1);return window.addEventListener("scroll",f,!0),window.addEventListener("resize",f),()=>{window.removeEventListener("scroll",f,!0),window.removeEventListener("resize",f)}},[l]),l?Jn.createPortal(s.jsx("div",{ref:i,className:`set-tip-bubble open${n?` ${n}`:""}`,role:"tooltip",style:{position:"fixed",left:p.left,top:p.top},onMouseEnter:b,onMouseLeave:m,children:a}),document.body):null}function sb({question:e}){const t=Me(),[n,a]=c.useState({}),[i,o]=c.useState({}),[l,u]=c.useState(0),[p,h]=c.useState(()=>e.deadline?Math.max(0,Math.ceil((e.deadline-Date.now())/1e3)):-1);c.useEffect(()=>{a({}),o({}),u(0),h(e.deadline?Math.max(0,Math.ceil((e.deadline-Date.now())/1e3)):-1)},[e.id,e.deadline]),c.useEffect(()=>{if(!e.deadline)return;const A=setInterval(()=>{h(R=>{const I=Math.max(0,Math.ceil((e.deadline-Date.now())/1e3));return I<=0&&R>0&&ie({type:"question_answer",id:e.id,answers:[],cancelled:!0}),I})},1e3);return()=>clearInterval(A)},[e.id,e.deadline]),c.useEffect(()=>{const A=R=>{R.key==="Escape"&&x()};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[e.id]);const b=e.questions.length,m=e.questions[l];if(!m)return null;const f=A=>{const R=e.questions.map(I=>{const $=A[I.id]??[],ce=(i[I.id]??"").trim();return{id:I.id,selected:$,...ce?{custom:ce}:{}}});ie({type:"question_answer",id:e.id,answers:R})},x=()=>{ie({type:"question_answer",id:e.id,answers:[],cancelled:!0})},v=(A,R)=>{a(I=>{const $=I[A]??[];return{...I,[A]:$.includes(R)?$.filter(ce=>ce!==R):[...$,R]}})},N=(A,R,I)=>{if(I){v(A,R);return}const $={...n,[A]:[R]};a($),l===b-1?f($):u(l+1)},B=()=>{l===b-1?f(n):u(l+1)},X=A=>(e.questions.find(I=>I.id===A)?.options?.length??0)===0?!0:(n[A]?.length??0)>0||(i[A]??"").trim()!=="",K=(m.options??[]).filter(A=>(n[m.id]??[]).includes(A.label)&&A.preview).map(A=>A.preview);return s.jsxs("div",{className:"dialog-inline","data-dialog-kind":"select",children:[s.jsxs("div",{className:"dialog-head",children:[s.jsx("span",{className:"dialog-badge",children:t("modelQuestion")}),b>1&&s.jsx("span",{className:"question-progress",children:t("questionStep",{cur:l+1,total:b})}),p>=0&&s.jsx("span",{className:"question-timer",children:p>0?t("questionTimeout",{s:p}):t("questionTimeoutExpired")}),s.jsx("button",{type:"button",className:"dialog-dismiss",title:t("cancel"),onClick:x,children:"✕"})]}),s.jsxs("div",{className:"set-section",children:[s.jsx("div",{className:"set-section-title",children:m.header??`${t("modelQuestion")} ${l+1}`}),s.jsx("div",{className:"question-head",children:s.jsx(dt,{text:m.question,rawHtml:!0})}),m.detail&&s.jsx("div",{className:"set-hint",children:s.jsx(dt,{text:m.detail,rawHtml:!0})}),(m.options?.length??0)>0&&s.jsx("div",{className:"set-list",children:m.options.map(A=>{const R=(n[m.id]??[]).includes(A.label);return s.jsx(nb,{label:A.label,description:A.description,mark:m.multiSelect?R?"☑ ":"☐ ":R?"● ":"○ ",active:R,onPick:()=>N(m.id,A.label,!!m.multiSelect)},A.label)})}),K.length>0&&s.jsxs("div",{className:"question-preview",children:[s.jsx("div",{className:"question-preview-label",children:t("optionPreview")}),K.map((A,R)=>s.jsx("div",{className:"question-preview-body",children:s.jsx(dt,{text:A,rawHtml:!0})},R))]}),s.jsx("input",{className:"set-prompt-input question-custom",placeholder:t("modelQuestionCustom"),value:i[m.id]??"",onChange:A=>o(R=>({...R,[m.id]:A.target.value})),onKeyDown:A=>{A.key==="Enter"&&(A.preventDefault(),X(m.id)&&B())}})]},m.id),s.jsxs("div",{className:"dialog-nav",children:[s.jsx("button",{type:"button",className:"dialog-dismiss-inline",onClick:x,children:t("cancel")}),s.jsxs("div",{className:"dialog-nav-right",children:[s.jsx("button",{type:"button",className:"dialog-prev",disabled:l===0,onClick:()=>u(l-1),children:t("previous")}),s.jsx("button",{type:"button",className:"dialog-submit",disabled:!X(m.id),onClick:B,children:l===b-1?t("modelQuestionSubmit"):t("next")})]})]})]})}function nb({label:e,description:t,mark:n,active:a,onPick:i}){const o=c.useRef(null);return s.jsxs("button",{type:"button",ref:o,className:`set-row question-option${a?" active":""}`,onClick:i,children:[s.jsxs("div",{className:"set-row-name",children:[s.jsx("span",{className:"question-mark",children:n}),s.jsx(dt,{text:e,rawHtml:!0})]}),t&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"set-row-desc",children:s.jsx(dt,{text:t,rawHtml:!0})}),s.jsx(tb,{anchorRef:o,enabled:Zg(),className:"question-desc-tip",children:s.jsx(dt,{text:t,rawHtml:!0})})]})]})}const to=e=>`'${e.replace(/'/g,"'\\''")}'`,Wn=300,so=200,no=720,ab=220,ao="pi-web-ui:scm-sidebar-width";function uc(e,t=0){if(!Number.isFinite(e))return Wn;const n=Math.max(so,Math.min(no,t>0?t-ab:no));return Math.min(n,Math.max(so,Math.round(e)))}function ib(e){return e===null||e.trim()===""?Wn:uc(Number(e))}function rb(e){if(e.x==="?"&&e.y==="?")return"untracked";const t=e.x!==" "&&e.x!=="?",n=e.y!==" "&&e.y!=="?";return t&&n?"both":t?"staged":"unstaged"}function ob({chat:e,terminal:t,active:n,onSwitchToTerminal:a}){const i=Me(),[o,l]=c.useState(null),[u,p]=c.useState([]),[h,b]=c.useState(""),[m,f]=c.useState(new Map),[x,v]=c.useState("changes"),[N,B]=c.useState([]),[X,K]=c.useState(null),[A,R]=c.useState(""),[I,$]=c.useState(!1),[ce,ge]=c.useState(null),[q,Y]=c.useState(null),[J,j]=c.useState(!1),[F,T]=c.useState(!1),[U,G]=c.useState(!1),[D,se]=c.useState(null),[ee,Ne]=c.useState(!1),[w,de]=c.useState(()=>ib(localStorage.getItem(ao))),[ue,pe]=c.useState(""),ke=c.useRef(0),Be=c.useRef(-1),ye=c.useRef(-1),Ae=c.useRef(-1),ve=c.useRef(-1),Ye=c.useRef(void 0),Pe=c.useRef(null),ae=c.useRef([]),be=c.useRef(w);be.current=w;const Oe=c.useRef(null),Le=c.useCallback(S=>{try{localStorage.setItem(ao,String(S))}catch{}},[]),We=c.useCallback(S=>{S.preventDefault();const he=S.clientX,Ce=be.current,$e=Oe.current?.getBoundingClientRect().width??0;let we=Ce;const Je=bt=>{we=uc(Ce+(bt.clientX-he),$e),de(we)},gt=()=>{window.removeEventListener("pointermove",Je),window.removeEventListener("pointerup",gt),document.body.classList.remove("panel-resizing"),Le(we)};window.addEventListener("pointermove",Je),window.addEventListener("pointerup",gt),document.body.classList.add("panel-resizing")},[Le]),_=c.useCallback(()=>{de(Wn),Le(Wn)},[Le]),Q=c.useCallback(S=>{if(S.reqId===Be.current){if(Be.current=-1,T(!1),se(null),!S.ok){se(S.error??i("scmQueryFailedShort"));return}if(S.notRepo){Ne(!0),l(null),p([]),f(new Map),B([]),K(null),R(""),Y(null);return}Ne(!1);const he={branch:S.branch??"",detached:!!S.detached,upstream:S.upstream??null,ahead:S.ahead??0,behind:S.behind??0,upstreamGone:!!S.upstreamGone,files:(S.files??[]).map(we=>({...we}))},Ce=(S.branches??[]).map(we=>({...we})),$e=new Map;for(const[we,Je]of Object.entries(S.stats??{}))$e.set(we,{add:Je[0],del:Je[1]});l(he),p(Ce),f($e),b(we=>he.detached?we||"":he.branch&&Ce.some(Je=>Je.name===he.branch)?he.branch:we&&Ce.some(Je=>Je.name===we)?we:Ce[0]?.name??""),Y(we=>we&&!he.files.some(Je=>Je.path===we.file.path)?null:we)}else if(S.reqId===ye.current){if(ye.current=-1,j(!1),!S.ok){se(S.error??i("scmQueryFailedShort"));return}const he=Pe.current;if(!he)return;Y({file:he,staged:S.stagedText??"",worktree:S.worktreeText??"",untracked:!1})}else if(S.reqId===ve.current){if(ve.current=-1,G(!1),!S.ok){se(S.error??i("scmQueryFailedShort"));return}B((S.history??[]).map(he=>({...he})))}else if(S.reqId===Ae.current){if(Ae.current=-1,$(!1),!S.ok){se(S.error??i("scmQueryFailedShort"));return}R(S.text??"")}},[]);c.useEffect(()=>{const S=e.scmData;S&&S.type==="scm_data"&&Q(S)},[e.scmData,Q]);const V=c.useCallback((S,he)=>{if(!e.ready||e.status!=="open")return!1;const Ce=++ke.current;return ie({...S,reqId:Ce})?(he.current=Ce,!0):(ke.current-=1,!1)},[e.ready,e.status]),Ee=c.useCallback((S=!1,he=!1)=>{!e.ready||e.status!=="open"||e.state?.cwd&&(Ye.current!==void 0&&Ye.current!==e.state.cwd&&(l(null),p([]),f(new Map),B([]),G(!1),ve.current=-1,K(null),R(""),Y(null),ge(null)),Ye.current=e.state.cwd,se(null),V({type:"scm_status"},Be)&&(he||T(!0)))},[e.ready,e.state?.cwd,e.status,V]),oe=c.useCallback(S=>{if(ge(S),K(null),Pe.current=S,S.x==="?"&&S.y==="?"){Y({file:S,staged:"",worktree:"",untracked:!0});return}j(!0),se(null),V({type:"scm_filediff",path:S.path},ye)||j(!1)},[V]),Z=c.useCallback(S=>{K(S),ge(null),Y(null),R(""),$(!0),se(null),V({type:"scm_commit",hash:S.hash},Ae)||$(!1)},[V]),y=c.useCallback((S,he)=>{if(!e.ready)return;const Ce={name:S,command:he,cwd:"${pwd}"};let $e;const we=e.terminals.find(Je=>Je.title===S);we?(t.restart(we.id),ie({type:"run_command",terminalId:we.id,conversationId:we.conversationId,command:Ce,cols:80,rows:24}),$e=we.id):($e=St(),t.create({id:$e,conversationId:e.activeConversationId||e.state?.conversationId||"",title:S,cwd:e.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:Ce})),t.select($e),a()},[e.ready,e.state?.cwd,e.terminals,a,t]),P=c.useCallback(()=>{const S=ue.trim();if(!S||ee)return;const he=S.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");y("git commit",`git commit -m "${he}"`),pe("")},[ue,ee,y]),le=c.useCallback(()=>{const S=ue.trim();if(!S||ee)return;const he=S.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");y("git commit",`git add -A && git commit -m "${he}"`),pe("")},[ue,ee,y]),Te=c.useCallback(S=>{ee||y("git add",`git add -- ${to(S.path)}`)},[ee,y]),Ie=c.useCallback(S=>{ee||y("git reset",`git reset HEAD -- ${to(S.path)}`)},[ee,y]),Fe=c.useCallback(()=>{if(!h||ee)return;const S=u.find(he=>he.name===h);if(S?.remote&&typeof S.remote=="string"){const he=h.slice(S.remote.length+1);y("git checkout",`git checkout -b ${he} ${h} || git checkout ${h}`)}else y("git checkout",`git checkout ${h}`)},[h,u,ee,y]),Re=c.useCallback(()=>y("git push","git push"),[y]),L=c.useCallback(()=>y("git pull","git pull"),[y]),De=c.useCallback(()=>{V({type:"scm_history"},ve)||(ve.current=-1)},[V]);c.useEffect(()=>{n&&Ee()},[n,Ee]),c.useEffect(()=>{x==="history"&&o&&De()},[x,o,De]),c.useEffect(()=>{e.scmDirty>0&&n&&Ee(!1,!0)},[e.scmDirty]),c.useEffect(()=>{if(!n||!e.ready||e.status!=="open")return;const S=setInterval(()=>{document.visibilityState!=="hidden"&&Ee(!1,!0)},3e4);return()=>clearInterval(S)},[n,e.ready,e.status,Ee]),c.useEffect(()=>{const S=ae.current;if(ae.current=e.terminals,!n)return;e.terminals.some(Ce=>Ce.running!==!1?!1:S.find(we=>we.id===Ce.id)?.running===!0&&Ce.title.startsWith("git "))&&e.ready&&e.status==="open"&&(Ee(!1,!0),x==="history"&&o&&De())},[e.terminals,n,e.ready,e.status,Ee,x,o,De]);const Ge={staged:i("scmStaged"),unstaged:i("scmUnstaged"),untracked:i("scmUntracked"),both:i("scmStagedUnstaged")},C=S=>{const he=S.split(`
342
- `);return s.jsx("pre",{className:"scm-diff-pre",children:he.map((Ce,$e)=>{let we="";return Ce.startsWith("diff --git")||Ce.startsWith("index ")||Ce.startsWith("new file")||Ce.startsWith("deleted file")||Ce.startsWith("old mode")||Ce.startsWith("new mode")||Ce.startsWith("similarity index")||Ce.startsWith("rename ")||Ce.startsWith("copy ")||Ce.startsWith("Binary files")||Ce.startsWith("---")||Ce.startsWith("+++")?we="hdr":Ce.startsWith("@@")?we="hunk":Ce.startsWith("+")?we="add":Ce.startsWith("-")&&(we="del"),s.jsx("div",{className:`scm-diff-line ${we}`,children:Ce||" "},$e)})})};return s.jsxs("div",{className:"scm-view",children:[s.jsxs("div",{className:"scm-header",children:[s.jsxs("div",{className:"scm-title-row",children:[s.jsxs("span",{className:"scm-title",children:[s.jsx(un,{}),i("scmTitle")]}),s.jsxs("div",{className:"scm-view-tabs",role:"tablist",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":x==="changes",className:x==="changes"?"active":"",onClick:()=>{v("changes"),se(null)},children:i("scmChanges")}),s.jsx("button",{type:"button",role:"tab","aria-selected":x==="history",className:x==="history"?"active":"",onClick:()=>{v("history"),se(null)},children:i("scmHistory")})]}),s.jsx("button",{type:"button",className:"panel-refresh",title:i("scmRefreshTip"),disabled:F,onClick:()=>Ee(!0),children:s.jsx(Rt,{className:F?"scm-spin":""})})]}),s.jsxs("div",{className:"scm-row",children:[s.jsxs("span",{className:"scm-branch-current",title:i("scmCurrentBranch"),children:[s.jsx(un,{}),o?o.detached?i("scmDetached"):o.branch:"…",o?.upstream&&s.jsx("span",{className:"scm-upstream",children:o.upstreamGone?i("scmUpstreamGone"):o.ahead>0||o.behind>0?i("scmAheadBehind",{ahead:o.ahead,behind:o.behind}):o.upstream})]}),s.jsxs("select",{className:"scm-select",value:h,disabled:ee||u.length===0,title:i("scmSwitchBranch"),onChange:S=>b(S.target.value),children:[s.jsx("option",{value:"",disabled:!0,children:i("scmSelectBranch")}),u.filter(S=>!S.remote).map(S=>s.jsx("option",{value:S.name,children:S.current?`* ${S.name}`:S.name},S.name)),u.some(S=>S.remote)&&s.jsx("optgroup",{label:i("scmRemoteBranches"),children:u.filter(S=>S.remote).map(S=>s.jsx("option",{value:S.name,children:S.name},S.name))})]}),s.jsxs("button",{type:"button",className:"btn",disabled:!h||h===o?.branch||ee,title:i("scmSwitchBranchTip",{branch:h}),onClick:Fe,children:[s.jsx(un,{}),i("scmSwitch")]}),s.jsxs("button",{type:"button",className:"btn",disabled:!o||o.detached||ee,title:i("scmPushTip"),onClick:Re,children:[s.jsx(Ra,{}),i("scmPush")]}),s.jsxs("button",{type:"button",className:"btn",disabled:!o||o.detached||ee,title:i("scmPullTip"),onClick:L,children:[s.jsx(So,{}),i("scmPull")]}),s.jsx("input",{className:"scm-commit-input",value:ue,placeholder:i("scmCommitPlaceholder"),disabled:ee,onChange:S=>pe(S.target.value),onKeyDown:S=>{S.key==="Enter"&&!S.nativeEvent.isComposing&&P()}}),s.jsxs("button",{type:"button",className:"btn primary",disabled:!ue.trim()||ee,title:i("scmCommitTip"),onClick:P,children:[s.jsx(Lt,{}),i("scmCommit")]}),s.jsx("button",{type:"button",className:"btn",disabled:!ue.trim()||ee,title:i("scmCommitAllTip"),onClick:le,children:i("scmCommitAll")})]})]}),s.jsxs("div",{className:"scm-body",ref:Oe,style:{"--scm-sidebar-w":`${w}px`},children:[x==="history"?s.jsxs("div",{className:"scm-history",children:[s.jsxs("div",{className:"scm-files-header",children:[s.jsx("span",{children:i("scmHistory")}),N.length>0&&s.jsx("span",{className:"scm-files-count",children:N.length})]}),s.jsx("div",{className:"scm-history-list",children:ee?s.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):!o||U?s.jsx("div",{className:"scm-empty",children:e.status==="open"?i("scmLoading"):i("scmConnecting")}):N.length===0?s.jsx("div",{className:"scm-empty",children:i("scmNoHistory")}):N.map(S=>s.jsxs("button",{type:"button",className:`scm-commit ${X?.hash===S.hash?"active":""}`,onClick:()=>Z(S),title:S.hash,children:[s.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:S.graph||"* "}),s.jsxs("span",{className:"scm-commit-info",children:[s.jsx("span",{className:"scm-commit-subject",children:S.subject}),s.jsxs("span",{className:"scm-commit-meta",children:[S.shortHash," · ",S.author," · ",S.date]}),S.decorations&&s.jsx("span",{className:"scm-commit-refs",children:S.decorations})]})]},S.hash))})]}):s.jsxs("div",{className:"scm-files",children:[s.jsxs("div",{className:"scm-files-header",children:[s.jsx("span",{children:i("scmChanges")}),o&&o.files.length>0&&s.jsx("span",{className:"scm-files-count",children:o.files.length})]}),s.jsx("div",{className:"scm-files-list",children:ee?s.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):o?o.files.length===0?s.jsx("div",{className:"scm-empty",children:i("scmNoChanges")}):o.files.map(S=>{const he=rb(S),Ce=m.get(S.path);return s.jsxs("div",{className:`scm-file ${ce?.path===S.path?"active":""}`,title:Ge[he],onClick:()=>oe(S),children:[s.jsx("span",{className:`scm-file-xy ${he==="untracked"?"q":"x"}`,children:S.x!==" "?S.x:" "}),s.jsx("span",{className:`scm-file-xy ${he==="untracked"?"q":"y"}`,children:S.y!==" "?S.y:" "}),s.jsx("span",{className:"scm-file-path",children:S.path}),Ce&&(Ce.add>0||Ce.del>0)&&s.jsxs("span",{className:"scm-file-stat",children:[Ce.add>0&&s.jsxs("span",{className:"add",children:["+",Ce.add]}),Ce.del>0&&s.jsxs("span",{className:"del",children:["-",Ce.del]})]}),s.jsxs("span",{className:"scm-file-actions",children:[(S.y!==" "||he==="untracked")&&s.jsx("button",{type:"button",className:"scm-act",title:i("scmStageTip",{path:S.path}),onClick:$e=>{$e.stopPropagation(),Te(S)},children:"+"}),he==="staged"||he==="both"?s.jsx("button",{type:"button",className:"scm-act",title:i("scmUnstageTip",{path:S.path}),onClick:$e=>{$e.stopPropagation(),Ie(S)},children:"−"}):null]})]},S.path)}):s.jsx("div",{className:"scm-empty",children:e.status==="open"?i("scmLoading"):i("scmConnecting")})})]}),s.jsx("div",{className:"scm-divider",role:"separator","aria-orientation":"vertical",title:i("dragToResize"),onPointerDown:We,onDoubleClick:_}),s.jsxs("div",{className:"scm-diff",children:[s.jsxs("div",{className:"scm-diff-header",children:[s.jsx("span",{children:x==="history"?X?`${X.shortHash} ${X.subject}`:i("scmCommitDetail"):ce?ce.path:i("scmDiff")}),(x==="history"?I:J)&&s.jsx("span",{className:"scm-diff-loading",children:i("scmLoading")})]}),s.jsx("div",{className:"scm-diff-body",children:x==="history"?s.jsxs(s.Fragment,{children:[D&&s.jsx("div",{className:"scm-error",children:D}),!X&&!D&&s.jsx("div",{className:"scm-empty",children:i("scmSelectCommitHint")}),X&&I&&!D&&s.jsx("div",{className:"scm-empty",children:i("scmLoading")}),X&&!I&&!D&&A?C(A):null]}):s.jsxs(s.Fragment,{children:[D&&s.jsx("div",{className:"scm-error",children:D}),!ce&&!D&&s.jsx("div",{className:"scm-empty",children:i("scmSelectFileHint")}),ce&&!q&&!D&&s.jsx("div",{className:"scm-empty",children:i("scmLoading")}),ce&&q&&q.untracked&&s.jsx("div",{className:"scm-empty",children:i("scmUntrackedNote")}),ce&&q&&!q.untracked&&s.jsxs(s.Fragment,{children:[q.staged&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"scm-diff-section",children:i("scmStaged")}),C(q.staged)]}),q.worktree&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"scm-diff-section",children:i("scmUnstaged")}),C(q.worktree)]}),!q.staged&&!q.worktree&&s.jsx("div",{className:"scm-empty",children:i("scmNoDiff")})]})]})})]})]}),s.jsxs("div",{className:"scm-hint",children:[s.jsx(Vn,{}),s.jsx("span",{children:i("scmRunsInTerminal")}),s.jsx("button",{type:"button",className:"scm-goto-term",onClick:a,children:i("scmViewTerminal")})]})]})}function lb({entry:e}){const t=c.useRef(null),n=Me();return c.useEffect(()=>{const a=t.current;if(!a)return;let i;try{i=e.module.mount(a,el(e.info.id,o=>ie(o)))}catch(o){console.error(`[plugin:${e.info.id}] mount failed:`,o),a.textContent=n("pluginMountFailed",{name:e.info.name})}return()=>{if(typeof i=="function")try{i()}catch(o){console.error(`[plugin:${e.info.id}] cleanup failed:`,o)}a.textContent=""}},[e]),s.jsx("div",{className:"plugin-view",ref:t})}const Za=["topbar.primary","topbar.overflow","bottombar","composer.actions","message.actions","rightpanel.tabs","contextmenu.topbar","contextmenu.message","contextmenu.session","contextmenu.file","settings.pages"],cb=[{id:"host:history",slot:"topbar.primary",labelKey:"openHistory",icon:"menu",kind:"action",order:5,group:"panels"},{id:"host:files",slot:"topbar.primary",labelKey:"openFiles",icon:"folder",kind:"action",order:6,group:"panels"},{id:"host:new-chat",slot:"topbar.primary",labelKey:"newChat",icon:"plus",kind:"action",order:10,group:"primary"},{id:"host:chat",slot:"topbar.primary",labelKey:"chat",icon:"chat",kind:"view",view:"chat",order:20,group:"views"},{id:"host:terminal",slot:"topbar.primary",labelKey:"terminal",icon:"terminal",kind:"view",view:"terminal",order:21,group:"views"},{id:"host:git",slot:"topbar.primary",labelKey:"scmTab",icon:"git",kind:"view",view:"git",order:22,group:"views"},{id:"host:search",slot:"topbar.primary",labelKey:"searchGlobal",icon:"search",kind:"action",order:40,group:"tools"},{id:"host:browser",slot:"topbar.primary",labelKey:"browserControl",icon:"browser",kind:"action",order:41,group:"tools"},{id:"host:tasks",slot:"topbar.primary",labelKey:"bgTasks",icon:"layers",kind:"action",order:42,group:"tools"},{id:"host:settings",slot:"topbar.primary",labelKey:"settingsTitle",icon:"settings",kind:"action",order:60,group:"system"},{id:"host:sound",slot:"topbar.primary",labelKey:"sound",icon:"sound",kind:"action",order:70,group:"system"},{id:"host:language",slot:"topbar.primary",labelKey:"language",icon:"globe",kind:"action",order:80,group:"system"},{id:"host:theme",slot:"topbar.primary",labelKey:"theme",icon:"sun",kind:"action",order:82,group:"system"},{id:"host:update",slot:"topbar.primary",labelKey:"update",icon:"download",kind:"action",order:90,group:"system"},{id:"host:github",slot:"topbar.primary",labelKey:"githubRepo",icon:"github",kind:"action",order:95,group:"system"},{id:"host:conn",slot:"bottombar",labelKey:"connected",icon:"dot",kind:"badge",order:5,group:"status"},{id:"host:engine",slot:"bottombar",labelKey:"engineBadge",icon:"cpu",kind:"badge",order:6,group:"status"},{id:"host:ctx",slot:"bottombar",labelKey:"context",icon:"gauge",kind:"badge",order:10,group:"usage"},{id:"host:cost",slot:"bottombar",labelKey:"cumulativeCost",icon:"coins",kind:"badge",order:11,group:"usage"},{id:"host:cache",slot:"bottombar",labelKey:"cacheHit",icon:"database",kind:"badge",order:12,group:"usage"},{id:"host:msg-count",slot:"bottombar",labelKey:"messages",icon:"message",kind:"badge",order:13,group:"usage"},{id:"host:plugin-status",slot:"bottombar",labelKey:"pluginStatus",icon:"activity",kind:"badge",order:14,group:"status"},{id:"host:working",slot:"bottombar",labelKey:"working",icon:"activity",kind:"badge",order:15,group:"status"},{id:"host:cwd",slot:"bottombar",labelKey:"cwdTip",icon:"folder",kind:"action",order:20,group:"context"},{id:"host:msg-edit-reask",slot:"message.actions",labelKey:"editReask",icon:"edit",kind:"action",order:10},{id:"host:msg-copy",slot:"message.actions",labelKey:"copyMessage",icon:"copy",kind:"action",order:20},{id:"host:right-files",slot:"rightpanel.tabs",labelKey:"openFiles",icon:"folder",kind:"view",view:"files",order:10},{id:"host:conv-dismiss-subagents",slot:"contextmenu.session",labelKey:"dismissFinishedSubagents",icon:"x",kind:"action",context:"session",order:10},{id:"host:conv-force-dismiss",slot:"contextmenu.session",labelKey:"forceDismissConversation",icon:"x",kind:"action",context:"session",order:20},{id:"host:file-upload",slot:"contextmenu.file",labelKey:"uploadToFolder",icon:"upload",kind:"action",context:"file",order:10},{id:"host:file-open-project",slot:"contextmenu.file",labelKey:"openAsProject",icon:"folder",kind:"action",context:"file",order:20},{id:"host:file-add-root",slot:"contextmenu.file",labelKey:"addWorkspaceRoot",icon:"folder",kind:"action",context:"file",order:30}];function dc(e){return typeof e=="string"&&Za.includes(e)}function pc(e,t){return t?e.label:e.labelEn??e.label}function mc(e,t){return t?e.hint??e.hintEn:e.hintEn??e.hint}function ub(e,t,n,a,i){const o=`${e}#${a.id}`,l=hc(o,t,n,a.children,i),u=mc(a,i);return{id:o,slot:t,source:n,label:pc(a,i),...a.icon?{icon:a.icon}:{},...u?{hint:u}:{},kind:a.kind??"action",...a.action?{action:a.action}:{},...a.view?{view:a.view}:{},...a.group?{group:a.group}:{},order:a.order??100,hidden:a.hidden??!1,...a.badge?{badge:a.badge}:{},...a.when?{when:a.when}:{},...l.length>0?{children:l}:{},userOverrides:[],arrangedBy:[]}}function hc(e,t,n,a,i){return a?.length?a.map((o,l)=>({entry:ub(e,t,n,o,i),index:l})).sort((o,l)=>o.entry.order===l.entry.order?o.index-l.index:o.entry.order-l.entry.order).map(o=>o.entry):[]}function db(e,t,n,a,i,o){const l=hc(e,t,n,a.children,i),u=mc(a,i);return{id:e,slot:t,source:n,label:pc(a,i),...a.icon?{icon:a.icon}:{},...u?{hint:u}:{},kind:a.kind??(t==="settings.pages"?"page":"action"),...a.action?{action:a.action}:{},...a.view?{view:a.view}:{},...a.group?{group:a.group}:{},order:a.order??100,hidden:a.hidden??!1,...a.badge?{badge:a.badge}:{},...a.when?{when:a.when}:{},...l.length>0?{children:l}:{},userOverrides:[],arrangedBy:[],seq:o}}function pb(e,t){return[...e].sort((n,a)=>{const i=t.get(n.id),o=t.get(a.id);return i!==void 0||o!==void 0?i!==void 0&&o!==void 0?i-o:i!==void 0?-1:1:n.order!==a.order?n.order-a.order:n.seq-a.seq})}function fc(e,t){const n=t.locale==="zh",a=new Set(t.disabledPlugins??[]),i=t.layout??{},o=new Map;let l=0;for(const f of cb)o.set(f.id,{id:f.id,slot:f.slot,source:"host",label:t.t(f.labelKey),labelKey:f.labelKey,...f.icon?{icon:f.icon}:{},kind:f.kind,...f.view?{view:f.view}:{},...f.group?{group:f.group}:{},order:f.order??100,hidden:f.hidden??!1,userOverrides:[],arrangedBy:[],seq:l++});for(const f of e){if(f.error||a.has(f.id))continue;const x=`plugin:${f.id}`;for(const v of f.ui?.items??[]){if(!dc(v.slot))continue;const N=`${f.id}:${v.id}`,B=o.get(N);o.set(N,db(N,v.slot,x,v,n,B?.seq??l++))}}for(const f of e)if(!(f.error||a.has(f.id)))for(const x of f.ui?.arrange??[])hb(o,x,f.id);const u=new Map,p=(f,x)=>{const v=u.get(f)??[];v.includes(x)||v.push(x),u.set(f,v)};for(const f of i.hidden??[]){const x=o.get(f);x&&(x.hidden=!0,p(f,"hidden"))}for(const f of i.shown??[]){const x=o.get(f);x&&(x.hidden=!1,p(f,"hidden"))}for(const[f,x]of Object.entries(i.groups??{})){const v=o.get(f);v&&(v.group=x,p(f,"group"))}for(const[f,x]of Object.entries(i.labels??{})){const v=o.get(f);v&&(v.label=x,p(f,"label"))}const h=new Map;(i.order??[]).forEach((f,x)=>{o.has(f)&&(h.has(f)||h.set(f,x),p(f,"order"))});const b=new Map;for(const f of Za)b.set(f,[]);for(const f of o.values())b.get(f.slot)?.push(f);const m={};for(const f of Za)m[f]=pb(b.get(f)??[],h).map(x=>mb(x,u.get(x.id)??[]));return m}function mb(e,t){const n={...e,userOverrides:t};return delete n.seq,n}function hb(e,t,n){const a=e.get(t.id);if(!a)return;let i=!1;t.hide!==void 0&&(a.hidden=t.hide,i=!0),t.group!==void 0&&(a.group=t.group,i=!0),t.order!==void 0&&(a.order=t.order,i=!0),t.label!==void 0&&(a.label=t.label,i=!0),t.hint!==void 0&&(a.hint=t.hint,i=!0),t.icon!==void 0&&(a.icon=t.icon,i=!0),t.slot!==void 0&&dc(t.slot)&&t.slot!==a.slot&&(a.movedFrom=a.movedFrom??a.slot,a.slot=t.slot,i=!0),i&&a.source!==`plugin:${n}`&&!a.arrangedBy.includes(n)&&a.arrangedBy.push(n)}function fb(e,t){const n=e??{},a={},i=(n.hidden??[]).filter(h=>h!==t),o=(n.shown??[]).filter(h=>h!==t),l=(n.order??[]).filter(h=>h!==t);i.length>0&&(a.hidden=i),o.length>0&&(a.shown=o),l.length>0&&(a.order=l);const u=io(n.groups,t);u&&(a.groups=u);const p=io(n.labels,t);return p&&(a.labels=p),a}function gb(){return{}}function io(e,t){if(!e)return;const n={};let a=!1;for(const[i,o]of Object.entries(e))i!==t&&(n[i]=o,a=!0);return a?n:void 0}function bb({onAction:e}){const t=jd(),n=c.useMemo(()=>t?Ln(t.entries):[],[t]),a=c.useMemo(()=>zi(n),[n]),i=c.useRef(null),o=c.useRef(null),[l,u]=c.useState(null),[p,h]=c.useState(-1),[b,m]=c.useState(-1),[f,x]=c.useState(!1),[v,N]=c.useState(0),B=c.useRef(-1),X=q=>{B.current=q,h(q)},K=c.useMemo(()=>b>=0?Ln(n[b]?.children??[]):[],[n,b]),A=c.useMemo(()=>zi(K),[K]),R=q=>{const Y=n[q];if(!(!t||!Y||fn(Y))){if(Y.children?.length){m(q);return}I(Y,t)||qt()}},I=(q,Y)=>q.source==="host"&&Y.onHostAction?Y.onHostAction(q,Y.target)===!0:(e(q,Y.target),!1),$=c.useRef(R);if(c.useLayoutEffect(()=>{$.current=R}),c.useEffect(()=>{if(!t){B.current=-1,h(-1),m(-1);return}const q=Vi(n,-1,1);B.current=q,h(q),m(-1),i.current?.focus()},[t,n]),c.useLayoutEffect(()=>{if(!t){u(null);return}const q=i.current;if(!q)return;const Y=q.getBoundingClientRect();u(Rd(t.x,t.y,Y.width,Y.height,window.innerWidth,window.innerHeight))},[t,n]),c.useLayoutEffect(()=>{const q=o.current,Y=i.current;if(b<0||!q||!Y){x(!1),N(0);return}const J=q.getBoundingClientRect(),j=Y.getBoundingClientRect(),F=window.innerWidth-j.right,T=j.left;x(F<J.width+Ot&&T>F);const U=J.bottom-(window.innerHeight-Ot);N(U>0?-Math.min(U,Math.max(0,J.top-Ot)):0)},[b,n]),c.useEffect(()=>{if(!t)return;const q=T=>i.current&&T instanceof Node&&i.current.contains(T),Y=T=>{q(T.target)||qt()},J=T=>{q(T.target)||qt()},j=()=>qt(),F=()=>qt();return document.addEventListener("mousedown",Y,!0),window.addEventListener("wheel",J,!0),window.addEventListener("scroll",j,!0),window.addEventListener("resize",F),()=>{document.removeEventListener("mousedown",Y,!0),window.removeEventListener("wheel",J,!0),window.removeEventListener("scroll",j,!0),window.removeEventListener("resize",F)}},[t]),c.useEffect(()=>{if(!t)return;const q=J=>{const j=Vi(n,B.current,J);B.current=j,h(j)},Y=J=>{switch(J.key){case"Escape":J.preventDefault(),qt();return;case"Tab":qt();return;case"ArrowDown":J.preventDefault(),q(1);return;case"ArrowUp":J.preventDefault(),q(-1);return;case"ArrowRight":n[B.current]?.children?.length&&(J.preventDefault(),m(B.current));return;case"ArrowLeft":b>=0&&(J.preventDefault(),m(-1));return;case"Enter":case" ":J.preventDefault(),$.current(B.current);return;default:return}};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[t,n,b]),c.useEffect(()=>{p<0||i.current?.querySelector('[data-ctx-active="true"]')?.scrollIntoView?.({block:"nearest"})},[p]),!t)return null;const ce=q=>{fn(q)||I(q,t)||qt()},ge=(q,Y,J)=>{const j=fn(q),F=!!q.children?.length,T=Pd(q.icon),U=J&&p===Y;return s.jsxs("div",{className:"ctx-menu-itemwrap",role:"none",children:[s.jsxs("button",{type:"button",role:"menuitem",className:`ctx-menu-item${j?" disabled":""}${U?" active":""}${F?" has-sub":""}`,"aria-label":q.label,title:q.hint,"aria-disabled":j||void 0,"aria-haspopup":F?"menu":void 0,"aria-expanded":F?b===Y:void 0,"data-ctx-active":U?"true":void 0,onMouseEnter:J?()=>{X(Y),F&&!j&&m(Y)}:void 0,onClick:()=>J?R(Y):ce(q),children:[T?s.jsx("span",{className:"ctx-menu-icon","aria-hidden":"true",children:T}):null,s.jsx("span",{className:"ctx-menu-label",children:q.label}),q.badge?s.jsx("span",{className:"ctx-menu-badge",children:q.badge}):null,F?s.jsx("span",{className:"ctx-menu-caret","aria-hidden":"true",children:"▸"}):null]}),J&&F&&b===Y?s.jsx("div",{ref:o,className:`ctx-menu-sub${f?" left":""}`,role:"menu","aria-label":q.label,style:v?{marginTop:v}:void 0,children:A.map(G=>G.kind==="sep"?s.jsx("div",{className:"ctx-menu-sep",role:"separator"},G.key):ge(G.entry,G.index,!1))}):null]},`${q.id}#${Y}`)};return Jn.createPortal(s.jsx("div",{ref:i,className:"ctx-menu",role:"menu","aria-label":t.target.label?`${t.slot}: ${t.target.label}`:t.slot,tabIndex:-1,style:{left:l?.x??t.x,top:l?.y??t.y,visibility:l?"visible":"hidden"},onContextMenu:q=>{q.preventDefault(),q.stopPropagation()},children:a.map(q=>q.kind==="sep"?s.jsx("div",{className:"ctx-menu-sep",role:"separator"},q.key):ge(q.entry,q.index,!0))}),document.body)}function Eb({piConfigured:e,piAgentInstalled:t,providers:n,installResult:a,onClose:i}){const o=Me(),l=Ko(),[u,p]=c.useState(!1),[h,b]=c.useState(""),[m,f]=c.useState(""),[x,v]=c.useState(!1);c.useEffect(()=>{ie({type:"list_providers"})},[]),c.useEffect(()=>{e&&i()},[e,i]),c.useEffect(()=>{a&&p(!1)},[a]),c.useEffect(()=>{!h&&n.length>0&&b(n.find(R=>!R.configured)?.id??n[0].id)},[n,h]);const N=()=>{u||(p(!0),ie({type:"install_pi_agent"}))},B=()=>{!m.trim()||x||(v(!0),ie({type:"set_provider_api_key",provider:h.trim(),apiKey:m.trim()}),setTimeout(()=>v(!1),3e3))},X=()=>{ie({type:"get_state"}),ie({type:"list_providers"})},K=n.find(R=>R.id===h),A=a!==null&&!a.ok;return s.jsx("div",{className:"modal-backdrop",children:s.jsxs("div",{className:"modal setup-modal",children:[s.jsx("button",{type:"button",className:"modal-close","aria-label":o("close"),onClick:i,children:s.jsx(tt,{})}),s.jsxs("div",{className:"modal-head",children:[s.jsx(Gs,{className:"modal-head-icon"}),s.jsx("h2",{children:o("setupTitle")})]}),s.jsx("p",{className:"modal-desc",children:o("setupDesc")}),A?s.jsxs("div",{className:"setup-failed",children:[s.jsx("div",{className:"setup-done",children:o("installFailed")}),s.jsx("pre",{className:"setup-detail",children:a.detail}),s.jsxs("div",{className:"setup-actions",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:u,onClick:N,children:o("retryInstall")}),s.jsx("button",{type:"button",className:"btn",onClick:i,children:o("skip")})]})]}):t||a?.ok?s.jsxs("div",{className:"setup-key-form",children:[s.jsx("div",{className:"setup-done",children:a?.ok?o("installDone"):o("cliReadyHint")}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:o("provider")}),s.jsxs("select",{value:h,onChange:R=>b(R.target.value),children:[n.length===0&&s.jsx("option",{value:"",children:o("loading")}),n.map(R=>s.jsxs("option",{value:R.id,children:[R.name,"(",R.id,")",R.configured?` · ${o("configured")}`:""]},R.id))]}),K?.configured&&s.jsx("div",{className:"field-hint",children:o("providerKeyReady")})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:o("apiKey")}),s.jsx("input",{type:"password",value:m,onChange:R=>f(R.target.value),placeholder:"sk-…"})]}),s.jsxs("div",{className:"setup-actions",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:!m.trim()||x||!h,onClick:B,children:o(x?"saving":"saveAndStart")}),s.jsxs("button",{type:"button",className:"btn",onClick:X,children:[s.jsx(Rt,{})," ",o("recheck")]})]})]}):l?s.jsxs("div",{className:"setup-actions",children:[s.jsx("div",{className:"setup-done",children:o("updatesManaged")}),s.jsx("button",{type:"button",className:"btn",onClick:i,children:o("skip")})]}):s.jsxs("div",{className:"setup-actions",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:u,onClick:N,children:o(u?"installing":"autoInstall")}),s.jsx("button",{type:"button",className:"btn",onClick:i,children:o("skip")})]})]})})}const Tb=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],bi=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),xb=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[bi()]});function Ca(e){return{providerId:e.providerId,name:e.name??"",api:e.api??"openai-completions",baseUrl:e.baseUrl??"",apiKey:e.apiKey??"",authHeader:e.authHeader??!1,models:(e.models.length?e.models:[bi()]).map(t=>({id:t.id,name:t.name??"",reasoning:t.reasoning??!1,input:t.input?.includes("image")?"text-image":"text",contextWindow:t.contextWindow?String(t.contextWindow):"",maxTokens:t.maxTokens?String(t.maxTokens):""}))}}function yb({providers:e,providerStatus:t,providerKeys:n,fetchModelsResult:a,cloneProviderResult:i,onClose:o}){const l=Me(),[u,p]=c.useState(null),[h,b]=c.useState({}),[m,f]=c.useState({}),[x,v]=c.useState(null),[N,B]=c.useState(!1),[X,K]=c.useState(0),[A,R]=c.useState(null),I=c.useRef(0),[$,ce]=c.useState(null),[ge,q]=c.useState(""),[Y,J]=c.useState(null);c.useEffect(()=>{ie({type:"list_models_config"}),ie({type:"list_providers"}),ie({type:"list_provider_keys"})},[]);const j=()=>{if(!u)return;const w=u.baseUrl.trim();if(!w){R({ok:!1,text:l("fetchModelsNeedBaseUrl")});return}if(N)return;B(!0),R(null);const de=X+1;K(de),ie({type:"fetch_models",reqId:de,baseUrl:w,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader,api:u.api})};c.useEffect(()=>{if(!(!a||a.reqId===I.current))if(I.current=a.reqId,B(!1),a.ok&&a.models?.length){const w=a.models;p(de=>{if(!de)return de;const ue=de.models.map(ye=>{if(!ye.id.trim())return ye;const Ae=w.find(Ye=>Ye.id===ye.id.trim());if(!Ae)return ye;const ve={...ye};return!ve.name&&Ae.name&&(ve.name=Ae.name),!ve.contextWindow&&Ae.contextWindow&&(ve.contextWindow=String(Ae.contextWindow)),!ve.maxTokens&&Ae.maxTokens&&(ve.maxTokens=String(Ae.maxTokens)),ve.input==="text"&&Ae.input?.includes("image")&&(ve.input="text-image"),!ve.reasoning&&Ae.reasoning&&(ve.reasoning=!0),ve}),pe=new Set(ue.map(ye=>ye.id.trim()).filter(Boolean)),ke=w.filter(ye=>!pe.has(ye.id)).map(ye=>({id:ye.id,name:ye.name??"",reasoning:ye.reasoning??!1,input:ye.input?.includes("image")?"text-image":"text",contextWindow:ye.contextWindow?String(ye.contextWindow):"",maxTokens:ye.maxTokens?String(ye.maxTokens):""})),Be=[...ue,...ke];return Be.some(ye=>ye.id.trim())?{...de,models:Be.filter(ye=>ye.id.trim())}:de}),R({ok:!0,text:l("fetchModelsOk",{n:w.length})})}else R({ok:!1,text:a.error||l("fetchModelsEmpty")})},[a]);const F=w=>{const de=(h[w.id]??"").trim();!de||x||(v(w.id),ie({type:"add_provider_key",provider:w.id,apiKey:de,name:(m[w.id]??"").trim()||void 0}),setTimeout(()=>{v(null),b(ue=>({...ue,[w.id]:""})),f(ue=>({...ue,[w.id]:""})),ie({type:"list_providers"}),ie({type:"list_provider_keys"})},1500))},T=(w,de)=>{ie({type:"activate_provider_key",provider:w,keyName:de}),ie({type:"list_provider_keys"})},U=(w,de)=>{window.confirm(l("removeKeyConfirm"))&&(ie({type:"remove_provider_key",provider:w,keyName:de}),ie({type:"list_provider_keys"}))},G=()=>{if(!Y)return;const w=Y.providerId.trim();if(!w||!Y.apiKey.trim())return;const de=Y.models.filter(pe=>pe.id.trim()).map(pe=>({id:pe.id.trim(),name:pe.name.trim()||void 0,reasoning:pe.reasoning||void 0,input:pe.input==="text-image"?["text","image"]:void 0,contextWindow:pe.contextWindow?Number(pe.contextWindow):void 0,maxTokens:pe.maxTokens?Number(pe.maxTokens):void 0})),ue={providerId:w,name:Y.name.trim()||void 0,api:Y.api.trim()||void 0,baseUrl:Y.baseUrl.trim()||void 0,apiKey:Y.apiKey.trim()||void 0,authHeader:Y.authHeader||void 0,models:de};ie({type:"save_model_config",providerId:w,config:ue}),J(null),o()},D=()=>{if(!u)return;const w=u.providerId.trim(),de=u.models.filter(pe=>pe.id.trim()).map(pe=>({id:pe.id.trim(),name:pe.name.trim()||void 0,reasoning:pe.reasoning||void 0,input:pe.input==="text-image"?["text","image"]:void 0,contextWindow:pe.contextWindow?Number(pe.contextWindow):void 0,maxTokens:pe.maxTokens?Number(pe.maxTokens):void 0})),ue={providerId:w,name:u.name.trim()||void 0,api:u.api.trim()||void 0,baseUrl:u.baseUrl.trim()||void 0,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader||void 0,models:de};ie({type:"save_model_config",providerId:w,config:ue}),o()};c.useEffect(()=>{if(i&&i.ok){const w=i.configs;if(w&&w.length>1){ce(w.map(de=>Ca({...de,apiKey:""}))),q("");return}if(i.config){J(Ca({...i.config,apiKey:""}));return}}},[i]);const se=w=>{window.confirm(l("clearKeyConfirm",{id:w}))&&ie({type:"clear_provider_api_key",provider:w})},ee=w=>{window.confirm(l("deleteProviderConfirm",{id:w.providerId,n:w.models.length}))&&ie({type:"delete_model_config",providerId:w.providerId})},Ne=(w,de)=>{u&&p({...u,models:u.models.map((ue,pe)=>pe===w?{...ue,...de}:ue)})};return s.jsx("div",{className:"modal-backdrop",onClick:o,children:s.jsxs("div",{className:"modal model-modal",onClick:w=>w.stopPropagation(),children:[s.jsx("button",{type:"button",className:"modal-close","aria-label":l("close"),onClick:o,children:s.jsx(tt,{})}),s.jsx("div",{className:"modal-head",children:s.jsx("h2",{children:Y?l("addKey"):$?l("batchCreateProviders",{n:$.length}):l(u?"editProvider":"manageModelsTitle")})}),Y?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"model-modal-body",children:s.jsxs("div",{className:"provider-form",children:[s.jsx("p",{className:"modal-desc",style:{marginBottom:12},children:l("secondKeyTitle",{api:Y.api,baseUrl:Y.baseUrl||l("noBaseUrlShort"),n:Y.models.length})}),s.jsxs("div",{className:"form-grid",children:[s.jsxs("label",{className:"field",children:[s.jsxs("span",{className:"field-label",children:[l("providerNameLabel")," ",s.jsx("em",{children:l("providerNameHint")})]}),s.jsx("input",{type:"text",value:Y.providerId,onChange:w=>J({...Y,providerId:w.target.value}),placeholder:"opencode-2"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:l("apiKeyLabel")}),s.jsx("input",{type:"password",value:Y.apiKey,onChange:w=>J({...Y,apiKey:w.target.value}),placeholder:l("secondKeyPlaceholder")})]})]}),s.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:8},children:[Y.models.slice(0,5).map(w=>w.id).join(", "),Y.models.length>5?` … +${Y.models.length-5}`:""]})]})}),s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>J(null),children:l("cancel")}),s.jsx("button",{type:"button",className:"btn",onClick:()=>{const w=Y;J(null),p(w)},children:l("advancedEdit")}),s.jsx("button",{type:"button",className:"btn primary",disabled:!Y.providerId.trim()||!Y.apiKey.trim(),onClick:G,children:l("save")})]})]}):$?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"model-modal-body",children:s.jsxs("div",{className:"provider-form",children:[s.jsx("p",{className:"modal-desc",style:{marginBottom:12},children:l("batchDesc",{apis:$.map(w=>w.api).join("、"),n:$.length})}),s.jsxs("label",{className:"field",style:{marginBottom:16},children:[s.jsx("span",{className:"field-label",children:l("batchKeyLabel",{n:$.length})}),s.jsx("input",{type:"password",value:ge,onChange:w=>q(w.target.value),placeholder:l("secondKeyPlaceholder")})]}),s.jsx("div",{className:"provider-list",style:{marginBottom:16},children:$.map((w,de)=>s.jsxs("div",{className:"provider-row",style:{flexDirection:"column",alignItems:"stretch",gap:6},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:13},children:[s.jsx("strong",{children:w.providerId}),s.jsx("span",{style:{opacity:.7},children:w.api})]}),s.jsxs("div",{className:"provider-sub",style:{fontSize:12,opacity:.7},children:[w.baseUrl||l("noBaseUrlShort")," · ",l("modelsCountShort",{n:w.models.length}),w.models.slice(0,3).map(ue=>ue.id).join(", "),w.models.length>3?` … +${w.models.length-3}`:""]}),s.jsx("input",{type:"text",value:w.providerId,onChange:ue=>ce(pe=>pe.map((ke,Be)=>Be===de?{...ke,providerId:ue.target.value}:ke)),placeholder:l("providerIdPlaceholder"),style:{fontSize:12}}),s.jsx("input",{type:"text",value:w.baseUrl,onChange:ue=>ce(pe=>pe.map((ke,Be)=>Be===de?{...ke,baseUrl:ue.target.value}:ke)),placeholder:l("baseUrlExamplePh"),style:{fontSize:12}})]},de))})]})}),s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>ce(null),children:l("cancel")}),s.jsx("button",{type:"button",className:"btn primary",disabled:!ge.trim(),onClick:()=>{for(const w of $){const de=w.providerId.trim();if(!de)continue;const ue=w.models.filter(ke=>ke.id.trim()).map(ke=>({id:ke.id.trim(),name:ke.name.trim()||void 0,reasoning:ke.reasoning||void 0,input:ke.input==="text-image"?["text","image"]:void 0,contextWindow:ke.contextWindow?Number(ke.contextWindow):void 0,maxTokens:ke.maxTokens?Number(ke.maxTokens):void 0})),pe={providerId:de,name:w.name.trim()||void 0,api:w.api.trim()||void 0,baseUrl:w.baseUrl.trim()||void 0,apiKey:ge.trim()||void 0,authHeader:w.authHeader||void 0,models:ue};ie({type:"save_model_config",providerId:de,config:pe})}ce(null),o()},children:l("saveAllBatch",{n:$.length})})]})]}):u?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"model-modal-body",children:s.jsxs("div",{className:"provider-form",children:[s.jsxs("div",{className:"form-grid",children:[s.jsxs("label",{className:"field",children:[s.jsxs("span",{className:"field-label",children:[l("providerId")," ",s.jsx("em",{children:l("providerIdHint")})]}),s.jsx("input",{type:"text",value:u.providerId,disabled:e.some(w=>w.providerId===u.providerId),onChange:w=>p({...u,providerId:w.target.value}),placeholder:"my-proxy"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:l("displayName")}),s.jsx("input",{type:"text",value:u.name,onChange:w=>p({...u,name:w.target.value}),placeholder:l("displayNamePh")})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:l("apiType")}),s.jsx("select",{value:u.api,onChange:w=>p({...u,api:w.target.value}),children:Tb.map(w=>s.jsx("option",{value:w,children:w},w))})]}),s.jsxs("label",{className:"field",children:[s.jsxs("span",{className:"field-label",children:["baseUrl ",s.jsx("em",{children:l("baseUrlHint")})]}),s.jsx("input",{type:"text",value:u.baseUrl,onChange:w=>p({...u,baseUrl:w.target.value}),placeholder:"http://localhost:11434/v1"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:l("apiKey")}),s.jsx("input",{type:"password",value:u.apiKey,onChange:w=>p({...u,apiKey:w.target.value}),placeholder:l("apiKeyHint")})]}),s.jsxs("label",{className:"field check",children:[s.jsx("input",{type:"checkbox",checked:u.authHeader,onChange:w=>p({...u,authHeader:w.target.checked})}),s.jsx("span",{children:l("authHeader")})]})]}),s.jsxs("div",{className:"model-section-head",children:[s.jsx("span",{className:"form-section-title",children:l("modelsTitle")}),s.jsxs("span",{className:"model-section-actions",children:[A&&s.jsx("span",{className:`fetch-msg ${A.ok?"ok":"err"}`,title:A.text,children:A.text}),s.jsxs("button",{type:"button",className:"btn sm",disabled:N||!u.baseUrl.trim(),title:l("fetchModelsHint"),onClick:j,children:[s.jsx(ss,{})," ",l(N?"fetchingModels":"fetchModels")]})]})]}),u.models.map((w,de)=>s.jsxs("div",{className:"model-row",children:[s.jsx("input",{type:"text",value:w.id,onChange:ue=>Ne(de,{id:ue.target.value}),placeholder:l("modelIdReq")}),s.jsx("input",{type:"text",value:w.name,onChange:ue=>Ne(de,{name:ue.target.value}),placeholder:l("displayName")}),s.jsxs("select",{value:w.input,onChange:ue=>Ne(de,{input:ue.target.value}),children:[s.jsx("option",{value:"text",children:l("text")}),s.jsx("option",{value:"text-image",children:l("textImage")})]}),s.jsxs("label",{className:"check",children:[s.jsx("input",{type:"checkbox",checked:w.reasoning,onChange:ue=>Ne(de,{reasoning:ue.target.checked})}),s.jsx("span",{children:l("reasoning")})]}),s.jsx("input",{type:"number",value:w.contextWindow,onChange:ue=>Ne(de,{contextWindow:ue.target.value}),placeholder:l("contextWindow"),title:"contextWindow"}),s.jsx("input",{type:"number",value:w.maxTokens,onChange:ue=>Ne(de,{maxTokens:ue.target.value}),placeholder:l("maxOutput"),title:"maxTokens"}),s.jsx("button",{type:"button",className:"iconbtn danger",title:l("removeModel"),onClick:()=>p({...u,models:u.models.filter((ue,pe)=>pe!==de)}),children:s.jsx(ut,{})})]},de)),s.jsxs("button",{type:"button",className:"btn",onClick:()=>p({...u,models:[...u.models,bi()]}),children:[s.jsx(kt,{})," ",l("addModel")]})]})}),s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>p(null),children:l("cancel")}),s.jsx("button",{type:"button",className:"btn primary",disabled:!u.providerId.trim()||!u.models.some(w=>w.id.trim()),onClick:D,children:l("save")})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"model-modal-fixed-hint",children:s.jsxs("div",{className:"form-section-title",children:[l("builtinProviders")," ",s.jsx("em",{className:"section-hint",children:l("hintKeyOnly")})]})}),s.jsxs("div",{className:"model-modal-body",children:[s.jsxs("div",{className:"provider-list",children:[t.length===0&&s.jsx("div",{className:"dd-loading",children:l("loading")}),t.map(w=>{const de=n[w.id]??[];return s.jsxs("div",{className:"provider-row provider-key-row",children:[s.jsxs("div",{className:"provider-key-head",children:[s.jsxs("div",{className:"provider-info",children:[s.jsx("span",{className:"provider-name",children:w.name}),s.jsxs("span",{className:"provider-sub",children:[w.id,w.configured&&s.jsx("span",{className:"auth-badge",children:l("configuredBadge")}),w.source&&!w.configured&&s.jsx("span",{className:"auth-badge dim",children:w.source})]})]}),w.source==="stored"&&s.jsxs("button",{type:"button",className:"btn sm danger",title:l("clearKeyTitle"),onClick:()=>se(w.id),children:[s.jsx(ut,{})," ",l("clearKey")]})]}),s.jsxs("div",{className:"provider-keys",children:[de.length===0&&s.jsx("div",{className:"provider-key-empty",children:l("noKeyYet")}),de.map(ue=>s.jsxs("div",{className:`provider-key-item ${ue.active?"active":""}`,children:[s.jsx("span",{className:"provider-key-dot",children:ue.active?"●":"○"}),s.jsx("span",{className:"provider-key-label",children:ue.name}),!ue.active&&s.jsx("button",{type:"button",className:"iconbtn",title:l("activateKey"),onClick:()=>T(w.id,ue.name),children:s.jsx(Lt,{})}),s.jsx("button",{type:"button",className:"iconbtn danger",title:l("removeKey"),onClick:()=>U(w.id,ue.name),children:s.jsx(ut,{})})]},ue.name)),s.jsxs("div",{className:"provider-add-key",children:[s.jsx("input",{type:"text",className:"key-input key-input-name",placeholder:l("keyNamePh"),value:m[w.id]??"",onChange:ue=>f(pe=>({...pe,[w.id]:ue.target.value}))}),s.jsx("input",{type:"password",className:"key-input key-input-value",placeholder:l("addKeyPlaceholder"),value:h[w.id]??"",onChange:ue=>b(pe=>({...pe,[w.id]:ue.target.value}))}),s.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(h[w.id]??"").trim()||x===w.id,onClick:()=>F(w),children:[s.jsx(kt,{})," ",x===w.id?l("savingKey"):l("addKey")]})]})]})]},w.id)})]}),s.jsx("div",{className:"form-section-title",children:l("customProviders")}),s.jsx("p",{className:"modal-desc",children:l("customDesc")}),s.jsx("p",{className:"modal-desc",children:l("reloadModelsHint")}),e.length===0&&s.jsx("div",{className:"dd-loading",children:l("noCustomProviders")}),s.jsx("div",{className:"provider-list",children:e.map(w=>s.jsxs("div",{className:"provider-row",children:[s.jsxs("div",{className:"provider-info",children:[s.jsx("span",{className:"provider-name",children:w.providerId}),s.jsxs("span",{className:"provider-sub",children:[w.api??"—",w.baseUrl?` · ${w.baseUrl}`:"",w.models.length>0&&` · ${l("modelsCount",{n:w.models.length})}`]})]}),s.jsxs("div",{className:"provider-actions",children:[s.jsx("button",{type:"button",className:"iconbtn",title:l("edit"),onClick:()=>p(Ca(w)),children:s.jsx(An,{})}),s.jsx("button",{type:"button",className:"iconbtn danger",title:l("delete"),onClick:()=>ee(w),children:s.jsx(ut,{})})]})]},w.providerId))})]}),s.jsxs("div",{className:"modal-actions",children:[s.jsxs("button",{type:"button",className:"btn",onClick:()=>ie({type:"reload_models_config"}),children:[s.jsx(Rt,{})," ",l("reloadModelsConfig")]}),s.jsxs("button",{type:"button",className:"btn primary",onClick:()=>p(xb()),children:[s.jsx(kt,{})," ",l("addProvider")]})]})]})]})})}function nt({text:e}){const t=c.useRef(null),n=c.useRef(null),[a,i]=c.useState(!1),[o,l]=c.useState({left:0,top:0}),u=()=>{const h=t.current?.getBoundingClientRect();h&&(l({left:Math.max(8,h.left-8),top:h.bottom+8}),i(!0))},p=()=>i(!1);return c.useEffect(()=>{if(!a)return;const h=n.current,b=t.current;if(!h||!b)return;const m=h.getBoundingClientRect(),f=b.getBoundingClientRect(),x=cc(f,m,{width:window.innerWidth,height:window.innerHeight});l(v=>v.left===x.left&&v.top===x.top?v:x)},[a,e]),c.useEffect(()=>{if(!a)return;const h=()=>i(!1);return window.addEventListener("scroll",h,!0),window.addEventListener("resize",h),()=>{window.removeEventListener("scroll",h,!0),window.removeEventListener("resize",h)}},[a]),s.jsxs("span",{ref:t,className:"set-tip",tabIndex:0,"aria-label":e,onMouseEnter:u,onMouseLeave:p,onFocus:u,onBlur:p,onKeyDown:h=>{h.key==="Escape"&&h.target.blur()},children:["?",a&&Jn.createPortal(s.jsx("span",{ref:n,className:"set-tip-bubble open",role:"tooltip",style:{position:"fixed",left:o.left,top:o.top},children:e}),document.body)]})}function kb({plugin:e}){const t=Me(),n=e.settingsSchema??[],[a,i]=c.useState(()=>({...e.settingsValues})),[o,l]=c.useState(!1);if(n.length===0)return null;const u=(m,f)=>i(x=>({...x,[m]:f})),p=n.some(m=>a[m.key]!==e.settingsValues?.[m.key]),h=()=>{l(!0),ie({type:"plugin_settings",pluginId:e.id,values:a}),setTimeout(()=>l(!1),800)},b=()=>i({...e.settingsValues});return s.jsxs("div",{className:"plugin-settings-form",children:[s.jsx("div",{className:"plugin-settings-fields",children:n.map(m=>s.jsxs("label",{className:"plugin-settings-field",title:m.hint,children:[s.jsx("span",{className:"plugin-settings-label",children:m.label}),m.type==="boolean"?s.jsx("input",{type:"checkbox",checked:!!a[m.key],onChange:f=>u(m.key,f.target.checked)}):m.type==="select"?s.jsx("select",{value:String(a[m.key]??""),onChange:f=>u(m.key,f.target.value),children:(m.options??[]).map(f=>s.jsx("option",{value:f,children:f},f))}):s.jsx("input",{type:m.type==="password"?"password":m.type==="number"?"number":"text",value:String(a[m.key]??""),min:m.min,max:m.max,onChange:f=>u(m.key,m.type==="number"?Number(f.target.value):f.target.value)})]},m.key))}),s.jsxs("div",{className:"plugin-settings-actions",children:[s.jsx("button",{type:"button",className:"btn plugin-settings-save",disabled:!p||o,onClick:h,children:t(o?"pluginSettingsSaving":"pluginSettingsSave")}),s.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:b,children:t("pluginSettingsReset")})]})]})}const gc="pi-web-ui:wide-chat",Kn={wide:!1};function bc(e){if(!e||typeof e!="object")return{...Kn};const t=e;return{wide:typeof t.wide=="boolean"?t.wide:Kn.wide}}function Nb(){try{const e=localStorage.getItem(gc);return e?bc(JSON.parse(e)):{...Kn}}catch{return{...Kn}}}function vb(e){const t=bc(e);try{localStorage.setItem(gc,JSON.stringify(t))}catch{}Tn=t;for(const n of ei)n()}let Tn=null;const ei=new Set;function Cb(e){return ei.add(e),()=>{ei.delete(e)}}function wb(){return Tn||(Tn=Nb()),Tn.wide}function Ec(){return c.useSyncExternalStore(Cb,wb)}const Tc="pi-web-ui:project-title",Yn={projectName:!0};function xc(e){if(!e||typeof e!="object")return{...Yn};const t=e;return{projectName:typeof t.projectName=="boolean"?t.projectName:Yn.projectName}}function Sb(e){return e?e.replace(/[\\/]+$/,"").split(/[\\/]/).pop()??"":""}function _b(){try{const e=localStorage.getItem(Tc);return e?xc(JSON.parse(e)):{...Yn}}catch{return{...Yn}}}function Ab(e){const t=xc(e);try{localStorage.setItem(Tc,JSON.stringify(t))}catch{}xn=t;for(const n of ti)n()}let xn=null;const ti=new Set;function Ib(e){return ti.add(e),()=>{ti.delete(e)}}function jb(){return xn||(xn=_b()),xn.projectName}function yc(){return c.useSyncExternalStore(Ib,jb)}const kc="pi-web-ui:wallpaper",Rb="has-wallpaper",Ws={url:"",dim:78,blur:0},Lb=2e3,Db=28e5;function si(e){if(typeof e!="string")return"";const t=e.trim();if(!t)return"";const n=t.toLowerCase().startsWith("data:image/")?Db:Lb;return t.length>n?"":/^https?:\/\//i.test(t)||/^blob:/i.test(t)||/^data:image\//i.test(t)||t.startsWith("/")&&!t.startsWith("//")?t:""}const ro=(e,t,n,a)=>typeof e!="number"||!Number.isFinite(e)?a:Math.min(n,Math.max(t,Math.round(e)));function Nc(e){if(!e||typeof e!="object")return{...Ws};const t=e;return{url:si(t.url),dim:ro(t.dim,0,95,Ws.dim),blur:ro(t.blur,0,24,Ws.blur)}}function vc(){try{const e=localStorage.getItem(kc);return e?Nc(JSON.parse(e)):{...Ws}}catch{return{...Ws}}}function Pb(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/[\r\n]/g,"")}async function Ob(e){const t=await fi(e);return t?`data:${t.mimeType};base64,${t.data}`:null}function yn(){const e=Ks??vc(),t=document.documentElement;e.url?(t.style.setProperty("--bg-image",`url("${Pb(e.url)}")`),t.style.setProperty("--bg-image-dim",String(e.dim/100)),t.style.setProperty("--bg-image-blur",`${e.blur}px`)):(t.style.removeProperty("--bg-image"),t.style.removeProperty("--bg-image-dim"),t.style.removeProperty("--bg-image-blur"));const n=getComputedStyle(t).getPropertyValue("--bg-image").trim();document.body.classList.toggle(Rb,e.url!==""||n!==""&&n!=="none")}function _s(e){const t=Nc(e);Ks=t;try{localStorage.setItem(kc,JSON.stringify(t))}catch{}for(const n of ni)n();yn()}let Ks=null;const ni=new Set;function Mb(e){return ni.add(e),()=>{ni.delete(e)}}function Bb(){return Ks||(Ks=vc()),Ks}function Cc(){return c.useSyncExternalStore(Mb,Bb)}function Fb(){const e=Cc();c.useEffect(()=>{yn()},[e]),c.useEffect(()=>{const t=()=>yn();return window.addEventListener(zt,t),yn(),()=>window.removeEventListener(zt,t)},[])}const Gn={zh:["继续","总结一下","详细解释一下","检查并修复问题","补充测试覆盖","发布上传"],en:["Continue","Summarize","Explain in detail","Check and fix issues","Add test coverage","Publish release"],it:["Continua","Riassumi","Spiega in dettaglio","Verifica e correggi i problemi","Aggiungi copertura dei test","Pubblica la release"],ja:["続ける","要約して","詳しく説明して","問題を確認して修正","テストカバレッジを追加","公開・リリース"],ko:["계속","요약해줘","자세히 설명해줘","문제를 확인하고 수정","테스트 커버리지 추가","게시/릴리스"],fr:["Continuer","Résumer","Expliquer en détail","Vérifier et corriger les problèmes","Ajouter des tests","Publier"],de:["Weiter","Zusammenfassen","Ausführlich erklären","Probleme prüfen und beheben","Testabdeckung ergänzen","Veröffentlichen"],es:["Continuar","Resumir","Explicar en detalle","Revisar y corregir problemas","Añadir cobertura de pruebas","Publicar"],ru:["Продолжить","Подведи итог","Объясни подробно","Проверь и исправь проблемы","Добавь покрытие тестами","Опубликовать"],pt:["Continuar","Resumir","Explique em detalhes","Verifique e corrija os problemas","Adicione cobertura de testes","Publique a release"]},wc=["soul","tools","guidelines","pi_docs","append","persona","terminal","markers","context","skills","cwd"],Hb=["tools","pi_docs","persona","terminal","markers","context","skills","cwd"];function Sc(e){return Hb.includes(e)}const cn=wc.map(e=>`{{${e}}}`).join(`
340
+ `)}}let va=null;function jg(){if(va?.isConnected)return va;const e=document.createElement("div");e.setAttribute("aria-hidden","true"),e.setAttribute("data-caret-mirror","");const t=e.style;return t.position="fixed",t.top="0",t.left="-99999px",t.visibility="hidden",t.pointerEvents="none",t.margin="0",t.padding="0",t.border="0",t.boxSizing="content-box",t.overflow="visible",document.body.appendChild(e),va=e,e}function Rg(e,t){const n=getComputedStyle(e),a=t.style;a.fontFamily=n.fontFamily,a.fontSize=n.fontSize,a.fontStyle=n.fontStyle,a.fontWeight=n.fontWeight,a.fontVariant=n.fontVariant,a.fontStretch=n.fontStretch,a.lineHeight=n.lineHeight,a.letterSpacing=n.letterSpacing,a.wordSpacing=n.wordSpacing,a.textTransform=n.textTransform,a.textIndent=n.textIndent,a.tabSize=n.tabSize,a.whiteSpace=n.whiteSpace||"pre-wrap",a.overflowWrap=n.overflowWrap||"break-word",a.wordBreak=n.wordBreak||"normal",a.direction=n.direction,a.writingMode=n.writingMode;const i=e.clientWidth-(parseFloat(n.paddingLeft)||0)-(parseFloat(n.paddingRight)||0);return i>0?(a.width=`${i}px`,i):0}function Jr(e,t){e.textContent=t;const n=document.createElement("span");return n.textContent=_g,e.appendChild(n),n.offsetTop}function Lg(e){const t=e.value,n=e.selectionStart;if(n!==e.selectionEnd)return{first:!1,last:!1};const a=Ig(t,n);if(!a.first&&!a.last||typeof document>"u"||typeof getComputedStyle!="function")return a;const i=jg();if(Rg(e,i)<=0)return a;const o=Jr(i,t.slice(0,n)),l=Jr(i,t),u=i.offsetHeight>0;return i.textContent="",!u&&t!==""?a:Ag(o,l)}const bi="pi-web-ui:prompt-history",Dg=100,ic="pi-web-ui:prompt-history-settings",Za={maxEntries:100,charLimitEnabled:!1,charLimit:2e3};function rc(e){const t=Za;if(!e||typeof e!="object")return{...t};const n=e;let a=typeof n.maxEntries=="number"?Math.floor(n.maxEntries):t.maxEntries;(!Number.isFinite(a)||a<1)&&(a=1),a>500&&(a=500);let i=typeof n.charLimit=="number"?Math.floor(n.charLimit):t.charLimit;(!Number.isFinite(i)||i<100)&&(i=100),i>2e4&&(i=2e4);const o=typeof n.charLimitEnabled=="boolean"?n.charLimitEnabled:t.charLimitEnabled;return{maxEntries:a,charLimitEnabled:o,charLimit:i}}function oc(){try{const e=localStorage.getItem(ic);return e?rc(JSON.parse(e)):{...Za}}catch{return{...Za}}}function Ca(e){const t=rc(e);try{localStorage.setItem(ic,JSON.stringify(t))}catch{}try{let n=Vs();t.charLimitEnabled&&(n=n.map(a=>a.length>t.charLimit?a.slice(0,t.charLimit):a)),n.length>t.maxEntries&&(n=n.slice(n.length-t.maxEntries)),lc(n)}catch{}}function Pg(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(typeof n!="string")continue;const a=n.trim();a&&t.push(a)}return t}function Og(e,t,n=Dg){const a=t.trim();if(!a||e.length>0&&e[e.length-1]===a)return e;const i=[...e,a];return i.length>n?i.slice(i.length-n):i}function Vs(){try{const e=localStorage.getItem(bi);return e?Pg(JSON.parse(e)):[]}catch{return[]}}function lc(e){let t=e;for(;t;)try{localStorage.setItem(bi,JSON.stringify(t));return}catch(n){if(!(n instanceof DOMException&&(n.name==="QuotaExceededError"||n.code===22))||t.length<=1)return;t=t.slice(Math.ceil(t.length/2))}}function Zr(e){let t=e.trim();if(!t)return;const n=oc();n.charLimitEnabled&&t.length>n.charLimit&&(t=t.slice(0,n.charLimit));const a=Vs(),i=Og(a,t,n.maxEntries);i!==a&&lc(i)}function Mg(){try{localStorage.removeItem(bi)}catch{}}const eo="skill:";function Bg(e,t){const n=e.toLowerCase();return t==="skill"&&n.startsWith(eo)?[n,n.slice(eo.length)]:[n]}function Fg(e,t){const n=t.toLowerCase();return n?e.filter(a=>Bg(a.name,a.source).some(i=>i.startsWith(n))):[...e]}function Hg(e){const t=e.query;if(!t||!t("(pointer: coarse)")||!t("(hover: none)"))return!1;const n=e.userAgent??"";return!(/Windows|CrOS/i.test(n)||/Linux/i.test(n)&&!/Android/i.test(n)||/Macintosh/i.test(n)&&(e.maxTouchPoints??0)<=1)}function Ug(){return typeof window>"u"||typeof navigator>"u"||typeof window.matchMedia!="function"?!1:Hg({query:e=>window.matchMedia(e).matches,userAgent:navigator.userAgent,maxTouchPoints:navigator.maxTouchPoints})}const cc=["off","minimal","low","medium","high","xhigh","max"],$g=c.memo(function({state:t,models:n,modelsLoading:a,onManageModels:i,providerKeys:o,compact:l=!1}){const u=Pe(),p=t?.model,h=p?`${p.provider}/${p.id}`:null,[b,m]=c.useState(!1),[f,x]=c.useState(!1),[v,N]=c.useState(""),[B,V]=c.useState(null),[W,I]=c.useState({}),j=c.useRef(null),X=c.useRef(null),[w,ce]=c.useState(null);c.useEffect(()=>{if(!b){ce(null);return}if(n.length===0)return;const D=requestAnimationFrame(()=>{const ae=X.current;ae&&ce(ae.offsetWidth)});return()=>cancelAnimationFrame(D)},[b,n.length]),c.useEffect(()=>{b&&I(Zl())},[b]),c.useEffect(()=>{b||(N(""),V(null))},[b]);const be=c.useMemo(()=>{const D=new Map;for(const ee of n)D.set(ee.provider,(D.get(ee.provider)??0)+1);const ae=[];for(const[ee,ve]of[...D.entries()].sort((S,de)=>S[0].localeCompare(de[0]))){const S=o[ee];if(S&&S.length>1)for(const de of S)ae.push({provider:ee,keyName:de.name,count:ve});else ae.push({provider:ee,keyName:null,count:ve})}return ae},[n,o]),$=c.useMemo(()=>fg(n,W),[n,W]),K=c.useMemo(()=>{let D=$;B&&(D=D.filter(ee=>ee.provider===B.provider));const ae=v.trim().toLowerCase();return ae?D.filter(ee=>ee.name.toLowerCase().includes(ae)||ee.provider.toLowerCase().includes(ae)||ee.id.toLowerCase().includes(ae)):D},[$,v,B]),J=c.useMemo(()=>{const D=[];for(const ae of K){const ee=o[ae.provider];if(!ee||ee.length<=1){D.push({model:ae,key:null});continue}let ve=ee.find(S=>S.active)??ee[0];if(B?.provider===ae.provider&&B.keyName){const S=ee.find(de=>de.name===B.keyName);S&&(ve=S)}D.push({model:ae,key:ve})}return D},[K,o,B]),[L,H]=c.useState(!1),T=t?.availableThinkingLevels&&t.availableThinkingLevels.length>0?new Set(t.availableThinkingLevels):null,F=cc.map(D=>({value:D,label:u(`thinking.${D}`),supported:T?T.has(D):!0})),Y=D=>F.find(ae=>ae.value===D)?.label??D;return c.useEffect(()=>{b&&n.length===0&&!L&&!a&&(H(!0),ie({type:"list_models"}))},[b,n.length,L,a]),c.useEffect(()=>{n.length>0&&H(!1)},[n.length]),c.useEffect(()=>{if(!b)return;j.current?.querySelector(".dd-item.active")?.scrollIntoView({block:"nearest"})},[b,h,n.length]),s.jsxs(s.Fragment,{children:[s.jsxs(Yt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(Gs,{}),s.jsx("span",{className:"chip-model",children:p?p.name:u("selectModel")}),!l&&p?.vision&&s.jsx("span",{className:"chip-vision",title:u("vision"),children:"🖼"}),!l&&p&&s.jsx("span",{className:"chip-sub",children:p.provider})]}),open:b,onOpenChange:m,menuClassName:"dd-menu-model",menuRef:X,menuStyle:w!=null?{width:w}:void 0,direction:"up",children:[s.jsx("div",{className:"dd-header",children:u("availableModels")}),s.jsxs("div",{className:"dd-search-row",children:[s.jsx(An,{}),s.jsx("input",{className:"dd-search",type:"text",placeholder:u("searchModels"),value:v,onChange:D=>N(D.target.value)})]}),s.jsxs("div",{className:"dd-model-body",children:[be.length>1&&s.jsxs("div",{className:"dd-provider-col",children:[s.jsx("div",{className:"dd-provider-head",children:u("providers")}),s.jsx("button",{type:"button",className:`dd-provider-item ${B===null?"active":""}`,onClick:()=>V(null),children:s.jsx("span",{children:u("allProviders")})}),be.map(D=>{const ae=B?.provider===D.provider&&B?.keyName===D.keyName;return s.jsxs("button",{type:"button",className:`dd-provider-item ${ae?"active":""}`,onClick:()=>V(ae?null:{provider:D.provider,keyName:D.keyName}),title:D.keyName?`${D.provider} · ${D.keyName}`:`${D.provider} · ${D.count}`,children:[s.jsxs("span",{className:"dd-provider-txt",children:[s.jsx("span",{className:"dd-provider-name",children:D.provider}),D.keyName&&s.jsx("span",{className:"dd-provider-key",children:D.keyName})]}),s.jsx("span",{className:"dd-provider-count",children:D.count})]},D.keyName?`${D.provider}::${D.keyName}`:D.provider)})]}),s.jsxs("div",{className:"dd-model-scroll",ref:j,children:[(L||a)&&s.jsx("div",{className:"dd-loading",children:u("loading")}),n.length===0&&!L&&!a&&s.jsx("div",{className:"dd-loading",children:u("noModels")}),K.length===0&&n.length>0&&s.jsx("div",{className:"dd-loading",children:u("noModelMatches")}),J.map(D=>{const ae=D.model,ee=h===ae.id&&(!D.key||D.key.active);return s.jsx(ft,{active:ee,onClick:()=>{D.key&&!D.key.active&&ie({type:"activate_provider_key",provider:ae.provider,keyName:D.key.name}),h!==ae.id&&ie({type:"set_model",modelId:ae.id}),m(!1)},children:s.jsxs("span",{className:"dd-model-cell",children:[s.jsx("span",{className:"dd-model-name",children:ae.name}),s.jsxs("span",{className:"dd-model-meta",children:[s.jsx("span",{className:"dd-model-provider",children:ae.provider}),s.jsx("span",{className:"dd-model-id",children:ae.id.split("/").slice(1).join("/")}),D.key&&s.jsxs("span",{className:`dd-model-key ${D.key.active?"active":""}`,children:[D.key.active?"●":"○"," ",D.key.name]}),(W[ae.id]??0)>0&&s.jsx("span",{className:"dd-model-usage",children:u("modelUsedCount",{n:W[ae.id]})}),(ae.reasoning||ae.vision)&&s.jsxs("span",{className:"dd-model-badges",children:[ae.reasoning&&s.jsx("span",{className:"dd-model-badge",children:u("reasoning")}),ae.vision&&s.jsx("span",{className:"dd-model-badge",children:u("vision")})]})]})]})},D.key?`${ae.id}::${D.key.name}`:ae.id)})]})]}),s.jsxs("div",{className:"dd-footer",children:[s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>ie({type:"list_models"}),children:u("refreshModels")}),s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{m(!1),i()},children:u("manageModels")})]})]}),s.jsxs(Yt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(ms,{}),s.jsx("span",{className:"chip-sub",children:u("thinkingChip",{level:t?Y(t.thinkingLevel):"—"})})]}),open:f,onOpenChange:x,direction:"up",children:[s.jsx("div",{className:"dd-header",children:u("thinkingLevel")}),F.map(D=>s.jsx(ft,{active:t?.thinkingLevel===D.value,disabled:!D.supported,title:D.supported?void 0:u("thinkingUnsupported"),onClick:()=>{t?.thinkingLevel!==D.value&&ie({type:"set_thinking",level:D.value}),x(!1)},children:D.label},D.value))]})]})}),to=Ug(),qg=c.memo(function({streaming:t,messages:n,slashCommands:a,modelState:i,models:o,modelsLoading:l,attachments:u,onRemoveAttachment:p,onAddImageFiles:h,onAddLocalFiles:b,onNotice:m,onSent:f,onManageModels:x,providerKeys:v,quickPhrases:N,quickPhrasesEnabled:B,recallDrafts:V,composerActions:W,onUiAction:I}){const j=Pe(),X=wt("ready"),w=Yo(),{locale:ce}=Ut(),{openPicker:be}=nc(),$=y=>ce!=="zh"&&y.descriptionEn?y.descriptionEn:y.description??"",K=y=>ce!=="zh"&&y.argumentHintEn?y.argumentHintEn:y.argumentHint??"",[J,L]=c.useState(""),[H,T]=c.useState(null),[F,Y]=c.useState(0),[D,ae]=c.useState(!1),[ee,ve]=c.useState(void 0),S=c.useRef(null),de=c.useRef(null),ue=c.useRef(null),pe=c.useRef(-1),ke=c.useRef(""),Oe=c.useRef(0);c.useEffect(()=>{if(!V||V.length===0)return;const y=V.filter(P=>P.text&&P.seq>Oe.current);y.length!==0&&(Oe.current=y[y.length-1].seq,L(P=>y.reduce((le,Ee)=>Qr(le,Ee.text),P)),pe.current=-1,ke.current="",requestAnimationFrame(()=>{const P=S.current;P&&(P.focus(),P.selectionStart=P.selectionEnd=P.value.length)}))},[V]),c.useEffect(()=>(Fi(y=>{L(P=>Qr(P,y)),pe.current=-1,ke.current="",requestAnimationFrame(()=>{const P=S.current;P&&(P.focus(),P.selectionStart=P.selectionEnd=P.value.length)})}),()=>Fi(null)),[]);const ye={builtin:j("slashBuiltin"),extension:j("slashExtension"),prompt:j("slashPrompt"),skill:j("slashSkill"),plugin:j("slashPlugin")},we=y=>{const P=y.match(/^\/([^\s]*)$/);if(P&&X){const le=P[1].toLowerCase(),Ee=Fg(a,le);T(Ee.length>0?Ee:null),Y(0)}else T(null)};c.useEffect(()=>{ue.current?.querySelector(".slash-item.active")?.scrollIntoView({block:"nearest"})},[F,H]);const Ce=y=>{const P=H??[],le=y??P[F%Math.max(P.length,1)];if(!le){T(null);return}const Ee=J.match(/^\/([^\s]*)([\s\S]*)$/),Ae=Ee?Ee[2]:"";L(`/${le.name} ${Ae}`),T(null),S.current?.focus()},qe=async()=>{const le=[...n].reverse().find(Ee=>Ee.role==="assistant"&&Ee.content.some(Ae=>Ae.type==="text"&&Ae.text))?.content.filter(Ee=>Ee.type==="text").map(Ee=>Ee.text).join(`
341
+ `);if(!le){m("warning",j("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(le),m("info",j("slashCopied"))}catch{m("error",j("slashCopyFailed"))}},Be=y=>{if(!y||y.length===0){m("warning",j("foldersNotSupported"));return}const P=Array.from(y).filter(Ae=>Ht(Ae.type)),le=Array.from(y).filter(Ae=>!Ht(Ae.type)),Ee=Te();P.length>0&&Ee?m("warning",Ee):P.length>0&&h(P),le.length>0&&b(le)},se=y=>{const P=y.clipboardData?.items;if(!P)return;const le=[];for(const Ae of P)if(Ae.kind==="file"&&Ht(Ae.type)){const Me=Ae.getAsFile();Me&&le.push(Me)}if(le.length===0)return;y.preventDefault();const Ee=Te();if(Ee){m("warning",Ee);return}h(le)},Te=()=>{const y=i?.model;if(!y?.id)return null;const P=o.find(le=>le.id===y.id);return P&&P.vision===!1?j("modelNoVision",{name:P.name}):null},De=X,Re=c.useRef(J);c.useEffect(()=>{Re.current=J},[J]),c.useEffect(()=>{we(Re.current)},[a]),c.useEffect(()=>{const y=P=>{const le=P.detail;L(le),S.current?.focus()};return window.addEventListener("pi-web:fill",y),()=>window.removeEventListener("pi-web:fill",y)},[]),c.useEffect(()=>{if(!D)return;const y=P=>{P.key==="Escape"&&ae(!1)};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[D]);const Ye=c.useRef(null);c.useEffect(()=>{const y=S.current,P=Ye.current;if(!y||!P)return;const le=y.closest("main")?.querySelector(".messages"),Ee=P.getBoundingClientRect().height,Ae=le?.scrollTop??0;y.style.height="auto";const Me=y.scrollHeight>220;if(y.style.height=`${Math.min(y.scrollHeight,220)}px`,y.style.overflowY=Me?"auto":"hidden",le){const Le=P.getBoundingClientRect().height-Ee;le.scrollTop=Ae+Le}},[J]);const A=()=>u.map(y=>y.imageData?{path:"",imageData:y.imageData,mimeType:y.mimeType,name:y.name}:y.fileData?{path:"",fileData:y.fileData,mimeType:y.mimeType,name:y.name,size:y.size}:{path:y.path,mode:y.mode,...y.lines?{lines:y.lines}:{},...y.mode==="page"?{name:y.name}:{}}),Q=(y=!1)=>{const P=J.trim(),le=u.some(Ee=>Ee.imageData||Ee.fileData);if(!(!De||!P&&!le)){if(P==="/help"){const Ee=S.current?.closest(".inputbox")?.getBoundingClientRect();ve(Ee?.width),ae(!0),L(""),S.current?.focus();return}if(P==="/copy"){L(""),S.current?.focus(),qe();return}if(ie({type:"prompt",text:P,queue:y,attachments:A()})){P&&Zr(P),pe.current=-1,ke.current="",L(""),f();const Ee=i?.model;Ee&&Yn(`${Ee.provider}/${Ee.id}`),S.current?.focus()}}},z=y=>{const P=y.trim();if(!(!De||!P)&&ie({type:"prompt",text:P,attachments:A()})){P&&Zr(P),pe.current=-1,ke.current="",f();const le=i?.model;le&&Yn(`${le.provider}/${le.id}`),to||S.current?.focus()}},ge=y=>{if(!y.nativeEvent.isComposing){if(H&&H.length>0)switch(y.key){case"ArrowDown":y.preventDefault(),Y(P=>(P+1)%H.length);return;case"ArrowUp":y.preventDefault(),Y(P=>(P-1+H.length)%H.length);return;case"Tab":case"Enter":y.preventDefault(),Ce();return;case"Escape":y.preventDefault(),T(null);return}if(y.key==="ArrowUp"||y.key==="ArrowDown"){if(y.ctrlKey||y.metaKey||y.altKey)return;const P=S.current;if(!P)return;const le=y.key==="ArrowUp",Ee=Lg(P);if(le&&!Ee.first||!le&&!Ee.last||!le&&pe.current===-1)return;const Ae=Vs();if(Ae.length===0)return;if(y.preventDefault(),le){if(pe.current===-1){ke.current=J;const Me=Ae.length-1;pe.current=Me;const Le=Ae[Me];L(Le),we(Le),requestAnimationFrame(()=>{const Ge=S.current;Ge&&(Ge.selectionStart=Ge.selectionEnd=Le.length)})}else if(pe.current>0){const Me=pe.current-1;pe.current=Me;const Le=Ae[Me];L(Le),we(Le),requestAnimationFrame(()=>{const Ge=S.current;Ge&&(Ge.selectionStart=Ge.selectionEnd=Le.length)})}}else{const Me=pe.current+1;if(Me<Ae.length){pe.current=Me;const Le=Ae[Me];L(Le),we(Le),requestAnimationFrame(()=>{const Ge=S.current;Ge&&(Ge.selectionStart=Ge.selectionEnd=Le.length)})}else{pe.current=-1;const Le=ke.current;L(Le),we(Le),requestAnimationFrame(()=>{const Ge=S.current;Ge&&(Ge.selectionStart=Ge.selectionEnd=Le.length)})}}return}if(y.key==="Escape"&&pe.current!==-1){y.preventDefault();const P=ke.current;pe.current=-1,L(P),we(P),requestAnimationFrame(()=>{const le=S.current;le&&(le.selectionStart=le.selectionEnd=P.length)});return}if(y.key==="Enter"){if(to&&!y.shiftKey&&!(y.ctrlKey||y.metaKey))return;y.shiftKey||(y.preventDefault(),Q())}}},oe=De&&(J.trim()!==""||u.some(y=>y.imageData||y.fileData)),Z=()=>s.jsx("div",{className:"inputbox-actions",children:t?oe?s.jsxs("div",{className:`split-send${w?" single":""}`,children:[s.jsx("button",{type:"button",className:"split-queue",title:j("supplementTip"),"aria-label":j("queueFollowTag"),onClick:()=>Q(!0),children:s.jsx(Mu,{})}),!w&&s.jsx("button",{type:"button",className:"split-steer",title:j("steerTip"),"aria-label":j("queueSteerTag"),onClick:()=>Q(),children:s.jsx(La,{})})]}):s.jsx("button",{type:"button",className:"btn stop",title:j("stopAgent"),onClick:()=>ie({type:"abort"}),children:s.jsx(Sn,{})}):s.jsx("button",{type:"button",className:"btn send",title:j("sendTip"),disabled:!oe,onClick:()=>Q(),children:s.jsx(La,{})})});return s.jsxs("div",{ref:Ye,className:"inputbar",onDragOver:y=>{y.preventDefault()},onDrop:y=>{y.preventDefault(),y.stopPropagation(),Be(y.dataTransfer?.files??null)},children:[u.length>0&&s.jsxs("div",{className:"attach-row",children:[u.map(y=>s.jsxs("span",{className:`attach-chip ${y.imageData?"image":y.fileData?"file":y.mode}`,title:y.imageData?j("attachImage",{name:y.name}):y.fileData?j("attachFile",{name:y.name}):y.isDir?j("folderRef",{path:y.path}):y.mode==="page"?j("attachPage",{name:y.name}):y.mode==="reference"?j("refOnly",{path:y.path}):y.mode==="lines"&&y.lines?j("attachLines",{path:y.path,start:y.lines.start,end:y.lines.end}):j("attachContent",{path:y.path}),children:[y.imageData?"🖼":y.fileData?"📄":y.isDir?"📁":y.mode==="page"?"🌐":y.mode==="reference"?"🔗":"📎",y.name,y.mode==="lines"&&y.lines&&s.jsxs("span",{className:"attach-range",children:["L",y.lines.start,"-",y.lines.end]}),s.jsx("button",{type:"button",className:"attach-remove",title:j("removeAttachment"),onClick:()=>p(y.key??y.path),children:"×"})]},y.key??`${y.path}|${y.mode}|${y.lines?`${y.lines.start}-${y.lines.end}`:""}`)),s.jsx("span",{className:"attach-hint",children:j("attachHint")})]}),H&&H.length>0&&s.jsxs("div",{className:"slash-menu",role:"listbox",ref:ue,"aria-label":j("slashCommands"),children:[s.jsxs("div",{className:"slash-menu-hint",children:[s.jsx("span",{children:j("slashMenuHint")}),s.jsx("span",{className:"slash-menu-close",onClick:()=>T(null),children:"Esc"})]}),H.map((y,P)=>s.jsxs("button",{type:"button",className:`slash-item${P===F?" active":""}`,onMouseEnter:()=>Y(P),onClick:()=>Ce(y),children:[s.jsxs("span",{className:"slash-name",children:["/",y.name]}),s.jsx("span",{className:`slash-source ${y.source}`,children:ye[y.source]}),s.jsxs("span",{className:"slash-desc",children:[$(y),y.argumentHint&&s.jsx("span",{className:"slash-hint",children:K(y)})]})]},y.name))]}),D&&s.jsx("div",{className:"modal-backdrop",onClick:()=>ae(!1),children:s.jsxs("div",{className:"slash-help",style:ee?{width:ee}:void 0,onClick:y=>y.stopPropagation(),children:[s.jsxs("div",{className:"slash-help-head",children:[s.jsxs("span",{children:["⚡ ",j("slashHelpTitle")]}),s.jsx("button",{type:"button",className:"btn",onClick:()=>ae(!1),children:j("close")})]}),s.jsx("div",{className:"slash-help-body",children:a.length===0?s.jsx("div",{className:"slash-help-empty",children:j("slashLoading")}):a.map(y=>s.jsxs("div",{className:"slash-help-row",children:[s.jsxs("span",{className:"slash-help-cmd",children:["/",y.name]}),s.jsx("span",{className:`slash-source ${y.source}`,children:ye[y.source]}),s.jsxs("span",{className:"slash-help-desc",children:[$(y),y.argumentHint&&s.jsx("span",{className:"slash-hint",children:K(y)})]})]},y.name))})]})}),B&&N.length>0&&s.jsx("div",{className:"quick-row","aria-label":j("quickPhrases"),children:N.map(y=>s.jsx("button",{type:"button",className:"quick-chip",title:j("quickPhrasesTip",{text:y}),disabled:!De,onClick:()=>z(y),children:y},y))}),s.jsxs("div",{className:"inputbox",children:[s.jsx("input",{ref:de,type:"file",multiple:!0,hidden:!0,onChange:y=>{Be(y.target.files),y.target.value=""}}),s.jsx("textarea",{ref:S,value:J,rows:1,placeholder:j(De?t?w?"placeholderStreamingQueued":"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!De,onChange:y=>{pe.current=-1,L(y.target.value),we(y.target.value)},onKeyDown:ge,onPaste:se}),s.jsxs("div",{className:"composer-tools",children:[s.jsxs("div",{className:"composer-tools-left",children:[s.jsx("button",{type:"button",className:"btn attach-img",title:j("uploadFile"),disabled:!De,onClick:()=>de.current?.click(),children:s.jsx(_u,{})}),s.jsx("button",{type:"button",className:"btn tpl-open",title:j("tpl.openPicker"),onClick:be,children:s.jsx(Hu,{})}),s.jsx($g,{state:i,models:o,modelsLoading:l,onManageModels:x,providerKeys:v,compact:!0})]}),(W??[]).filter(y=>y.source!=="host"&&!y.hidden).map(y=>s.jsxs("button",{type:"button",className:"btn composer-plugin-action",title:y.label,onClick:()=>I?.(y),children:[y.icon?`${y.icon} `:"",y.label]},y.id)),s.jsx("div",{className:"composer-tools-right",children:Z()})]})]})]})}),Wg=c.memo(function({goal:t,models:n,modelsLoading:a,activeConversationId:i}){const o=Pe(),{locale:l}=Ut(),u=l!=="zh"&&t.statusEn?t.statusEn:t.status||"",p=l!=="zh"&&t.wizard?.statusEn?t.wizard.statusEn:t.wizard?.status||"",h=Yo(),b=!t.conversationId||t.conversationId===i,m=t.goal!==null&&b,[f,x]=c.useState(""),[v,N]=c.useState(t.reviewModel??""),[B,V]=c.useState(t.maxRounds),[W,I]=c.useState(t.locked),[j,X]=c.useState(!1),[w,ce]=c.useState(!1),[be,$]=c.useState(!0);c.useEffect(()=>{N(t.reviewModel??""),V(t.maxRounds||0),I(t.locked)},[t.goal,t.reviewModel,t.maxRounds,t.locked]),c.useEffect(()=>{j&&n.length===0&&!w&&!a&&(ce(!0),ie({type:"list_models"}))},[j,n.length,w,a]),c.useEffect(()=>{n.length>0&&ce(!1)},[n.length]);const K=()=>v?n.find(T=>T.id===v)?.name??v:o("goalBarUseMainModel"),J=()=>{const T=f.trim();T&&(ie({type:"set_goal",goal:T,...v?{reviewModel:v}:{},maxRounds:B,locked:W}),x(""),$(!1))},L=()=>{const T=f.trim();T&&(ie({type:"start_goal_wizard",text:T,...v?{wizardModel:v}:{},maxRounds:B,locked:W}),x(""),$(!1))},H=(t.wizard?.active??!1)&&b;return H?s.jsx("div",{className:`goalbar goalbar-active ${H?"wizard":""}`,children:s.jsxs("div",{className:"goalbar-active-row",children:[s.jsx("span",{className:"goalbar-icon",children:s.jsx("span",{className:"goalbar-spin",children:"🔍"})}),s.jsxs("span",{className:"goalbar-text",title:t.wizard?.draft??"",children:[o("goalWizardRunning"),": ",t.wizard?.draft]}),s.jsxs("span",{className:"goalbar-chip reviewing",children:[o("goalBarRound",{n:(t.wizard?.step??0)+1})," / ",t.wizard?.maxSteps??6]}),s.jsx("span",{className:"goalbar-detail",children:p||o("goalBarReviewing")}),s.jsx("button",{type:"button",className:"goalbar-x",title:o("goalBarClear"),onClick:()=>{ie({type:"clear_goal"}),$(!0)},children:s.jsx(tt,{})})]})}):m?s.jsx("div",{className:`goalbar goalbar-active ${t.reviewing?"reviewing":""}`,children:s.jsxs("div",{className:"goalbar-active-row",children:[s.jsx("span",{className:"goalbar-icon",children:t.reviewing?s.jsx("span",{className:"goalbar-spin",children:"◌"}):"🎯"}),s.jsx("span",{className:"goalbar-text",title:t.goal??"",children:t.goal}),t.reviewing?s.jsxs("span",{className:"goalbar-chip reviewing",children:[o("goalBarReviewing")," ",o("goalBarRound",{n:t.round})]}):s.jsx("span",{className:`goalbar-chip ${t.verdict==="pass"?"pass":t.verdict==="fail"?"fail":""}`,children:t.verdict==="pass"?o("goalBarPassed"):t.verdict==="fail"?o("goalBarFailed"):`${o("goalBarRound",{n:t.round||1})} · ${t.locked?o("goalBarLocked"):o("goalBarUnlocked")}`}),s.jsx("span",{className:"goalbar-detail",children:u}),s.jsx("button",{type:"button",className:"goalbar-x",title:o("goalBarClear"),disabled:t.reviewing,onClick:()=>{ie({type:"clear_goal"}),$(!0)},children:s.jsx(tt,{})})]})}):be?s.jsx("div",{className:"goalbar goalbar-collapsed",children:s.jsxs("button",{type:"button",className:"goalbar-hint",title:o("goalBarPlaceholder"),onClick:()=>$(!1),children:[s.jsx(ji,{})," ",s.jsx("span",{children:o("goalBarTitle")})]})}):s.jsxs("div",{className:"goalbar",children:[s.jsxs("div",{className:"goalbar-row",children:[s.jsx("span",{className:"goalbar-icon",children:s.jsx(ji,{})}),s.jsx("input",{className:"goalbar-input",value:f,placeholder:o("goalBarPlaceholder"),onChange:T=>x(T.target.value),onKeyDown:T=>{T.key==="Enter"&&J()}}),s.jsx("button",{type:"button",className:"goalbar-btn",disabled:!f.trim(),onClick:J,children:o("goalBarSet")}),s.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!f.trim(),title:o("goalWizardTip"),onClick:L,children:["🔍 ",o("goalWizardBtn")]}),s.jsx("button",{type:"button",className:"goalbar-icon-btn",title:o(W?"goalBarLocked":"goalBarUnlocked"),onClick:()=>I(T=>(ie({type:"set_goal_prefs",locked:!T}),!T)),children:W?s.jsx(Pu,{}):s.jsx(Cu,{})}),s.jsx("button",{type:"button",className:"goalbar-icon-btn",title:o("goalBarClear"),onClick:()=>$(!0),children:s.jsx(Zn,{})})]}),s.jsxs("div",{className:"goalbar-opts",children:[h?s.jsx("p",{className:"goalbar-dsh-note",children:o("dshNoReviewModel")}):s.jsxs(Yt,{trigger:s.jsxs("span",{className:"goalbar-opt",children:[o("goalBarReviewModel"),": ",s.jsx("b",{children:K()})]}),open:j,onOpenChange:X,direction:"up",children:[s.jsx("div",{className:"dd-header",children:o("goalBarReviewModel")}),(w||a)&&s.jsx("div",{className:"dd-loading",children:o("loading")}),n.length===0&&!w&&!a&&s.jsx("div",{className:"dd-loading",children:o("noModels")}),s.jsx(ft,{active:v==="",onClick:()=>{N(""),X(!1),ie({type:"set_goal_prefs",reviewModel:""})},children:o("goalBarUseMainModel")}),n.map(T=>s.jsx(ft,{active:v===T.id,onClick:()=>{N(T.id),X(!1),ie({type:"set_goal_prefs",reviewModel:T.id})},children:s.jsxs("span",{className:"dd-model-cell",children:[s.jsx("span",{className:"dd-model-name",children:T.name}),s.jsxs("span",{className:"dd-model-meta",children:[s.jsx("span",{className:"dd-model-provider",children:T.provider}),s.jsx("span",{className:"dd-model-id",children:T.id.split("/").slice(1).join("/")})]})]})},T.id)),s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>ie({type:"list_models"}),children:o("refreshModels")})]}),s.jsxs("label",{className:"goalbar-round",title:o("goalBarMaxRoundsTip"),children:[s.jsx("span",{children:o("goalBarMaxRounds")}),s.jsx("input",{type:"number",min:0,step:1,value:B,placeholder:o("goalBarUnlimitedShort"),onChange:T=>{const F=parseInt(T.target.value,10);if(Number.isNaN(F)||F<0){V(0);return}V(F)},onBlur:()=>ie({type:"set_goal_prefs",maxRounds:B}),onKeyDown:T=>{T.key==="Enter"&&(ie({type:"set_goal_prefs",maxRounds:B}),T.target.blur())}})]}),s.jsx("span",{className:"goalbar-lock-hint",children:o(W?"goalBarLocked":"goalBarUnlocked")})]})]})});function Kg(e){const t=Math.max(0,e.input??0),n=Math.max(0,e.cacheRead??0),a=Math.max(0,e.cacheWrite??0),i=t+n+a;return{totalInput:i,miss:t,read:n,write:a,hitRate:i>0?Math.min(n/i,1):0,writeRate:i>0?Math.min(a/i,1):0}}const uc=2e3;function Yg(e,t,n=uc){return e.filter(a=>t-a.t<=n)}function Gg(e,t=uc){if(e.length<2)return 0;const n=e[e.length-1],a=e.find(o=>o.t>=n.t-t)??e[0],i=(n.t-a.t)/1e3;return i<=0?0:Math.max(0,(n.out-a.out)/i)}function so(e){if(!e)return 0;let t=0;for(let a=0;a<e.length;a++){const i=e.charCodeAt(a);(i>=12352&&i<=12543||i>=13312&&i<=19903||i>=19968&&i<=40959||i>=63744&&i<=64255||i>=65280&&i<=65519||i===12288)&&t++}const n=e.length-t;return Math.round(t+n/4)}function zg(e){let t=0;for(const n of e)n.type==="text"&&typeof n.text=="string"&&n.text?t+=so(n.text):n.type==="thinking"&&typeof n.thinking=="string"&&n.thinking&&(t+=so(n.thinking));return t}const vt="@root",Vg=["host:conn","host:engine","host:ctx","host:cost","host:cache","host:msg-count","host:plugin-status","host:working","host:cwd"];function Qg({chat:e,bottombarItems:t,onUiAction:n}){const a=Pe(),{engine:i}=oi(),o=wt("workspaceRoots"),l=e.state,[u,p]=c.useState(!1),[h,b]=c.useState(""),[m,f]=c.useState(""),[x,v]=c.useState(!1),[N,B]=c.useState(""),[V,W]=c.useState(-1),I=c.useRef(null),j=c.useRef(null),X=e.pathCompletions.filter(se=>se.type==="dir"),w=se=>se.endsWith("/")?se:se+"/",ce=se=>{let Te=se.endsWith("/")&&se!=="/"?se.slice(0,-1):se;if(Te===vt||Te==="/")return null;const De=Te.lastIndexOf("/");if(De<0)return/^[A-Za-z]:$/.test(Te)?vt:null;if(De===0)return"/";const Re=Te.slice(0,De);return/^[A-Za-z]:$/.test(Re)?Re+"/":Re};c.useEffect(()=>{if(!u)return;const se=setTimeout(()=>{ie({type:"complete_path",path:w(h)})},60);return()=>clearTimeout(se)},[h,u]),c.useEffect(()=>{if(!u||m===h)return;const se=setTimeout(()=>{ie({type:"complete_path",path:m})},150);return()=>clearTimeout(se)},[m,h,u]);const be=c.useRef([]),$=l?.isStreaming??!1,K=l?.streamingMessage?zg(l.streamingMessage.content):0;if(c.useEffect(()=>{if(!$){be.current=[];return}const se=Date.now(),Te=be.current,De=Te[Te.length-1];De&&se-De.t<250||(be.current=Yg([...Te,{t:se,out:K}],se))},[$,K]),!l)return null;const J=l.stats,L=Kg(J.tokens),H=L.hitRate*100,T=L.totalInput===0?"":L.hitRate>=.7?"ok":L.hitRate>=.4?"mid":"warn",F=L.totalInput>0?`${H.toFixed(1)}%`:"—",Y=$?Gg(be.current):0,D=e.ready?"ok":"busy",ae=e.ready?a("connected"):a("connecting"),ee=J.contextUsage,ve=ee.tokens!==null&&ee.percent!==null?`${ee.estimated?"~":""}${us(ee.tokens)} / ${us(ee.contextWindow)}`:"—",S=ee.percent??null,de=S===null?"":S>=80?"warn":S>=50?"mid":"ok",ue=l.queue.steering.length+l.queue.followUp.length,pe=()=>{const se=l.cwd.replace(/\\/g,"/");f(se),b(se),v(!1),B(""),p(!0)},ke=se=>{const Te=se.trim();Te!==vt&&(Te&&Te!==l.cwd&&ie({type:"set_cwd",path:Te}),p(!1))},Oe=()=>{const se=N.trim();se&&(ie({type:"make_dir",path:`${w(h)}${se}`}),setTimeout(()=>{ie({type:"complete_path",path:w(h)})},80),B(""),v(!1))},ye=se=>{if(se.key==="Escape")se.stopPropagation(),p(!1);else if(se.key==="Enter"&&!se.nativeEvent.isComposing)ke(m);else if(se.key==="Tab"){if(X.length===0)return;se.preventDefault();const Te=V>=0?(V+1)%X.length:0;W(Te),f(X[Te].path),b(X[Te].path)}},we=ce(h),Ce={"host:conn":s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`status-dot ${D}`,title:ae}),s.jsx("span",{className:"status-item",children:ae})]}),"host:engine":i!=="pi"?s.jsx("span",{className:`status-item engine-badge engine-${i}`,title:`${a("engineBadge")}: ${i}`,children:i==="dsh"?"DSH":i}):null,"host:ctx":s.jsxs("span",{className:"status-item status-ctx",title:a("contextUsage"),children:[s.jsx("span",{className:"ctx-label",children:a("context")}),s.jsx("span",{className:`ctx-bar ${de}`,children:S!==null&&s.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(S,100)}%`}})}),ve]}),"host:cost":s.jsxs("span",{className:"status-item",title:a("cumulativeCost"),children:["$",Xg(J.cost)]}),"host:cache":s.jsxs("span",{className:"status-item status-cache",title:a("cacheHitTip",{read:us(L.read),write:us(L.write),miss:us(L.miss),input:us(L.totalInput)}),children:[a("cacheHit"),s.jsx("b",{className:`cache-pct ${T}`,children:F})]}),"host:msg-count":s.jsxs("span",{className:"status-item",title:a("sessionMessages"),children:[a("messages")," ",J.totalMessages]}),"host:plugin-status":e.statuses.length>0?s.jsx("span",{className:"status-item ext-status",title:a("pluginStatus"),children:e.statuses.map(se=>se.text).join(" · ")}):null,"host:working":l.isStreaming?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"status-item working",children:[s.jsx("span",{className:"working-spin"}),a("working"),ue>0&&s.jsxs("span",{className:"status-queue",children:["⏳ ",ue," ",a("queued")]})]}),s.jsxs("span",{className:"status-item status-rate",title:a("rateTip"),children:[s.jsx("span",{className:"working-spin rate-spin"}),Y>0?`${Math.round(Y)}${a("tps")}`:"…"]})]}):null,"host:cwd":u?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"status-cwd-backdrop",onClick:()=>p(!1)}),s.jsxs("div",{className:"cwd-picker",children:[s.jsxs("div",{className:"cwd-picker-head",children:[s.jsxs("span",{className:"cwd-picker-title",title:h===vt?a("computer"):h,children:[h===vt?"💻":s.jsx(Bt,{}),s.jsx("span",{children:h===vt?a("computer"):h})]}),s.jsx("button",{type:"button",className:"cwd-up",disabled:h===vt,title:a("computer"),onClick:()=>{b(vt),f(vt),W(-1)},children:"💻"}),s.jsxs("button",{type:"button",className:"cwd-up",disabled:!we,title:a("cwdGoUp"),onClick:()=>{we&&(b(we),f(we),W(-1))},children:["↑ ",a("cwdGoUp")]}),(()=>{const se=Re=>{const Ye=Re.replace(/\\/g,"/").replace(/\/+$/,"");return/^[A-Za-z]:/.test(Ye)?Ye.toLowerCase():Ye},Te=se(h),De=!!h&&h!==vt&&Te!==se(l.cwd)&&!o.some(Re=>se(Re)===Te);return s.jsxs("button",{type:"button",className:"cwd-up",disabled:!De,title:a("addWorkspaceRootHint"),onClick:()=>{De&&ie({type:"set_workspace_roots",roots:[...o,h]})},children:["+ ",a("addWorkspaceRoot")]})})()]}),s.jsxs("div",{className:"cwd-picker-row",children:[s.jsx("input",{ref:I,className:"status-cwd-input cwd-picker-input",value:m,placeholder:a("enterPath"),spellCheck:!1,onChange:se=>{f(se.target.value),W(-1)},onKeyDown:ye}),s.jsx("button",{type:"button",className:"cwd-choose-btn primary",title:a("cwdPickCurrent"),disabled:h===vt,onClick:()=>ke(h),children:a("cwdPickCurrent")})]}),s.jsxs("div",{className:"cwd-list",children:[X.length===0&&s.jsx("div",{className:"cwd-empty",children:a("cwdEmpty")}),X.map(se=>s.jsxs("div",{className:"cwd-item",children:[s.jsxs("button",{type:"button",className:"cwd-enter",title:`${a("cwdEnter")} ${se.path}`,onClick:()=>{b(se.path),f(se.path),W(-1)},children:[s.jsx(Bt,{}),s.jsx("span",{className:"cwd-name",children:se.name})]}),s.jsx("button",{type:"button",className:"cwd-choose-btn",title:a("cwdChoose"),onClick:()=>ke(se.path),children:a("cwdChoose")})]},se.path))]}),s.jsx("div",{className:"cwd-picker-foot",children:x?s.jsxs("div",{className:"cwd-newrow",children:[s.jsx("input",{ref:j,value:N,autoFocus:!0,spellCheck:!1,placeholder:a("cwdNewName"),onChange:se=>B(se.target.value),onKeyDown:se=>{se.key==="Enter"&&!se.nativeEvent.isComposing?(se.preventDefault(),Oe()):se.key==="Escape"&&(se.stopPropagation(),v(!1),B(""))}}),s.jsx("button",{type:"button",className:"cwd-choose-btn primary",onClick:Oe,children:a("cwdCreate")}),s.jsx("button",{type:"button",className:"cwd-choose-btn",onClick:()=>{v(!1),B("")},children:a("cwdCancel")})]}):s.jsxs("button",{type:"button",className:"cwd-newbtn",onClick:()=>v(!0),children:["+ ",a("cwdNewFolder")]})})]})]}):s.jsxs("button",{type:"button",className:"status-item status-cwd",title:a("cwdTip",{path:l.cwd}),onClick:pe,children:["📁 ",l.cwd]})},qe=t?t.map(se=>({id:se.id,entry:se})):Vg.map(se=>({id:se,entry:null})),Be=[];for(const{id:se,entry:Te}of qe)if(!Te?.hidden){if(se.startsWith("host:")){const De=Ce[se];De&&Be.push({key:se,node:De});continue}Te&&Be.push({key:se,node:s.jsxs("button",{type:"button",className:"status-action",title:Te.hint??Te.label,onClick:()=>n?.(Te),children:[Te.icon?`${Te.icon} `:"",Te.label,Te.badge?s.jsx("span",{className:"status-badge",children:Te.badge}):null]})})}return s.jsx("footer",{className:"statusbar",children:Be.map((se,Te)=>s.jsxs(c.Fragment,{children:[Te>0&&s.jsx("span",{className:"status-sep",children:"·"}),se.node]},se.key))})}function us(e){return e>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(e)}function Xg(e){return e<=0?"0":e<1e-4?"<0.0001":e.toFixed(4).replace(/\.?0+$/,"")}function Jg({dialog:e}){const t=Pe(),[n,a]=c.useState(""),[i,o]=c.useState(0),l=h=>{ie({type:"dialog_response",id:e.id,value:h})};c.useEffect(()=>{a(""),o(0);const h=b=>{b.key==="Escape"&&l(null)};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[e.id]);const u=Array.isArray(e.args[0])?e.args[0]:[],p=typeof e.args[0]=="string"?e.args[0]:"";return s.jsxs("div",{className:"dialog-inline","data-dialog-kind":e.kind,children:[s.jsxs("div",{className:"dialog-head",children:[s.jsx("span",{className:"dialog-badge",children:t("pluginRequest")}),e.title&&e.title!==t("pluginRequest")&&s.jsx("span",{className:"dialog-title",children:e.title}),s.jsx("button",{type:"button",className:"dialog-dismiss",title:t("cancel"),onClick:()=>l(null),children:"✕"})]}),e.kind==="select"&&s.jsxs("div",{className:"dialog-options",children:[u.map((h,b)=>s.jsx("button",{type:"button",className:`dialog-option ${b===i?"sel":""}`,onMouseEnter:()=>o(b),onClick:()=>l(h),children:s.jsx(pt,{text:h,rawHtml:!0})},b)),u.length===0&&s.jsx("div",{className:"dialog-hint",children:t("noOptions")})]}),e.kind==="confirm"&&s.jsxs("div",{className:"dialog-body",children:[s.jsx(pt,{text:p,rawHtml:!0}),s.jsxs("div",{className:"dialog-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>l(!1),children:t("cancel")}),s.jsx("button",{type:"button",className:"btn primary",onClick:()=>l(!0),children:t("ok")})]})]}),e.kind==="input"&&s.jsxs("div",{className:"dialog-body",children:[s.jsx("input",{className:"dialog-input",value:n,placeholder:p||t("inputPlaceholder"),autoFocus:!0,onChange:h=>a(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.nativeEvent.isComposing&&l(n)}}),s.jsxs("div",{className:"dialog-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>l(null),children:t("cancel")}),s.jsx("button",{type:"button",className:"btn primary",onClick:()=>l(n),children:t("ok")})]})]})]})}const Ct=8;function dc(e,t,n){let a=e.left-Ct,i=e.bottom+Ct;return a+t.width>n.width-Ct&&(a=Math.max(Ct,e.right+Ct-t.width)),i+t.height>n.height-Ct&&(i=Math.max(Ct,e.top-Ct-t.height)),{left:a,top:i}}function Zg(){return typeof window<"u"&&window.matchMedia?.("(hover: hover) and (pointer: fine)")?.matches===!0}const eb=150;function tb({anchorRef:e,enabled:t=!0,className:n,children:a}){const i=c.useRef(null),o=c.useRef(null),[l,u]=c.useState(!1),[p,h]=c.useState({left:0,top:0}),b=c.useCallback(()=>{o.current!==null&&(clearTimeout(o.current),o.current=null)},[]),m=c.useCallback(()=>{b(),o.current=setTimeout(()=>u(!1),eb)},[b]);return c.useEffect(()=>{const f=e.current;if(!f)return;const x=()=>{b(),u(!0)};f.addEventListener("mouseenter",x);const v=N=>{const B=N.relatedTarget;B&&i.current?.contains(B)||m()};return f.addEventListener("mouseleave",v),t&&(f.addEventListener("focus",x),f.addEventListener("blur",m)),()=>{b(),f.removeEventListener("mouseenter",x),f.removeEventListener("mouseleave",v),f.removeEventListener("focus",x),f.removeEventListener("blur",m)}},[e,t,b,m]),c.useLayoutEffect(()=>{if(!l)return;const f=e.current?.getBoundingClientRect();if(!f)return;const x={left:Math.max(Ct,f.left-Ct),top:f.bottom+Ct};h(v=>v.left===x.left&&v.top===x.top?v:x)},[l,e]),c.useLayoutEffect(()=>{if(!l)return;const f=i.current,x=e.current;if(!f||!x)return;const v=dc(x.getBoundingClientRect(),f.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight});h(N=>N.left===v.left&&N.top===v.top?N:v)},[l,e,a]),c.useEffect(()=>{if(!l)return;const f=()=>u(!1);return window.addEventListener("scroll",f,!0),window.addEventListener("resize",f),()=>{window.removeEventListener("scroll",f,!0),window.removeEventListener("resize",f)}},[l]),l?ta.createPortal(s.jsx("div",{ref:i,className:`set-tip-bubble open${n?` ${n}`:""}`,role:"tooltip",style:{position:"fixed",left:p.left,top:p.top},onMouseEnter:b,onMouseLeave:m,children:a}),document.body):null}function sb({question:e}){const t=Pe(),[n,a]=c.useState({}),[i,o]=c.useState({}),[l,u]=c.useState(0),[p,h]=c.useState(()=>e.deadline?Math.max(0,Math.ceil((e.deadline-Date.now())/1e3)):-1);c.useEffect(()=>{a({}),o({}),u(0),h(e.deadline?Math.max(0,Math.ceil((e.deadline-Date.now())/1e3)):-1)},[e.id,e.deadline]),c.useEffect(()=>{if(!e.deadline)return;const I=setInterval(()=>{h(j=>{const X=Math.max(0,Math.ceil((e.deadline-Date.now())/1e3));return X<=0&&j>0&&ie({type:"question_answer",id:e.id,answers:[],cancelled:!0}),X})},1e3);return()=>clearInterval(I)},[e.id,e.deadline]),c.useEffect(()=>{const I=j=>{j.key==="Escape"&&x()};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[e.id]);const b=e.questions.length,m=e.questions[l];if(!m)return null;const f=I=>{const j=e.questions.map(X=>{const w=I[X.id]??[],ce=(i[X.id]??"").trim();return{id:X.id,selected:w,...ce?{custom:ce}:{}}});ie({type:"question_answer",id:e.id,answers:j})},x=()=>{ie({type:"question_answer",id:e.id,answers:[],cancelled:!0})},v=(I,j)=>{a(X=>{const w=X[I]??[];return{...X,[I]:w.includes(j)?w.filter(ce=>ce!==j):[...w,j]}})},N=(I,j,X)=>{if(X){v(I,j);return}const w={...n,[I]:[j]};a(w),l===b-1?f(w):u(l+1)},B=()=>{l===b-1?f(n):u(l+1)},V=I=>(e.questions.find(X=>X.id===I)?.options?.length??0)===0?!0:(n[I]?.length??0)>0||(i[I]??"").trim()!=="",W=(m.options??[]).filter(I=>(n[m.id]??[]).includes(I.label)&&I.preview).map(I=>I.preview);return s.jsxs("div",{className:"dialog-inline","data-dialog-kind":"select",children:[s.jsxs("div",{className:"dialog-head",children:[s.jsx("span",{className:"dialog-badge",children:t("modelQuestion")}),b>1&&s.jsx("span",{className:"question-progress",children:t("questionStep",{cur:l+1,total:b})}),p>=0&&s.jsx("span",{className:"question-timer",children:p>0?t("questionTimeout",{s:p}):t("questionTimeoutExpired")}),s.jsx("button",{type:"button",className:"dialog-dismiss",title:t("cancel"),onClick:x,children:"✕"})]}),s.jsxs("div",{className:"set-section",children:[s.jsx("div",{className:"set-section-title",children:m.header??`${t("modelQuestion")} ${l+1}`}),s.jsx("div",{className:"question-head",children:s.jsx(pt,{text:m.question,rawHtml:!0})}),m.detail&&s.jsx("div",{className:"set-hint",children:s.jsx(pt,{text:m.detail,rawHtml:!0})}),(m.options?.length??0)>0&&s.jsx("div",{className:"set-list",children:m.options.map(I=>{const j=(n[m.id]??[]).includes(I.label);return s.jsx(nb,{label:I.label,description:I.description,mark:m.multiSelect?j?"☑ ":"☐ ":j?"● ":"○ ",active:j,onPick:()=>N(m.id,I.label,!!m.multiSelect)},I.label)})}),W.length>0&&s.jsxs("div",{className:"question-preview",children:[s.jsx("div",{className:"question-preview-label",children:t("optionPreview")}),W.map((I,j)=>s.jsx("div",{className:"question-preview-body",children:s.jsx(pt,{text:I,rawHtml:!0})},j))]}),s.jsx("input",{className:"set-prompt-input question-custom",placeholder:t("modelQuestionCustom"),value:i[m.id]??"",onChange:I=>o(j=>({...j,[m.id]:I.target.value})),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),V(m.id)&&B())}})]},m.id),s.jsxs("div",{className:"dialog-nav",children:[s.jsx("button",{type:"button",className:"dialog-dismiss-inline",onClick:x,children:t("cancel")}),s.jsxs("div",{className:"dialog-nav-right",children:[s.jsx("button",{type:"button",className:"dialog-prev",disabled:l===0,onClick:()=>u(l-1),children:t("previous")}),s.jsx("button",{type:"button",className:"dialog-submit",disabled:!V(m.id),onClick:B,children:l===b-1?t("modelQuestionSubmit"):t("next")})]})]})]})}function nb({label:e,description:t,mark:n,active:a,onPick:i}){const o=c.useRef(null);return s.jsxs("button",{type:"button",ref:o,className:`set-row question-option${a?" active":""}`,onClick:i,children:[s.jsxs("div",{className:"set-row-name",children:[s.jsx("span",{className:"question-mark",children:n}),s.jsx(pt,{text:e,rawHtml:!0})]}),t&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"set-row-desc",children:s.jsx(pt,{text:t,rawHtml:!0})}),s.jsx(tb,{anchorRef:o,enabled:Zg(),className:"question-desc-tip",children:s.jsx(pt,{text:t,rawHtml:!0})})]})]})}const no=e=>`'${e.replace(/'/g,"'\\''")}'`,Gn=300,ao=200,io=720,ab=220,ro="pi-web-ui:scm-sidebar-width";function pc(e,t=0){if(!Number.isFinite(e))return Gn;const n=Math.max(ao,Math.min(io,t>0?t-ab:io));return Math.min(n,Math.max(ao,Math.round(e)))}function ib(e){return e===null||e.trim()===""?Gn:pc(Number(e))}function rb(e){if(e.x==="?"&&e.y==="?")return"untracked";const t=e.x!==" "&&e.x!=="?",n=e.y!==" "&&e.y!=="?";return t&&n?"both":t?"staged":"unstaged"}function ob({chat:e,terminal:t,active:n,onSwitchToTerminal:a}){const i=Pe(),[o,l]=c.useState(null),[u,p]=c.useState([]),[h,b]=c.useState(""),[m,f]=c.useState(new Map),[x,v]=c.useState("changes"),[N,B]=c.useState([]),[V,W]=c.useState(null),[I,j]=c.useState(""),[X,w]=c.useState(!1),[ce,be]=c.useState(null),[$,K]=c.useState(null),[J,L]=c.useState(!1),[H,T]=c.useState(!1),[F,Y]=c.useState(!1),[D,ae]=c.useState(null),[ee,ve]=c.useState(!1),[S,de]=c.useState(()=>ib(localStorage.getItem(ro))),[ue,pe]=c.useState(""),ke=c.useRef(0),Oe=c.useRef(-1),ye=c.useRef(-1),we=c.useRef(-1),Ce=c.useRef(-1),qe=c.useRef(void 0),Be=c.useRef(null),se=c.useRef([]),Te=c.useRef(S);Te.current=S;const De=c.useRef(null),Re=c.useCallback(_=>{try{localStorage.setItem(ro,String(_))}catch{}},[]),Ye=c.useCallback(_=>{_.preventDefault();const me=_.clientX,Ne=Te.current,$e=De.current?.getBoundingClientRect().width??0;let Ie=Ne;const Qe=ut=>{Ie=pc(Ne+(ut.clientX-me),$e),de(Ie)},gt=()=>{window.removeEventListener("pointermove",Qe),window.removeEventListener("pointerup",gt),document.body.classList.remove("panel-resizing"),Re(Ie)};window.addEventListener("pointermove",Qe),window.addEventListener("pointerup",gt),document.body.classList.add("panel-resizing")},[Re]),A=c.useCallback(()=>{de(Gn),Re(Gn)},[Re]),Q=c.useCallback(_=>{if(_.reqId===Oe.current){if(Oe.current=-1,T(!1),ae(null),!_.ok){ae(_.error??i("scmQueryFailedShort"));return}if(_.notRepo){ve(!0),l(null),p([]),f(new Map),B([]),W(null),j(""),K(null);return}ve(!1);const me={branch:_.branch??"",detached:!!_.detached,upstream:_.upstream??null,ahead:_.ahead??0,behind:_.behind??0,upstreamGone:!!_.upstreamGone,files:(_.files??[]).map(Ie=>({...Ie}))},Ne=(_.branches??[]).map(Ie=>({...Ie})),$e=new Map;for(const[Ie,Qe]of Object.entries(_.stats??{}))$e.set(Ie,{add:Qe[0],del:Qe[1]});l(me),p(Ne),f($e),b(Ie=>me.detached?Ie||"":me.branch&&Ne.some(Qe=>Qe.name===me.branch)?me.branch:Ie&&Ne.some(Qe=>Qe.name===Ie)?Ie:Ne[0]?.name??""),K(Ie=>Ie&&!me.files.some(Qe=>Qe.path===Ie.file.path)?null:Ie)}else if(_.reqId===ye.current){if(ye.current=-1,L(!1),!_.ok){ae(_.error??i("scmQueryFailedShort"));return}const me=Be.current;if(!me)return;K({file:me,staged:_.stagedText??"",worktree:_.worktreeText??"",untracked:!1})}else if(_.reqId===Ce.current){if(Ce.current=-1,Y(!1),!_.ok){ae(_.error??i("scmQueryFailedShort"));return}B((_.history??[]).map(me=>({...me})))}else if(_.reqId===we.current){if(we.current=-1,w(!1),!_.ok){ae(_.error??i("scmQueryFailedShort"));return}j(_.text??"")}},[]);c.useEffect(()=>{const _=e.scmData;_&&_.type==="scm_data"&&Q(_)},[e.scmData,Q]);const z=c.useCallback((_,me)=>{if(!e.ready||e.status!=="open")return!1;const Ne=++ke.current;return ie({..._,reqId:Ne})?(me.current=Ne,!0):(ke.current-=1,!1)},[e.ready,e.status]),ge=c.useCallback((_=!1,me=!1)=>{!e.ready||e.status!=="open"||e.state?.cwd&&(qe.current!==void 0&&qe.current!==e.state.cwd&&(l(null),p([]),f(new Map),B([]),Y(!1),Ce.current=-1,W(null),j(""),K(null),be(null)),qe.current=e.state.cwd,ae(null),z({type:"scm_status"},Oe)&&(me||T(!0)))},[e.ready,e.state?.cwd,e.status,z]),oe=c.useCallback(_=>{if(be(_),W(null),Be.current=_,_.x==="?"&&_.y==="?"){K({file:_,staged:"",worktree:"",untracked:!0});return}L(!0),ae(null),z({type:"scm_filediff",path:_.path},ye)||L(!1)},[z]),Z=c.useCallback(_=>{W(_),be(null),K(null),j(""),w(!0),ae(null),z({type:"scm_commit",hash:_.hash},we)||w(!1)},[z]),y=c.useCallback((_,me)=>{if(!e.ready)return;const Ne={name:_,command:me,cwd:"${pwd}"};let $e;const Ie=e.terminals.find(Qe=>Qe.title===_);Ie?(t.restart(Ie.id),ie({type:"run_command",terminalId:Ie.id,conversationId:Ie.conversationId,command:Ne,cols:80,rows:24}),$e=Ie.id):($e=St(),t.create({id:$e,conversationId:e.activeConversationId||e.state?.conversationId||"",title:_,cwd:e.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:Ne})),t.select($e),a()},[e.ready,e.state?.cwd,e.terminals,a,t]),P=c.useCallback(()=>{const _=ue.trim();if(!_||ee)return;const me=_.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");y("git commit",`git commit -m "${me}"`),pe("")},[ue,ee,y]),le=c.useCallback(()=>{const _=ue.trim();if(!_||ee)return;const me=_.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");y("git commit",`git add -A && git commit -m "${me}"`),pe("")},[ue,ee,y]),Ee=c.useCallback(_=>{ee||y("git add",`git add -- ${no(_.path)}`)},[ee,y]),Ae=c.useCallback(_=>{ee||y("git reset",`git reset HEAD -- ${no(_.path)}`)},[ee,y]),Me=c.useCallback(()=>{if(!h||ee)return;const _=u.find(me=>me.name===h);if(_?.remote&&typeof _.remote=="string"){const me=h.slice(_.remote.length+1);y("git checkout",`git checkout -b ${me} ${h} || git checkout ${h}`)}else y("git checkout",`git checkout ${h}`)},[h,u,ee,y]),Le=c.useCallback(()=>y("git push","git push"),[y]),Ge=c.useCallback(()=>y("git pull","git pull"),[y]),R=c.useCallback(()=>{z({type:"scm_history"},Ce)||(Ce.current=-1)},[z]);c.useEffect(()=>{n&&ge()},[n,ge]),c.useEffect(()=>{x==="history"&&o&&R()},[x,o,R]),c.useEffect(()=>{e.scmDirty>0&&n&&ge(!1,!0)},[e.scmDirty]),c.useEffect(()=>{if(!n||!e.ready||e.status!=="open")return;const _=setInterval(()=>{document.visibilityState!=="hidden"&&ge(!1,!0)},3e4);return()=>clearInterval(_)},[n,e.ready,e.status,ge]),c.useEffect(()=>{const _=se.current;if(se.current=e.terminals,!n)return;e.terminals.some(Ne=>Ne.running!==!1?!1:_.find(Ie=>Ie.id===Ne.id)?.running===!0&&Ne.title.startsWith("git "))&&e.ready&&e.status==="open"&&(ge(!1,!0),x==="history"&&o&&R())},[e.terminals,n,e.ready,e.status,ge,x,o,R]);const He={staged:i("scmStaged"),unstaged:i("scmUnstaged"),untracked:i("scmUntracked"),both:i("scmStagedUnstaged")},C=_=>{const me=_.split(`
342
+ `);return s.jsx("pre",{className:"scm-diff-pre",children:me.map((Ne,$e)=>{let Ie="";return Ne.startsWith("diff --git")||Ne.startsWith("index ")||Ne.startsWith("new file")||Ne.startsWith("deleted file")||Ne.startsWith("old mode")||Ne.startsWith("new mode")||Ne.startsWith("similarity index")||Ne.startsWith("rename ")||Ne.startsWith("copy ")||Ne.startsWith("Binary files")||Ne.startsWith("---")||Ne.startsWith("+++")?Ie="hdr":Ne.startsWith("@@")?Ie="hunk":Ne.startsWith("+")?Ie="add":Ne.startsWith("-")&&(Ie="del"),s.jsx("div",{className:`scm-diff-line ${Ie}`,children:Ne||" "},$e)})})};return s.jsxs("div",{className:"scm-view",children:[s.jsxs("div",{className:"scm-header",children:[s.jsxs("div",{className:"scm-title-row",children:[s.jsxs("span",{className:"scm-title",children:[s.jsx(mn,{}),i("scmTitle")]}),s.jsxs("div",{className:"scm-view-tabs",role:"tablist",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":x==="changes",className:x==="changes"?"active":"",onClick:()=>{v("changes"),ae(null)},children:i("scmChanges")}),s.jsx("button",{type:"button",role:"tab","aria-selected":x==="history",className:x==="history"?"active":"",onClick:()=>{v("history"),ae(null)},children:i("scmHistory")})]}),s.jsx("button",{type:"button",className:"panel-refresh",title:i("scmRefreshTip"),disabled:H,onClick:()=>ge(!0),children:s.jsx(jt,{className:H?"scm-spin":""})})]}),s.jsxs("div",{className:"scm-row",children:[s.jsxs("span",{className:"scm-branch-current",title:i("scmCurrentBranch"),children:[s.jsx(mn,{}),o?o.detached?i("scmDetached"):o.branch:"…",o?.upstream&&s.jsx("span",{className:"scm-upstream",children:o.upstreamGone?i("scmUpstreamGone"):o.ahead>0||o.behind>0?i("scmAheadBehind",{ahead:o.ahead,behind:o.behind}):o.upstream})]}),s.jsxs("select",{className:"scm-select",value:h,disabled:ee||u.length===0,title:i("scmSwitchBranch"),onChange:_=>b(_.target.value),children:[s.jsx("option",{value:"",disabled:!0,children:i("scmSelectBranch")}),u.filter(_=>!_.remote).map(_=>s.jsx("option",{value:_.name,children:_.current?`* ${_.name}`:_.name},_.name)),u.some(_=>_.remote)&&s.jsx("optgroup",{label:i("scmRemoteBranches"),children:u.filter(_=>_.remote).map(_=>s.jsx("option",{value:_.name,children:_.name},_.name))})]}),s.jsxs("button",{type:"button",className:"btn",disabled:!h||h===o?.branch||ee,title:i("scmSwitchBranchTip",{branch:h}),onClick:Me,children:[s.jsx(mn,{}),i("scmSwitch")]}),s.jsxs("button",{type:"button",className:"btn",disabled:!o||o.detached||ee,title:i("scmPushTip"),onClick:Le,children:[s.jsx(La,{}),i("scmPush")]}),s.jsxs("button",{type:"button",className:"btn",disabled:!o||o.detached||ee,title:i("scmPullTip"),onClick:Ge,children:[s.jsx(Ao,{}),i("scmPull")]}),s.jsx("input",{className:"scm-commit-input",value:ue,placeholder:i("scmCommitPlaceholder"),disabled:ee,onChange:_=>pe(_.target.value),onKeyDown:_=>{_.key==="Enter"&&!_.nativeEvent.isComposing&&P()}}),s.jsxs("button",{type:"button",className:"btn primary",disabled:!ue.trim()||ee,title:i("scmCommitTip"),onClick:P,children:[s.jsx(Rt,{}),i("scmCommit")]}),s.jsx("button",{type:"button",className:"btn",disabled:!ue.trim()||ee,title:i("scmCommitAllTip"),onClick:le,children:i("scmCommitAll")})]})]}),s.jsxs("div",{className:"scm-body",ref:De,style:{"--scm-sidebar-w":`${S}px`},children:[x==="history"?s.jsxs("div",{className:"scm-history",children:[s.jsxs("div",{className:"scm-files-header",children:[s.jsx("span",{children:i("scmHistory")}),N.length>0&&s.jsx("span",{className:"scm-files-count",children:N.length})]}),s.jsx("div",{className:"scm-history-list",children:ee?s.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):!o||F?s.jsx("div",{className:"scm-empty",children:e.status==="open"?i("scmLoading"):i("scmConnecting")}):N.length===0?s.jsx("div",{className:"scm-empty",children:i("scmNoHistory")}):N.map(_=>s.jsxs("button",{type:"button",className:`scm-commit ${V?.hash===_.hash?"active":""}`,onClick:()=>Z(_),title:_.hash,children:[s.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:_.graph||"* "}),s.jsxs("span",{className:"scm-commit-info",children:[s.jsx("span",{className:"scm-commit-subject",children:_.subject}),s.jsxs("span",{className:"scm-commit-meta",children:[_.shortHash," · ",_.author," · ",_.date]}),_.decorations&&s.jsx("span",{className:"scm-commit-refs",children:_.decorations})]})]},_.hash))})]}):s.jsxs("div",{className:"scm-files",children:[s.jsxs("div",{className:"scm-files-header",children:[s.jsx("span",{children:i("scmChanges")}),o&&o.files.length>0&&s.jsx("span",{className:"scm-files-count",children:o.files.length})]}),s.jsx("div",{className:"scm-files-list",children:ee?s.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):o?o.files.length===0?s.jsx("div",{className:"scm-empty",children:i("scmNoChanges")}):o.files.map(_=>{const me=rb(_),Ne=m.get(_.path);return s.jsxs("div",{className:`scm-file ${ce?.path===_.path?"active":""}`,title:He[me],onClick:()=>oe(_),children:[s.jsx("span",{className:`scm-file-xy ${me==="untracked"?"q":"x"}`,children:_.x!==" "?_.x:" "}),s.jsx("span",{className:`scm-file-xy ${me==="untracked"?"q":"y"}`,children:_.y!==" "?_.y:" "}),s.jsx("span",{className:"scm-file-path",children:_.path}),Ne&&(Ne.add>0||Ne.del>0)&&s.jsxs("span",{className:"scm-file-stat",children:[Ne.add>0&&s.jsxs("span",{className:"add",children:["+",Ne.add]}),Ne.del>0&&s.jsxs("span",{className:"del",children:["-",Ne.del]})]}),s.jsxs("span",{className:"scm-file-actions",children:[(_.y!==" "||me==="untracked")&&s.jsx("button",{type:"button",className:"scm-act",title:i("scmStageTip",{path:_.path}),onClick:$e=>{$e.stopPropagation(),Ee(_)},children:"+"}),me==="staged"||me==="both"?s.jsx("button",{type:"button",className:"scm-act",title:i("scmUnstageTip",{path:_.path}),onClick:$e=>{$e.stopPropagation(),Ae(_)},children:"−"}):null]})]},_.path)}):s.jsx("div",{className:"scm-empty",children:e.status==="open"?i("scmLoading"):i("scmConnecting")})})]}),s.jsx("div",{className:"scm-divider",role:"separator","aria-orientation":"vertical",title:i("dragToResize"),onPointerDown:Ye,onDoubleClick:A}),s.jsxs("div",{className:"scm-diff",children:[s.jsxs("div",{className:"scm-diff-header",children:[s.jsx("span",{children:x==="history"?V?`${V.shortHash} ${V.subject}`:i("scmCommitDetail"):ce?ce.path:i("scmDiff")}),(x==="history"?X:J)&&s.jsx("span",{className:"scm-diff-loading",children:i("scmLoading")})]}),s.jsx("div",{className:"scm-diff-body",children:x==="history"?s.jsxs(s.Fragment,{children:[D&&s.jsx("div",{className:"scm-error",children:D}),!V&&!D&&s.jsx("div",{className:"scm-empty",children:i("scmSelectCommitHint")}),V&&X&&!D&&s.jsx("div",{className:"scm-empty",children:i("scmLoading")}),V&&!X&&!D&&I?C(I):null]}):s.jsxs(s.Fragment,{children:[D&&s.jsx("div",{className:"scm-error",children:D}),!ce&&!D&&s.jsx("div",{className:"scm-empty",children:i("scmSelectFileHint")}),ce&&!$&&!D&&s.jsx("div",{className:"scm-empty",children:i("scmLoading")}),ce&&$&&$.untracked&&s.jsx("div",{className:"scm-empty",children:i("scmUntrackedNote")}),ce&&$&&!$.untracked&&s.jsxs(s.Fragment,{children:[$.staged&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"scm-diff-section",children:i("scmStaged")}),C($.staged)]}),$.worktree&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"scm-diff-section",children:i("scmUnstaged")}),C($.worktree)]}),!$.staged&&!$.worktree&&s.jsx("div",{className:"scm-empty",children:i("scmNoDiff")})]})]})})]})]}),s.jsxs("div",{className:"scm-hint",children:[s.jsx(Jn,{}),s.jsx("span",{children:i("scmRunsInTerminal")}),s.jsx("button",{type:"button",className:"scm-goto-term",onClick:a,children:i("scmViewTerminal")})]})]})}function lb({entry:e}){const t=c.useRef(null),n=Pe();return c.useEffect(()=>{const a=t.current;if(!a)return;let i;try{i=e.module.mount(a,sl(e.info.id,o=>ie(o)))}catch(o){console.error(`[plugin:${e.info.id}] mount failed:`,o),a.textContent=n("pluginMountFailed",{name:e.info.name})}return()=>{if(typeof i=="function")try{i()}catch(o){console.error(`[plugin:${e.info.id}] cleanup failed:`,o)}a.textContent=""}},[e]),s.jsx("div",{className:"plugin-view",ref:t})}const ei=["topbar.primary","topbar.overflow","bottombar","composer.actions","message.actions","rightpanel.tabs","contextmenu.topbar","contextmenu.message","contextmenu.session","contextmenu.file","settings.pages"],cb=[{id:"host:history",slot:"topbar.primary",labelKey:"openHistory",icon:"menu",kind:"action",order:5,group:"panels"},{id:"host:files",slot:"topbar.primary",labelKey:"openFiles",icon:"folder",kind:"action",order:6,group:"panels"},{id:"host:new-chat",slot:"topbar.primary",labelKey:"newChat",icon:"plus",kind:"action",order:10,group:"primary"},{id:"host:chat",slot:"topbar.primary",labelKey:"chat",icon:"chat",kind:"view",view:"chat",order:20,group:"views"},{id:"host:terminal",slot:"topbar.primary",labelKey:"terminal",icon:"terminal",kind:"view",view:"terminal",order:21,group:"views"},{id:"host:git",slot:"topbar.primary",labelKey:"scmTab",icon:"git",kind:"view",view:"git",order:22,group:"views"},{id:"host:search",slot:"topbar.primary",labelKey:"searchGlobal",icon:"search",kind:"action",order:40,group:"tools"},{id:"host:browser",slot:"topbar.primary",labelKey:"browserControl",icon:"browser",kind:"action",order:41,group:"tools"},{id:"host:tasks",slot:"topbar.primary",labelKey:"bgTasks",icon:"layers",kind:"action",order:42,group:"tools"},{id:"host:settings",slot:"topbar.primary",labelKey:"settingsTitle",icon:"settings",kind:"action",order:60,group:"system"},{id:"host:sound",slot:"topbar.primary",labelKey:"sound",icon:"sound",kind:"action",order:70,group:"system"},{id:"host:language",slot:"topbar.primary",labelKey:"language",icon:"globe",kind:"action",order:80,group:"system"},{id:"host:theme",slot:"topbar.primary",labelKey:"theme",icon:"sun",kind:"action",order:82,group:"system"},{id:"host:update",slot:"topbar.primary",labelKey:"update",icon:"download",kind:"action",order:90,group:"system"},{id:"host:github",slot:"topbar.primary",labelKey:"githubRepo",icon:"github",kind:"action",order:95,group:"system"},{id:"host:conn",slot:"bottombar",labelKey:"connected",icon:"dot",kind:"badge",order:5,group:"status"},{id:"host:engine",slot:"bottombar",labelKey:"engineBadge",icon:"cpu",kind:"badge",order:6,group:"status"},{id:"host:ctx",slot:"bottombar",labelKey:"context",icon:"gauge",kind:"badge",order:10,group:"usage"},{id:"host:cost",slot:"bottombar",labelKey:"cumulativeCost",icon:"coins",kind:"badge",order:11,group:"usage"},{id:"host:cache",slot:"bottombar",labelKey:"cacheHit",icon:"database",kind:"badge",order:12,group:"usage"},{id:"host:msg-count",slot:"bottombar",labelKey:"messages",icon:"message",kind:"badge",order:13,group:"usage"},{id:"host:plugin-status",slot:"bottombar",labelKey:"pluginStatus",icon:"activity",kind:"badge",order:14,group:"status"},{id:"host:working",slot:"bottombar",labelKey:"working",icon:"activity",kind:"badge",order:15,group:"status"},{id:"host:cwd",slot:"bottombar",labelKey:"cwdTip",icon:"folder",kind:"action",order:20,group:"context"},{id:"host:msg-edit-reask",slot:"message.actions",labelKey:"editReask",icon:"edit",kind:"action",order:10},{id:"host:msg-copy",slot:"message.actions",labelKey:"copyMessage",icon:"copy",kind:"action",order:20},{id:"host:right-files",slot:"rightpanel.tabs",labelKey:"openFiles",icon:"folder",kind:"view",view:"files",order:10},{id:"host:conv-dismiss-subagents",slot:"contextmenu.session",labelKey:"dismissFinishedSubagents",icon:"x",kind:"action",context:"session",order:10},{id:"host:conv-force-dismiss",slot:"contextmenu.session",labelKey:"forceDismissConversation",icon:"x",kind:"action",context:"session",order:20},{id:"host:file-upload",slot:"contextmenu.file",labelKey:"uploadToFolder",icon:"upload",kind:"action",context:"file",order:10},{id:"host:file-open-project",slot:"contextmenu.file",labelKey:"openAsProject",icon:"folder",kind:"action",context:"file",order:20},{id:"host:file-add-root",slot:"contextmenu.file",labelKey:"addWorkspaceRoot",icon:"folder",kind:"action",context:"file",order:30}];function mc(e){return typeof e=="string"&&ei.includes(e)}function hc(e,t){return t?e.label:e.labelEn??e.label}function fc(e,t){return t?e.hint??e.hintEn:e.hintEn??e.hint}function ub(e,t,n,a,i){const o=`${e}#${a.id}`,l=gc(o,t,n,a.children,i),u=fc(a,i);return{id:o,slot:t,source:n,label:hc(a,i),...a.icon?{icon:a.icon}:{},...u?{hint:u}:{},kind:a.kind??"action",...a.action?{action:a.action}:{},...a.view?{view:a.view}:{},...a.group?{group:a.group}:{},order:a.order??100,hidden:a.hidden??!1,...a.badge?{badge:a.badge}:{},...a.when?{when:a.when}:{},...l.length>0?{children:l}:{},userOverrides:[],arrangedBy:[]}}function gc(e,t,n,a,i){return a?.length?a.map((o,l)=>({entry:ub(e,t,n,o,i),index:l})).sort((o,l)=>o.entry.order===l.entry.order?o.index-l.index:o.entry.order-l.entry.order).map(o=>o.entry):[]}function db(e,t,n,a,i,o){const l=gc(e,t,n,a.children,i),u=fc(a,i);return{id:e,slot:t,source:n,label:hc(a,i),...a.icon?{icon:a.icon}:{},...u?{hint:u}:{},kind:a.kind??(t==="settings.pages"?"page":"action"),...a.action?{action:a.action}:{},...a.view?{view:a.view}:{},...a.group?{group:a.group}:{},order:a.order??100,hidden:a.hidden??!1,...a.badge?{badge:a.badge}:{},...a.when?{when:a.when}:{},...l.length>0?{children:l}:{},userOverrides:[],arrangedBy:[],seq:o}}function pb(e,t){return[...e].sort((n,a)=>{const i=t.get(n.id),o=t.get(a.id);return i!==void 0||o!==void 0?i!==void 0&&o!==void 0?i-o:i!==void 0?-1:1:n.order!==a.order?n.order-a.order:n.seq-a.seq})}function bc(e,t){const n=t.locale==="zh",a=new Set(t.disabledPlugins??[]),i=t.layout??{},o=new Map;let l=0;for(const f of cb)o.set(f.id,{id:f.id,slot:f.slot,source:"host",label:t.t(f.labelKey),labelKey:f.labelKey,...f.icon?{icon:f.icon}:{},kind:f.kind,...f.view?{view:f.view}:{},...f.group?{group:f.group}:{},order:f.order??100,hidden:f.hidden??!1,userOverrides:[],arrangedBy:[],seq:l++});for(const f of e){if(f.error||a.has(f.id))continue;const x=`plugin:${f.id}`;for(const v of f.ui?.items??[]){if(!mc(v.slot))continue;const N=`${f.id}:${v.id}`,B=o.get(N);o.set(N,db(N,v.slot,x,v,n,B?.seq??l++))}}for(const f of e)if(!(f.error||a.has(f.id)))for(const x of f.ui?.arrange??[])hb(o,x,f.id);const u=new Map,p=(f,x)=>{const v=u.get(f)??[];v.includes(x)||v.push(x),u.set(f,v)};for(const f of i.hidden??[]){const x=o.get(f);x&&(x.hidden=!0,p(f,"hidden"))}for(const f of i.shown??[]){const x=o.get(f);x&&(x.hidden=!1,p(f,"hidden"))}for(const[f,x]of Object.entries(i.groups??{})){const v=o.get(f);v&&(v.group=x,p(f,"group"))}for(const[f,x]of Object.entries(i.labels??{})){const v=o.get(f);v&&(v.label=x,p(f,"label"))}const h=new Map;(i.order??[]).forEach((f,x)=>{o.has(f)&&(h.has(f)||h.set(f,x),p(f,"order"))});const b=new Map;for(const f of ei)b.set(f,[]);for(const f of o.values())b.get(f.slot)?.push(f);const m={};for(const f of ei)m[f]=pb(b.get(f)??[],h).map(x=>mb(x,u.get(x.id)??[]));return m}function mb(e,t){const n={...e,userOverrides:t};return delete n.seq,n}function hb(e,t,n){const a=e.get(t.id);if(!a)return;let i=!1;t.hide!==void 0&&(a.hidden=t.hide,i=!0),t.group!==void 0&&(a.group=t.group,i=!0),t.order!==void 0&&(a.order=t.order,i=!0),t.label!==void 0&&(a.label=t.label,i=!0),t.hint!==void 0&&(a.hint=t.hint,i=!0),t.icon!==void 0&&(a.icon=t.icon,i=!0),t.slot!==void 0&&mc(t.slot)&&t.slot!==a.slot&&(a.movedFrom=a.movedFrom??a.slot,a.slot=t.slot,i=!0),i&&a.source!==`plugin:${n}`&&!a.arrangedBy.includes(n)&&a.arrangedBy.push(n)}function fb(e,t){const n=e??{},a={},i=(n.hidden??[]).filter(h=>h!==t),o=(n.shown??[]).filter(h=>h!==t),l=(n.order??[]).filter(h=>h!==t);i.length>0&&(a.hidden=i),o.length>0&&(a.shown=o),l.length>0&&(a.order=l);const u=oo(n.groups,t);u&&(a.groups=u);const p=oo(n.labels,t);return p&&(a.labels=p),a}function gb(){return{}}function oo(e,t){if(!e)return;const n={};let a=!1;for(const[i,o]of Object.entries(e))i!==t&&(n[i]=o,a=!0);return a?n:void 0}function bb({onAction:e}){const t=Rd(),n=c.useMemo(()=>t?On(t.entries):[],[t]),a=c.useMemo(()=>Vi(n),[n]),i=c.useRef(null),o=c.useRef(null),[l,u]=c.useState(null),[p,h]=c.useState(-1),[b,m]=c.useState(-1),[f,x]=c.useState(!1),[v,N]=c.useState(0),B=c.useRef(-1),V=$=>{B.current=$,h($)},W=c.useMemo(()=>b>=0?On(n[b]?.children??[]):[],[n,b]),I=c.useMemo(()=>Vi(W),[W]),j=$=>{const K=n[$];if(!(!t||!K||En(K))){if(K.children?.length){m($);return}X(K,t)||qt()}},X=($,K)=>$.source==="host"&&K.onHostAction?K.onHostAction($,K.target)===!0:(e($,K.target),!1),w=c.useRef(j);if(c.useLayoutEffect(()=>{w.current=j}),c.useEffect(()=>{if(!t){B.current=-1,h(-1),m(-1);return}const $=Qi(n,-1,1);B.current=$,h($),m(-1),i.current?.focus()},[t,n]),c.useLayoutEffect(()=>{if(!t){u(null);return}const $=i.current;if(!$)return;const K=$.getBoundingClientRect();u(Ld(t.x,t.y,K.width,K.height,window.innerWidth,window.innerHeight))},[t,n]),c.useLayoutEffect(()=>{const $=o.current,K=i.current;if(b<0||!$||!K){x(!1),N(0);return}const J=$.getBoundingClientRect(),L=K.getBoundingClientRect(),H=window.innerWidth-L.right,T=L.left;x(H<J.width+Ot&&T>H);const F=J.bottom-(window.innerHeight-Ot);N(F>0?-Math.min(F,Math.max(0,J.top-Ot)):0)},[b,n]),c.useEffect(()=>{if(!t)return;const $=T=>i.current&&T instanceof Node&&i.current.contains(T),K=T=>{$(T.target)||qt()},J=T=>{$(T.target)||qt()},L=()=>qt(),H=()=>qt();return document.addEventListener("mousedown",K,!0),window.addEventListener("wheel",J,!0),window.addEventListener("scroll",L,!0),window.addEventListener("resize",H),()=>{document.removeEventListener("mousedown",K,!0),window.removeEventListener("wheel",J,!0),window.removeEventListener("scroll",L,!0),window.removeEventListener("resize",H)}},[t]),c.useEffect(()=>{if(!t)return;const $=J=>{const L=Qi(n,B.current,J);B.current=L,h(L)},K=J=>{switch(J.key){case"Escape":J.preventDefault(),qt();return;case"Tab":qt();return;case"ArrowDown":J.preventDefault(),$(1);return;case"ArrowUp":J.preventDefault(),$(-1);return;case"ArrowRight":n[B.current]?.children?.length&&(J.preventDefault(),m(B.current));return;case"ArrowLeft":b>=0&&(J.preventDefault(),m(-1));return;case"Enter":case" ":J.preventDefault(),w.current(B.current);return;default:return}};return document.addEventListener("keydown",K),()=>document.removeEventListener("keydown",K)},[t,n,b]),c.useEffect(()=>{p<0||i.current?.querySelector('[data-ctx-active="true"]')?.scrollIntoView?.({block:"nearest"})},[p]),!t)return null;const ce=$=>{En($)||X($,t)||qt()},be=($,K,J)=>{const L=En($),H=!!$.children?.length,T=Od($.icon),F=J&&p===K;return s.jsxs("div",{className:"ctx-menu-itemwrap",role:"none",children:[s.jsxs("button",{type:"button",role:"menuitem",className:`ctx-menu-item${L?" disabled":""}${F?" active":""}${H?" has-sub":""}`,"aria-label":$.label,title:$.hint,"aria-disabled":L||void 0,"aria-haspopup":H?"menu":void 0,"aria-expanded":H?b===K:void 0,"data-ctx-active":F?"true":void 0,onMouseEnter:J?()=>{V(K),H&&!L&&m(K)}:void 0,onClick:()=>J?j(K):ce($),children:[T?s.jsx("span",{className:"ctx-menu-icon","aria-hidden":"true",children:T}):null,s.jsx("span",{className:"ctx-menu-label",children:$.label}),$.badge?s.jsx("span",{className:"ctx-menu-badge",children:$.badge}):null,H?s.jsx("span",{className:"ctx-menu-caret","aria-hidden":"true",children:"▸"}):null]}),J&&H&&b===K?s.jsx("div",{ref:o,className:`ctx-menu-sub${f?" left":""}`,role:"menu","aria-label":$.label,style:v?{marginTop:v}:void 0,children:I.map(Y=>Y.kind==="sep"?s.jsx("div",{className:"ctx-menu-sep",role:"separator"},Y.key):be(Y.entry,Y.index,!1))}):null]},`${$.id}#${K}`)};return ta.createPortal(s.jsx("div",{ref:i,className:"ctx-menu",role:"menu","aria-label":t.target.label?`${t.slot}: ${t.target.label}`:t.slot,tabIndex:-1,style:{left:l?.x??t.x,top:l?.y??t.y,visibility:l?"visible":"hidden"},onContextMenu:$=>{$.preventDefault(),$.stopPropagation()},children:a.map($=>$.kind==="sep"?s.jsx("div",{className:"ctx-menu-sep",role:"separator"},$.key):be($.entry,$.index,!0))}),document.body)}function Eb({piConfigured:e,piAgentInstalled:t,providers:n,installResult:a,onClose:i}){const o=Pe(),l=Go(),[u,p]=c.useState(!1),[h,b]=c.useState(""),[m,f]=c.useState(""),[x,v]=c.useState(!1);c.useEffect(()=>{ie({type:"list_providers"})},[]),c.useEffect(()=>{e&&i()},[e,i]),c.useEffect(()=>{a&&p(!1)},[a]),c.useEffect(()=>{!h&&n.length>0&&b(n.find(j=>!j.configured)?.id??n[0].id)},[n,h]);const N=()=>{u||(p(!0),ie({type:"install_pi_agent"}))},B=()=>{!m.trim()||x||(v(!0),ie({type:"set_provider_api_key",provider:h.trim(),apiKey:m.trim()}),setTimeout(()=>v(!1),3e3))},V=()=>{ie({type:"get_state"}),ie({type:"list_providers"})},W=n.find(j=>j.id===h),I=a!==null&&!a.ok;return s.jsx("div",{className:"modal-backdrop",children:s.jsxs("div",{className:"modal setup-modal",children:[s.jsx("button",{type:"button",className:"modal-close","aria-label":o("close"),onClick:i,children:s.jsx(tt,{})}),s.jsxs("div",{className:"modal-head",children:[s.jsx(Gs,{className:"modal-head-icon"}),s.jsx("h2",{children:o("setupTitle")})]}),s.jsx("p",{className:"modal-desc",children:o("setupDesc")}),I?s.jsxs("div",{className:"setup-failed",children:[s.jsx("div",{className:"setup-done",children:o("installFailed")}),s.jsx("pre",{className:"setup-detail",children:a.detail}),s.jsxs("div",{className:"setup-actions",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:u,onClick:N,children:o("retryInstall")}),s.jsx("button",{type:"button",className:"btn",onClick:i,children:o("skip")})]})]}):t||a?.ok?s.jsxs("div",{className:"setup-key-form",children:[s.jsx("div",{className:"setup-done",children:a?.ok?o("installDone"):o("cliReadyHint")}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:o("provider")}),s.jsxs("select",{value:h,onChange:j=>b(j.target.value),children:[n.length===0&&s.jsx("option",{value:"",children:o("loading")}),n.map(j=>s.jsxs("option",{value:j.id,children:[j.name,"(",j.id,")",j.configured?` · ${o("configured")}`:""]},j.id))]}),W?.configured&&s.jsx("div",{className:"field-hint",children:o("providerKeyReady")})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:o("apiKey")}),s.jsx("input",{type:"password",value:m,onChange:j=>f(j.target.value),placeholder:"sk-…"})]}),s.jsxs("div",{className:"setup-actions",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:!m.trim()||x||!h,onClick:B,children:o(x?"saving":"saveAndStart")}),s.jsxs("button",{type:"button",className:"btn",onClick:V,children:[s.jsx(jt,{})," ",o("recheck")]})]})]}):l?s.jsxs("div",{className:"setup-actions",children:[s.jsx("div",{className:"setup-done",children:o("updatesManaged")}),s.jsx("button",{type:"button",className:"btn",onClick:i,children:o("skip")})]}):s.jsxs("div",{className:"setup-actions",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:u,onClick:N,children:o(u?"installing":"autoInstall")}),s.jsx("button",{type:"button",className:"btn",onClick:i,children:o("skip")})]})]})})}const Tb=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],Ei=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),xb=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[Ei()]});function wa(e){return{providerId:e.providerId,name:e.name??"",api:e.api??"openai-completions",baseUrl:e.baseUrl??"",apiKey:e.apiKey??"",authHeader:e.authHeader??!1,models:(e.models.length?e.models:[Ei()]).map(t=>({id:t.id,name:t.name??"",reasoning:t.reasoning??!1,input:t.input?.includes("image")?"text-image":"text",contextWindow:t.contextWindow?String(t.contextWindow):"",maxTokens:t.maxTokens?String(t.maxTokens):""}))}}function yb({providers:e,providerStatus:t,providerKeys:n,fetchModelsResult:a,cloneProviderResult:i,onClose:o}){const l=Pe(),[u,p]=c.useState(null),[h,b]=c.useState({}),[m,f]=c.useState({}),[x,v]=c.useState(null),[N,B]=c.useState(!1),[V,W]=c.useState(0),[I,j]=c.useState(null),X=c.useRef(0),[w,ce]=c.useState(null),[be,$]=c.useState(""),[K,J]=c.useState(null);c.useEffect(()=>{ie({type:"list_models_config"}),ie({type:"list_providers"}),ie({type:"list_provider_keys"})},[]);const L=()=>{if(!u)return;const S=u.baseUrl.trim();if(!S){j({ok:!1,text:l("fetchModelsNeedBaseUrl")});return}if(N)return;B(!0),j(null);const de=V+1;W(de),ie({type:"fetch_models",reqId:de,baseUrl:S,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader,api:u.api})};c.useEffect(()=>{if(!(!a||a.reqId===X.current))if(X.current=a.reqId,B(!1),a.ok&&a.models?.length){const S=a.models;p(de=>{if(!de)return de;const ue=de.models.map(ye=>{if(!ye.id.trim())return ye;const we=S.find(qe=>qe.id===ye.id.trim());if(!we)return ye;const Ce={...ye};return!Ce.name&&we.name&&(Ce.name=we.name),!Ce.contextWindow&&we.contextWindow&&(Ce.contextWindow=String(we.contextWindow)),!Ce.maxTokens&&we.maxTokens&&(Ce.maxTokens=String(we.maxTokens)),Ce.input==="text"&&we.input?.includes("image")&&(Ce.input="text-image"),!Ce.reasoning&&we.reasoning&&(Ce.reasoning=!0),Ce}),pe=new Set(ue.map(ye=>ye.id.trim()).filter(Boolean)),ke=S.filter(ye=>!pe.has(ye.id)).map(ye=>({id:ye.id,name:ye.name??"",reasoning:ye.reasoning??!1,input:ye.input?.includes("image")?"text-image":"text",contextWindow:ye.contextWindow?String(ye.contextWindow):"",maxTokens:ye.maxTokens?String(ye.maxTokens):""})),Oe=[...ue,...ke];return Oe.some(ye=>ye.id.trim())?{...de,models:Oe.filter(ye=>ye.id.trim())}:de}),j({ok:!0,text:l("fetchModelsOk",{n:S.length})})}else j({ok:!1,text:a.error||l("fetchModelsEmpty")})},[a]);const H=S=>{const de=(h[S.id]??"").trim();!de||x||(v(S.id),ie({type:"add_provider_key",provider:S.id,apiKey:de,name:(m[S.id]??"").trim()||void 0}),setTimeout(()=>{v(null),b(ue=>({...ue,[S.id]:""})),f(ue=>({...ue,[S.id]:""})),ie({type:"list_providers"}),ie({type:"list_provider_keys"})},1500))},T=(S,de)=>{ie({type:"activate_provider_key",provider:S,keyName:de}),ie({type:"list_provider_keys"})},F=(S,de)=>{window.confirm(l("removeKeyConfirm"))&&(ie({type:"remove_provider_key",provider:S,keyName:de}),ie({type:"list_provider_keys"}))},Y=()=>{if(!K)return;const S=K.providerId.trim();if(!S||!K.apiKey.trim())return;const de=K.models.filter(pe=>pe.id.trim()).map(pe=>({id:pe.id.trim(),name:pe.name.trim()||void 0,reasoning:pe.reasoning||void 0,input:pe.input==="text-image"?["text","image"]:void 0,contextWindow:pe.contextWindow?Number(pe.contextWindow):void 0,maxTokens:pe.maxTokens?Number(pe.maxTokens):void 0})),ue={providerId:S,name:K.name.trim()||void 0,api:K.api.trim()||void 0,baseUrl:K.baseUrl.trim()||void 0,apiKey:K.apiKey.trim()||void 0,authHeader:K.authHeader||void 0,models:de};ie({type:"save_model_config",providerId:S,config:ue}),J(null),o()},D=()=>{if(!u)return;const S=u.providerId.trim(),de=u.models.filter(pe=>pe.id.trim()).map(pe=>({id:pe.id.trim(),name:pe.name.trim()||void 0,reasoning:pe.reasoning||void 0,input:pe.input==="text-image"?["text","image"]:void 0,contextWindow:pe.contextWindow?Number(pe.contextWindow):void 0,maxTokens:pe.maxTokens?Number(pe.maxTokens):void 0})),ue={providerId:S,name:u.name.trim()||void 0,api:u.api.trim()||void 0,baseUrl:u.baseUrl.trim()||void 0,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader||void 0,models:de};ie({type:"save_model_config",providerId:S,config:ue}),o()};c.useEffect(()=>{if(i&&i.ok){const S=i.configs;if(S&&S.length>1){ce(S.map(de=>wa({...de,apiKey:""}))),$("");return}if(i.config){J(wa({...i.config,apiKey:""}));return}}},[i]);const ae=S=>{window.confirm(l("clearKeyConfirm",{id:S}))&&ie({type:"clear_provider_api_key",provider:S})},ee=S=>{window.confirm(l("deleteProviderConfirm",{id:S.providerId,n:S.models.length}))&&ie({type:"delete_model_config",providerId:S.providerId})},ve=(S,de)=>{u&&p({...u,models:u.models.map((ue,pe)=>pe===S?{...ue,...de}:ue)})};return s.jsx("div",{className:"modal-backdrop",onClick:o,children:s.jsxs("div",{className:"modal model-modal",onClick:S=>S.stopPropagation(),children:[s.jsx("button",{type:"button",className:"modal-close","aria-label":l("close"),onClick:o,children:s.jsx(tt,{})}),s.jsx("div",{className:"modal-head",children:s.jsx("h2",{children:K?l("addKey"):w?l("batchCreateProviders",{n:w.length}):l(u?"editProvider":"manageModelsTitle")})}),K?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"model-modal-body",children:s.jsxs("div",{className:"provider-form",children:[s.jsx("p",{className:"modal-desc",style:{marginBottom:12},children:l("secondKeyTitle",{api:K.api,baseUrl:K.baseUrl||l("noBaseUrlShort"),n:K.models.length})}),s.jsxs("div",{className:"form-grid",children:[s.jsxs("label",{className:"field",children:[s.jsxs("span",{className:"field-label",children:[l("providerNameLabel")," ",s.jsx("em",{children:l("providerNameHint")})]}),s.jsx("input",{type:"text",value:K.providerId,onChange:S=>J({...K,providerId:S.target.value}),placeholder:"opencode-2"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:l("apiKeyLabel")}),s.jsx("input",{type:"password",value:K.apiKey,onChange:S=>J({...K,apiKey:S.target.value}),placeholder:l("secondKeyPlaceholder")})]})]}),s.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:8},children:[K.models.slice(0,5).map(S=>S.id).join(", "),K.models.length>5?` … +${K.models.length-5}`:""]})]})}),s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>J(null),children:l("cancel")}),s.jsx("button",{type:"button",className:"btn",onClick:()=>{const S=K;J(null),p(S)},children:l("advancedEdit")}),s.jsx("button",{type:"button",className:"btn primary",disabled:!K.providerId.trim()||!K.apiKey.trim(),onClick:Y,children:l("save")})]})]}):w?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"model-modal-body",children:s.jsxs("div",{className:"provider-form",children:[s.jsx("p",{className:"modal-desc",style:{marginBottom:12},children:l("batchDesc",{apis:w.map(S=>S.api).join("、"),n:w.length})}),s.jsxs("label",{className:"field",style:{marginBottom:16},children:[s.jsx("span",{className:"field-label",children:l("batchKeyLabel",{n:w.length})}),s.jsx("input",{type:"password",value:be,onChange:S=>$(S.target.value),placeholder:l("secondKeyPlaceholder")})]}),s.jsx("div",{className:"provider-list",style:{marginBottom:16},children:w.map((S,de)=>s.jsxs("div",{className:"provider-row",style:{flexDirection:"column",alignItems:"stretch",gap:6},children:[s.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:13},children:[s.jsx("strong",{children:S.providerId}),s.jsx("span",{style:{opacity:.7},children:S.api})]}),s.jsxs("div",{className:"provider-sub",style:{fontSize:12,opacity:.7},children:[S.baseUrl||l("noBaseUrlShort")," · ",l("modelsCountShort",{n:S.models.length}),S.models.slice(0,3).map(ue=>ue.id).join(", "),S.models.length>3?` … +${S.models.length-3}`:""]}),s.jsx("input",{type:"text",value:S.providerId,onChange:ue=>ce(pe=>pe.map((ke,Oe)=>Oe===de?{...ke,providerId:ue.target.value}:ke)),placeholder:l("providerIdPlaceholder"),style:{fontSize:12}}),s.jsx("input",{type:"text",value:S.baseUrl,onChange:ue=>ce(pe=>pe.map((ke,Oe)=>Oe===de?{...ke,baseUrl:ue.target.value}:ke)),placeholder:l("baseUrlExamplePh"),style:{fontSize:12}})]},de))})]})}),s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>ce(null),children:l("cancel")}),s.jsx("button",{type:"button",className:"btn primary",disabled:!be.trim(),onClick:()=>{for(const S of w){const de=S.providerId.trim();if(!de)continue;const ue=S.models.filter(ke=>ke.id.trim()).map(ke=>({id:ke.id.trim(),name:ke.name.trim()||void 0,reasoning:ke.reasoning||void 0,input:ke.input==="text-image"?["text","image"]:void 0,contextWindow:ke.contextWindow?Number(ke.contextWindow):void 0,maxTokens:ke.maxTokens?Number(ke.maxTokens):void 0})),pe={providerId:de,name:S.name.trim()||void 0,api:S.api.trim()||void 0,baseUrl:S.baseUrl.trim()||void 0,apiKey:be.trim()||void 0,authHeader:S.authHeader||void 0,models:ue};ie({type:"save_model_config",providerId:de,config:pe})}ce(null),o()},children:l("saveAllBatch",{n:w.length})})]})]}):u?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"model-modal-body",children:s.jsxs("div",{className:"provider-form",children:[s.jsxs("div",{className:"form-grid",children:[s.jsxs("label",{className:"field",children:[s.jsxs("span",{className:"field-label",children:[l("providerId")," ",s.jsx("em",{children:l("providerIdHint")})]}),s.jsx("input",{type:"text",value:u.providerId,disabled:e.some(S=>S.providerId===u.providerId),onChange:S=>p({...u,providerId:S.target.value}),placeholder:"my-proxy"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:l("displayName")}),s.jsx("input",{type:"text",value:u.name,onChange:S=>p({...u,name:S.target.value}),placeholder:l("displayNamePh")})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:l("apiType")}),s.jsx("select",{value:u.api,onChange:S=>p({...u,api:S.target.value}),children:Tb.map(S=>s.jsx("option",{value:S,children:S},S))})]}),s.jsxs("label",{className:"field",children:[s.jsxs("span",{className:"field-label",children:["baseUrl ",s.jsx("em",{children:l("baseUrlHint")})]}),s.jsx("input",{type:"text",value:u.baseUrl,onChange:S=>p({...u,baseUrl:S.target.value}),placeholder:"http://localhost:11434/v1"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:l("apiKey")}),s.jsx("input",{type:"password",value:u.apiKey,onChange:S=>p({...u,apiKey:S.target.value}),placeholder:l("apiKeyHint")})]}),s.jsxs("label",{className:"field check",children:[s.jsx("input",{type:"checkbox",checked:u.authHeader,onChange:S=>p({...u,authHeader:S.target.checked})}),s.jsx("span",{children:l("authHeader")})]})]}),s.jsxs("div",{className:"model-section-head",children:[s.jsx("span",{className:"form-section-title",children:l("modelsTitle")}),s.jsxs("span",{className:"model-section-actions",children:[I&&s.jsx("span",{className:`fetch-msg ${I.ok?"ok":"err"}`,title:I.text,children:I.text}),s.jsxs("button",{type:"button",className:"btn sm",disabled:N||!u.baseUrl.trim(),title:l("fetchModelsHint"),onClick:L,children:[s.jsx(ss,{})," ",l(N?"fetchingModels":"fetchModels")]})]})]}),u.models.map((S,de)=>s.jsxs("div",{className:"model-row",children:[s.jsx("input",{type:"text",value:S.id,onChange:ue=>ve(de,{id:ue.target.value}),placeholder:l("modelIdReq")}),s.jsx("input",{type:"text",value:S.name,onChange:ue=>ve(de,{name:ue.target.value}),placeholder:l("displayName")}),s.jsxs("select",{value:S.input,onChange:ue=>ve(de,{input:ue.target.value}),children:[s.jsx("option",{value:"text",children:l("text")}),s.jsx("option",{value:"text-image",children:l("textImage")})]}),s.jsxs("label",{className:"check",children:[s.jsx("input",{type:"checkbox",checked:S.reasoning,onChange:ue=>ve(de,{reasoning:ue.target.checked})}),s.jsx("span",{children:l("reasoning")})]}),s.jsx("input",{type:"number",value:S.contextWindow,onChange:ue=>ve(de,{contextWindow:ue.target.value}),placeholder:l("contextWindow"),title:"contextWindow"}),s.jsx("input",{type:"number",value:S.maxTokens,onChange:ue=>ve(de,{maxTokens:ue.target.value}),placeholder:l("maxOutput"),title:"maxTokens"}),s.jsx("button",{type:"button",className:"iconbtn danger",title:l("removeModel"),onClick:()=>p({...u,models:u.models.filter((ue,pe)=>pe!==de)}),children:s.jsx(dt,{})})]},de)),s.jsxs("button",{type:"button",className:"btn",onClick:()=>p({...u,models:[...u.models,Ei()]}),children:[s.jsx(yt,{})," ",l("addModel")]})]})}),s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>p(null),children:l("cancel")}),s.jsx("button",{type:"button",className:"btn primary",disabled:!u.providerId.trim()||!u.models.some(S=>S.id.trim()),onClick:D,children:l("save")})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"model-modal-fixed-hint",children:s.jsxs("div",{className:"form-section-title",children:[l("builtinProviders")," ",s.jsx("em",{className:"section-hint",children:l("hintKeyOnly")})]})}),s.jsxs("div",{className:"model-modal-body",children:[s.jsxs("div",{className:"provider-list",children:[t.length===0&&s.jsx("div",{className:"dd-loading",children:l("loading")}),t.map(S=>{const de=n[S.id]??[];return s.jsxs("div",{className:"provider-row provider-key-row",children:[s.jsxs("div",{className:"provider-key-head",children:[s.jsxs("div",{className:"provider-info",children:[s.jsx("span",{className:"provider-name",children:S.name}),s.jsxs("span",{className:"provider-sub",children:[S.id,S.configured&&s.jsx("span",{className:"auth-badge",children:l("configuredBadge")}),S.source&&!S.configured&&s.jsx("span",{className:"auth-badge dim",children:S.source})]})]}),S.source==="stored"&&s.jsxs("button",{type:"button",className:"btn sm danger",title:l("clearKeyTitle"),onClick:()=>ae(S.id),children:[s.jsx(dt,{})," ",l("clearKey")]})]}),s.jsxs("div",{className:"provider-keys",children:[de.length===0&&s.jsx("div",{className:"provider-key-empty",children:l("noKeyYet")}),de.map(ue=>s.jsxs("div",{className:`provider-key-item ${ue.active?"active":""}`,children:[s.jsx("span",{className:"provider-key-dot",children:ue.active?"●":"○"}),s.jsx("span",{className:"provider-key-label",children:ue.name}),!ue.active&&s.jsx("button",{type:"button",className:"iconbtn",title:l("activateKey"),onClick:()=>T(S.id,ue.name),children:s.jsx(Rt,{})}),s.jsx("button",{type:"button",className:"iconbtn danger",title:l("removeKey"),onClick:()=>F(S.id,ue.name),children:s.jsx(dt,{})})]},ue.name)),s.jsxs("div",{className:"provider-add-key",children:[s.jsx("input",{type:"text",className:"key-input key-input-name",placeholder:l("keyNamePh"),value:m[S.id]??"",onChange:ue=>f(pe=>({...pe,[S.id]:ue.target.value}))}),s.jsx("input",{type:"password",className:"key-input key-input-value",placeholder:l("addKeyPlaceholder"),value:h[S.id]??"",onChange:ue=>b(pe=>({...pe,[S.id]:ue.target.value}))}),s.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(h[S.id]??"").trim()||x===S.id,onClick:()=>H(S),children:[s.jsx(yt,{})," ",x===S.id?l("savingKey"):l("addKey")]})]})]})]},S.id)})]}),s.jsx("div",{className:"form-section-title",children:l("customProviders")}),s.jsx("p",{className:"modal-desc",children:l("customDesc")}),s.jsx("p",{className:"modal-desc",children:l("reloadModelsHint")}),e.length===0&&s.jsx("div",{className:"dd-loading",children:l("noCustomProviders")}),s.jsx("div",{className:"provider-list",children:e.map(S=>s.jsxs("div",{className:"provider-row",children:[s.jsxs("div",{className:"provider-info",children:[s.jsx("span",{className:"provider-name",children:S.providerId}),s.jsxs("span",{className:"provider-sub",children:[S.api??"—",S.baseUrl?` · ${S.baseUrl}`:"",S.models.length>0&&` · ${l("modelsCount",{n:S.models.length})}`]})]}),s.jsxs("div",{className:"provider-actions",children:[s.jsx("button",{type:"button",className:"iconbtn",title:l("edit"),onClick:()=>p(wa(S)),children:s.jsx(Rn,{})}),s.jsx("button",{type:"button",className:"iconbtn danger",title:l("delete"),onClick:()=>ee(S),children:s.jsx(dt,{})})]})]},S.providerId))})]}),s.jsxs("div",{className:"modal-actions",children:[s.jsxs("button",{type:"button",className:"btn",onClick:()=>ie({type:"reload_models_config"}),children:[s.jsx(jt,{})," ",l("reloadModelsConfig")]}),s.jsxs("button",{type:"button",className:"btn primary",onClick:()=>p(xb()),children:[s.jsx(yt,{})," ",l("addProvider")]})]})]})]})})}function nt({text:e}){const t=c.useRef(null),n=c.useRef(null),[a,i]=c.useState(!1),[o,l]=c.useState({left:0,top:0}),u=()=>{const h=t.current?.getBoundingClientRect();h&&(l({left:Math.max(8,h.left-8),top:h.bottom+8}),i(!0))},p=()=>i(!1);return c.useEffect(()=>{if(!a)return;const h=n.current,b=t.current;if(!h||!b)return;const m=h.getBoundingClientRect(),f=b.getBoundingClientRect(),x=dc(f,m,{width:window.innerWidth,height:window.innerHeight});l(v=>v.left===x.left&&v.top===x.top?v:x)},[a,e]),c.useEffect(()=>{if(!a)return;const h=()=>i(!1);return window.addEventListener("scroll",h,!0),window.addEventListener("resize",h),()=>{window.removeEventListener("scroll",h,!0),window.removeEventListener("resize",h)}},[a]),s.jsxs("span",{ref:t,className:"set-tip",tabIndex:0,"aria-label":e,onMouseEnter:u,onMouseLeave:p,onFocus:u,onBlur:p,onKeyDown:h=>{h.key==="Escape"&&h.target.blur()},children:["?",a&&ta.createPortal(s.jsx("span",{ref:n,className:"set-tip-bubble open",role:"tooltip",style:{position:"fixed",left:o.left,top:o.top},children:e}),document.body)]})}function kb({plugin:e}){const t=Pe(),n=e.settingsSchema??[],[a,i]=c.useState(()=>({...e.settingsValues})),[o,l]=c.useState(!1);if(n.length===0)return null;const u=(m,f)=>i(x=>({...x,[m]:f})),p=n.some(m=>a[m.key]!==e.settingsValues?.[m.key]),h=()=>{l(!0),ie({type:"plugin_settings",pluginId:e.id,values:a}),setTimeout(()=>l(!1),800)},b=()=>i({...e.settingsValues});return s.jsxs("div",{className:"plugin-settings-form",children:[s.jsx("div",{className:"plugin-settings-fields",children:n.map(m=>s.jsxs("label",{className:"plugin-settings-field",title:m.hint,children:[s.jsx("span",{className:"plugin-settings-label",children:m.label}),m.type==="boolean"?s.jsx("input",{type:"checkbox",checked:!!a[m.key],onChange:f=>u(m.key,f.target.checked)}):m.type==="select"?s.jsx("select",{value:String(a[m.key]??""),onChange:f=>u(m.key,f.target.value),children:(m.options??[]).map(f=>s.jsx("option",{value:f,children:f},f))}):s.jsx("input",{type:m.type==="password"?"password":m.type==="number"?"number":"text",value:String(a[m.key]??""),min:m.min,max:m.max,onChange:f=>u(m.key,m.type==="number"?Number(f.target.value):f.target.value)})]},m.key))}),s.jsxs("div",{className:"plugin-settings-actions",children:[s.jsx("button",{type:"button",className:"btn plugin-settings-save",disabled:!p||o,onClick:h,children:t(o?"pluginSettingsSaving":"pluginSettingsSave")}),s.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:b,children:t("pluginSettingsReset")})]})]})}const Ec="pi-web-ui:wide-chat",zn={wide:!1};function Tc(e){if(!e||typeof e!="object")return{...zn};const t=e;return{wide:typeof t.wide=="boolean"?t.wide:zn.wide}}function Nb(){try{const e=localStorage.getItem(Ec);return e?Tc(JSON.parse(e)):{...zn}}catch{return{...zn}}}function vb(e){const t=Tc(e);try{localStorage.setItem(Ec,JSON.stringify(t))}catch{}kn=t;for(const n of ti)n()}let kn=null;const ti=new Set;function Cb(e){return ti.add(e),()=>{ti.delete(e)}}function wb(){return kn||(kn=Nb()),kn.wide}function xc(){return c.useSyncExternalStore(Cb,wb)}const yc="pi-web-ui:project-title",Vn={projectName:!0};function kc(e){if(!e||typeof e!="object")return{...Vn};const t=e;return{projectName:typeof t.projectName=="boolean"?t.projectName:Vn.projectName}}function Sb(e){return e?e.replace(/[\\/]+$/,"").split(/[\\/]/).pop()??"":""}function _b(){try{const e=localStorage.getItem(yc);return e?kc(JSON.parse(e)):{...Vn}}catch{return{...Vn}}}function Ab(e){const t=kc(e);try{localStorage.setItem(yc,JSON.stringify(t))}catch{}Nn=t;for(const n of si)n()}let Nn=null;const si=new Set;function Ib(e){return si.add(e),()=>{si.delete(e)}}function jb(){return Nn||(Nn=_b()),Nn.projectName}function Nc(){return c.useSyncExternalStore(Ib,jb)}const vc="pi-web-ui:wallpaper",Rb="has-wallpaper",Ws={url:"",dim:78,blur:0},Lb=2e3,Db=28e5;function ni(e){if(typeof e!="string")return"";const t=e.trim();if(!t)return"";const n=t.toLowerCase().startsWith("data:image/")?Db:Lb;return t.length>n?"":/^https?:\/\//i.test(t)||/^blob:/i.test(t)||/^data:image\//i.test(t)||t.startsWith("/")&&!t.startsWith("//")?t:""}const lo=(e,t,n,a)=>typeof e!="number"||!Number.isFinite(e)?a:Math.min(n,Math.max(t,Math.round(e)));function Cc(e){if(!e||typeof e!="object")return{...Ws};const t=e;return{url:ni(t.url),dim:lo(t.dim,0,95,Ws.dim),blur:lo(t.blur,0,24,Ws.blur)}}function wc(){try{const e=localStorage.getItem(vc);return e?Cc(JSON.parse(e)):{...Ws}}catch{return{...Ws}}}function Pb(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/[\r\n]/g,"")}async function Ob(e){const t=await gi(e);return t?`data:${t.mimeType};base64,${t.data}`:null}function vn(){const e=Ks??wc(),t=document.documentElement;e.url?(t.style.setProperty("--bg-image",`url("${Pb(e.url)}")`),t.style.setProperty("--bg-image-dim",String(e.dim/100)),t.style.setProperty("--bg-image-blur",`${e.blur}px`)):(t.style.removeProperty("--bg-image"),t.style.removeProperty("--bg-image-dim"),t.style.removeProperty("--bg-image-blur"));const n=getComputedStyle(t).getPropertyValue("--bg-image").trim();document.body.classList.toggle(Rb,e.url!==""||n!==""&&n!=="none")}function _s(e){const t=Cc(e);Ks=t;try{localStorage.setItem(vc,JSON.stringify(t))}catch{}for(const n of ai)n();vn()}let Ks=null;const ai=new Set;function Mb(e){return ai.add(e),()=>{ai.delete(e)}}function Bb(){return Ks||(Ks=wc()),Ks}function Sc(){return c.useSyncExternalStore(Mb,Bb)}function Fb(){const e=Sc();c.useEffect(()=>{vn()},[e]),c.useEffect(()=>{const t=()=>vn();return window.addEventListener(zt,t),vn(),()=>window.removeEventListener(zt,t)},[])}const Qn={zh:["继续","总结一下","详细解释一下","检查并修复问题","补充测试覆盖","发布上传"],en:["Continue","Summarize","Explain in detail","Check and fix issues","Add test coverage","Publish release"],it:["Continua","Riassumi","Spiega in dettaglio","Verifica e correggi i problemi","Aggiungi copertura dei test","Pubblica la release"],ja:["続ける","要約して","詳しく説明して","問題を確認して修正","テストカバレッジを追加","公開・リリース"],ko:["계속","요약해줘","자세히 설명해줘","문제를 확인하고 수정","테스트 커버리지 추가","게시/릴리스"],fr:["Continuer","Résumer","Expliquer en détail","Vérifier et corriger les problèmes","Ajouter des tests","Publier"],de:["Weiter","Zusammenfassen","Ausführlich erklären","Probleme prüfen und beheben","Testabdeckung ergänzen","Veröffentlichen"],es:["Continuar","Resumir","Explicar en detalle","Revisar y corregir problemas","Añadir cobertura de pruebas","Publicar"],ru:["Продолжить","Подведи итог","Объясни подробно","Проверь и исправь проблемы","Добавь покрытие тестами","Опубликовать"],pt:["Continuar","Resumir","Explique em detalhes","Verifique e corrija os problemas","Adicione cobertura de testes","Publique a release"]},_c=["soul","tools","guidelines","pi_docs","append","persona","terminal","markers","context","skills","cwd"],Hb=["tools","pi_docs","persona","terminal","markers","context","skills","cwd"];function Ac(e){return Hb.includes(e)}const pn=_c.map(e=>`{{${e}}}`).join(`
343
343
 
344
- `);function Ub(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function oo(e){return e==="append"?0:Sc(e)?2:1}function Ze({title:e,subtitle:t,tip:n,enabled:a,onToggle:i,action:o}){const l=Me();return s.jsxs("div",{className:"set-row",children:[s.jsxs("div",{className:"set-row-info",children:[s.jsxs("div",{className:"set-row-name",children:[e,n&&s.jsx(nt,{text:n})]}),t&&s.jsx("div",{className:"set-row-desc",children:t})]}),o,s.jsx("button",{type:"button",className:`set-switch ${a?"on":""}`,role:"switch","aria-checked":a,title:l(a?"settingsEnabled":"settingsDisabled"),onClick:i,children:s.jsx("span",{className:"set-switch-knob"})})]})}function $b({chat:e,terminal:t,onSwitchToTerminal:n,onClose:a}){const i=Me(),{locale:o}=Ut(),l=d=>i(d),u=e.settings,{engine:p,managed:h}=ri(),b=p==="dsh",[m,f]=c.useState("prompt"),x=c.useRef(null);c.useEffect(()=>{x.current?.scrollTo({top:0})},[m]),c.useEffect(()=>{m==="plugins"&&b&&ie({type:"dsh_patches_list"})},[m,b]);const[v,N]=c.useState(""),[B,X]=c.useState({}),K=c.useRef(!1),A=c.useRef(null),R=[...wc].sort((d,W)=>oo(d)-oo(W)),[I,$]=c.useState(null),[ce,ge]=c.useState({}),[q,Y]=c.useState(""),[J,j]=c.useState("append"),F=c.useRef(!1),[T,U]=c.useState(""),G=c.useRef(!1),[D,se]=c.useState(""),[ee,Ne]=c.useState(null),[w,de]=c.useState(null),[ue,pe]=c.useState(!1),[ke,Be]=c.useState(!1),ye=Ec(),Ae=yc(),ve=Cc(),[Ye,Pe]=c.useState(ve.url),ae=c.useRef(!1),be=c.useRef(null),[Oe,Le]=c.useState(!1),[We,_]=c.useState(!1);c.useEffect(()=>{ae.current||Pe(ve.url.startsWith("data:")?"":ve.url)},[ve.url]);const Q=async d=>{const W=d.target.files?.[0];if(d.target.value="",!!W){Le(!0),_(!1);try{const fe=await Ob(W),qe=fe?si(fe):"";if(!qe){_(!0);return}Pe(""),_s({...ve,url:qe})}finally{Le(!1)}}},[V,Ee]=c.useState(()=>ic()),[oe,Z]=c.useState(()=>{try{return Vs().length}catch{return 0}}),[y,P]=c.useState(!1),le=()=>{try{Z(Vs().length)}catch{Z(0)}};c.useEffect(()=>{m==="prompt-history"&&le()},[m]),c.useEffect(()=>{if(!y)return;const d=window.setTimeout(()=>P(!1),3e3);return()=>window.clearTimeout(d)},[y]);const[Te,Ie]=c.useState(null),[Fe,Re]=c.useState(null),[L,De]=c.useState(""),[Ge,C]=c.useState(""),[S,he]=c.useState(""),[Ce,$e]=c.useState(""),[we,Je]=c.useState(""),[gt,bt]=c.useState(!1),[At,$t]=c.useState(!1),[H,te]=c.useState(""),[_e,je]=c.useState(null);c.useEffect(()=>{u&&(K.current||N(u.promptTemplate??""),X(d=>{const W={};for(const[fe,qe]of Object.entries(u.promptOverrides??{}))W[fe]=qe??"";return A.current&&(W[A.current]=d[A.current]??""),W}),j(u.visionBridgePromptMode),!F.current&&(Y(J==="append"||u.visionBridgePrompt?u.visionBridgePrompt:u.visionBridgeDefaultPrompt||""),G.current||U(u.reviewPrompt)))},[u,J]);const[Ke,ze]=c.useState(String(u?.terminalBashIdleMs??15e3));c.useEffect(()=>{ze(String(u?.terminalBashIdleMs??15e3))},[u?.terminalBashIdleMs]);const[pt,It]=c.useState(String(u?.retryMaxAttempts??6));c.useEffect(()=>{It(String(u?.retryMaxAttempts??6))},[u?.retryMaxAttempts]);const Zs=fc(e.plugins,{locale:o,t:d=>i(d),disabledPlugins:e.settings?.disabledPlugins??[],layout:e.settings?.uiLayout}),Qt=[];for(const d of Zs["settings.pages"]){if(d.source==="host"||d.hidden||d.kind==="divider")continue;const W=e.plugins.find(fe=>fe.id===d.source.slice(7));W&&Qt.push({entry:d,plugin:W})}const ks=d=>`plugin-page:${d}`;if(c.useEffect(()=>{m.startsWith("plugin-page:")&&(Qt.some(d=>ks(d.entry.id)===m)||f("prompt"))},[m,Qt]),!u)return null;const Tt=new Set(u.disabledAgentTools??[]),na=Tt.size,aa=[{id:"prompt",icon:s.jsx(vo,{}),label:i("settingsSystemPrompt")},{id:"prompt-history",icon:s.jsx(ja,{}),label:i("settingsPromptHistory"),count:oe},...b?[{id:"question",icon:s.jsx(Ri,{}),label:i("settingsQuestionnaire")}]:[{id:"tools",icon:s.jsx(Ai,{}),label:i("settingsTools"),count:na+(u.disabledMarkers?.length??0)||void 0}],{id:"display",icon:s.jsx(ts,{}),label:i("settingsMessageDisplay")},{id:"quick",icon:s.jsx(_a,{}),label:i("quickPhrases"),count:u.quickPhrases.length},{id:"skills",icon:s.jsx(Gs,{}),label:i("settingsSkills"),count:u.skills.length},{id:"extensions",icon:s.jsx(da,{}),label:i("settingsExtensions"),count:u.extensions.length},{id:"plugins",icon:s.jsx(an,{}),label:i("settingsUiPlugins"),count:e.plugins.length},{id:"review",icon:s.jsx(hs,{}),label:i("settingsReview"),count:u.reviewSkills.length},...b?[]:[{id:"vision",icon:s.jsx(_n,{}),label:i("settingsVisionBridge")}],{id:"presets",icon:s.jsx(ji,{}),label:i("settingsPresets"),count:u.presets.length},...b?[]:[{id:"subagent-templates",icon:s.jsx(_i,{}),label:i("settingsSubagentTemplates"),count:u.subagentTemplates.length}],...Qt.map(d=>({id:ks(d.entry.id),icon:d.entry.icon&&!/[a-z]/i.test(d.entry.icon)?s.jsx("span",{children:d.entry.icon}):s.jsx(an,{}),label:d.entry.label,pluginPage:{plugin:d.plugin,entry:d.entry}}))],en=m.startsWith("plugin-page:")?Qt.find(d=>ks(d.entry.id)===m)??null:null,ia=new Set(u.disabledSkills),ra=new Set(u.disabledExtensions),He=d=>ie({type:"set_settings",...d}),Pt=()=>{if(!_e||!u)return;const d=_e.value.trim(),W=_e.index;if(je(null),!d||d===u.quickPhrases[W])return;const fe=[...u.quickPhrases];fe[W]=d,He({quickPhrases:fe})},tn=d=>{const W=new Set(ia);W.has(d.name)?W.delete(d.name):W.add(d.name),He({disabledSkills:[...W]})},Ns=new Set(u.skillsFullText??[]),oa=d=>{const W=new Set(Ns);W.has(d)?W.delete(d):W.add(d),He({skillsFullText:[...W]})},ls=new Set(u.disabledPlugins??[]),O=new Set(e.plugins.map(d=>d.id)),me=d=>{const W=new Set(ls);W.has(d.id)?W.delete(d.id):W.add(d.id),He({disabledPlugins:[...W]})},Se=d=>{const W=new Set(ra);W.has(d.id)?W.delete(d.id):W.add(d.id),He({disabledExtensions:[...W]})},Ve={subagent_spawn:i("toolDescSubagentSpawn"),subagent_get_result:i("toolDescSubagentGetResult"),subagent_steer:i("toolDescSubagentSteer"),subagent_list:i("toolDescSubagentList"),subagent_stop:i("toolDescSubagentStop"),subagent_wait_all:i("toolDescSubagentWaitAll"),subagent_templates:i("toolDescSubagentTemplates")},Qe=d=>{const W=new Set(Tt);W.has(d)?W.delete(d):W.add(d),He({disabledAgentTools:[...W]})},Et=u.markersEnabled??!0,mt=new Set(u.disabledMarkers??[]),xt=d=>{const W=new Set(mt);!W.has(d)?W.add(d):W.delete(d),He({disabledMarkers:[...W]})},vs=(d,W)=>{const fe={name:d,command:W,cwd:"${pwd}"};let qe;const at=e.terminals.find(Xe=>Xe.title===d);at?(t.restart(at.id),ie({type:"run_command",terminalId:at.id,conversationId:at.conversationId,command:fe,cols:80,rows:24}),qe=at.id):(qe=St(),t.create({id:qe,conversationId:e.activeConversationId||e.state?.conversationId||"",title:d,cwd:e.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:fe})),t.select(qe),n(),a()},Mc=d=>{Ie(null),vs(`${i("uninstallTitle")} ${d}`,`pi remove npm:${d}`)},la=(d,W,fe)=>{ie({type:"plugin_job",jobId:St(),action:d,id:W,...fe?{source:fe}:{},...d!=="uninstall"&&At?{build:!0}:{}})},Bc=d=>{let W=null;for(const fe of Object.values(e.pluginJobs??{}))fe.pluginId===d&&(!W||fe.startedAt>=W.startedAt)&&(W=fe);return W},Fc=d=>{const W=Bc(d);if(!W)return null;if(W.phase!=="done"){const fe=W.lines[W.lines.length-1]??"";return s.jsxs("div",{className:"set-catalog-job running",title:fe,children:[s.jsx(Rt,{className:"set-job-spin"}),i("pluginJobRunning"),s.jsx("span",{className:"set-catalog-job-line",children:fe})]})}return W.ok?s.jsxs("div",{className:"set-catalog-job ok",children:["✓ ",i("pluginJobDone")]}):s.jsxs("div",{className:"set-catalog-job error",children:[s.jsxs("span",{children:["✗ ",W.error||i("pluginJobFailed")]}),W.output?s.jsx("pre",{className:"set-catalog-job-out",children:W.output}):null]})},Hc=[{slot:"topbar.primary",labelKey:"uiLayoutTopbar"},{slot:"topbar.overflow",labelKey:"uiLayoutTopbarOverflow"},{slot:"bottombar",labelKey:"uiLayoutBottombar"},{slot:"composer.actions",labelKey:"uiLayoutComposer"},{slot:"message.actions",labelKey:"uiLayoutMessage"},{slot:"rightpanel.tabs",labelKey:"uiLayoutRightPanel"},{slot:"settings.pages",labelKey:"uiLayoutSettingsPages"}],sn=e.settings?.uiLayout,Ei=d=>He({uiLayout:{...sn,...d}}),Uc=d=>{const W=new Set(sn?.hidden??[]),fe=new Set(sn?.shown??[]);d.hidden?(W.delete(d.id),fe.add(d.id)):(W.add(d.id),fe.delete(d.id)),Ei({hidden:[...W],shown:[...fe]})},Ti=(d,W,fe)=>{const qe=d.map(Zc=>Zc.id),at=qe.indexOf(W),Xe=at+fe;if(at<0||Xe<0||Xe>=qe.length)return;const it=[...qe],[ki]=it.splice(at,1);ki!==void 0&&(it.splice(Xe,0,ki),Ei({order:it}))},$c=d=>He({uiLayout:fb(sn,d)}),qc=()=>He({uiLayout:gb()}),xi=d=>{Re(null),la("uninstall",d)},yi=(d,W)=>{la("update",d,W)},Wc=d=>{la("install",d.id,d.source)},Kc=d=>{ie({type:"plugin_catalog_remove",id:d})},Yc=()=>{const d=L.trim();d&&(ie({type:"plugin_catalog_add",entry:{source:d,...Ge.trim()?{id:Ge.trim()}:{},...S.trim()?{name:S.trim()}:{},...Ce.trim()?{description:Ce.trim()}:{},...we.trim()?{icon:we.trim()}:{}}}),De(""),C(""),he(""),$e(""),Je(""),bt(!1))},Gc=d=>{const W=new Set(u.reviewSkills.filter(fe=>!fe.enabled).map(fe=>fe.name));W.has(d.name)?W.delete(d.name):W.add(d.name),He({reviewDisabledSkills:[...W]})},zc=()=>He({promptTemplate:v}),Vc=d=>{He({promptOverrides:{[d]:B[d]??""}})},ca=d=>{A.current===d&&(A.current=null),$(null),X(W=>{const fe={...W};return delete fe[d],fe}),He({promptOverrides:{[d]:""}})},Cs=d=>ge(W=>({...W,[d]:!W[d]})),ua=(d,W)=>{X(fe=>({...fe,[d]:W})),$(d)},Qc=()=>{K.current=!1,A.current=null,N(cn),X({}),He({promptTemplate:cn,promptOverrides:{}})},Xc=d=>{N(W=>W.trim()?`${W}
344
+ `);function Ub(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function co(e){return e==="append"?0:Ac(e)?2:1}function Ze({title:e,subtitle:t,tip:n,enabled:a,onToggle:i,action:o}){const l=Pe();return s.jsxs("div",{className:"set-row",children:[s.jsxs("div",{className:"set-row-info",children:[s.jsxs("div",{className:"set-row-name",children:[e,n&&s.jsx(nt,{text:n})]}),t&&s.jsx("div",{className:"set-row-desc",children:t})]}),o,s.jsx("button",{type:"button",className:`set-switch ${a?"on":""}`,role:"switch","aria-checked":a,title:l(a?"settingsEnabled":"settingsDisabled"),onClick:i,children:s.jsx("span",{className:"set-switch-knob"})})]})}function $b({chat:e,terminal:t,onSwitchToTerminal:n,onClose:a}){const i=Pe(),{locale:o}=Ut(),l=d=>i(d),u=e.settings,{engine:p,managed:h}=oi(),b=p==="dsh",[m,f]=c.useState("prompt"),x=c.useRef(null);c.useEffect(()=>{x.current?.scrollTo({top:0})},[m]),c.useEffect(()=>{m==="plugins"&&b&&ie({type:"dsh_patches_list"})},[m,b]);const[v,N]=c.useState(""),[B,V]=c.useState({}),W=c.useRef(!1),I=c.useRef(null),j=[..._c].sort((d,q)=>co(d)-co(q)),[X,w]=c.useState(null),[ce,be]=c.useState({}),[$,K]=c.useState(""),[J,L]=c.useState("append"),H=c.useRef(!1),[T,F]=c.useState(""),Y=c.useRef(!1),[D,ae]=c.useState(""),[ee,ve]=c.useState(null),[S,de]=c.useState(null),[ue,pe]=c.useState(!1),[ke,Oe]=c.useState(!1),ye=xc(),we=Nc(),Ce=Sc(),[qe,Be]=c.useState(Ce.url),se=c.useRef(!1),Te=c.useRef(null),[De,Re]=c.useState(!1),[Ye,A]=c.useState(!1);c.useEffect(()=>{se.current||Be(Ce.url.startsWith("data:")?"":Ce.url)},[Ce.url]);const Q=async d=>{const q=d.target.files?.[0];if(d.target.value="",!!q){Re(!0),A(!1);try{const fe=await Ob(q),Ke=fe?ni(fe):"";if(!Ke){A(!0);return}Be(""),_s({...Ce,url:Ke})}finally{Re(!1)}}},[z,ge]=c.useState(()=>oc()),[oe,Z]=c.useState(()=>{try{return Vs().length}catch{return 0}}),[y,P]=c.useState(!1),le=()=>{try{Z(Vs().length)}catch{Z(0)}};c.useEffect(()=>{m==="prompt-history"&&le()},[m]),c.useEffect(()=>{if(!y)return;const d=window.setTimeout(()=>P(!1),3e3);return()=>window.clearTimeout(d)},[y]);const[Ee,Ae]=c.useState(null),[Me,Le]=c.useState(null),[Ge,R]=c.useState(""),[He,C]=c.useState(""),[_,me]=c.useState(""),[Ne,$e]=c.useState(""),[Ie,Qe]=c.useState(""),[gt,ut]=c.useState(!1),[Dt,Pt]=c.useState(!1),[U,te]=c.useState(""),[je,_e]=c.useState(null);c.useEffect(()=>{u&&(W.current||N(u.promptTemplate??""),V(d=>{const q={};for(const[fe,Ke]of Object.entries(u.promptOverrides??{}))q[fe]=Ke??"";return I.current&&(q[I.current]=d[I.current]??""),q}),L(u.visionBridgePromptMode),!H.current&&(K(J==="append"||u.visionBridgePrompt?u.visionBridgePrompt:u.visionBridgeDefaultPrompt||""),Y.current||F(u.reviewPrompt)))},[u,J]);const[We,Ve]=c.useState(String(u?.terminalBashIdleMs??15e3));c.useEffect(()=>{Ve(String(u?.terminalBashIdleMs??15e3))},[u?.terminalBashIdleMs]);const[bt,Et]=c.useState(String(u?.retryMaxAttempts??6));c.useEffect(()=>{Et(String(u?.retryMaxAttempts??6))},[u?.retryMaxAttempts]);const Zs=bc(e.plugins,{locale:o,t:d=>i(d),disabledPlugins:e.settings?.disabledPlugins??[],layout:e.settings?.uiLayout}),Qt=[];for(const d of Zs["settings.pages"]){if(d.source==="host"||d.hidden||d.kind==="divider")continue;const q=e.plugins.find(fe=>fe.id===d.source.slice(7));q&&Qt.push({entry:d,plugin:q})}const ys=d=>`plugin-page:${d}`;if(c.useEffect(()=>{m.startsWith("plugin-page:")&&(Qt.some(d=>ys(d.entry.id)===m)||f("prompt"))},[m,Qt]),!u)return null;const kt=new Set(u.disabledAgentTools??[]),en=kt.size,ra=[{id:"prompt",icon:s.jsx(wo,{}),label:i("settingsSystemPrompt")},{id:"prompt-history",icon:s.jsx(Ra,{}),label:i("settingsPromptHistory"),count:oe},...b?[{id:"question",icon:s.jsx(Li,{}),label:i("settingsQuestionnaire")}]:[{id:"tools",icon:s.jsx(Ii,{}),label:i("settingsTools"),count:en+(u.disabledMarkers?.length??0)||void 0}],{id:"display",icon:s.jsx(ts,{}),label:i("settingsMessageDisplay")},{id:"quick",icon:s.jsx(Aa,{}),label:i("quickPhrases"),count:u.quickPhrases.length},{id:"skills",icon:s.jsx(Gs,{}),label:i("settingsSkills"),count:u.skills.length},{id:"extensions",icon:s.jsx(pa,{}),label:i("settingsExtensions"),count:u.extensions.length},{id:"plugins",icon:s.jsx(ln,{}),label:i("settingsUiPlugins"),count:e.plugins.length},{id:"review",icon:s.jsx(ms,{}),label:i("settingsReview"),count:u.reviewSkills.length},...b?[]:[{id:"vision",icon:s.jsx(jn,{}),label:i("settingsVisionBridge")}],{id:"presets",icon:s.jsx(Ri,{}),label:i("settingsPresets"),count:u.presets.length},...b?[]:[{id:"subagent-templates",icon:s.jsx(Ai,{}),label:i("settingsSubagentTemplates"),count:u.subagentTemplates.length}],...Qt.map(d=>({id:ys(d.entry.id),icon:d.entry.icon&&!/[a-z]/i.test(d.entry.icon)?s.jsx("span",{children:d.entry.icon}):s.jsx(ln,{}),label:d.entry.label,pluginPage:{plugin:d.plugin,entry:d.entry}}))],tn=m.startsWith("plugin-page:")?Qt.find(d=>ys(d.entry.id)===m)??null:null,oa=new Set(u.disabledSkills),la=new Set(u.disabledExtensions),Fe=d=>ie({type:"set_settings",...d}),sn=()=>{if(!je||!u)return;const d=je.value.trim(),q=je.index;if(_e(null),!d||d===u.quickPhrases[q])return;const fe=[...u.quickPhrases];fe[q]=d,Fe({quickPhrases:fe})},$t=d=>{const q=new Set(oa);q.has(d.name)?q.delete(d.name):q.add(d.name),Fe({disabledSkills:[...q]})},ks=new Set(u.skillsFullText??[]),nn=d=>{const q=new Set(ks);q.has(d)?q.delete(d):q.add(d),Fe({skillsFullText:[...q]})},an=new Set(u.disabledPlugins??[]),Ns=new Set(e.plugins.map(d=>d.id)),O=d=>{const q=new Set(an);q.has(d.id)?q.delete(d.id):q.add(d.id),Fe({disabledPlugins:[...q]})},he=d=>{const q=new Set(la);q.has(d.id)?q.delete(d.id):q.add(d.id),Fe({disabledExtensions:[...q]})},Se={subagent_spawn:i("toolDescSubagentSpawn"),subagent_get_result:i("toolDescSubagentGetResult"),subagent_steer:i("toolDescSubagentSteer"),subagent_list:i("toolDescSubagentList"),subagent_stop:i("toolDescSubagentStop"),subagent_wait_all:i("toolDescSubagentWaitAll"),subagent_templates:i("toolDescSubagentTemplates")},ze=d=>{const q=new Set(kt);q.has(d)?q.delete(d):q.add(d),Fe({disabledAgentTools:[...q]})},Je=u.markersEnabled??!0,At=new Set(u.disabledMarkers??[]),mt=d=>{const q=new Set(At);!q.has(d)?q.add(d):q.delete(d),Fe({disabledMarkers:[...q]})},Tt=(d,q)=>{const fe={name:d,command:q,cwd:"${pwd}"};let Ke;const at=e.terminals.find(Xe=>Xe.title===d);at?(t.restart(at.id),ie({type:"run_command",terminalId:at.id,conversationId:at.conversationId,command:fe,cols:80,rows:24}),Ke=at.id):(Ke=St(),t.create({id:Ke,conversationId:e.activeConversationId||e.state?.conversationId||"",title:d,cwd:e.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:fe})),t.select(Ke),n(),a()},vs=d=>{Ae(null),Tt(`${i("uninstallTitle")} ${d}`,`pi remove npm:${d}`)},ca=(d,q,fe)=>{ie({type:"plugin_job",jobId:St(),action:d,id:q,...fe?{source:fe}:{},...d!=="uninstall"&&Dt?{build:!0}:{}})},Fc=d=>{let q=null;for(const fe of Object.values(e.pluginJobs??{}))fe.pluginId===d&&(!q||fe.startedAt>=q.startedAt)&&(q=fe);return q},Hc=d=>{const q=Fc(d);if(!q)return null;if(q.phase!=="done"){const fe=q.lines[q.lines.length-1]??"";return s.jsxs("div",{className:"set-catalog-job running",title:fe,children:[s.jsx(jt,{className:"set-job-spin"}),i("pluginJobRunning"),s.jsx("span",{className:"set-catalog-job-line",children:fe})]})}return q.ok?s.jsxs("div",{className:"set-catalog-job ok",children:["✓ ",i("pluginJobDone")]}):s.jsxs("div",{className:"set-catalog-job error",children:[s.jsxs("span",{children:["✗ ",q.error||i("pluginJobFailed")]}),q.output?s.jsx("pre",{className:"set-catalog-job-out",children:q.output}):null]})},Uc=[{slot:"topbar.primary",labelKey:"uiLayoutTopbar"},{slot:"topbar.overflow",labelKey:"uiLayoutTopbarOverflow"},{slot:"bottombar",labelKey:"uiLayoutBottombar"},{slot:"composer.actions",labelKey:"uiLayoutComposer"},{slot:"message.actions",labelKey:"uiLayoutMessage"},{slot:"rightpanel.tabs",labelKey:"uiLayoutRightPanel"},{slot:"settings.pages",labelKey:"uiLayoutSettingsPages"}],rn=e.settings?.uiLayout,Ti=d=>Fe({uiLayout:{...rn,...d}}),$c=d=>{const q=new Set(rn?.hidden??[]),fe=new Set(rn?.shown??[]);d.hidden?(q.delete(d.id),fe.add(d.id)):(q.add(d.id),fe.delete(d.id)),Ti({hidden:[...q],shown:[...fe]})},xi=(d,q,fe)=>{const Ke=d.map(eu=>eu.id),at=Ke.indexOf(q),Xe=at+fe;if(at<0||Xe<0||Xe>=Ke.length)return;const it=[...Ke],[Ni]=it.splice(at,1);Ni!==void 0&&(it.splice(Xe,0,Ni),Ti({order:it}))},qc=d=>Fe({uiLayout:fb(rn,d)}),Wc=()=>Fe({uiLayout:gb()}),yi=d=>{Le(null),ca("uninstall",d)},ki=(d,q)=>{ca("update",d,q)},Kc=d=>{ca("install",d.id,d.source)},Yc=d=>{ie({type:"plugin_catalog_remove",id:d})},Gc=()=>{const d=Ge.trim();d&&(ie({type:"plugin_catalog_add",entry:{source:d,...He.trim()?{id:He.trim()}:{},..._.trim()?{name:_.trim()}:{},...Ne.trim()?{description:Ne.trim()}:{},...Ie.trim()?{icon:Ie.trim()}:{}}}),R(""),C(""),me(""),$e(""),Qe(""),ut(!1))},zc=d=>{const q=new Set(u.reviewSkills.filter(fe=>!fe.enabled).map(fe=>fe.name));q.has(d.name)?q.delete(d.name):q.add(d.name),Fe({reviewDisabledSkills:[...q]})},Vc=()=>Fe({promptTemplate:v}),Qc=d=>{Fe({promptOverrides:{[d]:B[d]??""}})},ua=d=>{I.current===d&&(I.current=null),w(null),V(q=>{const fe={...q};return delete fe[d],fe}),Fe({promptOverrides:{[d]:""}})},Cs=d=>be(q=>({...q,[d]:!q[d]})),da=(d,q)=>{V(fe=>({...fe,[d]:q})),w(d)},Xc=()=>{W.current=!1,I.current=null,N(pn),V({}),Fe({promptTemplate:pn,promptOverrides:{}})},Jc=d=>{N(q=>q.trim()?`${q}
345
345
 
346
- {{${d}}}`:`{{${d}}}`)},Jc=v.trim()&&v.trim()!==cn||Object.values(B).some(d=>d.trim());return s.jsx("div",{className:"modal-backdrop",onClick:a,children:s.jsxs("div",{className:"modal settings-modal",onClick:d=>d.stopPropagation(),children:[s.jsx("button",{type:"button",className:"modal-close","aria-label":i("close"),onClick:a,children:s.jsx(tt,{})}),s.jsxs("div",{className:"modal-head",children:[s.jsx(Cn,{className:"modal-head-icon"}),s.jsx("h2",{children:i("settingsTitle")}),s.jsx(nt,{text:i("settingsDesc")})]}),s.jsxs("div",{className:"settings-layout",children:[s.jsx("nav",{className:"settings-rail","aria-label":i("settingsTitle"),children:aa.map(d=>s.jsxs("button",{type:"button",className:`settings-tab${m===d.id?" active":""}`,"aria-current":m===d.id?"true":void 0,title:d.hint??d.label,onClick:()=>f(d.id),children:[s.jsx("span",{className:"settings-tab-icon",children:d.icon}),s.jsx("span",{className:"settings-tab-label",children:d.label}),d.count!==void 0&&s.jsx("span",{className:"set-count",children:d.count})]},d.id))}),s.jsxs("div",{className:"modal-body",ref:x,children:[m==="prompt"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(hs,{className:"set-section-icon"}),i("settingsSystemPrompt"),s.jsx(nt,{text:`${i("promptComposeHint")}
347
- ${i("promptComposeDesc")}`})]}),s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",children:i("promptTemplateLabel")}),s.jsx("textarea",{className:"set-prompt-input",rows:8,spellCheck:!1,placeholder:cn,value:v,onFocus:()=>K.current=!0,onBlur:()=>{K.current=!1,zc()},onChange:d=>N(d.target.value)}),s.jsxs("div",{className:"compose-toolbar",children:[s.jsx("span",{className:"set-field-label set-muted",children:i("promptInsertTokens")}),R.map(d=>s.jsx("button",{type:"button",className:"token-chip",title:l(`promptTok_${d}_desc`),onClick:()=>Xc(d),children:`{{${d}}}`},d))]})]}),s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",children:i("promptSourcesLabel")}),R.map(d=>{const W=B[d]??"",fe=u.promptSourceDefaults?.[d]??"",qe=I===d,at=fe.split(`
348
- `).length>6||fe.length>480;if(Sc(d)){const Xe=W.trim()?W:fe;return s.jsxs("div",{className:"override-row readonly",children:[s.jsxs("div",{className:"override-row-head",children:[`{{${d}}}`,s.jsxs("span",{className:"set-muted",children:[l(`promptTok_${d}`)," ",s.jsx(nt,{text:l(`promptTok_${d}_desc`)})]}),W.trim()?s.jsx("button",{type:"button",className:"set-btn-mini",title:i("promptReadonlyLockedHint"),onClick:()=>ca(d),children:i("promptResetSource")}):s.jsx("span",{className:"set-muted",children:i("promptReadonlyBadge")})]}),s.jsx("div",{className:`source-default readonly${Xe.trim()?"":" empty"}`,title:i("promptReadonlyTitle"),children:Xe.trim()?s.jsxs(s.Fragment,{children:[s.jsx("pre",{className:`source-default-text${at?ce[d]?" expanded":" clamped":""}`,children:Xe}),at&&s.jsx("span",{className:"source-default-toggle",role:"button",tabIndex:0,onClick:it=>{it.stopPropagation(),Cs(d)},onKeyDown:it=>{(it.key==="Enter"||it.key===" ")&&(it.preventDefault(),it.stopPropagation(),Cs(d))},children:ce[d]?i("promptSourceCollapse"):i("promptSourceExpand")})]}):s.jsx("span",{className:"source-default-empty",children:i("promptSourceDefaultEmpty")})})]},d)}return s.jsxs("div",{className:"override-row",children:[s.jsxs("div",{className:"override-row-head",children:[`{{${d}}}`,s.jsxs("span",{className:"set-muted",children:[l(`promptTok_${d}`)," ",s.jsx(nt,{text:l(`promptTok_${d}_desc`)})]}),W.trim()?s.jsx("button",{type:"button",className:"set-btn-mini",onClick:()=>ca(d),children:i("promptResetSource")}):s.jsx("span",{className:"set-muted",children:i("promptAutoBadge")})]}),W.trim()||qe?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"set-prompt-input override-input",rows:Math.min(10,Math.max(1,W.split(`
349
- `).length)),autoFocus:qe,placeholder:i("promptOverridePlaceholder"),value:W,onFocus:Xe=>{A.current=d,$(d);const it=Xe.currentTarget;it.value&&it.value===fe&&it.setSelectionRange(it.value.length,it.value.length)},onBlur:()=>{A.current===d&&(A.current=null);const Xe=B[d]??"";if(Xe.trim()&&Xe===fe){ca(d);return}Vc(d),Xe.trim()||$(null)},onChange:Xe=>X(it=>({...it,[d]:Xe.target.value}))}),s.jsxs("div",{className:"override-edit-foot",children:[s.jsxs("div",{className:"override-edit-foot-head",children:[s.jsx("span",{className:"set-muted",children:i("promptSourceRefLabel")}),at&&s.jsx("button",{type:"button",className:"source-default-toggle",onClick:()=>Cs(d),children:ce[d]?i("promptSourceCollapse"):i("promptSourceExpand")})]}),fe.trim()?s.jsx("pre",{className:`source-default-text${at?ce[d]?" expanded":" clamped":""}`,children:fe}):s.jsx("span",{className:"source-default-empty",children:i("promptSourceDefaultEmpty")}),!W.trim()&&fe.trim()&&s.jsx("button",{type:"button",className:"override-seed-btn",title:i("promptSourceSeedTip"),onClick:()=>ua(d,fe),children:i("promptSourceSeedButton")})]})]}):s.jsx("div",{className:"source-default",title:i("promptSourceDefaultEditHint"),role:"button",tabIndex:0,onClick:()=>ua(d,fe),onKeyDown:Xe=>{(Xe.key==="Enter"||Xe.key===" ")&&(Xe.preventDefault(),ua(d,fe))},children:fe.trim()?s.jsxs(s.Fragment,{children:[s.jsx("pre",{className:`source-default-text${at?ce[d]?" expanded":" clamped":""}`,children:fe}),at&&s.jsx("span",{className:"source-default-toggle",role:"button",tabIndex:0,onClick:Xe=>{Xe.stopPropagation(),Cs(d)},onKeyDown:Xe=>{(Xe.key==="Enter"||Xe.key===" ")&&(Xe.preventDefault(),Xe.stopPropagation(),Cs(d))},children:ce[d]?i("promptSourceCollapse"):i("promptSourceExpand")})]}):s.jsx("span",{className:"source-default-empty",children:i("promptSourceDefaultEmpty")})})]},d)}),s.jsx("div",{className:"compose-toolbar",children:s.jsx("button",{type:"button",className:"set-btn",onClick:Qc,disabled:!Jc,children:i("promptResetAll")})})]}),s.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":ue,onClick:()=>pe(d=>!d),children:[i("settingsViewPrompt")," ",ue?"▴":"▾"]}),ue&&s.jsxs("div",{className:"set-prompt-view",children:[s.jsxs("div",{className:"set-prompt-view-head",children:[s.jsx("span",{children:i("settingsViewPrompt")}),s.jsx(nt,{text:i("settingsViewPromptHint")}),s.jsx(Hn,{text:u.effectiveSystemPrompt})]}),u.effectiveSystemPrompt?s.jsx("pre",{className:"set-prompt-view-text",children:u.effectiveSystemPrompt}):s.jsx("p",{className:"set-empty",children:i("settingsViewPromptEmpty")})]}),s.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":ke,onClick:()=>Be(d=>!d),children:[i("settingsViewToolsSchema")," ",ke?"▴":"▾"]}),ke&&s.jsx("div",{className:"set-prompt-view",children:s.jsxs("div",{className:"set-prompt-tools",children:[s.jsxs("div",{className:"set-prompt-view-head",children:[s.jsx("span",{children:i("settingsViewToolsSchema")}),s.jsx(nt,{text:i("settingsViewToolsSchemaHint")}),s.jsx(Hn,{text:u.toolsSchema})]}),u.toolsSchema?s.jsx("pre",{className:"set-prompt-view-text",children:u.toolsSchema}):s.jsx("p",{className:"set-empty",children:i("settingsViewToolsSchemaEmpty")})]})})]}),m==="prompt-history"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(ja,{className:"set-section-icon"}),i("settingsPromptHistory"),s.jsx(nt,{text:i("settingsPromptHistoryDesc")}),s.jsx("span",{className:"set-count",children:i("promptHistoryCount",{n:String(oe)})})]}),oe===0?s.jsx("p",{className:"set-empty",children:i("promptHistoryEmpty")}):s.jsx("p",{className:"set-hint",children:i("promptHistoryCount",{n:String(oe)})}),s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",htmlFor:"ph-max",children:i("promptHistoryMax")}),s.jsxs("div",{className:"set-mode-row",children:[s.jsx("input",{id:"ph-max",className:"set-input",type:"number",min:1,max:500,step:1,value:String(V.maxEntries),onChange:d=>{const W=Math.floor(Number(d.target.value)||0),fe={...V,maxEntries:W};Ee(fe)},onBlur:()=>{const d={...V};(!Number.isFinite(d.maxEntries)||d.maxEntries<1)&&(d.maxEntries=1),d.maxEntries>500&&(d.maxEntries=500),d.maxEntries=Math.floor(d.maxEntries),Ee(d),va(d),le()}}),s.jsx(nt,{text:i("promptHistoryMaxHint")})]})]}),s.jsx(Ze,{title:i("promptHistoryCharLimit"),tip:i("promptHistoryCharLimitHint"),enabled:V.charLimitEnabled,onToggle:()=>{const d={...V,charLimitEnabled:!V.charLimitEnabled};Ee(d),va(d),le()}}),V.charLimitEnabled&&s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",htmlFor:"ph-char-limit",children:i("promptHistoryCharLimit")}),s.jsx("input",{id:"ph-char-limit",className:"set-input",type:"number",min:100,max:2e4,step:100,placeholder:i("promptHistoryCharLimitPlaceholder"),value:String(V.charLimit),onChange:d=>{const W=Math.floor(Number(d.target.value)||0);Ee({...V,charLimit:W})},onBlur:()=>{let d=Math.floor(Number(V.charLimit)||0);(!Number.isFinite(d)||d<100)&&(d=100),d>2e4&&(d=2e4);const W={...V,charLimit:d};Ee(W),va(W),le()}})]}),s.jsxs("div",{className:"set-field",style:{marginTop:12},children:[s.jsxs("button",{type:"button",className:`set-uninstall${y?" confirm":""}`,disabled:oe===0,title:i(oe===0?"promptHistoryEmpty":"promptHistoryClear"),onClick:()=>{if(!y){P(!0);return}Mg(),P(!1),le()},children:[s.jsx(ut,{})," ",i(y?"promptHistoryClearConfirm":"promptHistoryClear")]}),oe>0&&s.jsx("span",{className:"set-hint",style:{marginLeft:8},children:i("promptHistoryCount",{n:String(oe)})})]}),s.jsxs("p",{className:"set-hint",children:[s.jsx(_o,{style:{verticalAlign:"-2px",marginRight:4}}),i("settingsPromptHistoryDesc")]})]}),m==="tools"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Ai,{className:"set-section-icon"}),i("settingsTools")]}),s.jsx("div",{className:"set-field-label",children:i("toolsSectionTerminal")}),Oo.map(d=>s.jsx(Ze,{title:d,tip:i("settingsTerminalToolsDesc"),enabled:!Tt.has(d),onToggle:()=>Qe(d)},d)),s.jsx(Ze,{title:i("terminalBashTakeover"),tip:i("terminalBashTakeoverDesc"),enabled:u.terminalBash,onToggle:()=>He({terminalBash:!u.terminalBash})}),u.terminalBash&&s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",htmlFor:"tb-idle-ms",children:i("terminalBashIdleMs")}),s.jsx("input",{id:"tb-idle-ms",className:"set-input",type:"number",min:0,step:1e3,value:Ke,onChange:d=>ze(d.target.value),onBlur:()=>{const d=Math.max(0,Math.floor(Number(Ke)||0));ze(String(d)),d!==u.terminalBashIdleMs&&He({terminalBashIdleMs:d})}})]}),s.jsx("div",{className:"set-field-label",children:i("toolsSectionSubagent")}),s.jsx("div",{className:"set-row-desc",children:i("toolsSubagentDepHint")}),Mo.map(d=>s.jsx(Ze,{title:d,tip:Ve[d],enabled:!Tt.has(d),onToggle:()=>Qe(d)},d)),s.jsxs("div",{className:"set-field-label",children:[i("settingsMarkers"),s.jsx(nt,{text:`${i("settingsMarkersDesc")}
346
+ {{${d}}}`:`{{${d}}}`)},Zc=v.trim()&&v.trim()!==pn||Object.values(B).some(d=>d.trim());return s.jsx("div",{className:"modal-backdrop",onClick:a,children:s.jsxs("div",{className:"modal settings-modal",onClick:d=>d.stopPropagation(),children:[s.jsx("button",{type:"button",className:"modal-close","aria-label":i("close"),onClick:a,children:s.jsx(tt,{})}),s.jsxs("div",{className:"modal-head",children:[s.jsx(_n,{className:"modal-head-icon"}),s.jsx("h2",{children:i("settingsTitle")}),s.jsx(nt,{text:i("settingsDesc")})]}),s.jsxs("div",{className:"settings-layout",children:[s.jsx("nav",{className:"settings-rail","aria-label":i("settingsTitle"),children:ra.map(d=>s.jsxs("button",{type:"button",className:`settings-tab${m===d.id?" active":""}`,"aria-current":m===d.id?"true":void 0,title:d.hint??d.label,onClick:()=>f(d.id),children:[s.jsx("span",{className:"settings-tab-icon",children:d.icon}),s.jsx("span",{className:"settings-tab-label",children:d.label}),d.count!==void 0&&s.jsx("span",{className:"set-count",children:d.count})]},d.id))}),s.jsxs("div",{className:"modal-body",ref:x,children:[m==="prompt"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(ms,{className:"set-section-icon"}),i("settingsSystemPrompt"),s.jsx(nt,{text:`${i("promptComposeHint")}
347
+ ${i("promptComposeDesc")}`})]}),s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",children:i("promptTemplateLabel")}),s.jsx("textarea",{className:"set-prompt-input",rows:8,spellCheck:!1,placeholder:pn,value:v,onFocus:()=>W.current=!0,onBlur:()=>{W.current=!1,Vc()},onChange:d=>N(d.target.value)}),s.jsxs("div",{className:"compose-toolbar",children:[s.jsx("span",{className:"set-field-label set-muted",children:i("promptInsertTokens")}),j.map(d=>s.jsx("button",{type:"button",className:"token-chip",title:l(`promptTok_${d}_desc`),onClick:()=>Jc(d),children:`{{${d}}}`},d))]})]}),s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",children:i("promptSourcesLabel")}),j.map(d=>{const q=B[d]??"",fe=u.promptSourceDefaults?.[d]??"",Ke=X===d,at=fe.split(`
348
+ `).length>6||fe.length>480;if(Ac(d)){const Xe=q.trim()?q:fe;return s.jsxs("div",{className:"override-row readonly",children:[s.jsxs("div",{className:"override-row-head",children:[`{{${d}}}`,s.jsxs("span",{className:"set-muted",children:[l(`promptTok_${d}`)," ",s.jsx(nt,{text:l(`promptTok_${d}_desc`)})]}),q.trim()?s.jsx("button",{type:"button",className:"set-btn-mini",title:i("promptReadonlyLockedHint"),onClick:()=>ua(d),children:i("promptResetSource")}):s.jsx("span",{className:"set-muted",children:i("promptReadonlyBadge")})]}),s.jsx("div",{className:`source-default readonly${Xe.trim()?"":" empty"}`,title:i("promptReadonlyTitle"),children:Xe.trim()?s.jsxs(s.Fragment,{children:[s.jsx("pre",{className:`source-default-text${at?ce[d]?" expanded":" clamped":""}`,children:Xe}),at&&s.jsx("span",{className:"source-default-toggle",role:"button",tabIndex:0,onClick:it=>{it.stopPropagation(),Cs(d)},onKeyDown:it=>{(it.key==="Enter"||it.key===" ")&&(it.preventDefault(),it.stopPropagation(),Cs(d))},children:ce[d]?i("promptSourceCollapse"):i("promptSourceExpand")})]}):s.jsx("span",{className:"source-default-empty",children:i("promptSourceDefaultEmpty")})})]},d)}return s.jsxs("div",{className:"override-row",children:[s.jsxs("div",{className:"override-row-head",children:[`{{${d}}}`,s.jsxs("span",{className:"set-muted",children:[l(`promptTok_${d}`)," ",s.jsx(nt,{text:l(`promptTok_${d}_desc`)})]}),q.trim()?s.jsx("button",{type:"button",className:"set-btn-mini",onClick:()=>ua(d),children:i("promptResetSource")}):s.jsx("span",{className:"set-muted",children:i("promptAutoBadge")})]}),q.trim()||Ke?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"set-prompt-input override-input",rows:Math.min(10,Math.max(1,q.split(`
349
+ `).length)),autoFocus:Ke,placeholder:i("promptOverridePlaceholder"),value:q,onFocus:Xe=>{I.current=d,w(d);const it=Xe.currentTarget;it.value&&it.value===fe&&it.setSelectionRange(it.value.length,it.value.length)},onBlur:()=>{I.current===d&&(I.current=null);const Xe=B[d]??"";if(Xe.trim()&&Xe===fe){ua(d);return}Qc(d),Xe.trim()||w(null)},onChange:Xe=>V(it=>({...it,[d]:Xe.target.value}))}),s.jsxs("div",{className:"override-edit-foot",children:[s.jsxs("div",{className:"override-edit-foot-head",children:[s.jsx("span",{className:"set-muted",children:i("promptSourceRefLabel")}),at&&s.jsx("button",{type:"button",className:"source-default-toggle",onClick:()=>Cs(d),children:ce[d]?i("promptSourceCollapse"):i("promptSourceExpand")})]}),fe.trim()?s.jsx("pre",{className:`source-default-text${at?ce[d]?" expanded":" clamped":""}`,children:fe}):s.jsx("span",{className:"source-default-empty",children:i("promptSourceDefaultEmpty")}),!q.trim()&&fe.trim()&&s.jsx("button",{type:"button",className:"override-seed-btn",title:i("promptSourceSeedTip"),onClick:()=>da(d,fe),children:i("promptSourceSeedButton")})]})]}):s.jsx("div",{className:"source-default",title:i("promptSourceDefaultEditHint"),role:"button",tabIndex:0,onClick:()=>da(d,fe),onKeyDown:Xe=>{(Xe.key==="Enter"||Xe.key===" ")&&(Xe.preventDefault(),da(d,fe))},children:fe.trim()?s.jsxs(s.Fragment,{children:[s.jsx("pre",{className:`source-default-text${at?ce[d]?" expanded":" clamped":""}`,children:fe}),at&&s.jsx("span",{className:"source-default-toggle",role:"button",tabIndex:0,onClick:Xe=>{Xe.stopPropagation(),Cs(d)},onKeyDown:Xe=>{(Xe.key==="Enter"||Xe.key===" ")&&(Xe.preventDefault(),Xe.stopPropagation(),Cs(d))},children:ce[d]?i("promptSourceCollapse"):i("promptSourceExpand")})]}):s.jsx("span",{className:"source-default-empty",children:i("promptSourceDefaultEmpty")})})]},d)}),s.jsx("div",{className:"compose-toolbar",children:s.jsx("button",{type:"button",className:"set-btn",onClick:Xc,disabled:!Zc,children:i("promptResetAll")})})]}),s.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":ue,onClick:()=>pe(d=>!d),children:[i("settingsViewPrompt")," ",ue?"▴":"▾"]}),ue&&s.jsxs("div",{className:"set-prompt-view",children:[s.jsxs("div",{className:"set-prompt-view-head",children:[s.jsx("span",{children:i("settingsViewPrompt")}),s.jsx(nt,{text:i("settingsViewPromptHint")}),s.jsx(qn,{text:u.effectiveSystemPrompt})]}),u.effectiveSystemPrompt?s.jsx("pre",{className:"set-prompt-view-text",children:u.effectiveSystemPrompt}):s.jsx("p",{className:"set-empty",children:i("settingsViewPromptEmpty")})]}),s.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":ke,onClick:()=>Oe(d=>!d),children:[i("settingsViewToolsSchema")," ",ke?"▴":"▾"]}),ke&&s.jsx("div",{className:"set-prompt-view",children:s.jsxs("div",{className:"set-prompt-tools",children:[s.jsxs("div",{className:"set-prompt-view-head",children:[s.jsx("span",{children:i("settingsViewToolsSchema")}),s.jsx(nt,{text:i("settingsViewToolsSchemaHint")}),s.jsx(qn,{text:u.toolsSchema})]}),u.toolsSchema?s.jsx("pre",{className:"set-prompt-view-text",children:u.toolsSchema}):s.jsx("p",{className:"set-empty",children:i("settingsViewToolsSchemaEmpty")})]})})]}),m==="prompt-history"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Ra,{className:"set-section-icon"}),i("settingsPromptHistory"),s.jsx(nt,{text:i("settingsPromptHistoryDesc")}),s.jsx("span",{className:"set-count",children:i("promptHistoryCount",{n:String(oe)})})]}),oe===0?s.jsx("p",{className:"set-empty",children:i("promptHistoryEmpty")}):s.jsx("p",{className:"set-hint",children:i("promptHistoryCount",{n:String(oe)})}),s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",htmlFor:"ph-max",children:i("promptHistoryMax")}),s.jsxs("div",{className:"set-mode-row",children:[s.jsx("input",{id:"ph-max",className:"set-input",type:"number",min:1,max:500,step:1,value:String(z.maxEntries),onChange:d=>{const q=Math.floor(Number(d.target.value)||0),fe={...z,maxEntries:q};ge(fe)},onBlur:()=>{const d={...z};(!Number.isFinite(d.maxEntries)||d.maxEntries<1)&&(d.maxEntries=1),d.maxEntries>500&&(d.maxEntries=500),d.maxEntries=Math.floor(d.maxEntries),ge(d),Ca(d),le()}}),s.jsx(nt,{text:i("promptHistoryMaxHint")})]})]}),s.jsx(Ze,{title:i("promptHistoryCharLimit"),tip:i("promptHistoryCharLimitHint"),enabled:z.charLimitEnabled,onToggle:()=>{const d={...z,charLimitEnabled:!z.charLimitEnabled};ge(d),Ca(d),le()}}),z.charLimitEnabled&&s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",htmlFor:"ph-char-limit",children:i("promptHistoryCharLimit")}),s.jsx("input",{id:"ph-char-limit",className:"set-input",type:"number",min:100,max:2e4,step:100,placeholder:i("promptHistoryCharLimitPlaceholder"),value:String(z.charLimit),onChange:d=>{const q=Math.floor(Number(d.target.value)||0);ge({...z,charLimit:q})},onBlur:()=>{let d=Math.floor(Number(z.charLimit)||0);(!Number.isFinite(d)||d<100)&&(d=100),d>2e4&&(d=2e4);const q={...z,charLimit:d};ge(q),Ca(q),le()}})]}),s.jsxs("div",{className:"set-field",style:{marginTop:12},children:[s.jsxs("button",{type:"button",className:`set-uninstall${y?" confirm":""}`,disabled:oe===0,title:i(oe===0?"promptHistoryEmpty":"promptHistoryClear"),onClick:()=>{if(!y){P(!0);return}Mg(),P(!1),le()},children:[s.jsx(dt,{})," ",i(y?"promptHistoryClearConfirm":"promptHistoryClear")]}),oe>0&&s.jsx("span",{className:"set-hint",style:{marginLeft:8},children:i("promptHistoryCount",{n:String(oe)})})]}),s.jsxs("p",{className:"set-hint",children:[s.jsx(Io,{style:{verticalAlign:"-2px",marginRight:4}}),i("settingsPromptHistoryDesc")]})]}),m==="tools"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Ii,{className:"set-section-icon"}),i("settingsTools")]}),s.jsx("div",{className:"set-field-label",children:i("toolsSectionTerminal")}),Bo.map(d=>s.jsx(Ze,{title:d,tip:i("settingsTerminalToolsDesc"),enabled:!kt.has(d),onToggle:()=>ze(d)},d)),s.jsx(Ze,{title:i("terminalBashTakeover"),tip:i("terminalBashTakeoverDesc"),enabled:u.terminalBash,onToggle:()=>Fe({terminalBash:!u.terminalBash})}),u.terminalBash&&s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",htmlFor:"tb-idle-ms",children:i("terminalBashIdleMs")}),s.jsx("input",{id:"tb-idle-ms",className:"set-input",type:"number",min:0,step:1e3,value:We,onChange:d=>Ve(d.target.value),onBlur:()=>{const d=Math.max(0,Math.floor(Number(We)||0));Ve(String(d)),d!==u.terminalBashIdleMs&&Fe({terminalBashIdleMs:d})}})]}),s.jsx("div",{className:"set-field-label",children:i("toolsSectionSubagent")}),s.jsx("div",{className:"set-row-desc",children:i("toolsSubagentDepHint")}),Fo.map(d=>s.jsx(Ze,{title:d,tip:Se[d],enabled:!kt.has(d),onToggle:()=>ze(d)},d)),s.jsxs("div",{className:"set-field-label",children:[i("settingsMarkers"),s.jsx(nt,{text:`${i("settingsMarkersDesc")}
350
350
  ${i("markerRenameTip")}`})]}),s.jsx(Ze,{title:i("markersEnabled"),tip:`${i("markersEnabledDesc")}
351
- ${i("markersOffHint")}`,enabled:Et,onToggle:()=>He({markersEnabled:!Et})}),Et&&(u.markers?.length??0)===0&&s.jsxs("p",{className:"set-empty",children:[i("loading"),"..."]}),Et&&u.markers&&u.markers.length>0&&u.markers.map(d=>s.jsx(Ze,{title:d.name==="todo"?i("markerGroupTodo"):d.name==="notify"?i("markerGroupNotify"):d.name==="conv"?i("markerGroupRename"):d.name,tip:d.guidance.join(`
352
- `),enabled:d.enabled,onToggle:()=>xt(d.name)},d.name)),s.jsx(Ze,{title:hn,tip:`${i("todoListEnabledDesc")}
353
- ${i("todoListOffHint")}`,enabled:!Tt.has(hn),onToggle:()=>Qe(hn)}),s.jsx("div",{className:"set-field-label",children:i("toolsSectionOther")}),s.jsx(Ze,{title:dn,tip:`${i("editSoftEnabledDesc")}
354
- ${i("editSoftOffHint")}`,enabled:!Tt.has(dn),onToggle:()=>Qe(dn)}),s.jsx(Ze,{title:pn,tip:`${i("delegateTaskEnabledDesc")}
355
- ${i("delegateTaskOffHint")}`,enabled:!Tt.has(pn),onToggle:()=>Qe(pn)}),s.jsx(Ze,{title:mn,tip:`${i("questionnaireEnabledDesc")}
356
- ${i("questionnaireOffHint")}`,enabled:!Tt.has(mn),onToggle:()=>Qe(mn)}),s.jsx(Ze,{title:Ps,tip:`${i("browserPageEnabledDesc")}
357
- ${i("browserPageOffHint")}`,enabled:!Tt.has(Ps),onToggle:()=>Qe(Ps)})]}),m==="question"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Ri,{className:"set-section-icon"}),i("settingsQuestionnaire")]}),s.jsx(Ze,{title:i("questionnaireEnabled"),tip:`${i("questionnaireEnabledDesc")}
358
- ${i("questionnaireOffHint")}`,enabled:u.questionnaireEnabled,onToggle:()=>He({questionnaireEnabled:!u.questionnaireEnabled})})]}),m==="display"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(ts,{className:"set-section-icon"}),i("settingsMessageDisplay")]}),s.jsxs("div",{className:"set-field",children:[s.jsxs("label",{className:"set-field-label",htmlFor:"model-retry-max",children:[i("modelRetryAttempts")," ",s.jsx(nt,{text:i("modelRetryHint")})]}),s.jsx("input",{id:"model-retry-max",className:"set-input",type:"number",min:0,max:100,step:1,value:pt,onChange:d=>It(d.target.value),onBlur:()=>{const d=Math.min(100,Math.max(0,Math.floor(Number(pt)||0)));It(String(d)),d!==u.retryMaxAttempts&&He({retryMaxAttempts:d})},onKeyDown:d=>{d.key==="Enter"&&d.target.blur()}})]}),s.jsx("hr",{className:"set-sep"}),s.jsx(Ze,{title:i("thinkingWrap"),tip:i("thinkingWrapDesc"),enabled:u.thinkingWrap??!0,onToggle:()=>He({thinkingWrap:!(u.thinkingWrap??!0)})}),s.jsx(Ze,{title:i("toolsWrap"),tip:i("toolsWrapDesc"),enabled:u.toolsWrap??!0,onToggle:()=>He({toolsWrap:!(u.toolsWrap??!0)})}),s.jsx(Ze,{title:i("devNoCache"),tip:i("devNoCacheDesc"),enabled:u.devNoCache??!0,onToggle:()=>He({devNoCache:!(u.devNoCache??!0)})}),s.jsx(Ze,{title:i("autoReload"),tip:i("autoReloadDesc"),enabled:u.autoReload??!0,onToggle:()=>He({autoReload:!(u.autoReload??!0)})}),s.jsx("hr",{className:"set-sep"}),s.jsx(Ze,{title:i("wideChat"),tip:i("wideChatDesc"),enabled:ye,onToggle:()=>vb({wide:!ye})}),s.jsx(Ze,{title:i("projectTitle"),tip:i("projectTitleDesc"),enabled:Ae,onToggle:()=>Ab({projectName:!Ae})}),s.jsx("hr",{className:"set-sep"}),s.jsxs("div",{className:"set-row",children:[s.jsxs("div",{className:"set-row-info",children:[s.jsxs("div",{className:"set-row-name",children:[i("wallpaperTitle"),s.jsx(nt,{text:i("wallpaperDesc")})]}),s.jsxs("div",{className:"wallpaper-url-row",children:[s.jsx("input",{className:"set-input wallpaper-url",placeholder:i("wallpaperUrlPh"),value:Ye,maxLength:2e3,spellCheck:!1,onFocus:()=>{ae.current=!0},onChange:d=>Pe(d.target.value),onBlur:()=>{if(ae.current=!1,!Ye.trim()&&ve.url.startsWith("data:")){Pe("");return}const d=si(Ye);Pe(d),d!==ve.url&&_s({...ve,url:d})},onKeyDown:d=>{d.key==="Enter"?d.target.blur():d.key==="Escape"&&(Pe(ve.url.startsWith("data:")?"":ve.url),d.target.blur())}}),s.jsxs("button",{type:"button",className:"set-save-btn",disabled:Oe,onClick:()=>be.current?.click(),children:[s.jsx(Nu,{})," ",i("wallpaperUpload")]}),s.jsx("input",{ref:be,type:"file",accept:"image/*",hidden:!0,onChange:Q})]}),We&&s.jsx("p",{className:"set-hint",children:i("wallpaperUploadFailed")}),s.jsxs("div",{className:"wallpaper-sliders",children:[s.jsxs("label",{className:"wallpaper-slider",children:[s.jsx("span",{children:i("wallpaperDim")}),s.jsx("input",{type:"range",min:0,max:95,step:1,value:ve.dim,onChange:d=>_s({...ve,dim:Number(d.target.value)})}),s.jsxs("output",{children:[ve.dim,"%"]})]}),s.jsxs("label",{className:"wallpaper-slider",children:[s.jsx("span",{children:i("wallpaperBlur")}),s.jsx("input",{type:"range",min:0,max:24,step:1,value:ve.blur,onChange:d=>_s({...ve,blur:Number(d.target.value)})}),s.jsxs("output",{children:[ve.blur,"px"]})]})]})]}),ve.url&&s.jsxs("div",{className:"wallpaper-current",children:[s.jsx("img",{className:"wallpaper-preview",src:ve.url,alt:""}),s.jsx("button",{type:"button",className:"wallpaper-clear",onClick:()=>{Pe(""),_s({...ve,url:""})},children:i("wallpaperClear")})]})]})]}),m==="quick"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(_a,{className:"set-section-icon"}),i("quickPhrases"),s.jsx(nt,{text:i("quickPhrasesDesc")}),s.jsx("span",{className:"set-count",children:u.quickPhrases.length})]}),s.jsx(Ze,{title:i("quickPhrasesEnabled"),tip:i("quickPhrasesDesc"),enabled:u.quickPhrasesEnabled,onToggle:()=>He({quickPhrasesEnabled:!u.quickPhrasesEnabled})}),!u.quickPhrasesEnabled&&s.jsx("p",{className:"set-hint",children:i("quickPhrasesOffHint")}),s.jsxs("div",{className:"set-preset-save",children:[s.jsx("input",{className:"set-input",placeholder:i("quickPhrasesPlaceholder"),value:H,maxLength:200,onChange:d=>te(d.target.value),onKeyDown:d=>{d.key==="Enter"&&H.trim()&&(He({quickPhrases:[...u.quickPhrases,H.trim()]}),te(""))}}),s.jsxs("button",{type:"button",className:"set-save-btn",disabled:!H.trim(),onClick:()=>{He({quickPhrases:[...u.quickPhrases,H.trim()]}),te("")},children:[s.jsx(kt,{})," ",i("quickPhrasesAdd")]})]}),u.quickPhrases.length===0?s.jsx("p",{className:"set-empty",children:i("quickPhrasesEmpty")}):s.jsx("div",{className:"set-list",children:u.quickPhrases.map((d,W)=>s.jsx("div",{className:"set-row",children:_e?.index===W?s.jsx("div",{className:"set-row-info",children:s.jsx("input",{className:"set-input",autoFocus:!0,value:_e.value,maxLength:200,placeholder:i("quickPhrasesEditPh"),onChange:fe=>je({index:W,value:fe.target.value}),onKeyDown:fe=>{fe.key==="Enter"?Pt():fe.key==="Escape"&&je(null)},onBlur:Pt})}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"set-row-info",children:s.jsx("div",{className:"set-row-name",title:d,children:d})}),s.jsxs("div",{className:"set-row-actions",children:[s.jsx("button",{type:"button",className:"set-icon-btn",title:i("quickPhrasesEdit"),onClick:()=>je({index:W,value:d}),children:s.jsx(Ys,{})}),s.jsx("button",{type:"button",className:"set-icon-btn",title:i("quickPhrasesMoveUp"),disabled:W===0,onClick:()=>{const fe=[...u.quickPhrases];[fe[W-1],fe[W]]=[fe[W],fe[W-1]],He({quickPhrases:fe})},children:"↑"}),s.jsx("button",{type:"button",className:"set-icon-btn",title:i("quickPhrasesMoveDown"),disabled:W===u.quickPhrases.length-1,onClick:()=>{const fe=[...u.quickPhrases];[fe[W],fe[W+1]]=[fe[W+1],fe[W]],He({quickPhrases:fe})},children:"↓"}),s.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("quickPhrasesDelete"),onClick:()=>He({quickPhrases:u.quickPhrases.filter((fe,qe)=>qe!==W)}),children:s.jsx(ut,{})})]})]})},`${W}:${d}`))}),s.jsx("div",{className:"compose-toolbar",children:s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{je(null),He({quickPhrases:Gn[o]??Gn.en})},children:i("quickPhrasesReset")})})]}),m==="skills"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Gs,{className:"set-section-icon"}),i("settingsSkills"),s.jsx(nt,{text:`${i("skillFullTextLabel")}:${i("skillFullTextDesc")}`}),s.jsx("span",{className:"set-count",children:u.skills.length})]}),u.skills.length===0?s.jsx("p",{className:"set-empty",children:i(b?"dshSkillsNote":"noSkills")}):s.jsx("div",{className:"set-list",children:u.skills.map(d=>s.jsx(Ze,{title:d.name,subtitle:d.description,enabled:d.enabled,onToggle:()=>tn(d),action:s.jsx("button",{type:"button",className:`tpl-chip${Ns.has(d.name)?" on":""}`,title:i("skillFullTextDesc"),onClick:()=>oa(d.name),children:i("skillFullTextShort")})},d.name))})]}),m==="extensions"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(da,{className:"set-section-icon"}),i("settingsExtensions"),s.jsx("span",{className:"set-count",children:u.extensions.length})]}),u.extensions.length===0?s.jsx("p",{className:"set-empty",children:i(b?"dshExtensionsNote":"noExtensions")}):s.jsx("div",{className:"set-list",children:u.extensions.map(d=>{const W=d.id.startsWith("npm:")?d.id.slice(4):null;return s.jsx(Ze,{title:d.name,subtitle:d.path,enabled:d.enabled,onToggle:()=>Se(d),action:W?Te===d.id?s.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("uninstallConfirmHint"),onClick:()=>Mc(W),children:i("uninstallConfirm")}):s.jsxs("button",{type:"button",className:"set-uninstall",title:i("uninstallHint"),onClick:()=>Ie(d.id),children:[s.jsx(ut,{}),i("uninstallExt")]}):void 0},d.id)})})]}),m==="plugins"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(ji,{className:"set-section-icon"}),i("uiLayoutTitle"),s.jsx("button",{type:"button",className:"set-uninstall",onClick:qc,children:i("uiLayoutRestoreAll")})]}),s.jsx("div",{className:"set-note",children:i("uiLayoutHint")}),Hc.map(({slot:d,labelKey:W})=>{const fe=Zs[d]??[];return s.jsxs("div",{className:"set-ui-slot",children:[s.jsx("div",{className:"set-ui-slot-title",children:i(W)}),fe.length===0?s.jsx("div",{className:"set-empty",children:i("uiLayoutEmpty")}):fe.map((qe,at)=>s.jsxs("div",{className:"set-row",children:[s.jsxs("label",{className:"set-toggle",title:qe.id,children:[s.jsx("input",{type:"checkbox",checked:!qe.hidden,onChange:()=>Uc(qe)}),s.jsxs("span",{children:[qe.icon?`${qe.icon} `:"",qe.label]})]}),s.jsxs("div",{className:"set-row-actions",children:[qe.arrangedBy.length>0&&s.jsx("span",{className:"set-ui-source",title:qe.arrangedBy.join(", "),children:i("uiLayoutArranged")}),qe.userOverrides.length>0&&s.jsx("button",{type:"button",className:"set-uninstall",onClick:()=>$c(qe.id),children:i("uiLayoutRestore")}),s.jsx("button",{type:"button",className:"set-uninstall",disabled:at===0,onClick:()=>Ti(fe,qe.id,-1),children:"↑"}),s.jsx("button",{type:"button",className:"set-uninstall",disabled:at===fe.length-1,onClick:()=>Ti(fe,qe.id,1),children:"↓"})]})]},qe.id))]},d)})]}),m==="plugins"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Bt,{className:"set-section-icon"}),i("pluginGrantsTitle"),s.jsx("span",{className:"set-count",children:e.pluginGrants.reduce((d,W)=>d+W.paths.length,0)})]}),s.jsx("div",{className:"set-note",children:i("pluginGrantsHint")}),e.pluginGrants.length===0?s.jsx("p",{className:"set-empty",children:i("pluginGrantsEmpty")}):s.jsx("div",{className:"set-list",children:e.pluginGrants.map(d=>s.jsxs("div",{className:"set-grant-row",children:[s.jsx("div",{className:"set-catalog-title",children:s.jsx("span",{children:d.pluginId})}),d.paths.map(W=>s.jsxs("div",{className:"set-grant-path",children:[s.jsx("span",{className:"set-catalog-source",children:W}),s.jsx("button",{type:"button",className:"set-uninstall",onClick:()=>ie({type:"plugin_path_revoke",pluginId:d.pluginId,path:W}),children:i("pluginGrantsRevoke")})]},W))]},d.pluginId))})]}),m==="plugins"&&h&&s.jsx("div",{className:"set-section",children:s.jsx("div",{className:"set-note",children:i("updatesManaged")})}),m==="plugins"&&!h&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(da,{className:"set-section-icon"}),i("pluginMarket"),s.jsx("span",{className:"set-count",children:e.pluginCatalog.length}),s.jsxs("label",{className:"set-catalog-build",title:i("pluginBuildHint"),children:[s.jsx("input",{type:"checkbox",checked:At,onChange:d=>$t(d.target.checked)}),i("pluginBuildSource")]}),s.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginCatalogAddHint"),onClick:()=>bt(d=>!d),children:[s.jsx(kt,{}),i("pluginCatalogAdd")]})]}),gt&&s.jsxs("div",{className:"set-catalog-add",children:[s.jsx("input",{className:"set-input",placeholder:i("pluginCatalogSource"),value:L,onChange:d=>De(d.target.value)}),s.jsx("input",{className:"set-input",placeholder:i("pluginCatalogId"),value:Ge,onChange:d=>C(d.target.value)}),s.jsx("input",{className:"set-input",placeholder:i("pluginCatalogName"),value:S,onChange:d=>he(d.target.value)}),s.jsx("input",{className:"set-input",placeholder:i("pluginCatalogIcon"),value:we,onChange:d=>Je(d.target.value)}),s.jsx("textarea",{className:"set-input",rows:2,placeholder:i("pluginCatalogDesc"),value:Ce,onChange:d=>$e(d.target.value)}),s.jsxs("div",{className:"set-catalog-add-actions",children:[s.jsx("button",{type:"button",className:"set-uninstall confirm",disabled:!L.trim(),onClick:Yc,children:i("pluginCatalogAddSubmit")}),s.jsx("button",{type:"button",className:"set-uninstall",onClick:()=>bt(!1),children:i("cancel")})]})]}),e.pluginCatalog.length===0?s.jsx("p",{className:"set-empty",children:i("noPluginCatalog")}):s.jsx("div",{className:"set-list",children:e.pluginCatalog.map(d=>{const W=O.has(d.id);return s.jsxs("div",{className:"set-catalog-row",children:[s.jsxs("div",{className:"set-catalog-main",children:[s.jsxs("div",{className:"set-catalog-title",children:[s.jsxs("span",{children:[d.icon?`${d.icon} `:"",d.name]}),W&&s.jsx("span",{className:"set-catalog-installed",children:i("pluginInstalled")}),!d.builtin&&s.jsx("span",{className:"set-catalog-custom",children:i("pluginCatalogCustom")})]}),d.description&&s.jsx("div",{className:"set-catalog-desc",children:d.description}),s.jsx("div",{className:"set-catalog-source",children:d.source}),Fc(d.id)]}),s.jsxs("div",{className:"set-row-actions",children:[W?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUpdateHint"),onClick:()=>yi(d.id,d.source),children:[s.jsx(Rt,{}),i("pluginUpdate")]}),Fe===d.id?s.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("pluginUninstallHint"),onClick:()=>xi(d.id),children:i("uninstallConfirm")}):s.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUninstallHint"),onClick:()=>Re(d.id),children:[s.jsx(ut,{}),i("uninstallExt")]})]}):s.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginInstallHint"),onClick:()=>Wc(d),children:[s.jsx(ss,{}),i("pluginInstall")]}),!d.builtin&&s.jsx("button",{type:"button",className:"set-uninstall",title:i("pluginCatalogRemoveHint"),onClick:()=>Kc(d.id),children:s.jsx(tt,{})})]})]},d.id)})})]}),m==="plugins"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(an,{className:"set-section-icon"}),i("settingsUiPlugins"),s.jsx("span",{className:"set-count",children:e.plugins.length})]}),e.plugins.length===0?s.jsx("p",{className:"set-empty",children:i("noUiPlugins")}):s.jsx("div",{className:"set-list",children:e.plugins.map(d=>s.jsxs(s.Fragment,{children:[s.jsx(Ze,{title:`${d.icon?`${d.icon} `:""}${d.name}`,subtitle:(d.error?`${d.id} · ${d.error}`:d.source?`${d.id} · ${d.source}`:`${d.id} · ${i("uiPluginNoSource")}`)+(d.permissions?.length?` · ${i("uiPluginPerms")}: ${d.permissions.join(", ")}`:""),enabled:!ls.has(d.id)&&!d.error,onToggle:()=>!d.error&&me(d),action:s.jsxs("div",{className:"set-row-actions",children:[d.source&&s.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUpdateHint"),onClick:()=>yi(d.id,d.source),children:[s.jsx(Rt,{}),i("pluginUpdate")]}),Fe===d.id?s.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("pluginUninstallHint"),onClick:()=>xi(d.id),children:i("uninstallConfirm")}):s.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUninstallHint"),onClick:()=>Re(d.id),children:[s.jsx(ut,{}),i("uninstallExt")]})]})},d.id),d.settingsSchema&&d.settingsSchema.length>0&&s.jsx(kb,{plugin:d})]}))})]}),m==="plugins"&&b&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(an,{className:"set-section-icon"}),i("dshPatches"),s.jsx(nt,{text:i("dshPatchesDesc")}),s.jsx("span",{className:"set-count",children:e.dshPatches?.files.length??0}),s.jsxs("button",{type:"button",className:"set-uninstall",title:i("dshPatchesRescanHint"),onClick:()=>ie({type:"dsh_patches_rescan"}),children:[s.jsx(Rt,{}),i("dshPatchesRescan")]})]}),(e.dshPatches?.files.length??0)===0?s.jsx("p",{className:"set-empty",children:i("dshPatchesEmpty")}):s.jsx("div",{className:"set-list",children:e.dshPatches.files.map(d=>s.jsx("div",{className:"set-row",children:s.jsxs("div",{className:"set-row-info",children:[s.jsx("div",{className:"set-row-name",children:d.name}),s.jsxs("div",{className:"set-row-desc",children:[Ub(d.size)," · ",new Date(d.mtimeMs).toLocaleString()]})]})},d.name))}),s.jsxs("p",{className:"set-hint",children:[i("dshPatchesPath")," ",e.dshPatches?.patchDir??""]})]}),m==="review"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(hs,{className:"set-section-icon"}),i("settingsReview"),s.jsx(nt,{text:i("settingsReviewDesc")}),s.jsx("span",{className:"set-count",children:u.reviewSkills.length})]}),s.jsx(Ze,{title:i("goalModeEnabled"),tip:`${i("goalModeEnabledDesc")}
359
- ${i("goalModeOffHint")}`,enabled:u.goalModeEnabled,onToggle:()=>He({goalModeEnabled:!u.goalModeEnabled})}),s.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:i("reviewPromptPlaceholder"),value:T,onFocus:()=>G.current=!0,onBlur:()=>{G.current=!1,He({reviewPrompt:T})},onChange:d=>U(d.target.value)}),s.jsxs("div",{className:"set-field-label",children:[i("settingsReviewSkills"),b&&s.jsxs(s.Fragment,{children:[" ",s.jsx(nt,{text:i("dshReviewPromptNote")})]})]}),u.reviewSkills.length===0?s.jsx("p",{className:"set-empty",children:i("noSkills")}):s.jsx("div",{className:"set-list",children:u.reviewSkills.map(d=>s.jsx(Ze,{title:d.name,subtitle:d.description,enabled:d.enabled,onToggle:()=>Gc(d)},`review-${d.name}`))})]}),m==="vision"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(_n,{className:"set-section-icon"}),i("settingsVisionBridge")]}),s.jsx(Ze,{title:i("visionBridgeEnabled"),tip:`${i("settingsVisionBridgeDesc")}
360
- ${i("visionBridgeOffHint")}`,enabled:u.visionBridgeEnabled,onToggle:()=>He({visionBridgeEnabled:!u.visionBridgeEnabled})}),u.visionBridgeEnabled&&s.jsxs("div",{className:"set-mode-row",children:[s.jsx("label",{className:"set-field-label",children:i("visionBridgeModel")}),s.jsxs("select",{className:"set-select",value:u.visionBridgeModel??"",onChange:d=>He({visionBridgeModel:d.target.value||null}),children:[s.jsx("option",{value:"",children:i("visionBridgeAuto")}),u.visionModels.map(d=>s.jsx("option",{value:`${d.provider}/${d.id}`,children:d.label},`${d.provider}/${d.id}`))]})]}),u.visionBridgeEnabled&&s.jsxs("div",{className:"set-mode-row",children:[s.jsx("label",{className:"set-field-label",children:i("visionBridgePromptMode")}),s.jsxs("select",{className:"set-select",value:J,onChange:d=>{const W=d.target.value;j(W),He({visionBridgePromptMode:W})},children:[s.jsx("option",{value:"append",children:i("promptModeAppend")}),s.jsx("option",{value:"replace",children:i("promptModeReplace")})]})]}),u.visionBridgeEnabled&&s.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:i("visionBridgePromptPlaceholder"),value:q,onFocus:()=>F.current=!0,onBlur:()=>{F.current=!1;const d=J==="replace"&&u.visionBridgeDefaultPrompt&&q===u.visionBridgeDefaultPrompt?"":q;He({visionBridgePromptMode:J,visionBridgePrompt:d})},onChange:d=>Y(d.target.value)}),u.visionBridgeEnabled&&(u.visionModels.length===0?s.jsx("p",{className:"set-hint",children:i("visionBridgeNoModels")}):s.jsx("p",{className:"set-hint",children:i("visionBridgeCurrent",{model:u.visionBridgeModel??i("visionBridgeAuto")})}))]}),m==="presets"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Cn,{className:"set-section-icon"}),i("settingsPresets"),s.jsx("span",{className:"set-count",children:u.presets.length})]}),s.jsxs("div",{className:"set-preset-save",children:[s.jsx("input",{className:"set-input",placeholder:i("presetNamePlaceholder"),value:D,onChange:d=>se(d.target.value),onKeyDown:d=>{d.key==="Enter"&&D.trim()&&(ie({type:"save_preset",name:D.trim()}),se(""))}}),s.jsxs("button",{type:"button",className:"set-save-btn",disabled:!D.trim(),onClick:()=>{ie({type:"save_preset",name:D.trim()}),se("")},children:[s.jsx(kt,{})," ",i("saveAsPreset")]})]}),u.presets.length===0?s.jsx("p",{className:"set-empty",children:i("noPresets")}):s.jsx("div",{className:"set-list",children:u.presets.map(d=>s.jsxs("div",{className:"set-row",children:[s.jsxs("div",{className:"set-row-info",children:[s.jsx("div",{className:"set-row-name",children:d.name}),s.jsxs("div",{className:"set-row-desc",children:[d.promptMode==="replace"?i("promptModeReplace"):i("promptModeAppend"),d.disabledSkills.length>0&&` · ${i("settingsSkills")} ${d.disabledSkills.length}`,d.disabledExtensions.length>0&&` · ${i("settingsExtensions")} ${d.disabledExtensions.length}`]})]}),s.jsxs("div",{className:"set-row-actions",children:[s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>ie({type:"apply_preset",name:d.name}),children:i("applyPreset")}),s.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("deletePreset"),onClick:()=>ie({type:"delete_preset",name:d.name}),children:s.jsx(ut,{})})]})]},d.name))})]}),m==="subagent-templates"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(_i,{className:"set-section-icon"}),i("settingsSubagentTemplates"),s.jsx(nt,{text:i("settingsSubagentTemplatesDesc")}),s.jsx("span",{className:"set-count",children:u.subagentTemplates.length}),s.jsxs("button",{type:"button",className:"set-save-btn",title:i("subagentTemplateNew"),onClick:()=>Ne({name:"",description:"",promptMode:"replace",systemPrompt:"",enabledSkills:[],enabledExtensions:[],model:"",thinkingLevel:"",enabled:!0}),children:[s.jsx(kt,{})," ",i("subagentTemplateNew")]})]}),s.jsxs("div",{className:"set-mode-row",children:[s.jsxs("label",{className:"set-field-label",children:[i("subagentDefaultModelLabel")," ",s.jsx(nt,{text:i("subagentDefaultModelHint")})]}),s.jsxs("select",{className:"set-select",value:u.subagentDefaultModel??"",onChange:d=>He({subagentDefaultModel:d.target.value||null}),children:[s.jsx("option",{value:"",children:i("subagentFollowMain")}),u.subagentModels.map(d=>s.jsx("option",{value:`${d.provider}/${d.id}`,children:d.label},`${d.provider}/${d.id}`))]})]}),u.subagentModels.length===0&&s.jsx("p",{className:"set-hint",children:i("subagentNoModels")}),ee&&s.jsxs("div",{className:"tpl-editor",children:[s.jsxs("div",{className:"tpl-fields",children:[s.jsx("input",{className:"set-input",placeholder:i("tplNamePlaceholder"),value:ee.name,onChange:d=>Ne({...ee,name:d.target.value})}),s.jsx("input",{className:"set-input",placeholder:i("tplDescriptionPlaceholder"),value:ee.description,onChange:d=>Ne({...ee,description:d.target.value})}),s.jsx("input",{className:"set-input",placeholder:i("tplDescriptionEnPlaceholder"),value:ee.descriptionEn??"",onChange:d=>Ne({...ee,descriptionEn:d.target.value})})]}),s.jsxs("div",{className:"set-mode-row",children:[s.jsx("label",{className:"set-field-label",children:i("tplPromptModeLabel")}),s.jsxs("select",{className:"set-select",value:ee.promptMode,onChange:d=>Ne({...ee,promptMode:d.target.value}),children:[s.jsx("option",{value:"replace",children:i("promptModeReplace")}),s.jsx("option",{value:"append",children:i("promptModeAppend")})]})]}),s.jsxs("div",{className:"set-mode-row",children:[s.jsx("label",{className:"set-field-label",children:i("tplModelLabel")}),s.jsxs("select",{className:"set-select",value:ee.model??"",onChange:d=>Ne({...ee,model:d.target.value}),children:[s.jsx("option",{value:"",children:i("subagentFollowMain")}),u.subagentModels.map(d=>s.jsx("option",{value:`${d.provider}/${d.id}`,children:d.label},`${d.provider}/${d.id}`))]})]}),s.jsxs("div",{className:"set-mode-row",children:[s.jsxs("label",{className:"set-field-label",children:[i("tplThinkingLabel")," ",s.jsx(nt,{text:i("tplThinkingHint")})]}),s.jsxs("select",{className:"set-select",value:ee.thinkingLevel??"",onChange:d=>Ne({...ee,thinkingLevel:d.target.value}),children:[s.jsx("option",{value:"",children:i("tplThinkingFollowMain")}),oc.map(d=>s.jsx("option",{value:d,children:i(`thinking.${d}`)},d))]})]}),s.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:`${i("tplSystemPromptLabel")}${o==="zh"?":":": "}${i("tplSystemPromptPlaceholder")}`,value:ee.systemPrompt,onChange:d=>Ne({...ee,systemPrompt:d.target.value})}),s.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:`${i("tplSystemPromptLabel")}: ${i("tplSystemPromptEnPlaceholder")}`,value:ee.systemPromptEn??"",onChange:d=>Ne({...ee,systemPromptEn:d.target.value})}),s.jsxs("div",{className:"tpl-pick-block",children:[s.jsx("div",{className:"tpl-pick-head",children:s.jsxs("span",{children:[i("tplSkillsLabel")," · ",i("tplWhitelistHint")]})}),u.skills.length===0?s.jsx("p",{className:"set-hint",children:i("noSkills")}):s.jsx("div",{className:"tpl-pick",children:u.skills.map(d=>s.jsxs("label",{className:`tpl-chip${ee.enabledSkills.includes(d.name)?" on":""}`,children:[s.jsx("input",{type:"checkbox",checked:ee.enabledSkills.includes(d.name),onChange:W=>{const fe=W.target.checked;Ne({...ee,enabledSkills:fe?[...ee.enabledSkills,d.name]:ee.enabledSkills.filter(qe=>qe!==d.name)})}}),d.name]},d.name))})]}),s.jsxs("div",{className:"tpl-pick-block",children:[s.jsx("div",{className:"tpl-pick-head",children:s.jsxs("span",{children:[i("tplExtensionsLabel")," · ",i("tplWhitelistHint")]})}),u.extensions.length===0?s.jsx("p",{className:"set-hint",children:i("noExtensions")}):s.jsx("div",{className:"tpl-pick",children:u.extensions.map(d=>s.jsxs("label",{className:`tpl-chip${ee.enabledExtensions.includes(d.id)?" on":""}`,children:[s.jsx("input",{type:"checkbox",checked:ee.enabledExtensions.includes(d.id),onChange:W=>{const fe=W.target.checked;Ne({...ee,enabledExtensions:fe?[...ee.enabledExtensions,d.id]:ee.enabledExtensions.filter(qe=>qe!==d.id)})}}),d.name]},d.id))})]}),s.jsxs("div",{className:"tpl-actions",children:[s.jsx("button",{type:"button",className:"set-save-btn",disabled:!ee.name.trim(),onClick:()=>{ie({type:"save_subagent_template",template:{...ee,name:ee.name.trim()}}),Ne(null)},children:i("tplSave")}),s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>Ne(null),children:i("tplCancel")})]})]}),u.subagentTemplates.length===0?s.jsx("p",{className:"set-empty",children:i("noSubagentTemplates")}):s.jsx("div",{className:"set-list",children:u.subagentTemplates.map(d=>s.jsxs("div",{className:"set-row",children:[s.jsxs("div",{className:"set-row-info",children:[s.jsxs("div",{className:"set-row-name",children:[d.name,u.subagentDefaultTemplates.includes(d.name)&&s.jsx("span",{className:"tpl-badge default",children:i("tplDefaultBadge")}),!d.enabled&&s.jsx("span",{className:"tpl-badge",children:i("subagentTemplateClosed")})]}),s.jsxs("div",{className:"set-row-desc",children:[(o!=="zh"&&d.descriptionEn?d.descriptionEn:d.description)||`${d.promptMode==="replace"?i("promptModeReplace"):i("promptModeAppend")}`,d.model?` · ${i("tplModelLabel")} ${d.model}`:` · ${i("subagentFollowMain")}`,d.thinkingLevel?` · ${i("tplThinkingLabel")} ${l(`thinking.${d.thinkingLevel}`)}`:"",d.enabledSkills.length>0&&` · ${i("tplSkillsLabel")} ${d.enabledSkills.length}`,d.enabledExtensions.length>0&&` · ${i("tplExtensionsLabel")} ${d.enabledExtensions.length}`,!d.description&&d.enabledSkills.length===0&&d.enabledExtensions.length===0&&` · ${i("tplInherit")}`]})]}),s.jsxs("div",{className:"set-row-actions",children:[s.jsx("button",{type:"button",className:`set-switch${d.enabled?" on":""}`,role:"switch","aria-checked":d.enabled,title:`${d.enabled?i("subagentTemplateDisable"):i("subagentTemplateEnable")} · ${i("subagentTemplateOffHint")}`,onClick:()=>ie({type:"save_subagent_template",template:{...d,enabled:!d.enabled}}),children:s.jsx("span",{className:"set-switch-knob"})}),s.jsx("button",{type:"button",className:"dd-refresh",title:i("subagentTemplateEdit"),onClick:()=>Ne({...d}),children:i("subagentTemplateEdit")}),w===d.name?s.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("uninstallConfirmHint"),onClick:()=>{ie({type:"delete_subagent_template",name:d.name}),de(null)},children:i("uninstallConfirm")}):s.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("tplDelete"),onClick:()=>de(d.name),children:s.jsx(ut,{})})]})]},d.name))})]}),en&&s.jsx(nl,{plugin:en.plugin,epoch:e.pluginsEpoch,send:ie,className:"set-plugin-page"})]})]}),s.jsx("div",{className:"modal-actions",children:s.jsx("button",{type:"button",className:"dd-refresh",onClick:a,children:i("close")})})]})})}function qb(e,t){const n=Math.max(0,Date.now()-e),a=Math.floor(n/6e4);if(a<1)return t("bgTaskJustNow");if(a<60)return t("bgTaskMinutes",{n:a});const i=Math.floor(a/60);return i<24?t("bgTaskHours",{n:i}):t("bgTaskDays",{n:Math.floor(i/24)})}function Wb({servers:e,onClose:t}){const n=Me(),[a,i]=c.useState(new Set),o=l=>i(u=>{const p=new Set(u);return p.has(l)?p.delete(l):p.add(l),p});return c.useEffect(()=>{ie({type:"list_bg_servers"})},[]),s.jsx("div",{className:"modal-backdrop",onClick:t,children:s.jsxs("div",{className:"bg-task-modal",onClick:l=>l.stopPropagation(),children:[s.jsxs("div",{className:"bg-task-head",children:[s.jsxs("span",{className:"bg-task-title",children:[s.jsx(Sn,{})," ",n("bgTasks"),e.length>0&&s.jsx("em",{className:"bg-task-count",children:e.length})]}),s.jsx("button",{type:"button",className:"btn",title:n("close"),onClick:t,children:s.jsx(tt,{})})]}),e.length===0?s.jsxs("div",{className:"bg-task-empty",children:[s.jsx(Sn,{}),s.jsx("span",{children:n("bgTasksEmpty")}),s.jsx("small",{children:n("bgTasksDesc")})]}):s.jsx("ul",{className:"bg-task-list",children:e.map(l=>{const u=!!l.taskId,p=l.taskId??String(l.port);return s.jsxs("li",{className:"bg-task-item",children:[s.jsx("span",{className:"bg-task-icon",title:u?l.plugin:n("bgTaskPort")}),s.jsxs("div",{className:"bg-task-info",children:[s.jsxs("div",{className:"bg-task-line1",children:[u?s.jsxs("span",{className:"bg-task-port",title:l.taskId,children:["🧩 ",l.plugin]}):s.jsxs("span",{className:"bg-task-port",children:[":",l.port]}),l.name&&s.jsx("span",{className:"bg-task-name",children:l.name})]}),s.jsxs("div",{className:"bg-task-line2",children:[!u&&s.jsxs("span",{children:[n("bgTaskPid")," ",l.pid]}),s.jsxs("span",{children:[n("bgTaskSince")," ",qb(l.since,n)]}),u&&l.status&&s.jsx("span",{className:"bg-task-status",children:l.status})]}),l.command&&s.jsxs("button",{type:"button",className:`bg-task-cmd ${a.has(p)?"open":""}`,title:`${n("bgTaskCommand")}: ${l.command}`,onClick:()=>o(p),children:[s.jsx(Vn,{}),s.jsx("code",{children:l.command})]})]}),s.jsxs("button",{type:"button",className:"btn bg-task-stop",title:n("bgTaskStop"),onClick:()=>ie(u?{type:"kill_background_server",taskId:l.taskId}:{type:"kill_background_server",port:l.port}),children:[s.jsx(vn,{}),s.jsx("span",{children:n("bgTaskStop")})]})]},p)})}),s.jsxs("div",{className:"bg-task-foot",children:[s.jsxs("button",{type:"button",className:"btn",title:n("bgTaskRefresh"),onClick:()=>ie({type:"list_bg_servers"}),children:[s.jsx(Rt,{}),s.jsx("span",{children:n("bgTaskRefresh")})]}),s.jsxs("button",{type:"button",className:"btn bg-task-stopall",disabled:e.length===0,title:n("bgTaskStopAll"),onClick:()=>ie({type:"kill_background_servers"}),children:[s.jsx(vn,{}),s.jsx("span",{children:n("bgTaskStopAll")})]})]})]})})}function Kb(e,t){return e.toLowerCase().includes(t)}function Yb({open:e,projects:t,fileSearch:n,sessionSearch:a,onClose:i,onSwitchSession:o,onSwitchProject:l,onPreviewFile:u}){const p=Me(),h=wt("cwd"),b=c.useRef(null),[m,f]=c.useState(""),x=c.useDeferredValue(m),[v,N]=c.useState(0),B=c.useRef(1),X=c.useRef(0),K=c.useRef(null);c.useEffect(()=>{if(!e)return;ie({type:"list_sessions"}),ie({type:"list_projects"});const U=m.trim();if(U){const G=++B.current;X.current=G,R(!0),ie({type:"search_files",reqId:G,query:U}),ie({type:"search_sessions",reqId:G,query:U})}requestAnimationFrame(()=>b.current?.select())},[e]);const[A,R]=c.useState(!1);c.useEffect(()=>{K.current&&clearTimeout(K.current);const U=x.trim();if(!U){R(!1);return}return K.current=setTimeout(()=>{const G=++B.current;X.current=G,R(!0),ie({type:"search_files",reqId:G,query:U}),ie({type:"search_sessions",reqId:G,query:U})},300),()=>{K.current&&clearTimeout(K.current)}},[x]);const I=x.trim().toLowerCase(),$=c.useMemo(()=>!I||!a||a.reqId!==X.current||!a.ok?[]:a.results,[a,I]),ce=c.useMemo(()=>I?t.filter(U=>Kb(U.path,I)).slice(0,10):[],[t,I]),ge=c.useMemo(()=>!I||!n||n.reqId!==X.current||!n.ok?[]:n.results,[n,I]);c.useEffect(()=>{n&&n.reqId===X.current&&a&&a.reqId===X.current&&X.current!==0&&R(!1)},[n,a]);const q=!!n&&n.ok&&n.truncated,Y=c.useMemo(()=>[...$.map(U=>({kind:"session",path:U.path,anchors:U.anchors})),...ce.map(U=>({kind:"project",path:U.path})),...ge.filter(U=>U.type==="file").map(U=>({kind:"file",path:U.path,name:U.name}))],[$,ce,ge]);c.useEffect(()=>{N(0)},[x]);const J=c.useCallback(U=>{if(U)if(U.kind==="session")o(U.path,U.anchors),i();else if(U.kind==="project"){l(U.path),ie({type:"list_sessions"}),ie({type:"list_projects"});const G=x.trim();if(G){const D=++B.current;X.current=D,R(!0),ie({type:"search_files",reqId:D,query:G}),ie({type:"search_sessions",reqId:D,query:G})}}else u(U.path,U.name)},[o,l,u,x]);c.useEffect(()=>{if(!e)return;const U=G=>{G.key==="Escape"?(G.preventDefault(),G.stopPropagation(),i()):G.key==="ArrowDown"?(G.preventDefault(),N(D=>Math.min(D+1,Y.length-1))):G.key==="ArrowUp"?(G.preventDefault(),N(D=>Math.max(D-1,0))):G.key==="Enter"&&(G.preventDefault(),J(Y[v]))};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[Y,v,J,i,e]);const j=$.length+ce.length+ge.length,F=(U,G,D)=>s.jsxs("div",{className:"gs-section-head",children:[D,s.jsx("span",{children:U}),s.jsx("em",{children:G})]});let T=-1;return e?s.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:i,children:s.jsxs("div",{className:"gs-modal",onClick:U=>U.stopPropagation(),children:[s.jsxs("div",{className:"gs-input-row",children:[s.jsx(wn,{}),s.jsx("input",{ref:b,type:"text",value:m,placeholder:p("gsPlaceholder"),onChange:U=>f(U.target.value)}),s.jsx("button",{type:"button",className:"gs-close",title:p("close"),onClick:i,children:s.jsx(tt,{})})]}),s.jsxs("div",{className:"gs-results",children:[!I&&s.jsx("div",{className:"gs-empty",children:p("gsHint")}),I&&j===0&&!q&&s.jsx("div",{className:"gs-empty",children:p(A?"gsSearching":"gsNoResults")}),$.length>0&&s.jsxs("div",{className:"gs-section",children:[F(p("gsSessions"),$.length,s.jsx(ts,{})),$.map(U=>{T++;const G=T;return s.jsxs("button",{type:"button",className:G===v?"gs-item active":"gs-item",onMouseEnter:()=>N(G),onClick:()=>J({kind:"session",path:U.path,anchors:U.anchors}),children:[s.jsxs("span",{className:"gs-item-title",children:[U.name||U.path.split(/[\\/]/).pop(),s.jsx("em",{className:"gs-item-meta",children:U.messageCount})]}),s.jsx("span",{className:"gs-item-sub",children:U.firstMessage})]},U.path)})]}),ce.length>0&&s.jsxs("div",{className:"gs-section",children:[F(p("gsProjects"),ce.length,s.jsx(Bt,{})),ce.map(U=>{T++;const G=T,D=h&&U.path===h;return s.jsxs("button",{type:"button",className:G===v?"gs-item active":"gs-item",onMouseEnter:()=>N(G),onClick:()=>J({kind:"project",path:U.path}),children:[s.jsxs("span",{className:"gs-item-title",children:[U.path.split(/[\\/]/).pop(),D&&s.jsx("em",{className:"gs-item-meta",children:p("gsCurrentProject")})]}),s.jsx("span",{className:"gs-item-sub",children:U.path})]},U.path)})]}),(ge.length>0||I&&q)&&s.jsxs("div",{className:"gs-section",children:[F(p("gsFiles"),ge.length,s.jsx(vo,{})),ge.map(U=>{T++;const G=T;return s.jsxs("button",{type:"button",className:G===v?"gs-item active":"gs-item",disabled:U.type==="dir",title:U.type==="dir"?void 0:p("gsOpenPreview"),onMouseEnter:()=>N(G),onClick:()=>{U.type==="file"&&J({kind:"file",path:U.path,name:U.name})},children:[s.jsx("span",{className:"gs-item-title",children:U.name}),s.jsx("span",{className:"gs-item-sub",children:U.path})]},`${U.type}:${U.path}`)}),q&&s.jsx("div",{className:"gs-truncated",children:p("gsTruncated")})]})]}),s.jsxs("div",{className:"gs-foot",children:[s.jsxs("span",{children:["↑↓ ",p("gsNavigate")]}),s.jsxs("span",{children:["Enter ",p("gsOpen")]}),s.jsxs("span",{children:["Esc ",p("gsCloseHint")]})]})]})}):null}const wa=5e3;function Gb({file:e,content:t,onAddLines:n,onAttach:a,onClose:i}){const o=Me(),[l,u]=c.useState(null),[p,h]=c.useState(!1),[b,m]=c.useState(null),[f,x]=c.useState(!1),[v,N]=c.useState(!1),[B,X]=c.useState(!1),[K,A]=c.useState(""),[R,I]=c.useState(!0),[$,ce]=c.useState(!0),[ge,q]=c.useState(!1),Y=c.useRef(!1),[J,j]=c.useState(!0),[F,T]=c.useState(!1),[U,G]=c.useState(100),D=c.useRef(0),se=c.useRef(!1),ee=c.useRef(null);c.useEffect(()=>{h(!0),u(null),m(null),X(!1),A(""),I(!0),ce(!0),q(!1),Y.current=!1,ie({type:"read_file",path:e.path})},[e.path]),c.useEffect(()=>{t&&t.path===e.path&&(u(t),B||A(t.text),h(!1))},[t,B,e.path]),c.useEffect(()=>{const Z=y=>{if(y.key==="Escape"){Ye();return}if((y.ctrlKey||y.metaKey)&&y.key.toLowerCase()==="s"&&B){y.preventDefault(),ve();return}const P=y.target,le=P&&(P.tagName==="INPUT"||P.tagName==="TEXTAREA"||P.isContentEditable);(y.ctrlKey||y.metaKey)&&y.key.toLowerCase()==="a"&&!le&&(y.preventDefault(),pe())};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[i,l,B,K]),c.useEffect(()=>{const Z=()=>{se.current=!1,x(!1)};return window.addEventListener("mouseup",Z),()=>window.removeEventListener("mouseup",Z)},[]);const Ne=c.useMemo(()=>{if(!l)return[];const Z=l.text.split(`
361
- `);return Z.length>0&&Z[Z.length-1]===""&&Z.pop(),Z.slice(0,wa)},[l]),w=l?.lines??0,de=w>wa,ue=(Z,y)=>{if(y){const P=D.current>0?D.current:Z;m({start:Math.min(P,Z),end:Math.max(P,Z)})}else D.current=Z,m({start:Z,end:Z})},pe=()=>{Ne.length!==0&&(D.current=1,m({start:1,end:Ne.length}))},ke=()=>{b&&(n(e.path,e.name,b.start,b.end),N(!0),ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>N(!1),1400))},Be=l!==null&&l.kind==="text"&&!l.binary&&!l.truncated,ye=()=>{A(l?.text??""),X(!1),Y.current&&(As(e.name)&&I(!0),Is(e.name)&&ce(!0))},Ae=()=>{if(B){if(K!==(l?.text??"")&&!window.confirm(o("discardFileChanges")))return;ye();return}!Be||!l||(Y.current=As(e.name)&&R||Is(e.name)&&$,As(e.name)&&I(!1),Is(e.name)&&ce(!1),m(null),A(l.text),X(!0))},ve=()=>{!B||!l||!Be||ie({type:"write_file",path:e.path,text:K})&&(X(!1),Y.current&&(As(e.name)&&I(!0),Is(e.name)&&ce(!0)),m(null))},Ye=()=>{B&&K!==(l?.text??"")&&!window.confirm(o("discardFileChanges"))||i()},Pe=Z=>{G(Math.min(200,Math.max(50,Z)))},ae=b?b.end-b.start+1:0,be=l?.binary??!1,Oe=l?.truncated??!1,Le=l?.kind??"text",We=As(e.name),_=Is(e.name),Q=We&&R&&!B&&Le==="text"&&!be,V=_&&$&&!B&&Le==="text"&&!be,Ee=Z=>Ft(lt(`/api/file?clientId=${encodeURIComponent(On())}&path=${encodeURIComponent(Z)}`)),oe=Z=>{const y=Z.split("/").map(Te=>encodeURIComponent(Te)).join("/"),le=/^[A-Za-z]:([\\/]|$)/.test(Z)||Z.startsWith("/")?`/api/preview/__abs__/${y}`:`/api/preview/${y}`;return Ft(lt(`${le}?clientId=${encodeURIComponent(On())}${ge?"&allowJs=1":""}`))};return s.jsx("div",{className:`fp-overlay ${F?"fullscreen":""}`,onMouseDown:Z=>{Z.target===Z.currentTarget&&Ye()},children:s.jsxs("div",{className:`fp ${F?"fullscreen":""}`,style:{"--fp-zoom":U/100},children:[s.jsxs("div",{className:"fp-head",children:[s.jsx("span",{className:"fp-name",title:e.path,children:e.name}),s.jsx("span",{className:"fp-path",children:e.path}),s.jsxs("span",{className:"fp-meta",children:[l&&Le==="text"&&!be&&o("fileLines",{n:w}),l&&` · ${zb(l.size)}`]}),s.jsxs("span",{className:"fp-head-actions",children:[We&&Le==="text"&&!be&&l&&s.jsx("button",{type:"button",className:`fp-attach markdown ${R?"on":""}`,"data-tip":o(R?"showMarkdownSource":"showMarkdownPreview"),disabled:B,onClick:()=>I(Z=>!Z),children:R?s.jsx(_n,{}):s.jsx(Di,{})}),_&&Le==="text"&&!be&&l&&s.jsx("button",{type:"button",className:`fp-attach html ${$?"on":""}`,"data-tip":o($?"showHtmlSource":"showHtmlPreview"),disabled:B,onClick:()=>ce(Z=>!Z),children:$?s.jsx(Di,{}):s.jsx(_n,{})}),Le==="text"&&!be&&l&&s.jsx("button",{type:"button",className:`fp-attach edit ${B?"on":""}`,"data-tip":o(Oe?"fileEditTruncated":B?"exitEditFile":"editFile"),disabled:!Be&&!B,onClick:Ae,children:s.jsx(Ys,{})}),Le==="text"&&!be&&!Q&&!V&&s.jsx("button",{type:"button",className:`fp-attach wrap ${J?"on":""}`,"data-tip":o(J?"disableWrap":"enableWrap"),onClick:()=>j(Z=>!Z),children:s.jsx(Uu,{})}),Le==="text"&&l&&s.jsxs("span",{className:"fp-zoom",children:[s.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":o("zoomOut"),disabled:U<=50,onClick:()=>Pe(U-10),children:s.jsx(yu,{})}),s.jsxs("button",{type:"button",className:"fp-zoom-val",title:o("resetZoom"),onClick:()=>G(100),children:[U,"%"]}),s.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":o("zoomIn"),disabled:U>=200,onClick:()=>Pe(U+10),children:s.jsx(ku,{})})]}),Le!=="video"&&Le!=="none"&&s.jsx("button",{type:"button",className:"fp-attach inline","data-tip":o("attachInlineTip"),onClick:()=>a(e.path,e.name,"inline"),children:s.jsx(kt,{})}),s.jsx("button",{type:"button",className:"fp-attach ref","data-tip":o("referenceTip"),onClick:()=>a(e.path,e.name,"reference"),children:s.jsx(Ia,{})}),s.jsx("button",{type:"button",className:`fp-attach full ${F?"on":""}`,"data-tip":o(F?"exitFullscreen":"fullscreen"),onClick:()=>T(Z=>!Z),children:F?s.jsx(Iu,{}):s.jsx(Ru,{})}),s.jsx("button",{type:"button",className:"fp-close",title:o("close"),onClick:Ye,children:s.jsx(tt,{})})]})]}),Oe&&Le==="text"&&!be&&s.jsx("div",{className:"fp-notice",children:o("previewTruncated")}),p&&!l&&s.jsx("div",{className:"fp-empty",children:o("loading")}),!p&&Le==="none"&&!be&&s.jsx("div",{className:"fp-empty",children:o("previewNotSupported")}),!p&&Le==="image"&&s.jsx("div",{className:"fp-media-wrap",children:s.jsx("img",{className:"fp-media",src:Ee(e.path),alt:e.name})}),!p&&Le==="video"&&s.jsx("div",{className:"fp-media-wrap",children:s.jsx("video",{className:"fp-media",src:Ee(e.path),controls:!0,preload:"metadata"})}),!p&&V&&l&&s.jsxs("div",{className:"fp-html",children:[s.jsxs("div",{className:"fp-html-bar",children:[s.jsx("span",{className:"fp-html-hint",title:o(ge?"htmlJsOnTip":"htmlJsOffTip"),children:o(ge?"htmlJsOn":"htmlJsOff")}),s.jsx("button",{type:"button",className:`fp-html-js ${ge?"on":""}`,"data-tip":o(ge?"htmlDisableJs":"htmlEnableJs"),onClick:()=>q(Z=>!Z),children:o(ge?"htmlDisableJs":"htmlEnableJs")})]}),s.jsx("iframe",{className:"fp-html-frame",src:oe(e.path),title:e.name,sandbox:ge?"allow-scripts":"",referrerPolicy:"no-referrer"},ge?"js":"nojs")]}),!p&&Q&&l&&s.jsx("div",{className:"fp-markdown msg-text",children:s.jsx("div",{className:"fp-markdown-zoom",children:s.jsx(dt,{text:l.text})})}),!p&&be&&Le!=="image"&&Le!=="video"&&l&&s.jsxs("div",{className:"fp-hex-wrap",children:[s.jsxs("div",{className:"fp-notice",children:[o("binaryFile"),l.truncated&&o("binaryHexTruncated")]}),s.jsx("pre",{className:"fp-hex",children:l.text})]}),!p&&B&&Le==="text"&&!be&&l&&s.jsx("textarea",{className:`fp-editor ${J?"":"no-wrap"}`,value:K,onChange:Z=>A(Z.target.value),wrap:J?"soft":"off",spellCheck:!1,autoFocus:!0}),!p&&!Q&&!V&&!B&&Le==="text"&&!be&&l&&Ne.length===0&&s.jsx("div",{className:"fp-empty",children:o("emptyFile")}),!p&&!Q&&!V&&!B&&Le==="text"&&!be&&Ne.length>0&&s.jsxs("div",{className:`fp-code ${f?"dragging":""} ${J?"":"no-wrap"}`,onMouseDown:Z=>{Z.button===0&&Z.preventDefault()},children:[Ne.map((Z,y)=>{const P=y+1,le=b!==null&&P>=b.start&&P<=b.end;return s.jsxs("div",{className:`fp-line ${le?"sel":""}`,onMouseDown:Te=>{Te.button===0&&(ue(P,Te.shiftKey),se.current=!0,x(!0))},onMouseEnter:()=>{se.current&&ue(P,!0)},children:[s.jsx("span",{className:"fp-num",children:P}),s.jsx("span",{className:"fp-code-text",children:Z})]},P)}),de&&s.jsx("div",{className:"fp-lines-note",children:o("previewLinesTruncated",{n:wa})})]}),s.jsx("div",{className:"fp-foot",children:B?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"fp-hint",children:o("editFile")}),s.jsxs("div",{className:"fp-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:Ae,children:o("cancel")}),s.jsxs("button",{type:"button",className:"btn primary",disabled:K===(l?.text??""),onClick:ve,children:[s.jsx(wu,{})," ",o("saveFile")]})]})]}):!Q&&!V&&Le==="text"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"fp-hint",children:b?o("selectedRange",{n:ae,start:b.start,end:b.end}):o("selectLinesHint")}),s.jsxs("div",{className:"fp-actions",children:[s.jsx("button",{type:"button",className:"btn",disabled:Ne.length===0,onClick:pe,children:o("selectAll")}),s.jsx("button",{type:"button",className:"btn",disabled:!b,onClick:()=>m(null),children:o("clearSelection")}),s.jsxs("button",{type:"button",className:"btn primary",disabled:!b||be,onClick:ke,children:[v?s.jsx(Lt,{}):null,o(v?"addedToChat":"addToChat")]})]})]})})]})})}function As(e){const t=e.toLowerCase();return t.endsWith(".md")||t.endsWith(".markdown")}function Is(e){const t=e.toLowerCase();return t.endsWith(".html")||t.endsWith(".htm")||t.endsWith(".xhtml")}function zb(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}const _c="pi-web-sounds",js={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function Ac(){try{const e=localStorage.getItem(_c);if(!e)return{...js};const t=JSON.parse(e),n={...js,...t};for(const a of["enabled","question","done","start","error"])typeof n[a]!="boolean"&&(n[a]=js[a]);return typeof n.volume!="number"||!Number.isFinite(n.volume)?n.volume=js.volume:n.volume=Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...js}}}function Vb(e){try{localStorage.setItem(_c,JSON.stringify(e))}catch{}}let Rs=null;function Qb(){try{if(!Rs){const e=window.AudioContext??window.webkitAudioContext;if(!e)return null;Rs=new e}return Rs.state==="suspended"&&Rs.resume(),Rs}catch{return null}}const Xb=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],Jb=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],Zb=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],e1=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],t1={question:Xb,done:Jb,start:Zb,error:e1};function s1(e,t,n){const a=e.createOscillator(),i=e.createGain();a.type=t.type,a.frequency.value=t.freq;const o=e.currentTime+t.start,l=Math.max(1e-4,t.peak*n);i.gain.setValueAtTime(1e-4,o),i.gain.exponentialRampToValueAtTime(l,o+.012),i.gain.exponentialRampToValueAtTime(1e-4,o+t.dur),a.connect(i),i.connect(e.destination),a.start(o),a.stop(o+t.dur+.05)}function ps(e,t=Ac()){if(!t.enabled||!t[e])return;const n=Qb();if(!n)return;const a=Math.max(0,Math.min(1,t.volume/100));for(const i of t1[e])s1(n,i,a)}const n1=c.lazy(()=>mu(()=>import("./TerminalPanel-fC8DLbDz.js"),__vite__mapDeps([0,1,2,3,4])).then(e=>({default:e.TerminalPanel})));function a1({notice:e,onDismiss:t}){const n=Me(),{locale:a}=Ut(),i=a!=="zh"&&e.textEn?e.textEn:e.text,[o,l]=c.useState(!1);c.useEffect(()=>{if(o)return;const p=setTimeout(()=>t(e.id),e.level==="error"?12e3:7e3);return()=>clearTimeout(p)},[o,e.id,e.level,t]);const u=e.level==="error"?Yu:e.level==="warning"?Ku:Mu;return s.jsxs("div",{className:`notice notice-${e.level}${o?" paused":""}`,role:"status",onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[s.jsx(u,{className:"notice-icon"}),s.jsx("span",{className:"notice-text",children:i}),s.jsx("button",{type:"button",className:"notice-close",title:n("close"),onClick:()=>t(e.id),children:s.jsx(tt,{})})]})}const i1=[],Ic=180,jc=520,Rc=240,Lc=e=>`pi-web-ui:${e}-panel-width`;function lo(e){const t=Number(localStorage.getItem(Lc(e)));return Number.isFinite(t)&&t>=Ic&&t<=jc?t:Rc}const ai=e=>`pi-web-ui:${e}-panel-collapsed`;function co(e){return localStorage.getItem(ai(e))==="1"}function uo({side:e,width:t,onResize:n}){const a=Me(),i=c.useCallback(o=>{o.preventDefault();const l=o.clientX,u=t;let p=u;const h=m=>{const f=e==="left"?m.clientX-l:l-m.clientX;p=Math.min(jc,Math.max(Ic,Math.round(u+f))),n(p)},b=()=>{window.removeEventListener("pointermove",h),window.removeEventListener("pointerup",b),document.body.classList.remove("panel-resizing"),localStorage.setItem(Lc(e),String(p))};window.addEventListener("pointermove",h),window.addEventListener("pointerup",b),document.body.classList.add("panel-resizing")},[e,t,n]);return s.jsx("div",{className:`resize-handle resize-${e}`,title:a("dragToResize"),onPointerDown:i,onDoubleClick:()=>n(Rc)})}function po({side:e,onClick:t}){const n=Me();return s.jsx("button",{type:"button",className:`panel-rail panel-rail-${e}`,title:n("expandPanel"),onClick:t,children:e==="left"?s.jsx(Co,{}):s.jsx(wo,{})})}const Dc="pi-web-ui:plugin-path-grants";function Pc(){try{const e=localStorage.getItem(Dc),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function r1(e){try{const t=[...new Set([...Pc(),e])];localStorage.setItem(Dc,JSON.stringify(t))}catch{}}function o1(){const e=Me(),{locale:t}=Ut(),{chat:n,send:a,dismissNotice:i,pushNotice:o,terminal:l}=bp(),u=c.useRef(!1);c.useEffect(()=>{!n.ready||!n.settings||u.current||n.settings.quickPhrasesSeeded||(u.current=!0,n.settings.quickPhrases.length===0&&a({type:"set_settings",quickPhrases:Gn[t]??Gn.en,quickPhrasesSeeded:!0}))},[n.ready,n.settings,a,t]);const p=n.state?.cwd??"",h=yc();c.useEffect(()=>{const O=h?Sb(p):"";document.title=O?`${O} — pi-web-ui`:e("docTitle")},[p,h,e]);const[b,m]=c.useState([]);c.useEffect(()=>(Fi(O=>m(me=>wg(me,O))),()=>Fi(null)),[]);const[f,x]=c.useState(null),[v,N]=c.useState(!1);c.useEffect(()=>{const O=()=>N(!1);return window.addEventListener("drop",O,!0),()=>window.removeEventListener("drop",O,!0)},[]);const[B,X]=c.useState("chat"),K=O=>!n.tabs||O==="chat"||n.tabs.includes(O),A=B.startsWith("plugin:")?"plugins":B,R=K(A)?B:"chat",I=c.useMemo(()=>n.plugins.filter(O=>!n.settings?.disabledPlugins?.includes(O.id)),[n.plugins,n.settings?.disabledPlugins]),$=c.useMemo(()=>fc(n.plugins,{locale:t,t:O=>e(O),disabledPlugins:n.settings?.disabledPlugins??[],layout:n.settings?.uiLayout}),[n.plugins,n.settings?.disabledPlugins,n.settings?.uiLayout,t,e]),ce=c.useMemo(()=>$["topbar.primary"].filter(O=>!O.hidden),[$]),ge=c.useMemo(()=>[...$["topbar.primary"].filter(O=>O.hidden),...$["topbar.overflow"]],[$]),q=c.useCallback(O=>{const me=(O.action??"").trim();if(O.kind==="view"||(!me||me==="view")&&O.source!=="host"){X(O.view??`plugin:${O.source.startsWith("plugin:")?O.source.slice(7):""}`);return}if(!me)return;const Se=O.source.startsWith("plugin:")?O.source.slice(7):"";tp(Se,me,O.id,{loadBundle:async Ve=>{const Qe=j.current.plugins.find(Et=>Et.id===Ve);return Qe?Ha(Qe,j.current.pluginsEpoch):!1}}).then(Ve=>{Ve||o("info",e("pluginUiNoHandler"))})},[e,o]),[Y,J]=c.useState([]);c.useEffect(()=>ip(J),[]),c.useEffect(()=>{Vf(a),Qf(I,n.pluginsEpoch),rp(I,n.pluginsEpoch)},[I,n.pluginsEpoch,a]);const j=c.useRef(n);j.current=n;const F=c.useRef(X);F.current=X,c.useEffect(()=>(sr(ep({send:a,isReady:()=>!!j.current.state,setView:O=>F.current(O),getCwd:()=>j.current.state?.cwd??"",getWorkspaceRoots:()=>j.current.state?.workspaceRoots??[],listSessions:()=>{const O=j.current,me=O.state?.cwd??"";return[...O.conversations.map(Se=>({id:Se.id,title:Se.title,cwd:Se.cwd||me,kind:"running",isStreaming:Se.isStreaming})),...O.sessions.map(Se=>({id:Se.path,title:Se.name||Se.firstMessage||Se.path,cwd:me,kind:"history"}))]},getConversationId:()=>j.current.state?.conversationId??null,isConversationBlank:()=>(j.current.state?.messages.length??0)===0,listProjects:()=>j.current.projects.map(O=>O.path),grantedPaths:Pc,grantPath:r1,confirm:O=>new Promise(me=>_({path:O.path,resolve:me})),loadPluginBundle:O=>{const me=j.current.plugins.find(Se=>Se.id===O);return me?Ha(me,j.current.pluginsEpoch):Promise.resolve(!1)}})),()=>sr(null)),[a]);const[T,U]=c.useState(()=>lo("left")),[G,D]=c.useState(()=>lo("right")),se=c.useCallback(O=>U(O),[]),ee=c.useCallback(O=>D(O),[]),[Ne,w]=c.useState(()=>co("left")),[de,ue]=c.useState(()=>co("right")),pe=c.useCallback(()=>{w(O=>(localStorage.setItem(ai("left"),O?"0":"1"),!O))},[]),ke=c.useCallback(()=>{ue(O=>(localStorage.setItem(ai("right"),O?"0":"1"),!O))},[]),[Be,ye]=c.useState(null),[Ae,ve]=c.useState(()=>window.matchMedia("(max-width: 768px)").matches);c.useEffect(()=>{const O=window.matchMedia("(max-width: 768px)"),me=Se=>ve(Se.matches);return O.addEventListener("change",me),()=>O.removeEventListener("change",me)},[]);const[Ye,Pe]=c.useState(!1),[ae,be]=c.useState(!1),[Oe,Le]=c.useState(!1),[We,_]=c.useState(null),[Q,V]=c.useState(()=>new Set),Ee=(O,me)=>{a({type:"plugin_path_response",id:O,ok:me}),V(Se=>new Set(Se).add(O))},oe=n.pathRequests.find(O=>!Q.has(O.id))??null,Z=Ec(),[y,P]=c.useState(!1),[le,Te]=c.useState(!1),[Ie,Fe]=c.useState(null);c.useEffect(()=>{if(!Ie)return;const O=setTimeout(()=>Fe(null),15e3);return()=>clearTimeout(O)},[Ie]),c.useEffect(()=>{const O=Se=>{const Ve=Se.detail,Qe=Ve?.title||e("pluginCommandFallback"),Et=Ve?.command;if(!Et||!n.ready)return;const mt={name:Qe,command:Et,cwd:"${pwd}"},xt=n.terminals.find(vs=>vs.title===Qe);if(xt)l.restart(xt.id),a({type:"run_command",terminalId:xt.id,conversationId:xt.conversationId,command:mt,cols:80,rows:24});else{const vs=St();l.create({id:vs,conversationId:n.activeConversationId||n.state?.conversationId||"",title:Qe,cwd:n.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:mt})}X("terminal")};window.addEventListener("pi-web-ui:plugin-run-command",O);const me=Se=>{const Ve=Se.detail;typeof Ve=="string"&&Ve&&a({type:"switch_conversation",id:Ve})};return window.addEventListener("pi-web-ui:switch-conversation",me),()=>{window.removeEventListener("pi-web-ui:plugin-run-command",O),window.removeEventListener("pi-web-ui:switch-conversation",me)}},[n,l,a]),c.useEffect(()=>{const O=me=>{!(me.ctrlKey||me.metaKey)||me.key.toLowerCase()!=="k"||(me.preventDefault(),Te(Se=>!Se))};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[]);const[Re,L]=c.useState(Ac),{themes:De,theme:Ge,switchTheme:C}=t0();Fb();const S=c.useRef(null),he=c.useRef(null),Ce=c.useRef(null),$e=c.useRef(0),we=c.useRef(!1),Je=c.useRef(n.terminals);c.useEffect(()=>{Vb(Re)},[Re]),c.useEffect(()=>{const O=Je.current;Je.current=n.terminals;for(const me of n.terminals){const Se=me.command?.command??"";!O.find(Qe=>Qe.id===me.id)?.running||me.running||(Se.startsWith("pi remove ")?a({type:"extensions_reload"}):Se.startsWith("pi-web-ui install ")||Se.startsWith("pi-web-ui uninstall ")?a({type:"plugins_reload"}):Se.startsWith("npm i -g ")&&(a({type:"extensions_reload"}),a({type:"plugins_reload"}),a({type:"check_updates_all",force:!0})))}},[n.terminals,a]),c.useEffect(()=>{const O=n.state?.isStreaming??!1,me=S.current;S.current=O,me!==null&&(!me&&O?ps("start",Re):me&&!O&&(ps("done",Re),rn(e("notifyDoneTitle"),e("notifyDoneBody"))))},[n.state?.isStreaming,Re]),c.useEffect(()=>{const O=n.dialog?.id??null;O!==null&&O!==he.current&&(ps("question",Re),rn(e("notifyQuestionTitle"),e("notifyQuestionBody"))),he.current=O},[n.dialog,Re]),c.useEffect(()=>{const O=n.question?.id??null;O!==null&&O!==Ce.current&&(ps("question",Re),rn(e("notifyQuestionTitle"),e("notifyQuestionBody"))),Ce.current=O},[n.question,Re]),c.useEffect(()=>{const O=[...n.notices].reverse().find(me=>me.level==="error");O&&O.id!==$e.current&&($e.current=O.id,ps("error",Re),rn(e("notifyErrorTitle"),e("notifyErrorBody")))},[n.notices,Re]);const gt=(O,me,Se,Ve=!1,Qe)=>{const Et=`${O}|${Se}|${Qe?`${Qe.start}-${Qe.end}`:""}`;m(mt=>mt.some(xt=>`${xt.path}|${xt.mode}|${xt.lines?`${xt.lines.start}-${xt.lines.end}`:""}`===Et)?mt:[...mt,{path:O,name:me,mode:Se,isDir:Ve,...Qe?{lines:Qe}:{}}])},bt=O=>m(me=>me.filter(Se=>Se.key?Se.key!==O:Se.path!==O)),At=c.useCallback(O=>(!O.type.startsWith("list_")&&!O.type.startsWith("get_")&&ye(null),a(O)),[a]),$t=c.useRef(0),H=c.useRef(0),te=O=>{const me=Date.now();n.state?.model&&!n.state.model.vision&&me-H.current>1e4&&(H.current=me,o("warning",e("imageNotSupported")));const Se=`paste-${++$t.current}`;m(Ve=>[...Ve,{path:"",key:Se,name:O.name,mode:"inline",imageData:O.data,mimeType:O.mimeType}])},_e=async O=>{for(const me of O){const Se=await fi(me);if(!Se){o("error",e("imageLoadFailed",{name:me.name}));continue}te(Se)}},je=20*1024*1024,Ke=c.useRef(0),ze=async O=>{if(O.size>je){o("warning",e("fileTooLarge",{name:O.name,size:je/1024/1024}));return}let me;try{me=(await new Promise((Qe,Et)=>{const mt=new FileReader;mt.onload=()=>Qe(mt.result),mt.onerror=()=>Et(mt.error??new Error("read failed")),mt.readAsDataURL(O)})).replace(/^data:[^;]*;base64,/,"")}catch{o("error",e("fileLoadFailed",{name:O.name}));return}const Se=`upload-${++Ke.current}`;m(Ve=>[...Ve,{path:"",key:Se,name:O.name,mode:"inline",fileData:me,size:O.size,mimeType:O.type||void 0}])},pt=async O=>{for(const me of O)Ht(me.type)?await _e([me]):await ze(me)},It=c.useCallback((O,me,Se)=>{a({type:"edit_message",messageId:O,text:me,attachments:Se})},[a]),Zs=c.useCallback((O,me)=>{a({type:"queue_remove",kind:O,text:me})},[a]),[Qt,ks]=c.useState([]),Tt=c.useRef(0),na=c.useCallback((O,me)=>{a({type:"queue_remove",kind:O,text:me}),Tt.current+=1;const Se={text:me,seq:Tt.current};ks(Ve=>[...Ve.slice(-9),Se])},[a]),aa=c.useCallback(()=>be(!0),[]),en=c.useCallback(()=>m([]),[]),ia=c.useCallback(bt,[]),ra=c.useCallback(_e,[_e]),He=c.useCallback(pt,[pt]),Pt=n.state?.model,tn=n.state?.thinkingLevel,Ns=n.state?.availableThinkingLevels,oa=c.useMemo(()=>Pt?{model:Pt,thinkingLevel:tn??"off",availableThinkingLevels:Ns??[]}:null,[Pt,tn,Ns]),ls=c.useCallback(()=>!n.ready||n.terminals.length!==0?!1:(l.create({id:St(),conversationId:n.activeConversationId||n.state?.conversationId||"",title:e("terminalTitle",{n:1}),cwd:n.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null}),!0),[n.ready,n.state?.cwd,n.terminals.length,e,l]);return c.useEffect(()=>{if(we.current){if(R!=="terminal"||n.terminals.length!==0){we.current=!1;return}ls()&&(we.current=!1)}},[n.terminals.length,ls,R]),s.jsxs("div",{className:"app",onDragOver:O=>{Array.from(O.dataTransfer?.types??[]).includes("Files")&&(O.preventDefault(),N(!0))},onDragLeave:O=>{O.currentTarget.contains(O.relatedTarget)||N(!1)},onDrop:O=>{if(N(!1),!Array.from(O.dataTransfer?.types??[]).includes("Files"))return;O.preventDefault();const me=Array.from(O.dataTransfer?.files??[]);if(me.length===0){o("warning",e("foldersNotSupported"));return}const Se=me.filter(Qe=>Ht(Qe.type)),Ve=me.filter(Qe=>!Ht(Qe.type));Se.length>0&&_e(Se),Ve.length>0&&pt(Ve)},children:[v&&s.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:s.jsxs("span",{children:["📎 ",e("dropHereToAttach")]})}),s.jsx(Ud,{chat:n,terminal:l,view:R,plugins:I,uiPrimary:ce,uiOverflow:ge,uiContextTopbar:$["contextmenu.topbar"],onUiAction:q,onViewChange:O=>{we.current=O==="terminal"&&n.terminals.length===0,we.current&&ls()&&(we.current=!1),X(O),ye(null)},onOpenPanel:ye,onOpenSettings:()=>Le(!0),onOpenBgTasks:()=>P(!0),onOpenGlobalSearch:()=>Te(!0),sound:Re,onSoundChange:L,onSoundPreview:O=>ps(O,Re),themes:De,theme:Ge,onThemeChange:C}),n.protocolMismatch&&s.jsxs("div",{className:"protocol-banner",children:["⚠ ",e("protocolMismatch")]}),s.jsx("div",{className:"notices",children:n.notices.map(O=>s.jsx(a1,{notice:O,onDismiss:i},O.id))}),s.jsx(Eg,{currentModelId:Pt?`${Pt.provider}/${Pt.id}`:null,children:s.jsxs("div",{className:"layout",style:{"--left-w":`${T}px`,"--right-w":`${G}px`},children:[Be&&s.jsx("div",{className:"drawer-backdrop",onClick:()=>ye(null)}),s.jsxs("div",{className:`view-pane ${R==="chat"?"":"hidden"}`,children:[!Ae&&Ne&&s.jsx(po,{side:"left",onClick:pe}),s.jsx("div",{className:`panel-drawer drawer-left ${Be==="left"?"open":""}${Ae?"":Ne?" hidden":""}`,children:s.jsx(Vd,{collapsible:!Ae,onToggleCollapse:pe,panelSend:At,active:!Ae||Be==="left",sessionFile:n.state?.sessionFile??null,conversations:n.conversations,elsewhere:n.elsewhere,sessions:n.sessions,projects:n.projects,activeConversationId:n.activeConversationId,uiContextSession:$["contextmenu.session"]})}),!Ae&&s.jsx(uo,{side:"left",width:T,onResize:se}),s.jsxs("main",{className:Z?"main wide-chat":"main",children:[n.state?s.jsx(Cg,{uiMessageActions:$["message.actions"],uiContextMessage:$["contextmenu.message"],onUiAction:q,state:n.state,liveOutputs:n.liveOutputs,toolStatuses:n.toolStatuses,onEdit:It,onKillBash:()=>a({type:"abort_bash"}),onRetry:()=>{if(a({type:"retry_last"})){const O=n.state?.model;O&&qn(`${O.provider}/${O.id}`)}},onRemoveQueued:Zs,onRecallQueued:na,thinkingWrap:n.settings?.thinkingWrap??!0,toolsWrap:n.settings?.toolsWrap??!0,jumpTarget:Ie,onJumpDone:()=>Fe(null)},n.state.conversationId??"boot"):s.jsx("div",{className:"boot-wait",children:n.ready?e("loadingSession"):e("connectingServer")}),n.settings?.goalModeEnabled!==!1&&s.jsx(Wg,{goal:n.goal,models:n.models,modelsLoading:n.modelsLoading,activeConversationId:n.activeConversationId}),s.jsx(bb,{onAction:O=>q(O)}),n.dialog&&s.jsx(Jg,{dialog:n.dialog}),oe&&s.jsxs("div",{className:"dialog-inline","data-dialog-kind":"confirm",children:[s.jsxs("div",{className:"dialog-head",children:[s.jsx("span",{className:"dialog-badge",children:e("pluginRequest")}),s.jsx("span",{className:"dialog-title",children:e("pluginGrantRequestTitle")}),s.jsx("button",{type:"button",className:"dialog-dismiss",title:e("cancel"),onClick:()=>Ee(oe.id,!1),children:"✕"})]}),s.jsxs("div",{className:"dialog-body",children:[e("pluginGrantRequestBody").replace("{plugin}",oe.pluginId).replace("{path}",oe.path),oe.reason&&s.jsx("div",{className:"dialog-hint",children:oe.reason}),s.jsxs("div",{className:"dialog-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>Ee(oe.id,!1),children:e("pluginGrantDeny")}),s.jsx("button",{type:"button",className:"btn primary",onClick:()=>Ee(oe.id,!0),children:e("pluginGrantAllow")})]})]})]}),We&&s.jsxs("div",{className:"dialog-inline","data-dialog-kind":"confirm",children:[s.jsxs("div",{className:"dialog-head",children:[s.jsx("span",{className:"dialog-badge",children:e("pluginRequest")}),s.jsx("span",{className:"dialog-title",children:e("pluginSessionGrantTitle")}),s.jsx("button",{type:"button",className:"dialog-dismiss",title:e("cancel"),onClick:()=>{We.resolve(!1),_(null)},children:"✕"})]}),s.jsxs("div",{className:"dialog-body",children:[e("pluginSessionGrantBody").replace("{path}",We.path),s.jsxs("div",{className:"dialog-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>{We.resolve(!1),_(null)},children:e("cancel")}),s.jsx("button",{type:"button",className:"btn primary",onClick:()=>{We.resolve(!0),_(null)},children:e("ok")})]})]})]}),n.question&&s.jsx(sb,{question:n.question}),s.jsx(qg,{composerActions:$["composer.actions"],onUiAction:q,streaming:n.state?.isStreaming??!1,messages:n.state?.messages??i1,slashCommands:n.slashCommands,modelState:oa,models:n.models,modelsLoading:n.modelsLoading,providerKeys:n.providerKeys,attachments:b,onRemoveAttachment:ia,onAddImageFiles:ra,onAddLocalFiles:He,onNotice:o,onManageModels:aa,onSent:en,quickPhrases:n.settings?.quickPhrases??[],quickPhrasesEnabled:n.settings?.quickPhrasesEnabled??!0,recallDrafts:Qt})]}),!Ae&&s.jsx(uo,{side:"right",width:G,onResize:ee}),s.jsx("div",{className:`panel-drawer drawer-right ${Be==="right"?"open":""}${Ae?"":de?" hidden":""}`,children:s.jsx(Pp,{collapsible:!Ae,onToggleCollapse:ke,panelSend:At,files:n.files,fileChanged:n.fileChanged,widgets:n.widgets,onAttach:(O,me,Se,Ve)=>{ye(null),gt(O,me,Se,Ve)},onPreview:(O,me)=>{ye(null),x({path:O,name:me})},onNotice:(O,me)=>o(O,me),uiRightPanelTabs:$["rightpanel.tabs"],uiContextFile:$["contextmenu.file"],plugins:I,pluginsEpoch:n.pluginsEpoch,send:a})}),!Ae&&de&&s.jsx(po,{side:"right",onClick:ke})]}),s.jsx("div",{className:`view-pane ${R==="terminal"?"":"hidden"}`,children:s.jsx(c.Suspense,{fallback:null,children:s.jsx(n1,{chat:n,terminal:l})})}),s.jsx("div",{className:`view-pane ${R==="git"?"":"hidden"}`,children:s.jsx(ob,{chat:n,terminal:l,active:R==="git",onSwitchToTerminal:()=>X("terminal")})}),Y.map(O=>{const me=`plugin:${O.info.id}`;return s.jsx("div",{className:`view-pane ${R===me?"":"hidden"}`,children:s.jsx(lb,{entry:O})},O.info.id)})]})}),s.jsx(Qg,{chat:n,bottombarItems:$.bottombar,onUiAction:q}),f&&s.jsx(Gb,{file:f,content:n.fileContent,onAddLines:(O,me,Se,Ve)=>gt(O,me,"lines",!1,{start:Se,end:Ve}),onAttach:(O,me,Se)=>gt(O,me,Se),onClose:()=>x(null)}),n.ready&&n.state&&n.state.piConfigured===!1&&!Ye&&!ae&&s.jsx(Eb,{piConfigured:n.state.piConfigured,piAgentInstalled:n.state.piAgentInstalled,providers:n.providers,installResult:n.installResult,onClose:()=>Pe(!0)}),ae&&s.jsx(yb,{providers:n.modelsConfig,providerStatus:n.providers,providerKeys:n.providerKeys,fetchModelsResult:n.fetchModelsResult,cloneProviderResult:n.cloneProviderResult,onClose:()=>be(!1)}),Oe&&s.jsx($b,{chat:n,terminal:l,onSwitchToTerminal:()=>X("terminal"),onClose:()=>Le(!1)}),y&&s.jsx(Wb,{servers:n.bgServers,onClose:()=>P(!1)}),s.jsx(Yb,{open:le,projects:n.projects,fileSearch:n.fileSearch,sessionSearch:n.sessionSearch,onClose:()=>Te(!1),onSwitchSession:(O,me)=>{a({type:"switch_session",path:O});const Se=me&&me[0];Fe(Se?{path:O,role:Se.role,timestamp:Se.timestamp}:null)},onSwitchProject:O=>{a({type:"set_cwd",path:O})},onPreviewFile:(O,me)=>{x({path:O,name:me})}})]})}function l1(){typeof document>"u"||(Oc(c1()),d1())}function Oc(e){!Number.isFinite(e)||e<0||document.documentElement.style.setProperty("--msgs-gutter",`${Math.round(e*100)/100}px`)}function c1(){const e=document.createElement("div");e.style.cssText="position:fixed;top:-9999px;left:0;width:100px;height:100px;overflow-y:auto;scrollbar-gutter:stable both-edges;visibility:hidden;pointer-events:none;",document.body.appendChild(e);const t=(e.offsetWidth-e.clientWidth)/2;return e.remove(),t}function u1(e){const t=document.createElement("div");t.style.cssText="width:0;height:0;pointer-events:none;",e.appendChild(t);const n=getComputedStyle(e),a=e.getBoundingClientRect(),i=t.getBoundingClientRect(),o=Number.parseFloat(n.borderLeftWidth)||0,l=Number.parseFloat(n.paddingLeft)||0,u=i.left-(a.left+o+l);return t.remove(),u}function d1(){const e=()=>{const a=document.querySelector(".messages");return a?(Oc(u1(a)),!0):!1};let t=0;if(window.addEventListener("resize",()=>{t||(t=window.requestAnimationFrame(()=>{t=0,e()}))}),e())return;const n=new MutationObserver(()=>{e()&&n.disconnect()});n.observe(document.documentElement,{childList:!0,subtree:!0}),window.setTimeout(()=>n.disconnect(),6e4)}Qu();ql($l());l1();uu.createRoot(document.getElementById("root")).render(s.jsx(c.StrictMode,{children:s.jsx(od,{children:s.jsx(o1,{})})}));"serviceWorker"in navigator&&window.addEventListener("load",()=>{const e=Ao();navigator.serviceWorker.register(`${e}sw.js`,{scope:e}).catch(t=>{console.warn("Service worker registration failed:",t)})});export{Rt as F,zt as T,ie as a,f1 as b,Me as c,kt as d,h1 as e,An as f,ut as g,ju as h,Vn as i,tt as j,St as r,Ut as u};
351
+ ${i("markersOffHint")}`,enabled:Je,onToggle:()=>Fe({markersEnabled:!Je})}),Je&&(u.markers?.length??0)===0&&s.jsxs("p",{className:"set-empty",children:[i("loading"),"..."]}),Je&&u.markers&&u.markers.length>0&&u.markers.map(d=>s.jsx(Ze,{title:d.name==="todo"?i("markerGroupTodo"):d.name==="notify"?i("markerGroupNotify"):d.name==="conv"?i("markerGroupRename"):d.name,tip:d.guidance.join(`
352
+ `),enabled:d.enabled,onToggle:()=>mt(d.name)},d.name)),s.jsx(Ze,{title:bn,tip:`${i("todoListEnabledDesc")}
353
+ ${i("todoListOffHint")}`,enabled:!kt.has(bn),onToggle:()=>ze(bn)}),s.jsx("div",{className:"set-field-label",children:i("toolsSectionOther")}),s.jsx(Ze,{title:hn,tip:`${i("editSoftEnabledDesc")}
354
+ ${i("editSoftOffHint")}`,enabled:!kt.has(hn),onToggle:()=>ze(hn)}),s.jsx(Ze,{title:fn,tip:`${i("delegateTaskEnabledDesc")}
355
+ ${i("delegateTaskOffHint")}`,enabled:!kt.has(fn),onToggle:()=>ze(fn)}),s.jsx(Ze,{title:gn,tip:`${i("questionnaireEnabledDesc")}
356
+ ${i("questionnaireOffHint")}`,enabled:!kt.has(gn),onToggle:()=>ze(gn)}),s.jsx(Ze,{title:Ps,tip:`${i("browserPageEnabledDesc")}
357
+ ${i("browserPageOffHint")}`,enabled:!kt.has(Ps),onToggle:()=>ze(Ps)})]}),m==="question"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Li,{className:"set-section-icon"}),i("settingsQuestionnaire")]}),s.jsx(Ze,{title:i("questionnaireEnabled"),tip:`${i("questionnaireEnabledDesc")}
358
+ ${i("questionnaireOffHint")}`,enabled:u.questionnaireEnabled,onToggle:()=>Fe({questionnaireEnabled:!u.questionnaireEnabled})})]}),m==="display"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(ts,{className:"set-section-icon"}),i("settingsMessageDisplay")]}),s.jsxs("div",{className:"set-field",children:[s.jsxs("label",{className:"set-field-label",htmlFor:"model-retry-max",children:[i("modelRetryAttempts")," ",s.jsx(nt,{text:i("modelRetryHint")})]}),s.jsx("input",{id:"model-retry-max",className:"set-input",type:"number",min:0,max:100,step:1,value:bt,onChange:d=>Et(d.target.value),onBlur:()=>{const d=Math.min(100,Math.max(0,Math.floor(Number(bt)||0)));Et(String(d)),d!==u.retryMaxAttempts&&Fe({retryMaxAttempts:d})},onKeyDown:d=>{d.key==="Enter"&&d.target.blur()}})]}),s.jsx("hr",{className:"set-sep"}),s.jsx(Ze,{title:i("thinkingWrap"),tip:i("thinkingWrapDesc"),enabled:u.thinkingWrap??!0,onToggle:()=>Fe({thinkingWrap:!(u.thinkingWrap??!0)})}),s.jsx(Ze,{title:i("toolsWrap"),tip:i("toolsWrapDesc"),enabled:u.toolsWrap??!0,onToggle:()=>Fe({toolsWrap:!(u.toolsWrap??!0)})}),s.jsx(Ze,{title:i("devNoCache"),tip:i("devNoCacheDesc"),enabled:u.devNoCache??!0,onToggle:()=>Fe({devNoCache:!(u.devNoCache??!0)})}),s.jsx(Ze,{title:i("autoReload"),tip:i("autoReloadDesc"),enabled:u.autoReload??!0,onToggle:()=>Fe({autoReload:!(u.autoReload??!0)})}),s.jsx("hr",{className:"set-sep"}),s.jsx(Ze,{title:i("wideChat"),tip:i("wideChatDesc"),enabled:ye,onToggle:()=>vb({wide:!ye})}),s.jsx(Ze,{title:i("projectTitle"),tip:i("projectTitleDesc"),enabled:we,onToggle:()=>Ab({projectName:!we})}),s.jsx("hr",{className:"set-sep"}),s.jsxs("div",{className:"set-row",children:[s.jsxs("div",{className:"set-row-info",children:[s.jsxs("div",{className:"set-row-name",children:[i("wallpaperTitle"),s.jsx(nt,{text:i("wallpaperDesc")})]}),s.jsxs("div",{className:"wallpaper-url-row",children:[s.jsx("input",{className:"set-input wallpaper-url",placeholder:i("wallpaperUrlPh"),value:qe,maxLength:2e3,spellCheck:!1,onFocus:()=>{se.current=!0},onChange:d=>Be(d.target.value),onBlur:()=>{if(se.current=!1,!qe.trim()&&Ce.url.startsWith("data:")){Be("");return}const d=ni(qe);Be(d),d!==Ce.url&&_s({...Ce,url:d})},onKeyDown:d=>{d.key==="Enter"?d.target.blur():d.key==="Escape"&&(Be(Ce.url.startsWith("data:")?"":Ce.url),d.target.blur())}}),s.jsxs("button",{type:"button",className:"set-save-btn",disabled:De,onClick:()=>Te.current?.click(),children:[s.jsx(vu,{})," ",i("wallpaperUpload")]}),s.jsx("input",{ref:Te,type:"file",accept:"image/*",hidden:!0,onChange:Q})]}),Ye&&s.jsx("p",{className:"set-hint",children:i("wallpaperUploadFailed")}),s.jsxs("div",{className:"wallpaper-sliders",children:[s.jsxs("label",{className:"wallpaper-slider",children:[s.jsx("span",{children:i("wallpaperDim")}),s.jsx("input",{type:"range",min:0,max:95,step:1,value:Ce.dim,onChange:d=>_s({...Ce,dim:Number(d.target.value)})}),s.jsxs("output",{children:[Ce.dim,"%"]})]}),s.jsxs("label",{className:"wallpaper-slider",children:[s.jsx("span",{children:i("wallpaperBlur")}),s.jsx("input",{type:"range",min:0,max:24,step:1,value:Ce.blur,onChange:d=>_s({...Ce,blur:Number(d.target.value)})}),s.jsxs("output",{children:[Ce.blur,"px"]})]})]})]}),Ce.url&&s.jsxs("div",{className:"wallpaper-current",children:[s.jsx("img",{className:"wallpaper-preview",src:Ce.url,alt:""}),s.jsx("button",{type:"button",className:"wallpaper-clear",onClick:()=>{Be(""),_s({...Ce,url:""})},children:i("wallpaperClear")})]})]})]}),m==="quick"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Aa,{className:"set-section-icon"}),i("quickPhrases"),s.jsx(nt,{text:i("quickPhrasesDesc")}),s.jsx("span",{className:"set-count",children:u.quickPhrases.length})]}),s.jsx(Ze,{title:i("quickPhrasesEnabled"),tip:i("quickPhrasesDesc"),enabled:u.quickPhrasesEnabled,onToggle:()=>Fe({quickPhrasesEnabled:!u.quickPhrasesEnabled})}),!u.quickPhrasesEnabled&&s.jsx("p",{className:"set-hint",children:i("quickPhrasesOffHint")}),s.jsxs("div",{className:"set-preset-save",children:[s.jsx("input",{className:"set-input",placeholder:i("quickPhrasesPlaceholder"),value:U,maxLength:200,onChange:d=>te(d.target.value),onKeyDown:d=>{d.key==="Enter"&&U.trim()&&(Fe({quickPhrases:[...u.quickPhrases,U.trim()]}),te(""))}}),s.jsxs("button",{type:"button",className:"set-save-btn",disabled:!U.trim(),onClick:()=>{Fe({quickPhrases:[...u.quickPhrases,U.trim()]}),te("")},children:[s.jsx(yt,{})," ",i("quickPhrasesAdd")]})]}),u.quickPhrases.length===0?s.jsx("p",{className:"set-empty",children:i("quickPhrasesEmpty")}):s.jsx("div",{className:"set-list",children:u.quickPhrases.map((d,q)=>s.jsx("div",{className:"set-row",children:je?.index===q?s.jsx("div",{className:"set-row-info",children:s.jsx("input",{className:"set-input",autoFocus:!0,value:je.value,maxLength:200,placeholder:i("quickPhrasesEditPh"),onChange:fe=>_e({index:q,value:fe.target.value}),onKeyDown:fe=>{fe.key==="Enter"?sn():fe.key==="Escape"&&_e(null)},onBlur:sn})}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"set-row-info",children:s.jsx("div",{className:"set-row-name",title:d,children:d})}),s.jsxs("div",{className:"set-row-actions",children:[s.jsx("button",{type:"button",className:"set-icon-btn",title:i("quickPhrasesEdit"),onClick:()=>_e({index:q,value:d}),children:s.jsx(Ys,{})}),s.jsx("button",{type:"button",className:"set-icon-btn",title:i("quickPhrasesMoveUp"),disabled:q===0,onClick:()=>{const fe=[...u.quickPhrases];[fe[q-1],fe[q]]=[fe[q],fe[q-1]],Fe({quickPhrases:fe})},children:"↑"}),s.jsx("button",{type:"button",className:"set-icon-btn",title:i("quickPhrasesMoveDown"),disabled:q===u.quickPhrases.length-1,onClick:()=>{const fe=[...u.quickPhrases];[fe[q],fe[q+1]]=[fe[q+1],fe[q]],Fe({quickPhrases:fe})},children:"↓"}),s.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("quickPhrasesDelete"),onClick:()=>Fe({quickPhrases:u.quickPhrases.filter((fe,Ke)=>Ke!==q)}),children:s.jsx(dt,{})})]})]})},`${q}:${d}`))}),s.jsx("div",{className:"compose-toolbar",children:s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{_e(null),Fe({quickPhrases:Qn[o]??Qn.en})},children:i("quickPhrasesReset")})})]}),m==="skills"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Gs,{className:"set-section-icon"}),i("settingsSkills"),s.jsx(nt,{text:`${i("skillFullTextLabel")}:${i("skillFullTextDesc")}`}),s.jsx("span",{className:"set-count",children:u.skills.length})]}),u.skills.length===0?s.jsx("p",{className:"set-empty",children:i(b?"dshSkillsNote":"noSkills")}):s.jsx("div",{className:"set-list",children:u.skills.map(d=>s.jsx(Ze,{title:d.name,subtitle:d.description,enabled:d.enabled,onToggle:()=>$t(d),action:s.jsx("button",{type:"button",className:`tpl-chip${ks.has(d.name)?" on":""}`,title:i("skillFullTextDesc"),onClick:()=>nn(d.name),children:i("skillFullTextShort")})},d.name))})]}),m==="extensions"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(pa,{className:"set-section-icon"}),i("settingsExtensions"),s.jsx("span",{className:"set-count",children:u.extensions.length})]}),u.extensions.length===0?s.jsx("p",{className:"set-empty",children:i(b?"dshExtensionsNote":"noExtensions")}):s.jsx("div",{className:"set-list",children:u.extensions.map(d=>{const q=d.id.startsWith("npm:")?d.id.slice(4):null;return s.jsx(Ze,{title:d.name,subtitle:d.path,enabled:d.enabled,onToggle:()=>he(d),action:q?Ee===d.id?s.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("uninstallConfirmHint"),onClick:()=>vs(q),children:i("uninstallConfirm")}):s.jsxs("button",{type:"button",className:"set-uninstall",title:i("uninstallHint"),onClick:()=>Ae(d.id),children:[s.jsx(dt,{}),i("uninstallExt")]}):void 0},d.id)})})]}),m==="plugins"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Ri,{className:"set-section-icon"}),i("uiLayoutTitle"),s.jsx("button",{type:"button",className:"set-uninstall",onClick:Wc,children:i("uiLayoutRestoreAll")})]}),s.jsx("div",{className:"set-note",children:i("uiLayoutHint")}),Uc.map(({slot:d,labelKey:q})=>{const fe=Zs[d]??[];return s.jsxs("div",{className:"set-ui-slot",children:[s.jsx("div",{className:"set-ui-slot-title",children:i(q)}),fe.length===0?s.jsx("div",{className:"set-empty",children:i("uiLayoutEmpty")}):fe.map((Ke,at)=>s.jsxs("div",{className:"set-row",children:[s.jsxs("label",{className:"set-toggle",title:Ke.id,children:[s.jsx("input",{type:"checkbox",checked:!Ke.hidden,onChange:()=>$c(Ke)}),s.jsxs("span",{children:[Ke.icon?`${Ke.icon} `:"",Ke.label]})]}),s.jsxs("div",{className:"set-row-actions",children:[Ke.arrangedBy.length>0&&s.jsx("span",{className:"set-ui-source",title:Ke.arrangedBy.join(", "),children:i("uiLayoutArranged")}),Ke.userOverrides.length>0&&s.jsx("button",{type:"button",className:"set-uninstall",onClick:()=>qc(Ke.id),children:i("uiLayoutRestore")}),s.jsx("button",{type:"button",className:"set-uninstall",disabled:at===0,onClick:()=>xi(fe,Ke.id,-1),children:"↑"}),s.jsx("button",{type:"button",className:"set-uninstall",disabled:at===fe.length-1,onClick:()=>xi(fe,Ke.id,1),children:"↓"})]})]},Ke.id))]},d)})]}),m==="plugins"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Bt,{className:"set-section-icon"}),i("pluginGrantsTitle"),s.jsx("span",{className:"set-count",children:e.pluginGrants.reduce((d,q)=>d+q.paths.length,0)})]}),s.jsx("div",{className:"set-note",children:i("pluginGrantsHint")}),e.pluginGrants.length===0?s.jsx("p",{className:"set-empty",children:i("pluginGrantsEmpty")}):s.jsx("div",{className:"set-list",children:e.pluginGrants.map(d=>s.jsxs("div",{className:"set-grant-row",children:[s.jsx("div",{className:"set-catalog-title",children:s.jsx("span",{children:d.pluginId})}),d.paths.map(q=>s.jsxs("div",{className:"set-grant-path",children:[s.jsx("span",{className:"set-catalog-source",children:q}),s.jsx("button",{type:"button",className:"set-uninstall",onClick:()=>ie({type:"plugin_path_revoke",pluginId:d.pluginId,path:q}),children:i("pluginGrantsRevoke")})]},q))]},d.pluginId))})]}),m==="plugins"&&h&&s.jsx("div",{className:"set-section",children:s.jsx("div",{className:"set-note",children:i("updatesManaged")})}),m==="plugins"&&!h&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(pa,{className:"set-section-icon"}),i("pluginMarket"),s.jsx("span",{className:"set-count",children:e.pluginCatalog.length}),s.jsxs("label",{className:"set-catalog-build",title:i("pluginBuildHint"),children:[s.jsx("input",{type:"checkbox",checked:Dt,onChange:d=>Pt(d.target.checked)}),i("pluginBuildSource")]}),s.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginCatalogAddHint"),onClick:()=>ut(d=>!d),children:[s.jsx(yt,{}),i("pluginCatalogAdd")]})]}),gt&&s.jsxs("div",{className:"set-catalog-add",children:[s.jsx("input",{className:"set-input",placeholder:i("pluginCatalogSource"),value:Ge,onChange:d=>R(d.target.value)}),s.jsx("input",{className:"set-input",placeholder:i("pluginCatalogId"),value:He,onChange:d=>C(d.target.value)}),s.jsx("input",{className:"set-input",placeholder:i("pluginCatalogName"),value:_,onChange:d=>me(d.target.value)}),s.jsx("input",{className:"set-input",placeholder:i("pluginCatalogIcon"),value:Ie,onChange:d=>Qe(d.target.value)}),s.jsx("textarea",{className:"set-input",rows:2,placeholder:i("pluginCatalogDesc"),value:Ne,onChange:d=>$e(d.target.value)}),s.jsxs("div",{className:"set-catalog-add-actions",children:[s.jsx("button",{type:"button",className:"set-uninstall confirm",disabled:!Ge.trim(),onClick:Gc,children:i("pluginCatalogAddSubmit")}),s.jsx("button",{type:"button",className:"set-uninstall",onClick:()=>ut(!1),children:i("cancel")})]})]}),e.pluginCatalog.length===0?s.jsx("p",{className:"set-empty",children:i("noPluginCatalog")}):s.jsx("div",{className:"set-list",children:e.pluginCatalog.map(d=>{const q=Ns.has(d.id);return s.jsxs("div",{className:"set-catalog-row",children:[s.jsxs("div",{className:"set-catalog-main",children:[s.jsxs("div",{className:"set-catalog-title",children:[s.jsxs("span",{children:[d.icon?`${d.icon} `:"",d.name]}),q&&s.jsx("span",{className:"set-catalog-installed",children:i("pluginInstalled")}),!d.builtin&&s.jsx("span",{className:"set-catalog-custom",children:i("pluginCatalogCustom")})]}),d.description&&s.jsx("div",{className:"set-catalog-desc",children:d.description}),s.jsx("div",{className:"set-catalog-source",children:d.source}),Hc(d.id)]}),s.jsxs("div",{className:"set-row-actions",children:[q?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUpdateHint"),onClick:()=>ki(d.id,d.source),children:[s.jsx(jt,{}),i("pluginUpdate")]}),Me===d.id?s.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("pluginUninstallHint"),onClick:()=>yi(d.id),children:i("uninstallConfirm")}):s.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUninstallHint"),onClick:()=>Le(d.id),children:[s.jsx(dt,{}),i("uninstallExt")]})]}):s.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginInstallHint"),onClick:()=>Kc(d),children:[s.jsx(ss,{}),i("pluginInstall")]}),!d.builtin&&s.jsx("button",{type:"button",className:"set-uninstall",title:i("pluginCatalogRemoveHint"),onClick:()=>Yc(d.id),children:s.jsx(tt,{})})]})]},d.id)})})]}),m==="plugins"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(ln,{className:"set-section-icon"}),i("settingsUiPlugins"),s.jsx("span",{className:"set-count",children:e.plugins.length})]}),e.plugins.length===0?s.jsx("p",{className:"set-empty",children:i("noUiPlugins")}):s.jsx("div",{className:"set-list",children:e.plugins.map(d=>s.jsxs(s.Fragment,{children:[s.jsx(Ze,{title:`${d.icon?`${d.icon} `:""}${d.name}`,subtitle:(d.error?`${d.id} · ${d.error}`:d.source?`${d.id} · ${d.source}`:`${d.id} · ${i("uiPluginNoSource")}`)+(d.permissions?.length?` · ${i("uiPluginPerms")}: ${d.permissions.join(", ")}`:""),enabled:!an.has(d.id)&&!d.error,onToggle:()=>!d.error&&O(d),action:s.jsxs("div",{className:"set-row-actions",children:[d.source&&s.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUpdateHint"),onClick:()=>ki(d.id,d.source),children:[s.jsx(jt,{}),i("pluginUpdate")]}),Me===d.id?s.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("pluginUninstallHint"),onClick:()=>yi(d.id),children:i("uninstallConfirm")}):s.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUninstallHint"),onClick:()=>Le(d.id),children:[s.jsx(dt,{}),i("uninstallExt")]})]})},d.id),d.settingsSchema&&d.settingsSchema.length>0&&s.jsx(kb,{plugin:d})]}))})]}),m==="plugins"&&b&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(ln,{className:"set-section-icon"}),i("dshPatches"),s.jsx(nt,{text:i("dshPatchesDesc")}),s.jsx("span",{className:"set-count",children:e.dshPatches?.files.length??0}),s.jsxs("button",{type:"button",className:"set-uninstall",title:i("dshPatchesRescanHint"),onClick:()=>ie({type:"dsh_patches_rescan"}),children:[s.jsx(jt,{}),i("dshPatchesRescan")]})]}),(e.dshPatches?.files.length??0)===0?s.jsx("p",{className:"set-empty",children:i("dshPatchesEmpty")}):s.jsx("div",{className:"set-list",children:e.dshPatches.files.map(d=>s.jsx("div",{className:"set-row",children:s.jsxs("div",{className:"set-row-info",children:[s.jsx("div",{className:"set-row-name",children:d.name}),s.jsxs("div",{className:"set-row-desc",children:[Ub(d.size)," · ",new Date(d.mtimeMs).toLocaleString()]})]})},d.name))}),s.jsxs("p",{className:"set-hint",children:[i("dshPatchesPath")," ",e.dshPatches?.patchDir??""]})]}),m==="review"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(ms,{className:"set-section-icon"}),i("settingsReview"),s.jsx(nt,{text:i("settingsReviewDesc")}),s.jsx("span",{className:"set-count",children:u.reviewSkills.length})]}),s.jsx(Ze,{title:i("goalModeEnabled"),tip:`${i("goalModeEnabledDesc")}
359
+ ${i("goalModeOffHint")}`,enabled:u.goalModeEnabled,onToggle:()=>Fe({goalModeEnabled:!u.goalModeEnabled})}),s.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:i("reviewPromptPlaceholder"),value:T,onFocus:()=>Y.current=!0,onBlur:()=>{Y.current=!1,Fe({reviewPrompt:T})},onChange:d=>F(d.target.value)}),s.jsxs("div",{className:"set-field-label",children:[i("settingsReviewSkills"),b&&s.jsxs(s.Fragment,{children:[" ",s.jsx(nt,{text:i("dshReviewPromptNote")})]})]}),u.reviewSkills.length===0?s.jsx("p",{className:"set-empty",children:i("noSkills")}):s.jsx("div",{className:"set-list",children:u.reviewSkills.map(d=>s.jsx(Ze,{title:d.name,subtitle:d.description,enabled:d.enabled,onToggle:()=>zc(d)},`review-${d.name}`))})]}),m==="vision"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(jn,{className:"set-section-icon"}),i("settingsVisionBridge")]}),s.jsx(Ze,{title:i("visionBridgeEnabled"),tip:`${i("settingsVisionBridgeDesc")}
360
+ ${i("visionBridgeOffHint")}`,enabled:u.visionBridgeEnabled,onToggle:()=>Fe({visionBridgeEnabled:!u.visionBridgeEnabled})}),u.visionBridgeEnabled&&s.jsxs("div",{className:"set-mode-row",children:[s.jsx("label",{className:"set-field-label",children:i("visionBridgeModel")}),s.jsxs("select",{className:"set-select",value:u.visionBridgeModel??"",onChange:d=>Fe({visionBridgeModel:d.target.value||null}),children:[s.jsx("option",{value:"",children:i("visionBridgeAuto")}),u.visionModels.map(d=>s.jsx("option",{value:`${d.provider}/${d.id}`,children:d.label},`${d.provider}/${d.id}`))]})]}),u.visionBridgeEnabled&&s.jsxs("div",{className:"set-mode-row",children:[s.jsx("label",{className:"set-field-label",children:i("visionBridgePromptMode")}),s.jsxs("select",{className:"set-select",value:J,onChange:d=>{const q=d.target.value;L(q),Fe({visionBridgePromptMode:q})},children:[s.jsx("option",{value:"append",children:i("promptModeAppend")}),s.jsx("option",{value:"replace",children:i("promptModeReplace")})]})]}),u.visionBridgeEnabled&&s.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:i("visionBridgePromptPlaceholder"),value:$,onFocus:()=>H.current=!0,onBlur:()=>{H.current=!1;const d=J==="replace"&&u.visionBridgeDefaultPrompt&&$===u.visionBridgeDefaultPrompt?"":$;Fe({visionBridgePromptMode:J,visionBridgePrompt:d})},onChange:d=>K(d.target.value)}),u.visionBridgeEnabled&&(u.visionModels.length===0?s.jsx("p",{className:"set-hint",children:i("visionBridgeNoModels")}):s.jsx("p",{className:"set-hint",children:i("visionBridgeCurrent",{model:u.visionBridgeModel??i("visionBridgeAuto")})}))]}),m==="presets"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(_n,{className:"set-section-icon"}),i("settingsPresets"),s.jsx("span",{className:"set-count",children:u.presets.length})]}),s.jsxs("div",{className:"set-preset-save",children:[s.jsx("input",{className:"set-input",placeholder:i("presetNamePlaceholder"),value:D,onChange:d=>ae(d.target.value),onKeyDown:d=>{d.key==="Enter"&&D.trim()&&(ie({type:"save_preset",name:D.trim()}),ae(""))}}),s.jsxs("button",{type:"button",className:"set-save-btn",disabled:!D.trim(),onClick:()=>{ie({type:"save_preset",name:D.trim()}),ae("")},children:[s.jsx(yt,{})," ",i("saveAsPreset")]})]}),u.presets.length===0?s.jsx("p",{className:"set-empty",children:i("noPresets")}):s.jsx("div",{className:"set-list",children:u.presets.map(d=>s.jsxs("div",{className:"set-row",children:[s.jsxs("div",{className:"set-row-info",children:[s.jsx("div",{className:"set-row-name",children:d.name}),s.jsxs("div",{className:"set-row-desc",children:[d.promptMode==="replace"?i("promptModeReplace"):i("promptModeAppend"),d.disabledSkills.length>0&&` · ${i("settingsSkills")} ${d.disabledSkills.length}`,d.disabledExtensions.length>0&&` · ${i("settingsExtensions")} ${d.disabledExtensions.length}`]})]}),s.jsxs("div",{className:"set-row-actions",children:[s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>ie({type:"apply_preset",name:d.name}),children:i("applyPreset")}),s.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("deletePreset"),onClick:()=>ie({type:"delete_preset",name:d.name}),children:s.jsx(dt,{})})]})]},d.name))})]}),m==="subagent-templates"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Ai,{className:"set-section-icon"}),i("settingsSubagentTemplates"),s.jsx(nt,{text:i("settingsSubagentTemplatesDesc")}),s.jsx("span",{className:"set-count",children:u.subagentTemplates.length}),s.jsxs("button",{type:"button",className:"set-save-btn",title:i("subagentTemplateNew"),onClick:()=>ve({name:"",description:"",promptMode:"replace",systemPrompt:"",enabledSkills:[],enabledExtensions:[],model:"",thinkingLevel:"",enabled:!0}),children:[s.jsx(yt,{})," ",i("subagentTemplateNew")]})]}),s.jsxs("div",{className:"set-mode-row",children:[s.jsxs("label",{className:"set-field-label",children:[i("subagentDefaultModelLabel")," ",s.jsx(nt,{text:i("subagentDefaultModelHint")})]}),s.jsxs("select",{className:"set-select",value:u.subagentDefaultModel??"",onChange:d=>Fe({subagentDefaultModel:d.target.value||null}),children:[s.jsx("option",{value:"",children:i("subagentFollowMain")}),u.subagentModels.map(d=>s.jsx("option",{value:`${d.provider}/${d.id}`,children:d.label},`${d.provider}/${d.id}`))]})]}),u.subagentModels.length===0&&s.jsx("p",{className:"set-hint",children:i("subagentNoModels")}),ee&&s.jsxs("div",{className:"tpl-editor",children:[s.jsxs("div",{className:"tpl-fields",children:[s.jsx("input",{className:"set-input",placeholder:i("tplNamePlaceholder"),value:ee.name,onChange:d=>ve({...ee,name:d.target.value})}),s.jsx("input",{className:"set-input",placeholder:i("tplDescriptionPlaceholder"),value:ee.description,onChange:d=>ve({...ee,description:d.target.value})}),s.jsx("input",{className:"set-input",placeholder:i("tplDescriptionEnPlaceholder"),value:ee.descriptionEn??"",onChange:d=>ve({...ee,descriptionEn:d.target.value})})]}),s.jsxs("div",{className:"set-mode-row",children:[s.jsx("label",{className:"set-field-label",children:i("tplPromptModeLabel")}),s.jsxs("select",{className:"set-select",value:ee.promptMode,onChange:d=>ve({...ee,promptMode:d.target.value}),children:[s.jsx("option",{value:"replace",children:i("promptModeReplace")}),s.jsx("option",{value:"append",children:i("promptModeAppend")})]})]}),s.jsxs("div",{className:"set-mode-row",children:[s.jsx("label",{className:"set-field-label",children:i("tplModelLabel")}),s.jsxs("select",{className:"set-select",value:ee.model??"",onChange:d=>ve({...ee,model:d.target.value}),children:[s.jsx("option",{value:"",children:i("subagentFollowMain")}),u.subagentModels.map(d=>s.jsx("option",{value:`${d.provider}/${d.id}`,children:d.label},`${d.provider}/${d.id}`))]})]}),s.jsxs("div",{className:"set-mode-row",children:[s.jsxs("label",{className:"set-field-label",children:[i("tplThinkingLabel")," ",s.jsx(nt,{text:i("tplThinkingHint")})]}),s.jsxs("select",{className:"set-select",value:ee.thinkingLevel??"",onChange:d=>ve({...ee,thinkingLevel:d.target.value}),children:[s.jsx("option",{value:"",children:i("tplThinkingFollowMain")}),cc.map(d=>s.jsx("option",{value:d,children:i(`thinking.${d}`)},d))]})]}),s.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:`${i("tplSystemPromptLabel")}${o==="zh"?":":": "}${i("tplSystemPromptPlaceholder")}`,value:ee.systemPrompt,onChange:d=>ve({...ee,systemPrompt:d.target.value})}),s.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:`${i("tplSystemPromptLabel")}: ${i("tplSystemPromptEnPlaceholder")}`,value:ee.systemPromptEn??"",onChange:d=>ve({...ee,systemPromptEn:d.target.value})}),s.jsxs("div",{className:"tpl-pick-block",children:[s.jsx("div",{className:"tpl-pick-head",children:s.jsxs("span",{children:[i("tplSkillsLabel")," · ",i("tplWhitelistHint")]})}),u.skills.length===0?s.jsx("p",{className:"set-hint",children:i("noSkills")}):s.jsx("div",{className:"tpl-pick",children:u.skills.map(d=>s.jsxs("label",{className:`tpl-chip${ee.enabledSkills.includes(d.name)?" on":""}`,children:[s.jsx("input",{type:"checkbox",checked:ee.enabledSkills.includes(d.name),onChange:q=>{const fe=q.target.checked;ve({...ee,enabledSkills:fe?[...ee.enabledSkills,d.name]:ee.enabledSkills.filter(Ke=>Ke!==d.name)})}}),d.name]},d.name))})]}),s.jsxs("div",{className:"tpl-pick-block",children:[s.jsx("div",{className:"tpl-pick-head",children:s.jsxs("span",{children:[i("tplExtensionsLabel")," · ",i("tplWhitelistHint")]})}),u.extensions.length===0?s.jsx("p",{className:"set-hint",children:i("noExtensions")}):s.jsx("div",{className:"tpl-pick",children:u.extensions.map(d=>s.jsxs("label",{className:`tpl-chip${ee.enabledExtensions.includes(d.id)?" on":""}`,children:[s.jsx("input",{type:"checkbox",checked:ee.enabledExtensions.includes(d.id),onChange:q=>{const fe=q.target.checked;ve({...ee,enabledExtensions:fe?[...ee.enabledExtensions,d.id]:ee.enabledExtensions.filter(Ke=>Ke!==d.id)})}}),d.name]},d.id))})]}),s.jsxs("div",{className:"tpl-actions",children:[s.jsx("button",{type:"button",className:"set-save-btn",disabled:!ee.name.trim(),onClick:()=>{ie({type:"save_subagent_template",template:{...ee,name:ee.name.trim()}}),ve(null)},children:i("tplSave")}),s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>ve(null),children:i("tplCancel")})]})]}),u.subagentTemplates.length===0?s.jsx("p",{className:"set-empty",children:i("noSubagentTemplates")}):s.jsx("div",{className:"set-list",children:u.subagentTemplates.map(d=>s.jsxs("div",{className:"set-row",children:[s.jsxs("div",{className:"set-row-info",children:[s.jsxs("div",{className:"set-row-name",children:[d.name,u.subagentDefaultTemplates.includes(d.name)&&s.jsx("span",{className:"tpl-badge default",children:i("tplDefaultBadge")}),!d.enabled&&s.jsx("span",{className:"tpl-badge",children:i("subagentTemplateClosed")})]}),s.jsxs("div",{className:"set-row-desc",children:[(o!=="zh"&&d.descriptionEn?d.descriptionEn:d.description)||`${d.promptMode==="replace"?i("promptModeReplace"):i("promptModeAppend")}`,d.model?` · ${i("tplModelLabel")} ${d.model}`:` · ${i("subagentFollowMain")}`,d.thinkingLevel?` · ${i("tplThinkingLabel")} ${l(`thinking.${d.thinkingLevel}`)}`:"",d.enabledSkills.length>0&&` · ${i("tplSkillsLabel")} ${d.enabledSkills.length}`,d.enabledExtensions.length>0&&` · ${i("tplExtensionsLabel")} ${d.enabledExtensions.length}`,!d.description&&d.enabledSkills.length===0&&d.enabledExtensions.length===0&&` · ${i("tplInherit")}`]})]}),s.jsxs("div",{className:"set-row-actions",children:[s.jsx("button",{type:"button",className:`set-switch${d.enabled?" on":""}`,role:"switch","aria-checked":d.enabled,title:`${d.enabled?i("subagentTemplateDisable"):i("subagentTemplateEnable")} · ${i("subagentTemplateOffHint")}`,onClick:()=>ie({type:"save_subagent_template",template:{...d,enabled:!d.enabled}}),children:s.jsx("span",{className:"set-switch-knob"})}),s.jsx("button",{type:"button",className:"dd-refresh",title:i("subagentTemplateEdit"),onClick:()=>ve({...d}),children:i("subagentTemplateEdit")}),S===d.name?s.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("uninstallConfirmHint"),onClick:()=>{ie({type:"delete_subagent_template",name:d.name}),de(null)},children:i("uninstallConfirm")}):s.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("tplDelete"),onClick:()=>de(d.name),children:s.jsx(dt,{})})]})]},d.name))})]}),tn&&s.jsx(il,{plugin:tn.plugin,epoch:e.pluginsEpoch,send:ie,className:"set-plugin-page"})]})]}),s.jsx("div",{className:"modal-actions",children:s.jsx("button",{type:"button",className:"dd-refresh",onClick:a,children:i("close")})})]})})}function qb(e,t){const n=Math.max(0,Date.now()-e),a=Math.floor(n/6e4);if(a<1)return t("bgTaskJustNow");if(a<60)return t("bgTaskMinutes",{n:a});const i=Math.floor(a/60);return i<24?t("bgTaskHours",{n:i}):t("bgTaskDays",{n:Math.floor(i/24)})}function Wb({servers:e,onClose:t}){const n=Pe(),[a,i]=c.useState(new Set),o=l=>i(u=>{const p=new Set(u);return p.has(l)?p.delete(l):p.add(l),p});return c.useEffect(()=>{ie({type:"list_bg_servers"})},[]),s.jsx("div",{className:"modal-backdrop",onClick:t,children:s.jsxs("div",{className:"bg-task-modal",onClick:l=>l.stopPropagation(),children:[s.jsxs("div",{className:"bg-task-head",children:[s.jsxs("span",{className:"bg-task-title",children:[s.jsx(In,{})," ",n("bgTasks"),e.length>0&&s.jsx("em",{className:"bg-task-count",children:e.length})]}),s.jsx("button",{type:"button",className:"btn",title:n("close"),onClick:t,children:s.jsx(tt,{})})]}),e.length===0?s.jsxs("div",{className:"bg-task-empty",children:[s.jsx(In,{}),s.jsx("span",{children:n("bgTasksEmpty")}),s.jsx("small",{children:n("bgTasksDesc")})]}):s.jsx("ul",{className:"bg-task-list",children:e.map(l=>{const u=!!l.taskId,p=l.taskId??String(l.port);return s.jsxs("li",{className:"bg-task-item",children:[s.jsx("span",{className:"bg-task-icon",title:u?l.plugin:n("bgTaskPort")}),s.jsxs("div",{className:"bg-task-info",children:[s.jsxs("div",{className:"bg-task-line1",children:[u?s.jsxs("span",{className:"bg-task-port",title:l.taskId,children:["🧩 ",l.plugin]}):s.jsxs("span",{className:"bg-task-port",children:[":",l.port]}),l.name&&s.jsx("span",{className:"bg-task-name",children:l.name})]}),s.jsxs("div",{className:"bg-task-line2",children:[!u&&s.jsxs("span",{children:[n("bgTaskPid")," ",l.pid]}),s.jsxs("span",{children:[n("bgTaskSince")," ",qb(l.since,n)]}),u&&l.status&&s.jsx("span",{className:"bg-task-status",children:l.status})]}),l.command&&s.jsxs("button",{type:"button",className:`bg-task-cmd ${a.has(p)?"open":""}`,title:`${n("bgTaskCommand")}: ${l.command}`,onClick:()=>o(p),children:[s.jsx(Jn,{}),s.jsx("code",{children:l.command})]})]}),s.jsxs("button",{type:"button",className:"btn bg-task-stop",title:n("bgTaskStop"),onClick:()=>ie(u?{type:"kill_background_server",taskId:l.taskId}:{type:"kill_background_server",port:l.port}),children:[s.jsx(Sn,{}),s.jsx("span",{children:n("bgTaskStop")})]})]},p)})}),s.jsxs("div",{className:"bg-task-foot",children:[s.jsxs("button",{type:"button",className:"btn",title:n("bgTaskRefresh"),onClick:()=>ie({type:"list_bg_servers"}),children:[s.jsx(jt,{}),s.jsx("span",{children:n("bgTaskRefresh")})]}),s.jsxs("button",{type:"button",className:"btn bg-task-stopall",disabled:e.length===0,title:n("bgTaskStopAll"),onClick:()=>ie({type:"kill_background_servers"}),children:[s.jsx(Sn,{}),s.jsx("span",{children:n("bgTaskStopAll")})]})]})]})})}function Kb(e,t){return e.toLowerCase().includes(t)}function Yb({open:e,projects:t,fileSearch:n,sessionSearch:a,onClose:i,onSwitchSession:o,onSwitchProject:l,onPreviewFile:u}){const p=Pe(),h=wt("cwd"),b=c.useRef(null),[m,f]=c.useState(""),x=c.useDeferredValue(m),[v,N]=c.useState(0),B=c.useRef(1),V=c.useRef(0),W=c.useRef(null);c.useEffect(()=>{if(!e)return;ie({type:"list_sessions"}),ie({type:"list_projects"});const F=m.trim();if(F){const Y=++B.current;V.current=Y,j(!0),ie({type:"search_files",reqId:Y,query:F}),ie({type:"search_sessions",reqId:Y,query:F})}requestAnimationFrame(()=>b.current?.select())},[e]);const[I,j]=c.useState(!1);c.useEffect(()=>{W.current&&clearTimeout(W.current);const F=x.trim();if(!F){j(!1);return}return W.current=setTimeout(()=>{const Y=++B.current;V.current=Y,j(!0),ie({type:"search_files",reqId:Y,query:F}),ie({type:"search_sessions",reqId:Y,query:F})},300),()=>{W.current&&clearTimeout(W.current)}},[x]);const X=x.trim().toLowerCase(),w=c.useMemo(()=>!X||!a||a.reqId!==V.current||!a.ok?[]:a.results,[a,X]),ce=c.useMemo(()=>X?t.filter(F=>Kb(F.path,X)).slice(0,10):[],[t,X]),be=c.useMemo(()=>!X||!n||n.reqId!==V.current||!n.ok?[]:n.results,[n,X]);c.useEffect(()=>{n&&n.reqId===V.current&&a&&a.reqId===V.current&&V.current!==0&&j(!1)},[n,a]);const $=!!n&&n.ok&&n.truncated,K=c.useMemo(()=>[...w.map(F=>({kind:"session",path:F.path,anchors:F.anchors})),...ce.map(F=>({kind:"project",path:F.path})),...be.filter(F=>F.type==="file").map(F=>({kind:"file",path:F.path,name:F.name}))],[w,ce,be]);c.useEffect(()=>{N(0)},[x]);const J=c.useCallback(F=>{if(F)if(F.kind==="session")o(F.path,F.anchors),i();else if(F.kind==="project"){l(F.path),ie({type:"list_sessions"}),ie({type:"list_projects"});const Y=x.trim();if(Y){const D=++B.current;V.current=D,j(!0),ie({type:"search_files",reqId:D,query:Y}),ie({type:"search_sessions",reqId:D,query:Y})}}else u(F.path,F.name)},[o,l,u,x]);c.useEffect(()=>{if(!e)return;const F=Y=>{Y.key==="Escape"?(Y.preventDefault(),Y.stopPropagation(),i()):Y.key==="ArrowDown"?(Y.preventDefault(),N(D=>Math.min(D+1,K.length-1))):Y.key==="ArrowUp"?(Y.preventDefault(),N(D=>Math.max(D-1,0))):Y.key==="Enter"&&(Y.preventDefault(),J(K[v]))};return window.addEventListener("keydown",F,!0),()=>window.removeEventListener("keydown",F,!0)},[K,v,J,i,e]);const L=w.length+ce.length+be.length,H=(F,Y,D)=>s.jsxs("div",{className:"gs-section-head",children:[D,s.jsx("span",{children:F}),s.jsx("em",{children:Y})]});let T=-1;return e?s.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:i,children:s.jsxs("div",{className:"gs-modal",onClick:F=>F.stopPropagation(),children:[s.jsxs("div",{className:"gs-input-row",children:[s.jsx(An,{}),s.jsx("input",{ref:b,type:"text",value:m,placeholder:p("gsPlaceholder"),onChange:F=>f(F.target.value)}),s.jsx("button",{type:"button",className:"gs-close",title:p("close"),onClick:i,children:s.jsx(tt,{})})]}),s.jsxs("div",{className:"gs-results",children:[!X&&s.jsx("div",{className:"gs-empty",children:p("gsHint")}),X&&L===0&&!$&&s.jsx("div",{className:"gs-empty",children:p(I?"gsSearching":"gsNoResults")}),w.length>0&&s.jsxs("div",{className:"gs-section",children:[H(p("gsSessions"),w.length,s.jsx(ts,{})),w.map(F=>{T++;const Y=T;return s.jsxs("button",{type:"button",className:Y===v?"gs-item active":"gs-item",onMouseEnter:()=>N(Y),onClick:()=>J({kind:"session",path:F.path,anchors:F.anchors}),children:[s.jsxs("span",{className:"gs-item-title",children:[F.name||F.path.split(/[\\/]/).pop(),s.jsx("em",{className:"gs-item-meta",children:F.messageCount})]}),s.jsx("span",{className:"gs-item-sub",children:F.firstMessage})]},F.path)})]}),ce.length>0&&s.jsxs("div",{className:"gs-section",children:[H(p("gsProjects"),ce.length,s.jsx(Bt,{})),ce.map(F=>{T++;const Y=T,D=h&&F.path===h;return s.jsxs("button",{type:"button",className:Y===v?"gs-item active":"gs-item",onMouseEnter:()=>N(Y),onClick:()=>J({kind:"project",path:F.path}),children:[s.jsxs("span",{className:"gs-item-title",children:[F.path.split(/[\\/]/).pop(),D&&s.jsx("em",{className:"gs-item-meta",children:p("gsCurrentProject")})]}),s.jsx("span",{className:"gs-item-sub",children:F.path})]},F.path)})]}),(be.length>0||X&&$)&&s.jsxs("div",{className:"gs-section",children:[H(p("gsFiles"),be.length,s.jsx(wo,{})),be.map(F=>{T++;const Y=T;return s.jsxs("button",{type:"button",className:Y===v?"gs-item active":"gs-item",disabled:F.type==="dir",title:F.type==="dir"?void 0:p("gsOpenPreview"),onMouseEnter:()=>N(Y),onClick:()=>{F.type==="file"&&J({kind:"file",path:F.path,name:F.name})},children:[s.jsx("span",{className:"gs-item-title",children:F.name}),s.jsx("span",{className:"gs-item-sub",children:F.path})]},`${F.type}:${F.path}`)}),$&&s.jsx("div",{className:"gs-truncated",children:p("gsTruncated")})]})]}),s.jsxs("div",{className:"gs-foot",children:[s.jsxs("span",{children:["↑↓ ",p("gsNavigate")]}),s.jsxs("span",{children:["Enter ",p("gsOpen")]}),s.jsxs("span",{children:["Esc ",p("gsCloseHint")]})]})]})}):null}const Sa=5e3;function Gb({file:e,content:t,onAddLines:n,onAttach:a,onClose:i}){const o=Pe(),[l,u]=c.useState(null),[p,h]=c.useState(!1),[b,m]=c.useState(null),[f,x]=c.useState(!1),[v,N]=c.useState(!1),[B,V]=c.useState(!1),[W,I]=c.useState(""),[j,X]=c.useState(!0),[w,ce]=c.useState(!0),[be,$]=c.useState(!1),K=c.useRef(!1),[J,L]=c.useState(!0),[H,T]=c.useState(!1),[F,Y]=c.useState(100),D=c.useRef(0),ae=c.useRef(!1),ee=c.useRef(null);c.useEffect(()=>{h(!0),u(null),m(null),V(!1),I(""),X(!0),ce(!0),$(!1),K.current=!1,ie({type:"read_file",path:e.path})},[e.path]),c.useEffect(()=>{t&&t.path===e.path&&(u(t),B||I(t.text),h(!1))},[t,B,e.path]),c.useEffect(()=>{const Z=y=>{if(y.key==="Escape"){qe();return}if((y.ctrlKey||y.metaKey)&&y.key.toLowerCase()==="s"&&B){y.preventDefault(),Ce();return}const P=y.target,le=P&&(P.tagName==="INPUT"||P.tagName==="TEXTAREA"||P.isContentEditable);(y.ctrlKey||y.metaKey)&&y.key.toLowerCase()==="a"&&!le&&(y.preventDefault(),pe())};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[i,l,B,W]),c.useEffect(()=>{const Z=()=>{ae.current=!1,x(!1)};return window.addEventListener("mouseup",Z),()=>window.removeEventListener("mouseup",Z)},[]);const ve=c.useMemo(()=>{if(!l)return[];const Z=l.text.split(`
361
+ `);return Z.length>0&&Z[Z.length-1]===""&&Z.pop(),Z.slice(0,Sa)},[l]),S=l?.lines??0,de=S>Sa,ue=(Z,y)=>{if(y){const P=D.current>0?D.current:Z;m({start:Math.min(P,Z),end:Math.max(P,Z)})}else D.current=Z,m({start:Z,end:Z})},pe=()=>{ve.length!==0&&(D.current=1,m({start:1,end:ve.length}))},ke=()=>{b&&(n(e.path,e.name,b.start,b.end),N(!0),ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>N(!1),1400))},Oe=l!==null&&l.kind==="text"&&!l.binary&&!l.truncated,ye=()=>{I(l?.text??""),V(!1),K.current&&(As(e.name)&&X(!0),Is(e.name)&&ce(!0))},we=()=>{if(B){if(W!==(l?.text??"")&&!window.confirm(o("discardFileChanges")))return;ye();return}!Oe||!l||(K.current=As(e.name)&&j||Is(e.name)&&w,As(e.name)&&X(!1),Is(e.name)&&ce(!1),m(null),I(l.text),V(!0))},Ce=()=>{!B||!l||!Oe||ie({type:"write_file",path:e.path,text:W})&&(V(!1),K.current&&(As(e.name)&&X(!0),Is(e.name)&&ce(!0)),m(null))},qe=()=>{B&&W!==(l?.text??"")&&!window.confirm(o("discardFileChanges"))||i()},Be=Z=>{Y(Math.min(200,Math.max(50,Z)))},se=b?b.end-b.start+1:0,Te=l?.binary??!1,De=l?.truncated??!1,Re=l?.kind??"text",Ye=As(e.name),A=Is(e.name),Q=Ye&&j&&!B&&Re==="text"&&!Te,z=A&&w&&!B&&Re==="text"&&!Te,ge=Z=>Ft(lt(`/api/file?clientId=${encodeURIComponent(Fn())}&path=${encodeURIComponent(Z)}`)),oe=Z=>{const y=Z.split("/").map(Ee=>encodeURIComponent(Ee)).join("/"),le=/^[A-Za-z]:([\\/]|$)/.test(Z)||Z.startsWith("/")?`/api/preview/__abs__/${y}`:`/api/preview/${y}`;return Ft(lt(`${le}?clientId=${encodeURIComponent(Fn())}${be?"&allowJs=1":""}`))};return s.jsx("div",{className:`fp-overlay ${H?"fullscreen":""}`,onMouseDown:Z=>{Z.target===Z.currentTarget&&qe()},children:s.jsxs("div",{className:`fp ${H?"fullscreen":""}`,style:{"--fp-zoom":F/100},children:[s.jsxs("div",{className:"fp-head",children:[s.jsx("span",{className:"fp-name",title:e.path,children:e.name}),s.jsx("span",{className:"fp-path",children:e.path}),s.jsxs("span",{className:"fp-meta",children:[l&&Re==="text"&&!Te&&o("fileLines",{n:S}),l&&` · ${zb(l.size)}`]}),s.jsxs("span",{className:"fp-head-actions",children:[Ye&&Re==="text"&&!Te&&l&&s.jsx("button",{type:"button",className:`fp-attach markdown ${j?"on":""}`,"data-tip":o(j?"showMarkdownSource":"showMarkdownPreview"),disabled:B,onClick:()=>X(Z=>!Z),children:j?s.jsx(jn,{}):s.jsx(Pi,{})}),A&&Re==="text"&&!Te&&l&&s.jsx("button",{type:"button",className:`fp-attach html ${w?"on":""}`,"data-tip":o(w?"showHtmlSource":"showHtmlPreview"),disabled:B,onClick:()=>ce(Z=>!Z),children:w?s.jsx(Pi,{}):s.jsx(jn,{})}),Re==="text"&&!Te&&l&&s.jsx("button",{type:"button",className:`fp-attach edit ${B?"on":""}`,"data-tip":o(De?"fileEditTruncated":B?"exitEditFile":"editFile"),disabled:!Oe&&!B,onClick:we,children:s.jsx(Ys,{})}),Re==="text"&&!Te&&!Q&&!z&&s.jsx("button",{type:"button",className:`fp-attach wrap ${J?"on":""}`,"data-tip":o(J?"disableWrap":"enableWrap"),onClick:()=>L(Z=>!Z),children:s.jsx($u,{})}),Re==="text"&&l&&s.jsxs("span",{className:"fp-zoom",children:[s.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":o("zoomOut"),disabled:F<=50,onClick:()=>Be(F-10),children:s.jsx(ku,{})}),s.jsxs("button",{type:"button",className:"fp-zoom-val",title:o("resetZoom"),onClick:()=>Y(100),children:[F,"%"]}),s.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":o("zoomIn"),disabled:F>=200,onClick:()=>Be(F+10),children:s.jsx(Nu,{})})]}),Re!=="video"&&Re!=="none"&&s.jsx("button",{type:"button",className:"fp-attach inline","data-tip":o("attachInlineTip"),onClick:()=>a(e.path,e.name,"inline"),children:s.jsx(yt,{})}),s.jsx("button",{type:"button",className:"fp-attach ref","data-tip":o("referenceTip"),onClick:()=>a(e.path,e.name,"reference"),children:s.jsx(ja,{})}),s.jsx("button",{type:"button",className:`fp-attach full ${H?"on":""}`,"data-tip":o(H?"exitFullscreen":"fullscreen"),onClick:()=>T(Z=>!Z),children:H?s.jsx(ju,{}):s.jsx(Lu,{})}),s.jsx("button",{type:"button",className:"fp-close",title:o("close"),onClick:qe,children:s.jsx(tt,{})})]})]}),De&&Re==="text"&&!Te&&s.jsx("div",{className:"fp-notice",children:o("previewTruncated")}),p&&!l&&s.jsx("div",{className:"fp-empty",children:o("loading")}),!p&&Re==="none"&&!Te&&s.jsx("div",{className:"fp-empty",children:o("previewNotSupported")}),!p&&Re==="image"&&s.jsx("div",{className:"fp-media-wrap",children:s.jsx("img",{className:"fp-media",src:ge(e.path),alt:e.name})}),!p&&Re==="video"&&s.jsx("div",{className:"fp-media-wrap",children:s.jsx("video",{className:"fp-media",src:ge(e.path),controls:!0,preload:"metadata"})}),!p&&z&&l&&s.jsxs("div",{className:"fp-html",children:[s.jsxs("div",{className:"fp-html-bar",children:[s.jsx("span",{className:"fp-html-hint",title:o(be?"htmlJsOnTip":"htmlJsOffTip"),children:o(be?"htmlJsOn":"htmlJsOff")}),s.jsx("button",{type:"button",className:`fp-html-js ${be?"on":""}`,"data-tip":o(be?"htmlDisableJs":"htmlEnableJs"),onClick:()=>$(Z=>!Z),children:o(be?"htmlDisableJs":"htmlEnableJs")})]}),s.jsx("iframe",{className:"fp-html-frame",src:oe(e.path),title:e.name,sandbox:be?"allow-scripts":"",referrerPolicy:"no-referrer"},be?"js":"nojs")]}),!p&&Q&&l&&s.jsx("div",{className:"fp-markdown msg-text",children:s.jsx("div",{className:"fp-markdown-zoom",children:s.jsx(pt,{text:l.text})})}),!p&&Te&&Re!=="image"&&Re!=="video"&&l&&s.jsxs("div",{className:"fp-hex-wrap",children:[s.jsxs("div",{className:"fp-notice",children:[o("binaryFile"),l.truncated&&o("binaryHexTruncated")]}),s.jsx("pre",{className:"fp-hex",children:l.text})]}),!p&&B&&Re==="text"&&!Te&&l&&s.jsx("textarea",{className:`fp-editor ${J?"":"no-wrap"}`,value:W,onChange:Z=>I(Z.target.value),wrap:J?"soft":"off",spellCheck:!1,autoFocus:!0}),!p&&!Q&&!z&&!B&&Re==="text"&&!Te&&l&&ve.length===0&&s.jsx("div",{className:"fp-empty",children:o("emptyFile")}),!p&&!Q&&!z&&!B&&Re==="text"&&!Te&&ve.length>0&&s.jsxs("div",{className:`fp-code ${f?"dragging":""} ${J?"":"no-wrap"}`,onMouseDown:Z=>{Z.button===0&&Z.preventDefault()},children:[ve.map((Z,y)=>{const P=y+1,le=b!==null&&P>=b.start&&P<=b.end;return s.jsxs("div",{className:`fp-line ${le?"sel":""}`,onMouseDown:Ee=>{Ee.button===0&&(ue(P,Ee.shiftKey),ae.current=!0,x(!0))},onMouseEnter:()=>{ae.current&&ue(P,!0)},children:[s.jsx("span",{className:"fp-num",children:P}),s.jsx("span",{className:"fp-code-text",children:Z})]},P)}),de&&s.jsx("div",{className:"fp-lines-note",children:o("previewLinesTruncated",{n:Sa})})]}),s.jsx("div",{className:"fp-foot",children:B?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"fp-hint",children:o("editFile")}),s.jsxs("div",{className:"fp-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:we,children:o("cancel")}),s.jsxs("button",{type:"button",className:"btn primary",disabled:W===(l?.text??""),onClick:Ce,children:[s.jsx(Su,{})," ",o("saveFile")]})]})]}):!Q&&!z&&Re==="text"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"fp-hint",children:b?o("selectedRange",{n:se,start:b.start,end:b.end}):o("selectLinesHint")}),s.jsxs("div",{className:"fp-actions",children:[s.jsx("button",{type:"button",className:"btn",disabled:ve.length===0,onClick:pe,children:o("selectAll")}),s.jsx("button",{type:"button",className:"btn",disabled:!b,onClick:()=>m(null),children:o("clearSelection")}),s.jsxs("button",{type:"button",className:"btn primary",disabled:!b||Te,onClick:ke,children:[v?s.jsx(Rt,{}):null,o(v?"addedToChat":"addToChat")]})]})]})})]})})}function As(e){const t=e.toLowerCase();return t.endsWith(".md")||t.endsWith(".markdown")}function Is(e){const t=e.toLowerCase();return t.endsWith(".html")||t.endsWith(".htm")||t.endsWith(".xhtml")}function zb(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}const Ic="pi-web-sounds",js={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function jc(){try{const e=localStorage.getItem(Ic);if(!e)return{...js};const t=JSON.parse(e),n={...js,...t};for(const a of["enabled","question","done","start","error"])typeof n[a]!="boolean"&&(n[a]=js[a]);return typeof n.volume!="number"||!Number.isFinite(n.volume)?n.volume=js.volume:n.volume=Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...js}}}function Vb(e){try{localStorage.setItem(Ic,JSON.stringify(e))}catch{}}let Rs=null;function Qb(){try{if(!Rs){const e=window.AudioContext??window.webkitAudioContext;if(!e)return null;Rs=new e}return Rs.state==="suspended"&&Rs.resume(),Rs}catch{return null}}const Xb=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],Jb=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],Zb=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],e1=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],t1={question:Xb,done:Jb,start:Zb,error:e1};function s1(e,t,n){const a=e.createOscillator(),i=e.createGain();a.type=t.type,a.frequency.value=t.freq;const o=e.currentTime+t.start,l=Math.max(1e-4,t.peak*n);i.gain.setValueAtTime(1e-4,o),i.gain.exponentialRampToValueAtTime(l,o+.012),i.gain.exponentialRampToValueAtTime(1e-4,o+t.dur),a.connect(i),i.connect(e.destination),a.start(o),a.stop(o+t.dur+.05)}function ds(e,t=jc()){if(!t.enabled||!t[e])return;const n=Qb();if(!n)return;const a=Math.max(0,Math.min(1,t.volume/100));for(const i of t1[e])s1(n,i,a)}const n1=c.lazy(()=>hu(()=>import("./TerminalPanel-BytY8dx7.js"),__vite__mapDeps([0,1,2,3,4])).then(e=>({default:e.TerminalPanel})));function a1({notice:e,onDismiss:t}){const n=Pe(),{locale:a}=Ut(),i=a!=="zh"&&e.textEn?e.textEn:e.text,[o,l]=c.useState(!1);c.useEffect(()=>{if(o)return;const p=setTimeout(()=>t(e.id),e.level==="error"?12e3:7e3);return()=>clearTimeout(p)},[o,e.id,e.level,t]);const u=e.level==="error"?Gu:e.level==="warning"?Yu:Bu;return s.jsxs("div",{className:`notice notice-${e.level}${o?" paused":""}`,role:"status",onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[s.jsx(u,{className:"notice-icon"}),s.jsx("span",{className:"notice-text",children:i}),s.jsx("button",{type:"button",className:"notice-close",title:n("close"),onClick:()=>t(e.id),children:s.jsx(tt,{})})]})}const i1=[],Rc=180,Lc=520,Dc=240,Pc=e=>`pi-web-ui:${e}-panel-width`;function uo(e){const t=Number(localStorage.getItem(Pc(e)));return Number.isFinite(t)&&t>=Rc&&t<=Lc?t:Dc}const ii=e=>`pi-web-ui:${e}-panel-collapsed`;function po(e){return localStorage.getItem(ii(e))==="1"}function mo({side:e,width:t,onResize:n}){const a=Pe(),i=c.useCallback(o=>{o.preventDefault();const l=o.clientX,u=t;let p=u;const h=m=>{const f=e==="left"?m.clientX-l:l-m.clientX;p=Math.min(Lc,Math.max(Rc,Math.round(u+f))),n(p)},b=()=>{window.removeEventListener("pointermove",h),window.removeEventListener("pointerup",b),document.body.classList.remove("panel-resizing"),localStorage.setItem(Pc(e),String(p))};window.addEventListener("pointermove",h),window.addEventListener("pointerup",b),document.body.classList.add("panel-resizing")},[e,t,n]);return s.jsx("div",{className:`resize-handle resize-${e}`,title:a("dragToResize"),onPointerDown:i,onDoubleClick:()=>n(Dc)})}function ho({side:e,onClick:t}){const n=Pe();return s.jsx("button",{type:"button",className:`panel-rail panel-rail-${e}`,title:n("expandPanel"),onClick:t,children:e==="left"?s.jsx(So,{}):s.jsx(_o,{})})}const Oc="pi-web-ui:plugin-path-grants";function Mc(){try{const e=localStorage.getItem(Oc),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function r1(e){try{const t=[...new Set([...Mc(),e])];localStorage.setItem(Oc,JSON.stringify(t))}catch{}}function o1(){const e=Pe(),{locale:t}=Ut(),{chat:n,send:a,dismissNotice:i,pushNotice:o,terminal:l}=Ep(),u=c.useRef(!1);c.useEffect(()=>{!n.ready||!n.settings||u.current||n.settings.quickPhrasesSeeded||(u.current=!0,n.settings.quickPhrases.length===0&&a({type:"set_settings",quickPhrases:Qn[t]??Qn.en,quickPhrasesSeeded:!0}))},[n.ready,n.settings,a,t]);const p=n.state?.cwd??"",h=Nc();c.useEffect(()=>{const O=h?Sb(p):"";document.title=O?`${O} — pi-web-ui`:e("docTitle")},[p,h,e]);const[b,m]=c.useState([]);c.useEffect(()=>(Hi(O=>m(he=>wg(he,O))),()=>Hi(null)),[]);const[f,x]=c.useState(null),[v,N]=c.useState(!1);c.useEffect(()=>{const O=()=>N(!1);return window.addEventListener("drop",O,!0),()=>window.removeEventListener("drop",O,!0)},[]);const[B,V]=c.useState("chat"),W=O=>!n.tabs||O==="chat"||n.tabs.includes(O),I=B.startsWith("plugin:")?"plugins":B,j=W(I)?B:"chat",X=c.useMemo(()=>n.plugins.filter(O=>!n.settings?.disabledPlugins?.includes(O.id)),[n.plugins,n.settings?.disabledPlugins]),w=c.useMemo(()=>bc(n.plugins,{locale:t,t:O=>e(O),disabledPlugins:n.settings?.disabledPlugins??[],layout:n.settings?.uiLayout}),[n.plugins,n.settings?.disabledPlugins,n.settings?.uiLayout,t,e]),ce=c.useMemo(()=>w["topbar.primary"].filter(O=>!O.hidden),[w]),be=c.useMemo(()=>[...w["topbar.primary"].filter(O=>O.hidden),...w["topbar.overflow"]],[w]),$=c.useCallback(O=>{const he=(O.action??"").trim();if(O.kind==="view"||(!he||he==="view")&&O.source!=="host"){V(O.view??`plugin:${O.source.startsWith("plugin:")?O.source.slice(7):""}`);return}if(!he)return;const Se=O.source.startsWith("plugin:")?O.source.slice(7):"";sp(Se,he,O.id,{loadBundle:async ze=>{const Je=L.current.plugins.find(At=>At.id===ze);return Je?Ua(Je,L.current.pluginsEpoch):!1}}).then(ze=>{ze||o("info",e("pluginUiNoHandler"))})},[e,o]),[K,J]=c.useState([]);c.useEffect(()=>rp(J),[]),c.useEffect(()=>{Qf(a),Xf(X,n.pluginsEpoch),op(X,n.pluginsEpoch)},[X,n.pluginsEpoch,a]);const L=c.useRef(n);L.current=n;const H=c.useRef(V);H.current=V,c.useEffect(()=>(nr(tp({send:a,isReady:()=>!!L.current.state,setView:O=>H.current(O),getCwd:()=>L.current.state?.cwd??"",getWorkspaceRoots:()=>L.current.state?.workspaceRoots??[],listSessions:()=>{const O=L.current,he=O.state?.cwd??"";return[...O.conversations.map(Se=>({id:Se.id,title:Se.title,cwd:Se.cwd||he,kind:"running",isStreaming:Se.isStreaming})),...O.sessions.map(Se=>({id:Se.path,title:Se.name||Se.firstMessage||Se.path,cwd:he,kind:"history"}))]},getConversationId:()=>L.current.state?.conversationId??null,isConversationBlank:()=>(L.current.state?.messages.length??0)===0,listProjects:()=>L.current.projects.map(O=>O.path),grantedPaths:Mc,grantPath:r1,confirm:O=>new Promise(he=>A({path:O.path,resolve:he})),loadPluginBundle:O=>{const he=L.current.plugins.find(Se=>Se.id===O);return he?Ua(he,L.current.pluginsEpoch):Promise.resolve(!1)}})),()=>nr(null)),[a]);const[T,F]=c.useState(()=>uo("left")),[Y,D]=c.useState(()=>uo("right")),ae=c.useCallback(O=>F(O),[]),ee=c.useCallback(O=>D(O),[]),[ve,S]=c.useState(()=>po("left")),[de,ue]=c.useState(()=>po("right")),pe=c.useCallback(()=>{S(O=>(localStorage.setItem(ii("left"),O?"0":"1"),!O))},[]),ke=c.useCallback(()=>{ue(O=>(localStorage.setItem(ii("right"),O?"0":"1"),!O))},[]),[Oe,ye]=c.useState(null),[we,Ce]=c.useState(()=>window.matchMedia("(max-width: 768px)").matches);c.useEffect(()=>{const O=window.matchMedia("(max-width: 768px)"),he=Se=>Ce(Se.matches);return O.addEventListener("change",he),()=>O.removeEventListener("change",he)},[]);const[qe,Be]=c.useState(!1),[se,Te]=c.useState(!1),[De,Re]=c.useState(!1),[Ye,A]=c.useState(null),[Q,z]=c.useState(()=>new Set),ge=(O,he)=>{a({type:"plugin_path_response",id:O,ok:he}),z(Se=>new Set(Se).add(O))},oe=n.pathRequests.find(O=>!Q.has(O.id))??null,Z=xc(),[y,P]=c.useState(!1),[le,Ee]=c.useState(!1),[Ae,Me]=c.useState(null);c.useEffect(()=>{if(!Ae)return;const O=setTimeout(()=>Me(null),15e3);return()=>clearTimeout(O)},[Ae]),c.useEffect(()=>{const O=Se=>{const ze=Se.detail,Je=ze?.title||e("pluginCommandFallback"),At=ze?.command;if(!At||!n.ready)return;const mt={name:Je,command:At,cwd:"${pwd}"},Tt=n.terminals.find(vs=>vs.title===Je);if(Tt)l.restart(Tt.id),a({type:"run_command",terminalId:Tt.id,conversationId:Tt.conversationId,command:mt,cols:80,rows:24});else{const vs=St();l.create({id:vs,conversationId:n.activeConversationId||n.state?.conversationId||"",title:Je,cwd:n.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:mt})}V("terminal")};window.addEventListener("pi-web-ui:plugin-run-command",O);const he=Se=>{const ze=Se.detail;typeof ze=="string"&&ze&&a({type:"switch_conversation",id:ze})};return window.addEventListener("pi-web-ui:switch-conversation",he),()=>{window.removeEventListener("pi-web-ui:plugin-run-command",O),window.removeEventListener("pi-web-ui:switch-conversation",he)}},[n,l,a]),c.useEffect(()=>{const O=he=>{!(he.ctrlKey||he.metaKey)||he.key.toLowerCase()!=="k"||(he.preventDefault(),Ee(Se=>!Se))};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[]);const[Le,Ge]=c.useState(jc),{themes:R,theme:He,switchTheme:C,reloadThemes:_}=t0();Fb();const me=c.useRef(null),Ne=c.useRef(null),$e=c.useRef(null),Ie=c.useRef(0),Qe=c.useRef(!1),gt=c.useRef(n.terminals);c.useEffect(()=>{Vb(Le)},[Le]),c.useEffect(()=>{const O=gt.current;gt.current=n.terminals;for(const he of n.terminals){const Se=he.command?.command??"";!O.find(Je=>Je.id===he.id)?.running||he.running||(Se.startsWith("pi remove ")?a({type:"extensions_reload"}):Se.startsWith("pi-web-ui install ")||Se.startsWith("pi-web-ui uninstall ")?a({type:"plugins_reload"}):Se.startsWith("npm i -g ")&&(a({type:"extensions_reload"}),a({type:"plugins_reload"}),a({type:"check_updates_all",force:!0})))}},[n.terminals,a]),c.useEffect(()=>{const O=n.state?.isStreaming??!1,he=me.current;me.current=O,he!==null&&(!he&&O?ds("start",Le):he&&!O&&(ds("done",Le),cn(e("notifyDoneTitle"),e("notifyDoneBody"))))},[n.state?.isStreaming,Le]),c.useEffect(()=>{const O=n.dialog?.id??null;O!==null&&O!==Ne.current&&(ds("question",Le),cn(e("notifyQuestionTitle"),e("notifyQuestionBody"))),Ne.current=O},[n.dialog,Le]),c.useEffect(()=>{const O=n.question?.id??null;O!==null&&O!==$e.current&&(ds("question",Le),cn(e("notifyQuestionTitle"),e("notifyQuestionBody"))),$e.current=O},[n.question,Le]),c.useEffect(()=>{const O=[...n.notices].reverse().find(he=>he.level==="error");O&&O.id!==Ie.current&&(Ie.current=O.id,ds("error",Le),cn(e("notifyErrorTitle"),e("notifyErrorBody")))},[n.notices,Le]);const ut=(O,he,Se,ze=!1,Je)=>{const At=`${O}|${Se}|${Je?`${Je.start}-${Je.end}`:""}`;m(mt=>mt.some(Tt=>`${Tt.path}|${Tt.mode}|${Tt.lines?`${Tt.lines.start}-${Tt.lines.end}`:""}`===At)?mt:[...mt,{path:O,name:he,mode:Se,isDir:ze,...Je?{lines:Je}:{}}])},Dt=O=>m(he=>he.filter(Se=>Se.key?Se.key!==O:Se.path!==O)),Pt=c.useCallback(O=>(!O.type.startsWith("list_")&&!O.type.startsWith("get_")&&ye(null),a(O)),[a]),U=c.useRef(0),te=c.useRef(0),je=O=>{const he=Date.now();n.state?.model&&!n.state.model.vision&&he-te.current>1e4&&(te.current=he,o("warning",e("imageNotSupported")));const Se=`paste-${++U.current}`;m(ze=>[...ze,{path:"",key:Se,name:O.name,mode:"inline",imageData:O.data,mimeType:O.mimeType}])},_e=async O=>{for(const he of O){const Se=await gi(he);if(!Se){o("error",e("imageLoadFailed",{name:he.name}));continue}je(Se)}},We=20*1024*1024,Ve=c.useRef(0),bt=async O=>{if(O.size>We){o("warning",e("fileTooLarge",{name:O.name,size:We/1024/1024}));return}let he;try{he=(await new Promise((Je,At)=>{const mt=new FileReader;mt.onload=()=>Je(mt.result),mt.onerror=()=>At(mt.error??new Error("read failed")),mt.readAsDataURL(O)})).replace(/^data:[^;]*;base64,/,"")}catch{o("error",e("fileLoadFailed",{name:O.name}));return}const Se=`upload-${++Ve.current}`;m(ze=>[...ze,{path:"",key:Se,name:O.name,mode:"inline",fileData:he,size:O.size,mimeType:O.type||void 0}])},Et=async O=>{for(const he of O)Ht(he.type)?await _e([he]):await bt(he)},Zs=c.useCallback((O,he,Se)=>{a({type:"edit_message",messageId:O,text:he,attachments:Se})},[a]),Qt=c.useCallback((O,he)=>{a({type:"queue_remove",kind:O,text:he})},[a]),[ys,kt]=c.useState([]),en=c.useRef(0),ra=c.useCallback((O,he)=>{a({type:"queue_remove",kind:O,text:he}),en.current+=1;const Se={text:he,seq:en.current};kt(ze=>[...ze.slice(-9),Se])},[a]),tn=c.useCallback(()=>Te(!0),[]),oa=c.useCallback(()=>m([]),[]),la=c.useCallback(Dt,[]),Fe=c.useCallback(_e,[_e]),sn=c.useCallback(Et,[Et]),$t=n.state?.model,ks=n.state?.thinkingLevel,nn=n.state?.availableThinkingLevels,an=c.useMemo(()=>$t?{model:$t,thinkingLevel:ks??"off",availableThinkingLevels:nn??[]}:null,[$t,ks,nn]),Ns=c.useCallback(()=>!n.ready||n.terminals.length!==0?!1:(l.create({id:St(),conversationId:n.activeConversationId||n.state?.conversationId||"",title:e("terminalTitle",{n:1}),cwd:n.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null}),!0),[n.ready,n.state?.cwd,n.terminals.length,e,l]);return c.useEffect(()=>{if(Qe.current){if(j!=="terminal"||n.terminals.length!==0){Qe.current=!1;return}Ns()&&(Qe.current=!1)}},[n.terminals.length,Ns,j]),s.jsxs("div",{className:"app",onDragOver:O=>{Array.from(O.dataTransfer?.types??[]).includes("Files")&&(O.preventDefault(),N(!0))},onDragLeave:O=>{O.currentTarget.contains(O.relatedTarget)||N(!1)},onDrop:O=>{if(N(!1),!Array.from(O.dataTransfer?.types??[]).includes("Files"))return;O.preventDefault();const he=Array.from(O.dataTransfer?.files??[]);if(he.length===0){o("warning",e("foldersNotSupported"));return}const Se=he.filter(Je=>Ht(Je.type)),ze=he.filter(Je=>!Ht(Je.type));Se.length>0&&_e(Se),ze.length>0&&Et(ze)},children:[v&&s.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:s.jsxs("span",{children:["📎 ",e("dropHereToAttach")]})}),s.jsx($d,{chat:n,terminal:l,view:j,plugins:X,uiPrimary:ce,uiOverflow:be,uiContextTopbar:w["contextmenu.topbar"],onUiAction:$,onViewChange:O=>{Qe.current=O==="terminal"&&n.terminals.length===0,Qe.current&&Ns()&&(Qe.current=!1),V(O),ye(null)},onOpenPanel:ye,onOpenSettings:()=>Re(!0),onOpenBgTasks:()=>P(!0),onOpenGlobalSearch:()=>Ee(!0),sound:Le,onSoundChange:Ge,onSoundPreview:O=>ds(O,Le),themes:R,theme:He,onThemeChange:C,reloadThemes:_}),n.protocolMismatch&&s.jsxs("div",{className:"protocol-banner",children:["⚠ ",e("protocolMismatch")]}),s.jsx("div",{className:"notices",children:n.notices.map(O=>s.jsx(a1,{notice:O,onDismiss:i},O.id))}),s.jsx(Eg,{currentModelId:$t?`${$t.provider}/${$t.id}`:null,children:s.jsxs("div",{className:"layout",style:{"--left-w":`${T}px`,"--right-w":`${Y}px`},children:[Oe&&s.jsx("div",{className:"drawer-backdrop",onClick:()=>ye(null)}),s.jsxs("div",{className:`view-pane ${j==="chat"?"":"hidden"}`,children:[!we&&ve&&s.jsx(ho,{side:"left",onClick:pe}),s.jsx("div",{className:`panel-drawer drawer-left ${Oe==="left"?"open":""}${we?"":ve?" hidden":""}`,children:s.jsx(Qd,{collapsible:!we,onToggleCollapse:pe,panelSend:Pt,active:!we||Oe==="left",sessionFile:n.state?.sessionFile??null,conversations:n.conversations,elsewhere:n.elsewhere,sessions:n.sessions,projects:n.projects,activeConversationId:n.activeConversationId,uiContextSession:w["contextmenu.session"]})}),!we&&s.jsx(mo,{side:"left",width:T,onResize:ae}),s.jsxs("main",{className:Z?"main wide-chat":"main",children:[n.state?s.jsx(Cg,{uiMessageActions:w["message.actions"],uiContextMessage:w["contextmenu.message"],onUiAction:$,state:n.state,liveOutputs:n.liveOutputs,toolStatuses:n.toolStatuses,onEdit:Zs,onKillBash:()=>a({type:"abort_bash"}),onRetry:()=>{if(a({type:"retry_last"})){const O=n.state?.model;O&&Yn(`${O.provider}/${O.id}`)}},onRemoveQueued:Qt,onRecallQueued:ra,thinkingWrap:n.settings?.thinkingWrap??!0,toolsWrap:n.settings?.toolsWrap??!0,jumpTarget:Ae,onJumpDone:()=>Me(null)},n.state.conversationId??"boot"):s.jsx("div",{className:"boot-wait",children:n.ready?e("loadingSession"):e("connectingServer")}),n.settings?.goalModeEnabled!==!1&&s.jsx(Wg,{goal:n.goal,models:n.models,modelsLoading:n.modelsLoading,activeConversationId:n.activeConversationId}),s.jsx(bb,{onAction:O=>$(O)}),n.dialog&&s.jsx(Jg,{dialog:n.dialog}),oe&&s.jsxs("div",{className:"dialog-inline","data-dialog-kind":"confirm",children:[s.jsxs("div",{className:"dialog-head",children:[s.jsx("span",{className:"dialog-badge",children:e("pluginRequest")}),s.jsx("span",{className:"dialog-title",children:e("pluginGrantRequestTitle")}),s.jsx("button",{type:"button",className:"dialog-dismiss",title:e("cancel"),onClick:()=>ge(oe.id,!1),children:"✕"})]}),s.jsxs("div",{className:"dialog-body",children:[e("pluginGrantRequestBody").replace("{plugin}",oe.pluginId).replace("{path}",oe.path),oe.reason&&s.jsx("div",{className:"dialog-hint",children:oe.reason}),s.jsxs("div",{className:"dialog-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>ge(oe.id,!1),children:e("pluginGrantDeny")}),s.jsx("button",{type:"button",className:"btn primary",onClick:()=>ge(oe.id,!0),children:e("pluginGrantAllow")})]})]})]}),Ye&&s.jsxs("div",{className:"dialog-inline","data-dialog-kind":"confirm",children:[s.jsxs("div",{className:"dialog-head",children:[s.jsx("span",{className:"dialog-badge",children:e("pluginRequest")}),s.jsx("span",{className:"dialog-title",children:e("pluginSessionGrantTitle")}),s.jsx("button",{type:"button",className:"dialog-dismiss",title:e("cancel"),onClick:()=>{Ye.resolve(!1),A(null)},children:"✕"})]}),s.jsxs("div",{className:"dialog-body",children:[e("pluginSessionGrantBody").replace("{path}",Ye.path),s.jsxs("div",{className:"dialog-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>{Ye.resolve(!1),A(null)},children:e("cancel")}),s.jsx("button",{type:"button",className:"btn primary",onClick:()=>{Ye.resolve(!0),A(null)},children:e("ok")})]})]})]}),n.question&&s.jsx(sb,{question:n.question}),s.jsx(qg,{composerActions:w["composer.actions"],onUiAction:$,streaming:n.state?.isStreaming??!1,messages:n.state?.messages??i1,slashCommands:n.slashCommands,modelState:an,models:n.models,modelsLoading:n.modelsLoading,providerKeys:n.providerKeys,attachments:b,onRemoveAttachment:la,onAddImageFiles:Fe,onAddLocalFiles:sn,onNotice:o,onManageModels:tn,onSent:oa,quickPhrases:n.settings?.quickPhrases??[],quickPhrasesEnabled:n.settings?.quickPhrasesEnabled??!0,recallDrafts:ys})]}),!we&&s.jsx(mo,{side:"right",width:Y,onResize:ee}),s.jsx("div",{className:`panel-drawer drawer-right ${Oe==="right"?"open":""}${we?"":de?" hidden":""}`,children:s.jsx(Op,{collapsible:!we,onToggleCollapse:ke,panelSend:Pt,files:n.files,fileChanged:n.fileChanged,widgets:n.widgets,onAttach:(O,he,Se,ze)=>{ye(null),ut(O,he,Se,ze)},onPreview:(O,he)=>{ye(null),x({path:O,name:he})},onNotice:(O,he)=>o(O,he),uiRightPanelTabs:w["rightpanel.tabs"],uiContextFile:w["contextmenu.file"],plugins:X,pluginsEpoch:n.pluginsEpoch,send:a})}),!we&&de&&s.jsx(ho,{side:"right",onClick:ke})]}),s.jsx("div",{className:`view-pane ${j==="terminal"?"":"hidden"}`,children:s.jsx(c.Suspense,{fallback:null,children:s.jsx(n1,{chat:n,terminal:l})})}),s.jsx("div",{className:`view-pane ${j==="git"?"":"hidden"}`,children:s.jsx(ob,{chat:n,terminal:l,active:j==="git",onSwitchToTerminal:()=>V("terminal")})}),K.map(O=>{const he=`plugin:${O.info.id}`;return s.jsx("div",{className:`view-pane ${j===he?"":"hidden"}`,children:s.jsx(lb,{entry:O})},O.info.id)})]})}),s.jsx(Qg,{chat:n,bottombarItems:w.bottombar,onUiAction:$}),f&&s.jsx(Gb,{file:f,content:n.fileContent,onAddLines:(O,he,Se,ze)=>ut(O,he,"lines",!1,{start:Se,end:ze}),onAttach:(O,he,Se)=>ut(O,he,Se),onClose:()=>x(null)}),n.ready&&n.state&&n.state.piConfigured===!1&&!qe&&!se&&s.jsx(Eb,{piConfigured:n.state.piConfigured,piAgentInstalled:n.state.piAgentInstalled,providers:n.providers,installResult:n.installResult,onClose:()=>Be(!0)}),se&&s.jsx(yb,{providers:n.modelsConfig,providerStatus:n.providers,providerKeys:n.providerKeys,fetchModelsResult:n.fetchModelsResult,cloneProviderResult:n.cloneProviderResult,onClose:()=>Te(!1)}),De&&s.jsx($b,{chat:n,terminal:l,onSwitchToTerminal:()=>V("terminal"),onClose:()=>Re(!1)}),y&&s.jsx(Wb,{servers:n.bgServers,onClose:()=>P(!1)}),s.jsx(Yb,{open:le,projects:n.projects,fileSearch:n.fileSearch,sessionSearch:n.sessionSearch,onClose:()=>Ee(!1),onSwitchSession:(O,he)=>{a({type:"switch_session",path:O});const Se=he&&he[0];Me(Se?{path:O,role:Se.role,timestamp:Se.timestamp}:null)},onSwitchProject:O=>{a({type:"set_cwd",path:O})},onPreviewFile:(O,he)=>{x({path:O,name:he})}})]})}function l1(){typeof document>"u"||(Bc(c1()),d1())}function Bc(e){!Number.isFinite(e)||e<0||document.documentElement.style.setProperty("--msgs-gutter",`${Math.round(e*100)/100}px`)}function c1(){const e=document.createElement("div");e.style.cssText="position:fixed;top:-9999px;left:0;width:100px;height:100px;overflow-y:auto;scrollbar-gutter:stable both-edges;visibility:hidden;pointer-events:none;",document.body.appendChild(e);const t=(e.offsetWidth-e.clientWidth)/2;return e.remove(),t}function u1(e){const t=document.createElement("div");t.style.cssText="width:0;height:0;pointer-events:none;",e.appendChild(t);const n=getComputedStyle(e),a=e.getBoundingClientRect(),i=t.getBoundingClientRect(),o=Number.parseFloat(n.borderLeftWidth)||0,l=Number.parseFloat(n.paddingLeft)||0,u=i.left-(a.left+o+l);return t.remove(),u}function d1(){const e=()=>{const a=document.querySelector(".messages");return a?(Bc(u1(a)),!0):!1};let t=0;if(window.addEventListener("resize",()=>{t||(t=window.requestAnimationFrame(()=>{t=0,e()}))}),e())return;const n=new MutationObserver(()=>{e()&&n.disconnect()});n.observe(document.documentElement,{childList:!0,subtree:!0}),window.setTimeout(()=>n.disconnect(),6e4)}Xu();Kl(Wl());l1();du.createRoot(document.getElementById("root")).render(s.jsx(c.StrictMode,{children:s.jsx(ld,{children:s.jsx(o1,{})})}));"serviceWorker"in navigator&&window.addEventListener("load",()=>{const e=jo();navigator.serviceWorker.register(`${e}sw.js`,{scope:e}).catch(t=>{console.warn("Service worker registration failed:",t)})});export{jt as F,zt as T,ie as a,f1 as b,Pe as c,yt as d,h1 as e,Rn as f,dt as g,Ru as h,Jn as i,tt as j,St as r,Ut as u};