pi-web-ui 0.86.2 → 0.87.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +59 -21
- package/README.md +1 -1
- package/bin/pi-web-ui.mjs +312 -40
- package/dist/server/agent-service.js +297 -6
- package/dist/server/client-state.js +8 -0
- package/dist/server/composer-drafts.js +138 -0
- package/dist/server/dsh/dsh-agent-service.js +531 -54
- package/dist/server/dsh/dsh-client.js +28 -0
- package/dist/server/dsh/dsh-sessions.js +28 -0
- package/dist/server/dsh/dsh-usage.js +82 -0
- package/dist/server/dsh/preset-clones.js +260 -0
- package/dist/server/dsh/runtime/custom-prompt.mjs +33 -0
- package/dist/server/dsh/runtime/goal-rpc.mjs +406 -22
- package/dist/server/dsh/runtime/launcher.mjs +17 -0
- package/dist/server/dsh/runtime/override.patch.yml +19 -1
- package/dist/server/files-service.js +259 -1
- package/dist/server/index.js +219 -3
- package/dist/server/mcp-bridge.js +126 -22
- package/dist/server/mcp-hot-reload.js +117 -0
- package/dist/server/model-admin.js +93 -3
- package/dist/server/plugin-dom.js +83 -0
- package/dist/server/plugin-facilities.js +15 -1
- package/dist/server/plugin-installer.js +6 -0
- package/dist/server/plugins.js +781 -74
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/provider-oauth-flow.js +157 -0
- package/package.json +1 -1
- package/plugins/catalog.json +9 -0
- package/themes/dark-teal.css +63 -22
- package/web/dist/assets/index-DePnXpq-.js +374 -0
- package/web/dist/assets/index-F86qWlJy.css +41 -0
- package/web/dist/index.html +3 -2
- package/web/dist/assets/TerminalPanel-BytY8dx7.js +0 -6
- package/web/dist/assets/TerminalPanel-DOrYoP_4.css +0 -32
- package/web/dist/assets/index-CKoVyDkP.css +0 -10
- package/web/dist/assets/index-Dmwji4Cr.js +0 -361
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import{R as js,a as o,j as s,f as ad,s as Ia,h as Vr,w as ws,b as rd,c as id,d as dl,o as ir,z as pl,e as od,g as ld,p as Ds,v as cd,i as ml,k as mi,M as ud,l as dd,m as pd,n as hl,q as fl}from"./markdown-D3PKeHAZ.js";import{r as gl}from"./react-w24rH0km.js";import{D as md,o as hd}from"./xterm-B96xOxS9.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const c of a)if(c.type==="childList")for(const l of c.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(a){const c={};return a.integrity&&(c.integrity=a.integrity),a.referrerPolicy&&(c.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?c.credentials="include":a.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function r(a){if(a.ep)return;a.ep=!0;const c=n(a);fetch(a.href,c)}})();var Hn={},hi;function fd(){if(hi)return Hn;hi=1;var e=gl();return Hn.createRoot=e.createRoot,Hn.hydrateRoot=e.hydrateRoot,Hn}var gd=fd();const bd="modulepreload",xd=function(e){return"/"+e},fi={},Ed=function(t,n,r){let a=Promise.resolve();if(n&&n.length>0){let l=function(m){return Promise.all(m.map(f=>Promise.resolve(f).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const u=document.querySelector("meta[property=csp-nonce]"),d=u?.nonce||u?.getAttribute("nonce");a=l(n.map(m=>{if(m=xd(m),m in fi)return;fi[m]=!0;const f=m.endsWith(".css"),h=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${h}`))return;const b=document.createElement("link");if(b.rel=f?"stylesheet":bd,f||(b.as="script"),b.crossOrigin="",b.href=m,d&&b.setAttribute("nonce",d),document.head.appendChild(b),f)return new Promise((E,N)=>{b.addEventListener("load",E),b.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${m}`)))})}))}function c(l){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=l,window.dispatchEvent(u),!u.defaultPrevented)throw l}return a.then(l=>{for(const u of l||[])u.status==="rejected"&&c(u.reason);return t().catch(c)})};var In=gl(),bl={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},gi=js.createContext&&js.createContext(bl),yd=["attr","size","title"];function Td(e,t){if(e==null)return{};var n,r,a=kd(e,t);if(Object.getOwnPropertySymbols){var c=Object.getOwnPropertySymbols(e);for(r=0;r<c.length;r++)n=c[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function kd(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function ra(){return ra=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},ra.apply(null,arguments)}function bi(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function ia(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?bi(Object(n),!0).forEach(function(r){Nd(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):bi(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Nd(e,t,n){return(t=vd(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function vd(e){var t=Cd(e,"string");return typeof t=="symbol"?t:t+""}function Cd(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function xl(e){return e&&e.map((t,n)=>js.createElement(t.tag,ia({key:n},t.attr),xl(t.child)))}function _e(e){return t=>js.createElement(wd,ra({attr:ia({},e.attr)},t),xl(e.child))}function wd(e){var t=n=>{var r=e.attr,a=e.size,c=e.title,l=Td(e,yd),u=a||n.size||"1em",d;return n.className&&(d=n.className),e.className&&(d=(d?d+" ":"")+e.className),js.createElement("svg",ra({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,l,{className:d,style:ia(ia({color:e.color||n.color},n.style),e.style),height:u,width:u,xmlns:"http://www.w3.org/2000/svg"}),c&&js.createElement("title",null,c),e.children)};return gi!==void 0?js.createElement(gi.Consumer,null,n=>t(n)):t(bl)}function Sd(e){return _e({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 _d(e){return _e({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 qs(e){return _e({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 bt(e){return _e({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 El(e){return _e({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 xi(e){return _e({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 Ad(e){return _e({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 jd(e){return _e({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 Rt(e){return _e({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 Ei(e){return _e({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 Rn(e){return _e({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 yi(e){return _e({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 Id(e){return _e({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 oa(e){return _e({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 Ti(e){return _e({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 or(e){return _e({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"},child:[]}]})(e)}function la(e){return _e({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 lr(e){return _e({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 ca(e){return _e({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 Rd(e){return _e({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 yl(e){return _e({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 Yt(e){return _e({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 Dt(e){return _e({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 Pd(e){return _e({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 Ld(e){return _e({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 Gn(e){return _e({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 Dd(e){return _e({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 cr(e){return _e({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 Od(e){return _e({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 Md(e){return _e({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 Is(e){return _e({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 Tl(e){return _e({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 Bd(e){return _e({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 Fd(e){return _e({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 ur(e){return _e({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 Hd(e){return _e({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 Ud(e){return _e({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 dr(e){return _e({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 ua(e){return _e({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 $d(e){return _e({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 qd(e){return _e({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 ki(e){return _e({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 Wd(e){return _e({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 kl(e){return _e({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 Ni(e){return _e({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 Yn(e){return _e({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 is(e){return _e({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 vi(e){return _e({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 Nl(e){return _e({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 da(e){return _e({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 _n(e){return _e({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 zs(e){return _e({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 Rs(e){return _e({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 Ts(e){return _e({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 Kd(e){return _e({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 cs(e){return _e({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 Ci(e){return _e({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 pr(e){return _e({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 wi(e){return _e({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 vl(e){return _e({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 Cl(e){return _e({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 Ra(e){return _e({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 Os(e){return _e({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 ks(e){return _e({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 os(e){return _e({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 Qs(e){return _e({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 Un(e){return _e({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 Gd(e){return _e({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 Yd(e){return _e({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 mr(e){return _e({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 zd(e){return _e({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 wl(e){return _e({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 Sl(e){return _e({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 hr(e){return _e({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 Vd(e){return _e({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 Qd(e){return e.map(t=>t.kind==="package"?`pi update npm:${t.name}`:`npm i -g ${t.name}@latest`).join("; ")}function qt(){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 zt({trigger:e,open:t,onOpenChange:n,children:r,align:a="right",fit:c=!1,direction:l="down",menuClassName:u,menuRef:d,menuStyle:m}){const f=o.useRef(null);return o.useEffect(()=>{if(!t)return;const h=E=>{f.current&&!f.current.contains(E.target)&&n(!1)},b=E=>{E.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",h),document.addEventListener("keydown",b),()=>{document.removeEventListener("mousedown",h),document.removeEventListener("keydown",b)}},[t,n]),s.jsxs("div",{className:`dropdown ${a} ${c?"fit":""} ${l==="up"?"dd-up":""}`,ref:f,children:[s.jsxs("button",{type:"button",className:"chip",onClick:()=>n(!t),"aria-expanded":t,children:[e,s.jsx(ks,{className:`dd-caret ${t?"up":""}`})]}),t&&s.jsx("div",{className:`dd-menu ${u??""}`,ref:d,style:m,children:r})]})}function wt({active:e,disabled:t=!1,title:n,onClick:r,children:a}){return s.jsx("button",{type:"button",className:`dd-item ${e?"active":""}`,disabled:t,title:n,onClick:r,children:a})}let qa=null;function Xd(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 _l(){return qa===null&&(qa=Xd()),qa}function Jd(e,t){return t==="/"?e:t+e.replace(/^\/+/,"")}function _t(e){return Jd(e,_l())}const Al="pi-web-ui:token";function Zd(){try{const e=new URL(window.location.href),t=e.searchParams.get("token");t&&(localStorage.setItem(Al,t.trim()),e.searchParams.delete("token"),window.history.replaceState(null,"",e.toString()))}catch{}}function ep(){try{return localStorage.getItem(Al)??""}catch{return""}}function hs(e){const t=ep();return t?`${e}${e.includes("?")?"&":"?"}token=${encodeURIComponent(t)}`:e}const tp=["zh","en","de","es","fr","it","ja","ko","pt","ru"];function fr(e,t,n,r=tp){const a=(e??"").trim();if(a)return a;for(const l of t??[]){const u=String(l??"").trim().toLowerCase().replace(/_/g,"-");if(!u)continue;if(r.includes(u))return u;const d=u.split("-")[0];if(d&&r.includes(d))return d}const c=(n??"").trim().toLowerCase();return c&&r.includes(c)?c:"en"}const gr="pi-web-ui:lang",sp={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 补全",atMentions:"提及",atMenuHint:"↑↓ 选择 · 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:"根目录",homeDir:"用户目录",desktopDir:"桌面",filesHelp:`浏览:点文件夹进入、点文件预览,「..」返回上级;「根目录」回当前项目根,「此电脑」浏览全盘换盘符,「🏠」直达用户目录,「🖥️」直达桌面。
|
|
2
|
+
文件操作:右键可新建文件/文件夹、重命名、复制/剪切/粘贴、创建副本、删除、上传文件;文件可下载,行尾按钮可复制名称/路径。
|
|
3
|
+
切换项目:文件夹右键「以项目打开」,或点右下角 📁 路径按钮输入/选择目录。
|
|
4
|
+
发给 AI:行尾按钮附加内容或仅引用路径,也可把文件拖进输入框。`,workspaceRoots:"工作区根",workspaceRootsHint:"文件树可切换到这些根;插件读写这些目录不必再单独授权。",addWorkspaceRoot:"添加为工作区根",addWorkspaceRootHint:"把当前目录加成工作区根(右栏文件树可切换浏览;插件读写该目录不再单独授权)",removeWorkspaceRoot:"移除工作区根",noFiles:"暂无文件",filesTruncated:"目录过大,列表已截断,仅显示前 2000 项",linkFolderTip:"链接文件夹路径到对话",attachInlineTip:"附加内容到对话",referenceTip:"仅引用路径(AI 按需读取)",previewFile:"预览",downloadFile:"下载文件",copyName:"复制名称",copyPath:"复制路径",downloadFailed:"下载失败:{error}",fileNotFoundShort:"文件不存在",pluginMountFailed:"插件 {name} 挂载失败",liveOutputOmitted:`…[前 {n} 字符已省略]…
|
|
5
|
+
`,uploadToFolder:"上传文件到此文件夹",uploadToCurrentDir:"上传文件到当前目录",openAsProject:"以项目打开",fileOpenPreview:"打开预览",fileEnterDir:"进入目录",fileNewFile:"新建文件",fileNewDir:"新建文件夹",fileRename:"重命名",fileNamePlaceholder:"文件名",fileDuplicate:"创建副本",fileCut:"剪切",fileCopyEntry:"复制",filePaste:"粘贴",fileDelete:"删除",fileDeleteConfirm:"确认删除 {name}?",fileCopyRelPath:"复制相对路径",fileRefresh:"刷新列表",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":`请先扫描这个仓库,建立「其他工作流都能用」的基础上下文,输出一份简明报告:
|
|
6
|
+
|
|
7
|
+
1. 项目类型、技术栈与目录结构
|
|
8
|
+
2. 构建 / 测试 / 运行 / 格式化的具体命令
|
|
9
|
+
3. 代码约定与命名规范
|
|
10
|
+
4. 任务 / issue 的存放位置与格式
|
|
11
|
+
5. 目前已知的坑或遗留问题
|
|
12
|
+
|
|
13
|
+
先只报告,不修改任何文件。`,"tpl.sk.ask":"技能导航","tpl.sk.ask.desc":"告诉我该用哪个流程","tpl.sk.ask.prompt":"我先描述当前要解决的情况,你先判断最适合的工作流(需求澄清 / 拆解计划 / 测试驱动 / 排错 / 架构 / 审查 / 交接等),说明为什么推荐它、会怎么做,等我确认后按它执行。","tpl.sk.grilldocs":"需求拷问·落档","tpl.sk.grilldocs.desc":"边盘问需求边记录决策","tpl.sk.grilldocs.prompt":"动手前,请用拷问的方式向我盘问这个计划(一次一个问题),直到达成共识。同时把过程中的关键术语和已定决策记录下来(例如写入 CONTEXT.md 或 ADR 文件),让后续所有工作都基于同一套「共享语言」。每个问题先给出你的推荐答案。","tpl.sk.tospec":"转规格说明","tpl.sk.tospec.desc":"把讨论结果整理成规格书","tpl.sk.tospec.prompt":`请把我们在对话中已经达成的共识,整理成一份结构化的规格说明书:
|
|
14
|
+
|
|
15
|
+
1. 背景与目标
|
|
16
|
+
2. 明确的目标与非目标
|
|
17
|
+
3. 用户与使用场景
|
|
18
|
+
4. 边界条件与失败场景
|
|
19
|
+
5. 验收标准(怎样算完成)
|
|
20
|
+
6. 接口 / 数据结构概要
|
|
21
|
+
|
|
22
|
+
先输出规格让我评审,确认后再继续。`,"tpl.sk.totickets":"拆工单","tpl.sk.totickets.desc":"把规格拆成可构建的小任务","tpl.sk.totickets.prompt":`请把这份规格说明拆成一组小工单,供逐个构建:
|
|
23
|
+
|
|
24
|
+
1. 每个工单足够小、可独立验收
|
|
25
|
+
2. 标注依赖顺序(哪些必须先做)
|
|
26
|
+
3. 每个工单含:做什么、验收标准、涉及文件
|
|
27
|
+
4. 识别出可并行的工单
|
|
28
|
+
|
|
29
|
+
先输出工单列表,我确认顺序后再执行。`,"tpl.sk.implement":"规格落地","tpl.sk.implement.desc":"按规格测试优先实现","tpl.sk.implement.prompt":`请按这份规格说明实现,测试优先:
|
|
30
|
+
|
|
31
|
+
1. 先为每个工单写会失败的测试(覆盖正常、边界、错误分支)
|
|
32
|
+
2. 用最小实现让测试通过
|
|
33
|
+
3. 重构并保持测试通过
|
|
34
|
+
4. 逐工单推进,每完成一个简要汇报
|
|
35
|
+
|
|
36
|
+
最后对照验收标准逐条确认。`,"tpl.sk.codeview":"代码审查","tpl.sk.codeview.desc":"对照规格与标准审查 diff","tpl.sk.codeview.prompt":`请审查最近改动的 diff:
|
|
37
|
+
|
|
38
|
+
1. 对照规格说明,实现是否完全覆盖、有无偏差
|
|
39
|
+
2. 正确性:边界、空值、并发与时序
|
|
40
|
+
3. 安全:输入校验、注入、敏感信息
|
|
41
|
+
4. 性能与可读性:是否遵循项目约定
|
|
42
|
+
5. 测试:关键路径是否有覆盖
|
|
43
|
+
|
|
44
|
+
按严重程度分级列出问题,每条给出具体修改建议。`,"tpl.sk.wayfinder":"大任务地图","tpl.sk.wayfinder.desc":"把大工程画成决策地图","tpl.sk.wayfinder.prompt":`这是一个大型任务。请先把它画成一张「决策地图」:
|
|
45
|
+
|
|
46
|
+
1. 拆出所有需要做出的决策点及其依赖关系
|
|
47
|
+
2. 为每个决策点列出选项、权衡与你的推荐
|
|
48
|
+
3. 标注哪些可以并行推进、哪些必须串行
|
|
49
|
+
4. 输出一份路径规划,我逐项确认后再动手。`,"tpl.sk.prototype":"快速原型","tpl.sk.prototype.desc":"用一次性代码验证设计假设","tpl.sk.prototype.prompt":`请针对这个设计问题写一个最小原型来验证假设:
|
|
50
|
+
|
|
51
|
+
1. 只验证关键假设,不做完整实现
|
|
52
|
+
2. 用最简单的方式(可硬编码、可牺牲边界情况)
|
|
53
|
+
3. 运行并告诉我结论:假设成立吗?有哪些权衡?
|
|
54
|
+
4. 验证完的原型可以删除,或等确认后再正式实现。`,"tpl.sk.research":"有据调研","tpl.sk.research.desc":"读一手来源给出带引用的答案","tpl.sk.research.prompt":`请调研这个问题,优先读一手来源(官方文档 / 源码 / 规范):
|
|
55
|
+
|
|
56
|
+
1. 给出带来源链接的答案
|
|
57
|
+
2. 明确区分:事实、合理推断、仍不确定
|
|
58
|
+
3. 列出主要选项及其权衡
|
|
59
|
+
4. 避免用二手内容拼凑,找不到就直接说没找到。`,"tpl.sk.arch":"架构体检","tpl.sk.arch.desc":"找出值得重构的模块(报告)","tpl.sk.arch.prompt":`对整个代码库做一次架构体检:
|
|
60
|
+
|
|
61
|
+
1. 找出「深模块被破坏」的迹象:过长的函数与类、明显的重复、命名混乱、隐藏的耦合
|
|
62
|
+
2. 按严重程度与影响范围分级,输出一份可视化改进报告
|
|
63
|
+
3. 对每一项给出最小可行的重构方案与理由
|
|
64
|
+
4. 先报告再动手,重构前确认范围。`,"tpl.sk.debug":"系统化排错","tpl.sk.debug.desc":"从可复现的失败开始诊断","tpl.sk.debug.prompt":`请系统化诊断这个 bug:
|
|
65
|
+
|
|
66
|
+
1. 先复现,给出可复现的步骤或输入(没有就先造最小复现)
|
|
67
|
+
2. 二分或排除法缩小范围到具体模块
|
|
68
|
+
3. 提出假设,用日志 / 断言 / 最小样例验证,不凭感觉改
|
|
69
|
+
4. 定位根因后解释,再做最小修复
|
|
70
|
+
5. 补回归测试防止复发。`,"tpl.sk.merge":"解决合并冲突","tpl.sk.merge.desc":"逐个 hunk 完成合并/变基","tpl.sk.merge.prompt":`请帮我解决这个合并 / 变基冲突:
|
|
71
|
+
|
|
72
|
+
1. 逐个冲突 hunk 处理,先读懂双方各自的意图
|
|
73
|
+
2. 选择或合并出保留正确语义的代码,不盲目取一边
|
|
74
|
+
3. 处理完运行测试与构建确认没问题
|
|
75
|
+
4. 最后总结每处冲突的取舍原因。`,"tpl.sk.triage":"工单分流","tpl.sk.triage.desc":"把原始 issue 整理成可领取的工作","tpl.sk.triage.prompt":`请把这些原始 issue / 反馈整理成可执行的工作项:
|
|
76
|
+
|
|
77
|
+
1. 去重、合并相关的条目
|
|
78
|
+
2. 分类(bug / 功能 / 改进 / 问题)
|
|
79
|
+
3. 按影响与紧急度标优先级
|
|
80
|
+
4. 每个工作项补上:复现信息或期望、验收标准
|
|
81
|
+
|
|
82
|
+
输出整理后的清单。`,"tpl.sk.wizard":"设置向导","tpl.sk.wizard.desc":"生成引导人类完成设置的脚本","tpl.sk.wizard.prompt":`请为一个需要手动操作的设置流程生成一个引导向导(脚本或文档):
|
|
83
|
+
|
|
84
|
+
1. 一步步引导,每步说明为什么
|
|
85
|
+
2. 每步带校验,输错给出可操作的提示
|
|
86
|
+
3. 支持撤销 / 回退到上一步
|
|
87
|
+
4. 结束时做一次自检并给出验证方法。`,"tpl.sk.grillme":"需求拷问","tpl.sk.grillme.desc":"动手前盘问对齐想法","tpl.sk.grillme.prompt":`开始之前,请不遗余力地盘问我这个想法的每一个方面,直到我们达成共识(一次只问一个问题,每个问题先给推荐答案):
|
|
88
|
+
|
|
89
|
+
1. 目标与非目标
|
|
90
|
+
2. 用户与场景
|
|
91
|
+
3. 边界与失败模式
|
|
92
|
+
4. 约束与依赖
|
|
93
|
+
5. 验收标准
|
|
94
|
+
|
|
95
|
+
达成共识后再给实现计划,等确认再写代码。`,"tpl.sk.handoff":"交接","tpl.sk.handoff.desc":"把长会话写成交接文档","tpl.sk.handoff.prompt":`请把当前会话整理成一份交接文档,让另一个 agent / 同事能无缝继续:
|
|
96
|
+
|
|
97
|
+
1. 背景与目标
|
|
98
|
+
2. 已完成的工作与关键决策(附原因)
|
|
99
|
+
3. 未完成项与下一步
|
|
100
|
+
4. 已知风险与待确认问题
|
|
101
|
+
5. 如何验证当前状态(命令等)
|
|
102
|
+
|
|
103
|
+
输出为结构化文档。`,"tpl.sk.questionnaire":"转问卷","tpl.sk.questionnaire.desc":"把开放问题变成可填问卷","tpl.sk.questionnaire.prompt":`请把需要别人提供的信息整理成一份可填写的问卷:
|
|
104
|
+
|
|
105
|
+
1. 每个问题说明背景和用途
|
|
106
|
+
2. 标注必填 / 选填
|
|
107
|
+
3. 给出示例答案降低理解成本
|
|
108
|
+
4. 分组排序,先简单后复杂
|
|
109
|
+
|
|
110
|
+
输出一份文档,对方可以照着填。`,"tpl.sk.teach":"持续学习","tpl.sk.teach.desc":"跨多次会话循序渐进学习","tpl.sk.teach.prompt":`请按循序渐进的方式教我:
|
|
111
|
+
|
|
112
|
+
1. 先定学习路径和目标
|
|
113
|
+
2. 一次只讲一小节,讲完给个小练习
|
|
114
|
+
3. 基于上一节的内容递进,主动提问确认理解
|
|
115
|
+
4. 每节结束总结要点
|
|
116
|
+
|
|
117
|
+
适合跨多次会话推进。`,"tpl.sk.ww":"说人话","tpl.sk.ww.desc":"用大白话重讲刚才的解释","tpl.sk.ww.prompt":`请把刚才的解释用最简单的语言重新讲一遍:
|
|
118
|
+
|
|
119
|
+
1. 避免术语,必须用时先给一句话定义
|
|
120
|
+
2. 用类比或具体例子说明
|
|
121
|
+
3. 明确指出哪部分仍是猜测 / 不确定
|
|
122
|
+
4. 用最短的话说完核心意思。`,"tpl.sk.wfa":"写给 agent 的文档","tpl.sk.wfa.desc":"按 agent 易读的原则写文档","tpl.sk.wfa.prompt":`请按「写给 agent 阅读」的原则写这份文档 / 说明:
|
|
123
|
+
|
|
124
|
+
1. 目标与使用场景写在最前
|
|
125
|
+
2. 指令具体、可验证,避免歧义和空话
|
|
126
|
+
3. 给正反例帮助理解
|
|
127
|
+
4. 结构化:标题、步骤、清单
|
|
128
|
+
5. 标注哪些是硬性要求、哪些是可选。`,"tpl.sk.codesign":"深模块设计","tpl.sk.codesign.desc":"用深模块原则审查与设计","tpl.sk.codesign.prompt":`请用「深模块」设计原则审查 / 设计:
|
|
129
|
+
|
|
130
|
+
1. 识别模块对外暴露的接口是否比内部实现更简单
|
|
131
|
+
2. 找出把复杂度泄漏到外部的模块
|
|
132
|
+
3. 给出每个模块的职责边界与改进方案
|
|
133
|
+
4. 平衡内聚与复用,避免过度抽象
|
|
134
|
+
|
|
135
|
+
输出审查结论与重构建议。`,"tpl.sk.domain":"领域建模","tpl.sk.domain.desc":"打磨项目用词并写下来","tpl.sk.domain.prompt":`请帮我梳理这个项目的领域语言:
|
|
136
|
+
|
|
137
|
+
1. 找出核心术语及当前叫法
|
|
138
|
+
2. 识别同词异义 / 异词同义造成的混乱
|
|
139
|
+
3. 统一推荐用词,写进术语表
|
|
140
|
+
4. 说明每个术语的边界(不是什么)
|
|
141
|
+
|
|
142
|
+
输出一份领域术语表。`,"tpl.sk.grilling":"拷问流程","tpl.sk.grilling.desc":"用拷问压测一个计划","tpl.sk.grilling.prompt":`请对下面这个计划做压力测试(拷问):
|
|
143
|
+
|
|
144
|
+
1. 逐项检查假设:如果它是错的会怎样?
|
|
145
|
+
2. 找漏洞:边界、失败模式、依赖、时序
|
|
146
|
+
3. 质疑决策:为什么这样?有没有更简单的路?
|
|
147
|
+
4. 每次只提出一个最尖锐的问题,等我回答
|
|
148
|
+
|
|
149
|
+
直到这个计划经得起推敲。`,"tpl.sk.tdd":"测试驱动","tpl.sk.tdd.desc":"红-绿-重构的规则","tpl.sk.tdd.prompt":`请用 TDD(红-绿-重构)完成:
|
|
150
|
+
|
|
151
|
+
1. 先写会失败的测试,覆盖正常路径、边界与错误分支
|
|
152
|
+
2. 用最小实现让测试通过
|
|
153
|
+
3. 重构并保持测试通过
|
|
154
|
+
|
|
155
|
+
避免三种反模式:与实现耦合的测试、空洞断言(永远为真)、横向切片(只测表面)。每步汇报并运行测试。`,error:"出错",done:"完成",running:"执行中…",toolQueued:"排队中",copyArgs:"复制参数",copyMessage:"复制消息",copied:"已复制",errorOutput:"错误输出",output:"输出",waitingOutput:"等待输出…",toolDoneWaitingModel:"已结束 · 等模型",waitingModel:"等待模型响应…",thinkingNow:"思考中",thinkingPreview:"思考:{preview}",commands:"命令",newCommand:"新建命令",newTerminal:"新建终端",name:"名称",command:"命令",cwdHint:"(${pwd} = 当前工作目录)",noCommands:"还没有命令,点 + 添加一个",clickToRun:"点击运行",edit:"编辑",delete:"删除",confirmQ:"确认?",builtinTerminal:"内置终端",termEmptySub:"点击左侧命令运行,或点右侧 + 新建终端",noTerminal:"暂无终端",exited:"(已退出{code})",exitBanner:"[进程已退出,退出码 {code}]",closeTerminal:"关闭终端",renameTerminal:"重命名终端",rerun:"重新读取 .pi/commands.json",terminalTitle:"终端 {n}",aiBashGroup:"终端接管 bash",exampleName:"例如:启动开发服务器",exampleCommand:"例如:npm run dev",scmTab:"Git",scmTitle:"源代码管理",scmRefreshTip:"重新查询 Git 状态与差异",scmCurrentBranch:"当前分支",scmUpstreamGone:"上游已删除",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"分离 HEAD",scmSelectBranch:"选择分支…",scmRemoteBranches:"远程分支",scmStageTip:"暂存 {path}",scmUnstageTip:"取消暂存 {path}",scmSwitch:"切换",scmSwitchBranch:"切换分支",scmSwitchBranchTip:"在终端中执行 git checkout {branch}",scmPush:"推送",scmPushTip:"在终端中执行 git push",scmPull:"拉取",scmPullTip:"在终端中执行 git pull",scmCommit:"提交",scmCommitTip:'在终端中执行 git commit -m "…"(仅提交已暂存的更改)',scmCommitAll:"全部提交",scmCommitAllTip:'在终端中执行 git add -A && git commit -m "…"(暂存全部更改含未跟踪并提交)',scmCommitPlaceholder:"输入提交信息…",scmChanges:"更改",scmHistory:"提交树",scmCommitDetail:"提交详情",scmSelectCommitHint:"点击左侧提交查看详情",scmNoHistory:"暂无提交记录",scmNoChanges:"工作区干净,没有更改",scmNotGitRepo:"当前目录不是 Git 仓库",scmLoading:"查询中…",scmConnecting:"等待连接…",scmDiff:"差异",scmSelectFileHint:"点击左侧文件查看差异",scmNoDiff:"(无差异)",scmStaged:"已暂存",scmUnstaged:"未暂存",scmStagedUnstaged:"已暂存 + 未暂存",scmUntracked:"未跟踪",scmUntrackedNote:"未跟踪文件:需先用 + 暂存,或使用“全部提交”才会包含",scmQueryFailed:"Git 查询失败:{error}",scmQueryFailedShort:"查询失败",pluginCommandFallback:"插件命令",scmTooManyFailures:"Git 查询连续失败,请点击刷新重试",scmRunsInTerminal:"提交 / 切换分支 / 推送 / 拉取在终端中执行",scmViewTerminal:"去终端",editProvider:"编辑服务商",builtinProviders:"内置服务商",hintKeyOnly:"只需填入 API 密钥",providerAuthHint:"选择服务商支持的登录方式",oauthLogin:"使用 {name} 登录",oauthLogout:"退出登录",oauthConnected:"已通过 {name} 登录",oauthDeviceCode:"设备验证码",oauthOpenVerification:"打开验证页面",oauthContinue:"继续",configuredBadge:"✓ 已配置",keyReady:"密钥已就绪",replaceKey:"更换密钥",replaceKeyTitle:"替换已保存的密钥",clearKey:"清空",clearKeyTitle:"清除该服务商保存在 auth.json 的密钥,回到未配置状态(环境变量来源的无法在此清除)",clearKeyConfirm:"清空 {id} 已保存的密钥?其模型将从列表消失,直到重新配置。",cloneProvider:"添加密钥",cloning:"添加中",cloneProviderTitle:"为该供应商添加第二把密钥(自动复制 baseUrl 与模型列表,可改名后保存)",pasteKey:"粘贴 API 密钥…",savingKey:"保存中",saveKey:"保存密钥",addKey:"添加密钥",addKeyPlaceholder:"粘贴密钥值…",keyNamePh:"名称(可留空,如 备用)",providerIdPlaceholder:"供应商 ID",baseUrlExamplePh:"baseUrl 链接,如 https://api.opencode.ai/zen/v1 或 http://127.0.0.1:4096",saveAllBatch:"一键保存全部({n})",netDisconnected:"网络连接已断开,请重连后重试",advancedEdit:"高级编辑",batchCreateProviders:"批量创建供应商({n}个接口)",secondKeyTitle:"为 {api} · {baseUrl} · {n} 个模型添加第二把密钥,只需指定新供应商名字和密钥即可。",noBaseUrlShort:"(无 baseUrl)",providerNameLabel:"供应商名字",providerNameHint:"(新 ID,如 opencode-2)",apiKeyLabel:"API 密钥",secondKeyPlaceholder:"sk-… 第二把 key",batchDesc:"该供应商含多种接口({apis}),已按接口拆分为 {n} 个自定义供应商,分别保存后才能让所有模型(如 muse-spark)都可用。统一填入第二把 API 密钥后一键保存。",batchKeyLabel:"统一 API 密钥(将应用到全部 {n} 个供应商)",modelsCountShort:"{n} 个模型:",noKeyYet:"尚无密钥,添加一把即可用",activateKey:"设为当前",removeKey:"移除",removeKeyConfirm:"确定移除该密钥?移除后需重新配置才能使用。",customProviders:"自定义服务商",customDesc:"用于 Ollama / vLLM / 兼容 OpenAI 的代理等,写入 pi 的 models.json,保存后热重载、立即生效。",noCustomProviders:"还没有自定义服务商",reloadModelsConfig:"重新加载配置",reloadModelsHint:"直接改过 models.json(手工或脚本)?点下面的「重新加载配置」从磁盘重读,无需重启服务。",modelsCount:"{n} 个模型",addProvider:"新增服务商",providerId:"服务商 ID",providerIdHint:"(必填,如 ollama / my-proxy)",displayName:"显示名",displayNamePh:"我的代理",apiType:"API 类型",baseUrlHint:"(OpenAI 兼容端点)",apiKeyHint:"sk-…(可留空,用 auth.json 的密钥)",authHeader:"自动添加 Authorization 请求头",modelsTitle:"模型",modelIdReq:"模型 ID(必填)",text:"文本",textImage:"文本+图片",contextWindow:"上下文",maxOutput:"最大输出",removeModel:"移除模型",addModel:"添加模型",deleteProviderConfirm:"删除服务商 {id} 及其 {n} 个模型?",fetchModels:"自动获取模型列表",fetchModelsHint:"从 baseUrl 的 /models 接口自动拉取模型 ID(服务端请求,不受 CORS 限制)",fetchingModels:"获取中…",fetchModelsOk:"已获取 {n} 个模型",fetchModelsEmpty:"接口未返回任何模型",fetchModelsErr:"获取失败:{msg}",fetchModelsNeedBaseUrl:"请先填写 baseUrl 再获取",goalBarTitle:"目标",goalBarPlaceholder:"设定一个目标,agent 完成后自动审查…",goalBarSet:"开始",goalBarClear:"取消",goalBarLocked:"锁定:应用到后续所有回合",goalBarUnlocked:"仅本回合(改完自动清除)",goalBarReviewModel:"审查模型",goalBarUseMainModel:"使用主模型",goalBarMaxRounds:"最大轮数",goalBarMaxRoundsTip:"最大审查重改轮数;0 或不填 = 不限(持续改到通过)",goalBarUnlimitedShort:"不限",goalBarReviewing:"审查中…",goalBarRound:"第 {n} 轮",goalBarActive:"目标生效中",goalBarPassed:"已通过",goalBarFailed:"未通过",goalBarStatusPending:"等待生成…",goalWizardBtn:"AI 提炼",goalWizardTip:"让 AI 通过问卷调研细化需求,收敛为目标",goalWizardRunning:"目标调研中",goalWizardAnswer:"回答",goalWizardCard:"目标调研",settings:"设置",settingsTitle:"设置",settingsDesc:"修改立即生效:系统提示词、技能与插件开关会重建当前会话;审查提示词与审查技能只影响后续目标审查(回复进行中则主会话变更自动延迟)。",settingsSystemPrompt:"系统提示词",settingsPromptHistory:"输入历史",settingsPromptHistoryDesc:"用 ↑↓ 在输入框循环历史提问,全局跨对话共享(localStorage)",promptHistoryMax:"最大条数",promptHistoryMaxHint:"超过上限时最旧的自动丢弃,可设 1–500",promptHistoryCharLimit:"限制单条字数",promptHistoryCharLimitHint:"开启后超长输入截断后保存,避免大段粘贴占满存储",promptHistoryCharLimitPlaceholder:"最大字数(100–20000)",promptHistoryClear:"清空历史",promptHistoryClearConfirm:"确认清空?",promptHistoryCleared:"已清空输入历史",promptHistoryCount:"当前 {n} 条",promptHistoryEmpty:"暂无历史记录,上/下键暂无可循环内容",settingsPromptMode:"模式",promptModeAppend:"追加",promptModeReplace:"替换",promptAppendHint:"追加模式:自定义内容拼接到默认系统提示词末尾(推荐,保留默认行为约束)。",promptReplaceHint:"替换模式:只替换内置模板的「灵魂提示词」(人物设定段,如 “You are an expert coding assistant…”);工具列表、Guidelines、文档指引、项目上下文、技能段等自动拼装段仍由系统每次重新生成,不会被替换。切换后输入框显示原本的灵魂提示词,可直接修改;留空则使用内置默认。",promptPlaceholder:"输入自定义系统提示词…(失焦后自动应用)",promptComposeHint:"模板里的 {{token}} 在每次对话时展开为对应「来源」的提示词;未覆盖的来源用自动内容(工具列表/项目上下文/技能等永远用最新数据生成)。",promptComposeDesc:"组合模板:{{token}} 自由排序/删改/穿插自己的话;空 = 默认模板。下面每个来源可单独覆盖(留空 = 自动内容),也可逐块恢复默认。",promptTemplateLabel:"组合模板",promptSourcesLabel:"各来源(可单独覆盖)",promptInsertTokens:"插入段落:",promptResetAll:"恢复默认模板并清空所有覆盖",promptResetSource:"恢复默认",promptAutoBadge:"自动",promptOverridePlaceholder:"输入覆盖内容(留空 = 用自动内容)…",promptSourceDefaultEmpty:"(该来源当前无自动内容)",promptReadonlyBadge:"系统自动生成(只读)",promptReadonlyLockedBadge:"自定义覆盖(只读·锁定)",promptReadonlyLockedHint:"该来源由系统自动生成,只读;此覆盖不会被设置面板编辑,服务端仍按原样生效。",promptReadonlyTitle:"系统自动生成的来源,仅只读展示,不可编辑",promptSourceDefaultEditHint:"该来源当前的默认(自动)内容 —— 点击可直接输入覆盖文字",promptSourceExpand:"展开全文",promptSourceCollapse:"收起",promptSourceRefLabel:"默认(自动)内容(可对照 / 复制)",promptSourceSeedButton:"填入默认内容,只改一小部分",promptSourceSeedTip:"把该来源当前的默认内容复制进覆盖框:只想改一小部分时直接改这里。填入后此来源内容固定,不再随每次对话自动重新生成。",promptTok_soul:"灵魂提示词",promptTok_soul_desc:"agent 人物设定(无 SYSTEM.md 时内置默认)",promptTok_tools:"工具列表",promptTok_tools_desc:"Available tools(各工具说明,每次自动生成)",promptTok_guidelines:"行为准则",promptTok_guidelines_desc:"Guidelines:各工具引导 + 通用规则",promptTok_pi_docs:"Pi 文档指引",promptTok_pi_docs_desc:"指向 pi 包文档的提示段",promptTok_append:"追加段",promptTok_append_desc:"APPEND_SYSTEM.md 内容;覆盖 = 自定义追加文字",promptTok_persona:"Windows 约束",promptTok_persona_desc:"Windows persona(仅 win32;超时/PTY/GBK 注意事项)",promptTok_terminal:"终端工具引导",promptTok_terminal_desc:"持久终端使用引导(「终端工具」开时注入)",promptTok_markers:"标记工具引导",promptTok_markers_desc:"内置标记工具使用说明(markers 开时注入)",promptTok_context:"项目上下文",promptTok_context_desc:"<project_context>:AGENTS.md/CLAUDE.md 收集结果",promptTok_skills:"技能段",promptTok_skills_desc:"<available_skills>:可用技能清单",promptTok_cwd:"工作目录行",promptTok_cwd_desc:"Current working directory 行",settingsViewPrompt:"查看当前完整提示词",settingsViewPromptHint:"当前会话实际生效的完整系统提示词(含自定义追加/替换内容、项目上下文、技能说明与工具引导),只读。",settingsViewPromptEmpty:"会话尚未就绪,暂无系统提示词。",settingsViewToolsSchema:"工具 schema",settingsViewToolsSchemaHint:"发给模型的 function-calling 工具定义(name / description / parameters),与系统提示词正文拼成完整初始上下文,只读。",settingsViewToolsSchemaEmpty:"会话尚未就绪,暂无工具 schema。",settingsSkills:"技能",settingsReview:"目标审查",settingsReviewDesc:"为独立的目标审查会话配置额外提示词和技能;不会改变主会话设置。",settingsReviewSkills:"审查可用技能",reviewPromptPlaceholder:"输入审查自定义提示词…(失焦后自动应用)",reviewPromptHint:"这些内容会追加到审查任务中;审查仍会强制要求输出 pass/fail JSON。技能开关仅对审查生效。",goalModeEnabled:"启用目标模式",goalModeEnabledDesc:"目标条 / 目标调研向导 / 审查循环的总开关(默认开)。关闭后目标条隐藏,无法设置目标、启动调研或触发审查。",goalModeOffHint:"目标模式已关闭:目标条已隐藏,已有的目标将不再触发审查。",settingsVisionBridge:"视觉桥",settingsVisionBridgeDesc:"当前模型不支持识图时,把图片交给已配置的视觉模型转写为文字证据,再让模型回答",visionBridgeEnabled:"启用视觉桥",visionBridgeModel:"转写模型",visionBridgeAuto:"自动选择(按顺序)",visionBridgeNoModels:"未找到已配置的视觉模型:在模型配置里添加任意支持图片的模型(如 qwen-vl、GLM-4V、Gemini)即可自动启用",visionBridgeOffHint:"已关闭:图片将原样发送,纯文本模型可能看不到图片内容",visionBridgeCurrent:"当前转写模型:{model}",visionBridgePromptMode:"转写提示词",settingsMarkers:"标记工具",settingsMarkersDesc:"让 AI 用 [[todo:...]] / [[notify:...]] / [[conv:rename:...]] 内联标记在正文里改状态,无需工具往返。全局关闭则全部停用;分组开关可细粒度控制。",markersEnabled:"启用标记工具(全局)",markersEnabledDesc:"关闭后 AI 不再收到任何标记引导,解析也跳过(所有标记原文原样保留,不执行)。",markersOffHint:"已全局关闭:所有标记停用,AI 不会写标记,也不会触发任务/重命名等副作用。",markerGroupTodo:"任务标记 todo",markerGroupNotify:"提醒标记 notify",markerGroupRename:"重命名标记 conv/rename",markerRenameTip:"[[conv:rename:新标题]] 重命名当前对话(标题 ≤80 字;在回复第一条消息末尾根据情况重命名)",settingsTerminalTools:"终端工具",terminalToolsEnabled:"启用持久终端工具",settingsTerminalToolsDesc:"让 AI 在交互式程序(REPL/vim)、长驻服务、需要持续观察输出或你要求在可见终端操作时,使用内置终端;普通命令仍走一次性 bash 工具",terminalToolsOffHint:"已关闭:AI 无法使用 terminal_* 工具,也不会收到相关使用引导",settingsEditTools:"编辑工具",editSoftEnabled:"启用编辑工具 edit_soft",editSoftEnabledDesc:"让 AI 用一个独立、不严格要求缩进的编辑工具:当你的 oldText 与文件缩进/空白不一致(如 JS/JSON)时可避免因缩进差异导致编辑失败。命中后按你给出的 newText 原样写入(缩进即最终缩进)。",editSoftOffHint:"已关闭:AI 无法使用 edit_soft 工具,也不会收到相关使用引导",settingsQuestionnaire:"问卷提问",questionnaireEnabled:"允许模型向我提问(问卷)",questionnaireEnabledDesc:"开启默认值:模型可用 ask_user_question 弹出可回复的问卷/提问对话框(含选项、多选、自定义输入)。关闭后模型将不再弹出问卷,调用也会直接返回已禁用。",questionnaireOffHint:"已关闭:模型不能再向你弹出问卷/提问对话框",browserPageEnabledDesc:"让模型操作浏览器里被授权的页面(page-picker 扩展的 browser_page 工具:读内容 / 点击 / 输入 / 滚动 / 跳转,eval 另有单独开关)。需要先在扩展选项页授权目标页面。",browserPageOffHint:"已关闭:模型不能再点你的页面、也不能在页面里执行脚本",browserControl:"浏览器操作",browserControlTip:"让 AI 操作你在浏览器里授权的页面(读内容 / 点按钮 / 填表单 / 滚动),需要 page-picker 扩展;授权与开关都在扩展设置页里。",browserControlChecking:"正在查询扩展状态…",browserControlOffline:"还没连上浏览器扩展:装好(或启用)page-picker 扩展,在本页点一次扩展图标绑定地址,然后刷新本页。",browserControlInstall:"装扩展(两分钟)",browserControlInstallLead:"扩展不在 Chrome 应用商店,不用去商店搜,按下面四步装:",browserControlInstallDownload:"下载 page-picker-extension.zip(永远是最新版)",browserControlInstallStep1:"解压 zip(得到含 manifest.json 的目录)。",browserControlInstallStep2:"Chrome / Edge 打开 chrome://extensions(Edge 是 edge://extensions),右上角打开「开发者模式」。",browserControlInstallStep3:"点「加载已解压的扩展程序」,选中第 1 步解压出的目录。",browserControlInstallStep4:"回到这个 pi-web-ui 页面点一下扩展图标,按提示「设为服务地址」——地址端口不用手填。",browserControlEmpty:"扩展已就绪,但还没授权任何页面 —— 点下面的「打开扩展设置页」,在那里授权一个页面。",browserControlDisabled:"「允许 AI 操作页面」总开关是关的 —— 在扩展设置页打开它。",browserControlPages:"已授权的页面",browserControlPageOpen:"开着",browserControlPageClosed:"没打开",browserControlExamples:"可以这样让它干活",browserControlExample1:"「把那个页面上的订单读出来,按金额排序」",browserControlExample2:"「在搜索框输入 张三,点查询,等结果出来告诉我第一条」",browserControlOpenOptions:"打开扩展设置页",browserControlRefresh:"刷新状态",browserControlCite:"引用到对话",browserControlCiteTip:"把 {name} 作为网页引用放进输入框(不自动发送,你补一句话再发)",browserControlCiteNote:"点「引用到对话」会把网页引用放进输入框:模型据此知道操作哪个页面,不必再手打网址。",browserControlCited:"已引用到输入框 —— 补一句话再发",browserControlCiteFailed:"输入框还没准备好,稍后再试",browserControlOpenPanel:"打开面板(状态 / 授权管理)",browserControlSingleTip:"点击把 {name} 引用到对话;右侧 ▾ 打开面板",browserControlDesktop:"桌面版用不了浏览器操作 —— 不是你装错了",browserControlDesktopLead:"桌面窗口里没有 Chrome 扩展运行时,page-picker 扩展装不上。用下面的按钮在系统浏览器里打开同一个地址,再按网页版的四步装扩展即可。",browserControlOpenInBrowser:"用默认浏览器打开当前地址",attachPage:"网页引用:{name}(AI 已获授权操作这个页面)",attachPageShort:"网页",settingsTools:"工具",toolsSectionTerminal:"持久终端",toolsSectionSubagent:"子代理",toolsSectionOther:"其他工具",toolsSubagentDepHint:"逐个开关:关闭 subagent_spawn 后其余(等待/查询/改向/停止)无会话可管,只会返回空列表或“未找到”;delegate_task 走 spawn 通道,spawn 关了它也派不出去。",delegateTaskEnabledDesc:"把定义清楚的任务派给 specialist 子代理模板:六段派单(TASK/EXPECTED OUTCOME/REQUIRED TOOLS/MUST DO/MUST NOT DO/CONTEXT)在服务端校验,缺段或含糊直接报错打回。执行体复用子代理 spawn 通道。",delegateTaskOffHint:"已关闭:AI 无法使用 delegate_task 派单(可用 subagent_spawn 自由派单,不带六段校验)",todoListEnabledDesc:"只读查询当前任务列表,删除项需显式传参;写操作不走工具,直接写内联标记。",todoListOffHint:"已关闭:AI 不能再调查询工具(内联标记的写入不受影响)",toolDescSubagentSpawn:"后台起独立子代理对话(左栏可见),做可独立交付的任务;可并行多个。",toolDescSubagentGetResult:"取单个子代理的结果或当前进度;未完成返回现状和部分输出。",toolDescSubagentSteer:"向运行中的子代理注入消息,改向或补充要求。",toolDescSubagentList:"列出全部子代理的运行态(id/类型/状态/标题)。",toolDescSubagentStop:"停止运行中的子代理(等同中止它那路对话)。",toolDescSubagentWaitAll:"一次等多个子代理全部完成并汇总结果,不用轮询。",toolDescSubagentTemplates:"列出可用的子代理模板(停用的不出现),供 spawn 选用。",settingsMessageDisplay:"对话",thinkingWrap:"完整显示思考",thinkingWrapDesc:"开启:思考内容始终完整展开并自动换行(流式推理过程也实时可见);关闭:折叠成一行摘要,流式中一行实时显示最新文本",toolsWrap:"完整显示工具",toolsWrapDesc:"开启:工具调用始终完整展开显示参数和输出;关闭:默认折叠,点击展开",devNoCache:"开发模式:不缓存页面",devNoCacheDesc:"开启:每次加载都取最新页面(源码开发用);关闭:允许浏览器缓存(安装包默认)",autoReload:"新构建自动重载页面",autoReloadDesc:"开启:服务端重建后页面自动重载(源码开发用);关闭:只重连不断页面(安装包默认)",wideChat:"宽屏聊天列",wideChatDesc:"开启:中央列铺满宽度(超宽屏有用);关闭:保持 860px 上限",projectTitle:"标题显示项目名",projectTitleDesc:"开启:浏览器标签页标题为「项目目录名 — pi-web-ui」,切项目即时更新(多标签页开多个项目时好区分);关闭:固定显示应用名",terminalBashTakeover:"终端接管 bash",terminalBashTakeoverDesc:"此开关决定 bash 是否覆盖为终端版:关 = 原生 SDK bash(纯进程、不开终端);开 = 跑进可见终端,且 persist 参数在本开关的基础上决定一次性(false,命令跑完进程退出、输出留档)还是持久(true,shell 状态跨调用保留、静默自动转后台并通知 AI)",terminalBashIdleMs:"静默转后台阈值(毫秒)",terminalBashIdleMsDesc:"持久终端模式下,命令连续无输出达到该时长即不再阻塞等待,转入后台继续运行并通知 AI;0 = 一直等到命令结束(默认 15000)",visionBridgePromptPlaceholder:"输入自定义转写提示词…(留空 = 使用内置默认提示词,失焦后自动应用)",visionBridgePromptAppendHint:"追加模式:自定义内容拼接到内置转写提示词末尾(推荐,保留默认的逐字转写约束)。",visionBridgePromptReplaceHint:"替换模式:完全用自定义内容替换内置转写提示词。切换后输入框会显示内置默认提示词,可直接修改;不改动失焦则仍使用默认。",uninstallExt:"卸载",uninstallConfirm:"确认卸载?",uninstallConfirmHint:"再次点击确认,将在终端执行 pi remove",uninstallHint:"通过可见终端执行 pi remove 卸载此包,完成后自动刷新列表",uninstallTitle:"卸载",pluginUpdate:"更新",pluginUpdateHint:"从安装来源重新拉取并覆盖安装(保留 config.json 配置);后台执行,设置面板不用关,进度就地显示",pluginMarket:"插件市场",updatesManaged:"本实例由部署方管理:更新与插件安装不在此进行",pluginCatalogAdd:"添加插件",pluginCatalogAddHint:"把第三方插件填进可安装列表(owner/repo 或完整 GitHub 地址)",pluginCatalogSource:"来源 owner/repo 或 owner/repo/子目录(必填)",pluginCatalogId:"id(可选,默认取仓库/子目录名)",pluginCatalogName:"名称(可选)",pluginCatalogIcon:"图标 emoji(可选)",pluginCatalogDesc:"简介(可选)",pluginCatalogAddSubmit:"添加到列表",noPluginCatalog:"列表为空 —— 点「添加插件」把第三方插件填进列表",pluginInstalled:"已安装",pluginCatalogCustom:"自定义",pluginInstall:"安装",pluginInstallHint:"后台安装到界面插件(不用关设置面板,进度就地显示)",pluginCatalogRemoveHint:"从列表移除这条自定义插件",pluginUninstallHint:"后台卸载此插件(再次点击确认),完成后自动刷新列表",pluginJobRunning:"后台执行中…",pluginJobDone:"已完成",pluginJobFailed:"插件操作失败",pluginBuildSource:"源码构建",pluginBuildHint:"安装/更新前先在隔离目录里构建(等价 CLI --build;只有源码没有产物时会自动构建,无需勾选)",pluginCatalogSync:"从目录同步",pluginCatalogSyncHint:"从目录文档同步可安装列表(与插件的 reloadCatalog 同一通道)",pluginCatalogSyncSource:"目录 URL(http(s))或本地绝对路径",pluginCatalogSyncSubmit:"同步",pluginCatalogSyncInstall:"同步后安装全部条目",pluginCatalogSyncReplace:"整体替换(默认按 id 合并)",pluginCatalogSyncRecent:"最近同步",pluginCatalogSyncOk:"同步成功:列表共 {n} 条",pluginCatalogSyncInstalled:"安装结果:{ok} 成功,{fail} 失败",uiLayoutTitle:"界面布局",uiLayoutHint:"插件可以调整这里的条目(包括宿主内置入口);你随时能改回来:取消勾选=隐藏,↑/↓ 调顺序,改过的条目会显示「恢复」。隐藏的条目仍能在顶栏溢出菜单里点到。",pluginTopbarMore:"更多插件按钮",uiLayoutTopbar:"顶栏",uiLayoutTopbarOverflow:"顶栏溢出菜单",uiLayoutBottombar:"底栏",uiLayoutComposer:"输入框动作",uiLayoutMessage:"消息工具条",uiLayoutRightPanel:"右侧面板",uiLayoutSettingsPages:"设置页",uiLayoutRestore:"恢复",uiLayoutRestoreAll:"全部恢复默认",uiLayoutArranged:"插件调整过",uiLayoutEmpty:"(无)",pluginGrantsTitle:"已授权目录",pluginGrantsHint:"插件要访问工作区之外的目录时必须先经你确认(确认过的会记在这里,可随时撤销)。",pluginGrantsEmpty:"还没有插件获得过工作区外的目录授权",pluginGrantsRevoke:"撤销",pluginGrantRequestTitle:"插件请求访问目录",pluginGrantRequestBody:`{plugin} 想访问下面这个目录:
|
|
156
|
+
|
|
157
|
+
{path}`,pluginGrantAllow:"允许",pluginGrantDeny:"拒绝",pluginUiNoHandler:"插件没有接管这个动作(可能版本不匹配)",pluginSessionGrantTitle:"插件请求打开一个项目会话",pluginSessionGrantBody:`插件想在下面这个目录里打开一个新会话(工作区会切过去):
|
|
158
|
+
|
|
159
|
+
{path}
|
|
160
|
+
|
|
161
|
+
只在你确认后打开。`,settingsExtensions:"插件",settingsUiPlugins:"界面插件",noUiPlugins:"未安装界面组件(<dataDir>/plugins/)",dshPatches:"DSH 用户补丁",dshPatchesDesc:"启动时按文件名序加载的 Cordis patch(<dataDir>/dsh-patches/*.yml)。新增/修改后点「重扫」重启运行时生效;失败的文件会被跳过并打印到运行时 stderr。",dshPatchesRescan:"重扫",dshPatchesRescanHint:"重新扫描补丁目录并重启 DSH 运行时使新补丁生效",dshPatchesEmpty:"未放置补丁文件",dshPatchesPath:"补丁目录:",dshPreset:"Agent 预设",dshPresetNewChat:"以此预设开新对话",dshPresetLocked:"已锁定",dshPresetBlankOnly:"首轮发言后锁定,空白会话可切换",dshPresetBroken:"(不可用)",dshPresetUser:"自建",dshPresetDefaultTag:"默认",dshPresetCurrent:"当前",dshPresetMinimalNote:"极简模式:仅持久 shell;宿主插件工具与问卷不可用",dshDefaultPreset:"默认预设",dshDefaultPresetDesc:"新对话使用的预设;空白会话可随时切换,首轮发言后锁定",dshPresetUserNote:"自建预设来自用户预设目录(与 shell 同等信任);用裸包名的自建组合在此无法挂载(已知限制)",dshPerm:"权限",dshPermReadOnly:"仅可查看",dshPermReadOnlyDesc:"只能读文件、跑只读命令;写操作一律拒绝,不弹确认",dshPermWorkspaceWrite:"工作区内修改",dshPermWorkspaceWriteDesc:"工作区内读写,不弹确认;超出范围的操作直接拒绝",dshPermFullAccess:"完全权限",dshPermFullAccessDesc:"关闭沙箱,整机任意读写;只给信任的任务",dshPermFullAccessTag:"高危",dshPermCustom:"自定义",dshPermConfirmFull:"再点一次确认开启完全权限",dshPermDefault:"新会话默认权限",dshPermDefaultDesc:"新对话的初始权限;当前对话可随时热切换,无需重启",uiPluginNoSource:"手工安装,无来源信息,无法在线更新",uiPluginPerms:"能力声明",pluginDomNeed:"⚠ 请求完全 DOM 访问",pluginDomDesc:"该插件可直接读写页面 DOM(绕过界面布局限制)。只给可信来源的插件授权;授权后其界面代码可碰顶栏/输入框/任意页面元素。",pluginDomGrant:"授权 DOM 访问",pluginDomRevoke:"撤销 DOM 访问",pluginDomGranted:"已授权完全 DOM 访问",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:"上下文"},np={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",atMentions:"Mentions",atMenuHint:"↑↓ select · Enter/Tab insert",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",homeDir:"Home directory",desktopDir:"Desktop",filesHelp:`Navigate: click a folder to enter, a file to preview, '..' to go up; Root returns to the current project, This PC browses all drives, 🏠 jumps to your home directory, 🖥️ to the desktop.
|
|
162
|
+
Manage: right-click for new file/folder, rename, copy/cut/paste, duplicate, delete, upload; files can be downloaded, row buttons copy name/path.
|
|
163
|
+
Switch projects: right-click a folder → Open as project, or click the bottom-right 📁 path button to type/pick a directory.
|
|
164
|
+
Send to AI: row buttons attach content or reference a path, or drag files into the input.`,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]…
|
|
165
|
+
`,uploadToFolder:"Upload files to this folder",uploadToCurrentDir:"Upload files to current directory",openAsProject:"Open as project",fileOpenPreview:"Open preview",fileEnterDir:"Open folder",fileNewFile:"New file",fileNewDir:"New folder",fileRename:"Rename",fileNamePlaceholder:"File name",fileDuplicate:"Duplicate",fileCut:"Cut",fileCopyEntry:"Copy",filePaste:"Paste",fileDelete:"Delete",fileDeleteConfirm:"Delete {name}?",fileCopyRelPath:"Copy relative path",fileRefresh:"Refresh",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:
|
|
166
|
+
|
|
167
|
+
1. Project type, tech stack and directory layout
|
|
168
|
+
2. Concrete commands for build / test / run / format
|
|
169
|
+
3. Code conventions and naming rules
|
|
170
|
+
4. Where tasks / issues live and their format
|
|
171
|
+
5. Known pitfalls or leftover issues
|
|
172
|
+
|
|
173
|
+
Report only — do not modify any files.`,"tpl.sk.ask":"Skill navigator","tpl.sk.ask.desc":"Tell me which workflow to use","tpl.sk.ask.prompt":"I'll describe the situation I'm in; you decide the best workflow (clarify requirements / plan & execute / TDD / debugging / architecture / review / handoff, etc.), explain why you recommend it and how you'd run it, then execute it after I confirm.","tpl.sk.grilldocs":"Grill & record","tpl.sk.grilldocs.desc":"Interview the plan and record decisions","tpl.sk.grilldocs.prompt":"Before starting, grill me about this plan (one question at a time) until we reach shared understanding. Record key terms and settled decisions as you go (e.g. into CONTEXT.md or an ADR file) so all later work shares one vocabulary. Give your recommended answer with each question.","tpl.sk.tospec":"To spec","tpl.sk.tospec.desc":"Turn the agreed discussion into a written spec","tpl.sk.tospec.prompt":`Turn the consensus we reached into a structured specification:
|
|
174
|
+
|
|
175
|
+
1. Background and goals
|
|
176
|
+
2. Explicit goals and non-goals
|
|
177
|
+
3. Users and usage scenarios
|
|
178
|
+
4. Edge cases and failure modes
|
|
179
|
+
5. Acceptance criteria (what counts as done)
|
|
180
|
+
6. Interface / data-shape overview
|
|
181
|
+
|
|
182
|
+
Output the spec for my review first, then continue only after I confirm.`,"tpl.sk.totickets":"To tickets","tpl.sk.totickets.desc":"Split the spec into small buildable tickets","tpl.sk.totickets.prompt":`Split this spec into a set of small tickets an agent can build one by one:
|
|
183
|
+
|
|
184
|
+
1. Each ticket small enough to be independently accepted
|
|
185
|
+
2. Annotate dependency order (what must come first)
|
|
186
|
+
3. Each ticket has: what to do, acceptance criteria, files involved
|
|
187
|
+
4. Flag which tickets can run in parallel
|
|
188
|
+
|
|
189
|
+
Output the ticket list; I'll confirm the order before you execute.`,"tpl.sk.implement":"Implement spec","tpl.sk.implement.desc":"Build the finished spec, test-first","tpl.sk.implement.prompt":`Implement per this spec, test-first:
|
|
190
|
+
|
|
191
|
+
1. Write failing tests for each ticket first (happy path, edges, error branches)
|
|
192
|
+
2. Make them pass with the minimal implementation
|
|
193
|
+
3. Refactor while keeping tests green
|
|
194
|
+
4. Proceed ticket by ticket, reporting briefly after each
|
|
195
|
+
|
|
196
|
+
Finally check every acceptance criterion explicitly.`,"tpl.sk.codeview":"Code review","tpl.sk.codeview.desc":"Review the diff against the spec and your standards","tpl.sk.codeview.prompt":`Review the recently changed diff:
|
|
197
|
+
|
|
198
|
+
1. Against the spec: is the implementation complete and faithful?
|
|
199
|
+
2. Correctness: edges, nulls, concurrency and timing
|
|
200
|
+
3. Security: input validation, injection, sensitive data
|
|
201
|
+
4. Performance & readability: does it follow project conventions?
|
|
202
|
+
5. Tests: are critical paths covered?
|
|
203
|
+
|
|
204
|
+
List issues by severity, each with a concrete suggestion.`,"tpl.sk.wayfinder":"Wayfinder","tpl.sk.wayfinder.desc":"Chart a large effort as a map of decisions","tpl.sk.wayfinder.prompt":`This is a large task. First chart it as a decision map:
|
|
205
|
+
|
|
206
|
+
1. List every decision point and its dependencies
|
|
207
|
+
2. For each decision give options, trade-offs and your recommendation
|
|
208
|
+
3. Mark what can run in parallel vs. what must be sequential
|
|
209
|
+
4. Output a path plan; I'll confirm each item before you start.`,"tpl.sk.prototype":"Prototype","tpl.sk.prototype.desc":"Answer a design question with throwaway code","tpl.sk.prototype.prompt":`Write a minimal prototype to validate the design assumption:
|
|
210
|
+
|
|
211
|
+
1. Validate only the key assumption, not the full implementation
|
|
212
|
+
2. Use the simplest means (hard-coding and skipped edge cases are fine)
|
|
213
|
+
3. Run it and tell me the verdict: does the assumption hold? trade-offs?
|
|
214
|
+
4. The prototype can be deleted, or made production-ready only after I confirm.`,"tpl.sk.research":"Research","tpl.sk.research.desc":"Get a cited answer from primary sources","tpl.sk.research.prompt":`Research this question, preferring primary sources (official docs / source / specs):
|
|
215
|
+
|
|
216
|
+
1. Give an answer with source links
|
|
217
|
+
2. Distinguish facts, reasonable inference, and what's still uncertain
|
|
218
|
+
3. List the main options and their trade-offs
|
|
219
|
+
4. Don't stitch together secondary content; say so if you can't find it.`,"tpl.sk.arch":"Architecture review","tpl.sk.arch.desc":"Find the modules worth refactoring (report)","tpl.sk.arch.prompt":`Do an architecture review of the whole codebase:
|
|
220
|
+
|
|
221
|
+
1. Find signs of broken deep modules: oversized functions/classes, duplication, poor naming, hidden coupling
|
|
222
|
+
2. Prioritize improvements by severity and blast radius; produce a visual report
|
|
223
|
+
3. For each item give the minimal viable refactor with rationale
|
|
224
|
+
4. Report before changing anything; confirm scope before refactoring.`,"tpl.sk.debug":"Diagnose bugs","tpl.sk.debug.desc":"Diagnose from a repro that fails","tpl.sk.debug.prompt":`Diagnose this bug systematically:
|
|
225
|
+
|
|
226
|
+
1. Reproduce it first (build a minimal repro if none exists)
|
|
227
|
+
2. Narrow to a specific module via bisection or elimination
|
|
228
|
+
3. Form hypotheses and verify with logs / assertions / a minimal sample — no guessing
|
|
229
|
+
4. Once the root cause is found, explain it, then make the minimal fix
|
|
230
|
+
5. Add a regression test to prevent recurrence.`,"tpl.sk.merge":"Resolve merge conflicts","tpl.sk.merge.desc":"Finish a merge or rebase conflict hunk by hunk","tpl.sk.merge.prompt":`Help me resolve this merge / rebase conflict:
|
|
231
|
+
|
|
232
|
+
1. Handle each conflict hunk, reading both sides' intent first
|
|
233
|
+
2. Choose or merge to keep correct semantics — don't blindly pick one side
|
|
234
|
+
3. Run tests and build afterwards to confirm
|
|
235
|
+
4. Finally summarize the rationale for each resolution.`,"tpl.sk.triage":"Triage","tpl.sk.triage.desc":"Sort raw issues into work someone can pick up","tpl.sk.triage.prompt":`Turn these raw issues / feedback into actionable work items:
|
|
236
|
+
|
|
237
|
+
1. Deduplicate and merge related entries
|
|
238
|
+
2. Categorize (bug / feature / improvement / question)
|
|
239
|
+
3. Prioritize by impact and urgency
|
|
240
|
+
4. For each item add: repro info or expectation, acceptance criteria
|
|
241
|
+
|
|
242
|
+
Output the cleaned list.`,"tpl.sk.wizard":"Setup wizard","tpl.sk.wizard.desc":"Generate a script that walks a human through setup","tpl.sk.wizard.prompt":`Create a guided wizard (script or doc) for a manual setup flow:
|
|
243
|
+
|
|
244
|
+
1. Guide step by step, explaining why at each step
|
|
245
|
+
2. Validate each step; on wrong input give actionable hints
|
|
246
|
+
3. Support undo / going back a step
|
|
247
|
+
4. End with a self-check and how to verify.`,"tpl.sk.grillme":"Grill me","tpl.sk.grillme.desc":"Align on an idea before committing","tpl.sk.grillme.prompt":`Before starting, interview me relentlessly about every aspect of this idea until we reach shared understanding (one question at a time, each with your recommended answer):
|
|
248
|
+
|
|
249
|
+
1. Goals and non-goals
|
|
250
|
+
2. Users and scenarios
|
|
251
|
+
3. Edge cases and failure modes
|
|
252
|
+
4. Constraints and dependencies
|
|
253
|
+
5. Acceptance criteria
|
|
254
|
+
|
|
255
|
+
Then give an implementation plan and wait for my confirmation before writing code.`,"tpl.sk.handoff":"Handoff","tpl.sk.handoff.desc":"Write up a long session so another agent can continue","tpl.sk.handoff.prompt":`Turn this session into a handoff doc so another agent / teammate can continue seamlessly:
|
|
256
|
+
|
|
257
|
+
1. Background and goals
|
|
258
|
+
2. Work done and key decisions (with reasons)
|
|
259
|
+
3. Outstanding items and next steps
|
|
260
|
+
4. Known risks and open questions
|
|
261
|
+
5. How to verify current state (commands, etc.)
|
|
262
|
+
|
|
263
|
+
Output as a structured document.`,"tpl.sk.questionnaire":"To questionnaire","tpl.sk.questionnaire.desc":"Turn open questions into a doc someone fills in","tpl.sk.questionnaire.prompt":`Turn the info you need from someone into a fillable questionnaire:
|
|
264
|
+
|
|
265
|
+
1. Explain the background and purpose of each question
|
|
266
|
+
2. Mark required / optional
|
|
267
|
+
3. Give example answers to lower friction
|
|
268
|
+
4. Group and order: easy first, hard later
|
|
269
|
+
|
|
270
|
+
Output a doc they can fill in directly.`,"tpl.sk.teach":"Teach","tpl.sk.teach.desc":"Learn a topic across sessions that build on each other","tpl.sk.teach.prompt":`Teach me this topic incrementally:
|
|
271
|
+
|
|
272
|
+
1. First set a learning path and goal
|
|
273
|
+
2. Teach one small section at a time, then a quick exercise
|
|
274
|
+
3. Build on the previous section and ask questions to confirm understanding
|
|
275
|
+
4. Summarize key points at the end of each section
|
|
276
|
+
|
|
277
|
+
Works well across multiple sessions.`,"tpl.sk.ww":"Wait, what?","tpl.sk.ww.desc":"Say the last explanation again in plain English","tpl.sk.ww.prompt":`Re-explain what you just said in the simplest terms:
|
|
278
|
+
|
|
279
|
+
1. Avoid jargon; define any term you must use in one sentence
|
|
280
|
+
2. Use an analogy or concrete example
|
|
281
|
+
3. Be clear about what is still guesswork / uncertain
|
|
282
|
+
4. Keep the core point as short as possible.`,"tpl.sk.wfa":"Writing for agents","tpl.sk.wfa.desc":"Write docs that follow agent-friendly principles","tpl.sk.wfa.prompt":`Write this doc / explanation following “written for agents to read” principles:
|
|
283
|
+
|
|
284
|
+
1. Put the goal and usage up front
|
|
285
|
+
2. Make instructions concrete and verifiable — no vagueness
|
|
286
|
+
3. Give positive and negative examples
|
|
287
|
+
4. Structure with headings, steps and checklists
|
|
288
|
+
5. Mark what's required vs. optional.`,"tpl.sk.codesign":"Deep-module design","tpl.sk.codesign.desc":"Review & design with deep-module principles","tpl.sk.codesign.prompt":`Review / design using the “deep module” principle:
|
|
289
|
+
|
|
290
|
+
1. Check whether each module's public interface is simpler than its implementation
|
|
291
|
+
2. Find modules that leak complexity outward
|
|
292
|
+
3. Give responsibility boundaries and improvement plans
|
|
293
|
+
4. Balance cohesion and reuse without over-abstracting
|
|
294
|
+
|
|
295
|
+
Output the review conclusions and refactor suggestions.`,"tpl.sk.domain":"Domain modeling","tpl.sk.domain.desc":"Sharpen the words a project uses and write them down","tpl.sk.domain.prompt":`Help me clean up this project's domain language:
|
|
296
|
+
|
|
297
|
+
1. Find the core terms and their current spellings
|
|
298
|
+
2. Spot confusion from same-word-different-meaning / different-word-same-meaning
|
|
299
|
+
3. Recommend one canonical term each, into a glossary
|
|
300
|
+
4. State each term's boundary (what it is not)
|
|
301
|
+
|
|
302
|
+
Output a domain glossary.`,"tpl.sk.grilling":"Grilling","tpl.sk.grilling.desc":"Stress-test a plan with an interview","tpl.sk.grilling.prompt":`Stress-test this plan with an interview:
|
|
303
|
+
|
|
304
|
+
1. Check each assumption: what if it's wrong?
|
|
305
|
+
2. Hunt for holes: edges, failure modes, dependencies, timing
|
|
306
|
+
3. Challenge decisions: why this way? is there a simpler path?
|
|
307
|
+
4. Ask one sharp question at a time and wait for my answer
|
|
308
|
+
|
|
309
|
+
Keep going until the plan holds up.`,"tpl.sk.tdd":"Test-driven","tpl.sk.tdd.desc":"The rules of the red-green-refactor loop","tpl.sk.tdd.prompt":`Implement using TDD (red-green-refactor):
|
|
310
|
+
|
|
311
|
+
1. First write failing tests covering the happy path, edge cases and error branches
|
|
312
|
+
2. Make them pass with the minimal implementation
|
|
313
|
+
3. Refactor while keeping tests green
|
|
314
|
+
|
|
315
|
+
Avoid three test anti-patterns: tests coupled to the implementation, tautological assertions (always true), and horizontal slicing (surface only). Report after each step and run the tests.`,error:"Error",done:"Done",running:"Running…",toolQueued:"Queued",copyArgs:"Copy args",copyMessage:"Copy message",copied:"Copied",errorOutput:"Error output",output:"Output",waitingOutput:"Waiting for output…",toolDoneWaitingModel:"Done · waiting on model",waitingModel:"Waiting for model response…",thinkingNow:"Thinking",thinkingPreview:"Thinking: {preview}",commands:"Commands",newCommand:"New command",newTerminal:"New terminal",name:"Name",command:"Command",cwdHint:"(${pwd} = current working directory)",noCommands:"No commands yet — click + to add one",clickToRun:"Click to run",edit:"Edit",delete:"Delete",confirmQ:"Confirm?",builtinTerminal:"Built-in terminal",termEmptySub:"Click a command on the left to run it, or + on the right for a new terminal",noTerminal:"No terminals",exited:"(exited{code})",exitBanner:"[Process exited with code {code}]",closeTerminal:"Close terminal",renameTerminal:"Rename terminal",rerun:"Reload .pi/commands.json",terminalTitle:"Terminal {n}",aiBashGroup:"Terminal-backed bash",exampleName:"e.g. start dev server",exampleCommand:"e.g. npm run dev",scmTab:"Git",scmTitle:"Source Control",scmRefreshTip:"Re-query git status & diff",scmCurrentBranch:"Current branch",scmUpstreamGone:"Upstream deleted",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"Detached HEAD",scmSelectBranch:"Select branch…",scmRemoteBranches:"Remote branches",scmStageTip:"Stage {path}",scmUnstageTip:"Unstage {path}",scmSwitch:"Switch",scmSwitchBranch:"Switch branch",scmSwitchBranchTip:"Runs git checkout {branch} in the terminal",scmPush:"Push",scmPushTip:"Runs git push in the terminal",scmPull:"Pull",scmPullTip:"Runs git pull in the terminal",scmCommit:"Commit",scmCommitTip:'Runs git commit -m "…" in the terminal (commits staged changes only)',scmCommitAll:"Commit All",scmCommitAllTip:'Runs git add -A && git commit -m "…" in the terminal (stages all changes incl. untracked and commits)',scmCommitPlaceholder:"Type a commit message…",scmChanges:"Changes",scmHistory:"Commit tree",scmCommitDetail:"Commit details",scmSelectCommitHint:"Click a commit on the left to view its details",scmNoHistory:"No commits yet",scmNoChanges:"Working tree clean — no changes",scmNotGitRepo:"Current directory is not a Git repository",scmLoading:"Querying…",scmConnecting:"Waiting for connection…",scmDiff:"Diff",scmSelectFileHint:"Click a file on the left to view its diff",scmNoDiff:"(no diff)",scmStaged:"Staged",scmUnstaged:"Unstaged",scmStagedUnstaged:"Staged + unstaged",scmUntracked:"Untracked",scmUntrackedNote:"Untracked file — stage it with + to include (or use Commit All)",scmQueryFailed:"Git query failed: {error}",scmQueryFailedShort:"Query failed",pluginCommandFallback:"Plugin command",scmTooManyFailures:"Git queries keep failing — click refresh to retry",scmRunsInTerminal:"Commit / branch switch / push / pull run in the terminal",scmViewTerminal:"Open terminal",editProvider:"Edit provider",builtinProviders:"Built-in providers",hintKeyOnly:"Just enter an API key",providerAuthHint:"Choose a supported sign-in method",oauthLogin:"Sign in with {name}",oauthLogout:"Sign out",oauthConnected:"Signed in with {name}",oauthDeviceCode:"Device code",oauthOpenVerification:"Open verification page",oauthContinue:"Continue",configuredBadge:"✓ Configured",keyReady:"Key ready",replaceKey:"Replace key",replaceKeyTitle:"Replace the saved key",clearKey:"Clear",clearKeyTitle:"Remove this provider's key stored in auth.json; it returns to unconfigured (env-var sourced keys can't be cleared here)",clearKeyConfirm:"Clear the stored key for {id}? Its models will leave the list until you configure it again.",cloneProvider:"Add key",cloning:"Adding",cloneProviderTitle:"Add a second API key for this provider (baseUrl and model list are copied automatically)",pasteKey:"Paste API key…",savingKey:"Saving",saveKey:"Save key",addKey:"Add key",addKeyPlaceholder:"Paste the key value…",keyNamePh:"Name (optional, e.g. backup)",providerIdPlaceholder:"Provider ID",baseUrlExamplePh:"baseUrl, e.g. https://api.opencode.ai/zen/v1 or http://127.0.0.1:4096",saveAllBatch:"Save all ({n})",netDisconnected:"Network disconnected — reconnect and retry",advancedEdit:"Advanced edit",batchCreateProviders:"Batch-create providers ({n} APIs)",secondKeyTitle:"Add a second key for {api} · {baseUrl} · {n} models — just name the new provider and enter the key.",noBaseUrlShort:"(no baseUrl)",providerNameLabel:"Provider name",providerNameHint:"(new ID, e.g. opencode-2)",apiKeyLabel:"API key",secondKeyPlaceholder:"sk-… second key",batchDesc:"This provider has multiple APIs ({apis}); it was split into {n} custom providers. Save each so all models (e.g. muse-spark) work. Enter one shared second key to save all at once.",batchKeyLabel:"Shared API key (applies to all {n} providers)",modelsCountShort:"{n} models: ",noKeyYet:"No key yet — add one to use this provider",activateKey:"Set active",removeKey:"Remove",removeKeyConfirm:"Remove this key? It must be re-configured to be used again.",customProviders:"Custom providers",customDesc:"For Ollama / vLLM / OpenAI-compatible proxies, etc. Written to pi's models.json — hot-reloaded immediately.",noCustomProviders:"No custom providers yet",reloadModelsConfig:"Reload config",reloadModelsHint:"Edited models.json by hand or with a script? Hit “Reload config” below to re-read it from disk — no restart needed.",modelsCount:"{n} models",addProvider:"Add provider",providerId:"Provider ID",providerIdHint:"(required, e.g. ollama / my-proxy)",displayName:"Display name",displayNamePh:"My proxy",apiType:"API type",baseUrlHint:"(OpenAI-compatible endpoint)",apiKeyHint:"sk-… (optional — uses the auth.json key)",authHeader:"Auto-add Authorization header",modelsTitle:"Models",modelIdReq:"Model ID (required)",text:"Text",textImage:"Text+image",contextWindow:"Context",maxOutput:"Max output",removeModel:"Remove model",addModel:"Add model",deleteProviderConfirm:"Delete provider {id} and its {n} models?",fetchModels:"Fetch model list",fetchModelsHint:"Pull model IDs from the baseUrl /models endpoint (server-side, no CORS)",fetchingModels:"Fetching…",fetchModelsOk:"Fetched {n} models",fetchModelsEmpty:"The endpoint returned no models",fetchModelsErr:"Fetch failed: {msg}",fetchModelsNeedBaseUrl:"Enter a baseUrl first",goalBarTitle:"Goal",goalBarPlaceholder:"Set a goal; the agent's output is auto-reviewed…",goalBarSet:"Start",goalBarClear:"Cancel",goalBarLocked:"Locked: applies to every later turn",goalBarUnlocked:"This turn only (cleared afterwards)",goalBarReviewModel:"Review model",goalBarUseMainModel:"Use the main model",goalBarMaxRounds:"Max rounds",goalBarMaxRoundsTip:"Max review-revision rounds; 0 or empty = unlimited (keep revising until it passes)",goalBarUnlimitedShort:"Unlimited",goalBarReviewing:"Reviewing…",goalBarRound:"Round {n}",goalBarActive:"Goal active",goalBarPassed:"Passed",goalBarFailed:"Failed",goalBarStatusPending:"Waiting to generate…",goalWizardBtn:"AI Scrape",goalWizardTip:"Let AI refine the requirement into a goal via a Q&A survey",goalWizardRunning:"Scoping the goal",goalWizardAnswer:"Answer",goalWizardCard:"Goal survey",settings:"Settings",settingsTitle:"Settings",settingsDesc:"Changes apply immediately: system prompt, skill and extension toggles rebuild the current session; review instructions and review skills affect later goal reviews (main-session changes are deferred while streaming).",settingsSystemPrompt:"System prompt",settingsPromptHistory:"Input history",settingsPromptHistoryDesc:"Cycle previous prompts with ↑/↓ in the input — global across conversations (localStorage)",promptHistoryMax:"Max entries",promptHistoryMaxHint:"Oldest entries are dropped when exceeded (1–500)",promptHistoryCharLimit:"Limit characters per entry",promptHistoryCharLimitHint:"When enabled, overlong prompts are truncated before saving",promptHistoryCharLimitPlaceholder:"Max chars (100–20000)",promptHistoryClear:"Clear history",promptHistoryClearConfirm:"Confirm clear?",promptHistoryCleared:"Input history cleared",promptHistoryCount:"{n} entries",promptHistoryEmpty:"No history yet — ↑/↓ has nothing to cycle",settingsPromptMode:"Mode",promptModeAppend:"Append",promptModeReplace:"Replace",promptAppendHint:"Append mode: your text is appended to the end of the default system prompt (recommended — keeps the default behavior constraints).",promptReplaceHint:`Replace mode: only the built-in template's persona (soul) paragraph is replaced (e.g. "You are an expert coding assistant…"). The tools list, guidelines, docs pointers, project context and skills are auto-assembled on every run and are never replaced. After switching, the editor shows the built-in soul paragraph; leaving it empty keeps the built-in default.`,promptPlaceholder:"Type a custom system prompt… (applied on blur)",promptComposeHint:"Each {{token}} in the template expands to that source's prompt on every run; non-overridden sources use auto content (tools list / project context / skills are always regenerated from the latest data).",promptComposeDesc:"Compose: reorder / drop / annotate {{token}} blocks freely; empty = the default template. Each source below can be overridden individually (leave empty = auto content) and reset back to default.",promptTemplateLabel:"Compose template",promptSourcesLabel:"Sources (override individually)",promptInsertTokens:"Insert block: ",promptResetAll:"Restore default template and clear all overrides",promptResetSource:"Restore default",promptAutoBadge:"auto",promptOverridePlaceholder:"Override text (leave empty = auto content)…",promptSourceDefaultEmpty:"(no auto content for this source right now)",promptReadonlyBadge:"System-generated (read-only)",promptReadonlyLockedBadge:"Custom override (read-only/locked)",promptReadonlyLockedHint:"This source is system-generated and read-only; the override won't be edited here, but the server still applies it as-is.",promptReadonlyTitle:"System-generated source — read-only display, not editable",promptSourceDefaultEditHint:"This source's current default (auto) content — click to type an override",promptSourceExpand:"Show more",promptSourceCollapse:"Show less",promptSourceRefLabel:"Default (auto) content — for reference / copying",promptSourceSeedButton:"Load default text to tweak",promptSourceSeedTip:"Copies this source's current default text into the override box so you can tweak just a part. Once filled, this source stays fixed and is no longer auto-regenerated each run.",promptTok_soul:"Soul / persona",promptTok_soul_desc:"the agent persona (built-in default unless a SYSTEM.md exists)",promptTok_tools:"Tools list",promptTok_tools_desc:"Available tools with snippets, regenerated each run",promptTok_guidelines:"Guidelines",promptTok_guidelines_desc:"per-tool guidance + generic rules",promptTok_pi_docs:"Pi docs pointer",promptTok_pi_docs_desc:"the block pointing at the pi package docs",promptTok_append:"Append block",promptTok_append_desc:"APPEND_SYSTEM.md content; override = custom appended text",promptTok_persona:"Windows persona",promptTok_persona_desc:"win32-only safety rules (timeout / PTY / GBK)",promptTok_terminal:"Terminal guidance",promptTok_terminal_desc:"persistent-terminal usage guide (injected when terminal tools are on)",promptTok_markers:"Markers guidance",promptTok_markers_desc:"built-in marker tools usage (injected when markers are on)",promptTok_context:"Project context",promptTok_context_desc:"<project_context>: AGENTS.md / CLAUDE.md collection",promptTok_skills:"Skills",promptTok_skills_desc:"<available_skills> list of usable skills",promptTok_cwd:"Working dir line",promptTok_cwd_desc:"the Current working directory line",settingsViewPrompt:"View the current full prompt",settingsViewPromptHint:"The full system prompt actually in effect for this conversation (custom append/replace text, project context, skills and tool guidance). Read-only.",settingsViewPromptEmpty:"Session not ready yet — no system prompt available.",settingsViewToolsSchema:"Tools schema",settingsViewToolsSchemaHint:"The function-calling tool definitions sent to the model (name / description / parameters), combining with the system prompt text to form the full initial context. Read-only.",settingsViewToolsSchemaEmpty:"Session not ready yet — no tools schema available.",settingsSkills:"Skills",settingsReview:"Goal review",settingsReviewDesc:"Configure extra instructions and skills for the isolated goal-review session; the main session is unaffected.",settingsReviewSkills:"Skills available to review",reviewPromptPlaceholder:"Type custom review instructions… (applied on blur)",reviewPromptHint:"These instructions are added to the review task; pass/fail JSON output is still enforced. Skill toggles apply only to review.",goalModeEnabled:"Enable goal mode",goalModeEnabledDesc:"Master switch for the goal bar, the goal wizard and the review loop (on by default). When off, the goal bar is hidden and you cannot set a goal, run the wizard, or trigger reviews.",goalModeOffHint:"Goal mode is off: the goal bar is hidden and existing goals no longer trigger reviews.",settingsVisionBridge:"Vision bridge",settingsVisionBridgeDesc:"When the current model can't see images, send them to a configured vision model and transcribe into text evidence first",visionBridgeEnabled:"Enable vision bridge",visionBridgeModel:"Transcription model",visionBridgeAuto:"Auto (in order)",visionBridgeNoModels:"No configured vision model found: add any image-capable model (e.g. qwen-vl, GLM-4V, Gemini) in Model config to enable automatically",visionBridgeOffHint:"Disabled: images are sent as-is, a text-only model may not see them",visionBridgeCurrent:"Current transcription model: {model}",visionBridgePromptMode:"Transcription prompt",settingsMarkers:"Markers",settingsMarkersDesc:"Let the AI write [[todo:...]] / [[notify:...]] / [[conv:rename:...]] inline markers in replies to update state without a tool round-trip. Global off disables all; per-marker toggles give fine control.",markersEnabled:"Markers enabled (global)",markersEnabledDesc:"Off = no marker guidance injected and no parsing; markers stay as plain text.",markersOffHint:"Globally off: all markers disabled — the AI won't write markers and no side effects fire.",markerGroupTodo:"todo — tasks",markerGroupNotify:"notify — non-blocking hints",markerGroupRename:"conv/rename — rename chat",markerRenameTip:"[[conv:rename:Title]] renames the current conversation (≤80 chars; rename at the end of the first reply)",settingsTerminalTools:"Terminal tools",terminalToolsEnabled:"Enable persistent terminal tools",settingsTerminalToolsDesc:"Let the AI use the built-in terminal for interactive programs (REPLs/vim), long-running servers, continuous output watching, or when you ask it to work in the visible terminal; ordinary commands still go through the one-shot bash tool",terminalToolsOffHint:"Disabled: the AI has no terminal_* tools and receives no usage guidance",settingsEditTools:"Edit tools",editSoftEnabled:"Enable edit_soft tool",editSoftEnabledDesc:"Let the AI use a separate indentation-insensitive edit tool: avoids edit failures when your oldText spacing differs from the file (e.g. JS/JSON). On a match, newText is written verbatim as you provide it (its indentation is final).",editSoftOffHint:"Disabled: the AI has no edit_soft tool and receives no usage guidance",settingsQuestionnaire:"Questionnaire",questionnaireEnabled:"Allow the model to ask me questions",questionnaireEnabledDesc:"On by default: the model may use ask_user_question to pop up an answerable question dialog (options, multi-select, custom input). Off: the model no longer pops up questionnaires; a call also returns disabled immediately.",questionnaireOffHint:"Disabled: the model can no longer pop up question dialogs",browserPageEnabledDesc:"Let the model act on pages you granted in the page-picker extension (browser_page tool: read / click / type / scroll / goto; eval has its own switch). Grant the target page in the extension options first.",browserPageOffHint:"Disabled: the model can no longer click your pages or run scripts in them",browserControl:"Browser control",browserControlTip:"Let the AI act on pages you grant in your browser (read / click / type / scroll). Needs the page-picker extension — granting and the switches live in its options page.",browserControlChecking:"Checking the extension status…",browserControlOffline:"No browser extension yet: install (or enable) page-picker, click its icon on this page once to bind the address, then reload this page.",browserControlInstall:"Install the extension (2 minutes)",browserControlInstallLead:"The extension is not on the Chrome Web Store — no need to search there, follow these four steps:",browserControlInstallDownload:"Download page-picker-extension.zip (always the latest)",browserControlInstallStep1:"Unzip it (you get a folder containing manifest.json).",browserControlInstallStep2:"In Chrome / Edge open chrome://extensions (Edge uses edge://extensions) and switch on “Developer mode” (top right).",browserControlInstallStep3:"Click “Load unpacked” and pick the folder from step 1.",browserControlInstallStep4:"Back on this pi-web-ui page, click the extension icon once and choose “Set as service address” — no typing addresses or ports.",browserControlEmpty:"The extension is ready, but no page is granted yet — open its options page below and grant one.",browserControlDisabled:"The “allow AI to control pages” master switch is off — turn it on in the extension options.",browserControlPages:"Granted pages",browserControlPageOpen:"open",browserControlPageClosed:"not open",browserControlExamples:"You can ask for things like",browserControlExample1:'"Read the orders on that page and sort them by amount"',browserControlExample2:'"Type 张三 in the search box, click search, and tell me the first result"',browserControlOpenOptions:"Open extension options",browserControlRefresh:"Refresh status",browserControlCite:"Mention in chat",browserControlCiteTip:"Add {name} to the input as a page reference (you still write the instruction before sending)",browserControlCiteNote:"“Mention in chat” puts a page reference into the input — the model then knows which page to act on, no typing URLs.",browserControlCited:"Added to the input — write a line and send",browserControlCiteFailed:"The input is not ready yet, try again in a moment",browserControlOpenPanel:"Open panel (status / grants)",browserControlSingleTip:"Click to mention {name} in the chat; the ▾ on the right opens the panel",browserControlDesktop:"Browser control isn't available in the desktop app — nothing you did wrong",browserControlDesktopLead:"The desktop window has no Chrome extension runtime, so the page-picker extension can't be installed there. Open this same address in your system browser with the button below, then follow the four web steps to install the extension.",browserControlOpenInBrowser:"Open this address in the default browser",attachPage:"Page reference: {name} (the AI is granted access to this page)",attachPageShort:"page",settingsTools:"Tools",toolsSectionTerminal:"Persistent terminal",toolsSectionSubagent:"Subagents",toolsSectionOther:"Other tools",toolsSubagentDepHint:"Toggled individually: with subagent_spawn off, the rest (wait/get/steer/stop) have no sessions to manage and only return empty lists or “not found”; delegate_task rides the spawn channel, so it cannot dispatch with spawn off.",delegateTaskEnabledDesc:"Delegate a well-defined task to a specialist subagent template: the six-section brief (TASK/EXPECTED OUTCOME/REQUIRED TOOLS/MUST DO/MUST NOT DO/CONTEXT) is validated server-side; missing or vague sections are rejected. Runs on the subagent spawn channel.",delegateTaskOffHint:"Disabled: the AI cannot delegate via delegate_task (free-form delegation via subagent_spawn still works, without six-section validation)",todoListEnabledDesc:"Read-only query of the current task list (deleted items need an explicit flag); writes never go through tools — use inline markers.",todoListOffHint:"Disabled: the AI can no longer call the query tool (inline-marker writes are unaffected)",toolDescSubagentSpawn:"Spawn an independent background subagent conversation (visible on the left) for a self-contained task; several may run in parallel.",toolDescSubagentGetResult:"Fetch one subagent's result or current progress; unfinished ones return status plus partial output.",toolDescSubagentSteer:"Inject a message into a running subagent to redirect or supplement its work.",toolDescSubagentList:"List all subagents with live status (id/type/state/title).",toolDescSubagentStop:"Stop a running subagent (same as aborting its conversation).",toolDescSubagentWaitAll:"Wait for multiple subagents at once and collect results — no polling.",toolDescSubagentTemplates:"List available subagent templates (disabled ones hidden) for spawn to use.",settingsMessageDisplay:"Conversation",thinkingWrap:"Show full thinking",thinkingWrapDesc:"On: thinking always expands fully and wraps (live reasoning visible while streaming); Off: collapses to a one-line summary with the latest text shown live while streaming",toolsWrap:"Show full tools",toolsWrapDesc:"On: tool calls always expand fully showing arguments and output; Off: collapsed by default, click to expand",devNoCache:"Dev mode: no page cache",devNoCacheDesc:"On: always fetch a fresh page (for source development); Off: allow browser caching (install default)",autoReload:"Auto-reload on new build",autoReloadDesc:"On: page reloads itself after a server rebuild (for source development); Off: reconnect only (install default)",wideChat:"Wide chat column",wideChatDesc:"On: the center column fills the width (useful on ultrawide monitors); Off: keep the 860px cap",projectTitle:"Show project name in title",projectTitleDesc:"On: the browser tab title becomes “<project folder> — pi-web-ui” and updates when you switch projects (handy with several tabs open); Off: always show the app name",terminalBashTakeover:"Terminal-backed bash",terminalBashTakeoverDesc:"This switch decides whether bash is overridden to a terminal version: OFF = native SDK bash (process spawn, no terminal); ON = runs in a visible terminal, where the persist parameter decides (on top of the switch) one-shot (false — process exits when the command finishes, output retained) vs persistent (true — shell state retained across calls, silent commands move to the background and notify the AI)",terminalBashIdleMs:"Silence-to-background threshold (ms)",terminalBashIdleMsDesc:"In persistent-terminal mode, when a command produces no output for this long, stop blocking and let it keep running in the background; the AI is notified when it finishes. 0 = always wait until completion (default 15000)",visionBridgePromptPlaceholder:"Type a custom transcription prompt… (empty = built-in default, applied on blur)",visionBridgePromptAppendHint:"Append mode: custom text is appended after the built-in transcription prompt (recommended — keeps the verbatim-transcription contract).",visionBridgePromptReplaceHint:"Replace mode: custom text replaces the built-in transcription prompt entirely. After switching, the editor shows the built-in default prompt ready to edit; blurring without changes keeps the default.",uninstallExt:"Uninstall",uninstallConfirm:"Confirm?",uninstallConfirmHint:"Click again to confirm — runs pi remove in the terminal",uninstallHint:"Runs pi remove in a visible terminal, then refreshes the list automatically",uninstallTitle:"Uninstall",pluginUpdate:"Update",pluginUpdateHint:"Re-installs from the recorded source (--force, keeps config.json); runs in the background with in-place progress",pluginMarket:"Plugin marketplace",updatesManaged:"Managed instance: updates and plugin installs are handled by whoever deploys it",pluginCatalogAdd:"Add plugin",pluginCatalogAddHint:"Drop a third-party plugin into the installable list (owner/repo or full GitHub URL)",pluginCatalogSource:"Source owner/repo or owner/repo/subdir (required)",pluginCatalogId:"id (optional, defaults to repo/subdir name)",pluginCatalogName:"Name (optional)",pluginCatalogIcon:"Icon emoji (optional)",pluginCatalogDesc:"Description (optional)",pluginCatalogAddSubmit:"Add to list",noPluginCatalog:'List is empty — click "Add plugin" to drop a third-party plugin in',pluginInstalled:"Installed",pluginCatalogCustom:"custom",pluginInstall:"Install",pluginInstallHint:"Installs into UI plugins in the background (settings stay open, progress shown in place)",pluginCatalogRemoveHint:"Remove this custom plugin from the list",pluginUninstallHint:"Uninstalls this plugin in the background (click again to confirm), then refreshes the list",pluginJobRunning:"Running…",pluginJobDone:"Done",pluginJobFailed:"Plugin operation failed",pluginBuildSource:"Build from source",pluginBuildHint:"Build in an isolated directory before install/update (same as CLI --build; source-only plugins without artifacts are built automatically even when unchecked)",pluginCatalogSync:"Sync from catalog",pluginCatalogSyncHint:"Sync the installable list from a catalog document (same channel as plugin reloadCatalog)",pluginCatalogSyncSource:"Catalog URL (http(s)) or absolute local path",pluginCatalogSyncSubmit:"Sync",pluginCatalogSyncInstall:"Install all entries after sync",pluginCatalogSyncReplace:"Replace wholesale (default merges by id)",pluginCatalogSyncRecent:"Recent",pluginCatalogSyncOk:"Catalog synced: {n} entries in the list",pluginCatalogSyncInstalled:"Install results: {ok} succeeded, {fail} failed",uiLayoutTitle:"Interface layout",uiLayoutHint:"Plugins can rearrange these entries (built-in ones included). You can always change them back: uncheck to hide, ↑/↓ to reorder; changed rows offer “Restore”. Hidden entries stay reachable from the top-bar overflow menu.",pluginTopbarMore:"More plugin buttons",uiLayoutTopbar:"Top bar",uiLayoutTopbarOverflow:"Top-bar overflow",uiLayoutBottombar:"Bottom bar",uiLayoutComposer:"Composer actions",uiLayoutMessage:"Message actions",uiLayoutRightPanel:"Right panel",uiLayoutSettingsPages:"Settings pages",uiLayoutRestore:"Restore",uiLayoutRestoreAll:"Restore all",uiLayoutArranged:"Changed by a plugin",uiLayoutEmpty:"(none)",pluginGrantsTitle:"Granted directories",pluginGrantsHint:"Plugins must ask before touching directories outside the workspace. Approved ones are listed here and can be revoked at any time.",pluginGrantsEmpty:"No plugin has been granted a directory outside the workspace yet",pluginGrantsRevoke:"Revoke",pluginGrantRequestTitle:"A plugin wants to access a directory",pluginGrantRequestBody:`{plugin} wants to access this directory:
|
|
316
|
+
|
|
317
|
+
{path}`,pluginGrantAllow:"Allow",pluginGrantDeny:"Deny",pluginUiNoHandler:"The plugin does not handle this action (version mismatch?)",pluginSessionGrantTitle:"A plugin wants to open a project session",pluginSessionGrantBody:`The plugin wants to open a new session in this directory (the workspace will switch):
|
|
318
|
+
|
|
319
|
+
{path}
|
|
320
|
+
|
|
321
|
+
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: ",dshPreset:"Agent preset",dshPresetNewChat:"New chat with this preset",dshPresetLocked:"Locked",dshPresetBlankOnly:"Locked after the first message; blank sessions can switch",dshPresetBroken:" (unavailable)",dshPresetUser:"custom",dshPresetDefaultTag:"default",dshPresetCurrent:"current",dshPresetMinimalNote:"Minimal: persistent shell only; host plugin tools and questionnaire unavailable",dshDefaultPreset:"Default preset",dshDefaultPresetDesc:"Preset for new chats; blank sessions can switch anytime, locked after the first message",dshPresetUserNote:"Custom presets come from the user preset directory (trusted like shell access); compositions using bare package names cannot mount here (known limitation)",dshPerm:"Permissions",dshPermReadOnly:"Read Only",dshPermReadOnlyDesc:"Read files and run read-only commands; writes are always denied, no prompts",dshPermWorkspaceWrite:"Workspace Write",dshPermWorkspaceWriteDesc:"Read/write inside the workspace, no prompts; out-of-scope operations are denied directly",dshPermFullAccess:"Full access",dshPermFullAccessDesc:"Sandbox off, unrestricted machine access; only for tasks you trust",dshPermFullAccessTag:"risky",dshPermCustom:"Custom",dshPermConfirmFull:"Click again to confirm full access",dshPermDefault:"Default permission for new chats",dshPermDefaultDesc:"Initial permission for new chats; the current chat can switch live anytime, no restart",uiPluginNoSource:"Installed manually — no recorded source, online update unavailable",uiPluginPerms:"Permissions",pluginDomNeed:"⚠ Requests full DOM access",pluginDomDesc:"This plugin can freely read and write the page DOM (bypassing UI layout restrictions). Grant only to plugins from sources you trust; once granted its UI code can touch the topbar, composer and any page element.",pluginDomGrant:"Grant DOM access",pluginDomRevoke:"Revoke DOM access",pluginDomGranted:"Full DOM access granted",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"},ap=[{code:"zh",nativeName:"中文"},{code:"en",nativeName:"English"}],pn={};function rp(e){return!e||typeof e.code!="string"||!e.code||e.code==="zh"||e.code==="en"||!e.strings||typeof e.strings!="object"?!1:(pn[e.code]=e,!0)}function ip(e){delete pn[e]}function op(e){return e==="zh"?"中文":e.toUpperCase()}function lp(e){return e==="zh"?"zh-CN":e==="pt"?"pt-BR":e}async function Si(e){const t=await fetch(hs(_t(e)));if(!t.ok)throw new Error(`HTTP ${t.status} for ${e}`);return await t.json()}const jl=o.createContext(null);function Il(){try{return localStorage.getItem(gr)}catch{return null}}function cp(){return fr(Il(),typeof navigator<"u"?navigator.languages:[],null)}function up({children:e}){const[t,n]=o.useState(cp),[r,a]=o.useState(0),c=o.useRef(t);c.current=t;const l=o.useCallback(h=>{n(h);try{localStorage.setItem(gr,h)}catch{}try{window.dispatchEvent(new CustomEvent("pi-web-ui:locale",{detail:h}))}catch{}},[]),u=o.useCallback(async()=>{let h,b=null;try{const E=await Si("/api/locales");h=E.packs??[],b=E.defaultLocale??null}catch{return null}return await Promise.all(h.filter(E=>E.installed).map(async E=>{try{const N=await Si(`/api/locales/${E.code}`);rp({code:N.code||E.code,nativeName:N.nativeName||E.nativeName,strings:N.strings})}catch{}})),a(E=>E+1),b},[]);o.useEffect(()=>{u().then(h=>{if(!Il()?.trim()){const E=fr(null,typeof navigator<"u"?navigator.languages:[],h);E!==c.current&&(c.current=E,n(E))}const b=c.current;if(b!=="zh"&&b!=="en"&&!pn[b]){const E=fr(null,typeof navigator<"u"?navigator.languages:[],h,["zh","en"]);c.current=E,n(E);try{localStorage.setItem(gr,E)}catch{}}})},[u]);const d=o.useMemo(()=>[...ap,...Object.values(pn).map(h=>({code:h.code,nativeName:h.nativeName}))],[r]),m=o.useCallback((h,b)=>{let E=pn[t]?.strings[h]??(t==="zh"?sp[h]:np[h]);if(b)for(const[N,g]of Object.entries(b))E=E.replaceAll(`{${N}}`,String(g));return E},[t,r]);o.useEffect(()=>{document.documentElement.lang=lp(t)},[t]);const f=o.useMemo(()=>({locale:t,setLocale:l,t:m,packs:d,reloadPacks:u}),[t,l,m,d,u]);return s.jsx(jl.Provider,{value:f,children:e})}function Vt(){const e=o.useContext(jl);if(!e)throw new Error("useI18n must be used within LanguageProvider");return e}function He(){return Vt().t}const dp=[{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 _i({settings:e,onChange:t,onPreview:n}){const r=He(),a=c=>t({...e,...c});return s.jsxs("div",{className:"sound-menu",children:[s.jsx("div",{className:"dd-header",children:r("soundHeader")}),s.jsxs("label",{className:"sound-row sound-master",children:[s.jsxs("span",{className:"sound-label",children:[s.jsx(El,{className:"sound-icon"}),s.jsx("span",{children:r("enableSound")})]}),s.jsx("input",{type:"checkbox",checked:e.enabled,onChange:c=>a({enabled:c.target.checked})})]}),dp.map(({kind:c,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:r(l)}),s.jsx("span",{className:"sound-desc",children:r(u)})]}),s.jsxs("span",{className:"sound-right",children:[s.jsx("button",{type:"button",className:"sound-preview",title:r("preview"),disabled:!e.enabled,onClick:d=>{d.preventDefault(),n(c)},children:r("preview")}),s.jsx("input",{type:"checkbox",checked:e[c],disabled:!e.enabled,onChange:d=>a({[c]:d.target.checked})})]})]},c)),s.jsxs("div",{className:`sound-volume ${e.enabled?"":"disabled"}`,children:[s.jsx("span",{className:"sound-name",children:r("volume")}),s.jsx("input",{type:"range",min:0,max:100,step:5,value:e.volume,disabled:!e.enabled,onChange:c=>a({volume:Number(c.target.value)})}),s.jsxs("span",{className:"sound-vol-num",children:[e.volume,"%"]})]})]})}function Rl(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 pp="https://github.com/xing-shuyin/pi-web-ui/releases/latest/download/page-picker-extension.zip",Pl=()=>window.__piWebUiHost?.pageCall?.bind(window.__piWebUiHost);let br=null,Ll=0;function mp(){return br?.available===!0?br.pages??[]:[]}function hp(){Date.now()-Ll<5e3||Dl().catch(()=>{})}async function Dl(){if(Rl())return{available:!1,pages:[],desktop:!0,error:"桌面版不支持浏览器操作:窗口里没有 Chrome 扩展运行时,请改用系统浏览器打开同一个地址(网页版)"};const e=Pl();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??{},r={available:n.installed===!0,aiControl:n.aiControl===!0,allowEval:n.allowEval===!0,pages:Array.isArray(n.pages)?n.pages:[]};return r.available&&(br=r,Ll=Date.now()),r}catch(t){return{available:!1,pages:[],error:t instanceof Error?t.message:String(t)}}}function fp(e){return e.length===1?e[0]:null}function gp(e){return{path:e.origin,name:e.title?.trim()||e.origin,mode:"page",key:`page:${e.origin}`}}async function bp(){const e=Pl();if(!e)return!1;try{return(await e({op:"openOptions",timeoutMs:5e3})).ok===!0}catch{return!1}}function xp(e=45e3){const[t,n]=o.useState(null),r=o.useRef(!0),a=o.useCallback(async c=>{const l=await Dl();r.current&&(n(l),c&&!l.available&&setTimeout(()=>{r.current&&a(!1)},1500))},[]);return o.useEffect(()=>{r.current=!0,a(!0);const c=setInterval(()=>void a(!1),Math.max(5e3,e));return()=>{r.current=!1,clearInterval(c)}},[a,e]),{status:t,refresh:()=>void a(!0)}}let pa=null,ma=null;function Ai(e){pa=e}function ji(e){ma=e}function Ep(){return!!(pa||ma)}function Ol(e){const t=typeof e?.text=="string"?e.text:"",n=Array.isArray(e?.attachments)?e.attachments:[],r=t.trim()!=="",a=n.length>0;return!r&&!a||r&&!pa||a&&!ma?!1:(a&&ma?.(n),r&&pa?.(t),!0)}function yp(){const e=He(),{status:t,refresh:n}=xp(),[r,a]=o.useState(!1),[c,l]=o.useState(null),u=o.useRef(null),d=t?.pages??[],m=t?.available===!0&&(d.length===0||t.aiControl===!1),f=fp(d),h=N=>{l(N),u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>l(null),2600)},b=N=>{const g=Ol({attachments:[gp(N)]});h(e(g?"browserControlCited":"browserControlCiteFailed"))},E=()=>{a(!0),n()};return s.jsxs("span",{className:"bc-anchor",children:[f?s.jsxs("span",{className:"browser-control-split",children:[s.jsxs("button",{type:"button",className:`chip browser-control single${m?" attention":""}`,title:e("browserControlSingleTip",{name:f.title||f.origin}),onClick:()=>b(f),children:[s.jsx(cr,{size:14,"aria-hidden":!0}),s.jsx("span",{className:"bc-chip-label",children:f.title||f.origin})]}),s.jsx("button",{type:"button",className:"chip browser-control caret",title:e("browserControlOpenPanel"),"aria-label":e("browserControlOpenPanel"),onClick:E,children:"▾"})]}):s.jsxs("button",{type:"button",className:`chip browser-control${m?" attention":""}`,title:t?.error??e(m?"browserControlEmpty":"browserControlTip"),onClick:E,children:[s.jsx(cr,{size:14,"aria-hidden":!0}),s.jsxs("span",{children:[e("browserControl"),d.length>0?` · ${d.length}`:""]})]}),c&&s.jsx("span",{className:"bc-flash",children:c}),r&&s.jsx(Tp,{status:t,onRefresh:n,onCite:b,onClose:()=>a(!1)})]})}function Tp({status:e,onRefresh:t,onCite:n,onClose:r}){const a=He(),[c,l]=o.useState(!1),u=e?.pages??[],d=async()=>{l(!0);try{await bp()||t()}finally{l(!1)}};return s.jsx("div",{className:"modal-backdrop",onClick:r,children:s.jsxs("div",{className:"modal browser-control-modal",onClick:m=>m.stopPropagation(),children:[s.jsx("button",{type:"button",className:"modal-close","aria-label":a("close"),onClick:r,children:"✕"}),s.jsxs("div",{className:"modal-head",children:[s.jsx(cr,{size:16,"aria-hidden":!0}),s.jsx("h2",{children:a("browserControl")})]}),s.jsx("div",{className:"modal-desc",children:a("browserControlTip")}),e===null&&s.jsx("div",{className:"bc-note",children:a("browserControlChecking")}),e?.available===!1&&!e.desktop&&s.jsx("div",{className:"bc-note warn",children:a("browserControlOffline")}),e?.desktop===!0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"bc-note warn",children:a("browserControlDesktop")}),s.jsx("div",{className:"bc-note",children:a("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:a("browserControlOpenInBrowser")})})]}),e?.available===!1&&!e.desktop&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"bc-section",children:a("browserControlInstall")}),s.jsx("div",{className:"bc-note",children:a("browserControlInstallLead")}),s.jsx("div",{className:"bc-actions",style:{marginTop:0},children:s.jsx("a",{className:"btn primary",href:pp,target:"_blank",rel:"noreferrer noopener",children:a("browserControlInstallDownload")})}),s.jsxs("ol",{className:"bc-steps",children:[s.jsx("li",{children:a("browserControlInstallStep1")}),s.jsx("li",{children:a("browserControlInstallStep2")}),s.jsx("li",{children:a("browserControlInstallStep3")}),s.jsx("li",{children:a("browserControlInstallStep4")})]})]}),e?.available===!0&&e.aiControl===!1&&s.jsx("div",{className:"bc-note warn",children:a("browserControlDisabled")}),e?.available===!0&&u.length===0&&s.jsx("div",{className:"bc-note warn",children:a("browserControlEmpty")}),u.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"bc-section",children:a("browserControlPages")}),s.jsx("ul",{className:"bc-pages",children:u.map(m=>s.jsxs("li",{children:[s.jsx("span",{className:"bc-title",title:m.title,children:m.title}),s.jsx("span",{className:"bc-origin",title:m.origin,children:m.origin}),s.jsx("span",{className:`bc-open${m.open?" on":""}`,children:m.open?a("browserControlPageOpen"):a("browserControlPageClosed")}),s.jsx("button",{type:"button",className:"bc-cite",title:a("browserControlCiteTip",{name:m.title||m.origin}),onClick:()=>n(m),children:a("browserControlCite")})]},m.origin))}),s.jsx("div",{className:"bc-note",children:a("browserControlCiteNote")})]}),e?.desktop!==!0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"bc-section",children:a("browserControlExamples")}),s.jsxs("ul",{className:"bc-examples",children:[s.jsx("li",{children:a("browserControlExample1")}),s.jsx("li",{children:a("browserControlExample2")})]})]}),s.jsxs("div",{className:"bc-actions",children:[e?.desktop!==!0&&s.jsx("button",{type:"button",className:"primary",disabled:c,onClick:()=>void d(),children:a("browserControlOpenOptions")}),s.jsx("button",{type:"button",onClick:t,children:a("browserControlRefresh")})]})]})})}const Ml=["terminal_create","terminal_list","terminal_close","terminal_input","terminal_key","terminal_read","terminal_wait"],Bl=["subagent_spawn","subagent_get_result","subagent_steer","subagent_list","subagent_stop","subagent_wait_all","subagent_templates"],zn="edit_soft",Vn="delegate_task",Qn="ask_user_question",Xn="todo_list",mn="browser_page",kp=[...Ml.map(e=>({name:e,group:"terminal",defaultOn:!1,dshVisible:!0})),...Bl.map(e=>({name:e,group:"subagent",defaultOn:!0,dshVisible:!1})),{name:zn,group:"other",defaultOn:!1,dshVisible:!1},{name:Vn,group:"other",defaultOn:!0,dshVisible:!1},{name:Qn,group:"other",defaultOn:!0,dshVisible:!0},{name:Xn,group:"other",defaultOn:!0,dshVisible:!0},{name:mn,group:"other",defaultOn:!1,dshVisible:!1}];new Set(kp.map(e=>e.name));const Fl="pi-web-notify",Wa={enabled:!1};function Hl(){try{const e=localStorage.getItem(Fl);if(!e)return{...Wa};const t=JSON.parse(e);return{enabled:typeof t.enabled=="boolean"?t.enabled:Wa.enabled}}catch{return{...Wa}}}function Ii(e){try{localStorage.setItem(Fl,JSON.stringify(e))}catch{}}function Pn(){return typeof window<"u"&&"Notification"in window}function Np(){return Pn()?null:typeof window<"u"&&window.isSecureContext===!1?"insecure":"unsupported"}const vp=12e4;function Cp(e){const{screenX:t,screenY:n,outerWidth:r,outerHeight:a}=e;return Number.isFinite(t)&&Ri(t)||Number.isFinite(n)&&Ri(n)?!0:r>0&&r<=400&&a>0&&a<=40}function Ri(e){return e<=-1e4}function wp(e){return!(e.visibility!=="visible"||e.minimized||!e.hasFocus||e.windows&&e.idleMs>vp)}let Ul=Date.now(),Pi=!1;function Li(){Ul=Date.now()}function Sp(){return Math.max(0,Date.now()-Ul)}function _p(){if(Pi||typeof window>"u")return;Pi=!0;const e={passive:!0,capture:!0};for(const t of["pointerdown","pointermove","keydown","wheel","touchstart","focus","scroll"])window.addEventListener(t,Li,e);typeof document<"u"&&document.addEventListener("visibilitychange",Li,e)}function $l(){return typeof navigator>"u"?!1:/windows/i.test(navigator.userAgent??"")}function Ap(){return _p(),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:Cp({screenX:window.screenX,screenY:window.screenY,outerWidth:window.outerWidth,outerHeight:window.outerHeight}),idleMs:Sp(),windows:$l()}}function Di(){return Pn()?Notification.permission:"denied"}async function jp(){if(!Pn())return"denied";try{return await Notification.requestPermission()}catch{return"denied"}}function Oi(e){return e instanceof Error?`${e.name}: ${e.message}`:String(e)}function Ip(e,t=!1){return{body:e,requireInteraction:t,icon:_t("/icons/icon-192.png"),badge:_t("/icons/icon-192.png"),data:{url:typeof location<"u"?location.href:_t("/")}}}async function Rp(e,t,n=!1){if(!Pn())return{path:"none",error:"unsupported"};if(Notification.permission!=="granted")return{path:"none",error:`permission: ${Notification.permission}`};const r=Ip(t,n);let a;try{const c=await navigator.serviceWorker?.getRegistration();if(c?.active&&typeof c.showNotification=="function")return await c.showNotification(e,r),{path:"sw"};a=c?"service worker not active":"no service worker registration"}catch(c){a=Oi(c)}try{return new Notification(e,r),{path:"page",error:a}}catch(c){return{path:"none",error:`${a}; page: ${Oi(c)}`}}}async function $n(e,t){Pn()&&(wp(Ap())||Hl().enabled&&await Rp(e,t))}const Pp=!1;function Mi(){const e=He(),[t,n]=o.useState(Hl),[r,a]=o.useState(()=>Di()),[c,l]=o.useState(null),u=Np(),d=u!==null,m=$l();o.useEffect(()=>{const h=()=>a(Di());return window.addEventListener("focus",h),document.addEventListener("visibilitychange",h),()=>{window.removeEventListener("focus",h),document.removeEventListener("visibilitychange",h)}},[]);const f=async h=>{const b={...t,enabled:h};if(n(b),Ii(b),h){const E=await jp();if(a(E),E!=="granted"){const N={...b,enabled:!1};n(N),Ii(N)}}};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${d?" disabled":""}`,children:[s.jsxs("span",{className:"sound-label",children:[s.jsx(Yd,{className:"sound-icon"}),s.jsx("span",{children:e("notifyEnable")})]}),s.jsx("input",{type:"checkbox",checked:t.enabled&&!d,disabled:d,onChange:h=>f(h.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")}),!d&&r==="denied"&&s.jsx("div",{className:"sound-hint",children:e("notifyDenied")}),!d&&m&&s.jsx("div",{className:"sound-hint",children:e("notifyWindowsHint")}),Pp]})}let ha=null;const xr=new Set;function ql(){for(const e of xr)e()}function Pa(e){ha={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}:{}},ql()}function vs(){ha!==null&&(ha=null,ql())}function Lp(e){return xr.add(e),()=>{xr.delete(e)}}function Bi(){return ha}function Dp(){return o.useSyncExternalStore(Lp,Bi,Bi)}const ps=8;function Bs(e){return Number.isFinite(e)?e:0}function Op(e,t,n,r,a,c){const l=Math.max(0,Bs(n)),u=Math.max(0,Bs(r)),d=Math.max(ps,Bs(a)-l-ps),m=Math.max(ps,Bs(c)-u-ps);return{x:Math.min(Math.max(ps,Bs(e)),d),y:Math.min(Math.max(ps,Bs(t)),m)}}function Jn(e){return e?(e.when??[]).some(n=>n==="disabled"||typeof n=="string"&&n.startsWith("!")):!0}function fa(e){if(!Array.isArray(e)||e.length===0)return[];const t=e.filter(h=>h&&h.hidden!==!0),n=t.filter(h=>h.kind!=="divider"),r=new Map,a=new Map;n.forEach((h,b)=>{const E=h.group??"";r.has(E)||r.set(E,b);const N=Number.isFinite(h.order)?h.order:100,g=a.get(E);(g===void 0||N<g)&&a.set(E,N)});const c=[...r.keys()].sort((h,b)=>{const E=a.get(h)??100,N=a.get(b)??100;return E!==N?E-N:(r.get(h)??0)-(r.get(b)??0)}),l=new Map(c.map((h,b)=>[h,b])),u=new Map;n.forEach((h,b)=>u.set(h,b));const d=[...n].sort((h,b)=>{const E=l.get(h.group??"")??0,N=l.get(b.group??"")??0;if(E!==N)return E-N;const g=Number.isFinite(h.order)?h.order:100,R=Number.isFinite(b.order)?b.order:100;return g!==R?g-R:(u.get(h)??0)-(u.get(b)??0)}),m=new Map;t.forEach((h,b)=>{if(h.kind!=="divider")return;const E=t.slice(b+1).find(g=>g.kind!=="divider");if(!E)return;const N=m.get(E)??[];N.push(h),m.set(E,N)});const f=[];for(const h of d){for(const b of m.get(h)??[])f.push(b);f.push(h)}return f}function Fi(e){const t=[];let n=null,r=!1;return e.forEach((a,c)=>{if(!a||a.kind==="divider"){r=!0;return}const l=a.group??"";n!==null&&(r||l!==n)&&t.push({kind:"sep",key:`sep:${c}`}),t.push({kind:"item",key:`${a.id}#${c}`,index:c,entry:a}),n=l,r=!1}),t}function Mp(e){return!e||e.kind==="divider"||e.hidden===!0?!1:!Jn(e)}function Hi(e,t,n){const r=Array.isArray(e)?e.length:0;if(r===0)return-1;const a=n>=0?1:-1;let c=Number.isFinite(t)?Math.trunc(t):-1;(c<0||c>=r)&&(c=a>0?-1:r);for(let l=0;l<r;l++)if(c=(c+a+r)%r,Mp(e[c]))return c;return-1}const Bp={menu:"☰",folder:"📁",plus:"+",chat:"💬",terminal:"▙",git:"⎇",search:"🔍",browser:"🌐",layers:"🗂",settings:"⚙",sound:"🔊",globe:"🌍",sun:"☀",download:"⤓",github:"⌗",x:"✕",upload:"⬆",copy:"⧉",cut:"✂",paste:"📋",trash:"🗑",file:"📄",open:"↗",refresh:"⟳",link:"🔗",edit:"✎",dot:"●",cpu:"▣",gauge:"▤",coins:"◉",database:"▥",message:"✉",activity:"〜"};function Fp(e){const t=(e??"").trim();if(!t)return"";const n=Bp[t.toLowerCase()];return n||(/[^\p{L}\p{N}\s]/u.test(t)&&t.length<=4?t:"")}const Hp={engine:"pi",managed:!1,status:"connecting",ready:!1,cwd:"",workspaceRoots:[],homeDir:"",desktopDir:""};let Ws=Hp;const Er=new Set;function Ui(e,t){return e===t?!0:!e||!t||e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Up(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&&Ui(e.workspaceRoots,t.workspaceRoots)&&e.homeDir===t.homeDir&&e.desktopDir===t.desktopDir&&Ui(e.tabs,t.tabs)&&e.service?.name===t.service?.name&&e.service?.supervisor===t.service?.supervisor}function $i(e){const t={...Ws,...e};if(!Up(Ws,t)){Ws=t;for(const n of Er)n()}}function Wl(e){return Er.add(e),()=>{Er.delete(e)}}function qi(){return Ws}function Qr(){return o.useSyncExternalStore(Wl,qi,qi)}function $t(e){return o.useSyncExternalStore(Wl,()=>Ws[e],()=>Ws[e])}function Kl(){return $t("engine")==="dsh"}function Gl(){return $t("managed")}function $p(){return $t("service")}let yr=null;function qp(e){yr=e}const J=e=>yr?yr(e):!1;function Wp({onClose:e}){const t=He(),{locale:n,setLocale:r,reloadPacks:a}=Vt(),[c,l]=o.useState(null),[u,d]=o.useState(""),[m,f]=o.useState("");async function h(){try{const N=await fetch(hs(_t("/api/locales")));if(!N.ok)throw new Error(`HTTP ${N.status}`);const g=await N.json();l(g.packs??[]),d("")}catch(N){d(t("localeListFailed",{error:N instanceof Error?N.message:String(N)}))}}o.useEffect(()=>{h()},[]);async function b(N){f(N),d("");try{const g=await fetch(hs(_t(`/api/locales/${N}/install`)),{method:"POST"});if(!g.ok){let R=`HTTP ${g.status}`;try{R=(await g.json()).error??R}catch{}throw new Error(R)}await a(),await h()}catch(g){d(t("localeInstallFailed",{error:g instanceof Error?g.message:String(g)}))}finally{f("")}}async function E(N){f(N),d("");try{const g=await fetch(hs(_t(`/api/locales/${N}`)),{method:"DELETE"});if(!g.ok)throw new Error(`HTTP ${g.status}`);ip(N),n===N&&r("zh"),await a(),await h()}catch(g){d(t("localeInstallFailed",{error:g instanceof Error?g.message:String(g)}))}finally{f("")}}return s.jsx("div",{className:"modal-backdrop",onClick:e,children:s.jsxs("div",{className:"bg-task-modal",onClick:N=>N.stopPropagation(),children:[s.jsxs("div",{className:"bg-task-head",children:[s.jsxs("span",{className:"bg-task-title",children:[s.jsx(kl,{})," ",t("localePacks")]}),s.jsx("button",{type:"button",className:"btn",title:t("close"),onClick:e,children:s.jsx(bt,{})})]}),u&&s.jsx("div",{className:"bg-task-empty",children:u}),c===null&&!u?s.jsx("div",{className:"bg-task-empty",children:t("loading")}):s.jsx("ul",{className:"bg-task-list",children:(c??[]).map(N=>{const g=m===N.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:N.nativeName}),N.installed&&N.version&&s.jsxs("span",{className:"bg-task-name",children:["v",N.version]})]}),s.jsxs("div",{className:"bg-task-line2",children:[s.jsx("span",{children:N.code}),N.installed?s.jsxs("span",{children:[t("localeInstalled")," · ",t("localeRemoveHint")]}):s.jsx("span",{children:t("localeGetMore")})]})]}),N.installed?s.jsxs("button",{type:"button",className:"btn bg-task-stop",disabled:g,title:t("localeRemove"),onClick:()=>void E(N.code),children:[s.jsx(Rt,{}),s.jsx("span",{children:t(g?"localeRemoving":"localeRemove")})]}):s.jsxs("button",{type:"button",className:"btn",disabled:g,title:t("localeInstall"),onClick:()=>void b(N.code),children:[s.jsx(Rs,{}),s.jsx("span",{children:t(g?"localeDownloading":"localeInstall")})]})]},N.code)})}),s.jsx("div",{className:"bg-task-foot",children:s.jsxs("button",{type:"button",className:"btn",title:t("bgTaskRefresh"),onClick:()=>void h(),children:[s.jsx(Yt,{}),s.jsx("span",{children:t("bgTaskRefresh")})]})})]})})}function Kp({anchorRef:e,open:t,onClose:n,children:r}){const a=o.useRef(null),[c,l]=o.useState(null),u=o.useRef(n);o.useLayoutEffect(()=>{u.current=n});const d=()=>{const m=e.current?.getBoundingClientRect(),f=a.current?.getBoundingClientRect();if(!m||!f)return;const h=8,b=6,E=f.width,N=f.height,g=Math.max(h,Math.min(m.right-E,window.innerWidth-E-h));let R=m.bottom+b;R+N>window.innerHeight-h&&(R=m.top-N-b),R<h&&(R=h),l(M=>M?.x===g&&M?.y===R?M:{x:g,y:R})};return o.useLayoutEffect(()=>{t?d():l(null)},[t,r]),o.useEffect(()=>{if(!t)return;const m=()=>u.current(),f=E=>E instanceof Node&&(a.current&&a.current.contains(E)||e.current&&e.current.contains(E))||!1,h=E=>{f(E.target)||m()},b=E=>{E.key==="Escape"&&m()};return document.addEventListener("mousedown",h,!0),document.addEventListener("keydown",b,!0),window.addEventListener("resize",d,!0),window.addEventListener("scroll",d,!0),()=>{document.removeEventListener("mousedown",h,!0),document.removeEventListener("keydown",b,!0),window.removeEventListener("resize",d,!0),window.removeEventListener("scroll",d,!0)}},[t]),t?In.createPortal(s.jsx("div",{ref:a,className:"plugin-topbar-menu portal",role:"menu",style:{left:c?.x??-9999,top:c?.y??-9999,visibility:c?"visible":"hidden"},children:r}),document.body):null}function Gp({chat:e,terminal:t,view:n,plugins:r,uiPrimary:a,uiOverflow:c,uiContextTopbar:l,onUiAction:u,onViewChange:d,onOpenPanel:m,onOpenSettings:f,onOpenBgTasks:h,onOpenGlobalSearch:b,sound:E,onSoundChange:N,onSoundPreview:g,themes:R,theme:M,onThemeChange:B,reloadThemes:j}){const{locale:Y,setLocale:q,t:C,packs:Te}=Vt(),[xe,G]=o.useState(!1),ee=o.useRef(null),Q=4,O=new Set((a??[]).filter(D=>D.source==="host").map(D=>D.id)),F=(a??[]).filter(D=>D.source!=="host"),w=F.slice(0,Q),se=[...F.slice(Q),...c??[]],z=D=>we(D)&&(a===void 0||O.has(`host:${D}`)),A=D=>{if(D.source!=="host")return!1;switch(D.id){case"host:history":return m("left"),!0;case"host:files":return m("right"),!0;case"host:new-chat":return J({type:"new_chat"}),!0;case"host:search":return b(),!0;case"host:tasks":return h(),!0;case"host:settings":return f(),!0;default:return!1}},ue=(D,$e,it)=>{D.preventDefault(),Pa({x:D.clientX,y:D.clientY,slot:"contextmenu.topbar",target:{id:$e,label:it},entries:l??[]})},{appVersion:P}=Qr(),ie=Gl(),I=$p(),[he,_]=o.useState(!1);o.useEffect(()=>{he&&e.status==="open"&&_(!1)},[he,e.status]);const[re,le]=o.useState(!1),[Ee,Ne]=o.useState(!1),[Ue,ke]=o.useState(!1),[Ke,Ie]=o.useState(!1),[ce,pe]=o.useState(!1),[Fe,Ae]=o.useState(!1),et=e.ready?C("connected"):e.status==="closed"?C("reconnecting"):C("connecting"),dt=e.ready?"ok":"busy",Ve=()=>{if(!e.ready)return;const D=C("updateTabTitle"),$e={name:D,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},it=e.terminals.find(Xe=>Xe.title===D);it?(t.restart(it.id),J({type:"run_command",terminalId:it.id,conversationId:it.conversationId,command:$e,cols:80,rows:24})):t.create({id:qt(),conversationId:e.activeConversationId||e.state?.conversationId||"",title:D,cwd:e.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:$e}),Ie(!1),pe(!1),d("terminal")},X=(D,$e)=>{if(!e.ready||D.length===0)return;const it={name:$e,command:Qd(D),cwd:"${pwd}"},Xe=e.terminals.find(U=>U.title===$e);Xe?(t.restart(Xe.id),J({type:"run_command",terminalId:Xe.id,conversationId:Xe.conversationId,command:it,cols:80,rows:24})):t.create({id:qt(),conversationId:e.activeConversationId||e.state?.conversationId||"",title:$e,cwd:e.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:it}),Ie(!1),pe(!1),d("terminal")},we=D=>!e.tabs||D==="chat"||e.tabs.includes(D),L=e.updatesAll??[],W=L.filter(D=>!D.upToDate&&!D.error).length,oe=L.filter(D=>!D.upToDate&&!D.error&&D.kind!=="webui"),fe=()=>s.jsxs("div",{className:"dd-updates-all",children:[s.jsx("div",{className:"dd-header",children:C("updatesAllTitle")}),e.updatesAll===null?s.jsx("div",{className:"dd-note",children:C("checkingUpdate")}):L.length===0?s.jsx("div",{className:"dd-note",children:C("updatesAllUpToDate")}):s.jsx("ul",{className:"dd-all-list",children:L.map(D=>s.jsxs("li",{className:`dd-all-item${D.error?" err":D.upToDate?"":" warn"}`,children:[s.jsx("span",{className:"dd-all-name",title:D.name,children:D.name}),s.jsx("span",{className:"dd-all-kind",children:D.kind==="webui"?C("kindWebUi"):D.kind==="pi-core"?C("kindPiCore"):C("kindPackage")}),s.jsx("span",{className:"dd-all-vers",children:D.error?C("updateCheckFailed"):D.upToDate?`v${D.current}`:s.jsxs(s.Fragment,{children:["v",D.current," → v",D.latest]})}),D.kind!=="webui"&&!D.upToDate&&!D.error&&s.jsx("button",{type:"button",className:"dd-update-btn",onClick:()=>X([D],C("updatePkgTabTitle",{name:D.name})),children:C("updateBtn")})]},`${D.kind}:${D.name}`))}),s.jsxs("div",{className:"dd-actions",children:[oe.length>0&&s.jsx("button",{type:"button",className:"dd-refresh accent",style:{flex:1},onClick:()=>X(oe,C("updateAllTabTitle")),children:C("updateAllBtn")}),s.jsx("button",{type:"button",className:"dd-refresh",style:oe.length>0?{flex:1}:void 0,onClick:()=>J({type:"check_updates_all",force:!0}),children:C("updatesAllRefresh")})]})]}),de=()=>s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"dd-update",children:[s.jsxs("div",{className:"dd-row",children:[s.jsx("span",{children:C("currentVersion")}),s.jsxs("b",{children:["v",e.update?.current??"…"]})]}),s.jsxs("div",{className:"dd-row",children:[s.jsx("span",{children:C("latestVersion")}),s.jsx("b",{children:e.update===null?C("checkingUpdate"):e.update.error?e.update.error:e.update.latest?`v${e.update.latest}`:C("checkingUpdate")})]}),e.update&&e.update.upToDate&&s.jsx("div",{className:"dd-note ok",children:C("upToDate")}),e.update&&!e.update.upToDate&&e.update.latest&&s.jsx("div",{className:"dd-note warn",children:C("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:C("updateJustPublished",{version:e.update.latest??""})}),e.update&&!e.update.upToDate&&e.update.latest&&s.jsx("div",{className:"dd-note",children:C("updateTerminalHint")})]}),s.jsxs("div",{className:"dd-actions",children:[s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>J({type:"check_update"}),children:e.update===null?C("checkingUpdate"):C("checkUpdate")}),e.update&&!e.update.upToDate&&e.update.latest&&s.jsx("button",{type:"button",className:"dd-refresh accent",onClick:Ve,children:C("updateNow")}),I&&s.jsx("button",{type:"button",className:"dd-refresh accent",disabled:he,title:C("restartServiceTip",{name:I.name}),onClick:()=>{he||(_(!0),J({type:"restart_service"}))},children:C(he?"restartingService":"restartService")})]})]}),ge={"host:search":s.jsxs("button",{type:"button",className:"chip",title:C("searchGlobalTip"),onClick:b,children:[s.jsx(ca,{}),s.jsx("span",{className:"chip-sub",children:C("searchGlobal")})]}),"host:browser":e.settings?.disabledAgentTools?.includes(mn)??!1?null:s.jsx(yp,{}),"host:tasks":s.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":C("bgTasksTip"),onClick:h,children:[s.jsx(ua,{}),s.jsx("span",{className:"chip-sub",children:C("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:C("settingsTitle"),onClick:f,children:[s.jsx(la,{}),s.jsx("span",{className:"chip-sub",children:C("settings")})]}),"host:sound":s.jsxs(zt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(El,{}),s.jsx("span",{className:"chip-sub",children:C("sound")})]}),open:re,onOpenChange:le,children:[s.jsx(_i,{settings:E,onChange:N,onPreview:g}),s.jsx(Mi,{})]}),"host:language":s.jsxs(zt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(kl,{}),s.jsx("span",{className:"chip-sub",children:op(Y)})]}),open:Ee,onOpenChange:Ne,children:[s.jsx("div",{className:"dd-header",children:C("language")}),Te.map(D=>s.jsx(wt,{active:Y===D.code,onClick:()=>{q(D.code),Ne(!1)},children:D.nativeName},D.code)),s.jsxs(wt,{onClick:()=>{Ne(!1),Ae(!0)},children:[s.jsx(Rs,{})," ",C("localeGetMore")]})]}),"host:theme":s.jsxs(zt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(Id,{}),s.jsx("span",{className:"chip-sub",children:C("theme")})]}),open:Ue,onOpenChange:D=>{ke(D),D&&R.length===0&&j()},children:[s.jsx("div",{className:"dd-header",children:C("theme")}),s.jsx(wt,{active:M===null,onClick:()=>{B(null),ke(!1)},children:C("themeDefault")}),R.map(D=>s.jsx(wt,{active:M===D.id,onClick:()=>{B(D.id),ke(!1)},children:Y==="zh"?D.name:D.nameEn??D.name},D.id))]}),"host:update":ie?s.jsxs("span",{className:"chip",title:C("updatesManaged"),children:[s.jsx(Rs,{}),s.jsxs("span",{className:"chip-sub",children:["v",P??e.update?.current??"…"]})]}):s.jsxs(zt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(Rs,{}),s.jsxs("span",{className:"chip-sub",children:["v",e.update?.current??"…"]}),e.update&&!e.update.upToDate&&s.jsx("span",{className:"update-dot",title:C("updateAvailable",{version:e.update.latest??""})}),W>0&&s.jsx("span",{className:"update-badge",children:C("updatesAllBadge",{n:W})})]}),open:Ke,onOpenChange:D=>{Ie(D),D&&(J({type:"check_update"}),J({type:"check_updates_all"}))},fit:!0,children:[s.jsx("div",{className:"dd-header",children:C("update")}),de(),fe()]}),"host:github":s.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:C("githubRepo"),children:s.jsx(Ni,{})})},Qe=["host:search","host:browser","host:tasks","host:settings","host:sound","host:language","host:theme","host:update","host:github"],ye=new Set(["host:search","host:tasks","host:settings"]),Oe=new Set(["host:sound","host:language","host:theme","host:update","host:github","host:browser"]),rt=new Set(Qe),Ge=a===void 0?Qe.filter(D=>we(D.slice(5))):a.filter(D=>D.source==="host"&&rt.has(D.id)).filter(D=>ye.has(D.id)?we(D.id.slice(5)):!0).map(D=>D.id);return s.jsxs("header",{className:"topbar","data-pi-anchor":"topbar",children:[s.jsxs("div",{className:"brand",children:[n==="chat"&&z("history")&&s.jsx("button",{type:"button",className:"panel-toggle",title:C("openHistory"),onClick:()=>m("left"),children:s.jsx(Tl,{})}),s.jsx("span",{className:"brand-logo",children:"π"}),s.jsx("span",{className:"brand-name",children:"pi-web-ui"}),s.jsx("span",{className:`conn-dot ${dt}`,title:et}),s.jsx("span",{className:"conn-label",children:et})]}),s.jsxs("div",{className:"topbar-actions",children:[s.jsxs("div",{className:"view-switch",role:"tablist","aria-label":C("viewSwitch"),children:[s.jsxs("button",{type:"button",role:"tab","aria-selected":n==="chat",className:n==="chat"?"active":"",onClick:()=>d("chat"),children:[s.jsx(Is,{}),s.jsx("span",{children:C("chat")})]}),z("terminal")&&s.jsxs("button",{type:"button",role:"tab","aria-selected":n==="terminal",className:n==="terminal"?"active":"",onClick:()=>d("terminal"),children:[s.jsx(Rn,{}),s.jsx("span",{children:C("terminal")})]}),z("git")&&s.jsxs("button",{type:"button",role:"tab","aria-selected":n==="git",className:n==="git"?"active":"",onClick:()=>d("git"),children:[s.jsx(Yn,{}),s.jsx("span",{children:C("scmTab")})]}),(we("plugins")?r:[]).filter(D=>D.view!==!1).map(D=>{const $e=D.error?`${D.name}: ${D.error}`:D.description?`${D.name} — ${D.description}`:D.name;return s.jsxs("button",{type:"button",role:"tab","aria-selected":n===`plugin:${D.id}`,className:`plugin-tab${n===`plugin:${D.id}`?" active":""}${D.error?" broken":""}`,title:$e,onClick:()=>d(`plugin:${D.id}`),children:[D.icon?s.jsx("span",{"aria-hidden":!0,children:D.icon}):null,s.jsx("span",{children:D.name})]},D.id)}),w.map(D=>s.jsxs("button",{type:"button",className:"plugin-topbar-item",title:D.hint??D.label,onClick:()=>u?.(D),onContextMenu:$e=>ue($e,D.id,D.label),children:[D.icon?s.jsx("span",{"aria-hidden":!0,children:D.icon}):null,s.jsx("span",{children:D.label})]},D.id)),se.length>0&&s.jsxs("div",{className:"plugin-topbar-more",children:[s.jsx("button",{ref:ee,type:"button",className:"plugin-topbar-item","aria-haspopup":"menu","aria-expanded":xe,title:C("pluginTopbarMore"),onClick:()=>G(D=>!D),children:"⋯"}),s.jsx(Kp,{anchorRef:ee,open:xe,onClose:()=>G(!1),children:se.map(D=>{const $e=D.source==="host"&&Oe.has(D.id)?ge[D.id]:void 0;return $e!==void 0?s.jsx(o.Fragment,{children:$e},D.id):s.jsxs("button",{type:"button",role:"menuitem",title:D.hint??D.label,onClick:()=>{G(!1),A(D)||u?.(D)},children:[D.icon&&!/[a-z]/i.test(D.icon)?`${D.icon} `:"",D.label]},D.id)})})]})," "]}),s.jsx("div",{className:"topbar-desktop",children:Ge.map(D=>s.jsx(o.Fragment,{children:ge[D]??null},D))}),z("new-chat")&&s.jsxs("button",{type:"button",className:"chip newchat","data-tip":C("newChatTip"),onClick:()=>J({type:"new_chat"}),children:[s.jsx(Dt,{}),s.jsx("span",{children:C("newChat")})]}),s.jsx("div",{className:"topbar-more",children:s.jsxs(zt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(Dd,{}),s.jsx("span",{className:"chip-sub",children:C("more")}),!ie&&e.update&&!e.update.upToDate&&s.jsx("span",{className:"update-dot"})]}),open:ce,onOpenChange:D=>{pe(D),D&&R.length===0&&j(),D&&!ie&&(J({type:"check_update"}),J({type:"check_updates_all"}))},children:[s.jsx("div",{className:"dd-header",children:C("sound")}),s.jsx("div",{className:"dd-header",children:C("settings")}),s.jsxs(wt,{onClick:()=>{pe(!1),f()},children:[s.jsx(la,{})," ",C("settingsTitle")]}),s.jsxs(wt,{onClick:()=>{pe(!1),b()},children:[s.jsx(ca,{})," ",C("searchGlobal")]}),s.jsxs(wt,{onClick:()=>{pe(!1),h()},children:[s.jsx(ua,{})," ",C("bgTasks"),e.bgServers.length>0&&s.jsx("em",{className:"bg-task-badge",children:e.bgServers.length})]}),s.jsx(_i,{settings:E,onChange:N,onPreview:g}),s.jsx(Mi,{}),s.jsx("div",{className:"dd-header",children:C("language")}),Te.map(D=>s.jsx(wt,{active:Y===D.code,onClick:()=>q(D.code),children:D.nativeName},D.code)),s.jsx("div",{className:"dd-header",children:C("theme")}),s.jsx(wt,{active:M===null,onClick:()=>{B(null),pe(!1)},children:C("themeDefault")}),R.map(D=>s.jsx(wt,{active:M===D.id,onClick:()=>{B(D.id),pe(!1)},children:Y==="zh"?D.name:D.nameEn??D.name},D.id)),s.jsx("div",{className:"dd-header",children:C("update")}),de(),fe(),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(Ni,{})," ",C("githubRepo")]})]})})]}),n==="chat"&&z("files")&&s.jsx("button",{type:"button",className:"panel-toggle",title:C("openFiles"),onClick:()=>m("right"),children:s.jsx(is,{})}),Fe&&s.jsx(Wp,{onClose:()=>Ae(!1)})]})}function Yl(e,t){const n={...t};if(!e)return n;try{const r=JSON.parse(e);if(r&&typeof r=="object"&&!Array.isArray(r))for(const a of Object.keys(t)){const c=r[a];typeof c=="number"&&Number.isFinite(c)&&c>0&&(n[a]=c)}}catch{}return n}function zl(e){const t=e.start.above+e.start.below,n=Math.max(1,e.availablePx),r=e.totalWeight>0?e.totalWeight:1,a=n/r,c=e.minAbovePx/a,l=e.minBelowPx/a;if(c+l>=t){const d=e.minAbovePx+e.minBelowPx||1,m=t*e.minAbovePx/d;return{above:m,below:t-m}}const u=Math.min(t-l,Math.max(c,e.start.above+e.deltaPx/a));return{above:u,below:t-u}}function Yp(e,t,n){const r=new Map(e.map(m=>[m.id,m])),a=m=>m.parentId?r.get(m.parentId)?.cwd??m.cwd:m.cwd,c=e.find(m=>m.id===n),l=c?a(c):t,u=new Map;for(const m of e){const f=a(m),h=u.get(f)??[];h.push(m),u.set(f,h)}const d=[...u.entries()].map(([m,f])=>({cwd:m,isCurrent:m===l,convs:f}));return d.sort((m,f)=>m.isCurrent?-1:f.isCurrent?1:m.cwd<f.cwd?-1:m.cwd>f.cwd?1:0),d}function Wi(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 zp(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 Vp="pi-web-ui:lp-collapse-projects",Qp="pi-web-ui:lp-collapse-convs",Xp="pi-web-ui:lp-collapse-sessions";function Ka(e,t=!1){const[n,r]=o.useState(()=>{try{const c=localStorage.getItem(e);if(c==="1")return!0;if(c==="0")return!1}catch{}return t}),a=o.useCallback(()=>{r(c=>{const l=!c;try{localStorage.setItem(e,l?"1":"0")}catch{}return l})},[e]);return[n,a]}const Vl="pi-web-ui:lp-sizes",ga={projects:1,convs:1,sessions:1},Jp=32,Ki=72;function Zp(){try{return Yl(localStorage.getItem(Vl),ga)}catch{return{...ga}}}const em=o.memo(function({sessionFile:t,conversations:n,elsewhere:r,sessions:a,projects:c,activeConversationId:l,panelSend:u,active:d,collapsible:m,onToggleCollapse:f,uiContextSession:h,uiLeftSessions:b,onUiAction:E,presetNames:N}){const g=He(),R=t,M=$t("ready"),B=$t("status"),j=$t("cwd"),Y=j,[q,C]=o.useState(null),[Te,xe]=o.useState(null),[G,ee]=o.useState(""),[Q,O]=Ka(Vp,!1),[F,w]=Ka(Qp,!1),[se,z]=Ka(Xp,!1),A=o.useCallback((L,W)=>{if(!W)return L.filter(de=>de.isSubagent&&!de.isStreaming&&de.id!==l).length;const oe=new Map(L.map(de=>[de.id,de])),fe=de=>{if(de.id===W)return(oe.get(W)?.isSubagent??!1)&&!de.isStreaming&&de.id!==l;let ge=de;const Qe=new Set;for(;ge?.parentId;){if(ge.parentId===W)return!0;if(Qe.has(ge.parentId)||(Qe.add(ge.parentId),ge=oe.get(ge.parentId),!ge))return!1}return!1};return L.filter(de=>de.isSubagent&&!de.isStreaming&&de.id!==l&&fe(de)).length},[l]),ue=o.useCallback((L,W)=>{if(!W)return L.filter(de=>de.isSubagent).length;const oe=new Map(L.map(de=>[de.id,de])),fe=de=>{if(de.id===W)return oe.get(W)?.isSubagent??!1;let ge=de;const Qe=new Set;for(;ge?.parentId;){if(ge.parentId===W)return!0;if(Qe.has(ge.parentId)||(Qe.add(ge.parentId),ge=oe.get(ge.parentId),!ge))return!1}return!1};return L.filter(de=>de.isSubagent&&fe(de)).length},[]),P=o.useCallback((L,W)=>{if(!W)return 0;const oe=new Map(L.map(de=>[de.id,de])),fe=de=>{let ge=de;const Qe=new Set;for(;ge?.parentId;){if(ge.parentId===W)return!0;if(Qe.has(ge.parentId)||(Qe.add(ge.parentId),ge=oe.get(ge.parentId),!ge))return!1}return!1};return L.filter(de=>de.isSubagent&&de.isStreaming&&fe(de)).length},[]),ie=o.useRef(null),I=o.useRef(null),he=o.useRef(()=>{}),_=fa(h??[]).length>0,re=o.useCallback((L,W,oe)=>{ie.current={x:L,y:W,target:oe};const fe=oe.kind==="running"?oe.id:void 0,de=A(n,fe),ge=de===0?g("noFinishedSubagents"):fe?g("dismissFinishedSubagentsScoped",{n:de}):g("dismissFinishedSubagents",{n:de}),Qe=!!fe&&I.current===fe,ye=(h??[]).map(Oe=>Oe.source!=="host"?Oe:Oe.id==="host:conv-dismiss-subagents"?{...Oe,label:ge,...de===0?{when:[...Oe.when??[],"disabled"]}:{}}:Oe.id==="host:conv-force-dismiss"?fe?{...Oe,...Qe?{label:g("forceDismissConfirm")}:{}}:{...Oe,hidden:!0}:Oe);Pa({x:L,y:W,slot:"contextmenu.session",target:oe,entries:ye,onHostAction:(Oe,rt)=>he.current(Oe,rt)})},[h,n,A,g]),le=o.useCallback((L,W)=>{const oe=W.kind==="running"?W.id:void 0;if(L.id==="host:conv-dismiss-subagents"){u(oe?{type:"dismiss_finished_subagents",parentId:oe}:{type:"dismiss_finished_subagents"});return}if(L.id!=="host:conv-force-dismiss")return;const fe=ie.current;if(!(!oe||!fe)){if(I.current!==oe)return I.current=oe,re(fe.x,fe.y,fe.target),!0;I.current=null,u({type:"dismiss_conversation",id:oe,force:!0})}},[u,re]);he.current=le;const Ee=()=>!b||b.length===0?null:s.jsx("span",{className:"lp-slot-sessions",children:b.map((L,W)=>{const oe=`${L.id}#${W}`,fe=L.label||L.id,de=L.hint||fe;return L.kind==="divider"?s.jsx("span",{className:"lp-slot-divider","aria-hidden":"true"},oe):L.kind==="badge"?s.jsx("span",{className:"lp-slot-badge",title:de,children:L.badge??fe},oe):s.jsx("button",{type:"button",className:"lp-slot-btn",title:de,"aria-label":fe,onClick:ge=>{ge.stopPropagation(),E?.(L)},children:L.icon?s.jsx("span",{"aria-hidden":!0,children:L.icon}):s.jsx("span",{children:fe})},oe)})}),Ne=o.useCallback((L,W)=>{zp(L.target)||_&&(L.preventDefault(),L.stopPropagation(),I.current=null,re(L.clientX,L.clientY,W))},[_,re]),Ue=o.useRef(null),[ke,Ke]=o.useState(()=>Zp());o.useEffect(()=>{try{localStorage.setItem(Vl,JSON.stringify(ke))}catch{}},[ke]);const Ie=[...n,...r.map((L,W)=>({id:`elsewhere:${L.cwd}:${L.title}:${W}`,title:L.title,cwd:L.cwd,messageCount:0,isStreaming:L.isStreaming,isSubagent:!1,elsewhere:!0}))],ce=o.useCallback((L,W)=>oe=>{oe.preventDefault();const fe=oe.currentTarget,de=oe.clientY,ge={...ke},Qe=Ue.current;if(!Qe)return;const ye=[{key:"projects",visible:c.length>0,collapsed:Q},{key:"convs",visible:Ie.length>0,collapsed:F},{key:"sessions",visible:!0,collapsed:se}].filter(Xe=>Xe.visible),Oe=ye.filter(Xe=>Xe.collapsed).length,Ge=ye.filter(Xe=>!Xe.collapsed).map(Xe=>Xe.key).reduce((Xe,U)=>Xe+(ge[U]??1),0)||1,D=Math.max(120,Qe.clientHeight-Oe*Jp);fe.classList.add("dragging"),document.body.classList.add("lp-resizing");const $e=Xe=>{const{above:U,below:Pe}=zl({start:{above:ge[L]??1,below:ge[W]??1},deltaPx:Xe.clientY-de,availablePx:D,totalWeight:Ge,minAbovePx:Ki,minBelowPx:Ki});Ke(Le=>({...Le,[L]:U,[W]:Pe}))},it=()=>{window.removeEventListener("pointermove",$e),window.removeEventListener("pointerup",it),fe.classList.remove("dragging"),document.body.classList.remove("lp-resizing")};window.addEventListener("pointermove",$e),window.addEventListener("pointerup",it)},[ke,c.length,Ie.length,Q,F,se]);o.useEffect(()=>{!d||!M||B!=="open"||j&&(u({type:"list_sessions"}),u({type:"list_projects"}))},[d,M,B,j,u]);const pe=L=>{const W=L.name||L.firstMessage.trim();return W.length>0?W:g("emptyChat")},Fe=L=>L.split(/[\\/]/).pop()||L,Ae=(L,W,oe,fe,de)=>{const ge=q===L;return s.jsx("button",{type:"button",className:`lp-del ${ge?"confirm":""}`,title:ge?oe:W,onClick:Qe=>{Qe.stopPropagation(),ge?(C(null),fe()):C(L)},children:ge?s.jsx(os,{}):de??s.jsx(Rt,{})})},et=(L,W,oe,fe)=>s.jsxs("button",{type:"button",className:"lp-section-title panel-section-title",onClick:oe,title:g(W?"expandSection":"collapseSection"),children:[s.jsxs("span",{className:"lp-section-title-text",children:[L,fe!==void 0?` (${fe})`:""]}),s.jsx("span",{className:"lp-section-chevron",children:W?s.jsx(ks,{}):s.jsx(Ra,{})})]}),Ve=[{key:"projects",visible:c.length>0,collapsed:Q},{key:"convs",visible:Ie.length>0,collapsed:F},{key:"sessions",visible:!0,collapsed:se}].filter(L=>L.visible).filter(L=>!L.collapsed),X=Ve.reduce((L,W)=>L+(ke[W.key]??1),0)||1,we=L=>Ve.length<=1?1:(ke[L]??1)/X*Ve.length;return s.jsxs("aside",{ref:Ue,className:"panel panel-left lp-panel",children:[m&&f&&s.jsx("button",{type:"button",className:"panel-collapse-btn",title:g("collapsePanel"),onClick:f,children:s.jsx(Cl,{})}),c.length>0&&s.jsxs("div",{className:`lp-section panel-projects ${Q?"collapsed":""}`,style:Q?void 0:{flex:`${we("projects")} 1 0px`},children:[et(g("recentProjects"),Q,O,c.length),!Q&&s.jsx("div",{className:"lp-section-body projects-scroll",children:c.map(L=>{const W=Y===L.path;return s.jsxs("div",{className:"lp-row",onMouseLeave:()=>C(oe=>oe===`proj:${L.path}`?null:oe),children:[s.jsxs("button",{type:"button",className:`project-item ${W?"active":""}`,title:L.path,onClick:()=>{W||u({type:"set_cwd",path:L.path})},children:[s.jsx(is,{className:"project-icon"}),s.jsxs("span",{className:"project-info",children:[s.jsx("span",{className:"project-name",children:Fe(L.path)}),s.jsx("span",{className:"project-path",children:L.path})]}),s.jsx("span",{className:"project-time",children:Wi(L.lastUsed)})]}),Ae(`proj:${L.path}`,g("deleteProject"),g("deleteProjectConfirm"),()=>u({type:"remove_project",path:L.path}))]},L.path)})})]}),c.length>0&&!Q&&(Ie.length>0?!F:!se)&&s.jsx("div",{className:"lp-sash",onPointerDown:ce("projects",Ie.length>0?"convs":"sessions"),onDoubleClick:()=>Ke({...ga}),title:g("dragToResize")}),Ie.length>0&&s.jsxs("div",{className:`lp-section lp-section-convs panel-convs ${F?"collapsed":""}`,style:F?void 0:{flex:`${we("convs")} 1 0px`},onContextMenu:L=>Ne(L,{id:"",kind:"section",label:g("runningConversations")}),children:[et(g("runningConversations"),F,w,Ie.length),!F&&s.jsx("div",{className:"lp-section-body convs-scroll",children:Yp(Ie,j,l).map(L=>s.jsxs("div",{className:"panel-conv-group",children:[!L.isCurrent&&s.jsx("div",{className:"panel-conv-group-title",title:L.cwd,children:Fe(L.cwd)}),(()=>{const W=new Map(L.convs.map(ye=>[ye.id,ye])),oe=new Map,fe=[];for(const ye of L.convs)if(ye.parentId&&W.has(ye.parentId)){const Oe=oe.get(ye.parentId)??[];Oe.push(ye),oe.set(ye.parentId,Oe)}else fe.push(ye);const de=[],ge=new Set,Qe=(ye,Oe)=>{if(!ge.has(ye.id)){ge.add(ye.id),de.push({c:ye,depth:Oe});for(const rt of oe.get(ye.id)??[])Qe(rt,Oe+1)}};for(const ye of fe)Qe(ye,0);for(const ye of L.convs)Qe(ye,0);return de.map(({c:ye,depth:Oe})=>{if(ye.elsewhere)return s.jsx("div",{className:"lp-row",children:s.jsxs("div",{className:"session-item elsewhere-item",title:`${g("elsewhereTip")}
|
|
322
|
+
${ye.cwd}`,children:[s.jsx(Is,{className:"session-icon"}),s.jsxs("span",{className:"session-info",children:[s.jsxs("span",{className:"session-title",children:[s.jsx("span",{className:"elsewhere-badge",children:g("elsewhereBadge")}),ye.title]}),s.jsx("span",{className:"session-sub",children:Fe(ye.cwd)})]}),ye.isStreaming&&s.jsx("span",{className:"conv-streaming",title:g("streaming")})]})},ye.id);const rt=l===ye.id;return s.jsxs("div",{className:`lp-row${Oe>0?" lp-sub":""}`,style:Oe>0?{marginLeft:Oe*18}:void 0,onMouseLeave:()=>C(Ge=>Ge===`conv:${ye.id}`?null:Ge),onContextMenu:Ge=>Ne(Ge,{id:ye.id,kind:"running",label:ye.title}),children:[s.jsxs("button",{type:"button",className:`session-item ${rt?"active":""}`,title:`${ye.title}${L.isCurrent?"":` — ${L.cwd}`}`,onClick:()=>{rt||u({type:"switch_conversation",id:ye.id})},children:[s.jsx(Is,{className:"session-icon"}),s.jsxs("span",{className:"session-info",children:[Te===`conv:${ye.id}`?s.jsx("input",{autoFocus:!0,className:"session-rename-input",value:G,placeholder:g("renameSessionPlaceholder"),onClick:Ge=>Ge.stopPropagation(),onChange:Ge=>ee(Ge.target.value),onKeyDown:Ge=>{if(Ge.stopPropagation(),Ge.key==="Enter"&&!Ge.nativeEvent.isComposing){const D=G.trim();D&&u({type:"rename_conversation",id:ye.id,name:D}),xe(null)}else Ge.key==="Escape"&&xe(null)},onBlur:()=>xe(null)}):s.jsxs("span",{className:"session-title",children:[ye.isSubagent&&s.jsx("span",{className:"subagent-badge",children:g("subagentBadge")}),ye.agentPreset&&s.jsx("span",{className:"preset-badge",title:ye.agentPreset,children:N?.[ye.agentPreset]??ye.agentPreset}),ye.title,ye.error&&s.jsx("span",{className:"conv-error-badge",title:g("convErrorBadge",{error:ye.error})})]}),Te===`conv:${ye.id}`?null:s.jsx("span",{className:"session-sub",children:rt?g("current"):g("messageCount",{n:ye.messageCount})})]}),ye.isStreaming&&s.jsx("span",{className:"conv-streaming",title:g("streaming")})]}),s.jsx("button",{type:"button",className:"lp-del lp-rename",title:g("renameSession"),onClick:Ge=>{Ge.stopPropagation(),C(null),ee(ye.title),xe(`conv:${ye.id}`)},children:s.jsx(zs,{})}),(()=>{const Ge=`conv:${ye.id}`,D=q===Ge,$e=A(n,ye.id),it=P(n,ye.id),Xe=ue(n,ye.id);return Xe===0&&!ye.isStreaming?Ae(Ge,g("dismissConversation"),g("dismissConversationConfirm"),()=>u({type:"dismiss_conversation",id:ye.id}),s.jsx(bt,{})):Xe===0?Ae(Ge,g("dismissConversation"),g("dismissStreamingConfirm"),()=>u({type:"dismiss_conversation",id:ye.id,force:!0}),s.jsx(bt,{})):D?s.jsxs("span",{className:"lp-del-group",children:[$e>0&&s.jsx("button",{type:"button",className:"lp-del-opt",title:g("dismissFinishedSubagentsScoped",{n:$e}),onClick:U=>{U.stopPropagation(),C(null),u({type:"dismiss_finished_subagents",parentId:ye.id})},children:g("dismissFinishedOnly",{n:$e})}),s.jsx("button",{type:"button",className:"lp-del-opt danger",title:g("forceDismissTitle",{n:Xe,m:it}),onClick:U=>{U.stopPropagation(),C(null),u({type:"dismiss_conversation",id:ye.id,force:!0})},children:g("dismissForceAll",{n:Xe})})]}):s.jsx("button",{type:"button",className:"lp-del",title:g("dismissConversation"),onClick:U=>{U.stopPropagation(),C(Ge)},children:s.jsx(bt,{})})})(),Ee(),ye.isStreaming&&s.jsx("span",{className:"lp-row-stalled",title:g("streaming"),style:{position:"absolute",right:28,top:"50%",transform:"translateY(-50%)"}})]},ye.id)})})()]},L.cwd))})]}),Ie.length>0&&!F&&!se&&s.jsx("div",{className:"lp-sash",onPointerDown:ce("convs","sessions"),onDoubleClick:()=>Ke({...ga}),title:g("dragToResize")}),s.jsxs("div",{className:`lp-section lp-section-sessions panel-sessions ${se?"collapsed":""}`,style:se?void 0:{flex:`${we("sessions")} 1 0px`},children:[et(g("historySessions"),se,z,a.length),!se&&s.jsxs("div",{className:"lp-section-body sessions-scroll",children:[a.length===0&&s.jsx("div",{className:"panel-empty",children:g("noHistory")}),a.map(L=>{const W=R===L.path;return s.jsxs("div",{className:"lp-row",onMouseLeave:()=>C(oe=>oe===`sess:${L.path}`?null:oe),onContextMenu:oe=>Ne(oe,{id:L.path,kind:"history",label:pe(L)}),children:[s.jsxs("button",{type:"button",className:`session-item ${W?"active":""}`,title:L.path,onClick:()=>{Te||W||u({type:"switch_session",path:L.path})},children:[s.jsx(Is,{className:"session-icon"}),s.jsxs("span",{className:"session-info",children:[Te===L.path?s.jsx("input",{autoFocus:!0,className:"session-rename-input",value:G,placeholder:g("renameSessionPlaceholder"),onClick:oe=>oe.stopPropagation(),onChange:oe=>ee(oe.target.value),onKeyDown:oe=>{if(oe.stopPropagation(),oe.key==="Enter"&&!oe.nativeEvent.isComposing){const fe=G.trim();fe&&u({type:"rename_session",path:L.path,name:fe}),xe(null)}else oe.key==="Escape"&&xe(null)},onBlur:()=>xe(null)}):s.jsx("span",{className:"session-title",children:pe(L)}),Te===L.path?null:s.jsxs("span",{className:"session-sub",children:[W?g("current"):g("messageCount",{n:L.messageCount}),L.source==="tui"&&s.jsx("span",{className:"session-src",title:g("tuiTip"),children:"TUI"})]})]}),s.jsx("span",{className:"session-time",children:Wi(L.modified)})]}),s.jsx("button",{type:"button",className:"lp-del lp-rename",title:g("renameSession"),onClick:oe=>{oe.stopPropagation(),C(null),ee(L.name??""),xe(L.path)},children:s.jsx(zs,{})}),Ae(`sess:${L.path}`,g("deleteSession"),g("deleteSessionConfirm"),()=>u({type:"delete_session",path:L.path})),Ee()]},L.path)})]})]})]})});function tm(e,t){const n=t.assistantMessageEvent,r=e.stats.tokens,a=t.usage!==null?{...r,...t.usage}:r,c=a===r?e.stats:{...e.stats,tokens:a};if(n.type!=="text_delta"&&n.type!=="thinking_delta")return c===e.stats?e:{...e,stats:c};const l=n.delta??"";if(!l)return c===e.stats?e:{...e,stats:c};const u=e.streamingMessage??null,d=u&&u.id===t.messageId?u:{id:t.messageId,content:[]},m=[...d.content],f=n.type==="thinking_delta"?"thinking":"text",h=n.contentIndex??m.length-1;return h>=0&&h<m.length&&m[h].type===f?m[h]=f==="thinking"?{type:"thinking",thinking:(m[h].thinking??"")+l}:{type:"text",text:(m[h].text??"")+l}:m.push(f==="thinking"?{type:"thinking",thinking:l}:{type:"text",text:l}),{...e,stats:c,streamingMessage:{...d,id:t.messageId,content:m}}}function sm(e){const{current:t,source:n,snapshot:r,answered:a}=e;return r&&r.id&&!a.has(r.id)?t?.id===r.id?{changed:!1,question:t,source:n}:{changed:!0,question:r,source:"snapshot"}:!r&&t&&n==="snapshot"?{changed:!0,question:null,source:"live"}:{changed:!1,question:t,source:n}}const Gi="__piWebUiHost",nm=9,Ql=e=>new Promise(t=>setTimeout(t,e));async function am(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 Ql(100)}}function rm(e){const t=Math.max(1,Number(e.pollMs??100)),n=Math.max(t,Number(e.timeoutMs??8e3)),r=async c=>{const l=Date.now()+n;for(;;){if(c())return!0;if(Date.now()>=l)return c();await Ql(t)}},a=async(c,l)=>{const u=String(l.cwd??"").trim();if(u&&e.getCwd()!==u&&(e.send({type:"set_cwd",path:u}),await r(()=>e.getCwd()===u)),l.newChat!==!1){const d=e.getConversationId();e.send({type:"new_chat"}),await r(()=>e.getConversationId()!==d||e.isConversationBlank())}e.send({type:"prompt",text:c})};return{version:nm,setView(c){const l=String(c??"").trim();l&&e.setView(l)},startChat(c){const l=String(c?.prompt??"").trim();return!l||!e.isReady()?!1:(a(l,c??{}).catch(()=>{}),!0)},compose(c){return Ep()?Ol({text:typeof c?.text=="string"?c.text:void 0,attachments:Array.isArray(c?.attachments)?c.attachments:void 0}):!1},async openSession(c){const l=Array.isArray(c?.folders)?c.folders.filter(g=>typeof g=="string"&&g.trim().length>0).map(g=>g.trim()):[],u=Array.isArray(c?.roots)?c.roots.filter(g=>typeof g=="string"&&g.trim().length>0).map(g=>g.trim()):[],d=String(c?.cwd??"").trim(),m=[...new Set([...l,...u])],f=d||m[0]||"";if(!f)return{ok:!1,error:"openSession 需要 cwd / folders / roots(绝对路径)"};if(!e.isReady())return{ok:!1,error:"尚未连接到服务器(还没有快照)"};const h=m.filter(g=>g!==f).slice(0,7),b=new Set([...e.listProjects?.()??[],...e.grantedPaths?.()??[]]);for(const g of[f,...h]){if(b.has(g))continue;if(!(e.confirm?await e.confirm({path:g}).catch(()=>!1):!1))return{ok:!1,error:`用户拒绝了该目录的访问:${g}`};e.grantPath?.(g)}if(e.getCwd()!==f&&(e.send({type:"set_cwd",path:f}),!await r(()=>e.getCwd()===f)))return{ok:!1,error:`切换工作目录失败或超时:${f}`};(h.length>0||e.getWorkspaceRoots().length>0)&&e.send({type:"set_workspace_roots",roots:h});let E=e.getConversationId()??void 0;if(c?.newChat!==!1){const g=E;e.send({type:"new_chat"}),await r(()=>e.getConversationId()!==g||e.isConversationBlank()),E=e.getConversationId()??void 0}const N=String(c?.prompt??"").trim();return N&&e.send({type:"prompt",text:N}),{ok:!0,...E?{sessionId:E}:{}}},sessions:{list:()=>e.listSessions(),async open(c){const l=String(c??"").trim();if(!l)return{ok:!1,error:"sessions.open 需要一个会话 id(先调 list)"};if(!e.isReady())return{ok:!1,error:"尚未连接到服务器(还没有快照)"};const u=e.listSessions().find(f=>f.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 r(()=>e.getCwd()===u.cwd))return{ok:!1,error:`切换工作目录失败或超时:${u.cwd}`}}const d=e.getConversationId();return u.kind==="running"?e.send({type:"switch_conversation",id:u.id}):e.send({type:"switch_session",path:u.id}),await r(()=>e.getConversationId()!==d)?{ok:!0,sessionId:e.getConversationId()??void 0}:{ok:!1,error:`切换会话超时:${u.title}`}}},async reloadCatalog(c,l){const u=String(c??"").trim();if(!u)return{ok:!1,error:"reloadCatalog 需要一个目录来源(http(s) URL 或本地文件路径)"};if(!e.isReady())return{ok:!1,error:"尚未连接到服务器(还没有快照)"};const d=qt();return new Promise(m=>{const f=setTimeout(()=>{xa.delete(d),m({ok:!1,error:"目录同步超时(服务端未在等待窗口内回执)"})},Math.max(1e3,Number(e.catalogTimeoutMs??18e4)));xa.set(d,h=>{clearTimeout(f),m(h)}),e.send({type:"plugin_catalog_sync",requestId:d,source:u,...l?.install?{install:!0}:{},...l?.replace?{replace:!0}:{}})})},onUiAction(c,l){return zi(hn,String(c??"").trim(),l)},onTopbarAction(c,l){return zi(hn,String(c??"").trim(),l)},async pageCall(c){const l=String(c?.op??"").trim();if(!l)return{ok:!1,error:"pageCall 需要一个动作名(op)"};if(Rl())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 am(e.bridgeWaitMs??3e3);if(!u)return{ok:!1,error:"浏览器扩展的页面桥没就绪:确认已安装并启用 page-picker 扩展、本页地址已绑定,然后刷新本页"};try{const d=await u.call({op:l,...c.args===void 0?{}:{args:c.args},...c.target?{to:c.target}:{},...c.timeoutMs?{timeoutMs:c.timeoutMs}:{}});return d===void 0?{ok:!0}:{ok:!0,result:d}}catch(d){return{ok:!1,error:d instanceof Error?d.message:String(d)}}},dom:{anchors(){const c=l=>{try{return document.querySelector(`[data-pi-anchor="${l}"]`)}catch{return null}};return{app:c("app"),topbar:c("topbar"),composer:c("composer")}}},dialogs:{async select(c){try{const l=e.select;if(typeof l!="function")return{ok:!1};const u=Array.isArray(c?.options)?c.options:[],d=await l({title:String(c?.title??""),options:u.filter(f=>typeof f=="object"&&f!==null&&typeof f.label=="string").map(f=>({label:String(f.label),...typeof f.description=="string"?{description:f.description}:{}})),...c?.multi?{multi:!0}:{}});return!d||typeof d!="object"||d.ok!==!0?{ok:!1,...d&&typeof d=="object"&&typeof d.error=="string"?{error:d.error}:{}}:{ok:!0,selected:Array.isArray(d.selected)?d.selected.filter(f=>typeof f=="string"):[]}}catch{return{ok:!1}}},async confirm(c){const l=String(c?.title??""),u=typeof c?.detail=="string"?c.detail:"";try{if(typeof e.dialogConfirm=="function")try{return await e.dialogConfirm({title:l,...u?{detail:u}:{}})===!0}catch{}if(typeof window<"u"&&typeof window.confirm=="function")try{return window.confirm(u?`${l}
|
|
323
|
+
|
|
324
|
+
${u}`:l)}catch{return!1}return!1}catch{return!1}},async input(c){try{const l=e.input;if(typeof l!="function")return{ok:!1};const u=await l({title:String(c?.title??""),...typeof c?.placeholder=="string"?{placeholder:c.placeholder}:{},...typeof c?.initial=="string"?{initial:c.initial}:{}});return!u||typeof u!="object"||u.ok!==!0?{ok:!1}:typeof u.value=="string"?{ok:!0,value:u.value}:{ok:!0}}catch{return{ok:!1}}}},async notifyAction(c){const l=String(c?.text??""),u=(Array.isArray(c?.actions)?c.actions:[]).filter(d=>typeof d=="object"&&d!==null&&typeof d.id=="string"&&typeof d.label=="string");try{if(typeof e.notifyAction=="function"){const d=await e.notifyAction({text:l,actions:u});return typeof d=="string"?d:null}}catch{return null}try{typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent(im,{detail:{text:l}}))}catch{}return null},shortcuts:{register:(c,l)=>dm(String(c??""),l)},searchProviders:{register:c=>pm(c),list:()=>Tr()},composerProviders:{register:c=>mm(c),list:()=>ec()},onTheme:c=>gm(c),onLocale:c=>bm(c),onViewChange:c=>xm(c)}}function Yi(e){try{const t=window;e?t[Gi]=e:delete t[Gi]}catch{}}const Zn=new Map;let hn=null;async function Xl(e,t){const n=hn;hn=e;try{return await t()}finally{hn=n}}function zi(e,t,n){if(!t||typeof n!="function")return()=>{};const r=e?`${e}:${t}`:t;let a=Zn.get(r);a||(a=new Set,Zn.set(r,a));const c=a;return c.add(n),()=>{c.delete(n),c.size===0&&Zn.delete(r)}}async function Jl(e,t,n,r){const a=c=>{const l=Zn.get(c);if(!l||l.size===0)return!1;for(const u of[...l])try{u(n)}catch(d){console.error(`[plugin:${e}] 顶栏动作 ${t} 抛错:`,d)}return!0};if(a(`${e}:${t}`)||a(t))return!0;if(r?.loadBundle&&await r.loadBundle(e).catch(()=>!1)){const l=Date.now()+Math.max(100,Number(r.waitMs??1500));for(;;){if(a(`${e}:${t}`)||a(t))return!0;if(Date.now()>=l)break;await new Promise(u=>setTimeout(u,100))}}return!1}const im="pi-web-ui:toast",fn=new Map;let ba=!1;function om(e){const t=e.split("+").map(d=>d.trim().toLowerCase()).filter(d=>d.length>0);if(t.length===0)return null;let n=!1,r=!1,a=!1,c=!1;for(const d of t.slice(0,-1))if(d==="ctrl"||d==="control")n=!0;else if(d==="shift")r=!0;else if(d==="alt"||d==="option")a=!0;else if(d==="meta"||d==="cmd"||d==="command"||d==="win"||d==="super")c=!0;else return null;const l=t[t.length-1]??"";return!l||["ctrl","control","shift","alt","option","meta","cmd","command","win","super"].includes(l)?null:{combo:`${n?"ctrl+":""}${r?"shift+":""}${a?"alt+":""}${c?"meta+":""}${l}`,key:l,ctrl:n,shift:r,alt:a,meta:c}}function lm(){try{if(typeof document>"u")return!1;const e=document.activeElement;if(!e)return!1;const t=(e.tagName||"").toUpperCase();return!!(t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable)}catch{return!1}}function Zl(e){try{if(lm())return;const t=`${e.ctrlKey?"ctrl+":""}${e.shiftKey?"shift+":""}${e.altKey?"alt+":""}${e.metaKey?"meta+":""}${(e.key??"").toLowerCase()}`,n=fn.get(t);if(!n||n.size===0)return;for(const r of[...n])try{r()}catch(a){console.error("[plugin-host] 快捷键处理器抛错:",a)}}catch{}}function cm(){if(!ba)try{if(typeof window>"u"||typeof window.addEventListener!="function")return;window.addEventListener("keydown",Zl),ba=!0}catch{}}function um(){if(!(fn.size>0||!ba))try{window.removeEventListener("keydown",Zl)}catch{}finally{ba=!1}}function dm(e,t){if(typeof t!="function")return()=>{};const n=om(e);if(!n)return()=>{};let r=fn.get(n.combo);r||(r=new Set,fn.set(n.combo,r));const a=r;return a.add(t),cm(),()=>{a.delete(t),a.size===0&&fn.delete(n.combo),um()}}const gn=new Map;function pm(e){const t=String(e?.id??"").trim();if(!t||typeof e?.search!="function")return()=>{};const n={id:t,label:String(e.label??t),search:e.search};return gn.set(t,n),()=>{gn.get(t)===n&&gn.delete(t)}}function Tr(){return[...gn.values()].map(e=>({id:e.id,label:e.label}))}const bn=new Map;function mm(e){const t=String(e?.id??"").trim();if(!t||typeof e?.search!="function")return()=>{};const n={id:t,label:String(e.label??t),search:e.search};return bn.set(t,n),()=>{bn.get(t)===n&&bn.delete(t)}}function ec(){return[...bn.values()].map(e=>({id:e.id,label:e.label}))}function hm(e){return bn.get(String(e??""))}function fm(e){return gn.get(String(e??""))}const kr=new Set,Nr=new Set,vr=new Set;function gm(e){return typeof e!="function"?()=>{}:(kr.add(e),()=>{kr.delete(e)})}function bm(e){return typeof e!="function"?()=>{}:(Nr.add(e),()=>{Nr.delete(e)})}function xm(e){return typeof e!="function"?()=>{}:(vr.add(e),()=>{vr.delete(e)})}function Vi(e){const t=String(e??"");for(const n of[...kr])try{n(t)}catch(r){console.error("[plugin-host] onTheme 处理器抛错:",r)}}function Qi(e){const t=String(e??"");for(const n of[...Nr])try{n(t)}catch(r){console.error("[plugin-host] onLocale 处理器抛错:",r)}}function Xi(e){const t=String(e??"");for(const n of[...vr])try{n(t)}catch(r){console.error("[plugin-host] onViewChange 处理器抛错:",r)}}const xa=new Map;function Em(e){const t=xa.get(e.requestId);if(t){if(xa.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 Cr="pi-web-ui:plugin-data";function ym(e,t){window.dispatchEvent(new CustomEvent(Cr,{detail:{pluginId:e,payload:t}}))}function Tm(e){const t=n=>{const r=n.detail;e(r.pluginId,r.payload)};return window.addEventListener(Cr,t),()=>window.removeEventListener(Cr,t)}const Ss=new Map,wr=new Set,_s=new Set;let Ji=-1;function tc(){return[...Ss.values()]}function sc(){const e=tc();for(const t of wr)t(e)}function km(e){return wr.add(e),e(tc()),()=>wr.delete(e)}async function nc(e,t){try{const r=(await Xl(e.id,()=>import(_t(`/plugins/${encodeURIComponent(e.id)}/client/entry.mjs?e=${t}`)))).default;return r&&typeof r.mount=="function"?(Ss.set(e.id,{info:e,module:r}),!0):(_s.add(e.id),console.error(`[plugin:${e.id}] entry.mjs 缺少 default.mount`),!1)}catch(n){return _s.add(e.id),console.error(`[plugin:${e.id}] 客户端加载失败:`,n),!1}}async function Sr(e,t){if(Ss.has(e.id))return!0;if(_s.has(e.id)||!e.hasClient)return!1;const n=await nc(e,t);return sc(),n}async function Nm(e,t){t!==Ji&&(Ji=t,Ss.clear(),_s.clear());const n=new Set(e.map(r=>r.id));for(const r of[...Ss.keys()])n.has(r)||Ss.delete(r);for(const r of[..._s])n.has(r)||_s.delete(r);await Promise.all(e.filter(r=>r.hasClient&&r.view!==!1&&!r.error&&!Ss.has(r.id)&&!_s.has(r.id)).map(r=>nc(r,t))),sc()}function ac(e,t){return{pluginId:e,send:n=>t({type:"plugin_message",pluginId:e,payload:n}),onData:n=>Tm((r,a)=>{r===e&&n(a)})}}const vm=17;function Cm(){return{flows:[],results:{}}}function Zi(e,t){const n=e.findIndex(r=>r.flowId===t.flowId);return n<0?[...e,t]:e.map((r,a)=>a===n?t:r)}function wm(e,t){switch(t.type){case"provider_oauth_started":{const n={...e.results};return delete n[t.provider],{flows:[...e.flows.filter(r=>r.provider!==t.provider),{flowId:t.flowId,provider:t.provider}],results:n}}case"provider_oauth_flows":return{...e,flows:t.flows.map(n=>({...n}))};case"provider_oauth_prompt":{const n=e.flows.find(r=>r.flowId===t.flowId);return{...e,flows:Zi(e.flows,{...n,flowId:t.flowId,provider:t.provider,promptId:t.promptId,prompt:t.prompt})}}case"provider_oauth_event":{const n=e.flows.find(r=>r.flowId===t.flowId);return{...e,flows:Zi(e.flows,{...n,flowId:t.flowId,provider:t.provider,event:t.event,promptId:void 0,prompt:void 0})}}case"provider_oauth_result":return{flows:e.flows.filter(n=>n.flowId!==t.flowId),results:{...e.results,[t.provider]:{ok:t.ok,...t.cancelled===void 0?{}:{cancelled:t.cancelled},...t.error===void 0?{}:{error:t.error}}}};case"provider_oauth_logout_result":return{...e,results:{...e.results,[t.provider]:{ok:t.ok,...t.error===void 0?{}:{error:t.error}}}}}}const Sm="pi-web-ui:lang";function eo(){try{return(localStorage.getItem(Sm)??"").trim()}catch{return""}}const to="pi-web-ui:locale",Ga=2e5,_m=2e5,Am="LIVE_OMIT",jm={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 Im(){const e=new Map,t=new Map,n=(r,a)=>`${r}:${a}`;return{write(r,a,c){const l=n(r,a),u=e.get(l);if(u&&u.size>0){for(const f of u)try{f.write(c)}catch{}return}const d=t.get(l)??"",m=d.length+c.length>_m?c:d+c;t.set(l,m)},register(r,a,c){const l=n(r,a);let u=e.get(l);u||(u=new Set,e.set(l,u)),u.add(c);const d=t.get(l);if(d){try{c.write(d)}catch{}t.delete(l)}return()=>{const m=e.get(l);m&&(m.delete(c),m.size===0&&e.delete(l)),t.delete(l)}},clear(){e.clear(),t.clear()}}}function so(e,t){const n=new Set;for(const a of t.messages)a.role==="toolResult"&&a.toolCallId&&n.add(a.toolCallId),a.role==="bashExecution"&&n.add(`bash-${a.id}`);let r=!1;for(const a of e.keys())n.has(a)&&(e.delete(a),r=!0);return r?new Map(e):e}function no(e,t){if(e.size===0)return e;const n=new Set;for(const a of t.messages)a.role==="toolResult"&&a.toolCallId&&n.add(a.toolCallId);let r=!1;for(const a of e.keys())n.has(a)&&(e.delete(a),r=!0);return r?new Map(e):e}function Rm(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!==vm};case"snapshot":return{...e,ready:!0,state:t.state,activeConversationId:t.state.conversationId,liveOutputs:so(e.liveOutputs,t.state),toolStatuses:no(e.toolStatuses,t.state)};case"snapshot_delta":{const n=e.state,r=t.msg;if(!n||n.conversationId!==r.conversationId||n.rev!==r.baseRev)return e;const a={...n,...r.state,messages:r.appended.length>0?[...n.messages,...r.appended]:n.messages};return{...e,ready:!0,state:a,activeConversationId:a.conversationId,liveOutputs:so(e.liveOutputs,a),toolStatuses:no(e.toolStatuses,a)}}case"tool_delta":{const r=(e.liveOutputs.get(t.toolCallId)?.text??"")+t.delta,a=r.length>Ga?`…[${Am}:${r.length-Ga}]…
|
|
325
|
+
`+r.slice(r.length-Ga):r,c=new Map(e.liveOutputs);return c.set(t.toolCallId,{toolName:t.toolName,text:a}),{...e,liveOutputs:c}}case"message_delta":{const n=e.state;return!n||n.conversationId!==t.msg.conversationId?e:{...e,state:tm(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"provider_oauth":{const n=wm({flows:e.providerOAuthFlows,results:e.providerOAuthResults},t.message);return{...e,providerOAuthFlows:n.flows,providerOAuthResults:n.results}}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],r=t.line?[...n?.lines??[],t.line].slice(-40):n?.lines??[],a={...n,...t.job,lines:r,startedAt:n?.startedAt??Date.now()};return{...e,pluginJobs:{...e.pluginJobs,[t.job.jobId]:a}}}case"plugin_catalog_sync_result":return{...e,catalogSync:{...t.result,receivedAt:Date.now()}};case"dsh_patches":return{...e,dshPatches:{patchDir:t.patchDir,files:t.files}};case"dsh_presets":return{...e,dshPresets:{presets:t.presets,defaultPreset:t.defaultPreset}};case"dsh_permission":return{...e,dshPermission:{options:t.options,defaultPreset:t.defaultPreset}};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 ao="pi-web-client-id";let Ya=null;function Ea(){if(Ya)return Ya;let e=null;try{e=sessionStorage.getItem(ao),e||(e=qt(),sessionStorage.setItem(ao,e))}catch{e=e??qt()}return Ya=e,e}const rc="pi-web-last-cwd";function Pm(){try{return localStorage.getItem(rc)}catch{return null}}function Lm(e){try{localStorage.setItem(rc,e)}catch{}}function Dm(){const e=location.protocol==="https:"?"wss:":"ws:";return hs(`${e}//${location.host}${_t("/ws")}`)}function Om(){const[e,t]=o.useReducer(Rm,{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:{},providerOAuthFlows:[],providerOAuthResults:Cm().results,installResult:null,pathCompletions:[],update:null,updatesAll:null,widgets:[],statuses:[],dialog:null,question:null,commands:[],commandsPath:"",slashCommands:[],terminals:[],terminalActiveId:null,goal:jm,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,sessionSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,pluginCatalog:[],pluginCatalogEpoch:0,pluginJobs:{},catalogSync:null,pluginGrants:[],pathRequests:[],dshPatches:null,dshPresets:null,dshPermission:null,protocolMismatch:!1}),n=o.useRef(null),r=o.useRef(Im()),a=o.useRef(0),c=o.useRef(null),l=o.useRef(!0),u=o.useRef(0),d=o.useRef(0),m=o.useRef(new Map),f=o.useRef(null),h=o.useRef(!1),b=o.useRef(null),E=o.useRef(new Set),N=o.useRef("live"),g=()=>{f.current||(f.current=setTimeout(()=>{f.current=null;const O=n.current;O&&O.readyState===WebSocket.OPEN&&O.send(JSON.stringify({type:"get_state"}))},300))},R=(O,F)=>{const w=m.current,se=w.get(O);if(se!==void 0&&F!==se+1){const z=Q.current.chat,A=z.activeConversationId||z.state?.conversationId;O===A&&g()}w.set(O,F)},M=o.useCallback((O,F)=>{const w=++d.current;t({type:"notice",notice:{id:w,level:O,text:F}})},[]),B=o.useCallback(O=>{const F=n.current;if(F&&F.readyState===WebSocket.OPEN){if(O.type==="check_updates_all"&&O.force===!0&&t({type:"updates_check_started"}),F.send(JSON.stringify(O)),O.type==="question_answer"){if(E.current.add(O.id),E.current.size>64){const w=E.current.values().next().value;w!==void 0&&E.current.delete(w)}N.current="live",t({type:"question",question:null})}return!0}return!1},[]),j=o.useCallback(O=>{const F=sm({current:Q.current.chat.question,source:N.current,snapshot:O,answered:E.current});F.changed&&(N.current=F.source,t({type:"question",question:F.question}))},[]);qp(B);const Y=o.useCallback(()=>{if(!l.current)return;t({type:"status",status:"connecting"});const O=new WebSocket(Dm());n.current=O,O.onopen=()=>{n.current===O&&(t({type:"status",status:"open"}),a.current=0,u.current=Date.now(),O.send(JSON.stringify({type:"hello",clientId:Ea(),locale:eo()})))},O.onmessage=F=>{if(n.current!==O)return;u.current=Date.now();let w;try{w=JSON.parse(F.data)}catch{return}switch(w.type){case"ready":{const se="20260916T01100";if((Q.current.chat.settings?.autoReload??!0)&&w.buildId&&se&&w.buildId!==se){const A=`pi-web-ui-reloaded-${w.buildId}`;if(!sessionStorage.getItem(A)){sessionStorage.setItem(A,"1"),location.reload();return}}$i({engine:w.engine??"pi",managed:!!w.managed,tabs:w.tabs,appVersion:w.appVersion,serverVersion:w.serverVersion,service:w.service}),t({type:"ready",serverVersion:w.serverVersion,protocolVersion:w.protocolVersion,engine:w.engine,appVersion:w.appVersion,managed:w.managed,tabs:w.tabs,service:w.service}),O.send(JSON.stringify({type:"get_state"})),O.send(JSON.stringify({type:"list_files"})),O.send(JSON.stringify({type:"list_models"})),O.send(JSON.stringify({type:"list_commands"})),O.send(JSON.stringify({type:"get_commands"})),w.managed||(O.send(JSON.stringify({type:"check_update"})),O.send(JSON.stringify({type:"check_updates_all"})));break}case"snapshot":m.current=new Map,t({type:"snapshot",state:w.state}),j(w.state.pendingQuestion);break;case"snapshot_delta":{const se=Q.current.chat.state;(!se||se.conversationId!==w.conversationId||se.rev!==w.baseRev)&&g(),t({type:"snapshot_delta",msg:w}),j(w.state.pendingQuestion);break}case"tool_delta":R(w.conversationId,w.seq),t({type:"tool_delta",toolCallId:w.toolCallId,toolName:w.toolName,delta:w.delta});break;case"tool_status":t({type:"tool_status",status:w});break;case"message_delta":{R(w.conversationId,w.seq),t({type:"message_delta",msg:w});break}case"notice":{const se=++d.current;t({type:"notice",notice:{id:se,level:w.level,text:w.text,textEn:w.textEn}});break}case"sessions":t({type:"sessions",sessions:w.sessions});break;case"conversations":t({type:"conversations",conversations:w.conversations,activeId:w.activeId,elsewhere:w.elsewhere});break;case"projects":t({type:"projects",projects:w.projects});break;case"files":t({type:"files",files:w});break;case"file_changed":t({type:"file_changed",path:w.path});break;case"file_content":t({type:"file_content",content:w});break;case"models":t({type:"models",models:w.models,loading:!1});break;case"models_config":t({type:"models_config",providers:w.providers});break;case"providers_status":t({type:"providers_status",providers:w.providers});break;case"provider_keys":t({type:"provider_keys",keys:w.keys});break;case"provider_oauth_started":case"provider_oauth_flows":case"provider_oauth_prompt":case"provider_oauth_event":case"provider_oauth_result":case"provider_oauth_logout_result":t({type:"provider_oauth",message:w});break;case"fetch_models_result":t({type:"fetch_models_result",result:{reqId:w.reqId,ok:w.ok,models:w.models,error:w.error}});break;case"refresh_provider_result":t({type:"refresh_provider_result",result:{reqId:w.reqId,ok:w.ok,added:w.added,total:w.total,error:w.error}});break;case"clone_provider_result":t({type:"clone_provider_result",result:{reqId:w.reqId,ok:w.ok,config:w.config,configs:w.configs,error:w.error}});break;case"scm_data":t({type:"scm_data",data:w});break;case"search_files_result":t({type:"file_search_result",result:{reqId:w.reqId,ok:w.ok,results:w.results,truncated:w.truncated}});break;case"session_search_results":t({type:"session_search_result",result:{reqId:w.reqId,ok:w.ok,results:w.results}});break;case"scm_changed":t({type:"scm_changed"});break;case"install_result":t({type:"install_result",result:w});break;case"path_completions":t({type:"path_completions",completions:w.completions});break;case"update_status":t({type:"update_status",status:w});break;case"update_status_all":t({type:"update_status_all",items:w.items});break;case"widgets":t({type:"widgets",widgets:w.widgets});break;case"statuses":t({type:"statuses",statuses:w.statuses});break;case"dialog":t({type:"dialog",dialog:{id:w.id,kind:w.kind,title:w.title,args:w.args}});break;case"dialog_closed":t({type:"dialog",dialog:null});break;case"question_pending":N.current="live",t({type:"question",question:{id:w.id,...w.deadline!==void 0?{deadline:w.deadline}:{},questions:w.questions}});break;case"page_request":{(async()=>{const se=window.__piWebUiHost;let z;if(!se?.pageCall)z={ok:!1,error:"宿主页面桥不可用(页面版本过旧?)—— 刷新本页后再试"};else try{z=await se.pageCall({op:w.op,...w.args===void 0?{}:{args:w.args},...w.target?{target:w.target}:{},timeoutMs:w.timeoutMs})}catch(A){z={ok:!1,error:A instanceof Error?A.message:String(A)}}B({type:"page_response",id:w.id,ok:z.ok===!0,...z.ok===!0?z.result===void 0?{}:{result:z.result}:{error:z.error??"页面操作失败"}})})();break}case"terminal_output":r.current.write(w.conversationId??Q.current.chat.activeConversationId,w.terminalId,w.data);break;case"terminal_exit":t({type:"terminal_exit",conversationId:w.conversationId,terminalId:w.terminalId,exitCode:w.exitCode});break;case"terminal_list":t({type:"terminal_list",conversationId:w.conversationId,terminals:w.terminals});break;case"commands":t({type:"commands",commands:w.commands,path:w.path});break;case"slash_commands":t({type:"slash_commands",commands:w.commands});break;case"goal_status":t({type:"goal_status",status:w.status});break;case"settings_state":t({type:"settings",settings:w.settings});break;case"bg_servers":t({type:"bg_servers",servers:w.servers});break;case"plugins":t({type:"plugins",plugins:w.plugins,epoch:w.epoch});break;case"plugin_catalog":t({type:"plugin_catalog",entries:w.entries,epoch:w.epoch});break;case"plugin_grants":t({type:"plugin_grants",grants:w.grants});break;case"plugin_path_request":t({type:"plugin_path_request",req:{id:w.id,pluginId:w.pluginId,path:w.path,...w.reason?{reason:w.reason}:{}}});break;case"plugin_job":t({type:"plugin_job",job:{jobId:w.jobId,action:w.action,pluginId:w.pluginId,phase:w.phase,...w.ok===void 0?{}:{ok:w.ok},...w.error?{error:w.error}:{},...w.output?{output:w.output}:{}},...w.line?{line:w.line}:{}});break;case"plugin_catalog_sync_result":Em(w),t({type:"plugin_catalog_sync_result",result:{requestId:String(w.requestId??""),ok:w.ok===!0,...w.error?{error:w.error}:{},...w.entries?{entryCount:w.entries.length}:{},...w.installed?{installed:w.installed}:{}}});break;case"dsh_patches":t({type:"dsh_patches",patchDir:w.patchDir,files:w.files});break;case"dsh_presets":t({type:"dsh_presets",presets:w.presets,defaultPreset:w.defaultPreset});break;case"dsh_permission":t({type:"dsh_permission",options:w.options,defaultPreset:w.defaultPreset});break;case"plugin_data":ym(w.pluginId,w.payload);break}},O.onclose=()=>{if(n.current===O&&(n.current=null),r.current.clear(),!l.current||n.current&&n.current!==O)return;t({type:"status",status:"closed"});const F=Math.min(1e3*2**a.current,1e4);a.current+=1,c.current=setTimeout(()=>{c.current=null,Y()},F)},O.onerror=()=>{}},[]);o.useEffect(()=>{const O=F=>{const w=F.detail??eo();w&&B({type:"set_locale",locale:w})};return window.addEventListener(to,O),()=>window.removeEventListener(to,O)},[B]),o.useEffect(()=>{l.current=!0,Y();const O=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(O),c.current&&(clearTimeout(c.current),c.current=null),n.current?.close(),n.current=null}},[Y]),o.useEffect(()=>{const O=e.state?.cwd;if(O){if(!h.current){h.current=!0;const F=Pm();if(F&&F!==O){B({type:"set_cwd",path:F});return}}b.current!==O&&(b.current=O,Lm(O))}},[e.state?.cwd,B]),o.useEffect(()=>{$i({ready:e.ready,status:e.status,cwd:e.state?.cwd??"",workspaceRoots:e.state?.workspaceRoots??[],homeDir:e.state?.homeDir??"",desktopDir:e.state?.desktopDir??""})},[e.ready,e.status,e.state?.cwd,e.state?.workspaceRoots,e.state?.homeDir,e.state?.desktopDir]);const q=o.useCallback(O=>t({type:"dismiss_notice",id:O}),[]),C=o.useCallback(O=>t({type:"terminal_add",meta:O}),[]),Te=o.useCallback(O=>t({type:"terminal_remove",id:O}),[]),xe=o.useCallback(O=>t({type:"terminal_restart",terminalId:O}),[]),G=o.useCallback(O=>t({type:"terminal_active",id:O}),[]),ee=o.useCallback((O,F,w)=>r.current.register(O,F,w),[]),Q=o.useRef({chat:e,send:B,pushNotice:M,dismissNotice:q,terminal:{create:C,close:Te,register:ee,restart:xe,select:G}});return Q.current={chat:e,send:B,pushNotice:M,dismissNotice:q,terminal:{create:C,close:Te,register:ee,restart:xe,select:G}},Q.current}const Mm=200*1024*1024,Bm=/windows/i.test(navigator.userAgent),Fm=/[<>:"/\\|?*\u0000-\u001f]/g,Hm=/[. ]+$/,Um=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function $m(e){const t=e.replace(Fm,"_").replace(Hm,"");return t?Um.test(t)?`_${t}`:t:"_"}function ro(e,t=!0){const n=new URLSearchParams({clientId:Ea(),path:e,...t?{download:"1"}:{}});return hs(_t(`/api/file?${n}`))}const ic="FILE_NOT_FOUND";async function qm(e,t){const n=Bm?$m(t):t;try{const r=await fetch(ro(e));if(!r.ok)return{ok:!1,cancelled:!1,error:await r.text().catch(()=>"")||(r.status===404?ic:`HTTP ${r.status}`)};if(Number(r.headers.get("content-length")??"0")>Mm)return window.location.assign(ro(e)),{ok:!0};const c=await r.blob();return window.showSaveFilePicker&&window.isSecureContext?Wm(c,n):_r(c,n)}catch(r){return{ok:!1,cancelled:!1,error:r instanceof Error?r.message:String(r)}}}async function Wm(e,t){let n;const r=window.showSaveFilePicker;if(!r)return _r(e,t);try{n=await r({suggestedName:t})}catch(a){return a instanceof DOMException&&a.name==="AbortError"?{ok:!1,cancelled:!0}:_r(e,t)}try{const a=await n.createWritable();return await a.write(e),await a.close(),{ok:!0}}catch(a){return{ok:!1,cancelled:!1,error:a instanceof Error?a.message:String(a)}}}function _r(e,t){const n=URL.createObjectURL(e),r=document.createElement("a");return r.href=n,r.download=t,document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4),{ok:!0}}const ss=8;function oc(e,t,n){let r=e.left-ss,a=e.bottom+ss;return r+t.width>n.width-ss&&(r=Math.max(ss,e.right+ss-t.width)),a+t.height>n.height-ss&&(a=Math.max(ss,e.top-ss-t.height)),{left:r,top:a}}function Km(){return typeof window<"u"&&window.matchMedia?.("(hover: hover) and (pointer: fine)")?.matches===!0}function Et({text:e}){const t=o.useRef(null),n=o.useRef(null),[r,a]=o.useState(!1),[c,l]=o.useState({left:0,top:0}),u=()=>{const m=t.current?.getBoundingClientRect();m&&(l({left:Math.max(8,m.left-8),top:m.bottom+8}),a(!0))},d=()=>a(!1);return o.useEffect(()=>{if(!r)return;const m=n.current,f=t.current;if(!m||!f)return;const h=m.getBoundingClientRect(),b=f.getBoundingClientRect(),E=oc(b,h,{width:window.innerWidth,height:window.innerHeight});l(N=>N.left===E.left&&N.top===E.top?N:E)},[r,e]),o.useEffect(()=>{if(!r)return;const m=()=>a(!1);return window.addEventListener("scroll",m,!0),window.addEventListener("resize",m),()=>{window.removeEventListener("scroll",m,!0),window.removeEventListener("resize",m)}},[r]),s.jsxs("span",{ref:t,className:"set-tip",tabIndex:0,"aria-label":e,onMouseEnter:u,onMouseLeave:d,onFocus:u,onBlur:d,onKeyDown:m=>{m.key==="Escape"&&m.target.blur()},children:["?",r&&In.createPortal(s.jsx("span",{ref:n,className:"set-tip-bubble open",role:"tooltip",style:{position:"fixed",left:c.left,top:c.top},children:e}),document.body)]})}function Gm(e){return e instanceof Error?e.message:String(e)}function Ym(e,t,n,r){const a=n==="zh";switch(e.kind){case"no-client":return a?`插件 ${t} 没有客户端脚本(client/entry.mjs),无法显示这一页。`:`Plugin ${t} ships no client bundle (client/entry.mjs), so this page cannot be shown.`;case"load":return a?`插件 ${t} 的页面脚本加载失败:${e.detail}`:`Failed to load plugin ${t}'s page bundle: ${e.detail}`;case"mount":return`${r("pluginMountFailed",{name:t})}:${e.detail}`}}function lc({plugin:e,epoch:t,send:n,className:r}){const a=o.useRef(null),{locale:c}=Vt(),l=He(),[u,d]=o.useState(null),m=o.useRef(n);o.useEffect(()=>{m.current=n},[n]),o.useEffect(()=>{const h=a.current;if(!h)return;let b=!1,E,N=!1;if(d(null),!e.hasClient){d({kind:"no-client"});return}return(async()=>{try{if(await Sr(e,t),b)return;const g=await Xl(e.id,()=>import(_t(`/plugins/${encodeURIComponent(e.id)}/client/entry.mjs?e=${t}`)));if(b)return;const R=g.default;if(!R||typeof R.mount!="function")throw new Error("client/entry.mjs 没有导出 default.mount()");N=!0,E=R.mount(h,ac(e.id,M=>m.current(M)))}catch(g){if(b)return;console.error(`[plugin:${e.id}] 页面${N?"挂载":"加载"}失败:`,g),d({kind:N?"mount":"load",detail:Gm(g)})}})(),()=>{if(b=!0,typeof E=="function")try{E()}catch(g){console.error(`[plugin:${e.id}] cleanup 失败:`,g)}h.textContent=""}},[e.id,e.hasClient,t]);const f=r?`plugin-page ${r}`:"plugin-page";return s.jsxs("div",{className:f,children:[s.jsx("div",{className:"plugin-page-host",ref:a}),u&&s.jsx("div",{className:"plugin-page-error",role:"alert",children:Ym(u,e.name,c,l)})]})}function cc(e){return`pi-web-ui:${e}:tab`}function zm(e,t){try{const n=localStorage.getItem(cc(e));return n&&t.some(r=>r.id===n)?n:null}catch{return null}}function io(e,t){try{localStorage.setItem(cc(e),t)}catch{}}function Vm(e){return e.length>0&&!/[a-z]/i.test(e)}function oo(e){if(e.label)return e.label;const t=e.pluginPage;return t?.entry.label||t?.plugin.name||e.id}function Qm({storageKey:e,tabs:t,epoch:n,send:r,extra:a,className:c}){const l=o.useId(),[u,d]=o.useState(()=>zm(e,t)??t[0]?.id??""),m=o.useRef([]),f=o.useRef(""),h=t.findIndex(B=>B.id===u),b=h>=0?t[h]:t[0],E=b?t.indexOf(b):-1;o.useEffect(()=>{if(!b)return;u!==b.id&&d(b.id);const B=`${e}:${b.id}`;f.current!==B&&(f.current=B,io(e,b.id))},[b,u,e]);const N=B=>{d(B.id),f.current=`${e}:${B.id}`,io(e,B.id)},g=(B,j)=>{const Y=t.length;let q=-1;if(B.key==="ArrowRight")q=(j+1)%Y;else if(B.key==="ArrowLeft")q=(j-1+Y)%Y;else if(B.key==="Home")q=0;else if(B.key==="End")q=Y-1;else return;const C=t[q];C&&(B.preventDefault(),N(C),m.current[q]?.focus())};if(!b)return null;const R=`${l}-panel-${E}`,M=c?`slot-tabs ${c}`:"slot-tabs";return s.jsxs("div",{className:M,children:[s.jsxs("div",{className:"slot-tabs-bar",role:"tablist",children:[t.map((B,j)=>{const Y=j===E;return s.jsxs("button",{type:"button",role:"tab",id:`${l}-tab-${j}`,className:Y?"slot-tab active":"slot-tab",title:B.hint??oo(B),"aria-selected":Y,"aria-controls":`${l}-panel-${j}`,tabIndex:Y?0:-1,ref:q=>{m.current[j]=q},onClick:()=>N(B),onKeyDown:q=>g(q,j),children:[B.icon&&Vm(B.icon)?s.jsx("span",{className:"slot-tab-icon",children:B.icon}):null,s.jsx("span",{className:"slot-tab-label",children:oo(B)})]},B.id)}),a?s.jsx("div",{className:"slot-tabs-extra",children:a}):null]}),s.jsx("div",{className:"slot-tabs-body",id:R,role:"tabpanel","aria-labelledby":`${l}-tab-${E}`,children:b.pluginPage?s.jsx(lc,{plugin:b.pluginPage.plugin,epoch:n,send:r}):b.element??null})]})}const bs="@root",lo="pi-web-ui:rp-sizes",za={files:4,widgets:1},co=120,uo=56;function Xm(e,t){return t?Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top):32}const Jm="files",Zm=[],eh=()=>{};function th(e){const t=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e,n=t.lastIndexOf("/");return n<0?"":n===0?"/":t.slice(0,n)}function sn(e){return e===bs||e==="/"||/^[A-Za-z]:$/.test(e)}function sh(e){return e.startsWith("/")||/^[A-Za-z]:([/]|$)/.test(e)}const nh=o.memo(function({files:t,fileChanged:n,widgets:r,panelSend:a,onAttach:c,onPreview:l,onNotice:u,collapsible:d,onToggleCollapse:m,uiRightPanelTabs:f,uiContextFile:h,plugins:b,pluginsEpoch:E,send:N}){const g=He(),R=b??Zm,M=$t("cwd"),B=$t("workspaceRoots"),j=$t("homeDir"),Y=$t("desktopDir"),[q,C]=o.useState(""),[Te,xe]=o.useState(null),[G,ee]=o.useState(!1),Q=o.useRef(null),O=o.useRef(null),[F,w]=o.useState(()=>{try{return Yl(localStorage.getItem(lo),za)}catch{return{...za}}});o.useEffect(()=>{try{localStorage.setItem(lo,JSON.stringify(F))}catch{}},[F]);const se=r.some(v=>v.lines.length>0),z=o.useCallback(v=>{v.preventDefault();const te=Q.current;if(!te)return;const Be=v.currentTarget,ht=v.clientY,nt={above:F.files,below:F.widgets},yt=Math.max(120,te.clientHeight-Xm(te,O.current));Be.classList.add("dragging"),document.body.classList.add("rp-resizing");const Xt=ae=>{const{above:Se,below:Me}=zl({start:nt,deltaPx:ae.clientY-ht,availablePx:yt,totalWeight:nt.above+nt.below,minAbovePx:co,minBelowPx:uo});w({files:Se,widgets:Me})},k=()=>{window.removeEventListener("pointermove",Xt),window.removeEventListener("pointerup",k),Be.classList.remove("dragging"),document.body.classList.remove("rp-resizing")};window.addEventListener("pointermove",Xt),window.addEventListener("pointerup",k)},[F.files,F.widgets]),A=o.useRef(null),ue=o.useRef(0),P=o.useCallback(v=>{A.current=v,v&&(v.scrollTop=ue.current)},[]),[ie,I]=o.useState(null),he=o.useRef(null);o.useEffect(()=>()=>{he.current&&clearTimeout(he.current)},[]);const _=o.useCallback(v=>{I(v),he.current&&clearTimeout(he.current),he.current=setTimeout(()=>I(null),1200)},[]),re=v=>{try{const te=document.createElement("textarea");te.value=v,te.style.position="fixed",te.style.opacity="0",document.body.appendChild(te),te.select();const Be=document.execCommand("copy");return document.body.removeChild(te),Be}catch{return!1}},le=o.useCallback((v,te)=>{if(!v)return;const Be=()=>_(te),ht=()=>u("error",g("slashCopyFailed")),nt=navigator;nt.clipboard?.writeText?nt.clipboard.writeText(v).then(Be,()=>{re(v)?Be():ht()}):re(v)?Be():ht()},[_,u,g]),Ee=o.useCallback(v=>{if(!v)return M;if(/^[A-Za-z]:$/.test(v))return`${v}/`;if(v.startsWith("/")||/^[A-Za-z]:([/]|$)/.test(v))return v;const te=M.replace(/\\/g,"/").replace(/\/+$/,"");return te?`${te}/${v}`:v},[M]),Ne=o.useCallback(v=>!v||v===bs?null:v.startsWith("/")||/^[A-Za-z]:([/]|$)/.test(v)?v:`${M.replace(/\\/g,"/").replace(/\/+$/,"")}/${v}`,[M]),Ue=o.useCallback((v,te)=>{for(const Be of te){const ht=new FileReader;ht.onload=()=>{const nt=ht.result,yt=nt.slice(nt.indexOf(",")+1);yt&&a({type:"upload_file",dirPath:v,name:Be.name,data:yt})},ht.readAsDataURL(Be)}},[a]),ke=o.useRef(null),Ke=o.useRef(null),Ie=o.useCallback(()=>{const v=ke.current?.project;v&&a({type:"set_cwd",path:v.path})},[a]),ce=o.useCallback(()=>{Ke.current&&(Ke.current.value=""),Ke.current?.click()},[]),[pe,Fe]=o.useState(null),[Ae,et]=o.useState(null),[dt,Ve]=o.useState(""),[X,we]=o.useState(null),[L,W]=o.useState(""),oe=o.useCallback((v,te)=>{qm(v,te).then(Be=>{Be.ok||Be.cancelled||u("error",g("downloadFailed",{error:Be.error===ic?g("fileNotFoundShort"):Be.error}))})},[u,g]),fe=o.useCallback(()=>{const v=ke.current?.target;!v||v.kind==="list"||sn(v.id)||(we(null),Ve(v.label),et(v.id))},[]),de=o.useCallback(()=>{if(!Ae)return;const v=dt.trim();et(null),v&&a({type:"file_rename",path:Ae,newName:v})},[Ae,dt,a]),ge=o.useCallback(v=>{const te=ke.current?.dir??q;et(null),W(""),we({dir:te,kind:v})},[q]),Qe=o.useCallback(()=>{if(!X)return;const v=L.trim();we(null),v&&a({type:"file_create",dir:X.dir,name:v,kind:X.kind})},[X,L,a]),ye=(v,te,Be,ht)=>s.jsx("input",{autoFocus:!0,className:"session-rename-input",value:v,placeholder:g("fileNamePlaceholder"),onClick:nt=>nt.stopPropagation(),onChange:nt=>te(nt.target.value),onKeyDown:nt=>{nt.stopPropagation(),nt.key==="Enter"&&!nt.nativeEvent.isComposing?Be():nt.key==="Escape"&&ht()},onBlur:ht}),Oe=o.useCallback(()=>{const v=ke.current?.target;!v||v.kind==="list"||sn(v.id)||window.confirm(g("fileDeleteConfirm",{name:v.label}))&&(pe?.src===v.id&&Fe(null),Ae===v.id&&et(null),a({type:"file_delete",path:v.id}))},[a,g,pe,Ae]),rt=o.useCallback(()=>{const v=ke.current?.target;!v||v.kind==="list"||sn(v.id)||a({type:"file_copy",src:v.id,destDir:th(v.id)})},[a]),Ge=o.useCallback(v=>{const te=ke.current?.target;!te||te.kind==="list"||sn(te.id)||Fe({src:te.id,cut:v})},[]),D=o.useCallback(()=>{if(!pe)return;const v=ke.current?.dir??q;pe.cut?(a({type:"file_copy",src:pe.src,destDir:v,move:!0}),Fe(null)):a({type:"file_copy",src:pe.src,destDir:v})},[pe,a,q]),$e=o.useCallback(()=>{a({type:"list_files",path:q===""?void 0:q})},[a,q]),[it,Xe]=o.useState(!1);o.useEffect(()=>{if(!it)return;const v=Be=>{Be.target?.closest(".root-picker")||Xe(!1)},te=Be=>{Be.key==="Escape"&&Xe(!1)};return window.addEventListener("mousedown",v,!0),window.addEventListener("keydown",te),()=>{window.removeEventListener("mousedown",v,!0),window.removeEventListener("keydown",te)}},[it]);const U=o.useCallback(v=>{a({type:"set_workspace_roots",roots:v})},[a]),Pe=o.useCallback(()=>{const v=ke.current?.target;if(!v||v.kind!=="dir")return;const te=Ne(v.id);!te||B.includes(te)||U([...B,te])},[B,Ne,U]),Le=o.useCallback(v=>{Ue(ke.current?.dir??q,Array.from(v.target.files??[]))},[Ue,q]),ot=o.useCallback(v=>{const te=ke.current?.target;switch(v.id){case"host:file-open-project":Ie();break;case"host:file-upload":ce();break;case"host:file-add-root":Pe();break;case"host:file-open":te?.kind==="file"&&l(te.id,te.label);break;case"host:file-enter":te?.kind==="dir"&&Lt(te.id);break;case"host:file-download":te?.kind==="file"&&oe(te.id,te.label);break;case"host:file-attach-inline":te?.kind==="file"&&c(te.id,te.label,"inline");break;case"host:file-attach-ref":te?.kind==="file"&&c(te.id,te.label,"reference");break;case"host:file-attach-folder":te?.kind==="dir"&&c(te.id,te.label,"reference",!0);break;case"host:file-new-file":ge("file");break;case"host:file-new-dir":ge("dir");break;case"host:file-paste":D();break;case"host:file-rename":fe();break;case"host:file-duplicate":rt();break;case"host:file-cut":Ge(!0);break;case"host:file-copy":Ge(!1);break;case"host:file-copy-name":te&&te.kind!=="list"&&le(te.label,`name:${te.id}`);break;case"host:file-copy-path":te&&te.kind!=="list"&&le(Ee(te.id),`path:${te.id}`);break;case"host:file-copy-rel":te&&te.kind!=="list"&&le(te.id,`rel:${te.id}`);break;case"host:file-refresh":$e();break;case"host:file-delete":Oe();break}},[Ie,ce,Pe,l,c,le,Ee,oe,ge,D,fe,rt,Ge,$e,Oe]),Ye=o.useCallback((v,te)=>{const Be=te.kind==="dir"?Ne(te.id):null,ht={target:te,dir:te.kind==="dir"?te.id:q,project:Be?{path:Be,name:te.label}:null},nt=te.kind,yt=nt==="file",Xt=nt==="dir",k=nt==="list",ae=!k&&sn(te.id),Se=!k&&sh(te.id),Me=q===bs,We=(h??[]).map(De=>{if(De.source!=="host")return De;switch(De.id){case"host:file-upload":return yt||Me?{...De,hidden:!0}:{...De,label:ht.dir===q?g("uploadToCurrentDir"):g("uploadToFolder")};case"host:file-open-project":return Be?De:{...De,hidden:!0};case"host:file-add-root":return!!Be&&Be!==M&&!B.includes(Be)?De:{...De,hidden:!0};case"host:file-open":case"host:file-download":case"host:file-attach-inline":case"host:file-attach-ref":return yt?De:{...De,hidden:!0};case"host:file-enter":case"host:file-attach-folder":return Xt?De:{...De,hidden:!0};case"host:file-new-file":case"host:file-new-dir":return!yt&&!Me?De:{...De,hidden:!0};case"host:file-paste":return!yt&&!Me&&pe?De:{...De,hidden:!0};case"host:file-rename":case"host:file-duplicate":case"host:file-cut":case"host:file-copy":case"host:file-delete":return!k&&!ae?De:{...De,hidden:!0};case"host:file-copy-name":case"host:file-copy-path":return k?{...De,hidden:!0}:De;case"host:file-copy-rel":return!k&&!Se?De:{...De,hidden:!0};case"host:file-refresh":return k?De:{...De,hidden:!0};default:return De}});fa(We).length!==0&&(v.preventDefault(),v.stopPropagation(),ke.current=ht,Pa({x:v.clientX,y:v.clientY,slot:"contextmenu.file",target:te,entries:We,onHostAction:ot}))},[h,q,Ne,g,ot,M,B,pe]),ct=v=>Array.from(v.dataTransfer?.types??[]).includes("Files"),mt=o.useCallback(()=>{A.current?.querySelectorAll(".file-item.drop-target").forEach(v=>v.classList.remove("drop-target")),A.current?.classList.remove("drop-root")},[]),Mt=o.useCallback(v=>{if(mt(),v==null)return;const te=A.current?.querySelector(`.file-item[data-path="${CSS.escape(v)}"]`);te?te.classList.add("drop-target"):A.current?.classList.add("drop-root")},[mt]),$=v=>{const te=v instanceof Element?v.closest(".file-item"):null;return te?.dataset.type==="dir"?te.dataset.path??q:q},Z=o.useCallback(()=>{const v=document.querySelector(".app");v&&v.dispatchEvent(new DragEvent("dragleave",{bubbles:!0}))},[]),Re=1e4,je=o.useRef(0),Je=o.useRef(void 0),qe=o.useCallback((v,te)=>{const Be=++je.current;C(v),te?.silent||ee(!0),a({type:"list_files",path:v===""?void 0:v})||je.current===Be&&ee(!1)},[a]),At=o.useCallback(v=>{const te=B.filter(Be=>Be!==v);U(te),(q===v||q.startsWith(`${v}/`))&&qe("")},[B,U,q,qe]);o.useEffect(()=>{t&&t.path===q&&ee(!1)},[t,q]),o.useEffect(()=>{if(M!==Je.current){Je.current=M,qe("",{silent:!0});return}const v=setInterval(()=>{document.visibilityState!=="hidden"&&qe(q,{silent:!0})},Re);return()=>clearInterval(v)},[M,q,qe]),o.useEffect(()=>{n&&n.path===q&&qe(q,{silent:!0})},[n,q,qe]);const Lt=v=>qe(v),jt=()=>{t?.parent!==null&&t?.parent!==void 0&&qe(t.parent)},us=(()=>{if(q===""||q===bs)return[];const v=q.split("/").filter(te=>!!te&&te!==bs);return q.startsWith("/")?v.map((te,Be)=>({label:Be===0?"/":v[Be],path:"/"+v.slice(0,Be+1).join("/")})):v.map((te,Be)=>({label:v[Be],path:v.slice(0,Be+1).join("/")}))})(),Qt=[];for(const v of f??[]){if(v.source==="host"||v.hidden||v.kind==="divider")continue;const te=R.find(Be=>Be.id===v.source.slice(7));te&&Qt.push({id:v.id,label:v.label,icon:v.icon,hint:v.hint,pluginPage:{plugin:te,entry:v}})}const Ut=(f??[]).some(v=>v.id==="host:right-files"&&v.hidden);return s.jsxs("aside",{className:"panel panel-right",ref:Q,children:[d&&m&&s.jsx("button",{type:"button",className:"panel-collapse-btn",title:g("collapsePanel"),onClick:m,children:s.jsx(vl,{})}),s.jsx("div",{ref:O,style:{display:"flex",flexDirection:"column",flex:se?`${F.files} 1 0`:"1 1 0",minHeight:se?co:0},children:s.jsx(Qm,{storageKey:"rightpanel",epoch:E??0,send:N??eh,tabs:[...Ut?[]:[{id:Jm,label:g("openFiles"),element:s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"panel-crumbs",children:[s.jsx("button",{type:"button",className:`crumb ${q===""?"active":""}`,onClick:()=>qe(""),children:g("rootDir")}),s.jsx("button",{type:"button",className:`crumb ${q===bs?"active":""}`,title:g("computer"),onClick:()=>qe(bs),children:"💻"}),j!==""&&s.jsx("button",{type:"button",className:`crumb ${q===j||q.startsWith(`${j}/`)?"active":""}`,title:g("homeDir"),onClick:()=>qe(j),children:"🏠"}),Y!==""&&s.jsx("button",{type:"button",className:`crumb ${q===Y||q.startsWith(`${Y}/`)?"active":""}`,title:g("desktopDir"),onClick:()=>qe(Y),children:"🖥️"}),s.jsx(Et,{text:g("filesHelp")}),B.length>0&&s.jsxs("div",{className:"root-picker",children:[s.jsxs("button",{type:"button",className:"crumb root-picker-trigger","aria-haspopup":"menu","aria-expanded":it,title:g("workspaceRoots"),onClick:()=>Xe(v=>!v),children:[s.jsx(is,{}),s.jsx("span",{className:"root-picker-label",children:g("workspaceRoots")}),s.jsx("span",{className:"set-count",children:B.length+1}),"▾"]}),it&&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:q===""?"root-picker-item active":"root-picker-item",title:M,onClick:()=>{Xe(!1),qe("")},children:[g("rootDir"),s.jsx("span",{className:"root-picker-path",children:M})]})}),B.map(v=>s.jsxs("div",{className:"root-picker-row",children:[s.jsx("button",{type:"button",role:"menuitem",className:q===v?"root-picker-item active":"root-picker-item",title:v,onClick:()=>{Xe(!1),qe(v)},children:s.jsx("span",{className:"root-picker-path",children:v})}),s.jsx("button",{type:"button",className:"root-picker-remove",title:g("removeWorkspaceRoot"),"aria-label":g("removeWorkspaceRoot"),onClick:()=>At(v),children:s.jsx(bt,{})})]},v)),s.jsx("div",{className:"root-picker-hint",children:g("workspaceRootsHint")})]})]}),us.map(v=>s.jsxs("span",{className:"crumb-seg",children:[s.jsx(Os,{}),s.jsx("button",{type:"button",className:`crumb ${v.path===q?"active":""}`,onClick:()=>qe(v.path),children:v.label})]},v.path))]}),s.jsxs("div",{ref:P,className:"panel-body",onScroll:v=>{ue.current=v.currentTarget.scrollTop},onContextMenu:v=>Ye(v,{id:q,kind:"list",label:q===""?g("rootDir"):q===bs?g("computer"):q}),onDragOver:v=>{ct(v)&&(v.preventDefault(),v.stopPropagation(),v.dataTransfer.dropEffect="copy",Z(),Mt($(v.target)))},onDragLeave:v=>{v.relatedTarget&&v.currentTarget.contains(v.relatedTarget)||mt()},onDrop:v=>{if(mt(),!ct(v))return;v.preventDefault(),v.stopPropagation(),Z();const te=Array.from(v.dataTransfer?.files??[]);if(te.length===0){u("warning",g("foldersNotSupported"));return}Ue($(v.target),te)},onDragEnd:mt,children:[s.jsx("input",{ref:Ke,type:"file",multiple:!0,hidden:!0,onChange:Le}),X&&s.jsxs("div",{className:"file-item dir",children:[X.kind==="dir"?s.jsx(is,{className:"file-icon"}):s.jsx(vi,{className:"file-icon"}),ye(L,W,Qe,()=>we(null))]}),G&&s.jsx("div",{className:"panel-empty",children:g("loading")}),!G&&t&&t.path===q&&s.jsxs(s.Fragment,{children:[t.parent!=null&&s.jsxs("button",{type:"button",className:"file-item dir",onClick:jt,children:[s.jsx(is,{className:"file-icon"}),s.jsx("span",{className:"file-name",children:".."})]}),t.entries.map(v=>v.type==="dir"?s.jsxs("div",{className:`file-item dir${pe?.cut&&pe.src===v.path?" cut":""}`,"data-type":"dir","data-path":v.path,onContextMenu:te=>Ye(te,{id:v.path,kind:"dir",label:v.name}),children:[Ae===v.path?ye(dt,Ve,de,()=>et(null)):s.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>Lt(v.path),children:[s.jsx(is,{className:"file-icon"}),s.jsx("span",{className:"file-name",children:v.name})]}),s.jsx("button",{type:"button",className:"file-attach ref","data-tip":g("linkFolderTip"),"aria-label":g("linkFolderTip"),onClick:()=>c(v.path,v.name,"reference",!0),children:s.jsx(dr,{})}),s.jsx("button",{type:"button",className:`file-attach copy${ie===`name:${v.path}`?" copied":""}`,"data-tip":g("copyName"),"aria-label":g("copyName"),onClick:()=>le(v.name,`name:${v.path}`),children:ie===`name:${v.path}`?s.jsx(os,{}):s.jsx(cs,{})}),s.jsx("button",{type:"button",className:`file-attach copy${ie===`path:${v.path}`?" copied":""}`,"data-tip":g("copyPath"),"aria-label":g("copyPath"),onClick:()=>le(Ee(v.path),`path:${v.path}`),children:ie===`path:${v.path}`?s.jsx(os,{}):s.jsx(wi,{})})]},v.path):s.jsxs("div",{className:`file-item file${pe?.cut&&pe.src===v.path?" cut":""}`,"data-type":"file","data-path":v.path,onContextMenu:te=>Ye(te,{id:v.path,kind:"file",label:v.name}),children:[Ae===v.path?ye(dt,Ve,de,()=>et(null)):s.jsxs("button",{type:"button",className:"file-name",title:`${v.path} — ${g("previewFile")}`,onClick:()=>l(v.path,v.name),children:[s.jsx(vi,{className:"file-icon"}),s.jsx("span",{className:"file-name-text",children:v.name})]}),s.jsx("button",{type:"button",className:"file-attach download","data-tip":g("downloadFile"),onClick:()=>oe(v.path,v.name),children:s.jsx(Rs,{})}),s.jsx("button",{type:"button",className:"file-attach inline","data-tip":g("attachInlineTip"),onClick:()=>c(v.path,v.name,"inline"),children:s.jsx(Dt,{})}),s.jsx("button",{type:"button",className:"file-attach ref","data-tip":g("referenceTip"),"aria-label":g("referenceTip"),onClick:()=>c(v.path,v.name,"reference"),children:s.jsx(dr,{})}),s.jsx("button",{type:"button",className:`file-attach copy${ie===`name:${v.path}`?" copied":""}`,"data-tip":g("copyName"),"aria-label":g("copyName"),onClick:()=>le(v.name,`name:${v.path}`),children:ie===`name:${v.path}`?s.jsx(os,{}):s.jsx(cs,{})}),s.jsx("button",{type:"button",className:`file-attach copy${ie===`path:${v.path}`?" copied":""}`,"data-tip":g("copyPath"),"aria-label":g("copyPath"),onClick:()=>le(Ee(v.path),`path:${v.path}`),children:ie===`path:${v.path}`?s.jsx(os,{}):s.jsx(wi,{})})]},v.path)),t.truncated&&s.jsx("div",{className:"panel-empty files-truncated",children:g("filesTruncated")})]}),!G&&!t&&s.jsx("div",{className:"panel-empty",children:g("noFiles")})]})]})}],...Qt]})}),se&&s.jsx("div",{className:"rp-sash",onPointerDown:z,onDoubleClick:()=>w({...za}),title:g("dragToResize")}),se&&s.jsx("div",{className:"panel-widgets",style:{flexGrow:F.widgets,minHeight:uo},children:r.filter(v=>v.lines.length>0).map(v=>s.jsxs("div",{className:"widget",children:[s.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:g("widgetExpand"),onClick:()=>xe(v.key),children:[s.jsx("span",{children:v.key}),s.jsx(Fd,{})]}),s.jsx("pre",{className:"widget-lines",children:v.lines.join(`
|
|
326
|
+
`)})]},v.key))}),Te&&(()=>{const v=r.find(te=>te.key===Te);return v?s.jsx("div",{className:"modal-backdrop",onClick:()=>xe(null),children:s.jsxs("div",{className:"widget-expand",onClick:te=>te.stopPropagation(),children:[s.jsxs("div",{className:"widget-expand-head",children:[s.jsx("span",{className:"widget-expand-title",children:v.key}),s.jsx("button",{type:"button",className:"btn",title:g("close"),onClick:()=>xe(null),children:s.jsx(bt,{})})]}),s.jsx("pre",{className:"widget-expand-lines",children:v.lines.join(`
|
|
327
|
+
`)})]})}):null})()]})});function ah(e){ad(e,[/\r?\n|\r/g,rh])}function rh(){return{type:"break"}}function ih(){return function(e){ah(e)}}function oh(e){const t=String(e),n=[];return{toOffset:a,toPoint:r};function r(c){if(typeof c=="number"&&c>-1&&c<=t.length){let l=0;for(;;){let u=n[l];if(u===void 0){const d=po(t,n[l-1]);u=d===-1?t.length+1:d+1,n[l]=u}if(u>c)return{line:l+1,column:c-(l>0?n[l-1]:0)+1,offset:c};l++}}}function a(c){if(c&&typeof c.line=="number"&&typeof c.column=="number"&&!Number.isNaN(c.line)&&!Number.isNaN(c.column)){for(;n.length<c.line;){const u=n[n.length-1],d=po(t,u),m=d===-1?t.length+1:d+1;if(u===m)break;n.push(m)}const l=(c.line>1?n[c.line-2]:0)+c.column-1;if(l<n[c.line-1])return l}}}function po(e,t){const n=e.indexOf("\r",t),r=e.indexOf(`
|
|
328
|
+
`,t);return r===-1?n:n===-1||n+1===r?r:n<r?n:r}const uc={}.hasOwnProperty,lh=Object.prototype;function ch(e,t){const n=t||{};return Xr({file:n.file||void 0,location:!1,schema:n.space==="svg"?Ia:Vr,verbose:n.verbose||!1},e)}function Xr(e,t){let n;switch(t.nodeName){case"#comment":{const r=t;return n={type:"comment",value:r.data},ea(e,r,n),n}case"#document":case"#document-fragment":{const r=t,a="mode"in r?r.mode==="quirks"||r.mode==="limited-quirks":!1;if(n={type:"root",children:dc(e,t.childNodes),data:{quirksMode:a}},e.file&&e.location){const c=String(e.file),l=oh(c),u=l.toPoint(0),d=l.toPoint(c.length);n.position={start:u,end:d}}return n}case"#documentType":{const r=t;return n={type:"doctype"},ea(e,r,n),n}case"#text":{const r=t;return n={type:"text",value:r.value},ea(e,r,n),n}default:return n=uh(e,t),n}}function dc(e,t){let n=-1;const r=[];for(;++n<t.length;){const a=Xr(e,t[n]);r.push(a)}return r}function uh(e,t){const n=e.schema;e.schema=t.namespaceURI===ws.svg?Ia:Vr;let r=-1;const a={};for(;++r<t.attrs.length;){const u=t.attrs[r],d=(u.prefix?u.prefix+":":"")+u.name;uc.call(lh,d)||(a[d]=u.value)}const l=(e.schema.space==="svg"?rd:id)(t.tagName,a,dc(e,t.childNodes));if(ea(e,t,l),l.tagName==="template"){const u=t,d=u.sourceCodeLocation,m=d&&d.startTag&&Us(d.startTag),f=d&&d.endTag&&Us(d.endTag),h=Xr(e,u.content);m&&f&&e.file&&(h.position={start:m.end,end:f.start}),l.content=h}return e.schema=n,l}function ea(e,t,n){if("sourceCodeLocation"in t&&t.sourceCodeLocation&&e.file){const r=dh(e,n,t.sourceCodeLocation);r&&(e.location=!0,n.position=r)}}function dh(e,t,n){const r=Us(n);if(t.type==="element"){const a=t.children[t.children.length-1];if(r&&!n.endTag&&a&&a.position&&a.position.end&&(r.end=Object.assign({},a.position.end)),e.verbose){const c={};let l;if(n.attrs)for(l in n.attrs)uc.call(n.attrs,l)&&(c[dl(e.schema,l).property]=Us(n.attrs[l]));ir(n.startTag);const u=Us(n.startTag),d=n.endTag?Us(n.endTag):void 0,m={opening:u};d&&(m.closing=d),m.properties=c,t.data={position:m}}}return r}function Us(e){const t=mo({line:e.startLine,column:e.startCol,offset:e.startOffset}),n=mo({line:e.endLine,column:e.endCol,offset:e.endOffset});return t||n?{start:t,end:n}:void 0}function mo(e){return e.line&&e.column?e:void 0}const ph={},mh={}.hasOwnProperty,pc=pl("type",{handlers:{root:fh,element:yh,text:xh,comment:Eh,doctype:bh}});function hh(e,t){const r=(t||ph).space;return pc(e,r==="svg"?Ia:Vr)}function fh(e,t){const n={nodeName:"#document",mode:(e.data||{}).quirksMode?"quirks":"no-quirks",childNodes:[]};return n.childNodes=Jr(e.children,n,t),Xs(e,n),n}function gh(e,t){const n={nodeName:"#document-fragment",childNodes:[]};return n.childNodes=Jr(e.children,n,t),Xs(e,n),n}function bh(e){const t={nodeName:"#documentType",name:"html",publicId:"",systemId:"",parentNode:null};return Xs(e,t),t}function xh(e){const t={nodeName:"#text",value:e.value,parentNode:null};return Xs(e,t),t}function Eh(e){const t={nodeName:"#comment",data:e.value,parentNode:null};return Xs(e,t),t}function yh(e,t){const n=t;let r=n;e.type==="element"&&e.tagName.toLowerCase()==="svg"&&n.space==="html"&&(r=Ia);const a=[];let c;if(e.properties){for(c in e.properties)if(c!=="children"&&mh.call(e.properties,c)){const d=Th(r,c,e.properties[c]);d&&a.push(d)}}const l=r.space,u={nodeName:e.tagName,tagName:e.tagName,attrs:a,namespaceURI:ws[l],childNodes:[],parentNode:null};return u.childNodes=Jr(e.children,u,r),Xs(e,u),e.tagName==="template"&&e.content&&(u.content=gh(e.content,r)),u}function Th(e,t,n){const r=dl(e,t);if(n===!1||n===null||n===void 0||typeof n=="number"&&Number.isNaN(n)||!n&&r.boolean)return;Array.isArray(n)&&(n=r.commaSeparated?od(n):ld(n));const a={name:r.attribute,value:n===!0?"":String(n)};if(r.space&&r.space!=="html"&&r.space!=="svg"){const c=a.name.indexOf(":");c<0?a.prefix="":(a.name=a.name.slice(c+1),a.prefix=r.attribute.slice(0,c)),a.namespace=ws[r.space]}return a}function Jr(e,t,n){let r=-1;const a=[];if(e)for(;++r<e.length;){const c=pc(e[r],n);c.parentNode=t,a.push(c)}return a}function Xs(e,t){const n=e.position;n&&n.start&&n.end&&(ir(typeof n.start.offset=="number"),ir(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 kh=["area","base","basefont","bgsound","br","col","command","embed","frame","hr","image","img","input","keygen","link","meta","param","source","track","wbr"],Nh=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]),gt="�";var x;(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"})(x||(x={}));const Ht={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"};function mc(e){return e>=55296&&e<=57343}function vh(e){return e>=56320&&e<=57343}function Ch(e,t){return(e-55296)*1024+9216+t}function hc(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function fc(e){return e>=64976&&e<=65007||Nh.has(e)}var V;(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"})(V||(V={}));const wh=65536;class Sh{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=wh,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:r,col:a,offset:c}=this,l=a+n,u=c+n;return{code:t,startLine:r,endLine:r,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(vh(n))return this.pos++,this._addGap(),Ch(t,n)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,x.EOF;return this._err(V.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 r=0;r<t.length;r++)if((this.html.charCodeAt(this.pos+r)|32)!==t.charCodeAt(r))return!1;return!0}peek(t){const n=this.pos+t;if(n>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,x.EOF;const r=this.html.charCodeAt(n);return r===x.CARRIAGE_RETURN?x.LINE_FEED:r}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,x.EOF;let t=this.html.charCodeAt(this.pos);return t===x.CARRIAGE_RETURN?(this.isEol=!0,this.skipNextNewLine=!0,x.LINE_FEED):t===x.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance()):(this.skipNextNewLine=!1,mc(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===x.LINE_FEED||t===x.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){hc(t)?this._err(V.controlCharacterInInputStream):fc(t)&&this._err(V.noncharacterInInputStream)}retreat(t){for(this.pos-=t;this.pos<this.lastGapPos;)this.lastGapPos=this.gapStack.pop(),this.pos--;this.isEol=!1}}var Ze;(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"})(Ze||(Ze={}));function gc(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 _h=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୕ୖ୪௫ఄ಄ದൡඅ櫬Āoungruent;扢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;怳Ādpuct;戏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ǣጓ\0y;䐎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Ā;tbrk;掶Āoyᜁᝁ;䐱quo;怞ʀcmprtᝓᝡᝤᝨausĀ;eĊĉptyv;榰séᜌnoõēƀahwᝯᝳ;䎲;愶een;扬r;쀀𝔟gcostuvwឍឝឳេ៕៛ƀ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Ā;elƀ;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\0aĀ;t䀬;䁀ƀ;fl戁îᅠeĀmxent»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ↄⅪ←ٖ↛ǰ↉\0proø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;䅓Ācrir;榿;쀀𝔬ͯ\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\0m;櫳;櫽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))),Ah=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 jh(e){var t;return e>=55296&&e<=57343||e>1114111?65533:(t=Ah.get(e))!==null&&t!==void 0?t:e}var St;(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"})(St||(St={}));const Ih=32;var ys;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"})(ys||(ys={}));function Ar(e){return e>=St.ZERO&&e<=St.NINE}function Rh(e){return e>=St.UPPER_A&&e<=St.UPPER_F||e>=St.LOWER_A&&e<=St.LOWER_F}function Ph(e){return e>=St.UPPER_A&&e<=St.UPPER_Z||e>=St.LOWER_A&&e<=St.LOWER_Z||Ar(e)}function Lh(e){return e===St.EQUALS||Ph(e)}var Ct;(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"})(Ct||(Ct={}));var ms;(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(ms||(ms={}));class Dh{constructor(t,n,r){this.decodeTree=t,this.emitCodePoint=n,this.errors=r,this.state=Ct.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=ms.Strict}startEntity(t){this.decodeMode=t,this.state=Ct.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(t,n){switch(this.state){case Ct.EntityStart:return t.charCodeAt(n)===St.NUM?(this.state=Ct.NumericStart,this.consumed+=1,this.stateNumericStart(t,n+1)):(this.state=Ct.NamedEntity,this.stateNamedEntity(t,n));case Ct.NumericStart:return this.stateNumericStart(t,n);case Ct.NumericDecimal:return this.stateNumericDecimal(t,n);case Ct.NumericHex:return this.stateNumericHex(t,n);case Ct.NamedEntity:return this.stateNamedEntity(t,n)}}stateNumericStart(t,n){return n>=t.length?-1:(t.charCodeAt(n)|Ih)===St.LOWER_X?(this.state=Ct.NumericHex,this.consumed+=1,this.stateNumericHex(t,n+1)):(this.state=Ct.NumericDecimal,this.stateNumericDecimal(t,n))}addToNumericResult(t,n,r,a){if(n!==r){const c=r-n;this.result=this.result*Math.pow(a,c)+Number.parseInt(t.substr(n,c),a),this.consumed+=c}}stateNumericHex(t,n){const r=n;for(;n<t.length;){const a=t.charCodeAt(n);if(Ar(a)||Rh(a))n+=1;else return this.addToNumericResult(t,r,n,16),this.emitNumericEntity(a,3)}return this.addToNumericResult(t,r,n,16),-1}stateNumericDecimal(t,n){const r=n;for(;n<t.length;){const a=t.charCodeAt(n);if(Ar(a))n+=1;else return this.addToNumericResult(t,r,n,10),this.emitNumericEntity(a,2)}return this.addToNumericResult(t,r,n,10),-1}emitNumericEntity(t,n){var r;if(this.consumed<=n)return(r=this.errors)===null||r===void 0||r.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(t===St.SEMI)this.consumed+=1;else if(this.decodeMode===ms.Strict)return 0;return this.emitCodePoint(jh(this.result),this.consumed),this.errors&&(t!==St.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(t,n){const{decodeTree:r}=this;let a=r[this.treeIndex],c=(a&ys.VALUE_LENGTH)>>14;for(;n<t.length;n++,this.excess++){const l=t.charCodeAt(n);if(this.treeIndex=Oh(r,a,this.treeIndex+Math.max(1,c),l),this.treeIndex<0)return this.result===0||this.decodeMode===ms.Attribute&&(c===0||Lh(l))?0:this.emitNotTerminatedNamedEntity();if(a=r[this.treeIndex],c=(a&ys.VALUE_LENGTH)>>14,c!==0){if(l===St.SEMI)return this.emitNamedEntityData(this.treeIndex,c,this.consumed+this.excess);this.decodeMode!==ms.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var t;const{result:n,decodeTree:r}=this,a=(r[n]&ys.VALUE_LENGTH)>>14;return this.emitNamedEntityData(n,a,this.consumed),(t=this.errors)===null||t===void 0||t.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,n,r){const{decodeTree:a}=this;return this.emitCodePoint(n===1?a[t]&~ys.VALUE_LENGTH:a[t+1],r),n===3&&this.emitCodePoint(a[t+2],r),r}end(){var t;switch(this.state){case Ct.NamedEntity:return this.result!==0&&(this.decodeMode!==ms.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case Ct.NumericDecimal:return this.emitNumericEntity(0,2);case Ct.NumericHex:return this.emitNumericEntity(0,3);case Ct.NumericStart:return(t=this.errors)===null||t===void 0||t.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case Ct.EntityStart:return 0}}}function Oh(e,t,n,r){const a=(t&ys.BRANCH_LENGTH)>>7,c=t&ys.JUMP_TABLE;if(a===0)return c!==0&&r===c?n:-1;if(c){const d=r-c;return d<0||d>=a?-1:e[n+d]-1}let l=n,u=l+a-1;for(;l<=u;){const d=l+u>>>1,m=e[d];if(m<r)l=d+1;else if(m>r)u=d-1;else return e[d+a]}return-1}var me;(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/"})(me||(me={}));var Ps;(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"})(Ps||(Ps={}));var Gt;(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks"})(Gt||(Gt={}));var H;(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"})(H||(H={}));var i;(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"})(i||(i={}));const Mh=new Map([[H.A,i.A],[H.ADDRESS,i.ADDRESS],[H.ANNOTATION_XML,i.ANNOTATION_XML],[H.APPLET,i.APPLET],[H.AREA,i.AREA],[H.ARTICLE,i.ARTICLE],[H.ASIDE,i.ASIDE],[H.B,i.B],[H.BASE,i.BASE],[H.BASEFONT,i.BASEFONT],[H.BGSOUND,i.BGSOUND],[H.BIG,i.BIG],[H.BLOCKQUOTE,i.BLOCKQUOTE],[H.BODY,i.BODY],[H.BR,i.BR],[H.BUTTON,i.BUTTON],[H.CAPTION,i.CAPTION],[H.CENTER,i.CENTER],[H.CODE,i.CODE],[H.COL,i.COL],[H.COLGROUP,i.COLGROUP],[H.DD,i.DD],[H.DESC,i.DESC],[H.DETAILS,i.DETAILS],[H.DIALOG,i.DIALOG],[H.DIR,i.DIR],[H.DIV,i.DIV],[H.DL,i.DL],[H.DT,i.DT],[H.EM,i.EM],[H.EMBED,i.EMBED],[H.FIELDSET,i.FIELDSET],[H.FIGCAPTION,i.FIGCAPTION],[H.FIGURE,i.FIGURE],[H.FONT,i.FONT],[H.FOOTER,i.FOOTER],[H.FOREIGN_OBJECT,i.FOREIGN_OBJECT],[H.FORM,i.FORM],[H.FRAME,i.FRAME],[H.FRAMESET,i.FRAMESET],[H.H1,i.H1],[H.H2,i.H2],[H.H3,i.H3],[H.H4,i.H4],[H.H5,i.H5],[H.H6,i.H6],[H.HEAD,i.HEAD],[H.HEADER,i.HEADER],[H.HGROUP,i.HGROUP],[H.HR,i.HR],[H.HTML,i.HTML],[H.I,i.I],[H.IMG,i.IMG],[H.IMAGE,i.IMAGE],[H.INPUT,i.INPUT],[H.IFRAME,i.IFRAME],[H.KEYGEN,i.KEYGEN],[H.LABEL,i.LABEL],[H.LI,i.LI],[H.LINK,i.LINK],[H.LISTING,i.LISTING],[H.MAIN,i.MAIN],[H.MALIGNMARK,i.MALIGNMARK],[H.MARQUEE,i.MARQUEE],[H.MATH,i.MATH],[H.MENU,i.MENU],[H.META,i.META],[H.MGLYPH,i.MGLYPH],[H.MI,i.MI],[H.MO,i.MO],[H.MN,i.MN],[H.MS,i.MS],[H.MTEXT,i.MTEXT],[H.NAV,i.NAV],[H.NOBR,i.NOBR],[H.NOFRAMES,i.NOFRAMES],[H.NOEMBED,i.NOEMBED],[H.NOSCRIPT,i.NOSCRIPT],[H.OBJECT,i.OBJECT],[H.OL,i.OL],[H.OPTGROUP,i.OPTGROUP],[H.OPTION,i.OPTION],[H.P,i.P],[H.PARAM,i.PARAM],[H.PLAINTEXT,i.PLAINTEXT],[H.PRE,i.PRE],[H.RB,i.RB],[H.RP,i.RP],[H.RT,i.RT],[H.RTC,i.RTC],[H.RUBY,i.RUBY],[H.S,i.S],[H.SCRIPT,i.SCRIPT],[H.SEARCH,i.SEARCH],[H.SECTION,i.SECTION],[H.SELECT,i.SELECT],[H.SOURCE,i.SOURCE],[H.SMALL,i.SMALL],[H.SPAN,i.SPAN],[H.STRIKE,i.STRIKE],[H.STRONG,i.STRONG],[H.STYLE,i.STYLE],[H.SUB,i.SUB],[H.SUMMARY,i.SUMMARY],[H.SUP,i.SUP],[H.TABLE,i.TABLE],[H.TBODY,i.TBODY],[H.TEMPLATE,i.TEMPLATE],[H.TEXTAREA,i.TEXTAREA],[H.TFOOT,i.TFOOT],[H.TD,i.TD],[H.TH,i.TH],[H.THEAD,i.THEAD],[H.TITLE,i.TITLE],[H.TR,i.TR],[H.TRACK,i.TRACK],[H.TT,i.TT],[H.U,i.U],[H.UL,i.UL],[H.SVG,i.SVG],[H.VAR,i.VAR],[H.WBR,i.WBR],[H.XMP,i.XMP]]);function Js(e){var t;return(t=Mh.get(e))!==null&&t!==void 0?t:i.UNKNOWN}const be=i,Bh={[me.HTML]:new Set([be.ADDRESS,be.APPLET,be.AREA,be.ARTICLE,be.ASIDE,be.BASE,be.BASEFONT,be.BGSOUND,be.BLOCKQUOTE,be.BODY,be.BR,be.BUTTON,be.CAPTION,be.CENTER,be.COL,be.COLGROUP,be.DD,be.DETAILS,be.DIR,be.DIV,be.DL,be.DT,be.EMBED,be.FIELDSET,be.FIGCAPTION,be.FIGURE,be.FOOTER,be.FORM,be.FRAME,be.FRAMESET,be.H1,be.H2,be.H3,be.H4,be.H5,be.H6,be.HEAD,be.HEADER,be.HGROUP,be.HR,be.HTML,be.IFRAME,be.IMG,be.INPUT,be.LI,be.LINK,be.LISTING,be.MAIN,be.MARQUEE,be.MENU,be.META,be.NAV,be.NOEMBED,be.NOFRAMES,be.NOSCRIPT,be.OBJECT,be.OL,be.P,be.PARAM,be.PLAINTEXT,be.PRE,be.SCRIPT,be.SECTION,be.SELECT,be.SOURCE,be.STYLE,be.SUMMARY,be.TABLE,be.TBODY,be.TD,be.TEMPLATE,be.TEXTAREA,be.TFOOT,be.TH,be.THEAD,be.TITLE,be.TR,be.TRACK,be.UL,be.WBR,be.XMP]),[me.MATHML]:new Set([be.MI,be.MO,be.MN,be.MS,be.MTEXT,be.ANNOTATION_XML]),[me.SVG]:new Set([be.TITLE,be.FOREIGN_OBJECT,be.DESC]),[me.XLINK]:new Set,[me.XML]:new Set,[me.XMLNS]:new Set},jr=new Set([be.H1,be.H2,be.H3,be.H4,be.H5,be.H6]);H.STYLE,H.SCRIPT,H.XMP,H.IFRAME,H.NOEMBED,H.NOFRAMES,H.PLAINTEXT;var y;(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"})(y||(y={}));const Tt={DATA:y.DATA,RCDATA:y.RCDATA,RAWTEXT:y.RAWTEXT,SCRIPT_DATA:y.SCRIPT_DATA,PLAINTEXT:y.PLAINTEXT,CDATA_SECTION:y.CDATA_SECTION};function Fh(e){return e>=x.DIGIT_0&&e<=x.DIGIT_9}function dn(e){return e>=x.LATIN_CAPITAL_A&&e<=x.LATIN_CAPITAL_Z}function Hh(e){return e>=x.LATIN_SMALL_A&&e<=x.LATIN_SMALL_Z}function xs(e){return Hh(e)||dn(e)}function ho(e){return xs(e)||Fh(e)}function qn(e){return e+32}function bc(e){return e===x.SPACE||e===x.LINE_FEED||e===x.TABULATION||e===x.FORM_FEED}function fo(e){return bc(e)||e===x.SOLIDUS||e===x.GREATER_THAN_SIGN}function Uh(e){return e===x.NULL?V.nullCharacterReference:e>1114111?V.characterReferenceOutsideUnicodeRange:mc(e)?V.surrogateCharacterReference:fc(e)?V.noncharacterCharacterReference:hc(e)||e===x.CARRIAGE_RETURN?V.controlCharacterReference:null}class $h{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=y.DATA,this.returnState=y.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new Sh(n),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new Dh(_h,(r,a)=>{this.preprocessor.pos=this.entityStartPos+a-1,this._flushCodePointConsumedAsCharacterReference(r)},n.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(V.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:r=>{this._err(V.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+r)},validateNumericCharacterReference:r=>{const a=Uh(r);a&&this._err(a,1)}}:void 0)}_err(t,n=0){var r,a;(a=(r=this.handler).onParseError)===null||a===void 0||a.call(r,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,r){this.active=!0,this.preprocessor.write(t,n),this._runParsingLoop(),this.paused||r?.()}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:Ze.START_TAG,tagName:"",tagID:i.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(1)}}_createEndTagToken(){this.currentToken={type:Ze.END_TAG,tagName:"",tagID:i.UNKNOWN,selfClosing:!1,ackSelfClosing:!1,attrs:[],location:this.getCurrentLocation(2)}}_createCommentToken(t){this.currentToken={type:Ze.COMMENT,data:"",location:this.getCurrentLocation(t)}}_createDoctypeToken(t){this.currentToken={type:Ze.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 r=this.currentToken;if(gc(r,this.currentAttr.name)===null){if(r.attrs.push(this.currentAttr),r.location&&this.currentLocation){const a=(t=(n=r.location).attrs)!==null&&t!==void 0?t:n.attrs=Object.create(null);a[this.currentAttr.name]=this.currentLocation,this._leaveAttrValue()}}else this._err(V.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=Js(t.tagName),t.type===Ze.START_TAG?(this.lastStartTagName=t.tagName,this.handler.onStartTag(t)):(t.attrs.length>0&&this._err(V.endTagWithAttributes),t.selfClosing&&this._err(V.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 Ze.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case Ze.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case Ze.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:Ze.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=bc(t)?Ze.WHITESPACE_CHARACTER:t===x.NULL?Ze.NULL_CHARACTER:Ze.CHARACTER;this._appendCharToCurrentCharacterToken(n,String.fromCodePoint(t))}_emitChars(t){this._appendCharToCurrentCharacterToken(Ze.CHARACTER,t)}_startCharacterReference(){this.returnState=this.state,this.state=y.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?ms.Attribute:ms.Legacy)}_isCharacterReferenceInAttribute(){return this.returnState===y.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===y.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===y.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t)}_callState(t){switch(this.state){case y.DATA:{this._stateData(t);break}case y.RCDATA:{this._stateRcdata(t);break}case y.RAWTEXT:{this._stateRawtext(t);break}case y.SCRIPT_DATA:{this._stateScriptData(t);break}case y.PLAINTEXT:{this._statePlaintext(t);break}case y.TAG_OPEN:{this._stateTagOpen(t);break}case y.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case y.TAG_NAME:{this._stateTagName(t);break}case y.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case y.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case y.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case y.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case y.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case y.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case y.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case y.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case y.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case y.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case y.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case y.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case y.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case y.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case y.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case y.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case y.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case y.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case y.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case y.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case y.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case y.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case y.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case y.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case y.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case y.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case y.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case y.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case y.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case y.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case y.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case y.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case y.BOGUS_COMMENT:{this._stateBogusComment(t);break}case y.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case y.COMMENT_START:{this._stateCommentStart(t);break}case y.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case y.COMMENT:{this._stateComment(t);break}case y.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case y.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case y.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case y.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case y.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case y.COMMENT_END:{this._stateCommentEnd(t);break}case y.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case y.DOCTYPE:{this._stateDoctype(t);break}case y.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case y.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case y.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case y.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case y.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case y.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case y.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case y.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case y.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case y.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case y.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case y.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case y.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case y.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case y.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case y.CDATA_SECTION:{this._stateCdataSection(t);break}case y.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case y.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case y.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case y.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case x.LESS_THAN_SIGN:{this.state=y.TAG_OPEN;break}case x.AMPERSAND:{this._startCharacterReference();break}case x.NULL:{this._err(V.unexpectedNullCharacter),this._emitCodePoint(t);break}case x.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRcdata(t){switch(t){case x.AMPERSAND:{this._startCharacterReference();break}case x.LESS_THAN_SIGN:{this.state=y.RCDATA_LESS_THAN_SIGN;break}case x.NULL:{this._err(V.unexpectedNullCharacter),this._emitChars(gt);break}case x.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRawtext(t){switch(t){case x.LESS_THAN_SIGN:{this.state=y.RAWTEXT_LESS_THAN_SIGN;break}case x.NULL:{this._err(V.unexpectedNullCharacter),this._emitChars(gt);break}case x.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptData(t){switch(t){case x.LESS_THAN_SIGN:{this.state=y.SCRIPT_DATA_LESS_THAN_SIGN;break}case x.NULL:{this._err(V.unexpectedNullCharacter),this._emitChars(gt);break}case x.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_statePlaintext(t){switch(t){case x.NULL:{this._err(V.unexpectedNullCharacter),this._emitChars(gt);break}case x.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateTagOpen(t){if(xs(t))this._createStartTagToken(),this.state=y.TAG_NAME,this._stateTagName(t);else switch(t){case x.EXCLAMATION_MARK:{this.state=y.MARKUP_DECLARATION_OPEN;break}case x.SOLIDUS:{this.state=y.END_TAG_OPEN;break}case x.QUESTION_MARK:{this._err(V.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=y.BOGUS_COMMENT,this._stateBogusComment(t);break}case x.EOF:{this._err(V.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(V.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=y.DATA,this._stateData(t)}}_stateEndTagOpen(t){if(xs(t))this._createEndTagToken(),this.state=y.TAG_NAME,this._stateTagName(t);else switch(t){case x.GREATER_THAN_SIGN:{this._err(V.missingEndTagName),this.state=y.DATA;break}case x.EOF:{this._err(V.eofBeforeTagName),this._emitChars("</"),this._emitEOFToken();break}default:this._err(V.invalidFirstCharacterOfTagName),this._createCommentToken(2),this.state=y.BOGUS_COMMENT,this._stateBogusComment(t)}}_stateTagName(t){const n=this.currentToken;switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:{this.state=y.BEFORE_ATTRIBUTE_NAME;break}case x.SOLIDUS:{this.state=y.SELF_CLOSING_START_TAG;break}case x.GREATER_THAN_SIGN:{this.state=y.DATA,this.emitCurrentTagToken();break}case x.NULL:{this._err(V.unexpectedNullCharacter),n.tagName+=gt;break}case x.EOF:{this._err(V.eofInTag),this._emitEOFToken();break}default:n.tagName+=String.fromCodePoint(dn(t)?qn(t):t)}}_stateRcdataLessThanSign(t){t===x.SOLIDUS?this.state=y.RCDATA_END_TAG_OPEN:(this._emitChars("<"),this.state=y.RCDATA,this._stateRcdata(t))}_stateRcdataEndTagOpen(t){xs(t)?(this.state=y.RCDATA_END_TAG_NAME,this._stateRcdataEndTagName(t)):(this._emitChars("</"),this.state=y.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 x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:return this._advanceBy(this.lastStartTagName.length),this.state=y.BEFORE_ATTRIBUTE_NAME,!1;case x.SOLIDUS:return this._advanceBy(this.lastStartTagName.length),this.state=y.SELF_CLOSING_START_TAG,!1;case x.GREATER_THAN_SIGN:return this._advanceBy(this.lastStartTagName.length),this.emitCurrentTagToken(),this.state=y.DATA,!1;default:return!this._ensureHibernation()}}_stateRcdataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=y.RCDATA,this._stateRcdata(t))}_stateRawtextLessThanSign(t){t===x.SOLIDUS?this.state=y.RAWTEXT_END_TAG_OPEN:(this._emitChars("<"),this.state=y.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagOpen(t){xs(t)?(this.state=y.RAWTEXT_END_TAG_NAME,this._stateRawtextEndTagName(t)):(this._emitChars("</"),this.state=y.RAWTEXT,this._stateRawtext(t))}_stateRawtextEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=y.RAWTEXT,this._stateRawtext(t))}_stateScriptDataLessThanSign(t){switch(t){case x.SOLIDUS:{this.state=y.SCRIPT_DATA_END_TAG_OPEN;break}case x.EXCLAMATION_MARK:{this.state=y.SCRIPT_DATA_ESCAPE_START,this._emitChars("<!");break}default:this._emitChars("<"),this.state=y.SCRIPT_DATA,this._stateScriptData(t)}}_stateScriptDataEndTagOpen(t){xs(t)?(this.state=y.SCRIPT_DATA_END_TAG_NAME,this._stateScriptDataEndTagName(t)):(this._emitChars("</"),this.state=y.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=y.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStart(t){t===x.HYPHEN_MINUS?(this.state=y.SCRIPT_DATA_ESCAPE_START_DASH,this._emitChars("-")):(this.state=y.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscapeStartDash(t){t===x.HYPHEN_MINUS?(this.state=y.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-")):(this.state=y.SCRIPT_DATA,this._stateScriptData(t))}_stateScriptDataEscaped(t){switch(t){case x.HYPHEN_MINUS:{this.state=y.SCRIPT_DATA_ESCAPED_DASH,this._emitChars("-");break}case x.LESS_THAN_SIGN:{this.state=y.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case x.NULL:{this._err(V.unexpectedNullCharacter),this._emitChars(gt);break}case x.EOF:{this._err(V.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataEscapedDash(t){switch(t){case x.HYPHEN_MINUS:{this.state=y.SCRIPT_DATA_ESCAPED_DASH_DASH,this._emitChars("-");break}case x.LESS_THAN_SIGN:{this.state=y.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case x.NULL:{this._err(V.unexpectedNullCharacter),this.state=y.SCRIPT_DATA_ESCAPED,this._emitChars(gt);break}case x.EOF:{this._err(V.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=y.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedDashDash(t){switch(t){case x.HYPHEN_MINUS:{this._emitChars("-");break}case x.LESS_THAN_SIGN:{this.state=y.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN;break}case x.GREATER_THAN_SIGN:{this.state=y.SCRIPT_DATA,this._emitChars(">");break}case x.NULL:{this._err(V.unexpectedNullCharacter),this.state=y.SCRIPT_DATA_ESCAPED,this._emitChars(gt);break}case x.EOF:{this._err(V.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=y.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedLessThanSign(t){t===x.SOLIDUS?this.state=y.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:xs(t)?(this._emitChars("<"),this.state=y.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=y.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagOpen(t){xs(t)?(this.state=y.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("</"),this.state=y.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagName(t){this.handleSpecialEndTag(t)&&(this._emitChars("</"),this.state=y.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscapeStart(t){if(this.preprocessor.startsWith(Ht.SCRIPT,!1)&&fo(this.preprocessor.peek(Ht.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<Ht.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=y.SCRIPT_DATA_DOUBLE_ESCAPED}else this._ensureHibernation()||(this.state=y.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataDoubleEscaped(t){switch(t){case x.HYPHEN_MINUS:{this.state=y.SCRIPT_DATA_DOUBLE_ESCAPED_DASH,this._emitChars("-");break}case x.LESS_THAN_SIGN:{this.state=y.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case x.NULL:{this._err(V.unexpectedNullCharacter),this._emitChars(gt);break}case x.EOF:{this._err(V.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDash(t){switch(t){case x.HYPHEN_MINUS:{this.state=y.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH,this._emitChars("-");break}case x.LESS_THAN_SIGN:{this.state=y.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case x.NULL:{this._err(V.unexpectedNullCharacter),this.state=y.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(gt);break}case x.EOF:{this._err(V.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=y.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedDashDash(t){switch(t){case x.HYPHEN_MINUS:{this._emitChars("-");break}case x.LESS_THAN_SIGN:{this.state=y.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN,this._emitChars("<");break}case x.GREATER_THAN_SIGN:{this.state=y.SCRIPT_DATA,this._emitChars(">");break}case x.NULL:{this._err(V.unexpectedNullCharacter),this.state=y.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(gt);break}case x.EOF:{this._err(V.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=y.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedLessThanSign(t){t===x.SOLIDUS?(this.state=y.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=y.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(Ht.SCRIPT,!1)&&fo(this.preprocessor.peek(Ht.SCRIPT.length))){this._emitCodePoint(t);for(let n=0;n<Ht.SCRIPT.length;n++)this._emitCodePoint(this._consume());this.state=y.SCRIPT_DATA_ESCAPED}else this._ensureHibernation()||(this.state=y.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateBeforeAttributeName(t){switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:break;case x.SOLIDUS:case x.GREATER_THAN_SIGN:case x.EOF:{this.state=y.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case x.EQUALS_SIGN:{this._err(V.unexpectedEqualsSignBeforeAttributeName),this._createAttr("="),this.state=y.ATTRIBUTE_NAME;break}default:this._createAttr(""),this.state=y.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateAttributeName(t){switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:case x.SOLIDUS:case x.GREATER_THAN_SIGN:case x.EOF:{this._leaveAttrName(),this.state=y.AFTER_ATTRIBUTE_NAME,this._stateAfterAttributeName(t);break}case x.EQUALS_SIGN:{this._leaveAttrName(),this.state=y.BEFORE_ATTRIBUTE_VALUE;break}case x.QUOTATION_MARK:case x.APOSTROPHE:case x.LESS_THAN_SIGN:{this._err(V.unexpectedCharacterInAttributeName),this.currentAttr.name+=String.fromCodePoint(t);break}case x.NULL:{this._err(V.unexpectedNullCharacter),this.currentAttr.name+=gt;break}default:this.currentAttr.name+=String.fromCodePoint(dn(t)?qn(t):t)}}_stateAfterAttributeName(t){switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:break;case x.SOLIDUS:{this.state=y.SELF_CLOSING_START_TAG;break}case x.EQUALS_SIGN:{this.state=y.BEFORE_ATTRIBUTE_VALUE;break}case x.GREATER_THAN_SIGN:{this.state=y.DATA,this.emitCurrentTagToken();break}case x.EOF:{this._err(V.eofInTag),this._emitEOFToken();break}default:this._createAttr(""),this.state=y.ATTRIBUTE_NAME,this._stateAttributeName(t)}}_stateBeforeAttributeValue(t){switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:break;case x.QUOTATION_MARK:{this.state=y.ATTRIBUTE_VALUE_DOUBLE_QUOTED;break}case x.APOSTROPHE:{this.state=y.ATTRIBUTE_VALUE_SINGLE_QUOTED;break}case x.GREATER_THAN_SIGN:{this._err(V.missingAttributeValue),this.state=y.DATA,this.emitCurrentTagToken();break}default:this.state=y.ATTRIBUTE_VALUE_UNQUOTED,this._stateAttributeValueUnquoted(t)}}_stateAttributeValueDoubleQuoted(t){switch(t){case x.QUOTATION_MARK:{this.state=y.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case x.AMPERSAND:{this._startCharacterReference();break}case x.NULL:{this._err(V.unexpectedNullCharacter),this.currentAttr.value+=gt;break}case x.EOF:{this._err(V.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueSingleQuoted(t){switch(t){case x.APOSTROPHE:{this.state=y.AFTER_ATTRIBUTE_VALUE_QUOTED;break}case x.AMPERSAND:{this._startCharacterReference();break}case x.NULL:{this._err(V.unexpectedNullCharacter),this.currentAttr.value+=gt;break}case x.EOF:{this._err(V.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAttributeValueUnquoted(t){switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:{this._leaveAttrValue(),this.state=y.BEFORE_ATTRIBUTE_NAME;break}case x.AMPERSAND:{this._startCharacterReference();break}case x.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=y.DATA,this.emitCurrentTagToken();break}case x.NULL:{this._err(V.unexpectedNullCharacter),this.currentAttr.value+=gt;break}case x.QUOTATION_MARK:case x.APOSTROPHE:case x.LESS_THAN_SIGN:case x.EQUALS_SIGN:case x.GRAVE_ACCENT:{this._err(V.unexpectedCharacterInUnquotedAttributeValue),this.currentAttr.value+=String.fromCodePoint(t);break}case x.EOF:{this._err(V.eofInTag),this._emitEOFToken();break}default:this.currentAttr.value+=String.fromCodePoint(t)}}_stateAfterAttributeValueQuoted(t){switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:{this._leaveAttrValue(),this.state=y.BEFORE_ATTRIBUTE_NAME;break}case x.SOLIDUS:{this._leaveAttrValue(),this.state=y.SELF_CLOSING_START_TAG;break}case x.GREATER_THAN_SIGN:{this._leaveAttrValue(),this.state=y.DATA,this.emitCurrentTagToken();break}case x.EOF:{this._err(V.eofInTag),this._emitEOFToken();break}default:this._err(V.missingWhitespaceBetweenAttributes),this.state=y.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateSelfClosingStartTag(t){switch(t){case x.GREATER_THAN_SIGN:{const n=this.currentToken;n.selfClosing=!0,this.state=y.DATA,this.emitCurrentTagToken();break}case x.EOF:{this._err(V.eofInTag),this._emitEOFToken();break}default:this._err(V.unexpectedSolidusInTag),this.state=y.BEFORE_ATTRIBUTE_NAME,this._stateBeforeAttributeName(t)}}_stateBogusComment(t){const n=this.currentToken;switch(t){case x.GREATER_THAN_SIGN:{this.state=y.DATA,this.emitCurrentComment(n);break}case x.EOF:{this.emitCurrentComment(n),this._emitEOFToken();break}case x.NULL:{this._err(V.unexpectedNullCharacter),n.data+=gt;break}default:n.data+=String.fromCodePoint(t)}}_stateMarkupDeclarationOpen(t){this._consumeSequenceIfMatch(Ht.DASH_DASH,!0)?(this._createCommentToken(Ht.DASH_DASH.length+1),this.state=y.COMMENT_START):this._consumeSequenceIfMatch(Ht.DOCTYPE,!1)?(this.currentLocation=this.getCurrentLocation(Ht.DOCTYPE.length+1),this.state=y.DOCTYPE):this._consumeSequenceIfMatch(Ht.CDATA_START,!0)?this.inForeignNode?this.state=y.CDATA_SECTION:(this._err(V.cdataInHtmlContent),this._createCommentToken(Ht.CDATA_START.length+1),this.currentToken.data="[CDATA[",this.state=y.BOGUS_COMMENT):this._ensureHibernation()||(this._err(V.incorrectlyOpenedComment),this._createCommentToken(2),this.state=y.BOGUS_COMMENT,this._stateBogusComment(t))}_stateCommentStart(t){switch(t){case x.HYPHEN_MINUS:{this.state=y.COMMENT_START_DASH;break}case x.GREATER_THAN_SIGN:{this._err(V.abruptClosingOfEmptyComment),this.state=y.DATA;const n=this.currentToken;this.emitCurrentComment(n);break}default:this.state=y.COMMENT,this._stateComment(t)}}_stateCommentStartDash(t){const n=this.currentToken;switch(t){case x.HYPHEN_MINUS:{this.state=y.COMMENT_END;break}case x.GREATER_THAN_SIGN:{this._err(V.abruptClosingOfEmptyComment),this.state=y.DATA,this.emitCurrentComment(n);break}case x.EOF:{this._err(V.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=y.COMMENT,this._stateComment(t)}}_stateComment(t){const n=this.currentToken;switch(t){case x.HYPHEN_MINUS:{this.state=y.COMMENT_END_DASH;break}case x.LESS_THAN_SIGN:{n.data+="<",this.state=y.COMMENT_LESS_THAN_SIGN;break}case x.NULL:{this._err(V.unexpectedNullCharacter),n.data+=gt;break}case x.EOF:{this._err(V.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+=String.fromCodePoint(t)}}_stateCommentLessThanSign(t){const n=this.currentToken;switch(t){case x.EXCLAMATION_MARK:{n.data+="!",this.state=y.COMMENT_LESS_THAN_SIGN_BANG;break}case x.LESS_THAN_SIGN:{n.data+="<";break}default:this.state=y.COMMENT,this._stateComment(t)}}_stateCommentLessThanSignBang(t){t===x.HYPHEN_MINUS?this.state=y.COMMENT_LESS_THAN_SIGN_BANG_DASH:(this.state=y.COMMENT,this._stateComment(t))}_stateCommentLessThanSignBangDash(t){t===x.HYPHEN_MINUS?this.state=y.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:(this.state=y.COMMENT_END_DASH,this._stateCommentEndDash(t))}_stateCommentLessThanSignBangDashDash(t){t!==x.GREATER_THAN_SIGN&&t!==x.EOF&&this._err(V.nestedComment),this.state=y.COMMENT_END,this._stateCommentEnd(t)}_stateCommentEndDash(t){const n=this.currentToken;switch(t){case x.HYPHEN_MINUS:{this.state=y.COMMENT_END;break}case x.EOF:{this._err(V.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="-",this.state=y.COMMENT,this._stateComment(t)}}_stateCommentEnd(t){const n=this.currentToken;switch(t){case x.GREATER_THAN_SIGN:{this.state=y.DATA,this.emitCurrentComment(n);break}case x.EXCLAMATION_MARK:{this.state=y.COMMENT_END_BANG;break}case x.HYPHEN_MINUS:{n.data+="-";break}case x.EOF:{this._err(V.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--",this.state=y.COMMENT,this._stateComment(t)}}_stateCommentEndBang(t){const n=this.currentToken;switch(t){case x.HYPHEN_MINUS:{n.data+="--!",this.state=y.COMMENT_END_DASH;break}case x.GREATER_THAN_SIGN:{this._err(V.incorrectlyClosedComment),this.state=y.DATA,this.emitCurrentComment(n);break}case x.EOF:{this._err(V.eofInComment),this.emitCurrentComment(n),this._emitEOFToken();break}default:n.data+="--!",this.state=y.COMMENT,this._stateComment(t)}}_stateDoctype(t){switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:{this.state=y.BEFORE_DOCTYPE_NAME;break}case x.GREATER_THAN_SIGN:{this.state=y.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t);break}case x.EOF:{this._err(V.eofInDoctype),this._createDoctypeToken(null);const n=this.currentToken;n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(V.missingWhitespaceBeforeDoctypeName),this.state=y.BEFORE_DOCTYPE_NAME,this._stateBeforeDoctypeName(t)}}_stateBeforeDoctypeName(t){if(dn(t))this._createDoctypeToken(String.fromCharCode(qn(t))),this.state=y.DOCTYPE_NAME;else switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:break;case x.NULL:{this._err(V.unexpectedNullCharacter),this._createDoctypeToken(gt),this.state=y.DOCTYPE_NAME;break}case x.GREATER_THAN_SIGN:{this._err(V.missingDoctypeName),this._createDoctypeToken(null);const n=this.currentToken;n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=y.DATA;break}case x.EOF:{this._err(V.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=y.DOCTYPE_NAME}}_stateDoctypeName(t){const n=this.currentToken;switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:{this.state=y.AFTER_DOCTYPE_NAME;break}case x.GREATER_THAN_SIGN:{this.state=y.DATA,this.emitCurrentDoctype(n);break}case x.NULL:{this._err(V.unexpectedNullCharacter),n.name+=gt;break}case x.EOF:{this._err(V.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:n.name+=String.fromCodePoint(dn(t)?qn(t):t)}}_stateAfterDoctypeName(t){const n=this.currentToken;switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:break;case x.GREATER_THAN_SIGN:{this.state=y.DATA,this.emitCurrentDoctype(n);break}case x.EOF:{this._err(V.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._consumeSequenceIfMatch(Ht.PUBLIC,!1)?this.state=y.AFTER_DOCTYPE_PUBLIC_KEYWORD:this._consumeSequenceIfMatch(Ht.SYSTEM,!1)?this.state=y.AFTER_DOCTYPE_SYSTEM_KEYWORD:this._ensureHibernation()||(this._err(V.invalidCharacterSequenceAfterDoctypeName),n.forceQuirks=!0,this.state=y.BOGUS_DOCTYPE,this._stateBogusDoctype(t))}}_stateAfterDoctypePublicKeyword(t){const n=this.currentToken;switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:{this.state=y.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER;break}case x.QUOTATION_MARK:{this._err(V.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=y.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case x.APOSTROPHE:{this._err(V.missingWhitespaceAfterDoctypePublicKeyword),n.publicId="",this.state=y.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case x.GREATER_THAN_SIGN:{this._err(V.missingDoctypePublicIdentifier),n.forceQuirks=!0,this.state=y.DATA,this.emitCurrentDoctype(n);break}case x.EOF:{this._err(V.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(V.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=!0,this.state=y.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypePublicIdentifier(t){const n=this.currentToken;switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:break;case x.QUOTATION_MARK:{n.publicId="",this.state=y.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED;break}case x.APOSTROPHE:{n.publicId="",this.state=y.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED;break}case x.GREATER_THAN_SIGN:{this._err(V.missingDoctypePublicIdentifier),n.forceQuirks=!0,this.state=y.DATA,this.emitCurrentDoctype(n);break}case x.EOF:{this._err(V.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(V.missingQuoteBeforeDoctypePublicIdentifier),n.forceQuirks=!0,this.state=y.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypePublicIdentifierDoubleQuoted(t){const n=this.currentToken;switch(t){case x.QUOTATION_MARK:{this.state=y.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case x.NULL:{this._err(V.unexpectedNullCharacter),n.publicId+=gt;break}case x.GREATER_THAN_SIGN:{this._err(V.abruptDoctypePublicIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=y.DATA;break}case x.EOF:{this._err(V.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 x.APOSTROPHE:{this.state=y.AFTER_DOCTYPE_PUBLIC_IDENTIFIER;break}case x.NULL:{this._err(V.unexpectedNullCharacter),n.publicId+=gt;break}case x.GREATER_THAN_SIGN:{this._err(V.abruptDoctypePublicIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=y.DATA;break}case x.EOF:{this._err(V.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 x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:{this.state=y.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS;break}case x.GREATER_THAN_SIGN:{this.state=y.DATA,this.emitCurrentDoctype(n);break}case x.QUOTATION_MARK:{this._err(V.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=y.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case x.APOSTROPHE:{this._err(V.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers),n.systemId="",this.state=y.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case x.EOF:{this._err(V.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(V.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=y.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBetweenDoctypePublicAndSystemIdentifiers(t){const n=this.currentToken;switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:break;case x.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=y.DATA;break}case x.QUOTATION_MARK:{n.systemId="",this.state=y.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case x.APOSTROPHE:{n.systemId="",this.state=y.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case x.EOF:{this._err(V.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(V.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=y.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateAfterDoctypeSystemKeyword(t){const n=this.currentToken;switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:{this.state=y.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER;break}case x.QUOTATION_MARK:{this._err(V.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=y.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case x.APOSTROPHE:{this._err(V.missingWhitespaceAfterDoctypeSystemKeyword),n.systemId="",this.state=y.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case x.GREATER_THAN_SIGN:{this._err(V.missingDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=y.DATA,this.emitCurrentDoctype(n);break}case x.EOF:{this._err(V.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(V.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=y.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBeforeDoctypeSystemIdentifier(t){const n=this.currentToken;switch(t){case x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:break;case x.QUOTATION_MARK:{n.systemId="",this.state=y.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED;break}case x.APOSTROPHE:{n.systemId="",this.state=y.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED;break}case x.GREATER_THAN_SIGN:{this._err(V.missingDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=y.DATA,this.emitCurrentDoctype(n);break}case x.EOF:{this._err(V.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(V.missingQuoteBeforeDoctypeSystemIdentifier),n.forceQuirks=!0,this.state=y.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateDoctypeSystemIdentifierDoubleQuoted(t){const n=this.currentToken;switch(t){case x.QUOTATION_MARK:{this.state=y.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case x.NULL:{this._err(V.unexpectedNullCharacter),n.systemId+=gt;break}case x.GREATER_THAN_SIGN:{this._err(V.abruptDoctypeSystemIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=y.DATA;break}case x.EOF:{this._err(V.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 x.APOSTROPHE:{this.state=y.AFTER_DOCTYPE_SYSTEM_IDENTIFIER;break}case x.NULL:{this._err(V.unexpectedNullCharacter),n.systemId+=gt;break}case x.GREATER_THAN_SIGN:{this._err(V.abruptDoctypeSystemIdentifier),n.forceQuirks=!0,this.emitCurrentDoctype(n),this.state=y.DATA;break}case x.EOF:{this._err(V.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 x.SPACE:case x.LINE_FEED:case x.TABULATION:case x.FORM_FEED:break;case x.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=y.DATA;break}case x.EOF:{this._err(V.eofInDoctype),n.forceQuirks=!0,this.emitCurrentDoctype(n),this._emitEOFToken();break}default:this._err(V.unexpectedCharacterAfterDoctypeSystemIdentifier),this.state=y.BOGUS_DOCTYPE,this._stateBogusDoctype(t)}}_stateBogusDoctype(t){const n=this.currentToken;switch(t){case x.GREATER_THAN_SIGN:{this.emitCurrentDoctype(n),this.state=y.DATA;break}case x.NULL:{this._err(V.unexpectedNullCharacter);break}case x.EOF:{this.emitCurrentDoctype(n),this._emitEOFToken();break}}}_stateCdataSection(t){switch(t){case x.RIGHT_SQUARE_BRACKET:{this.state=y.CDATA_SECTION_BRACKET;break}case x.EOF:{this._err(V.eofInCdata),this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateCdataSectionBracket(t){t===x.RIGHT_SQUARE_BRACKET?this.state=y.CDATA_SECTION_END:(this._emitChars("]"),this.state=y.CDATA_SECTION,this._stateCdataSection(t))}_stateCdataSectionEnd(t){switch(t){case x.GREATER_THAN_SIGN:{this.state=y.DATA;break}case x.RIGHT_SQUARE_BRACKET:{this._emitChars("]");break}default:this._emitChars("]]"),this.state=y.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(x.AMPERSAND),this.state=!this._isCharacterReferenceInAttribute()&&ho(this.preprocessor.peek(1))?y.AMBIGUOUS_AMPERSAND:this.returnState):this.state=this.returnState}_stateAmbiguousAmpersand(t){ho(t)?this._flushCodePointConsumedAsCharacterReference(t):(t===x.SEMICOLON&&this._err(V.unknownNamedCharacterReference),this.state=this.returnState,this._callState(t))}}const xc=new Set([i.DD,i.DT,i.LI,i.OPTGROUP,i.OPTION,i.P,i.RB,i.RP,i.RT,i.RTC]),go=new Set([...xc,i.CAPTION,i.COLGROUP,i.TBODY,i.TD,i.TFOOT,i.TH,i.THEAD,i.TR]),ya=new Set([i.APPLET,i.CAPTION,i.HTML,i.MARQUEE,i.OBJECT,i.TABLE,i.TD,i.TEMPLATE,i.TH]),qh=new Set([...ya,i.OL,i.UL]),Wh=new Set([...ya,i.BUTTON]),bo=new Set([i.ANNOTATION_XML,i.MI,i.MN,i.MO,i.MS,i.MTEXT]),xo=new Set([i.DESC,i.FOREIGN_OBJECT,i.TITLE]),Kh=new Set([i.TR,i.TEMPLATE,i.HTML]),Gh=new Set([i.TBODY,i.TFOOT,i.THEAD,i.TEMPLATE,i.HTML]),Yh=new Set([i.TABLE,i.TEMPLATE,i.HTML]),zh=new Set([i.TD,i.TH]);class Vh{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,n,r){this.treeAdapter=n,this.handler=r,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=i.UNKNOWN,this.current=t}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===i.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===me.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 r=this._indexOf(t);this.items[r]=n,r===this.stackTop&&(this.current=n)}insertAfter(t,n,r){const a=this._indexOf(t)+1;this.items.splice(a,0,n),this.tagIDs.splice(a,0,r),this.stackTop++,a===this.stackTop&&this._updateCurrentElement(),this.current&&this.currentTagId!==void 0&&this.handler.onItemPush(this.current,this.currentTagId,a===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])!==me.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 r=this._indexOfTagNames(t,n);this.shortenToLength(Math.max(r,0))}popUntilNumberedHeaderPopped(){this.popUntilPopped(jr,me.HTML)}popUntilTableCellPopped(){this.popUntilPopped(zh,me.HTML)}popAllUpToHtmlElement(){this.tmplCount=0,this.shortenToLength(1)}_indexOfTagNames(t,n){for(let r=this.stackTop;r>=0;r--)if(t.has(this.tagIDs[r])&&this.treeAdapter.getNamespaceURI(this.items[r])===n)return r;return-1}clearBackTo(t,n){const r=this._indexOfTagNames(t,n);this.shortenToLength(r+1)}clearBackToTableContext(){this.clearBackTo(Yh,me.HTML)}clearBackToTableBodyContext(){this.clearBackTo(Gh,me.HTML)}clearBackToTableRowContext(){this.clearBackTo(Kh,me.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]===i.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]===i.HTML}hasInDynamicScope(t,n){for(let r=this.stackTop;r>=0;r--){const a=this.tagIDs[r];switch(this.treeAdapter.getNamespaceURI(this.items[r])){case me.HTML:{if(a===t)return!0;if(n.has(a))return!1;break}case me.SVG:{if(xo.has(a))return!1;break}case me.MATHML:{if(bo.has(a))return!1;break}}}return!0}hasInScope(t){return this.hasInDynamicScope(t,ya)}hasInListItemScope(t){return this.hasInDynamicScope(t,qh)}hasInButtonScope(t){return this.hasInDynamicScope(t,Wh)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){const n=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case me.HTML:{if(jr.has(n))return!0;if(ya.has(n))return!1;break}case me.SVG:{if(xo.has(n))return!1;break}case me.MATHML:{if(bo.has(n))return!1;break}}}return!0}hasInTableScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===me.HTML)switch(this.tagIDs[n]){case t:return!0;case i.TABLE:case i.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===me.HTML)switch(this.tagIDs[t]){case i.TBODY:case i.THEAD:case i.TFOOT:return!0;case i.TABLE:case i.HTML:return!1}return!0}hasInSelectScope(t){for(let n=this.stackTop;n>=0;n--)if(this.treeAdapter.getNamespaceURI(this.items[n])===me.HTML)switch(this.tagIDs[n]){case t:return!0;case i.OPTION:case i.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;this.currentTagId!==void 0&&xc.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;this.currentTagId!==void 0&&go.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==void 0&&this.currentTagId!==t&&go.has(this.currentTagId);)this.pop()}}const Va=3;var rs;(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element"})(rs||(rs={}));const Eo={type:rs.Marker};class Qh{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(t,n){const r=[],a=n.length,c=this.treeAdapter.getTagName(t),l=this.treeAdapter.getNamespaceURI(t);for(let u=0;u<this.entries.length;u++){const d=this.entries[u];if(d.type===rs.Marker)break;const{element:m}=d;if(this.treeAdapter.getTagName(m)===c&&this.treeAdapter.getNamespaceURI(m)===l){const f=this.treeAdapter.getAttrList(m);f.length===a&&r.push({idx:u,attrs:f})}}return r}_ensureNoahArkCondition(t){if(this.entries.length<Va)return;const n=this.treeAdapter.getAttrList(t),r=this._getNoahArkConditionCandidates(t,n);if(r.length<Va)return;const a=new Map(n.map(l=>[l.name,l.value]));let c=0;for(let l=0;l<r.length;l++){const u=r[l];u.attrs.every(d=>a.get(d.name)===d.value)&&(c+=1,c>=Va&&this.entries.splice(u.idx,1))}}insertMarker(){this.entries.unshift(Eo)}pushElement(t,n){this._ensureNoahArkCondition(t),this.entries.unshift({type:rs.Element,element:t,token:n})}insertElementAfterBookmark(t,n){const r=this.entries.indexOf(this.bookmark);this.entries.splice(r,0,{type:rs.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(Eo);t===-1?this.entries.length=0:this.entries.splice(0,t+1)}getElementEntryInScopeWithTagName(t){const n=this.entries.find(r=>r.type===rs.Marker||this.treeAdapter.getTagName(r.element)===t);return n&&n.type===rs.Element?n:null}getElementEntry(t){return this.entries.find(n=>n.type===rs.Element&&n.element===t)}}const Es={createDocument(){return{nodeName:"#document",mode:Gt.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 r=e.childNodes.indexOf(n);e.childNodes.splice(r,0,t),t.parentNode=e},setTemplateContent(e,t){e.content=t},getTemplateContent(e){return e.content},setDocumentType(e,t,n,r){const a=e.childNodes.find(c=>c.nodeName==="#documentType");if(a)a.name=t,a.publicId=n,a.systemId=r;else{const c={nodeName:"#documentType",name:t,publicId:n,systemId:r,parentNode:null};Es.appendChild(e,c)}},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(Es.isTextNode(n)){n.value+=t;return}}Es.appendChild(e,Es.createTextNode(t))},insertTextBefore(e,t,n){const r=e.childNodes[e.childNodes.indexOf(n)-1];r&&Es.isTextNode(r)?r.value+=t:Es.insertBefore(e,Es.createTextNode(t),n)},adoptAttributes(e,t){const n=new Set(e.attrs.map(r=>r.name));for(let r=0;r<t.length;r++)n.has(t[r].name)||e.attrs.push(t[r])},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}}},Ec="html",Xh="about:legacy-compat",Jh="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",yc=["+//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//"],Zh=[...yc,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],ef=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),Tc=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],tf=[...Tc,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"];function yo(e,t){return t.some(n=>e.startsWith(n))}function sf(e){return e.name===Ec&&e.publicId===null&&(e.systemId===null||e.systemId===Xh)}function nf(e){if(e.name!==Ec)return Gt.QUIRKS;const{systemId:t}=e;if(t&&t.toLowerCase()===Jh)return Gt.QUIRKS;let{publicId:n}=e;if(n!==null){if(n=n.toLowerCase(),ef.has(n))return Gt.QUIRKS;let r=t===null?Zh:yc;if(yo(n,r))return Gt.QUIRKS;if(r=t===null?Tc:tf,yo(n,r))return Gt.LIMITED_QUIRKS}return Gt.NO_QUIRKS}const To={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},af="definitionurl",rf="definitionURL",of=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])),lf=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:me.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:me.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:me.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:me.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:me.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:me.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:me.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:me.XML}],["xml:space",{prefix:"xml",name:"space",namespace:me.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:me.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:me.XMLNS}]]),cf=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])),uf=new Set([i.B,i.BIG,i.BLOCKQUOTE,i.BODY,i.BR,i.CENTER,i.CODE,i.DD,i.DIV,i.DL,i.DT,i.EM,i.EMBED,i.H1,i.H2,i.H3,i.H4,i.H5,i.H6,i.HEAD,i.HR,i.I,i.IMG,i.LI,i.LISTING,i.MENU,i.META,i.NOBR,i.OL,i.P,i.PRE,i.RUBY,i.S,i.SMALL,i.SPAN,i.STRONG,i.STRIKE,i.SUB,i.SUP,i.TABLE,i.TT,i.U,i.UL,i.VAR]);function df(e){const t=e.tagID;return t===i.FONT&&e.attrs.some(({name:r})=>r===Ps.COLOR||r===Ps.SIZE||r===Ps.FACE)||uf.has(t)}function kc(e){for(let t=0;t<e.attrs.length;t++)if(e.attrs[t].name===af){e.attrs[t].name=rf;break}}function Nc(e){for(let t=0;t<e.attrs.length;t++){const n=of.get(e.attrs[t].name);n!=null&&(e.attrs[t].name=n)}}function Zr(e){for(let t=0;t<e.attrs.length;t++){const n=lf.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 pf(e){const t=cf.get(e.tagName);t!=null&&(e.tagName=t,e.tagID=Js(e.tagName))}function mf(e,t){return t===me.MATHML&&(e===i.MI||e===i.MO||e===i.MN||e===i.MS||e===i.MTEXT)}function hf(e,t,n){if(t===me.MATHML&&e===i.ANNOTATION_XML){for(let r=0;r<n.length;r++)if(n[r].name===Ps.ENCODING){const a=n[r].value.toLowerCase();return a===To.TEXT_HTML||a===To.APPLICATION_XML}}return t===me.SVG&&(e===i.FOREIGN_OBJECT||e===i.DESC||e===i.TITLE)}function ff(e,t,n,r){return(!r||r===me.HTML)&&hf(e,t,n)||(!r||r===me.MATHML)&&mf(e,t)}const gf="hidden",bf=8,xf=3;var S;(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"})(S||(S={}));const Ef={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},vc=new Set([i.TABLE,i.TBODY,i.TFOOT,i.THEAD,i.TR]),ko={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:Es,onParseError:null};class No{constructor(t,n,r=null,a=null){this.fragmentContext=r,this.scriptHandler=a,this.currentToken=null,this.stopped=!1,this.insertionMode=S.INITIAL,this.originalInsertionMode=S.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={...ko,...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 $h(this.options,this),this.activeFormattingElements=new Qh(this.treeAdapter),this.fragmentContextID=r?Js(this.treeAdapter.getTagName(r)):i.UNKNOWN,this._setContextModes(r??this.document,this.fragmentContextID),this.openElements=new Vh(this.document,this.treeAdapter,this)}static parse(t,n){const r=new this(n);return r.tokenizer.write(t,!0),r.document}static getFragmentParser(t,n){const r={...ko,...n};t??(t=r.treeAdapter.createElement(H.TEMPLATE,me.HTML,[]));const a=r.treeAdapter.createElement("documentmock",me.HTML,[]),c=new this(r,a,t);return c.fragmentContextID===i.TEMPLATE&&c.tmplInsertionModeStack.unshift(S.IN_TEMPLATE),c._initTokenizerForFragmentParsing(),c._insertFakeRootElement(),c._resetInsertionMode(),c._findFormInFragmentContext(),c}getFragment(){const t=this.treeAdapter.getFirstChild(this.document),n=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,n),n}_err(t,n,r){var a;if(!this.onParseError)return;const c=(a=t.location)!==null&&a!==void 0?a:Ef,l={code:n,startLine:c.startLine,startCol:c.startCol,startOffset:c.startOffset,endLine:r?c.startLine:c.endLine,endCol:r?c.startCol:c.endCol,endOffset:r?c.startOffset:c.endOffset};this.onParseError(l)}onItemPush(t,n,r){var a,c;(c=(a=this.treeAdapter).onItemPush)===null||c===void 0||c.call(a,t),r&&this.openElements.stackTop>0&&this._setContextModes(t,n)}onItemPop(t,n){var r,a;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(a=(r=this.treeAdapter).onItemPop)===null||a===void 0||a.call(r,t,this.openElements.current),n){let c,l;this.openElements.stackTop===0&&this.fragmentContext?(c=this.fragmentContext,l=this.fragmentContextID):{current:c,currentTagId:l}=this.openElements,this._setContextModes(c,l)}}_setContextModes(t,n){const r=t===this.document||t&&this.treeAdapter.getNamespaceURI(t)===me.HTML;this.currentNotInHTML=!r,this.tokenizer.inForeignNode=!r&&t!==void 0&&n!==void 0&&!this._isIntegrationPoint(n,t)}_switchToTextParsing(t,n){this._insertElement(t,me.HTML),this.tokenizer.state=n,this.originalInsertionMode=this.insertionMode,this.insertionMode=S.TEXT}switchToPlaintextParsing(){this.insertionMode=S.TEXT,this.originalInsertionMode=S.IN_BODY,this.tokenizer.state=Tt.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)===H.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t)}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==me.HTML))switch(this.fragmentContextID){case i.TITLE:case i.TEXTAREA:{this.tokenizer.state=Tt.RCDATA;break}case i.STYLE:case i.XMP:case i.IFRAME:case i.NOEMBED:case i.NOFRAMES:case i.NOSCRIPT:{this.tokenizer.state=Tt.RAWTEXT;break}case i.SCRIPT:{this.tokenizer.state=Tt.SCRIPT_DATA;break}case i.PLAINTEXT:{this.tokenizer.state=Tt.PLAINTEXT;break}}}_setDocumentType(t){const n=t.name||"",r=t.publicId||"",a=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,n,r,a),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 r=n&&{...n,startTag:n};this.treeAdapter.setNodeSourceCodeLocation(t,r)}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else{const r=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(r??this.document,t)}}_appendElement(t,n){const r=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(r,t.location)}_insertElement(t,n){const r=this.treeAdapter.createElement(t.tagName,n,t.attrs);this._attachElementToTree(r,t.location),this.openElements.push(r,t.tagID)}_insertFakeElement(t,n){const r=this.treeAdapter.createElement(t,me.HTML,[]);this._attachElementToTree(r,null),this.openElements.push(r,n)}_insertTemplate(t){const n=this.treeAdapter.createElement(t.tagName,me.HTML,t.attrs),r=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(n,r),this._attachElementToTree(n,t.location),this.openElements.push(n,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(r,null)}_insertFakeRootElement(){const t=this.treeAdapter.createElement(H.HTML,me.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,i.HTML)}_appendCommentNode(t,n){const r=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(n,r),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(r,t.location)}_insertCharacters(t){let n,r;if(this._shouldFosterParentOnInsertion()?({parent:n,beforeElement:r}=this._findFosterParentingLocation(),r?this.treeAdapter.insertTextBefore(n,t.chars,r):this.treeAdapter.insertText(n,t.chars)):(n=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(n,t.chars)),!t.location)return;const a=this.treeAdapter.getChildNodes(n),c=r?a.lastIndexOf(r):a.length,l=a[c-1];if(this.treeAdapter.getNodeSourceCodeLocation(l)){const{endLine:d,endCol:m,endOffset:f}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(l,{endLine:d,endCol:m,endOffset:f})}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(l,t.location)}_adoptNodes(t,n){for(let r=this.treeAdapter.getFirstChild(t);r;r=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(r),this.treeAdapter.appendChild(n,r)}_setEndLocation(t,n){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&n.location){const r=n.location,a=this.treeAdapter.getTagName(t),c=n.type===Ze.END_TAG&&a===n.tagName?{endTag:{...r},endLine:r.endLine,endCol:r.endCol,endOffset:r.endOffset}:{endLine:r.startLine,endCol:r.startCol,endOffset:r.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,c)}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return!1;let n,r;return this.openElements.stackTop===0&&this.fragmentContext?(n=this.fragmentContext,r=this.fragmentContextID):{current:n,currentTagId:r}=this.openElements,t.tagID===i.SVG&&this.treeAdapter.getTagName(n)===H.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(n)===me.MATHML?!1:this.tokenizer.inForeignNode||(t.tagID===i.MGLYPH||t.tagID===i.MALIGNMARK)&&r!==void 0&&!this._isIntegrationPoint(r,n,me.HTML)}_processToken(t){switch(t.type){case Ze.CHARACTER:{this.onCharacter(t);break}case Ze.NULL_CHARACTER:{this.onNullCharacter(t);break}case Ze.COMMENT:{this.onComment(t);break}case Ze.DOCTYPE:{this.onDoctype(t);break}case Ze.START_TAG:{this._processStartTag(t);break}case Ze.END_TAG:{this.onEndTag(t);break}case Ze.EOF:{this.onEof(t);break}case Ze.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,n,r){const a=this.treeAdapter.getNamespaceURI(n),c=this.treeAdapter.getAttrList(n);return ff(t,a,c,r)}_reconstructActiveFormattingElements(){const t=this.activeFormattingElements.entries.length;if(t){const n=this.activeFormattingElements.entries.findIndex(a=>a.type===rs.Marker||this.openElements.contains(a.element)),r=n===-1?t-1:n-1;for(let a=r;a>=0;a--){const c=this.activeFormattingElements.entries[a];this._insertElement(c.token,this.treeAdapter.getNamespaceURI(c.element)),c.element=this.openElements.current}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=S.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(i.P),this.openElements.popUntilTagNamePopped(i.P)}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case i.TR:{this.insertionMode=S.IN_ROW;return}case i.TBODY:case i.THEAD:case i.TFOOT:{this.insertionMode=S.IN_TABLE_BODY;return}case i.CAPTION:{this.insertionMode=S.IN_CAPTION;return}case i.COLGROUP:{this.insertionMode=S.IN_COLUMN_GROUP;return}case i.TABLE:{this.insertionMode=S.IN_TABLE;return}case i.BODY:{this.insertionMode=S.IN_BODY;return}case i.FRAMESET:{this.insertionMode=S.IN_FRAMESET;return}case i.SELECT:{this._resetInsertionModeForSelect(t);return}case i.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case i.HTML:{this.insertionMode=this.headElement?S.AFTER_HEAD:S.BEFORE_HEAD;return}case i.TD:case i.TH:{if(t>0){this.insertionMode=S.IN_CELL;return}break}case i.HEAD:{if(t>0){this.insertionMode=S.IN_HEAD;return}break}}this.insertionMode=S.IN_BODY}_resetInsertionModeForSelect(t){if(t>0)for(let n=t-1;n>0;n--){const r=this.openElements.tagIDs[n];if(r===i.TEMPLATE)break;if(r===i.TABLE){this.insertionMode=S.IN_SELECT_IN_TABLE;return}}this.insertionMode=S.IN_SELECT}_isElementCausesFosterParenting(t){return vc.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 i.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(n)===me.HTML)return{parent:this.treeAdapter.getTemplateContent(n),beforeElement:null};break}case i.TABLE:{const r=this.treeAdapter.getParentNode(n);return r?{parent:r,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 r=this.treeAdapter.getNamespaceURI(t);return Bh[r].has(n)}onCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){Vg(this,t);return}switch(this.insertionMode){case S.INITIAL:{nn(this,t);break}case S.BEFORE_HTML:{xn(this,t);break}case S.BEFORE_HEAD:{En(this,t);break}case S.IN_HEAD:{yn(this,t);break}case S.IN_HEAD_NO_SCRIPT:{Tn(this,t);break}case S.AFTER_HEAD:{kn(this,t);break}case S.IN_BODY:case S.IN_CAPTION:case S.IN_CELL:case S.IN_TEMPLATE:{wc(this,t);break}case S.TEXT:case S.IN_SELECT:case S.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case S.IN_TABLE:case S.IN_TABLE_BODY:case S.IN_ROW:{Qa(this,t);break}case S.IN_TABLE_TEXT:{Rc(this,t);break}case S.IN_COLUMN_GROUP:{Ta(this,t);break}case S.AFTER_BODY:{ka(this,t);break}case S.AFTER_AFTER_BODY:{ta(this,t);break}}}onNullCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){zg(this,t);return}switch(this.insertionMode){case S.INITIAL:{nn(this,t);break}case S.BEFORE_HTML:{xn(this,t);break}case S.BEFORE_HEAD:{En(this,t);break}case S.IN_HEAD:{yn(this,t);break}case S.IN_HEAD_NO_SCRIPT:{Tn(this,t);break}case S.AFTER_HEAD:{kn(this,t);break}case S.TEXT:{this._insertCharacters(t);break}case S.IN_TABLE:case S.IN_TABLE_BODY:case S.IN_ROW:{Qa(this,t);break}case S.IN_COLUMN_GROUP:{Ta(this,t);break}case S.AFTER_BODY:{ka(this,t);break}case S.AFTER_AFTER_BODY:{ta(this,t);break}}}onComment(t){if(this.skipNextNewLine=!1,this.currentNotInHTML){Ir(this,t);return}switch(this.insertionMode){case S.INITIAL:case S.BEFORE_HTML:case S.BEFORE_HEAD:case S.IN_HEAD:case S.IN_HEAD_NO_SCRIPT:case S.AFTER_HEAD:case S.IN_BODY:case S.IN_TABLE:case S.IN_CAPTION:case S.IN_COLUMN_GROUP:case S.IN_TABLE_BODY:case S.IN_ROW:case S.IN_CELL:case S.IN_SELECT:case S.IN_SELECT_IN_TABLE:case S.IN_TEMPLATE:case S.IN_FRAMESET:case S.AFTER_FRAMESET:{Ir(this,t);break}case S.IN_TABLE_TEXT:{an(this,t);break}case S.AFTER_BODY:{wf(this,t);break}case S.AFTER_AFTER_BODY:case S.AFTER_AFTER_FRAMESET:{Sf(this,t);break}}}onDoctype(t){switch(this.skipNextNewLine=!1,this.insertionMode){case S.INITIAL:{_f(this,t);break}case S.BEFORE_HEAD:case S.IN_HEAD:case S.IN_HEAD_NO_SCRIPT:case S.AFTER_HEAD:{this._err(t,V.misplacedDoctype);break}case S.IN_TABLE_TEXT:{an(this,t);break}}}onStartTag(t){this.skipNextNewLine=!1,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,V.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?Qg(this,t):this._startTagOutsideForeignContent(t)}_startTagOutsideForeignContent(t){switch(this.insertionMode){case S.INITIAL:{nn(this,t);break}case S.BEFORE_HTML:{Af(this,t);break}case S.BEFORE_HEAD:{If(this,t);break}case S.IN_HEAD:{ns(this,t);break}case S.IN_HEAD_NO_SCRIPT:{Lf(this,t);break}case S.AFTER_HEAD:{Of(this,t);break}case S.IN_BODY:{Pt(this,t);break}case S.IN_TABLE:{Vs(this,t);break}case S.IN_TABLE_TEXT:{an(this,t);break}case S.IN_CAPTION:{Rg(this,t);break}case S.IN_COLUMN_GROUP:{si(this,t);break}case S.IN_TABLE_BODY:{Oa(this,t);break}case S.IN_ROW:{Ma(this,t);break}case S.IN_CELL:{Dg(this,t);break}case S.IN_SELECT:{Dc(this,t);break}case S.IN_SELECT_IN_TABLE:{Mg(this,t);break}case S.IN_TEMPLATE:{Fg(this,t);break}case S.AFTER_BODY:{Ug(this,t);break}case S.IN_FRAMESET:{$g(this,t);break}case S.AFTER_FRAMESET:{Wg(this,t);break}case S.AFTER_AFTER_BODY:{Gg(this,t);break}case S.AFTER_AFTER_FRAMESET:{Yg(this,t);break}}}onEndTag(t){this.skipNextNewLine=!1,this.currentToken=t,this.currentNotInHTML?Xg(this,t):this._endTagOutsideForeignContent(t)}_endTagOutsideForeignContent(t){switch(this.insertionMode){case S.INITIAL:{nn(this,t);break}case S.BEFORE_HTML:{jf(this,t);break}case S.BEFORE_HEAD:{Rf(this,t);break}case S.IN_HEAD:{Pf(this,t);break}case S.IN_HEAD_NO_SCRIPT:{Df(this,t);break}case S.AFTER_HEAD:{Mf(this,t);break}case S.IN_BODY:{Da(this,t);break}case S.TEXT:{kg(this,t);break}case S.IN_TABLE:{An(this,t);break}case S.IN_TABLE_TEXT:{an(this,t);break}case S.IN_CAPTION:{Pg(this,t);break}case S.IN_COLUMN_GROUP:{Lg(this,t);break}case S.IN_TABLE_BODY:{Rr(this,t);break}case S.IN_ROW:{Lc(this,t);break}case S.IN_CELL:{Og(this,t);break}case S.IN_SELECT:{Oc(this,t);break}case S.IN_SELECT_IN_TABLE:{Bg(this,t);break}case S.IN_TEMPLATE:{Hg(this,t);break}case S.AFTER_BODY:{Bc(this,t);break}case S.IN_FRAMESET:{qg(this,t);break}case S.AFTER_FRAMESET:{Kg(this,t);break}case S.AFTER_AFTER_BODY:{ta(this,t);break}}}onEof(t){switch(this.insertionMode){case S.INITIAL:{nn(this,t);break}case S.BEFORE_HTML:{xn(this,t);break}case S.BEFORE_HEAD:{En(this,t);break}case S.IN_HEAD:{yn(this,t);break}case S.IN_HEAD_NO_SCRIPT:{Tn(this,t);break}case S.AFTER_HEAD:{kn(this,t);break}case S.IN_BODY:case S.IN_TABLE:case S.IN_CAPTION:case S.IN_COLUMN_GROUP:case S.IN_TABLE_BODY:case S.IN_ROW:case S.IN_CELL:case S.IN_SELECT:case S.IN_SELECT_IN_TABLE:{jc(this,t);break}case S.TEXT:{Ng(this,t);break}case S.IN_TABLE_TEXT:{an(this,t);break}case S.IN_TEMPLATE:{Mc(this,t);break}case S.AFTER_BODY:case S.IN_FRAMESET:case S.AFTER_FRAMESET:case S.AFTER_AFTER_BODY:case S.AFTER_AFTER_FRAMESET:{ti(this,t);break}}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=!1,t.chars.charCodeAt(0)===x.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 S.IN_HEAD:case S.IN_HEAD_NO_SCRIPT:case S.AFTER_HEAD:case S.TEXT:case S.IN_COLUMN_GROUP:case S.IN_SELECT:case S.IN_SELECT_IN_TABLE:case S.IN_FRAMESET:case S.AFTER_FRAMESET:{this._insertCharacters(t);break}case S.IN_BODY:case S.IN_CAPTION:case S.IN_CELL:case S.IN_TEMPLATE:case S.AFTER_BODY:case S.AFTER_AFTER_BODY:case S.AFTER_AFTER_FRAMESET:{Cc(this,t);break}case S.IN_TABLE:case S.IN_TABLE_BODY:case S.IN_ROW:{Qa(this,t);break}case S.IN_TABLE_TEXT:{Ic(this,t);break}}}}function yf(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):Ac(e,t),n}function Tf(e,t){let n=null,r=e.openElements.stackTop;for(;r>=0;r--){const a=e.openElements.items[r];if(a===t.element)break;e._isSpecialElement(a,e.openElements.tagIDs[r])&&(n=a)}return n||(e.openElements.shortenToLength(Math.max(r,0)),e.activeFormattingElements.removeEntry(t)),n}function kf(e,t,n){let r=t,a=e.openElements.getCommonAncestor(t);for(let c=0,l=a;l!==n;c++,l=a){a=e.openElements.getCommonAncestor(l);const u=e.activeFormattingElements.getElementEntry(l),d=u&&c>=xf;!u||d?(d&&e.activeFormattingElements.removeEntry(u),e.openElements.remove(l)):(l=Nf(e,u),r===t&&(e.activeFormattingElements.bookmark=u),e.treeAdapter.detachNode(r),e.treeAdapter.appendChild(l,r),r=l)}return r}function Nf(e,t){const n=e.treeAdapter.getNamespaceURI(t.element),r=e.treeAdapter.createElement(t.token.tagName,n,t.token.attrs);return e.openElements.replace(t.element,r),t.element=r,r}function vf(e,t,n){const r=e.treeAdapter.getTagName(t),a=Js(r);if(e._isElementCausesFosterParenting(a))e._fosterParentElement(n);else{const c=e.treeAdapter.getNamespaceURI(t);a===i.TEMPLATE&&c===me.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,n)}}function Cf(e,t,n){const r=e.treeAdapter.getNamespaceURI(n.element),{token:a}=n,c=e.treeAdapter.createElement(a.tagName,r,a.attrs);e._adoptNodes(t,c),e.treeAdapter.appendChild(t,c),e.activeFormattingElements.insertElementAfterBookmark(c,a),e.activeFormattingElements.removeEntry(n),e.openElements.remove(n.element),e.openElements.insertAfter(t,c,a.tagID)}function ei(e,t){for(let n=0;n<bf;n++){const r=yf(e,t);if(!r)break;const a=Tf(e,r);if(!a)break;e.activeFormattingElements.bookmark=r;const c=kf(e,a,r.element),l=e.openElements.getCommonAncestor(r.element);e.treeAdapter.detachNode(c),l&&vf(e,l,c),Cf(e,a,r)}}function Ir(e,t){e._appendCommentNode(t,e.openElements.currentTmplContentOrNode)}function wf(e,t){e._appendCommentNode(t,e.openElements.items[0])}function Sf(e,t){e._appendCommentNode(t,e.document)}function ti(e,t){if(e.stopped=!0,t.location){const n=e.fragmentContext?0:2;for(let r=e.openElements.stackTop;r>=n;r--)e._setEndLocation(e.openElements.items[r],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){const r=e.openElements.items[0],a=e.treeAdapter.getNodeSourceCodeLocation(r);if(a&&!a.endTag&&(e._setEndLocation(r,t),e.openElements.stackTop>=1)){const c=e.openElements.items[1],l=e.treeAdapter.getNodeSourceCodeLocation(c);l&&!l.endTag&&e._setEndLocation(c,t)}}}}function _f(e,t){e._setDocumentType(t);const n=t.forceQuirks?Gt.QUIRKS:nf(t);sf(t)||e._err(t,V.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,n),e.insertionMode=S.BEFORE_HTML}function nn(e,t){e._err(t,V.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,Gt.QUIRKS),e.insertionMode=S.BEFORE_HTML,e._processToken(t)}function Af(e,t){t.tagID===i.HTML?(e._insertElement(t,me.HTML),e.insertionMode=S.BEFORE_HEAD):xn(e,t)}function jf(e,t){const n=t.tagID;(n===i.HTML||n===i.HEAD||n===i.BODY||n===i.BR)&&xn(e,t)}function xn(e,t){e._insertFakeRootElement(),e.insertionMode=S.BEFORE_HEAD,e._processToken(t)}function If(e,t){switch(t.tagID){case i.HTML:{Pt(e,t);break}case i.HEAD:{e._insertElement(t,me.HTML),e.headElement=e.openElements.current,e.insertionMode=S.IN_HEAD;break}default:En(e,t)}}function Rf(e,t){const n=t.tagID;n===i.HEAD||n===i.BODY||n===i.HTML||n===i.BR?En(e,t):e._err(t,V.endTagWithoutMatchingOpenElement)}function En(e,t){e._insertFakeElement(H.HEAD,i.HEAD),e.headElement=e.openElements.current,e.insertionMode=S.IN_HEAD,e._processToken(t)}function ns(e,t){switch(t.tagID){case i.HTML:{Pt(e,t);break}case i.BASE:case i.BASEFONT:case i.BGSOUND:case i.LINK:case i.META:{e._appendElement(t,me.HTML),t.ackSelfClosing=!0;break}case i.TITLE:{e._switchToTextParsing(t,Tt.RCDATA);break}case i.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,Tt.RAWTEXT):(e._insertElement(t,me.HTML),e.insertionMode=S.IN_HEAD_NO_SCRIPT);break}case i.NOFRAMES:case i.STYLE:{e._switchToTextParsing(t,Tt.RAWTEXT);break}case i.SCRIPT:{e._switchToTextParsing(t,Tt.SCRIPT_DATA);break}case i.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=!1,e.insertionMode=S.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(S.IN_TEMPLATE);break}case i.HEAD:{e._err(t,V.misplacedStartTagForHeadElement);break}default:yn(e,t)}}function Pf(e,t){switch(t.tagID){case i.HEAD:{e.openElements.pop(),e.insertionMode=S.AFTER_HEAD;break}case i.BODY:case i.BR:case i.HTML:{yn(e,t);break}case i.TEMPLATE:{Ms(e,t);break}default:e._err(t,V.endTagWithoutMatchingOpenElement)}}function Ms(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==i.TEMPLATE&&e._err(t,V.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(i.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,V.endTagWithoutMatchingOpenElement)}function yn(e,t){e.openElements.pop(),e.insertionMode=S.AFTER_HEAD,e._processToken(t)}function Lf(e,t){switch(t.tagID){case i.HTML:{Pt(e,t);break}case i.BASEFONT:case i.BGSOUND:case i.HEAD:case i.LINK:case i.META:case i.NOFRAMES:case i.STYLE:{ns(e,t);break}case i.NOSCRIPT:{e._err(t,V.nestedNoscriptInHead);break}default:Tn(e,t)}}function Df(e,t){switch(t.tagID){case i.NOSCRIPT:{e.openElements.pop(),e.insertionMode=S.IN_HEAD;break}case i.BR:{Tn(e,t);break}default:e._err(t,V.endTagWithoutMatchingOpenElement)}}function Tn(e,t){const n=t.type===Ze.EOF?V.openElementsLeftAfterEof:V.disallowedContentInNoscriptInHead;e._err(t,n),e.openElements.pop(),e.insertionMode=S.IN_HEAD,e._processToken(t)}function Of(e,t){switch(t.tagID){case i.HTML:{Pt(e,t);break}case i.BODY:{e._insertElement(t,me.HTML),e.framesetOk=!1,e.insertionMode=S.IN_BODY;break}case i.FRAMESET:{e._insertElement(t,me.HTML),e.insertionMode=S.IN_FRAMESET;break}case i.BASE:case i.BASEFONT:case i.BGSOUND:case i.LINK:case i.META:case i.NOFRAMES:case i.SCRIPT:case i.STYLE:case i.TEMPLATE:case i.TITLE:{e._err(t,V.abandonedHeadElementChild),e.openElements.push(e.headElement,i.HEAD),ns(e,t),e.openElements.remove(e.headElement);break}case i.HEAD:{e._err(t,V.misplacedStartTagForHeadElement);break}default:kn(e,t)}}function Mf(e,t){switch(t.tagID){case i.BODY:case i.HTML:case i.BR:{kn(e,t);break}case i.TEMPLATE:{Ms(e,t);break}default:e._err(t,V.endTagWithoutMatchingOpenElement)}}function kn(e,t){e._insertFakeElement(H.BODY,i.BODY),e.insertionMode=S.IN_BODY,La(e,t)}function La(e,t){switch(t.type){case Ze.CHARACTER:{wc(e,t);break}case Ze.WHITESPACE_CHARACTER:{Cc(e,t);break}case Ze.COMMENT:{Ir(e,t);break}case Ze.START_TAG:{Pt(e,t);break}case Ze.END_TAG:{Da(e,t);break}case Ze.EOF:{jc(e,t);break}}}function Cc(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function wc(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function Bf(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function Ff(e,t){const n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e.openElements.tmplCount===0&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(n,t.attrs))}function Hf(e,t){const n=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&n&&(e.treeAdapter.detachNode(n),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,me.HTML),e.insertionMode=S.IN_FRAMESET)}function Uf(e,t){e.openElements.hasInButtonScope(i.P)&&e._closePElement(),e._insertElement(t,me.HTML)}function $f(e,t){e.openElements.hasInButtonScope(i.P)&&e._closePElement(),e.openElements.currentTagId!==void 0&&jr.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,me.HTML)}function qf(e,t){e.openElements.hasInButtonScope(i.P)&&e._closePElement(),e._insertElement(t,me.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function Wf(e,t){const n=e.openElements.tmplCount>0;(!e.formElement||n)&&(e.openElements.hasInButtonScope(i.P)&&e._closePElement(),e._insertElement(t,me.HTML),n||(e.formElement=e.openElements.current))}function Kf(e,t){e.framesetOk=!1;const n=t.tagID;for(let r=e.openElements.stackTop;r>=0;r--){const a=e.openElements.tagIDs[r];if(n===i.LI&&a===i.LI||(n===i.DD||n===i.DT)&&(a===i.DD||a===i.DT)){e.openElements.generateImpliedEndTagsWithExclusion(a),e.openElements.popUntilTagNamePopped(a);break}if(a!==i.ADDRESS&&a!==i.DIV&&a!==i.P&&e._isSpecialElement(e.openElements.items[r],a))break}e.openElements.hasInButtonScope(i.P)&&e._closePElement(),e._insertElement(t,me.HTML)}function Gf(e,t){e.openElements.hasInButtonScope(i.P)&&e._closePElement(),e._insertElement(t,me.HTML),e.tokenizer.state=Tt.PLAINTEXT}function Yf(e,t){e.openElements.hasInScope(i.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(i.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.framesetOk=!1}function zf(e,t){const n=e.activeFormattingElements.getElementEntryInScopeWithTagName(H.A);n&&(ei(e,t),e.openElements.remove(n.element),e.activeFormattingElements.removeEntry(n)),e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function Vf(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function Qf(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(i.NOBR)&&(ei(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,me.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function Xf(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function Jf(e,t){e.treeAdapter.getDocumentMode(e.document)!==Gt.QUIRKS&&e.openElements.hasInButtonScope(i.P)&&e._closePElement(),e._insertElement(t,me.HTML),e.framesetOk=!1,e.insertionMode=S.IN_TABLE}function Sc(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,me.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function _c(e){const t=gc(e,Ps.TYPE);return t!=null&&t.toLowerCase()===gf}function Zf(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,me.HTML),_c(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function eg(e,t){e._appendElement(t,me.HTML),t.ackSelfClosing=!0}function tg(e,t){e.openElements.hasInButtonScope(i.P)&&e._closePElement(),e._appendElement(t,me.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function sg(e,t){t.tagName=H.IMG,t.tagID=i.IMG,Sc(e,t)}function ng(e,t){e._insertElement(t,me.HTML),e.skipNextNewLine=!0,e.tokenizer.state=Tt.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=!1,e.insertionMode=S.TEXT}function ag(e,t){e.openElements.hasInButtonScope(i.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,Tt.RAWTEXT)}function rg(e,t){e.framesetOk=!1,e._switchToTextParsing(t,Tt.RAWTEXT)}function vo(e,t){e._switchToTextParsing(t,Tt.RAWTEXT)}function ig(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML),e.framesetOk=!1,e.insertionMode=e.insertionMode===S.IN_TABLE||e.insertionMode===S.IN_CAPTION||e.insertionMode===S.IN_TABLE_BODY||e.insertionMode===S.IN_ROW||e.insertionMode===S.IN_CELL?S.IN_SELECT_IN_TABLE:S.IN_SELECT}function og(e,t){e.openElements.currentTagId===i.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML)}function lg(e,t){e.openElements.hasInScope(i.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,me.HTML)}function cg(e,t){e.openElements.hasInScope(i.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(i.RTC),e._insertElement(t,me.HTML)}function ug(e,t){e._reconstructActiveFormattingElements(),kc(t),Zr(t),t.selfClosing?e._appendElement(t,me.MATHML):e._insertElement(t,me.MATHML),t.ackSelfClosing=!0}function dg(e,t){e._reconstructActiveFormattingElements(),Nc(t),Zr(t),t.selfClosing?e._appendElement(t,me.SVG):e._insertElement(t,me.SVG),t.ackSelfClosing=!0}function Co(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,me.HTML)}function Pt(e,t){switch(t.tagID){case i.I:case i.S:case i.B:case i.U:case i.EM:case i.TT:case i.BIG:case i.CODE:case i.FONT:case i.SMALL:case i.STRIKE:case i.STRONG:{Vf(e,t);break}case i.A:{zf(e,t);break}case i.H1:case i.H2:case i.H3:case i.H4:case i.H5:case i.H6:{$f(e,t);break}case i.P:case i.DL:case i.OL:case i.UL:case i.DIV:case i.DIR:case i.NAV:case i.MAIN:case i.MENU:case i.ASIDE:case i.CENTER:case i.FIGURE:case i.FOOTER:case i.HEADER:case i.HGROUP:case i.DIALOG:case i.DETAILS:case i.ADDRESS:case i.ARTICLE:case i.SEARCH:case i.SECTION:case i.SUMMARY:case i.FIELDSET:case i.BLOCKQUOTE:case i.FIGCAPTION:{Uf(e,t);break}case i.LI:case i.DD:case i.DT:{Kf(e,t);break}case i.BR:case i.IMG:case i.WBR:case i.AREA:case i.EMBED:case i.KEYGEN:{Sc(e,t);break}case i.HR:{tg(e,t);break}case i.RB:case i.RTC:{lg(e,t);break}case i.RT:case i.RP:{cg(e,t);break}case i.PRE:case i.LISTING:{qf(e,t);break}case i.XMP:{ag(e,t);break}case i.SVG:{dg(e,t);break}case i.HTML:{Bf(e,t);break}case i.BASE:case i.LINK:case i.META:case i.STYLE:case i.TITLE:case i.SCRIPT:case i.BGSOUND:case i.BASEFONT:case i.TEMPLATE:{ns(e,t);break}case i.BODY:{Ff(e,t);break}case i.FORM:{Wf(e,t);break}case i.NOBR:{Qf(e,t);break}case i.MATH:{ug(e,t);break}case i.TABLE:{Jf(e,t);break}case i.INPUT:{Zf(e,t);break}case i.PARAM:case i.TRACK:case i.SOURCE:{eg(e,t);break}case i.IMAGE:{sg(e,t);break}case i.BUTTON:{Yf(e,t);break}case i.APPLET:case i.OBJECT:case i.MARQUEE:{Xf(e,t);break}case i.IFRAME:{rg(e,t);break}case i.SELECT:{ig(e,t);break}case i.OPTION:case i.OPTGROUP:{og(e,t);break}case i.NOEMBED:case i.NOFRAMES:{vo(e,t);break}case i.FRAMESET:{Hf(e,t);break}case i.TEXTAREA:{ng(e,t);break}case i.NOSCRIPT:{e.options.scriptingEnabled?vo(e,t):Co(e,t);break}case i.PLAINTEXT:{Gf(e,t);break}case i.COL:case i.TH:case i.TD:case i.TR:case i.HEAD:case i.FRAME:case i.TBODY:case i.TFOOT:case i.THEAD:case i.CAPTION:case i.COLGROUP:break;default:Co(e,t)}}function pg(e,t){if(e.openElements.hasInScope(i.BODY)&&(e.insertionMode=S.AFTER_BODY,e.options.sourceCodeLocationInfo)){const n=e.openElements.tryPeekProperlyNestedBodyElement();n&&e._setEndLocation(n,t)}}function mg(e,t){e.openElements.hasInScope(i.BODY)&&(e.insertionMode=S.AFTER_BODY,Bc(e,t))}function hg(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n))}function fg(e){const t=e.openElements.tmplCount>0,{formElement:n}=e;t||(e.formElement=null),(n||t)&&e.openElements.hasInScope(i.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(i.FORM):n&&e.openElements.remove(n))}function gg(e){e.openElements.hasInButtonScope(i.P)||e._insertFakeElement(H.P,i.P),e._closePElement()}function bg(e){e.openElements.hasInListItemScope(i.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(i.LI),e.openElements.popUntilTagNamePopped(i.LI))}function xg(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.popUntilTagNamePopped(n))}function Eg(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function yg(e,t){const n=t.tagID;e.openElements.hasInScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker())}function Tg(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(H.BR,i.BR),e.openElements.pop(),e.framesetOk=!1}function Ac(e,t){const n=t.tagName,r=t.tagID;for(let a=e.openElements.stackTop;a>0;a--){const c=e.openElements.items[a],l=e.openElements.tagIDs[a];if(r===l&&(r!==i.UNKNOWN||e.treeAdapter.getTagName(c)===n)){e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.stackTop>=a&&e.openElements.shortenToLength(a);break}if(e._isSpecialElement(c,l))break}}function Da(e,t){switch(t.tagID){case i.A:case i.B:case i.I:case i.S:case i.U:case i.EM:case i.TT:case i.BIG:case i.CODE:case i.FONT:case i.NOBR:case i.SMALL:case i.STRIKE:case i.STRONG:{ei(e,t);break}case i.P:{gg(e);break}case i.DL:case i.UL:case i.OL:case i.DIR:case i.DIV:case i.NAV:case i.PRE:case i.MAIN:case i.MENU:case i.ASIDE:case i.BUTTON:case i.CENTER:case i.FIGURE:case i.FOOTER:case i.HEADER:case i.HGROUP:case i.DIALOG:case i.ADDRESS:case i.ARTICLE:case i.DETAILS:case i.SEARCH:case i.SECTION:case i.SUMMARY:case i.LISTING:case i.FIELDSET:case i.BLOCKQUOTE:case i.FIGCAPTION:{hg(e,t);break}case i.LI:{bg(e);break}case i.DD:case i.DT:{xg(e,t);break}case i.H1:case i.H2:case i.H3:case i.H4:case i.H5:case i.H6:{Eg(e);break}case i.BR:{Tg(e);break}case i.BODY:{pg(e,t);break}case i.HTML:{mg(e,t);break}case i.FORM:{fg(e);break}case i.APPLET:case i.OBJECT:case i.MARQUEE:{yg(e,t);break}case i.TEMPLATE:{Ms(e,t);break}default:Ac(e,t)}}function jc(e,t){e.tmplInsertionModeStack.length>0?Mc(e,t):ti(e,t)}function kg(e,t){var n;t.tagID===i.SCRIPT&&((n=e.scriptHandler)===null||n===void 0||n.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode}function Ng(e,t){e._err(t,V.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function Qa(e,t){if(e.openElements.currentTagId!==void 0&&vc.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=!1,e.originalInsertionMode=e.insertionMode,e.insertionMode=S.IN_TABLE_TEXT,t.type){case Ze.CHARACTER:{Rc(e,t);break}case Ze.WHITESPACE_CHARACTER:{Ic(e,t);break}}else Ln(e,t)}function vg(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,me.HTML),e.insertionMode=S.IN_CAPTION}function Cg(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,me.HTML),e.insertionMode=S.IN_COLUMN_GROUP}function wg(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(H.COLGROUP,i.COLGROUP),e.insertionMode=S.IN_COLUMN_GROUP,si(e,t)}function Sg(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,me.HTML),e.insertionMode=S.IN_TABLE_BODY}function _g(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(H.TBODY,i.TBODY),e.insertionMode=S.IN_TABLE_BODY,Oa(e,t)}function Ag(e,t){e.openElements.hasInTableScope(i.TABLE)&&(e.openElements.popUntilTagNamePopped(i.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function jg(e,t){_c(t)?e._appendElement(t,me.HTML):Ln(e,t),t.ackSelfClosing=!0}function Ig(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,me.HTML),e.formElement=e.openElements.current,e.openElements.pop())}function Vs(e,t){switch(t.tagID){case i.TD:case i.TH:case i.TR:{_g(e,t);break}case i.STYLE:case i.SCRIPT:case i.TEMPLATE:{ns(e,t);break}case i.COL:{wg(e,t);break}case i.FORM:{Ig(e,t);break}case i.TABLE:{Ag(e,t);break}case i.TBODY:case i.TFOOT:case i.THEAD:{Sg(e,t);break}case i.INPUT:{jg(e,t);break}case i.CAPTION:{vg(e,t);break}case i.COLGROUP:{Cg(e,t);break}default:Ln(e,t)}}function An(e,t){switch(t.tagID){case i.TABLE:{e.openElements.hasInTableScope(i.TABLE)&&(e.openElements.popUntilTagNamePopped(i.TABLE),e._resetInsertionMode());break}case i.TEMPLATE:{Ms(e,t);break}case i.BODY:case i.CAPTION:case i.COL:case i.COLGROUP:case i.HTML:case i.TBODY:case i.TD:case i.TFOOT:case i.TH:case i.THEAD:case i.TR:break;default:Ln(e,t)}}function Ln(e,t){const n=e.fosterParentingEnabled;e.fosterParentingEnabled=!0,La(e,t),e.fosterParentingEnabled=n}function Ic(e,t){e.pendingCharacterTokens.push(t)}function Rc(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=!0}function an(e,t){let n=0;if(e.hasNonWhitespacePendingCharacterToken)for(;n<e.pendingCharacterTokens.length;n++)Ln(e,e.pendingCharacterTokens[n]);else for(;n<e.pendingCharacterTokens.length;n++)e._insertCharacters(e.pendingCharacterTokens[n]);e.insertionMode=e.originalInsertionMode,e._processToken(t)}const Pc=new Set([i.CAPTION,i.COL,i.COLGROUP,i.TBODY,i.TD,i.TFOOT,i.TH,i.THEAD,i.TR]);function Rg(e,t){const n=t.tagID;Pc.has(n)?e.openElements.hasInTableScope(i.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(i.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=S.IN_TABLE,Vs(e,t)):Pt(e,t)}function Pg(e,t){const n=t.tagID;switch(n){case i.CAPTION:case i.TABLE:{e.openElements.hasInTableScope(i.CAPTION)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(i.CAPTION),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=S.IN_TABLE,n===i.TABLE&&An(e,t));break}case i.BODY:case i.COL:case i.COLGROUP:case i.HTML:case i.TBODY:case i.TD:case i.TFOOT:case i.TH:case i.THEAD:case i.TR:break;default:Da(e,t)}}function si(e,t){switch(t.tagID){case i.HTML:{Pt(e,t);break}case i.COL:{e._appendElement(t,me.HTML),t.ackSelfClosing=!0;break}case i.TEMPLATE:{ns(e,t);break}default:Ta(e,t)}}function Lg(e,t){switch(t.tagID){case i.COLGROUP:{e.openElements.currentTagId===i.COLGROUP&&(e.openElements.pop(),e.insertionMode=S.IN_TABLE);break}case i.TEMPLATE:{Ms(e,t);break}case i.COL:break;default:Ta(e,t)}}function Ta(e,t){e.openElements.currentTagId===i.COLGROUP&&(e.openElements.pop(),e.insertionMode=S.IN_TABLE,e._processToken(t))}function Oa(e,t){switch(t.tagID){case i.TR:{e.openElements.clearBackToTableBodyContext(),e._insertElement(t,me.HTML),e.insertionMode=S.IN_ROW;break}case i.TH:case i.TD:{e.openElements.clearBackToTableBodyContext(),e._insertFakeElement(H.TR,i.TR),e.insertionMode=S.IN_ROW,Ma(e,t);break}case i.CAPTION:case i.COL:case i.COLGROUP:case i.TBODY:case i.TFOOT:case i.THEAD:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=S.IN_TABLE,Vs(e,t));break}default:Vs(e,t)}}function Rr(e,t){const n=t.tagID;switch(t.tagID){case i.TBODY:case i.TFOOT:case i.THEAD:{e.openElements.hasInTableScope(n)&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=S.IN_TABLE);break}case i.TABLE:{e.openElements.hasTableBodyContextInTableScope()&&(e.openElements.clearBackToTableBodyContext(),e.openElements.pop(),e.insertionMode=S.IN_TABLE,An(e,t));break}case i.BODY:case i.CAPTION:case i.COL:case i.COLGROUP:case i.HTML:case i.TD:case i.TH:case i.TR:break;default:An(e,t)}}function Ma(e,t){switch(t.tagID){case i.TH:case i.TD:{e.openElements.clearBackToTableRowContext(),e._insertElement(t,me.HTML),e.insertionMode=S.IN_CELL,e.activeFormattingElements.insertMarker();break}case i.CAPTION:case i.COL:case i.COLGROUP:case i.TBODY:case i.TFOOT:case i.THEAD:case i.TR:{e.openElements.hasInTableScope(i.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=S.IN_TABLE_BODY,Oa(e,t));break}default:Vs(e,t)}}function Lc(e,t){switch(t.tagID){case i.TR:{e.openElements.hasInTableScope(i.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=S.IN_TABLE_BODY);break}case i.TABLE:{e.openElements.hasInTableScope(i.TR)&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=S.IN_TABLE_BODY,Rr(e,t));break}case i.TBODY:case i.TFOOT:case i.THEAD:{(e.openElements.hasInTableScope(t.tagID)||e.openElements.hasInTableScope(i.TR))&&(e.openElements.clearBackToTableRowContext(),e.openElements.pop(),e.insertionMode=S.IN_TABLE_BODY,Rr(e,t));break}case i.BODY:case i.CAPTION:case i.COL:case i.COLGROUP:case i.HTML:case i.TD:case i.TH:break;default:An(e,t)}}function Dg(e,t){const n=t.tagID;Pc.has(n)?(e.openElements.hasInTableScope(i.TD)||e.openElements.hasInTableScope(i.TH))&&(e._closeTableCell(),Ma(e,t)):Pt(e,t)}function Og(e,t){const n=t.tagID;switch(n){case i.TD:case i.TH:{e.openElements.hasInTableScope(n)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(n),e.activeFormattingElements.clearToLastMarker(),e.insertionMode=S.IN_ROW);break}case i.TABLE:case i.TBODY:case i.TFOOT:case i.THEAD:case i.TR:{e.openElements.hasInTableScope(n)&&(e._closeTableCell(),Lc(e,t));break}case i.BODY:case i.CAPTION:case i.COL:case i.COLGROUP:case i.HTML:break;default:Da(e,t)}}function Dc(e,t){switch(t.tagID){case i.HTML:{Pt(e,t);break}case i.OPTION:{e.openElements.currentTagId===i.OPTION&&e.openElements.pop(),e._insertElement(t,me.HTML);break}case i.OPTGROUP:{e.openElements.currentTagId===i.OPTION&&e.openElements.pop(),e.openElements.currentTagId===i.OPTGROUP&&e.openElements.pop(),e._insertElement(t,me.HTML);break}case i.HR:{e.openElements.currentTagId===i.OPTION&&e.openElements.pop(),e.openElements.currentTagId===i.OPTGROUP&&e.openElements.pop(),e._appendElement(t,me.HTML),t.ackSelfClosing=!0;break}case i.INPUT:case i.KEYGEN:case i.TEXTAREA:case i.SELECT:{e.openElements.hasInSelectScope(i.SELECT)&&(e.openElements.popUntilTagNamePopped(i.SELECT),e._resetInsertionMode(),t.tagID!==i.SELECT&&e._processStartTag(t));break}case i.SCRIPT:case i.TEMPLATE:{ns(e,t);break}}}function Oc(e,t){switch(t.tagID){case i.OPTGROUP:{e.openElements.stackTop>0&&e.openElements.currentTagId===i.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===i.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===i.OPTGROUP&&e.openElements.pop();break}case i.OPTION:{e.openElements.currentTagId===i.OPTION&&e.openElements.pop();break}case i.SELECT:{e.openElements.hasInSelectScope(i.SELECT)&&(e.openElements.popUntilTagNamePopped(i.SELECT),e._resetInsertionMode());break}case i.TEMPLATE:{Ms(e,t);break}}}function Mg(e,t){const n=t.tagID;n===i.CAPTION||n===i.TABLE||n===i.TBODY||n===i.TFOOT||n===i.THEAD||n===i.TR||n===i.TD||n===i.TH?(e.openElements.popUntilTagNamePopped(i.SELECT),e._resetInsertionMode(),e._processStartTag(t)):Dc(e,t)}function Bg(e,t){const n=t.tagID;n===i.CAPTION||n===i.TABLE||n===i.TBODY||n===i.TFOOT||n===i.THEAD||n===i.TR||n===i.TD||n===i.TH?e.openElements.hasInTableScope(n)&&(e.openElements.popUntilTagNamePopped(i.SELECT),e._resetInsertionMode(),e.onEndTag(t)):Oc(e,t)}function Fg(e,t){switch(t.tagID){case i.BASE:case i.BASEFONT:case i.BGSOUND:case i.LINK:case i.META:case i.NOFRAMES:case i.SCRIPT:case i.STYLE:case i.TEMPLATE:case i.TITLE:{ns(e,t);break}case i.CAPTION:case i.COLGROUP:case i.TBODY:case i.TFOOT:case i.THEAD:{e.tmplInsertionModeStack[0]=S.IN_TABLE,e.insertionMode=S.IN_TABLE,Vs(e,t);break}case i.COL:{e.tmplInsertionModeStack[0]=S.IN_COLUMN_GROUP,e.insertionMode=S.IN_COLUMN_GROUP,si(e,t);break}case i.TR:{e.tmplInsertionModeStack[0]=S.IN_TABLE_BODY,e.insertionMode=S.IN_TABLE_BODY,Oa(e,t);break}case i.TD:case i.TH:{e.tmplInsertionModeStack[0]=S.IN_ROW,e.insertionMode=S.IN_ROW,Ma(e,t);break}default:e.tmplInsertionModeStack[0]=S.IN_BODY,e.insertionMode=S.IN_BODY,Pt(e,t)}}function Hg(e,t){t.tagID===i.TEMPLATE&&Ms(e,t)}function Mc(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(i.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):ti(e,t)}function Ug(e,t){t.tagID===i.HTML?Pt(e,t):ka(e,t)}function Bc(e,t){var n;if(t.tagID===i.HTML){if(e.fragmentContext||(e.insertionMode=S.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===i.HTML){e._setEndLocation(e.openElements.items[0],t);const r=e.openElements.items[1];r&&!(!((n=e.treeAdapter.getNodeSourceCodeLocation(r))===null||n===void 0)&&n.endTag)&&e._setEndLocation(r,t)}}else ka(e,t)}function ka(e,t){e.insertionMode=S.IN_BODY,La(e,t)}function $g(e,t){switch(t.tagID){case i.HTML:{Pt(e,t);break}case i.FRAMESET:{e._insertElement(t,me.HTML);break}case i.FRAME:{e._appendElement(t,me.HTML),t.ackSelfClosing=!0;break}case i.NOFRAMES:{ns(e,t);break}}}function qg(e,t){t.tagID===i.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==i.FRAMESET&&(e.insertionMode=S.AFTER_FRAMESET))}function Wg(e,t){switch(t.tagID){case i.HTML:{Pt(e,t);break}case i.NOFRAMES:{ns(e,t);break}}}function Kg(e,t){t.tagID===i.HTML&&(e.insertionMode=S.AFTER_AFTER_FRAMESET)}function Gg(e,t){t.tagID===i.HTML?Pt(e,t):ta(e,t)}function ta(e,t){e.insertionMode=S.IN_BODY,La(e,t)}function Yg(e,t){switch(t.tagID){case i.HTML:{Pt(e,t);break}case i.NOFRAMES:{ns(e,t);break}}}function zg(e,t){t.chars=gt,e._insertCharacters(t)}function Vg(e,t){e._insertCharacters(t),e.framesetOk=!1}function Fc(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==me.HTML&&e.openElements.currentTagId!==void 0&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop()}function Qg(e,t){if(df(t))Fc(e),e._startTagOutsideForeignContent(t);else{const n=e._getAdjustedCurrentElement(),r=e.treeAdapter.getNamespaceURI(n);r===me.MATHML?kc(t):r===me.SVG&&(pf(t),Nc(t)),Zr(t),t.selfClosing?e._appendElement(t,r):e._insertElement(t,r),t.ackSelfClosing=!0}}function Xg(e,t){if(t.tagID===i.P||t.tagID===i.BR){Fc(e),e._endTagOutsideForeignContent(t);return}for(let n=e.openElements.stackTop;n>0;n--){const r=e.openElements.items[n];if(e.treeAdapter.getNamespaceURI(r)===me.HTML){e._endTagOutsideForeignContent(t);break}const a=e.treeAdapter.getTagName(r);if(a.toLowerCase()===t.tagName){t.tagName=a,e.openElements.shortenToLength(n);break}}}H.AREA,H.BASE,H.BASEFONT,H.BGSOUND,H.BR,H.COL,H.EMBED,H.FRAME,H.HR,H.IMG,H.INPUT,H.KEYGEN,H.LINK,H.META,H.PARAM,H.SOURCE,H.TRACK,H.WBR;const Jg=/<(\/?)(iframe|noembed|noframes|plaintext|script|style|textarea|title|xmp)(?=[\t\n\f\r />])/gi,Zg=new Set(["mdxFlowExpression","mdxJsxFlowElement","mdxJsxTextElement","mdxTextExpression","mdxjsEsm"]),wo={sourceCodeLocationInfo:!0,scriptingEnabled:!1};function Hc(e,t){const n=c0(e),r=pl("type",{handlers:{root:e0,element:t0,text:s0,comment:$c,doctype:n0,raw:r0},unknown:i0}),a={parser:n?new No(wo):No.getFragmentParser(void 0,wo),handle(u){r(u,a)},stitches:!1,options:t||{}};r(e,a),Zs(a,Ds());const c=n?a.parser.document:a.parser.getFragment(),l=ch(c,{file:a.options.file});return a.stitches&&cd(l,"comment",function(u,d,m){const f=u;if(f.value.stitch&&m&&d!==void 0){const h=m.children;return h[d]=f.value.stitch,d}}),l.type==="root"&&l.children.length===1&&l.children[0].type===e.type?l.children[0]:l}function Uc(e,t){let n=-1;if(e)for(;++n<e.length;)t.handle(e[n])}function e0(e,t){Uc(e.children,t)}function t0(e,t){o0(e,t),Uc(e.children,t),l0(e,t)}function s0(e,t){t.parser.tokenizer.state>4&&(t.parser.tokenizer.state=0);const n={type:Ze.CHARACTER,chars:e.value,location:Dn(e)};Zs(t,Ds(e)),t.parser.currentToken=n,t.parser._processToken(t.parser.currentToken)}function n0(e,t){const n={type:Ze.DOCTYPE,name:"html",forceQuirks:!1,publicId:"",systemId:"",location:Dn(e)};Zs(t,Ds(e)),t.parser.currentToken=n,t.parser._processToken(t.parser.currentToken)}function a0(e,t){t.stitches=!0;const n=u0(e);if("children"in e&&"children"in n){const r=Hc({type:"root",children:e.children},t.options);n.children=r.children}$c({type:"comment",value:{stitch:n}},t)}function $c(e,t){const n=e.value,r={type:Ze.COMMENT,data:n,location:Dn(e)};Zs(t,Ds(e)),t.parser.currentToken=r,t.parser._processToken(t.parser.currentToken)}function r0(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,qc(t,Ds(e)),t.parser.tokenizer.write(t.options.tagfilter?e.value.replace(Jg,"<$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 i0(e,t){const n=e;if(t.options.passThrough&&t.options.passThrough.includes(n.type))a0(n,t);else{let r="";throw Zg.has(n.type)&&(r=". 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"+r)}}function Zs(e,t){qc(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=Tt.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 qc(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 o0(e,t){const n=e.tagName.toLowerCase();if(t.parser.tokenizer.state===Tt.PLAINTEXT)return;Zs(t,Ds(e));const r=t.parser.openElements.current;let a="namespaceURI"in r?r.namespaceURI:ws.html;a===ws.html&&n==="svg"&&(a=ws.svg);const c=hh({...e,children:[]},{space:a===ws.svg?"svg":"html"}),l={type:Ze.START_TAG,tagName:n,tagID:Js(n),selfClosing:!1,ackSelfClosing:!1,attrs:"attrs"in c?c.attrs:[],location:Dn(e)};t.parser.currentToken=l,t.parser._processToken(t.parser.currentToken),t.parser.tokenizer.lastStartTagName=n}function l0(e,t){const n=e.tagName.toLowerCase();if(!t.parser.tokenizer.inForeignNode&&kh.includes(n)||t.parser.tokenizer.state===Tt.PLAINTEXT)return;Zs(t,ml(e));const r={type:Ze.END_TAG,tagName:n,tagID:Js(n),selfClosing:!1,ackSelfClosing:!1,attrs:[],location:Dn(e)};t.parser.currentToken=r,t.parser._processToken(t.parser.currentToken),n===t.parser.tokenizer.lastStartTagName&&(t.parser.tokenizer.state===Tt.RCDATA||t.parser.tokenizer.state===Tt.RAWTEXT||t.parser.tokenizer.state===Tt.SCRIPT_DATA)&&(t.parser.tokenizer.state=Tt.DATA)}function c0(e){const t=e.type==="root"?e.children[0]:e;return!!(t&&(t.type==="doctype"||t.type==="element"&&t.tagName.toLowerCase()==="html"))}function Dn(e){const t=Ds(e)||{line:void 0,column:void 0,offset:void 0},n=ml(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 u0(e){return"children"in e?mi({...e,children:[]}):mi(e)}function d0(e){return function(t,n){return Hc(t,{...e,file:n})}}const Na=o.memo(function({text:t}){const n=He(),[r,a]=o.useState(!1);return t?s.jsx("button",{type:"button",className:"copy-btn",title:n("copy"),onClick:()=>{navigator.clipboard.writeText(t).then(()=>{a(!0),setTimeout(()=>a(!1),1200)})},children:r?s.jsx(os,{}):s.jsx(cs,{})}):null});function p0(e){const t=r=>{if(typeof r=="string"||typeof r=="number"){const a=String(r);return a===""?[[]]:a.split(`
|
|
329
|
+
`).map(c=>c===""?[]:[c])}if(Array.isArray(r)){let a=[];for(const c of r){const l=t(c);if(a.length===0)a=l;else{const u=l[0]??[];a[a.length-1].push(...u),a.push(...l.slice(1))}}return a}if(r&&typeof r=="object"&&"props"in r){const a=r,c=a.props?.children,l={...a.props,children:void 0},u=c==null?[]:t(c);return u.length===0?[[o.createElement(a.type,l)]]:u.map(d=>[o.createElement(a.type,l,...d)])}return[[r]]},n=t(e);return n.length>1&&n[n.length-1].length===0&&n.pop(),n}function Pr(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Pr).join("");if(e&&typeof e=="object"&&"props"in e){const t=e.props;return Pr(t?.children)}return""}function m0(e){const t=Array.isArray(e)?e[0]:e;return!t||typeof t!="object"||!("props"in t)?null:t}function h0(e){const n=m0(e)?.props?.className;if(typeof n!="string")return null;const r=n.match(/(?:^|\s)language-([A-Za-z0-9_+\-]+)(?:\s|$)/);return r?r[1]:null}const So="pi-web-ui:plugin-data";let Nn=new Map,vn=new Map,Ks=new Set,Lr=-1,Wc=0;const Dr=new Set;function f0(){Wc++;for(const e of Dr)e()}function g0(e){return Dr.add(e),()=>{Dr.delete(e)}}function _o(){return Wc}let Kc=null;function b0(e){Kc=e}function x0(e,t){t!==Lr&&(Lr=t,vn.clear(),Ks.clear());const n=new Map;for(const a of e)if(!(a.error||!a.renderers))for(const c of a.renderers)n.has(c)||n.set(c,a.id);let r=n.size!==Nn.size;if(!r){for(const[a,c]of n)if(Nn.get(a)!==c){r=!0;break}}if(r){for(const a of vn.keys())n.has(a)||vn.delete(a);for(const a of Ks)n.has(a)||Ks.delete(a);Nn=n,f0()}}async function E0(e,t){const n=Nn.get(e);if(!n)return null;let r=vn.get(e);if(!r&&!Ks.has(e))try{const l=(await import(_t(`/plugins/${encodeURIComponent(n)}/client/entry.mjs?e=${Lr}`))).default?.renderers?.[e];typeof l=="function"?(r={pluginId:n,renderer:l},vn.set(e,r)):(Ks.add(e),console.error(`[plugin:${n}] entry.mjs 未提供 renderers["${e}"]`))}catch(c){Ks.add(e),console.error(`[plugin:${n}] renderer 加载失败(${e}):`,c)}if(!r)return null;const a={pluginId:r.pluginId,send:c=>{Kc?.({type:"plugin_message",pluginId:r.pluginId,payload:c})},onData:c=>{const l=u=>{const d=u.detail;d.pluginId===r.pluginId&&c(d.payload)};return window.addEventListener(So,l),()=>window.removeEventListener(So,l)}};try{const c=await r.renderer(t,a);return c instanceof HTMLElement?c:null}catch(c){return console.error(`[plugin:${r.pluginId}] renderer("${e}") 执行失败:`,c),null}}function y0(e){return Nn.has(e)}const Gs=new Map,Cn=new Map,Ys=new Set;let Or=-1;function T0(e,t){t!==Or&&(Or=t,Cn.clear(),Ys.clear());const n=new Map;for(const r of e){if(r.error)continue;const a=r.messageWidgets;if(Array.isArray(a))for(const c of a)typeof c!="string"||!c||n.has(c)||n.set(c,r.id)}for(const r of[...Gs.keys()])n.has(r)||Gs.delete(r);for(const[r,a]of n)Gs.set(r,a);for(const r of Cn.keys())n.has(r)||Cn.delete(r);for(const r of Ys)n.has(r)||Ys.delete(r)}function Gc(e){return Gs.has(e)}async function k0(e){const t=Gs.get(e);if(!t)return null;let n=Cn.get(e);if(!n&&!Ys.has(e))try{const a=(await import(_t(`/plugins/${encodeURIComponent(t)}/client/entry.mjs?e=${Or}`))).default?.messageWidgets?.[e];typeof a=="function"?(n={pluginId:t,renderer:a},Cn.set(e,n)):(Ys.add(e),console.error(`[plugin:${t}] entry.mjs 未提供 messageWidgets["${e}"]`))}catch(r){Ys.add(e),console.error(`[plugin:${t}] messageWidget 加载失败(${e}):`,r)}return n?.renderer??null}const Mr="pi-web-ui:theme",Yc="dark",Ao="theme-stylesheet",ls="pi-web-ui:theme-change";function zc(){try{const e=localStorage.getItem(Mr);if(e&&e!==Yc)return e}catch{}return null}function N0(e){try{e?localStorage.setItem(Mr,e):localStorage.removeItem(Mr)}catch{}}function Vc(e){let t=document.getElementById(Ao);if(!e){t?.remove(),window.dispatchEvent(new CustomEvent(ls));return}t||(t=document.createElement("link"),t.id=Ao,t.rel="stylesheet",document.head.appendChild(t)),t.href=_t(`/themes/${encodeURIComponent(e)}.css`),t.onload=()=>window.dispatchEvent(new CustomEvent(ls))}async function jo(){try{const e=await fetch(hs(_t("/api/themes")));if(!e.ok)return[];const t=await e.json();return Array.isArray(t.themes)?t.themes:[]}catch{return[]}}function v0(){const[e,t]=o.useState([]),[n,r]=o.useState(()=>zc());o.useEffect(()=>{let l=!1;return jo().then(u=>{l||t(u)}),()=>{l=!0}},[]);const a=o.useCallback(()=>{jo().then(t)},[]);return o.useEffect(()=>{Vc(n),N0(n)},[n]),{themes:e,theme:n,switchTheme:l=>r(l===Yc?null:l),reloadThemes:a}}function Io(){const e=getComputedStyle(document.documentElement),t=(n,r)=>e.getPropertyValue(n).trim()||r;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 C0({lang:e,code:t}){const n=o.useRef(null),r=o.useRef(null),a=o.useRef(0),c=o.useRef(new WeakMap),[l,u]=o.useState(null);return o.useEffect(()=>{const d=()=>{const m=++a.current,f=r.current;f&&(f.dispatchEvent(new CustomEvent(ls)),c.current.set(f,m))};return window.addEventListener(ls,d),()=>window.removeEventListener(ls,d)},[]),o.useEffect(()=>{let d=!1;const m=a.current;return u(null),E0(e,t).then(f=>{d||(f&&c.current.set(f,m),u(f))}),()=>{d=!0}},[e,t]),o.useEffect(()=>{r.current=l;const d=n.current;return d&&(d.replaceChildren(),l&&(d.appendChild(l),(c.current.get(l)??a.current)<a.current&&(l.dispatchEvent(new CustomEvent(ls)),c.current.set(l,a.current)))),()=>{r.current===l&&(r.current=null)}},[l]),l?s.jsx("div",{className:"plugin-fence",ref:n}):s.jsxs("div",{className:"codeblock",children:[s.jsx(Na,{text:t}),s.jsx("pre",{children:s.jsx("code",{children:t})})]})}const w0=[hl,fl],S0=[hl,ih,fl],Ro=[[dd,{strict:!1,throwOnError:!1}],[pd,{detect:!0,ignoreMissing:!0}]];function ni({text:e,rawHtml:t=!1,hardBreaks:n=!1}){const r=t?[d0,...Ro]:Ro;return s.jsx(ud,{remarkPlugins:n?S0:w0,rehypePlugins:r,components:{pre:A0,a:_0},children:e})}const Ot=o.memo(function({text:t,rawHtml:n=!1,hardBreaks:r=!1}){return s.jsx("div",{className:"md",children:s.jsx(ni,{text:t,rawHtml:n,hardBreaks:r})})});function _0({href:e,children:t,...n}){const r=String(e??"");return/^(https?:|mailto:|tel:)/i.test(r)?s.jsx("a",{href:e,target:"_blank",rel:"noreferrer noopener",...n,children:t}):s.jsx("a",{href:e,...n,children:t})}function A0({children:e,...t}){o.useSyncExternalStore(g0,_o,_o);const n=h0(e);return n&&y0(n)?s.jsx(C0,{lang:n,code:Pr(e)}):s.jsx(j0,{children:e,...t})}function j0({children:e,...t}){const n=e&&typeof e=="object"&&"props"in e?e.props?.children:e,r=p0(n),a=r.length>1,c=a?`${String(r.length).length+1}ch`:void 0;return s.jsxs("div",{className:"codeblock",children:[s.jsx(Na,{text:Br(e)}),s.jsx("pre",{...t,children:r.map((l,u)=>s.jsxs("div",{className:"code-line",children:[a&&s.jsx("span",{className:"code-num",style:c?{width:c}:void 0,children:u+1}),s.jsx("code",{className:"code-line-body hljs",children:l})]},u))})]})}function Br(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Br).join("");if(e&&typeof e=="object"&&"props"in e){const t=e.props;return Br(t?.children)}return""}function I0({type:e,code:t,children:n}){const r=o.useRef(null),[a,c]=o.useState(null);return o.useEffect(()=>{let l=!1;if(c(null),!!Gc(e))return k0(e).then(async u=>{if(!(l||!u))try{const d={pluginId:Gs.get(e)??e,send:()=>{},onData:()=>()=>{}},m=await u(t,d);!l&&m instanceof HTMLElement&&c(m)}catch(d){console.error(`[plugin-widget:${e}] 渲染失败:`,d)}}),()=>{l=!0}},[e,t]),o.useEffect(()=>{const l=r.current;l&&(l.replaceChildren(),a&&l.appendChild(a))},[a]),a?s.jsx("div",{className:"plugin-widget",ref:r}):s.jsx(s.Fragment,{children:n})}const R0=/^\s{0,3}(`{3,}|~{3,})/,P0=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function Xa(e){return e.trim()===""}function Po(e){const t=R0.exec(e);return t?t[1]:null}function L0(e){const t=e.split(`
|
|
330
|
+
`),n=[];let r=[],a=null;for(let c=0;c<t.length;c++){const l=t[c];if(a!==null){const d=Po(l);d&&d[0]===a[0]&&d.length>=a.length&&(a=null),r.push(l);continue}const u=Po(l);if(u&&!Xa(l)){a=u,r.push(l);continue}if(Xa(l)){let d=c;for(;d<t.length&&Xa(t[d]);)d++;if(!(d<t.length&&P0.test(t[d]))&&r.length>0){n.push(r.join(`
|
|
331
|
+
`)),r=[];continue}r.push(l);continue}r.push(l)}return{frozen:n,active:r.join(`
|
|
332
|
+
`),inFence:a!==null}}const D0=o.memo(function({text:t}){return s.jsx(ni,{text:t})}),Lo=200;function O0({text:e,inFence:t}){const[n,r]=o.useState(e),a=o.useRef(0),c=o.useRef(null);return o.useEffect(()=>{if(t)return;const l=Date.now()-a.current,u=()=>{a.current=Date.now(),r(e)};if(l>=Lo){u();return}return c.current=setTimeout(u,Lo-l),()=>{c.current&&clearTimeout(c.current)}},[e,t]),t?s.jsx("div",{className:"codeblock",children:s.jsx("pre",{children:s.jsx("code",{children:e})})}):s.jsx(ni,{text:n})}const M0=o.memo(function({text:t}){const{frozen:n,active:r,inFence:a}=o.useMemo(()=>L0(t),[t]);return s.jsxs("div",{className:"md",children:[n.map((c,l)=>s.jsx(D0,{text:c},l)),r.length>0&&s.jsx(O0,{text:r,inFence:a},n.length)]})});function B0({thinking:e,streaming:t,wrap:n=!0,forceOpen:r=!1}){const a=He(),[c,l]=o.useState(null),u=c??n,d=u||r,m=t?e.trimEnd().slice(-80):e.split(`
|
|
333
|
+
`)[0].slice(0,80),[f,h]=o.useState(!1),b=()=>{navigator.clipboard.writeText(e),h(!0),window.setTimeout(()=>h(!1),1200)};return s.jsxs("div",{className:`thinking ${d?"open":""} ${t?"live":""}`,children:[s.jsxs("div",{className:"chead thinking-head",role:"button",tabIndex:0,"aria-expanded":d,title:a(d?"collapseMsg":"expandMsg"),onClick:()=>l(!u),onKeyDown:E=>{E.target===E.currentTarget&&(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),l(!u))},children:[s.jsx("button",{type:"button",className:"chead-toggle thinking-toggle",title:a(d?"collapseMsg":"expandMsg"),"aria-label":a(d?"collapseMsg":"expandMsg"),"aria-expanded":d,onClick:E=>{E.stopPropagation(),l(!u)},children:d?s.jsx(ks,{}):s.jsx(Os,{})}),s.jsx("span",{className:"chead-icon thinking-icon",children:s.jsx(Ts,{})}),s.jsx("span",{className:"chead-title thinking-label",children:t&&d?s.jsxs("span",{className:"thinking-live-label",children:[a("thinkingNow"),s.jsx("span",{className:"dots"})]}):d?a("thinking"):a("thinkingPreview",{preview:m})}),s.jsx("button",{type:"button",className:"chead-copy toolcall-copy thinking-copy",title:a(f?"copied":"copyMessage"),"aria-label":a("copyMessage"),onClick:E=>{E.stopPropagation(),b()},children:f?s.jsx(Qs,{}):s.jsx(cs,{})})]}),d&&s.jsx("div",{className:"thinking-body",children:e})]})}const va=256*1024,Ca=300,F0=/"(path|file_path|filePath|filename|file)"\s*:\s*"((?:[^"\\\n]|\\.){0,4000})"/,H0=/"agent"\s*:\s*"((?:[^"\\\n]|\\.){0,200})"/,U0=/"(timeout|timeoutSeconds|timeout_seconds|timeoutSec|timeoutMs|timeout_ms|timeoutMilliseconds)"\s*:\s*(-?\d+(?:\.\d+)?)(?![0-9eE.])/,$0=1e9;function q0(e){if(!e)return{};const t=e.length>va?e.slice(0,va):e;return{path:z0(t),timeout:V0(t),command:Q0(e),agent:W0(t)}}function W0(e){const t=H0.exec(e);if(!t)return;const n=t[1].replace(/[\u0000-\u001f\u007f]/g,"").trim();if(n)return n.length>Ca?`${n.slice(0,Ca)}…`:n}const K0=["task","expected_outcome","required_tools","must_do","must_not_do","context"];function G0(e){if(!e||e.length>va)return{};try{const t=JSON.parse(e);if(!t||typeof t!="object"||Array.isArray(t))return{};const n=t,r={};for(const a of[...K0,"agent","model"])typeof n[a]=="string"&&n[a].trim()&&(r[a]=n[a]);return r}catch{return{}}}function Y0(e,t=56){if(e.length<=t)return e;const n=e.split(/[\\/]+/).filter(Boolean),r=n[n.length-1];if(!r||n.length<=1)return`…${e.slice(-(t-1))}`;let a=r;for(let c=n.length-2;c>=0;c--){const l=`${n[c]}/${a}`;if(l.length+2>t)break;a=l}return`…/${a}`}function z0(e){const t=F0.exec(e);if(!t)return;const r=X0(t[2]).replace(/[\u0000-\u001f\u007f]/g," ").replace(/\s+/g," ").trim();if(r)return r.length>Ca?`${r.slice(0,Ca-1)}…`:r}function V0(e){const t=U0.exec(e);if(!t)return;const n=Number(t[2]);if(!Number.isFinite(n)||n<=0||n>$0)return;const r=t[1].toLowerCase();return!r.endsWith("ms")&&!r.endsWith("milliseconds")?`${n}s`:n<1e3?`${n}ms`:`${Math.round(n/100)/10}s`}function Q0(e){if(!(e.length>va))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 X0(e){try{const t=JSON.parse(`"${e}"`);return typeof t=="string"?t:e}catch{return e}}const J0={bash:"$",delegate_task:"◈",read:"📄",write:"✍️",edit:"✏️",edit_soft:"✏️",grep:"🔍",find:"🧭",ls:"📂"};function Z0(e){return J0[e]??"🛠"}const eb=o.memo(function({block:t,view:n,onKillBash:r,wrap:a=!0,forceOpen:c=!1}){const l=He(),[u,d]=o.useState(null),m=u??a,f=m||c,[h,b]=o.useState(!1),E=!n.result&&n.streaming&&!n.status,N=t.name==="bash"&&E,g=n.result!==void 0,R=!n.result&&!!n.status,M=n.result?.isError??n.status?.isError??!1,B=n.result?n.result.content.map(z=>z.type==="text"?z.text:"").join(""):n.liveOutput??"",j=B.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(z,A)=>l("liveOutputOmitted",{n:A})),Y=t.name==="delegate_task",q=Y?G0(t.argumentsText):{},C=Y&&n.result&&typeof n.result.details=="object"&&n.result.details!==null?n.result.details.convId:void 0,Te=typeof C=="string"&&C?C:/sa-[0-9a-f]{8}/.exec(B)?.[0],xe=M?"err":g?"ok":E||R?"run":"idle";let G=l(M?"error":g?"done":E?"running":R?"toolDoneWaitingModel":"toolQueued");const ee=R&&n.status?.durationMs!==void 0?ab(n.status.durationMs):"";R&&ee&&(G=`${G} · ${ee}`);const Q=R&&n.status?.exitCode!==void 0?`exit ${n.status.exitCode}`:"",O=q0(t.argumentsText),F=t.name==="bash"?O.command:void 0,w=!f&&F?nb(F):void 0,se=()=>{t.argumentsText&&(navigator.clipboard.writeText(t.argumentsText),b(!0),setTimeout(()=>b(!1),1200))};return s.jsxs("div",{className:`toolcall ${xe}`,children:[s.jsxs("div",{className:"chead toolcall-head",role:"button",tabIndex:0,"aria-expanded":f,title:l(f?"collapseMsg":"expandMsg"),onClick:()=>d(!m),onKeyDown:z=>{z.target===z.currentTarget&&(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),d(!m))},children:[s.jsx("button",{type:"button",className:"chead-toggle toolcall-toggle",title:l(f?"collapseMsg":"expandMsg"),"aria-label":l(f?"collapseMsg":"expandMsg"),"aria-expanded":f,onClick:z=>{z.stopPropagation(),d(!m)},children:f?s.jsx(ks,{}):s.jsx(Os,{})}),s.jsx("span",{className:"chead-icon toolcall-icon",children:Z0(t.name)}),s.jsx("span",{className:"chead-title toolcall-name",children:t.name}),s.jsx("span",{className:"toolcall-status",title:Q?`${G} · ${Q}`:G,"aria-label":Q?`${G} · ${Q}`:G,children:M?s.jsx(bt,{}):g?s.jsx(os,{}):E?s.jsx(Hd,{}):R?s.jsx(pr,{}):s.jsx(Od,{})}),w&&s.jsxs("span",{className:"toolcall-cmd",title:F,children:["$ ",w]}),O.path&&s.jsx("span",{className:"toolcall-path",title:O.path,children:Y0(O.path)}),O.timeout&&s.jsxs("span",{className:"toolcall-timeout",children:["⏱ ",O.timeout]}),Y&&O.agent&&s.jsxs("span",{className:"toolcall-agent",title:O.agent,children:["◈ ",O.agent]}),s.jsx("span",{className:"toolcall-spacer"}),N&&r&&s.jsxs("button",{type:"button",className:"toolcall-kill",title:l("stopBashTip"),onClick:z=>{z.stopPropagation(),r?.()},children:[s.jsx(oa,{}),s.jsx("span",{children:l("stopBash")})]}),Y&&g&&Te&&s.jsxs("button",{type:"button",className:"toolcall-open",title:l("delegateOpenSubagent"),onClick:z=>{z.stopPropagation(),window.dispatchEvent(new CustomEvent("pi-web-ui:switch-conversation",{detail:Te}))},children:[s.jsx(zd,{}),s.jsx("span",{children:l("delegateOpenSubagent")})]}),s.jsx("button",{type:"button",className:"chead-copy toolcall-copy",title:l("copyArgs"),onClick:z=>{z.stopPropagation(),se()},children:h?s.jsx(Qs,{}):s.jsx(cs,{})})]}),f&&s.jsxs("div",{className:"toolcall-body",children:[Y?s.jsx(sb,{args:q}):t.argumentsText&&s.jsx("div",{className:"toolcall-args",children:F?s.jsx(tb,{command:F}):s.jsx("pre",{children:t.argumentsText})}),j.length>0&&s.jsxs("div",{className:"toolcall-output",children:[s.jsxs("div",{className:"toolcall-output-label",children:[l(M?"errorOutput":"output"),(E||R)&&s.jsx("span",{className:"cursor"})]}),s.jsx("pre",{children:j})]}),E&&j.length===0&&s.jsxs("div",{className:"toolcall-waiting",children:[s.jsx("span",{className:"cursor"})," ",l("waitingOutput")]}),R&&j.length===0&&s.jsxs("div",{className:"toolcall-waiting",children:[s.jsx("span",{className:"cursor"})," ",l("waitingModel")]})]})]})});function tb({command:e}){return s.jsxs("div",{className:"termline",children:[s.jsx(Rn,{className:"termline-icon"}),s.jsx("code",{children:e})]})}function sb({args:e}){const t=He(),r=[{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:a})=>e[a]?.trim());return r.length===0?null:s.jsx("div",{className:"delegate-brief",children:r.map(({field:a,label:c})=>s.jsxs("div",{className:"delegate-sec",children:[s.jsx("div",{className:"delegate-sec-label",children:c}),s.jsx("div",{className:"delegate-sec-text",children:e[a]})]},a))})}function nb(e){const t=e.split(`
|
|
334
|
+
`),n=t[0].replace(/\s+/g," ").trim();if(!n)return;const r=t.length-1,a=n.length>80?`${n.slice(0,80)}…`:n;return r>0?`${a} +${r}`:a}function ab(e){if(e===void 0)return"";const t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;const n=Math.floor(t/60),r=Math.round(t%60);return`${n}m ${String(r).padStart(2,"0")}s`}const rb=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function ai(e){const t=e.match(rb);return t?{name:t[1],location:t[2],content:t[3],userMessage:t[4]?.trim()||void 0}:null}const ib=1568,ob=2*1024*1024;function fs(e){return e.startsWith("image/")&&e!=="image/svg+xml"&&e!=="image/svg"}async function ri(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,ib/Math.max(t.width,t.height)),r=Math.max(1,Math.round(t.width*n)),a=Math.max(1,Math.round(t.height*n)),c=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,d]of c){const m=document.createElement("canvas");m.width=r,m.height=a;const f=m.getContext("2d");if(!f)continue;u!=="image/png"&&(f.fillStyle="#ffffff",f.fillRect(0,0,r,a)),f.drawImage(t,0,0,r,a);const h=m.toDataURL(u,d),b=h.match(/^data:([^;]+);base64,/),E=b?b[1]:u,N=h.replace(/^data:[^;]*;base64,/,""),g=Math.floor(N.length*3/4);if(l={data:N,mimeType:E,name:e.name,size:g},g<=ob)return l}return l}finally{t.close()}}const lb=20*1024*1024;function Ls(e){return e.type==="text"&&typeof e.text=="string"?e:null}function Qc(e){return e.type==="thinking"&&typeof e.thinking=="string"?e:null}function Xc(e){return e.type==="toolCall"&&typeof e.id=="string"&&typeof e.name=="string"?e:null}function Jc(e){return e.type==="image"&&typeof e.dataUrl=="string"?e:null}function Zc(e){return e.type==="bash"&&typeof e.command=="string"?e:null}function cb(e){return e.imageData?"image":e.uploadPath?"upload":e.fileData?"file":"path"}function ub(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 db={edit:s.jsx(_n,{}),copy:s.jsx(cs,{}),x:s.jsx(bt,{})};function Do(e){const t=(e??"").trim();if(!t)return s.jsx(qs,{});const n=db[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(qs,{}))}function pb(e,t){const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}…`:n}const Oo=o.memo(function({message:t,toolResults:n,liveOutputs:r,toolStatuses:a,streaming:c,isLast:l,onEdit:u,onKillBash:d,onRetry:m,onCollapse:f,questionAttachments:h,qnIndex:b,qnActive:E,onJump:N,thinkingWrap:g,toolsWrap:R,searchActive:M,autoExpand:B,uiMessageActions:j,uiContextMessage:Y,onUiAction:q}){const C=He(),[Te,xe]=o.useState(!1),[G,ee]=o.useState(""),[Q,O]=o.useState([]),[F,w]=o.useState(!1),[se,z]=o.useState(null),A=X=>{z(X),window.setTimeout(()=>z(we=>we===X?null:we),4e3)};if(t.role==="toolResult")return null;if(t.role==="compactionSummary")return s.jsx(fb,{message:t,forceOpen:M,autoExpand:B});const ue=t.role==="custom"&&t.customType==="file",P=t.content.map(X=>Ls(X)?.text??"").filter(Boolean).join(`
|
|
335
|
+
`),ie=t.content.map(X=>Ls(X)?.text??"").filter(Boolean).join(" "),I=t.role==="user"?ai(P):null,he=I?I.userMessage??`skill:${I.name}`:P.split(`
|
|
336
|
+
`).join(" ").trim(),_=c&&l&&t.content.length===0,re=t.role==="user"&&!c&&!_&&!!u,le=async X=>{const we=[];for(const L of X){if(!fs(L.type))continue;const W=await ri(L);W&&we.push({path:"",imageData:W.data,mimeType:W.mimeType,name:W.name})}we.length>0&&O(L=>[...L,...we])},Ee=async X=>{if(X.size>lb){A(C("fileTooLarge",{name:X.name,size:20}));return}let we;try{we=(await new Promise((W,oe)=>{const fe=new FileReader;fe.onload=()=>W(fe.result),fe.onerror=()=>oe(fe.error??new Error("read failed")),fe.readAsDataURL(X)})).replace(/^data:[^;]*;base64,/,"")}catch{A(C("fileLoadFailed",{name:X.name}));return}O(L=>[...L,{path:"",fileData:we,name:X.name,size:X.size,mimeType:X.type||void 0}])},Ne=async X=>{const we=[];for(const L of X)fs(L.type)?we.push(L):Ee(L);we.length>0&&await le(we)},Ue=()=>{ee(I?`/skill:${I.name}${I.userMessage?` ${I.userMessage}`:""}`:t.content.map(X=>Ls(X)?.text??"").filter(Boolean).join(`
|
|
337
|
+
`)),O(h??[]),xe(!0)},ke=()=>{const X=G.trim();X&&(u?.(t.id,X,Q.length>0?Q:void 0),xe(!1))},Ke=j?j.some(X=>X?.id==="host:msg-copy"&&X.hidden!==!0):!0,Ie=pb(ie,40)||Fr(t.role,C),ce=(Y??[]).some(X=>X&&X.hidden!==!0&&X.kind!=="divider"),pe=X=>{if(!ce)return;const we=X.target;if(we instanceof Element&&we.closest("pre, code, a, input, textarea, [contenteditable='true']"))return;const L=window.getSelection?.();L&&!L.isCollapsed&&L.toString().trim().length>0||(X.preventDefault(),Pa({x:X.clientX,y:X.clientY,slot:"contextmenu.message",target:{id:t.id,kind:"message",label:Ie},entries:Y??[]}))},Fe=()=>{if(!j)return re?s.jsx("div",{className:"msg-actions",children:s.jsxs("button",{type:"button",className:"msg-action",title:C("editReaskTip"),onClick:Ue,children:[s.jsx(_n,{})," ",C("editReask")]})}):null;const X=[];return j.forEach((we,L)=>{if(!we||we.hidden===!0||we.id==="host:msg-copy")return;const W=`${we.id}#${L}`,oe=we.label||we.id;if(we.id==="host:msg-edit-reask"){if(!re)return;X.push(s.jsxs("button",{type:"button",className:"msg-action",title:C("editReaskTip"),onClick:Ue,children:[Do(we.icon)," ",oe]},W));return}if(we.kind==="divider"){X.push(s.jsx("span",{className:"msg-action-divider","aria-hidden":"true"},W));return}if(we.kind==="badge"){X.push(s.jsx("span",{className:"msg-action-badge",title:oe,children:we.badge??oe},W));return}X.push(s.jsxs("button",{type:"button",className:"msg-action",title:oe,"aria-label":oe,onClick:()=>q?.(we),children:[Do(we.icon)," ",oe,we.badge?s.jsx("span",{className:"msg-action-count",children:we.badge}):null]},W))}),X.length===0?null:s.jsx("div",{className:"msg-actions",children:X})},Ae=t.role==="custom"&&(t.customType==="goal-review"||t.customType==="goal-wizard"),et=t.role==="custom"&&t.customType==="goal-wizard",dt=t.role==="custom"&&!!t.customType&&t.customType!=="file"&&!Ae&&Gc(t.customType),Ve=dt?JSON.stringify({customType:t.customType,details:t.details??{}}):"";return s.jsxs("div",{className:`msg msg-${t.role}${Ae?" msg-goal-review":""}`,"data-role":t.role,"data-msg-id":t.id,onContextMenu:pe,children:[s.jsxs("div",{className:"msg-meta",children:[s.jsx("span",{className:"msg-role",children:t.role==="custom"?et?C("goalWizardCard"):Ae?C("goalBarTitle"):t.customType==="file"?C("attachment"):`${C("plugin")} · ${t.customType??C("unknown")}`:Fr(t.role,C)}),t.model&&s.jsx("span",{className:"msg-model",children:t.model}),t.timestamp&&s.jsx("span",{className:"msg-time",children:eu(t.timestamp)}),f&&s.jsxs("button",{type:"button",className:"msg-collapse-btn",title:C("collapseMsg"),onClick:()=>f(t.id),children:[s.jsx(Ra,{})," ",C("collapseMsg")]}),b!==void 0&&N&&s.jsxs("button",{type:"button",className:`qn-tag ${E?"active":""}`,title:`${b+1}. ${he}`,"aria-label":`${b+1}. ${he}`,onClick:()=>N(t.id),children:[s.jsx("span",{className:"qn-tag-bar"}),s.jsx("span",{className:"qn-tag-idx",children:b+1})]})]}),s.jsx("div",{className:"msg-body",children:Te?s.jsxs("div",{className:`msg-editor${F?" drag-over":""}`,onDragOver:X=>{X.preventDefault(),X.stopPropagation(),w(!0)},onDragLeave:X=>{X.currentTarget.contains(X.relatedTarget)||w(!1)},onDrop:X=>{X.preventDefault(),X.stopPropagation(),w(!1),Ne(Array.from(X.dataTransfer?.files??[]))},children:[Q.length>0&&s.jsx("div",{className:"msg-editor-images",children:Q.map((X,we)=>{const L=cb(X);return s.jsxs("span",{className:`msg-editor-img ${L==="image"?"":"file-chip"}`,title:ub(X,C),children:[L==="image"?s.jsx("img",{src:`data:${X.mimeType??"image/png"};base64,${X.imageData}`,alt:X.name}):s.jsxs("span",{className:"msg-editor-file",children:[s.jsx("span",{className:"msg-editor-file-icon",children:L==="path"?X.mode==="page"?"🌐":X.mode==="reference"?"🔗":"📎":"📄"}),s.jsx("span",{className:"msg-editor-file-name",children:X.name??X.path?.split("/").pop()})]}),s.jsx("button",{type:"button",className:"msg-editor-img-remove",title:C("removeAttachment"),onClick:()=>O(W=>W.filter((oe,fe)=>fe!==we)),children:s.jsx(bt,{})})]},`${X.name??X.path??"att"}-${we}`)})}),se&&s.jsx("div",{className:"msg-editor-notice",children:se}),s.jsx("textarea",{className:"msg-editor-input",value:G,autoFocus:!0,placeholder:C("editPlaceholder"),rows:Math.max(2,Math.min(10,G.split(`
|
|
338
|
+
`).length+1)),onChange:X=>ee(X.target.value),onPaste:X=>{const we=[];for(const L of X.clipboardData?.items??[])if(L.kind==="file"&&fs(L.type)){const W=L.getAsFile();W&&we.push(W)}we.length!==0&&(X.preventDefault(),le(we))},onKeyDown:X=>{X.key==="Enter"&&(X.metaKey||X.ctrlKey)?(X.preventDefault(),ke()):X.key==="Escape"&&xe(!1)}}),s.jsxs("div",{className:"msg-editor-actions",children:[s.jsxs("span",{className:"msg-editor-hint",children:[s.jsx(qd,{})," ",C("editAttachmentHint")]}),s.jsx("button",{type:"button",className:"chip",onClick:()=>xe(!1),children:C("cancel")}),s.jsxs("button",{type:"button",className:"chip primary",disabled:!G.trim(),title:C("reaskFromHere"),onClick:ke,children:[s.jsx(_n,{})," ",C("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&&!c&&m&&s.jsxs("button",{type:"button",className:"msg-retry-btn",title:C("retryLastTip"),onClick:m,children:[s.jsx(Yt,{})," ",C("retryNow")]})]}),ue?s.jsx(mb,{message:t,forceOpen:M}):I?s.jsxs(s.Fragment,{children:[s.jsx(gb,{block:I,forceOpen:M}),I.userMessage&&s.jsx("div",{className:"msg-text",children:s.jsx(Ot,{text:I.userMessage,hardBreaks:!0})}),t.content.map((X,we)=>X.type==="text"?null:s.jsx(Ja,{block:X,toolResults:n,liveOutputs:r,toolStatuses:a,streaming:c,isLast:l,onKillBash:d,toolsWrap:R,thinkingWrap:g,searchActive:M,role:t.role,showCopy:Ke},`${t.id}-${we}`))]}):dt?s.jsx(I0,{type:t.customType??"",code:Ve,children:t.content.map((X,we)=>s.jsx(Ja,{block:X,toolResults:n,liveOutputs:r,toolStatuses:a,streaming:c,isLast:l,onKillBash:d,toolsWrap:R,thinkingWrap:g,searchActive:M,role:t.role,showCopy:Ke},`${t.id}-${we}`))}):t.content.map((X,we)=>s.jsx(Ja,{block:X,toolResults:n,liveOutputs:r,toolStatuses:a,streaming:c,isLast:l,onKillBash:d,toolsWrap:R,thinkingWrap:g,searchActive:M,role:t.role,showCopy:Ke},`${t.id}-${we}`)),_&&s.jsxs("div",{className:"thinking-wait",children:[C("thinkingWait"),s.jsx("span",{className:"dot"})]}),c&&l&&!_&&s.jsx("span",{className:"stream-cursor"})]})}),!Te&&Fe()]})});function mb({message:e,forceOpen:t=!1}){const n=He(),[r,a]=o.useState(!1),[c,l]=o.useState(!1),u=r||t,d=e.details??{},m=d.name??d.path??n("attachment"),f=d.type==="folder",h=d.mode==="reference",b=d.mode==="bridged",E=d.mode==="page",N=e.content.filter(j=>j.type==="text").map(j=>j.text).join(`
|
|
339
|
+
`),g=hb(N),R=e.content.find(j=>j.type==="image"),M=g.split(`
|
|
340
|
+
`).length,B=!h&&!E&&g.length>0;return s.jsxs("div",{className:`attachcard ${h?"reference":""}${E?" page":""}`,children:[s.jsxs("div",{className:"chead attachcard-head",role:"button",tabIndex:0,"aria-expanded":u,title:n(u?"collapseMsg":"expandMsg"),onClick:()=>a(j=>t?!0:!j),onKeyDown:j=>{j.target===j.currentTarget&&(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),a(Y=>t?!0:!Y))},children:[!h&&!E&&s.jsx("span",{className:"chead-toggle",children:u?s.jsx(ks,{}):s.jsx(Os,{})}),s.jsx("span",{className:"chead-icon attachcard-icon",children:f?"📁":E?"🌐":"📎"}),s.jsx("span",{className:"chead-title attachcard-name",children:m}),d.path&&(E?s.jsx("a",{className:"attachcard-path attachcard-link",href:d.path,target:"_blank",rel:"noreferrer",children:d.path}):s.jsx("span",{className:"attachcard-path",children:d.path})),s.jsx("span",{className:`attachcard-mode ${d.mode==="lines"?"lines":h?"ref":E?"page":b?"bridged":"inline"}`,children:E?n("attachPageShort"):h?f?n("folderRefShort"):`${n("refOnlyShort")} · ${Mo(d.size)}`:b?n("bridgedVision"):R?n("image"):d.mode==="lines"?n("inlineLinesRange",{start:d.startLine??1,end:d.endLine??d.lines??1}):n("inlineLines",{n:d.lines??M})}),B&&s.jsx("button",{type:"button",className:"chead-copy",title:n(c?"copied":"copyMessage"),"aria-label":n("copyMessage"),onClick:j=>{j.stopPropagation(),navigator.clipboard.writeText(g),l(!0),window.setTimeout(()=>l(!1),1200)},children:c?s.jsx(Qs,{}):s.jsx(cs,{})})]}),!h&&u&&(b?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"attachcard-bridgenote",children:n("bridgedVisionDetail")}),R?.dataUrl&&s.jsx("div",{className:"attachcard-image",children:s.jsx("img",{src:R.dataUrl,alt:m})}),g&&s.jsx("pre",{className:"attachcard-content",children:g})]}):R?.dataUrl?s.jsx("div",{className:"attachcard-image",children:s.jsx("img",{src:R.dataUrl,alt:m})}):s.jsx("pre",{className:"attachcard-content",children:g})),h&&s.jsx("div",{className:"attachcard-refnote",children:f?n("folderNotExpanded"):n("fileNotExpanded",{size:Mo(d.size)})})]})}function Mo(e){return e===void 0?"":e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}function hb(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 fb({message:e,forceOpen:t=!1,autoExpand:n=!1}){const r=He(),[a,c]=o.useState(!1),[l,u]=o.useState(!1),[d,m]=o.useState(n);n!==d&&(m(n),n&&c(!0));const f=a||t,h=e.content.map(E=>Ls(E)?.text??"").filter(Boolean).join(`
|
|
341
|
+
`),b=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:r("role.compaction")}),e.timestamp&&s.jsx("span",{className:"msg-time",children:eu(e.timestamp)})]}),s.jsxs("div",{className:`compaction-card${a?" expanded":""}`,children:[s.jsxs("div",{className:"chead compaction-head",role:"button",tabIndex:0,"aria-expanded":f,title:r(f?"collapseMsg":"expandMsg"),onClick:()=>c(E=>t?!0:!E),onKeyDown:E=>{E.target===E.currentTarget&&(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),c(N=>t?!0:!N))},children:[s.jsx("span",{className:"chead-toggle",children:f?s.jsx(ks,{}):s.jsx(Os,{})}),s.jsx("span",{className:"chead-icon compaction-icon",children:s.jsx(Sl,{})}),s.jsx("span",{className:"chead-title compaction-title",children:b?r("compactionFrom",{tokens:b}):r("role.compaction")}),h&&s.jsx("button",{type:"button",className:"chead-copy",title:r(l?"copied":"copyMessage"),"aria-label":r("copyMessage"),onClick:E=>{E.stopPropagation(),navigator.clipboard.writeText(h),u(!0),window.setTimeout(()=>u(!1),1200)},children:l?s.jsx(Qs,{}):s.jsx(cs,{})})]}),f&&s.jsxs("div",{className:"compaction-body",children:[s.jsx(Ot,{text:h}),s.jsx("div",{className:"compaction-hint",children:r("compactionKeptHint")})]})]})]})}function gb({block:e,forceOpen:t=!1}){const n=He(),[r,a]=o.useState(!1),[c,l]=o.useState(!1),u=r||t;return s.jsxs("div",{className:`skillcard${r?" expanded":""}`,children:[s.jsxs("div",{className:"chead skillcard-head",role:"button",tabIndex:0,"aria-expanded":u,title:e.location,onClick:()=>a(d=>t?!0:!d),onKeyDown:d=>{d.target===d.currentTarget&&(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),a(m=>t?!0:!m))},children:[s.jsx("span",{className:"chead-toggle",children:u?s.jsx(ks,{}):s.jsx(Os,{})}),s.jsx("span",{className:"chead-icon skillcard-icon",children:s.jsx(Gd,{})}),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(c?"copied":"copyMessage"),"aria-label":n("copyMessage"),onClick:d=>{d.stopPropagation(),navigator.clipboard.writeText(e.content),l(!0),window.setTimeout(()=>l(!1),1200)},children:c?s.jsx(Qs,{}):s.jsx(cs,{})})]}),u&&s.jsx("div",{className:"skillcard-body",children:s.jsx(Ot,{text:e.content})})]})}function Ja({block:e,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:a,isLast:c,onKillBash:l,thinkingWrap:u,toolsWrap:d,searchActive:m,role:f,showCopy:h}){const b=He(),[E,N]=o.useState(!1),g=Ls(e);if(g){const Y=a&&c,q=(f==="assistant"||f==="user")&&h!==!1,C=q&&!g.text.includes(`
|
|
342
|
+
`)&&!g.truncated,Te=f==="user"?s.jsx(Ot,{text:g.text,hardBreaks:!0}):Y?s.jsx(M0,{text:g.text}):s.jsx(Ot,{text:g.text});return s.jsxs("div",{className:`msg-text${C?" single":""}`,children:[C?s.jsx("div",{className:"msg-text-main",children:Te}):s.jsxs(s.Fragment,{children:[Te,g.truncated&&s.jsx("div",{className:"trunc-note",children:b("truncated")})]}),q?s.jsx("button",{type:"button",className:"msg-text-copy",title:b(E?"copied":"copyMessage"),"aria-label":b("copyMessage"),onClick:()=>{navigator.clipboard.writeText(g.text),N(!0),window.setTimeout(()=>N(!1),1200)},children:E?s.jsx(Qs,{}):s.jsx(cs,{})}):null]})}const R=Qc(e);if(R)return s.jsx(B0,{thinking:R.thinking,streaming:a&&c,wrap:u,forceOpen:m});const M=Xc(e);if(M){const Y=t.get(M.id),q=n.get(M.id),C={result:Y,liveOutput:q?.text,streaming:a,status:r.get(M.id)};return s.jsx(eb,{block:M,view:C,onKillBash:l,wrap:d,forceOpen:m})}const B=Jc(e);if(B&&B.dataUrl)return s.jsx("div",{className:"msg-image",children:s.jsx("img",{src:B.dataUrl,alt:"attachment"})});const j=Zc(e);return j?s.jsxs("div",{className:"bashblock",children:[s.jsxs("div",{className:"bashblock-command",children:[s.jsx("span",{className:"bashblock-prompt",children:"$"}),s.jsx("code",{children:j.command}),j.exitCode!==void 0&&s.jsx("span",{className:`bashblock-exit ${j.exitCode===0?"ok":"err"}`,children:b("exitCode",{code:j.exitCode})}),j.cancelled&&s.jsx("span",{className:"bashblock-exit err",children:b("cancelled")})]}),j.output&&s.jsx("pre",{className:"bashblock-output",children:j.output}),j.truncated&&s.jsx("div",{className:"trunc-note",children:b("outputTruncated")})]}):null}function Fr(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 eu(e){const t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0");return`${n}:${r}`}function Bo(e,t,n){let r=!1;for(const a of t){const c=a;if(c.type!=="image"||typeof c.dataUrl!="string"||!c.dataUrl.startsWith("data:"))continue;const l=c.dataUrl.match(/^data:([^;]*);base64,(.+)$/);l&&(r=!0,e.push({path:"",imageData:l[2],mimeType:l[1]||"image/png",name:n??`image.${(l[1]||"image/png").split("/")[1]??"png"}`}))}return r}function bb(e){const t=new Map;for(let n=0;n<e.length;n++){const r=e[n];if(r.role!=="user"||!r.id)continue;const a=[];Bo(a,r.content);for(let c=n+1;c<e.length&&e[c].role==="custom"&&e[c].customType==="file";c++){const l=e[c].details??{};if(!Bo(a,e[c].content,l.name)){if(l.upload&&l.path){a.push({path:"",uploadPath:l.path,name:l.name??l.path,size:l.size});continue}if(l.mode==="page"&&l.path){a.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",d={path:l.path,mode:u};l.mode==="lines"&&typeof l.startLine=="number"&&typeof l.endLine=="number"&&(d.lines={start:l.startLine,end:l.endLine}),a.push(d)}}}a.length>0&&t.set(r.id,a)}return t}const xb=o.memo(function({message:t,onExpand:n}){const r=He();let a="";for(const h of t.content){const b=Ls(h);if(b&&b.text.trim()){const E=ai(b.text);E?a=`skill:${E.name}`+(E.userMessage?` · ${E.userMessage.replace(/\s+/g," ").trim()}`:""):a=b.text.replace(/\s+/g," ").trim();break}}if(!a&&t.role==="custom"&&t.customType==="file"){const h=t.details??{};a=h.name??h.path??""}a.length>90&&(a=`${a.slice(0,90)}…`);let l=0,u=0,d=0,m=0;for(const h of t.content)Qc(h)?l++:Xc(h)?u++:Zc(h)?d++:Jc(h)&&m++;const f=[];return l&&f.push(`${r("thinking")} ${l}`),u&&f.push(`${r("toolCalls")} ${u}`),d&&f.push(`${r("bashRuns")} ${d}`),m&&f.push(`${r("images")} ${m}`),s.jsxs("div",{role:"button",tabIndex:0,className:"msg-collapsed","data-msg-id":t.id,title:`${r("expandMsg")} · ${a||f.join(" · ")||t.role}`,onClick:()=>n(t.id),onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),n(t.id))},children:[s.jsx("span",{className:`msg-collapsed-role role-${t.role}`,children:t.role==="custom"&&t.customType==="file"?r("attachment"):Fr(t.role,r)}),s.jsxs("span",{className:"msg-collapsed-body",children:[a&&s.jsx("span",{className:"msg-collapsed-preview",children:a}),f.length>0&&s.jsx("span",{className:"msg-collapsed-chips",children:f.map((h,b)=>s.jsx("span",{className:"msg-collapsed-chip",children:h},b))})]}),t.timestamp?s.jsx("span",{className:"msg-collapsed-time",children:Eb(t.timestamp)}):null,s.jsxs("span",{className:"msg-collapsed-action",children:[s.jsx(Os,{})," ",r("expandMsg")]})]})});function Eb(e){const t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0");return`${n}:${r}`}const yb=o.memo(function({id:t,show:n,height:r,containerRef:a,onMeasured:c,lazyRef:l,children:u}){const d=o.useRef(null),m=o.useRef(null);return o.useLayoutEffect(()=>{const f=m.current;if(m.current=n,!n||f!==!1)return;const h=d.current,b=a.current;if(!h||!b)return;const E=h.offsetHeight;c?.(t,E);const N=E-r;if(N!==0){const g=h.parentElement;g&&g.getBoundingClientRect().bottom<=b.getBoundingClientRect().top&&(b.scrollTop+=N)}},[n]),n?s.jsx("div",{ref:l,"data-lazy-id":t,children:s.jsx("div",{ref:d,children:u})}):s.jsx("div",{ref:l,className:"msg-lazy-ph","data-msg-id":t,"data-lazy-id":t,style:{height:r},"aria-hidden":"true"})});function Tb(e,t,n,r){const a=[],c=[];let l=0;for(const u of e){if(n.has(u.id))continue;u.top<t.bottom&&u.bottom>t.top?r.has(u.id)&&a.push(u.id):r.has(u.id)||(c.push(u.id),u.bottom<=t.top&&(l+=u.bottom-u.top))}return{show:a,hide:c,shrinkAbove:l}}function kb(e,t){if(t.show.length===0&&t.hide.length===0)return e;const n=new Set(e);for(const r of t.show)n.delete(r);for(const r of t.hide)n.add(r);return n}function Nb(e,t,n){const r=new Set;let a=0;for(let c=e.length-1;c>=0&&!(c<e.length-1&&a>=n);c--){const l=e[c];r.add(l.id),a+=t.get(l.id)??tu(l.role,l.customType)}return r}function tu(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 vb=["text","thinking","argumentsText","output","command"];function Cb(e){let t=0;for(const n of e.content){n.type==="image"&&(t+=1);for(const r of vb){const a=n[r];typeof a=="string"&&(t+=a.length)}}return t}function wb(e,t,n,r){const a=n.get(e);return a&&a.len===t?a.h:r}function Sb(e){const t=[];for(const n of e.content)n.type==="text"&&typeof n.text=="string"&&t.push(n.text);return t.join(`
|
|
343
|
+
`)}function _b(e,t){const n=[];for(const r of e.content)if(r.type==="text"&&typeof r.text=="string")n.push(r.text);else if(r.type==="thinking"&&typeof r.thinking=="string")n.push(r.thinking);else if(r.type==="toolCall"){if(typeof r.name=="string"&&n.push(r.name),typeof r.argumentsText=="string"&&n.push(r.argumentsText),typeof r.id=="string"){const a=t.get(r.id);if(a){const c=Sb(a);c&&n.push(c)}}}else r.type==="bash"&&(typeof r.command=="string"&&n.push(r.command),typeof r.output=="string"&&n.push(r.output));return n.join(`
|
|
344
|
+
`)}function Ab(e,t){let n=0,r=e.indexOf(t);for(;r!==-1;)n++,r=e.indexOf(t,r+t.length);return n}function jb(e,t,n,r){const a=new Map,c=n.toLowerCase();if(!c)return a;for(const l of e){if(!t.has(l.id))continue;const u=Ab(_b(l,r).toLowerCase(),c);u>0&&a.set(l.id,u)}return a}function Ib(e,t){const n=[],r=t.toLowerCase();if(!r)return n;const a=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(c){const l=c.parentElement;return!l||l.closest(".search-bar")||l.closest(".msg-collapsed")?NodeFilter.FILTER_REJECT:(c.textContent??"").toLowerCase().includes(r)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let c=a.nextNode();c;c=a.nextNode()){const l=(c.textContent??"").toLowerCase();if(!c.parentElement?.closest("[data-msg-id]"))continue;let u=l.indexOf(r);for(;u!==-1;){const d=document.createRange();d.setStart(c,u),d.setEnd(c,u+r.length),n.push(d),u=l.indexOf(r,u+r.length)}}return n}function Rb(e,t,n,r,a){const c=jb(n,r,t,a),l=new Map;for(const d of Ib(e,t)){const m=d.startContainer.parentElement?.closest("[data-msg-id]");if(!m?.dataset.msgId)continue;const f=l.get(m.dataset.msgId);f?f.push(d):l.set(m.dataset.msgId,[d])}const u=[];for(const d of n){const m=l.get(d.id);if(m)for(let h=0;h<m.length;h++)u.push({kind:"dom",range:m[h],msgId:d.id,k:h});const f=c.get(d.id);if(f)for(let h=0;h<f;h++)u.push({kind:"folded",msgId:d.id,k:h})}return u}function Za(e,t){return e.findIndex(n=>n.msgId===t.msgId&&n.k===t.k)}function es(e,t){const n=CSS;if(!n.highlights)return;if(t.length===0){n.highlights.delete(e);return}const r=window.Highlight;r&&n.highlights.set(e,new r(...t))}function Pb(e,t){const n=[];let r=e;for(;r&&r!==t;){const a=getComputedStyle(r);/(auto|scroll|hidden)/.test(a.overflowY+a.overflowX)&&(r.scrollHeight>r.clientHeight||r.scrollWidth>r.clientWidth)&&n.push(r),r=r.parentElement}return n}function Lb(e,t){const n=t.startContainer.parentElement;for(const u of Pb(n,e)){const d=t.getBoundingClientRect(),m=u.getBoundingClientRect();if(d.height<=0||d.width<=0)return;d.top>=m.top+4&&d.bottom<=m.bottom-4||(u.scrollTop+=d.top-m.top-(u.clientHeight-d.height)/2),d.left>=m.left+4&&d.right<=m.right-4||(u.scrollLeft+=d.left-m.left-(u.clientWidth-d.width)/2)}const r=t.getBoundingClientRect(),a=e.getBoundingClientRect();if(r.height<=0||r.width<=0)return;const c=r.top>=a.top+6&&r.bottom<=a.bottom-6,l=r.left>=a.left+6&&r.right<=a.right-6;c&&l||(c||(e.scrollTop+=r.top-a.top-(a.height-r.height)/2),l||(e.scrollLeft+=r.left-a.left-(a.width-r.width)/2))}function Db({containerRef:e,messages:t,collapsedIds:n,toolResults:r,onExpand:a,onProgrammaticScroll:c,open:l,onClose:u}){const d=He(),m=o.useRef(null),[f,h]=o.useState(""),[b,E]=o.useState(null),[N,g]=o.useState(0),[,R]=o.useState(0),M=o.useDeferredValue(f),B=l?M.trim():"",j=o.useRef(null);j.current=b;const Y=o.useRef([]),q=o.useRef({key:null}),C=o.useRef("");o.useEffect(()=>{l&&(E(null),requestAnimationFrame(()=>m.current?.select()))},[l]),o.useEffect(()=>{if(!l)return;const G=ee=>{ee.key==="Escape"&&(ee.preventDefault(),ee.stopPropagation(),u())};return window.addEventListener("keydown",G,!0),()=>window.removeEventListener("keydown",G,!0)},[l,u]),o.useEffect(()=>(l||(es("msg-search",[]),es("msg-search-active",[])),()=>{es("msg-search",[]),es("msg-search-active",[])}),[l]),o.useLayoutEffect(()=>{const G=()=>{g(0),E(null),R(0),Y.current=[],es("msg-search",[]),es("msg-search-active",[]),q.current={key:null},C.current=""};if(!l||!B){G();return}const ee=e.current;if(!ee)return;let Q=!1,O=0;return O=requestAnimationFrame(()=>{if(Q)return;const F=Rb(ee,B,t,n,r);Y.current=F;const w=F.length;if(g(w),w===0){E(null),R(0),es("msg-search",[]),es("msg-search-active",[]),q.current={key:null},C.current=B;return}const se=j.current;let z;if(se){if(z=Za(F,se),z===-1){const I=[];for(let he=0;he<F.length;he++)F[he].msgId===se.msgId&&I.push(he);if(I.length>0){const he=Math.min(se.k,I.length-1);z=I[he]}else z=0}}else z=0;z<0&&(z=0),z>=w&&(z=w-1),(!se||se.msgId!==F[z].msgId||se.k!==F[z].k)&&E({msgId:F[z].msgId,k:F[z].k}),R(z);const A=F[z],ue=q.current,P=ue.key?.msgId!==A.msgId||ue.key?.k!==A.k||ue.kind==="folded"&&A.kind==="dom"||B!==C.current;q.current={key:{msgId:A.msgId,k:A.k},kind:A.kind},C.current=B;const ie=F.filter(I=>I.kind==="dom").map(I=>I.range);if(es("msg-search",ie),A.kind==="folded"){es("msg-search-active",[]),P&&a(A.msgId);return}es("msg-search-active",[A.range]),P&&(c?.(),Lb(ee,A.range))}),()=>{Q=!0,cancelAnimationFrame(O)}},[l,B,t,e,b,n,r,a,c]);const Te=o.useCallback(G=>{const ee=Y.current,Q=ee.length;if(Q===0)return;const O=j.current,F=O?Za(ee,O):0,w=ee[(F+G+Q)%Q];E(w.kind==="dom"||w.kind==="folded"?{msgId:w.msgId,k:w.k}:null)},[]);if(!l)return null;const xe=b?(()=>{const G=Za(Y.current,b);return G===-1?0:G})():0;return s.jsxs("div",{className:"search-bar",role:"search",children:[s.jsx("input",{ref:m,className:"search-input",type:"text",value:f,placeholder:d("searchPlaceholder"),onChange:G=>{h(G.target.value)},onKeyDown:G=>{G.key==="Enter"&&(G.preventDefault(),Te(G.shiftKey?-1:1))}}),s.jsx("span",{className:`search-count ${N===0?"empty":""}`,children:N===0?d("searchNoResults"):`${Math.min(xe+1,N)}/${N}`}),s.jsx("button",{type:"button",className:"search-btn",title:d("searchPrev"),disabled:N===0,onClick:()=>Te(-1),children:s.jsx(Ra,{})}),s.jsx("button",{type:"button",className:"search-btn",title:d("searchNext"),disabled:N===0,onClick:()=>Te(1),children:s.jsx(ks,{})}),s.jsx("button",{type:"button",className:"search-btn",title:d("searchClose"),onClick:u,children:s.jsx(bt,{})})]})}function Ob(e){const{dSt:t,dSh:n,escaped:r,graceActive:a,stuck:c}=e;return a?{flipEscape:!1,reassert:!1}:t>=-4||t<=-500?{flipEscape:!1,reassert:!1}:n<0?{flipEscape:!1,reassert:c&&!r}:{flipEscape:!0,reassert:!1}}const su="pi-web-model-usage";function Mb(e){if(!e||typeof e!="object")return{};const t={};for(const[n,r]of Object.entries(e)){const a=typeof r=="number"?Math.floor(r):0;Number.isFinite(a)&&a>0&&(t[n]=a)}return t}function Bb(e,t){return t?{...e,[t]:(e[t]??0)+1}:e}function Fb(e,t){const n=t;return e.map((r,a)=>({m:r,i:a,count:n[r.id]??0})).sort((r,a)=>a.count-r.count||r.i-a.i).map(r=>r.m)}function nu(){try{const e=localStorage.getItem(su);return e?Mb(JSON.parse(e)):{}}catch{return{}}}function Hb(e){try{localStorage.setItem(su,JSON.stringify(e))}catch{}}function wa(e){const t=Bb(nu(),e);return Hb(t),t}const au=[{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"}],ru="pi-web-ui:prompt-templates";function Ub(){try{const e=localStorage.getItem(ru);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 Fo(e){return au.some(t=>t.id===e)}function Wn(e){return typeof e.title=="string"}const iu=o.createContext(null);function ou(){const e=o.useContext(iu);if(!e)throw new Error("useTemplates must be used within TemplateProvider");return e}function $b({children:e,currentModelId:t}){const n=He(),[r,a]=o.useState(Ub),[c,l]=o.useState(!1),[u,d]=o.useState(null),[m,f]=o.useState(!1),[h,b]=o.useState(!1),[E,N]=o.useState(!1);o.useEffect(()=>{try{localStorage.setItem(ru,JSON.stringify(r))}catch{}},[r]);const g=o.useMemo(()=>{const F=new Map,w=new Set;for(const A of r)A.hidden?w.add(A.id):(Wn(A)&&!Fo(A.id)||Wn(A))&&F.set(A.id,A);const se=au.filter(A=>!w.has(A.id)).map(A=>{const ue=F.get(A.id);return{id:A.id,icon:ue?.icon??A.icon,title:ue?.title??n(A.titleKey),desc:ue?.desc??n(A.descKey),prompt:ue?.prompt??n(A.promptKey),builtin:!0}}),z=r.filter(A=>Wn(A)&&!Fo(A.id)).map(A=>({id:A.id,icon:A.icon??"📌",title:A.title??"",desc:A.desc??"",prompt:A.prompt??""}));return[...se,...z]},[r,n]),R=o.useCallback(()=>l(!0),[]),M=o.useCallback(F=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:F}))},[]),B=o.useCallback((F,w=!1)=>{N(w),F?(f(!1),d({...F})):(f(!0),d({id:qt(),icon:"📌",title:"",desc:"",prompt:""}))},[]),j=o.useCallback(()=>{l(!1),d(null),N(!1)},[]),Y=o.useCallback(()=>{h?(a([]),b(!1)):(b(!0),setTimeout(()=>b(!1),5e3))},[h]),q=o.useCallback(F=>{l(!1),M(F.prompt)},[M]),C=o.useCallback(F=>{l(!1),B(F,!0)},[B]),Te=o.useCallback(()=>{l(!1),B(void 0,!0)},[B]),xe=o.useCallback(F=>{a(w=>{const se=w.findIndex(z=>z.id===F.id);if(se>=0){const z=[...w];return z[se]=F,z}return[...w,F]}),d(null),E&&(l(!0),N(!1))},[E]),G=o.useCallback(F=>{a(w=>F.builtin?[...w.filter(z=>z.id!==F.id),{id:F.id,hidden:!0}]:w.filter(se=>se.id!==F.id)),d(null),E&&(l(!0),N(!1))},[E]),ee=o.useCallback(F=>{a(w=>w.filter(se=>se.id!==F.id||se.hidden)),d(null),E&&(l(!0),N(!1))},[E]),Q=o.useMemo(()=>({templates:g,fill:M,openPicker:R,openEdit:B,resetConfirm:h,toggleReset:Y}),[g,M,R,B,h,Y]),O=u?r.some(F=>F.id===u.id&&!F.hidden&&Wn(F)):!1;return s.jsxs(iu.Provider,{value:Q,children:[e,c&&s.jsx(Wb,{templates:g,resetConfirm:h,onFill:q,onEditTpl:C,onNew:Te,onResetToggle:Y,onClose:j}),u&&s.jsx(Kb,{editing:u,isNew:m,hasOverride:O,onDraft:d,onSave:xe,onRestore:()=>ee(u),onRemove:()=>G(u),onFill:()=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:u.prompt})),j()},onSend:()=>{const F=u.prompt.trim();F&&J({type:"prompt",text:F,queue:!1})&&(t&&wa(t),j())},onClose:j})]})}function qb(){const e=He(),{templates:t,fill:n,openEdit:r,toggleReset:a,resetConfirm:c}=ou();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(lu,{tpl:l,title:e("tpl.clickCard"),onFill:()=>n(l.prompt),onEdit:()=>r(l),editTitle:e("tpl.editTpl")},l.id)),s.jsxs("button",{type:"button",className:"empty-template add",onClick:()=>r(),title:e("tpl.add"),children:[s.jsx("span",{className:"empty-template-icon",children:s.jsx(Dt,{})}),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:a,children:[s.jsx(yl,{}),e(c?"tpl.resetConfirm":"tpl.reset")]})})]})}function lu({tpl:e,title:t,onFill:n,onEdit:r,editTitle:a}){const c=He();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:a??c("tpl.editTpl"),onClick:l=>{l.stopPropagation(),r()},children:s.jsx(zs,{})})]})}function Wb({templates:e,resetConfirm:t,onFill:n,onEditTpl:r,onNew:a,onResetToggle:c,onClose:l}){const u=He();return o.useEffect(()=>{const d=m=>{m.key==="Escape"&&l()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[l]),s.jsx("div",{className:"modal-backdrop",onClick:l,children:s.jsxs("div",{className:"modal template-picker",onClick:d=>d.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(bt,{})})]}),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(d=>s.jsx(lu,{tpl:d,title:u("tpl.clickCard"),onFill:()=>n(d),onEdit:()=>r(d),editTitle:u("tpl.editTpl")},d.id)),s.jsxs("button",{type:"button",className:"empty-template add",onClick:a,title:u("tpl.add"),children:[s.jsx("span",{className:"empty-template-icon",children:s.jsx(Dt,{})}),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:c,children:[s.jsx(yl,{}),u(t?"tpl.resetConfirm":"tpl.reset")]})})]})})}function Kb({editing:e,isNew:t,hasOverride:n,onDraft:r,onSave:a,onRestore:c,onRemove:l,onFill:u,onSend:d,onClose:m}){const f=He(),h=o.useRef(null);o.useEffect(()=>{const N=g=>{g.key==="Escape"&&m()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[m]),o.useEffect(()=>{const N=h.current;if(!N)return;N.style.height="auto";const g=N.scrollHeight>300;N.style.height=`${Math.min(N.scrollHeight,300)}px`,N.style.overflowY=g?"auto":"hidden"},[e.prompt]);const b=()=>{const N=e.title.trim(),g=e.prompt.trim();if(!N||!g){r({...e,error:f("tpl.required")});return}a({id:e.id,icon:e.icon.trim()||"📌",title:N,desc:e.desc.trim(),prompt:g})},E=!!e.builtin&&!t;return s.jsx("div",{className:"modal-backdrop",onClick:m,children:s.jsxs("div",{className:"modal template-modal",onClick:N=>N.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:f(E?"tpl.builtin":"tpl.custom")}),s.jsx("span",{className:"template-modal-title",children:f(t?"tpl.newTitle":"tpl.editTitle")}),s.jsx("button",{type:"button",className:"btn template-modal-close",title:f("close"),onClick:m,children:s.jsx(bt,{})})]}),s.jsxs("div",{className:"template-modal-body",children:[s.jsxs("label",{className:"template-field",children:[s.jsx("span",{className:"template-field-label",children:f("tpl.fieldIcon")}),s.jsx("input",{className:"template-field-input icon",value:e.icon,maxLength:4,onChange:N=>r({...e,icon:N.target.value})})]}),s.jsxs("label",{className:"template-field",children:[s.jsx("span",{className:"template-field-label",children:f("tpl.fieldTitle")}),s.jsx("input",{className:"template-field-input",value:e.title,placeholder:f("tpl.fieldTitlePh"),onChange:N=>r({...e,title:N.target.value})})]}),s.jsxs("label",{className:"template-field",children:[s.jsx("span",{className:"template-field-label",children:f("tpl.fieldDesc")}),s.jsx("input",{className:"template-field-input",value:e.desc,placeholder:f("tpl.fieldDescPh"),onChange:N=>r({...e,desc:N.target.value})})]}),s.jsxs("label",{className:"template-field",children:[s.jsx("span",{className:"template-field-label",children:f("tpl.fieldPrompt")}),s.jsx("textarea",{ref:h,className:"template-field-prompt",value:e.prompt,placeholder:f("tpl.fieldPromptPh"),onChange:N=>r({...e,prompt:N.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&&E&&n&&s.jsx("button",{type:"button",className:"btn template-btn ghost",title:f("tpl.restoreTip"),onClick:c,children:f("tpl.restore")}),!t&&E&&s.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:f("tpl.removeTip"),onClick:l,children:[s.jsx(Rt,{})," ",f("tpl.remove")]}),!t&&!E&&s.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:f("tpl.deleteTip"),onClick:l,children:[s.jsx(Rt,{})," ",f("tpl.delete")]})]}),s.jsxs("div",{className:"template-modal-actions-right",children:[s.jsx("button",{type:"button",className:"btn template-btn",onClick:b,children:f("tpl.save")}),s.jsx("button",{type:"button",className:"btn template-btn fill",onClick:u,title:f("tpl.fillTip"),children:f("tpl.fill")}),s.jsxs("button",{type:"button",className:"btn template-btn send",onClick:d,title:f("tpl.sendTip"),children:[s.jsx(lr,{})," ",f("tpl.sendNow")]})]})]})]})})}const Ho=new Map,Gb=15,Uo=30,er=250,$o=1200,Yb=1600;function qo({kind:e,text:t,onRemoveQueued:n,onRecallQueued:r}){const a=He();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:a("role.user")}),s.jsx("span",{className:`queued-tag ${e==="steer"?"steer":"follow"}`,children:a(e==="steer"?"queueSteerTag":"queueFollowTag")}),s.jsxs("div",{className:"msg-queued-actions",children:[r&&s.jsx("button",{type:"button",className:"msg-queued-recall",title:a("queueRecallTip"),"aria-label":a("queueRecallTip"),onClick:()=>r(e,t),children:"↩"}),n&&s.jsx("button",{type:"button",className:"msg-queued-remove",title:a("queueRemoveTip"),"aria-label":a("queueRemoveTip"),onClick:()=>n(e,t),children:"✕"})]})]}),s.jsx("div",{className:"msg-body",children:s.jsx("div",{className:"msg-text",children:s.jsx(Ot,{text:t,hardBreaks:!0})})})]})}function zb({compaction:e}){const t=He(),[,n]=o.useState(0);o.useEffect(()=>{const c=setInterval(()=>n(l=>l+1),1e3);return()=>clearInterval(c)},[]);const r=Math.max(0,Math.floor((Date.now()-e.startedAt)/1e3)),a=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")," · ",r,"s"]}),s.jsx("span",{className:"compact-reason",children:a})]})}function Wo(e){return e.content.some(t=>t.type==="toolCall")}function Vb({state:e,liveOutputs:t,toolStatuses:n,onEdit:r,onKillBash:a,onRetry:c,onRemoveQueued:l,onRecallQueued:u,thinkingWrap:d,toolsWrap:m,jumpTarget:f,onJumpDone:h,uiMessageActions:b,uiContextMessage:E,onUiAction:N}){const g=He(),R=o.useRef(null),[M,B]=o.useState(!0),j=o.useRef(!0),Y=o.useRef(0),q=o.useRef(0),C=o.useRef(!1),Te=o.useRef(0),[xe,G]=o.useState(()=>new Set),[ee,Q]=o.useState(!1),O=e.streamingMessage?[...e.messages,e.streamingMessage]:e.messages,F=o.useMemo(()=>{const $=new Map;for(const Z of e.messages)Z.role==="toolResult"&&Z.toolCallId&&$.set(Z.toolCallId,Z);return $},[e.messages]),w=o.useMemo(()=>bb(e.messages),[e.messages]),se=O.length>0?O[O.length-1].id:null,z=e.messages.length>Uo?Math.max(0,e.messages.length-Gb):0,A=o.useMemo(()=>{const $=new Set;for(let Z=0;Z<z;Z++){const Re=e.messages[Z];Re.role!=="toolResult"&&(xe.has(Re.id)||$.add(Re.id))}return $},[e.messages,z,xe]),[ue,P]=o.useState(()=>new Set),[ie,I]=o.useState(()=>new Set),he=o.useRef(new Map),_=o.useRef(new Map),re=o.useRef(new Map),le=o.useRef(0),Ee=o.useMemo(()=>{const $=new Map;for(const Z of e.messages)$.set(Z.id,Cb(Z));return $},[e.messages]),Ne=o.useRef(Ee);Ne.current=Ee;const Ue=o.useRef(ue);Ue.current=ue;const ke=e.messages.length>Uo&&!ee,Ke=o.useRef(ke);Ke.current=ke;const Ie=Nb(e.messages,he.current,Yb),ce=o.useRef(Ie);ce.current=Ie;const pe=o.useCallback(()=>{const $=R.current;if(!$)return;if(!Ke.current){P(qe=>qe.size?new Set:qe);return}const Z=$.getBoundingClientRect(),Re={top:Z.top-$o,bottom:Z.bottom+$o},je=[];for(const[qe,At]of re.current){const Lt=At.getBoundingClientRect();je.push({id:qe,top:Lt.top,bottom:Lt.bottom}),Ue.current.has(qe)||et(qe,Lt.bottom-Lt.top,Ne.current.get(qe))}const Je=Tb(je,Re,ce.current,Ue.current);for(const qe of Je.hide){const At=re.current.get(qe);At&&et(qe,At.offsetHeight,Ne.current.get(qe))}P(qe=>kb(qe,Je))},[]),Fe=o.useCallback(()=>{le.current||(le.current=requestAnimationFrame(()=>{le.current=0,pe()}))},[pe]);o.useLayoutEffect(()=>{pe()},[pe]);const Ae=o.useRef(ee);o.useLayoutEffect(()=>{Ae.current&&!ee&&pe(),Ae.current=ee},[ee,pe]);const et=o.useCallback(($,Z,Re)=>{Re!==void 0&&(_.current.set($,{h:Z,len:Re}),he.current.set($,Z))},[]),dt=o.useCallback(($,Z)=>{et($,Z,Ne.current.get($))},[et]),Ve=o.useCallback($=>{$&&re.current.set($.dataset.lazyId??"",$)},[]);o.useEffect(()=>{const $=new Set(e.messages.map(Z=>Z.id));for(const Z of re.current.keys())$.has(Z)||(re.current.delete(Z),he.current.delete(Z),_.current.delete(Z));P(Z=>{let Re=!1;const je=new Set;for(const Je of Z)$.has(Je)?je.add(Je):Re=!0;return Re?je:Z})},[e.messages,xe]),o.useEffect(()=>()=>cancelAnimationFrame(le.current),[]);const X=o.useMemo(()=>{const $=[];for(const Z of e.messages){if(Z.role!=="user")continue;const Re=Z.content.map(qe=>Ls(qe)?.text??"").filter(Boolean).join(" "),je=ai(Re),Je=je?je.userMessage??`skill:${je.name}`:Re.trim();Je&&$.push({id:Z.id,text:Je})}return $},[e.messages]),we=o.useMemo(()=>{const $=new Map;return X.forEach((Z,Re)=>$.set(Z.id,Re)),$},[X]),[L,W]=o.useState(-1),oe=o.useRef(-1),fe=o.useRef(X);o.useEffect(()=>{fe.current=X},[X]);const de=o.useCallback(()=>{const $=R.current,Z=fe.current;if(!$||Z.length===0)return;const Re=$.getBoundingClientRect().top,je=140;let Je=-1;for(let qe=0;qe<Z.length;qe++){const At=$.querySelector(`[data-msg-id="${Z[qe].id}"]`);if(At)if(At.getBoundingClientRect().top<=Re+je)Je=qe;else break}Je!==oe.current&&(oe.current=Je,W(Je))},[]);o.useEffect(()=>{de()},[X,de]);const ge=o.useCallback($=>{G(Z=>Z.has($)?Z:new Set(Z).add($))},[]);o.useEffect(()=>{const $=Z=>{if(!(Z.ctrlKey||Z.metaKey)||Z.key.toLowerCase()!=="f")return;const Re=Z.target;Re&&(Re.tagName==="INPUT"||Re.tagName==="TEXTAREA"||Re.isContentEditable)||(Z.preventDefault(),Q(!0))};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[]);const Qe=o.useCallback($=>{G(Z=>{if(!Z.has($))return Z;const Re=new Set(Z);return Re.delete($),Re})},[]),ye=o.useCallback($=>{const Z=e.messages.findIndex(je=>je.id===$);In.flushSync(()=>{Z>=0&&Z<z&&!xe.has($)&&ge($),I(je=>je.has($)?je:new Set(je).add($))});const Re=fe.current.findIndex(je=>je.id===$);oe.current=Re,W(Re),requestAnimationFrame(()=>{const je=R.current?.querySelector(`[data-msg-id="${$}"]`);je&&(R.current?.querySelectorAll(".msg-flash").forEach(Je=>Je.classList.remove("msg-flash")),je.scrollIntoView({block:"start"}),je.classList.remove("msg-flash"),je.offsetWidth,je.classList.add("msg-flash"),je!==R.current?.lastElementChild&&(C.current=!0))})},[e.messages,z,xe,ge]),[Oe,rt]=o.useState(null),Ge=o.useRef(null),D=o.useRef(null);o.useEffect(()=>{const $=Ge.current;if(!$||$.convId!==e.conversationId){Ge.current={convId:e.conversationId,ids:new Set(e.messages.filter(Z=>Z.role==="compactionSummary").map(Z=>Z.id))},D.current=null,rt(null);return}for(const Z of e.messages)if(Z.role==="compactionSummary"&&!$.ids.has(Z.id)){$.ids.add(Z.id),rt(Z.id);break}},[e.messages,e.conversationId]),o.useEffect(()=>{!Oe||D.current===Oe||(D.current=Oe,ye(Oe))},[Oe,ye]);const $e=o.useMemo(()=>f?e.messages.find($=>$.role===f.role&&$.timestamp===f.timestamp)?.id??null:null,[e.messages,f]);o.useEffect(()=>{if(f){if($e){ye($e),h?.();return}e.sessionFile===f.path&&e.messages.length>0&&h?.()}},[$e,ye,h,f,e.sessionFile,e.messages.length]);const it=o.useCallback(()=>{const $=R.current;if(!$)return;const Z=$.scrollTop-Y.current,Re=$.scrollHeight-q.current;Y.current=$.scrollTop,q.current=$.scrollHeight;const je=$.scrollHeight-$.scrollTop-$.clientHeight<80,Je=Date.now()<Te.current,qe=Ob({dSt:Z,dSh:Re,escaped:C.current,graceActive:Je,stuck:j.current});qe.reassert&&(Te.current=Date.now()+er,$.scrollTop=$.scrollHeight),qe.flipEscape&&(C.current=!0),je&&Z>=0&&(C.current=!1),Je||(Z<0?j.current=je&&!C.current:je&&(j.current=!0)),B(j.current),de(),Fe()},[de,Fe]),Xe=o.useRef(!1);o.useEffect(()=>{const $=Xe.current;if(Xe.current=!!e.isStreaming,$&&!e.isStreaming&&!C.current){const Z=()=>{const je=R.current;je&&!C.current&&(je.scrollTop=je.scrollHeight,j.current=!0,B(!0))};requestAnimationFrame(()=>requestAnimationFrame(Z));const Re=setTimeout(Z,180);return()=>clearTimeout(Re)}},[e.isStreaming]),o.useEffect(()=>{const $=R.current;$&&j.current&&($.scrollTop=$.scrollHeight)},[O,e.isStreaming,t]);const U=e.queue.steering.join("\0")+""+e.queue.followUp.join("\0");o.useEffect(()=>{const $=R.current;$&&j.current&&($.scrollTop=$.scrollHeight)},[U]),o.useEffect(()=>{const $=R.current;if(!$||typeof ResizeObserver>"u")return;let Z=$.clientHeight;const Re=new ResizeObserver(()=>{const je=$.clientHeight,Je=je-Z;Z=je,Je>0&&($.scrollTop=Math.min($.scrollTop,$.scrollHeight-$.clientHeight))});return Re.observe($),()=>Re.disconnect()},[]),o.useEffect(()=>{const $=R.current;if(!$||typeof MutationObserver>"u")return;let Z=!1;const Re=new MutationObserver(()=>{Z||(Z=!0,requestAnimationFrame(()=>{Z=!1;const je=R.current;je&&j.current&&!C.current&&(je.scrollTop=je.scrollHeight,B(!0))}))});return Re.observe($,{childList:!0,subtree:!0,characterData:!0}),()=>Re.disconnect()},[]);const Pe=o.useCallback(()=>{if(!R.current)return;j.current=!0,C.current=!1,B(!0),Te.current=Date.now()+er;const Z=()=>{const Re=R.current;!Re||!j.current||C.current||(Te.current=Date.now()+er,Re.scrollTop=Re.scrollHeight)};Z(),requestAnimationFrame(()=>requestAnimationFrame(Z)),setTimeout(Z,120),setTimeout(Z,300),setTimeout(Z,600)},[]),Le=o.useRef(null);o.useEffect(()=>{const $=Le.current,Z=R.current;if(!$||!Z)return;const Re=je=>{je.preventDefault();const Je=$.querySelector(".qn-list");if(Je&&Je.contains(je.target)&&Je.scrollHeight>Je.clientHeight){Je.scrollTop+=je.deltaY;return}Z.scrollTop+=je.deltaY};return $.addEventListener("wheel",Re,{passive:!1}),()=>$.removeEventListener("wheel",Re)},[]);const[ot,Ye]=o.useState(0);o.useEffect(()=>{const $=()=>{Ye(R.current?.clientHeight??0),Fe()};return $(),window.addEventListener("resize",$),()=>window.removeEventListener("resize",$)},[Fe]);const ct=X.length,mt=o.useMemo(()=>ct===0?27:Math.max(4,Math.min(27,Math.floor(((ot||600)-16)/ct)-3)),[ct,ot]),Mt=mt<20;return s.jsxs("div",{className:"messages-wrap",children:[s.jsxs("div",{className:`messages${ee||M?"":" anchor-live"}`,ref:R,onScroll:it,children:[e.messages.length===0&&!e.streamingMessage&&s.jsx("div",{className:"empty-state",children:s.jsx(qb,{})}),e.messages.map(($,Z)=>{const Re=Z<z,je=Re&&xe.has($.id);if(Re&&!je)return $.role==="toolResult"?null:s.jsx(xb,{message:$,onExpand:ge},$.id);const Je=$.role==="user"?we.get($.id):void 0,qe=!ke||Ie.has($.id)||ie.has($.id)||!ue.has($.id);return s.jsx(yb,{id:$.id,show:qe,height:wb($.id,Ee.get($.id)??-1,_.current,tu($.role,$.customType)),containerRef:R,onMeasured:dt,lazyRef:Ve,children:s.jsx(Oo,{uiMessageActions:b,uiContextMessage:E,onUiAction:N,message:$,qnIndex:Je,qnActive:Je!==void 0?Je===L:void 0,onJump:ye,toolResults:F,liveOutputs:Wo($)?t:Ho,toolStatuses:n,streaming:e.isStreaming,onKillBash:a,onRetry:$.id===se?c:void 0,toolsWrap:m,thinkingWrap:d,isLast:$.id===se,onEdit:r,questionAttachments:w.get($.id),onCollapse:je?Qe:void 0,searchActive:ee,autoExpand:$.id===Oe},$.id)},$.id)}),e.streamingMessage&&s.jsx(Oo,{uiMessageActions:b,uiContextMessage:E,onUiAction:N,message:e.streamingMessage,toolResults:F,liveOutputs:Wo(e.streamingMessage)?t:Ho,toolStatuses:n,streaming:!0,isLast:!0,onEdit:r,onKillBash:a,toolsWrap:m,thinkingWrap:d,searchActive:ee},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?g("retryingApi",{attempt:Math.max(1,e.retry.attempt),max:e.retry.maxAttempts,error:e.retry.errorMessage}):g("retryingApiSoon",{error:e.retry.errorMessage})})]}),e.compaction&&s.jsx(zb,{compaction:e.compaction}),e.isStreaming&&O.length===0&&s.jsx("div",{className:"streaming-wait",children:g("waitingResponse")}),e.queue.steering.map(($,Z)=>s.jsx(qo,{kind:"steer",text:$,onRemoveQueued:l,onRecallQueued:u},`q-steer-${Z}`)),e.queue.followUp.map(($,Z)=>s.jsx(qo,{kind:"followUp",text:$,onRemoveQueued:l,onRecallQueued:u},`q-fu-${Z}`))]}),!M&&s.jsxs("button",{type:"button",className:"scroll-bottom",onClick:Pe,children:[s.jsx(wl,{})," ",g("backToBottom")]}),s.jsx(Db,{containerRef:R,messages:O,collapsedIds:A,toolResults:F,onExpand:ge,onProgrammaticScroll:()=>{C.current=!0,j.current=!1,B(!1)},open:ee,onClose:()=>Q(!1)}),X.length>0&&s.jsxs("div",{className:`qn-rail ${Mt?"many":""}`,ref:Le,"aria-label":g("questionNavTitle"),style:{"--rail-gap":`${mt}px`},children:[X.map(($,Z)=>s.jsx("button",{type:"button",className:`qn-bar ${Z===L?"active":""}`,"aria-label":`${Z+1}. ${$.text}`,onClick:()=>ye($.id),children:s.jsxs("span",{className:"qn-bar-text",children:[Z+1,". ",$.text]})},$.id)),Mt&&s.jsx("div",{className:"qn-list",children:X.map(($,Z)=>s.jsxs("button",{type:"button",className:`qn-list-item ${Z===L?"active":""}`,"aria-label":`${Z+1}. ${$.text}`,onClick:()=>ye($.id),children:[s.jsx("span",{className:"qn-list-idx",children:Z+1}),s.jsx("span",{className:"qn-list-text",children:$.text})]},$.id))})]})]})}function Ko(e,t){return t?e.trim()?`${e.replace(/\s+$/,"")}
|
|
345
|
+
${t}`:t:e}function Go(e){return e.key?`key:${e.key}`:e.path?`${e.path}|${e.mode}|${e.lines?`${e.lines.start}-${e.lines.end}`:""}`:null}function Qb(e,t){if(t.length===0)return e;if(e.length===0)return[...t];const n=new Set(e.map(Go).filter(a=>a!==null)),r=[...e];for(const a of t){const c=Go(a);if(c!==null){if(n.has(c))continue;n.add(c)}r.push(a)}return r}const Xb=1,Jb="";function Zb(e,t,n=Xb){return{first:e<=n,last:Math.abs(t-e)<=n}}function e1(e,t){return{first:!e.slice(0,t).includes(`
|
|
346
|
+
`),last:!e.slice(t).includes(`
|
|
347
|
+
`)}}let tr=null;function t1(){if(tr?.isConnected)return tr;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),tr=e,e}function s1(e,t){const n=getComputedStyle(e),r=t.style;r.fontFamily=n.fontFamily,r.fontSize=n.fontSize,r.fontStyle=n.fontStyle,r.fontWeight=n.fontWeight,r.fontVariant=n.fontVariant,r.fontStretch=n.fontStretch,r.lineHeight=n.lineHeight,r.letterSpacing=n.letterSpacing,r.wordSpacing=n.wordSpacing,r.textTransform=n.textTransform,r.textIndent=n.textIndent,r.tabSize=n.tabSize,r.whiteSpace=n.whiteSpace||"pre-wrap",r.overflowWrap=n.overflowWrap||"break-word",r.wordBreak=n.wordBreak||"normal",r.direction=n.direction,r.writingMode=n.writingMode;const a=e.clientWidth-(parseFloat(n.paddingLeft)||0)-(parseFloat(n.paddingRight)||0);return a>0?(r.width=`${a}px`,a):0}function Yo(e,t){e.textContent=t;const n=document.createElement("span");return n.textContent=Jb,e.appendChild(n),n.offsetTop}function n1(e){const t=e.value,n=e.selectionStart;if(n!==e.selectionEnd)return{first:!1,last:!1};const r=e1(t,n);if(!r.first&&!r.last||typeof document>"u"||typeof getComputedStyle!="function")return r;const a=t1();if(s1(e,a)<=0)return r;const c=Yo(a,t.slice(0,n)),l=Yo(a,t),u=a.offsetHeight>0;return a.textContent="",!u&&t!==""?r:Zb(c,l)}const ii="pi-web-ui:prompt-history",a1=100,cu="pi-web-ui:prompt-history-settings",Hr={maxEntries:100,charLimitEnabled:!1,charLimit:2e3};function uu(e){const t=Hr;if(!e||typeof e!="object")return{...t};const n=e;let r=typeof n.maxEntries=="number"?Math.floor(n.maxEntries):t.maxEntries;(!Number.isFinite(r)||r<1)&&(r=1),r>500&&(r=500);let a=typeof n.charLimit=="number"?Math.floor(n.charLimit):t.charLimit;(!Number.isFinite(a)||a<100)&&(a=100),a>2e4&&(a=2e4);const c=typeof n.charLimitEnabled=="boolean"?n.charLimitEnabled:t.charLimitEnabled;return{maxEntries:r,charLimitEnabled:c,charLimit:a}}function du(){try{const e=localStorage.getItem(cu);return e?uu(JSON.parse(e)):{...Hr}}catch{return{...Hr}}}function sr(e){const t=uu(e);try{localStorage.setItem(cu,JSON.stringify(t))}catch{}try{let n=jn();t.charLimitEnabled&&(n=n.map(r=>r.length>t.charLimit?r.slice(0,t.charLimit):r)),n.length>t.maxEntries&&(n=n.slice(n.length-t.maxEntries)),pu(n)}catch{}}function r1(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(typeof n!="string")continue;const r=n.trim();r&&t.push(r)}return t}function i1(e,t,n=a1){const r=t.trim();if(!r||e.length>0&&e[e.length-1]===r)return e;const a=[...e,r];return a.length>n?a.slice(a.length-n):a}function jn(){try{const e=localStorage.getItem(ii);return e?r1(JSON.parse(e)):[]}catch{return[]}}function pu(e){let t=e;for(;t;)try{localStorage.setItem(ii,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 zo(e){let t=e.trim();if(!t)return;const n=du();n.charLimitEnabled&&t.length>n.charLimit&&(t=t.slice(0,n.charLimit));const r=jn(),a=i1(r,t,n.maxEntries);a!==r&&pu(a)}function o1(){try{localStorage.removeItem(ii)}catch{}}const Vo="skill:";function l1(e,t){const n=e.toLowerCase();return t==="skill"&&n.startsWith(Vo)?[n,n.slice(Vo.length)]:[n]}function c1(e,t){const n=t.toLowerCase();return n?e.filter(r=>l1(r.name,r.source).some(a=>a.startsWith(n))):[...e]}const u1=new Set(["p","page","pages","web","网页","页面"]);function d1(e,t,n,r=10){if(!Array.isArray(t))return[];const a=String(n??"").toLowerCase(),c=a===""||u1.has(a),l=[];for(const u of t){if(!u||typeof u.origin!="string"||!u.origin||u.open!==!0)continue;const d=typeof u.title=="string"&&u.title.trim()?u.title.trim():u.origin;if(!c&&!d.toLowerCase().includes(a)&&!u.origin.toLowerCase().includes(a))continue;const m=d.indexOf(" · "),f=m===-1?`page · ${d}`:`page · ${d.slice(m+3)}`;if(l.push({providerId:"host:pages",providerLabel:e,title:f,hint:u.origin,text:d,attachments:[{path:u.origin,name:d,mode:"page"}]}),l.length>=Math.max(0,r))break}return l}function p1(e,t,n=10){if(!Array.isArray(t))return[];const r=[];for(const a of t.slice(0,Math.max(0,n))){if(!a||typeof a!="object")continue;const c=a;typeof c.path!="string"||!c.path||typeof c.name!="string"||!c.name||r.push({providerId:"host:files",providerLabel:e,title:c.name,hint:c.path,text:c.name,attachments:[{path:c.path,name:c.name,mode:"reference",...c.type==="dir"?{isDir:!0}:{}}]})}return r}function m1(e,t,n,r=10){if(!Array.isArray(n))return[];const a=[];for(const c of n.slice(0,Math.max(0,r))){if(!c||typeof c!="object")continue;const l=c;if(typeof l.title!="string"||!l.title.trim())continue;const u=Array.isArray(l.attachments)?l.attachments.filter(d=>!!d&&typeof d=="object"&&typeof d.path=="string").slice(0,4).map(d=>{const m=d.mode;return{path:d.path,...typeof d.name=="string"?{name:d.name}:{},...m==="inline"||m==="reference"||m==="lines"||m==="page"?{mode:m}:{},...typeof d.isDir=="boolean"?{isDir:d.isDir}:{}}}):void 0;a.push({providerId:e,providerLabel:t,title:l.title.trim(),...typeof l.hint=="string"&&l.hint?{hint:l.hint}:{},...typeof l.text=="string"&&l.text?{text:l.text}:{},...u?.length?{attachments:u}:{}})}return a}function h1(e){return e===void 0?!0:!(e==="@"||/[A-Za-z0-9_]/.test(e))}function f1(e,t){const n=typeof e=="string"?e:"",r=Math.max(0,Math.min(typeof t=="number"&&Number.isFinite(t)?Math.floor(t):0,n.length)),a=n.slice(0,r),c=a.lastIndexOf("@");if(c===-1||!h1(c>0?a[c-1]:void 0))return null;const l=a.slice(c+1);return/[\s@]/.test(l)?null:{start:c,query:l}}function g1(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 b1(){return typeof window>"u"||typeof navigator>"u"||typeof window.matchMedia!="function"?!1:g1({query:e=>window.matchMedia(e).matches,userAgent:navigator.userAgent,maxTouchPoints:navigator.maxTouchPoints})}const Ur=["topbar.primary","topbar.overflow","bottombar","composer.actions","message.actions","rightpanel.tabs","contextmenu.topbar","contextmenu.message","contextmenu.session","contextmenu.file","settings.pages","leftpanel.sessions","chat.header","chat.empty","file.preview.toolbar","terminal.toolbar","scm.toolbar","goalbar.actions","notice.actions"],x1=[{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-open",slot:"contextmenu.file",labelKey:"fileOpenPreview",icon:"open",kind:"action",context:"file",order:11,group:"open"},{id:"host:file-enter",slot:"contextmenu.file",labelKey:"fileEnterDir",icon:"folder",kind:"action",context:"file",order:12,group:"open"},{id:"host:file-download",slot:"contextmenu.file",labelKey:"downloadFile",icon:"download",kind:"action",context:"file",order:13,group:"open"},{id:"host:file-open-project",slot:"contextmenu.file",labelKey:"openAsProject",icon:"folder",kind:"action",context:"file",order:14,group:"open"},{id:"host:file-add-root",slot:"contextmenu.file",labelKey:"addWorkspaceRoot",icon:"folder",kind:"action",context:"file",order:15,group:"open"},{id:"host:file-new-file",slot:"contextmenu.file",labelKey:"fileNewFile",icon:"file",kind:"action",context:"file",order:21,group:"new"},{id:"host:file-new-dir",slot:"contextmenu.file",labelKey:"fileNewDir",icon:"folder",kind:"action",context:"file",order:22,group:"new"},{id:"host:file-upload",slot:"contextmenu.file",labelKey:"uploadToFolder",icon:"upload",kind:"action",context:"file",order:23,group:"new"},{id:"host:file-paste",slot:"contextmenu.file",labelKey:"filePaste",icon:"paste",kind:"action",context:"file",order:24,group:"new"},{id:"host:file-attach-inline",slot:"contextmenu.file",labelKey:"attachInlineTip",icon:"plus",kind:"action",context:"file",order:31,group:"chat"},{id:"host:file-attach-ref",slot:"contextmenu.file",labelKey:"referenceTip",icon:"link",kind:"action",context:"file",order:32,group:"chat"},{id:"host:file-attach-folder",slot:"contextmenu.file",labelKey:"linkFolderTip",icon:"link",kind:"action",context:"file",order:33,group:"chat"},{id:"host:file-rename",slot:"contextmenu.file",labelKey:"fileRename",icon:"edit",kind:"action",context:"file",order:41,group:"edit"},{id:"host:file-duplicate",slot:"contextmenu.file",labelKey:"fileDuplicate",icon:"copy",kind:"action",context:"file",order:42,group:"edit"},{id:"host:file-cut",slot:"contextmenu.file",labelKey:"fileCut",icon:"cut",kind:"action",context:"file",order:43,group:"edit"},{id:"host:file-copy",slot:"contextmenu.file",labelKey:"fileCopyEntry",icon:"copy",kind:"action",context:"file",order:44,group:"edit"},{id:"host:file-copy-name",slot:"contextmenu.file",labelKey:"copyName",icon:"copy",kind:"action",context:"file",order:51,group:"clipboard"},{id:"host:file-copy-path",slot:"contextmenu.file",labelKey:"copyPath",icon:"copy",kind:"action",context:"file",order:52,group:"clipboard"},{id:"host:file-copy-rel",slot:"contextmenu.file",labelKey:"fileCopyRelPath",icon:"copy",kind:"action",context:"file",order:53,group:"clipboard"},{id:"host:file-refresh",slot:"contextmenu.file",labelKey:"fileRefresh",icon:"refresh",kind:"action",context:"file",order:54,group:"clipboard"},{id:"host:file-delete",slot:"contextmenu.file",labelKey:"fileDelete",icon:"trash",kind:"action",context:"file",order:61,group:"danger"}];function mu(e){return typeof e=="string"&&Ur.includes(e)}function hu(e,t){return t?e.label:e.labelEn??e.label}function fu(e,t){return t?e.hint??e.hintEn:e.hintEn??e.hint}function E1(e,t,n,r,a){const c=`${e}#${r.id}`,l=gu(c,t,n,r.children,a),u=fu(r,a);return{id:c,slot:t,source:n,label:hu(r,a),...r.icon?{icon:r.icon}:{},...u?{hint:u}:{},kind:r.kind??"action",...r.action?{action:r.action}:{},...r.view?{view:r.view}:{},...r.group?{group:r.group}:{},order:r.order??100,align:"start",hidden:r.hidden??!1,...r.badge?{badge:r.badge}:{},...r.when?{when:r.when}:{},...l.length>0?{children:l}:{},userOverrides:[],arrangedBy:[]}}function gu(e,t,n,r,a){return r?.length?r.map((c,l)=>({entry:E1(e,t,n,c,a),index:l})).sort((c,l)=>c.entry.order===l.entry.order?c.index-l.index:c.entry.order-l.entry.order).map(c=>c.entry):[]}function y1(e){if(e===void 0)return;const t=Number(e);return Number.isFinite(t)?Math.min(100,Math.max(0,t)):0}function T1(e,t,n,r,a,c){const l=gu(e,t,n,r.children,a),u=fu(r,a),d=y1(r.progress);return{id:e,slot:t,source:n,label:hu(r,a),...r.icon?{icon:r.icon}:{},...u?{hint:u}:{},kind:r.kind??(t==="settings.pages"?"page":"action"),...r.action?{action:r.action}:{},...r.view?{view:r.view}:{},...r.group?{group:r.group}:{},order:r.order??100,align:r.align??"start",hidden:r.hidden??!1,...r.badge?{badge:r.badge}:{},...typeof r.checked=="boolean"?{checked:r.checked}:{},...typeof r.value=="string"?{value:r.value}:{},...d!==void 0?{progress:d}:{},...r.when?{when:r.when}:{},...l.length>0?{children:l}:{},userOverrides:[],arrangedBy:[],seq:c}}function k1(e,t){return[...e].sort((n,r)=>{const a=t.get(n.id),c=t.get(r.id);return a!==void 0||c!==void 0?a!==void 0&&c!==void 0?a-c:a!==void 0?-1:1:n.order!==r.order?n.order-r.order:n.seq-r.seq})}function bu(e,t){const n=t.locale==="zh",r=new Set(t.disabledPlugins??[]),a=t.layout??{},c=new Map;let l=0;for(const b of x1)c.set(b.id,{id:b.id,slot:b.slot,source:"host",label:t.t(b.labelKey),labelKey:b.labelKey,...b.icon?{icon:b.icon}:{},kind:b.kind,...b.view?{view:b.view}:{},...b.group?{group:b.group}:{},order:b.order??100,align:"start",hidden:b.hidden??!1,userOverrides:[],arrangedBy:[],seq:l++});for(const b of e){if(b.error||r.has(b.id))continue;const E=`plugin:${b.id}`;for(const N of b.ui?.items??[]){if(!mu(N.slot))continue;const g=`${b.id}:${N.id}`,R=c.get(g);c.set(g,T1(g,N.slot,E,N,n,R?.seq??l++))}}for(const b of e)if(!(b.error||r.has(b.id)))for(const E of b.ui?.arrange??[])v1(c,E,b.id);const u=new Map,d=(b,E)=>{const N=u.get(b)??[];N.includes(E)||N.push(E),u.set(b,N)};for(const b of a.hidden??[]){const E=c.get(b);E&&(E.hidden=!0,d(b,"hidden"))}for(const b of a.shown??[]){const E=c.get(b);E&&(E.hidden=!1,d(b,"hidden"))}for(const[b,E]of Object.entries(a.groups??{})){const N=c.get(b);N&&(N.group=E,d(b,"group"))}for(const[b,E]of Object.entries(a.align??{})){const N=c.get(b);!N||E!=="start"&&E!=="center"&&E!=="end"||(N.align=E,d(b,"align"))}for(const[b,E]of Object.entries(a.labels??{})){const N=c.get(b);N&&(N.label=E,d(b,"label"))}const m=new Map;(a.order??[]).forEach((b,E)=>{c.has(b)&&(m.has(b)||m.set(b,E),d(b,"order"))});const f=new Map;for(const b of Ur)f.set(b,[]);for(const b of c.values())f.get(b.slot)?.push(b);const h={};for(const b of Ur)h[b]=k1(f.get(b)??[],m).map(E=>N1(E,u.get(E.id)??[]));return h}function N1(e,t){const n={...e,userOverrides:t};return delete n.seq,n}function v1(e,t,n){const r=e.get(t.id);if(!r)return;let a=!1;t.hide!==void 0&&(r.hidden=t.hide,a=!0),t.group!==void 0&&(r.group=t.group,a=!0),t.order!==void 0&&(r.order=t.order,a=!0),t.align!==void 0&&(r.align=t.align,a=!0),t.label!==void 0&&(r.label=t.label,a=!0),t.hint!==void 0&&(r.hint=t.hint,a=!0),t.icon!==void 0&&(r.icon=t.icon,a=!0),t.slot!==void 0&&mu(t.slot)&&t.slot!==r.slot&&(r.movedFrom=r.movedFrom??r.slot,r.slot=t.slot,a=!0),a&&r.source!==`plugin:${n}`&&!r.arrangedBy.includes(n)&&r.arrangedBy.push(n)}function C1(e){const t=[],n=[],r=[];for(const a of e)a.align==="end"?r.push(a):a.align==="center"?n.push(a):t.push(a);return{start:t,center:n,end:r}}function w1(e,t){const n=e??{},r={},a=(n.hidden??[]).filter(f=>f!==t),c=(n.shown??[]).filter(f=>f!==t),l=(n.order??[]).filter(f=>f!==t);a.length>0&&(r.hidden=a),c.length>0&&(r.shown=c),l.length>0&&(r.order=l);const u=nr(n.groups,t);u&&(r.groups=u);const d=nr(n.labels,t);d&&(r.labels=d);const m=nr(n.align,t);return m&&(r.align=m),r}function S1(){return{}}function nr(e,t){if(!e)return;const n={};let r=!1;for(const[a,c]of Object.entries(e))a!==t&&(n[a]=c,r=!0);return r?n:void 0}const xu=["off","minimal","low","medium","high","xhigh","max"],_1=o.memo(function({state:t,models:n,modelsLoading:r,onManageModels:a,providerKeys:c,compact:l=!1}){const u=He(),d=t?.model,m=d?`${d.provider}/${d.id}`:null,[f,h]=o.useState(!1),[b,E]=o.useState(!1),[N,g]=o.useState(""),[R,M]=o.useState(null),[B,j]=o.useState({}),Y=o.useRef(null),q=o.useRef(null),[C,Te]=o.useState(null);o.useEffect(()=>{if(!f){Te(null);return}if(n.length===0)return;const A=requestAnimationFrame(()=>{const ue=q.current;ue&&Te(ue.offsetWidth)});return()=>cancelAnimationFrame(A)},[f,n.length]),o.useEffect(()=>{f&&j(nu())},[f]),o.useEffect(()=>{f||(g(""),M(null))},[f]);const xe=o.useMemo(()=>{const A=new Map;for(const P of n)A.set(P.provider,(A.get(P.provider)??0)+1);const ue=[];for(const[P,ie]of[...A.entries()].sort((I,he)=>I[0].localeCompare(he[0]))){const I=c[P];if(I&&I.length>1)for(const he of I)ue.push({provider:P,keyName:he.name,count:ie});else ue.push({provider:P,keyName:null,count:ie})}return ue},[n,c]),G=o.useMemo(()=>Fb(n,B),[n,B]),ee=o.useMemo(()=>{let A=G;R&&(A=A.filter(P=>P.provider===R.provider));const ue=N.trim().toLowerCase();return ue?A.filter(P=>P.name.toLowerCase().includes(ue)||P.provider.toLowerCase().includes(ue)||P.id.toLowerCase().includes(ue)):A},[G,N,R]),Q=o.useMemo(()=>{const A=[];for(const ue of ee){const P=c[ue.provider];if(!P||P.length<=1){A.push({model:ue,key:null});continue}let ie=P.find(I=>I.active)??P[0];if(R?.provider===ue.provider&&R.keyName){const I=P.find(he=>he.name===R.keyName);I&&(ie=I)}A.push({model:ue,key:ie})}return A},[ee,c,R]),[O,F]=o.useState(!1),w=t?.availableThinkingLevels&&t.availableThinkingLevels.length>0?new Set(t.availableThinkingLevels):null,se=xu.map(A=>({value:A,label:u(`thinking.${A}`),supported:w?w.has(A):!0})),z=A=>se.find(ue=>ue.value===A)?.label??A;return o.useEffect(()=>{f&&n.length===0&&!O&&!r&&(F(!0),J({type:"list_models"}))},[f,n.length,O,r]),o.useEffect(()=>{n.length>0&&F(!1)},[n.length]),o.useEffect(()=>{if(!f)return;Y.current?.querySelector(".dd-item.active")?.scrollIntoView({block:"nearest"})},[f,m,n.length]),s.jsxs(s.Fragment,{children:[s.jsxs(zt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(Ts,{}),s.jsx("span",{className:"chip-model",children:d?d.name:u("selectModel")}),!l&&d?.vision&&s.jsx("span",{className:"chip-vision",title:u("vision"),children:"🖼"}),!l&&d&&s.jsx("span",{className:"chip-sub",children:d.provider})]}),open:f,onOpenChange:h,menuClassName:"dd-menu-model",menuRef:q,menuStyle:C!=null?{width:C}:void 0,direction:"up",children:[s.jsx("div",{className:"dd-header",children:u("availableModels")}),s.jsxs("div",{className:"dd-search-row",children:[s.jsx(ca,{}),s.jsx("input",{className:"dd-search",type:"text",placeholder:u("searchModels"),value:N,onChange:A=>g(A.target.value)})]}),s.jsxs("div",{className:"dd-model-body",children:[xe.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 ${R===null?"active":""}`,onClick:()=>M(null),children:s.jsx("span",{children:u("allProviders")})}),xe.map(A=>{const ue=R?.provider===A.provider&&R?.keyName===A.keyName;return s.jsxs("button",{type:"button",className:`dd-provider-item ${ue?"active":""}`,onClick:()=>M(ue?null:{provider:A.provider,keyName:A.keyName}),title:A.keyName?`${A.provider} · ${A.keyName}`:`${A.provider} · ${A.count}`,children:[s.jsxs("span",{className:"dd-provider-txt",children:[s.jsx("span",{className:"dd-provider-name",children:A.provider}),A.keyName&&s.jsx("span",{className:"dd-provider-key",children:A.keyName})]}),s.jsx("span",{className:"dd-provider-count",children:A.count})]},A.keyName?`${A.provider}::${A.keyName}`:A.provider)})]}),s.jsxs("div",{className:"dd-model-scroll",ref:Y,children:[(O||r)&&s.jsx("div",{className:"dd-loading",children:u("loading")}),n.length===0&&!O&&!r&&s.jsx("div",{className:"dd-loading",children:u("noModels")}),ee.length===0&&n.length>0&&s.jsx("div",{className:"dd-loading",children:u("noModelMatches")}),Q.map(A=>{const ue=A.model,P=m===ue.id&&(!A.key||A.key.active);return s.jsx(wt,{active:P,onClick:()=>{A.key&&!A.key.active&&J({type:"activate_provider_key",provider:ue.provider,keyName:A.key.name}),m!==ue.id&&J({type:"set_model",modelId:ue.id}),h(!1)},children:s.jsxs("span",{className:"dd-model-cell",children:[s.jsx("span",{className:"dd-model-name",children:ue.name}),s.jsxs("span",{className:"dd-model-meta",children:[s.jsx("span",{className:"dd-model-provider",children:ue.provider}),s.jsx("span",{className:"dd-model-id",children:ue.id.split("/").slice(1).join("/")}),A.key&&s.jsxs("span",{className:`dd-model-key ${A.key.active?"active":""}`,children:[A.key.active?"●":"○"," ",A.key.name]}),(B[ue.id]??0)>0&&s.jsx("span",{className:"dd-model-usage",children:u("modelUsedCount",{n:B[ue.id]})}),(ue.reasoning||ue.vision)&&s.jsxs("span",{className:"dd-model-badges",children:[ue.reasoning&&s.jsx("span",{className:"dd-model-badge",children:u("reasoning")}),ue.vision&&s.jsx("span",{className:"dd-model-badge",children:u("vision")})]})]})]})},A.key?`${ue.id}::${A.key.name}`:ue.id)})]})]}),s.jsxs("div",{className:"dd-footer",children:[s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>J({type:"list_models"}),children:u("refreshModels")}),s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{h(!1),a()},children:u("manageModels")})]})]}),s.jsxs(zt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(qs,{}),s.jsx("span",{className:"chip-sub",children:u("thinkingChip",{level:t?z(t.thinkingLevel):"—"})})]}),open:b,onOpenChange:E,direction:"up",children:[s.jsx("div",{className:"dd-header",children:u("thinkingLevel")}),se.map(A=>s.jsx(wt,{active:t?.thinkingLevel===A.value,disabled:!A.supported,title:A.supported?void 0:u("thinkingUnsupported"),onClick:()=>{t?.thinkingLevel!==A.value&&J({type:"set_thinking",level:A.value}),E(!1)},children:A.label},A.value))]})]})}),Qo=["standard","ptc","minimal","cordis"];function $r(e){return[...e].sort((t,n)=>{const r=Number.isSafeInteger(t.order)?t.order:Qo.indexOf(t.id),a=Number.isSafeInteger(n.order)?n.order:Qo.indexOf(n.id),c=r>=0?r:1e3,l=a>=0?a:1e3;return c!==l?c-l:t.id.localeCompare(n.id)})}const A1=o.memo(function({preset:t,presets:n,defaultPreset:r,blank:a,conversationId:c,compact:l=!1}){const u=He(),[d,m]=o.useState(!1),[f,h]=o.useState(t?.id??r);if(o.useEffect(()=>{h(t?.id??r)},[c,t?.id,r]),n.length===0)return null;const b=t?.locked||!a,E=$r(n),N=E.find(M=>M.id===t?.id),g=E.find(M=>M.id===f)??N,R=M=>{h(M),m(!1),a&&M!==t?.id&&J({type:"dsh_preset_select",preset:M})};if(l){const M=N?.description??N?.id??u("dshPreset");return s.jsx(zt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(Ts,{}),s.jsxs("span",{className:"chip-sub",title:b?`${M}(${u("dshPresetLocked")})`:M,children:[N?.name??N?.id??t?.name??u("dshPreset"),b&&s.jsx(ur,{style:{marginLeft:3}})]})]}),open:d&&!b,onOpenChange:m,direction:"up",children:E.map(B=>s.jsxs(wt,{active:B.id===t?.id,disabled:!!B.broken,title:B.broken??B.description??B.id,onClick:()=>R(B.id),children:[s.jsxs("span",{className:"dd-preset-name",children:[B.name??B.id,B.trust==="user"&&s.jsx("span",{className:"dd-preset-tag",children:u("dshPresetUser")}),B.id===r&&s.jsx("span",{className:"dd-preset-tag",children:u("dshPresetDefaultTag")}),B.broken&&s.jsx("span",{className:"dd-preset-tag warn",children:u("dshPresetBroken")})]}),B.description&&!B.broken&&s.jsx("span",{className:"dd-preset-desc",children:B.description})]},B.id))})}return s.jsxs("div",{className:"dsh-presetbar","data-testid":"dsh-presetbar",children:[s.jsxs("span",{className:"dsh-preset-label",children:[s.jsx(Ts,{}),u("dshPreset")]}),s.jsx(zt,{trigger:s.jsxs("span",{title:N?.description??N?.id??"",children:[N?.name??N?.id??t?.name??"…",b&&s.jsxs("span",{className:"dsh-preset-lock",title:u("dshPresetBlankOnly"),children:[s.jsx(ur,{})," ",u("dshPresetLocked")]})]}),open:d&&!b,onOpenChange:m,children:E.map(M=>s.jsxs(wt,{active:M.id===t?.id,disabled:!!M.broken,title:M.broken??M.description??M.id,onClick:()=>R(M.id),children:[s.jsxs("span",{className:"dd-preset-name",children:[M.name??M.id,M.trust==="user"&&s.jsx("span",{className:"dd-preset-tag",children:u("dshPresetUser")}),M.id===r&&s.jsx("span",{className:"dd-preset-tag",children:u("dshPresetDefaultTag")}),M.broken&&s.jsx("span",{className:"dd-preset-tag warn",children:u("dshPresetBroken")})]}),M.description&&!M.broken&&s.jsx("span",{className:"dd-preset-desc",children:M.description})]},M.id))}),!b&&s.jsx("span",{className:"dsh-preset-hint",title:u("dshPresetBlankOnly"),children:u("dshPresetBlankOnly")}),g?.id==="minimal"&&s.jsx("span",{className:"dsh-preset-hint warn",children:u("dshPresetMinimalNote")}),s.jsxs("button",{type:"button",className:"chip",title:u("dshPresetNewChat"),onClick:()=>J({type:"new_chat",preset:g?.id??f}),children:[s.jsx(Dt,{})," ",u("dshPresetNewChat")]})]})}),j1=["read-only","workspace-write-never","danger-full-access"],Xo=["read-only","workspace-write-never","danger-full-access"];function $s(e){return e==="read-only"?"dshPermReadOnly":e==="danger-full-access"?"dshPermFullAccess":"dshPermWorkspaceWrite"}function Cs(e){return e==="read-only"?"dshPermReadOnlyDesc":e==="danger-full-access"?"dshPermFullAccessDesc":"dshPermWorkspaceWriteDesc"}const I1=o.memo(function({current:t,options:n,defaultPreset:r,conversationId:a,compact:c=!1}){const l=He(),[u,d]=o.useState(!1),[m,f]=o.useState(!1);o.useEffect(()=>{f(!1),d(!1)},[a]);const h=j1.filter(g=>n.some(R=>R.value===g));if(h.length===0)return null;const b=t??r,E=!!t&&!h.includes(t),N=g=>{if(g==="danger-full-access"&&g!==b&&!m){f(!0);return}f(!1),d(!1),g!==b&&J({type:"dsh_permission_set",preset:g})};if(c){const g=l(E?"dshPermCustom":$s(b)),R=E?t??g:l(Cs(b));return s.jsxs(zt,{trigger:s.jsxs(s.Fragment,{children:[s.jsx(or,{}),s.jsxs("span",{className:"chip-sub",title:R,children:[g,b==="danger-full-access"&&s.jsx(hr,{style:{marginLeft:3}})]})]}),open:u,onOpenChange:M=>{d(M),M||f(!1)},direction:"up",children:[h.map(M=>{const B=n.find(j=>j.value===M);return s.jsxs(wt,{active:M===b,title:B?.description??l(Cs(M)),onClick:()=>N(M),children:[s.jsxs("span",{className:"dd-preset-name",children:[l($s(M)),M===r&&s.jsx("span",{className:"dd-preset-tag",children:l("dshPresetDefaultTag")}),M==="danger-full-access"&&s.jsx("span",{className:"dd-preset-tag warn",children:l("dshPermFullAccessTag")})]}),s.jsx("span",{className:"dd-preset-desc",children:l(Cs(M))})]},M)}),m&&s.jsx("div",{className:"dd-note warn",children:l("dshPermConfirmFull")})]})}return s.jsxs("div",{className:"dsh-presetbar","data-testid":"dsh-permissionbar",children:[s.jsxs("span",{className:"dsh-preset-label",children:[s.jsx(or,{}),l("dshPerm")]}),s.jsx(zt,{trigger:s.jsxs("span",{title:E?t:l(Cs(b)),children:[l(E?"dshPermCustom":$s(b)),b==="danger-full-access"&&s.jsxs("span",{className:"dd-preset-tag warn",children:[s.jsx(hr,{})," ",l("dshPermFullAccessTag")]})]}),open:u,onOpenChange:g=>{d(g),g||f(!1)},children:h.map(g=>{const R=n.find(M=>M.value===g);return s.jsxs(wt,{active:g===b,title:R?.description??l(Cs(g)),onClick:()=>N(g),children:[s.jsxs("span",{className:"dd-preset-name",children:[l($s(g)),g===r&&s.jsx("span",{className:"dd-preset-tag",children:l("dshPresetDefaultTag")}),g==="danger-full-access"&&s.jsx("span",{className:"dd-preset-tag warn",children:l("dshPermFullAccessTag")})]}),s.jsx("span",{className:"dd-preset-desc",children:l(Cs(g))})]},g)})}),m&&s.jsx("span",{className:"dsh-preset-hint warn",children:l("dshPermConfirmFull")})]})}),Jo=b1(),R1=o.memo(function({streaming:t,messages:n,slashCommands:r,modelState:a,models:c,modelsLoading:l,attachments:u,onRemoveAttachment:d,onAddImageFiles:m,onAddLocalFiles:f,onAddPathAttachment:h,fileSearch:b,onSearchFiles:E,onNotice:N,onSent:g,onManageModels:R,providerKeys:M,quickPhrases:B,quickPhrasesEnabled:j,recallDrafts:Y,composerActions:q,onUiAction:C,dshPermCurrent:Te,dshPermOptions:xe,dshPermDefault:G,dshPreset:ee,dshPresets:Q,dshPresetDefault:O,dshBlank:F,conversationId:w,sessionDraft:se,sessionId:z}){const A=He(),ue=$t("ready"),P=Kl(),{locale:ie}=Vt(),{openPicker:I}=ou(),he=k=>ie!=="zh"&&k.descriptionEn?k.descriptionEn:k.description??"",_=k=>ie!=="zh"&&k.argumentHintEn?k.argumentHintEn:k.argumentHint??"",[re,le]=o.useState(""),[Ee,Ne]=o.useState(null),[Ue,ke]=o.useState(0),Ke=o.useRef(0),Ie=o.useRef(0),ce=o.useRef(new Map),pe=o.useRef(""),[Fe,Ae]=o.useState(!1),[et,dt]=o.useState(void 0),Ve=o.useRef(null),X=o.useRef(null),we=o.useRef(null),L=o.useRef(-1),W=o.useRef(""),oe=o.useRef(0);o.useEffect(()=>{if(!Y||Y.length===0)return;const k=Y.filter(ae=>ae.text&&ae.seq>oe.current);k.length!==0&&(oe.current=k[k.length-1].seq,le(ae=>k.reduce((Se,Me)=>Ko(Se,Me.text),ae)),L.current=-1,W.current="",requestAnimationFrame(()=>{const ae=Ve.current;ae&&(ae.focus(),ae.selectionStart=ae.selectionEnd=ae.value.length)}))},[Y]),o.useEffect(()=>(Ai(k=>{le(ae=>Ko(ae,k)),L.current=-1,W.current="",requestAnimationFrame(()=>{const ae=Ve.current;ae&&(ae.focus(),ae.selectionStart=ae.selectionEnd=ae.value.length)})}),()=>Ai(null)),[]);const fe=2e4,de=2e3,ge=!P&&z?`${w??""}${z}`:null,Qe=ge&&z?`pi-web-ui:composer-draft:${z}`:null,ye=o.useRef(""),Oe=o.useRef(0),rt=o.useRef(!1),Ge=o.useRef(0),D=o.useRef(null),$e=o.useRef(null),it=k=>{try{const ae=localStorage.getItem(k);if(!ae)return null;const Se=JSON.parse(ae);return typeof Se.text!="string"||!Se.text||typeof Se.ts!="number"?null:{text:Se.text.slice(0,fe),ts:Se.ts}}catch{return null}},Xe=(k,ae,Se,Me)=>{const We=Se.slice(0,fe);try{We.trim()?localStorage.setItem(ae,JSON.stringify({text:We,ts:Me})):localStorage.removeItem(ae)}catch{}J({type:"draft_update",sessionId:k,text:We,ts:Me})},U=()=>{D.current&&(clearTimeout(D.current),D.current=null),!(!rt.current||!ge||!Qe||!z||!jt)&&Xe(z,Qe,ye.current,Oe.current)},Pe=k=>{if(ye.current=k,rt.current=!0,Oe.current=Date.now(),Qe){const ae=k.slice(0,fe);try{ae.trim()?localStorage.setItem(Qe,JSON.stringify({text:ae,ts:Oe.current})):localStorage.removeItem(Qe)}catch{}}if(ge&&z&&jt){D.current&&clearTimeout(D.current);const ae=z,Se=Qe,Me=Oe.current,We=ge;D.current=setTimeout(()=>{D.current=null,!(We!==$e.current||!Se)&&Xe(ae,Se,ye.current,Me)},de)}},Le=(k,ae)=>{L.current=-1,le(k),Ye(k,ae),Pe(k)};o.useEffect(()=>{const k=ge,ae=z,Se=Qe;return()=>{D.current&&(clearTimeout(D.current),D.current=null),rt.current&&k&&ae&&Se&&ye.current.trim()&&Xe(ae,Se,ye.current,Oe.current)}},[ge]),o.useEffect(()=>{$e.current=ge,rt.current=!1,Ge.current=0,ye.current="",Oe.current=0,le(""),Ne(null),L.current=-1},[ge]),o.useEffect(()=>{if(!ge||!Qe||rt.current||ye.current!=="")return;let k=null;se&&se.text&&se.ts>0&&(k={text:se.text.slice(0,fe),ts:se.ts});const ae=it(Qe);ae&&ae.ts>(k?.ts??0)&&(k=ae),!(!k||k.ts<=Ge.current)&&(Ge.current=k.ts,ye.current=k.text,Oe.current=k.ts,le(k.text),Ye(k.text,null))});const ot={builtin:A("slashBuiltin"),extension:A("slashExtension"),prompt:A("slashPrompt"),skill:A("slashSkill"),plugin:A("slashPlugin")},Ye=(k,ae)=>{pe.current=k;const Se=k.match(/^\/([^\s]*)$/);if(Se&&ue){const lt=Se[1].toLowerCase(),It=c1(r,lt);Ne(It.length>0?{kind:"slash",items:It}:null),ke(0);return}if(ae===null||!ue){Ne(null);return}const Me=f1(k,ae);if(!Me){Ne(null);return}let We=[];try{We=ec()}catch{We=[]}const De=++Ke.current,at=k,xt=Me.start,Jt=Me.query,Nt=We.map(lt=>({id:lt.id,label:lt.label,run:()=>{let It;try{It=hm(lt.id)?.search}catch{It=void 0}return typeof It!="function"?Promise.resolve([]):It(Jt)}}));if(Jt&&typeof E=="function"&&Nt.push({id:"host:files",label:A("openFiles"),run:()=>ct(Jt)}),hp(),Nt.push({id:"host:pages",label:A("browserControl"),run:()=>Promise.resolve(d1(A("browserControl"),mp(),Jt))}),Nt.length===0){Ne(null);return}Promise.allSettled(Nt.map(lt=>Promise.race([lt.run(),new Promise((It,ze)=>setTimeout(()=>ze(new Error("at-mention timeout")),2e3))]))).then(lt=>{if(Ke.current!==De||pe.current!==at)return;const It=[],ze=[];lt.forEach((ds,as)=>{ds.status!=="fulfilled"||It.length+ze.length>=30||(Nt[as].id==="host:pages"&&Array.isArray(ds.value)?It.push(...ds.value):Nt[as].id==="host:files"?ze.push(...p1(Nt[as].label,ds.value)):ze.push(...m1(Nt[as].id,Nt[as].label,ds.value)))});const Ns=[...It,...ze].slice(0,30);Ne(Ns.length>0?{kind:"at",start:xt,items:Ns}:null),ke(0)})},ct=k=>{if(typeof E!="function")return Promise.resolve([]);const ae=++Ie.current;return new Promise(Se=>{ce.current.set(ae,Se);try{E(ae,k)}catch{ce.current.delete(ae),Se([]);return}setTimeout(()=>{ce.current.get(ae)===Se&&(ce.current.delete(ae),Se([]))},3e3)})};o.useEffect(()=>{if(!b||!b.ok)return;const k=ce.current.get(b.reqId);k&&(ce.current.delete(b.reqId),k(b.results??[]))},[b]);const mt=k=>Ye(k,null);o.useEffect(()=>{we.current?.querySelector(".slash-item.active")?.scrollIntoView({block:"nearest"})},[Ue,Ee]);const Mt=k=>{const ae=Ee?.kind==="slash"?Ee.items:[],Se=k??ae[Ue%Math.max(ae.length,1)];if(!Se){Ne(null);return}const Me=re.match(/^\/([^\s]*)([\s\S]*)$/),We=Me?Me[2]:"",De=`/${Se.name} ${We}`;pe.current=De,le(De),Ne(null),Ve.current?.focus()},$=(k,ae)=>{const Se=Ee?.kind==="at"?Ee:null,Me=Se?.items??[],We=k??Me[Ue%Math.max(Me.length,1)],De=ae??Se?.start;if(!We||De===void 0){Ne(null);return}const at=Ve.current,xt=at?at.selectionStart??re.length:re.length,Jt=`${We.text??We.title} `,Nt=`${re.slice(0,De)}${Jt}${re.slice(xt)}`;pe.current=Nt,le(Nt),Ne(null);for(const lt of We.attachments??[])try{h?.({path:lt.path,name:lt.name??lt.path.split("/").pop()??lt.path,...lt.mode?{mode:lt.mode}:{mode:"reference"},...typeof lt.isDir=="boolean"?{isDir:lt.isDir}:{},...lt.lines?{lines:lt.lines}:{}})}catch{}requestAnimationFrame(()=>{const lt=Ve.current;lt&&(lt.focus(),lt.selectionStart=lt.selectionEnd=De+Jt.length)})},Z=()=>Ee?.kind!=="slash"?null:Ee.items.map((k,ae)=>s.jsxs("button",{type:"button",className:`slash-item${ae===Ue?" active":""}`,onMouseEnter:()=>ke(ae),onClick:()=>je(k),children:[s.jsxs("span",{className:"slash-name",children:["/",k.name]}),s.jsx("span",{className:`slash-source ${k.source}`,children:ot[k.source]}),s.jsxs("span",{className:"slash-desc",children:[he(k),k.argumentHint&&s.jsx("span",{className:"slash-hint",children:_(k)})]})]},k.name)),Re=()=>Ee?.kind!=="at"?null:Ee.items.map((k,ae)=>s.jsxs("button",{type:"button",className:`slash-item${ae===Ue?" active":""}`,onMouseEnter:()=>ke(ae),onClick:()=>je(k),title:k.hint??k.title,children:[s.jsxs("span",{className:"slash-name",children:["@",k.title]}),s.jsx("span",{className:"slash-source plugin",children:k.providerLabel}),k.hint&&s.jsx("span",{className:"slash-desc",children:k.hint})]},`${k.providerId}:${k.title}:${ae}`)),je=k=>{Ee&&(Ee.kind==="slash"?Mt(k):$(k,Ee.start))},Je=async()=>{const Se=[...n].reverse().find(Me=>Me.role==="assistant"&&Me.content.some(We=>We.type==="text"&&We.text))?.content.filter(Me=>Me.type==="text").map(Me=>Me.text).join(`
|
|
348
|
+
`);if(!Se){N("warning",A("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(Se),N("info",A("slashCopied"))}catch{N("error",A("slashCopyFailed"))}},qe=k=>{if(!k||k.length===0){N("warning",A("foldersNotSupported"));return}const ae=Array.from(k).filter(We=>fs(We.type)),Se=Array.from(k).filter(We=>!fs(We.type)),Me=Lt();ae.length>0&&Me?N("warning",Me):ae.length>0&&m(ae),Se.length>0&&f(Se)},At=k=>{const ae=k.clipboardData?.items;if(!ae)return;const Se=[];for(const We of ae)if(We.kind==="file"&&fs(We.type)){const De=We.getAsFile();De&&Se.push(De)}if(Se.length===0)return;k.preventDefault();const Me=Lt();if(Me){N("warning",Me);return}m(Se)},Lt=()=>{const k=a?.model;if(!k?.id)return null;const ae=c.find(Se=>Se.id===k.id);return ae&&ae.vision===!1?A("modelNoVision",{name:ae.name}):null},jt=ue,us=o.useRef(re);o.useEffect(()=>{us.current=re},[re]),o.useEffect(()=>{mt(us.current)},[r]),o.useEffect(()=>{const k=ae=>{const Se=ae.detail;le(Se),Ve.current?.focus()};return window.addEventListener("pi-web:fill",k),()=>window.removeEventListener("pi-web:fill",k)},[]),o.useEffect(()=>{if(!Fe)return;const k=ae=>{ae.key==="Escape"&&Ae(!1)};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[Fe]);const Qt=o.useRef(null);o.useEffect(()=>{const k=Ve.current,ae=Qt.current;if(!k||!ae)return;const Se=k.closest("main")?.querySelector(".messages"),Me=ae.getBoundingClientRect().height,We=Se?.scrollTop??0;k.style.height="auto";const De=k.scrollHeight>220;if(k.style.height=`${Math.min(k.scrollHeight,220)}px`,k.style.overflowY=De?"auto":"hidden",Se){const at=ae.getBoundingClientRect().height-Me;Se.scrollTop=We+at}},[re]);const Ut=()=>u.map(k=>k.imageData?{path:"",imageData:k.imageData,mimeType:k.mimeType,name:k.name}:k.fileData?{path:"",fileData:k.fileData,mimeType:k.mimeType,name:k.name,size:k.size}:{path:k.path,mode:k.mode,...k.lines?{lines:k.lines}:{},...k.mode==="page"?{name:k.name}:{}}),v=(k=!1)=>{const ae=re.trim(),Se=u.some(Me=>Me.imageData||Me.fileData);if(!(!jt||!ae&&!Se)){if(ae==="/help"){const Me=Ve.current?.closest(".inputbox")?.getBoundingClientRect();dt(Me?.width),Ae(!0),le(""),Ve.current?.focus();return}if(ae==="/copy"){le(""),Ve.current?.focus(),Je();return}if(J({type:"prompt",text:ae,queue:k,attachments:Ut()})){if(ae&&zo(ae),L.current=-1,W.current="",le(""),Qe)try{localStorage.removeItem(Qe)}catch{}D.current&&(clearTimeout(D.current),D.current=null),rt.current=!1,Ge.current=0,ye.current="",Oe.current=0,g();const Me=a?.model;Me&&wa(`${Me.provider}/${Me.id}`),Ve.current?.focus()}}},te=k=>{const ae=k.trim();if(!(!jt||!ae)&&J({type:"prompt",text:ae,attachments:Ut()})){ae&&zo(ae),L.current=-1,W.current="",U(),g();const Se=a?.model;Se&&wa(`${Se.provider}/${Se.id}`),Jo||Ve.current?.focus()}},Be=k=>{if(!k.nativeEvent.isComposing){if(Ee&&Ee.items.length>0){const ae=Ee.items.length;switch(k.key){case"ArrowDown":k.preventDefault(),ke(Se=>(Se+1)%ae);return;case"ArrowUp":k.preventDefault(),ke(Se=>(Se-1+ae)%ae);return;case"Tab":case"Enter":k.preventDefault(),je();return;case"Escape":k.preventDefault(),Ne(null);return}}if(k.key==="ArrowUp"||k.key==="ArrowDown"){if(k.ctrlKey||k.metaKey||k.altKey)return;const ae=Ve.current;if(!ae)return;const Se=k.key==="ArrowUp",Me=n1(ae);if(Se&&!Me.first||!Se&&!Me.last||!Se&&L.current===-1)return;const We=jn();if(We.length===0)return;if(k.preventDefault(),Se){if(L.current===-1){W.current=re;const De=We.length-1;L.current=De;const at=We[De];le(at),mt(at),requestAnimationFrame(()=>{const xt=Ve.current;xt&&(xt.selectionStart=xt.selectionEnd=at.length)})}else if(L.current>0){const De=L.current-1;L.current=De;const at=We[De];le(at),mt(at),requestAnimationFrame(()=>{const xt=Ve.current;xt&&(xt.selectionStart=xt.selectionEnd=at.length)})}}else{const De=L.current+1;if(De<We.length){L.current=De;const at=We[De];le(at),mt(at),requestAnimationFrame(()=>{const xt=Ve.current;xt&&(xt.selectionStart=xt.selectionEnd=at.length)})}else{L.current=-1;const at=W.current;le(at),mt(at),requestAnimationFrame(()=>{const xt=Ve.current;xt&&(xt.selectionStart=xt.selectionEnd=at.length)})}}return}if(k.key==="Escape"&&L.current!==-1){k.preventDefault();const ae=W.current;L.current=-1,le(ae),mt(ae),requestAnimationFrame(()=>{const Se=Ve.current;Se&&(Se.selectionStart=Se.selectionEnd=ae.length)});return}if(k.key==="Enter"){if(Jo&&!k.shiftKey&&!(k.ctrlKey||k.metaKey))return;k.shiftKey||(k.preventDefault(),v())}}},ht=jt&&(re.trim()!==""||u.some(k=>k.imageData||k.fileData)),nt=o.useMemo(()=>C1((q??[]).filter(k=>k.source!=="host"&&!k.hidden)),[q]),yt=k=>s.jsx("button",{type:"button",className:"btn composer-plugin-action",title:k.hint||k.label,"aria-label":k.label,onClick:()=>C?.(k),children:k.icon||k.label},k.id),Xt=()=>s.jsx("div",{className:"inputbox-actions",children:t?ht?s.jsxs("div",{className:`split-send${P?" single":""}`,children:[s.jsx("button",{type:"button",className:"split-queue",title:A("supplementTip"),"aria-label":A("queueFollowTag"),onClick:()=>v(!0),children:s.jsx(Ud,{})}),!P&&s.jsx("button",{type:"button",className:"split-steer",title:A("steerTip"),"aria-label":A("queueSteerTag"),onClick:()=>v(),children:s.jsx(mr,{})})]}):s.jsx("button",{type:"button",className:"btn stop",title:A("stopAgent"),onClick:()=>J({type:"abort"}),children:s.jsx(oa,{})}):s.jsx("button",{type:"button",className:"btn send",title:A("sendTip"),disabled:!ht,onClick:()=>v(),children:s.jsx(mr,{})})});return s.jsxs("div",{ref:Qt,className:"inputbar",onDragOver:k=>{k.preventDefault()},onDrop:k=>{k.preventDefault(),k.stopPropagation(),qe(k.dataTransfer?.files??null)},children:[u.length>0&&s.jsxs("div",{className:"attach-row",children:[u.map(k=>s.jsxs("span",{className:`attach-chip ${k.imageData?"image":k.fileData?"file":k.mode}`,title:k.imageData?A("attachImage",{name:k.name}):k.fileData?A("attachFile",{name:k.name}):k.isDir?A("folderRef",{path:k.path}):k.mode==="page"?A("attachPage",{name:k.name}):k.mode==="reference"?A("refOnly",{path:k.path}):k.mode==="lines"&&k.lines?A("attachLines",{path:k.path,start:k.lines.start,end:k.lines.end}):A("attachContent",{path:k.path}),children:[k.imageData?"🖼":k.fileData?"📄":k.isDir?"📁":k.mode==="page"?"🌐":k.mode==="reference"?"🔗":"📎",k.name,k.mode==="lines"&&k.lines&&s.jsxs("span",{className:"attach-range",children:["L",k.lines.start,"-",k.lines.end]}),s.jsx("button",{type:"button",className:"attach-remove",title:A("removeAttachment"),onClick:()=>d(k.key??k.path),children:"×"})]},k.key??`${k.path}|${k.mode}|${k.lines?`${k.lines.start}-${k.lines.end}`:""}`)),s.jsx("span",{className:"attach-hint",children:A("attachHint")})]}),Ee&&Ee.items.length>0&&s.jsxs("div",{className:"slash-menu",role:"listbox",ref:we,"aria-label":Ee.kind==="slash"?A("slashCommands"):A("atMentions"),"data-menu-kind":Ee.kind,children:[s.jsxs("div",{className:"slash-menu-hint",children:[s.jsx("span",{children:Ee.kind==="slash"?A("slashMenuHint"):A("atMenuHint")}),s.jsx("span",{className:"slash-menu-close",onClick:()=>Ne(null),children:"Esc"})]}),Ee.kind==="slash"?Z():Re()]}),Fe&&s.jsx("div",{className:"modal-backdrop",onClick:()=>Ae(!1),children:s.jsxs("div",{className:"slash-help",style:et?{width:et}:void 0,onClick:k=>k.stopPropagation(),children:[s.jsxs("div",{className:"slash-help-head",children:[s.jsxs("span",{children:["⚡ ",A("slashHelpTitle")]}),s.jsx("button",{type:"button",className:"btn",onClick:()=>Ae(!1),children:A("close")})]}),s.jsx("div",{className:"slash-help-body",children:r.length===0?s.jsx("div",{className:"slash-help-empty",children:A("slashLoading")}):r.map(k=>s.jsxs("div",{className:"slash-help-row",children:[s.jsxs("span",{className:"slash-help-cmd",children:["/",k.name]}),s.jsx("span",{className:`slash-source ${k.source}`,children:ot[k.source]}),s.jsxs("span",{className:"slash-help-desc",children:[he(k),k.argumentHint&&s.jsx("span",{className:"slash-hint",children:_(k)})]})]},k.name))})]})}),j&&B.length>0&&s.jsx("div",{className:"quick-row","aria-label":A("quickPhrases"),children:B.map(k=>s.jsx("button",{type:"button",className:"quick-chip",title:A("quickPhrasesTip",{text:k}),disabled:!jt,onClick:()=>te(k),children:k},k))}),s.jsxs("div",{className:"inputbox","data-pi-anchor":"composer",children:[s.jsx("input",{ref:X,type:"file",multiple:!0,hidden:!0,onChange:k=>{qe(k.target.files),k.target.value=""}}),s.jsx("textarea",{ref:Ve,value:re,rows:1,placeholder:A(jt?t?P?"placeholderStreamingQueued":"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!jt,onChange:k=>{Le(k.target.value,k.target.selectionStart??k.target.value.length)},onBlur:U,onKeyDown:Be,onPaste:At}),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:A("uploadFile"),disabled:!jt,onClick:()=>X.current?.click(),children:s.jsx(Ld,{})}),s.jsx("button",{type:"button",className:"btn tpl-open",title:A("tpl.openPicker"),onClick:I,children:s.jsx(Wd,{})}),s.jsx(_1,{state:a,models:c,modelsLoading:l,onManageModels:R,providerKeys:M,compact:!0}),xe&&xe.length>0&&G!==void 0&&s.jsx(I1,{compact:!0,current:Te??null,options:xe,defaultPreset:G,conversationId:w??""}),Q&&Q.length>0&&O!==void 0&&s.jsx(A1,{compact:!0,preset:ee??null,presets:Q,defaultPreset:O,blank:F??!1,conversationId:w??""}),nt.start.map(yt)]}),nt.center.length>0&&s.jsx("div",{className:"composer-tools-center",children:nt.center.map(yt)}),s.jsxs("div",{className:"composer-tools-right",children:[nt.end.map(yt),Xt()]})]})]})]})});function P1(e){let t=null;return{clean:e.replace(/\r?\n?\[pi-term-exit:(-?\d+)\]\r?\n?/g,(r,a)=>(t=Number(a),`\r
|
|
349
|
+
`)).replace(/\r?\n?\x1b\[90m\[(?:进程已退出,退出码 |Process exited with code )-?\d+\]\x1b\[0m\r?\n?/g,`\r
|
|
350
|
+
`),exitCode:t}}function L1({conversationId:e,terminalId:t,command:n,cwd:r,title:a,agentBash:c,active:l,running:u,exitCode:d,register:m}){const f=o.useRef(null),h=o.useRef(null),{locale:b}=Vt(),E=o.useRef(b);E.current=b;const N=n?JSON.stringify(n):"",g=o.useRef(u===!1);o.useEffect(()=>{const B=f.current;if(!B)return;const j=new md({theme:Io(),fontFamily:'"SF Mono", "JetBrains Mono", ui-monospace, Menlo, Consolas, monospace',fontSize:13,cursorBlink:!0,scrollback:8e3}),Y=new hd;j.loadAddon(Y),j.open(B),h.current={term:j,fit:Y},l&&j.focus();const q=()=>{j.options.theme=Io()};window.addEventListener(ls,q),j.attachCustomKeyEventHandler(Q=>{if(Q.type!=="keydown")return!0;const O=Q.key?.toLowerCase();if((Q.ctrlKey||Q.metaKey)&&O==="v")return!1;if(Q.ctrlKey&&!Q.shiftKey&&!Q.altKey&&O==="c"&&j.hasSelection()){const F=j.textarea;return F&&(F.value=j.getSelection(),F.select()),!1}return!0});const C=m(e,t,{write:Q=>j.write(P1(Q).clean),dispose:()=>j.dispose()}),Te=()=>{try{Y.fit(),J({type:"terminal_resize",terminalId:t,conversationId:e,cols:j.cols,rows:j.rows})}catch{}},xe=requestAnimationFrame(()=>{try{Y.fit()}catch{}g.current||J(n?{type:"run_command",terminalId:t,conversationId:e,command:n,cols:j.cols,rows:j.rows}:{type:"terminal_create",terminalId:t,title:a,locale:E.current,agentBash:c,conversationId:e,cwd:r,cols:j.cols,rows:j.rows})}),G=j.onData(Q=>{J({type:"terminal_input",terminalId:t,conversationId:e,data:Q})});let ee=null;return typeof ResizeObserver<"u"&&(ee=new ResizeObserver(()=>{B.offsetWidth>0&&B.offsetHeight>0&&Te()}),ee.observe(B)),()=>{cancelAnimationFrame(xe),G.dispose(),window.removeEventListener(ls,q),ee?.disconnect(),C(),j.dispose(),h.current=null}},[e,t,N,m]),o.useEffect(()=>{if(!l)return;const B=requestAnimationFrame(()=>{const j=h.current;if(j){try{j.fit.fit(),J({type:"terminal_resize",terminalId:t,conversationId:e,cols:j.term.cols,rows:j.term.rows})}catch{}j.term.focus()}});return()=>cancelAnimationFrame(B)},[l]);const{t:R}=Vt(),M=o.useRef(void 0);return o.useEffect(()=>{if(u===M.current||(M.current=u,u!==!1))return;const B=h.current;B&&B.term.write(`\r
|
|
351
|
+
\x1B[90m${R("exitBanner",{code:d??""})}\x1B[0m\r
|
|
352
|
+
`)},[u,t,d]),s.jsx("div",{ref:f,className:`term-xterm ${l?"":"hidden"}`})}const Zo={name:"",command:"",cwd:"${pwd}"};function As(e,t){return!e||e.length===0?null:s.jsx("span",{className:"slot-toolbar",children:e.map((n,r)=>{const a=`${n.id}#${r}`,c=n.label||n.id,l=n.hint||c;return n.kind==="divider"?s.jsx("span",{className:"slot-divider","aria-hidden":"true"},a):n.kind==="badge"?s.jsx("span",{className:"slot-badge",title:l,children:n.badge??c},a):n.kind==="toggle"?s.jsxs("button",{type:"button",className:`slot-btn${n.checked?" on":""}`,title:l,"aria-label":c,"aria-pressed":!!n.checked,onClick:()=>t?.(n),children:[n.icon?s.jsx("span",{"aria-hidden":!0,children:n.icon}):null,s.jsx("span",{children:c})]},a):n.kind==="progress"?s.jsx("span",{className:"slot-progress",title:`${l} ${n.progress??0}%`,children:s.jsx("progress",{value:n.progress??0,max:100})},a):n.kind==="input"?s.jsx("input",{className:"slot-input",defaultValue:n.value??"",placeholder:c,title:l,"aria-label":c,onKeyDown:u=>{u.key==="Enter"&&!u.nativeEvent.isComposing&&t?.(n)}},`${a}:${n.value??""}`):s.jsxs("button",{type:"button",className:"slot-btn",title:l,"aria-label":c,onClick:()=>t?.(n),children:[n.icon?s.jsx("span",{"aria-hidden":!0,children:n.icon}):null,s.jsx("span",{children:c})]},a)})})}function D1({chat:e,terminal:t,uiTerminalToolbar:n,onUiAction:r}){const a=He(),[c,l]=o.useState(null),[u,d]=o.useState(!1),[m,f]=o.useState(!1),[h,b]=o.useState(null),[E,N]=o.useState(Zo),[g,R]=o.useState(null),M=o.useRef(null),[B,j]=o.useState(!0),[Y,q]=o.useState(null),[C,Te]=o.useState("");o.useEffect(()=>{e.terminals.length===0?l(null):e.terminals.some(I=>I.id===c)||l(e.terminals[e.terminals.length-1].id)},[e.terminals,c]),o.useEffect(()=>{e.terminalActiveId&&(l(e.terminalActiveId),d(!1))},[e.terminalActiveId]),o.useEffect(()=>()=>{M.current&&clearTimeout(M.current)},[]);const xe=e.terminals.filter(I=>!I.agentBash),G=e.terminals.filter(I=>I.agentBash),ee=I=>{if(!e.ready)return;const he=qt(),_=e.activeConversationId||e.state?.conversationId||"";t.create({...I,id:he,conversationId:_,cols:I.cols??80,rows:I.rows??24,running:!0,exitCode:null}),l(he),d(!1)},Q=()=>ee({title:a("terminalTitle",{n:xe.length+1}),cwd:e.state?.cwd??""}),O=I=>{const he=I.name||I.command,_=e.terminals.find(re=>re.title===he);if(_){t.restart(_.id),l(_.id),J({type:"run_command",terminalId:_.id,conversationId:_.conversationId,command:I,cols:80,rows:24});return}ee({title:he,cwd:e.state?.cwd??"",command:I})},F=I=>{const he=e.terminals.find(_=>_.id===I);if(he&&J({type:"terminal_kill",terminalId:I,conversationId:he.conversationId}),t.close(I),c===I){const _=e.terminals.filter(re=>re.id!==I);l(_.length>0?_[_.length-1].id:null)}},w=I=>s.jsxs("div",{className:`term-tab ${I.id===c?"active":""}`,children:[s.jsxs("button",{type:"button",className:"term-tab-main",title:`${I.cwd}${I.command?`
|
|
353
|
+
> ${I.command.command}`:""}`,onClick:()=>{Y||(l(I.id),d(!1))},children:[s.jsx("span",{className:`term-tab-dot ${I.running?"run":"exit"}`}),s.jsxs("span",{className:"term-tab-title",children:[Y===I.id?s.jsx("input",{autoFocus:!0,className:"term-tab-rename-input",value:C,placeholder:I.title,onClick:he=>he.stopPropagation(),onChange:he=>Te(he.target.value),onKeyDown:he=>{if(he.stopPropagation(),he.key==="Enter"&&!he.nativeEvent.isComposing){const _=C.trim();_&&J({type:"rename_terminal",terminalId:I.id,conversationId:I.conversationId,title:_}),q(null)}else he.key==="Escape"&&q(null)},onBlur:()=>q(null)}):I.title,!I.running&&s.jsx("span",{className:"term-tab-exit",children:a("exited",{code:I.exitCode===null?"":` ${I.exitCode}`})})]})]}),s.jsx("button",{type:"button",className:"term-tab-close term-tab-rename",title:a("renameTerminal"),onClick:he=>{he.stopPropagation(),Te(I.title),q(I.id)},children:s.jsx(zs,{})}),s.jsx("button",{type:"button",className:"term-tab-close",title:a("closeTerminal"),onClick:()=>F(I.id),children:s.jsx(bt,{})})]},I.id),se=()=>{f(!0),b(null),N(Zo)},z=I=>{const he=e.commands[I];he&&(f(!1),b(I),N({name:he.name,command:he.command,cwd:he.cwd??""}))},A=()=>{f(!1),b(null)},ue=()=>{const I=E.name.trim(),he=E.command.trim();if(!I||!he)return;const _=E.cwd.trim(),re={name:I,command:he,cwd:_||void 0},le=m?[...e.commands,re]:h!==null?e.commands.map((Ee,Ne)=>Ne===h?re:Ee):e.commands;J({type:"save_commands",commands:le}),A()},P=I=>{if(g===I){const he=e.commands.filter((_,re)=>re!==I);J({type:"save_commands",commands:he}),R(null),M.current&&clearTimeout(M.current)}else R(I),M.current&&clearTimeout(M.current),M.current=setTimeout(()=>R(null),2500)},ie=m||h!==null;return s.jsxs("div",{className:"terminal-view",children:[s.jsxs("aside",{className:`term-side term-commands ${u?"open":""}`,children:[s.jsxs("div",{className:"panel-header",children:[s.jsx("span",{className:"panel-title",children:a("commands")}),s.jsxs("div",{className:"panel-header-actions",children:[s.jsx("button",{type:"button",className:"panel-refresh",title:a("rerun"),onClick:()=>J({type:"list_commands"}),children:s.jsx(Yt,{})}),s.jsx("button",{type:"button",className:"panel-new",title:a("newCommand"),onClick:se,children:s.jsx(Dt,{})})]})]}),s.jsx("div",{className:"panel-body",children:ie?s.jsxs("div",{className:"cmd-form",children:[s.jsx("label",{htmlFor:"cmd-name",children:a("name")}),s.jsx("input",{id:"cmd-name",className:"cmd-input",value:E.name,placeholder:a("exampleName"),autoFocus:!0,onChange:I=>N({...E,name:I.target.value})}),s.jsx("label",{htmlFor:"cmd-command",children:a("command")}),s.jsx("input",{id:"cmd-command",className:"cmd-input",value:E.command,placeholder:a("exampleCommand"),onChange:I=>N({...E,command:I.target.value}),onKeyDown:I=>{I.key==="Enter"&&!I.nativeEvent.isComposing&&ue()}}),s.jsxs("label",{htmlFor:"cmd-cwd",children:[a("directory")," ",s.jsx("span",{className:"cmd-hint",children:a("cwdHint")})]}),s.jsx("input",{id:"cmd-cwd",className:"cmd-input",value:E.cwd,placeholder:"${pwd}",onChange:I=>N({...E,cwd:I.target.value}),onKeyDown:I=>{I.key==="Enter"&&!I.nativeEvent.isComposing&&ue()}}),s.jsxs("div",{className:"cmd-form-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:A,children:a("cancel")}),s.jsx("button",{type:"button",className:"btn primary",disabled:!E.name.trim()||!E.command.trim(),onClick:ue,children:a("save")})]})]}):s.jsxs(s.Fragment,{children:[e.commands.length===0&&s.jsx("div",{className:"panel-empty",children:a("noCommands")}),e.commands.map((I,he)=>s.jsxs("div",{className:"cmd-item",children:[s.jsx("button",{type:"button",className:"cmd-run",title:a("clickToRun"),onClick:()=>O(I),children:s.jsx(Pd,{})}),s.jsxs("button",{type:"button",className:"cmd-main",title:a("clickToRun"),onClick:()=>O(I),children:[s.jsx("span",{className:"cmd-name",children:I.name}),s.jsx("span",{className:"cmd-command",children:I.command}),I.cwd&&s.jsx("span",{className:"cmd-cwd",children:I.cwd})]}),s.jsx("button",{type:"button",className:"cmd-act",title:a("edit"),onClick:()=>z(he),children:s.jsx(zs,{})}),s.jsx("button",{type:"button",className:`cmd-act del ${g===he?"confirm":""}`,title:a("delete"),onClick:()=>P(he),children:g===he?a("confirmQ"):s.jsx(Rt,{})})]},he))]})}),s.jsxs("div",{className:"term-tabs-block",children:[s.jsxs("div",{className:"panel-header",children:[s.jsx("span",{className:"panel-title",children:a("terminal")}),s.jsx("button",{type:"button",className:"panel-new",title:a("newTerminal"),onClick:Q,children:s.jsx(Dt,{})}),As(n,r)]}),s.jsxs("div",{className:"panel-body",children:[e.terminals.length===0&&s.jsx("div",{className:"panel-empty",children:a("noTerminal")}),xe.map(w),G.length>0&&s.jsxs("div",{className:"term-folder",children:[s.jsxs("button",{type:"button",className:`term-folder-header ${B?"open":""}`,title:a("aiBashGroup"),onClick:()=>j(I=>!I),children:[s.jsx("span",{className:"term-folder-caret",children:B?"▾":"▸"}),s.jsx("span",{className:"term-folder-title",children:a("aiBashGroup")}),s.jsx("span",{className:"term-folder-count",children:G.length})]}),B&&s.jsx("div",{className:"term-folder-body",children:G.map(w)})]})]})]})]}),s.jsxs("div",{className:"term-main",children:[u&&s.jsx("div",{className:"drawer-backdrop",onClick:()=>d(!1)}),s.jsx("button",{type:"button",className:"term-side-toggle",title:a("commands"),onClick:()=>d(I=>!I),children:s.jsx(Tl,{})}),e.terminals.length===0?s.jsxs("div",{className:"term-empty",children:[s.jsx(Rn,{className:"term-empty-icon"}),s.jsx("div",{className:"term-empty-title",children:a("builtinTerminal")}),s.jsx("div",{className:"term-empty-sub",children:a("termEmptySub")})]}):e.terminals.map(I=>s.jsx(L1,{conversationId:I.conversationId,terminalId:I.id,command:I.command,cwd:I.cwd,title:I.title,agentBash:I.agentBash,active:I.id===c,running:I.running,exitCode:I.exitCode,register:t.register},`${I.conversationId}:${I.id}`))]})]})}const O1=Object.freeze(Object.defineProperty({__proto__:null,TerminalPanel:D1,renderSlotToolbar:As},Symbol.toStringTag,{value:"Module"})),M1=o.memo(function({goal:t,models:n,modelsLoading:r,activeConversationId:a,uiGoalbarActions:c,onUiAction:l}){const u=He(),{locale:d}=Vt(),m=d!=="zh"&&t.statusEn?t.statusEn:t.status||"",f=d!=="zh"&&t.wizard?.statusEn?t.wizard.statusEn:t.wizard?.status||"",h=Kl(),b=!t.conversationId||t.conversationId===a,E=t.goal!==null&&b,[N,g]=o.useState(""),[R,M]=o.useState(t.reviewModel??""),[B,j]=o.useState(t.maxRounds),[Y,q]=o.useState(t.locked),[C,Te]=o.useState(!1),[xe,G]=o.useState(!1),[ee,Q]=o.useState(!0);o.useEffect(()=>{M(t.reviewModel??""),j(t.maxRounds||0),q(t.locked)},[t.goal,t.reviewModel,t.maxRounds,t.locked]),o.useEffect(()=>{C&&n.length===0&&!xe&&!r&&(G(!0),J({type:"list_models"}))},[C,n.length,xe,r]),o.useEffect(()=>{n.length>0&&G(!1)},[n.length]);const O=()=>R?n.find(z=>z.id===R)?.name??R:u("goalBarUseMainModel"),F=()=>{const z=N.trim();z&&(J({type:"set_goal",goal:z,...R?{reviewModel:R}:{},maxRounds:B,locked:Y}),g(""),Q(!1))},w=()=>{const z=N.trim();z&&(J({type:"start_goal_wizard",text:z,...R?{wizardModel:R}:{},maxRounds:B,locked:Y}),g(""),Q(!1))},se=(t.wizard?.active??!1)&&b;return se?s.jsx("div",{className:`goalbar goalbar-active ${se?"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:[u("goalWizardRunning"),": ",t.wizard?.draft]}),s.jsxs("span",{className:"goalbar-chip reviewing",children:[u("goalBarRound",{n:(t.wizard?.step??0)+1})," / ",t.wizard?.maxSteps??6]}),s.jsx("span",{className:"goalbar-detail",children:f||u("goalBarReviewing")}),s.jsx("button",{type:"button",className:"goalbar-x",title:u("goalBarClear"),onClick:()=>{J({type:"clear_goal"}),Q(!0)},children:s.jsx(bt,{})}),As(c,l)]})}):E?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:[u("goalBarReviewing")," ",u("goalBarRound",{n:t.round})]}):s.jsx("span",{className:`goalbar-chip ${t.verdict==="pass"?"pass":t.verdict==="fail"?"fail":""}`,children:t.verdict==="pass"?u("goalBarPassed"):t.verdict==="fail"?u("goalBarFailed"):`${u("goalBarRound",{n:t.round||1})} · ${t.locked?u("goalBarLocked"):u("goalBarUnlocked")}`}),s.jsx("span",{className:"goalbar-detail",children:m}),s.jsx("button",{type:"button",className:"goalbar-x",title:u("goalBarClear"),disabled:t.reviewing,onClick:()=>{J({type:"clear_goal"}),Q(!0)},children:s.jsx(bt,{})}),As(c,l)]})}):ee?s.jsxs("div",{className:"goalbar goalbar-collapsed",children:[s.jsxs("button",{type:"button",className:"goalbar-hint",title:u("goalBarPlaceholder"),onClick:()=>Q(!1),children:[s.jsx(yi,{})," ",s.jsx("span",{children:u("goalBarTitle")})]}),As(c,l)]}):s.jsxs("div",{className:"goalbar",children:[s.jsxs("div",{className:"goalbar-row",children:[s.jsx("span",{className:"goalbar-icon",children:s.jsx(yi,{})}),s.jsx("input",{className:"goalbar-input",value:N,placeholder:u("goalBarPlaceholder"),onChange:z=>g(z.target.value),onKeyDown:z=>{z.key==="Enter"&&F()}}),s.jsx("button",{type:"button",className:"goalbar-btn",disabled:!N.trim(),onClick:F,children:u("goalBarSet")}),s.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!N.trim(),title:u("goalWizardTip"),onClick:w,children:["🔍 ",u("goalWizardBtn")]}),s.jsx("button",{type:"button",className:"goalbar-icon-btn",title:u(Y?"goalBarLocked":"goalBarUnlocked"),onClick:()=>q(z=>(J({type:"set_goal_prefs",locked:!z}),!z)),children:Y?s.jsx(ur,{}):s.jsx(jd,{})}),s.jsx("button",{type:"button",className:"goalbar-icon-btn",title:u("goalBarClear"),onClick:()=>Q(!0),children:s.jsx(Ra,{})}),As(c,l)]}),s.jsxs("div",{className:"goalbar-opts",children:[h?s.jsx("p",{className:"goalbar-dsh-note",children:u("dshNoReviewModel")}):s.jsxs(zt,{trigger:s.jsxs("span",{className:"goalbar-opt",children:[u("goalBarReviewModel"),": ",s.jsx("b",{children:O()})]}),open:C,onOpenChange:Te,direction:"up",children:[s.jsx("div",{className:"dd-header",children:u("goalBarReviewModel")}),(xe||r)&&s.jsx("div",{className:"dd-loading",children:u("loading")}),n.length===0&&!xe&&!r&&s.jsx("div",{className:"dd-loading",children:u("noModels")}),s.jsx(wt,{active:R==="",onClick:()=>{M(""),Te(!1),J({type:"set_goal_prefs",reviewModel:""})},children:u("goalBarUseMainModel")}),n.map(z=>s.jsx(wt,{active:R===z.id,onClick:()=>{M(z.id),Te(!1),J({type:"set_goal_prefs",reviewModel:z.id})},children:s.jsxs("span",{className:"dd-model-cell",children:[s.jsx("span",{className:"dd-model-name",children:z.name}),s.jsxs("span",{className:"dd-model-meta",children:[s.jsx("span",{className:"dd-model-provider",children:z.provider}),s.jsx("span",{className:"dd-model-id",children:z.id.split("/").slice(1).join("/")})]})]})},z.id)),s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>J({type:"list_models"}),children:u("refreshModels")})]}),s.jsxs("label",{className:"goalbar-round",title:u("goalBarMaxRoundsTip"),children:[s.jsx("span",{children:u("goalBarMaxRounds")}),s.jsx("input",{type:"number",min:0,step:1,value:B,placeholder:u("goalBarUnlimitedShort"),onChange:z=>{const A=parseInt(z.target.value,10);if(Number.isNaN(A)||A<0){j(0);return}j(A)},onBlur:()=>J({type:"set_goal_prefs",maxRounds:B}),onKeyDown:z=>{z.key==="Enter"&&(J({type:"set_goal_prefs",maxRounds:B}),z.target.blur())}})]}),s.jsx("span",{className:"goalbar-lock-hint",children:u(Y?"goalBarLocked":"goalBarUnlocked")})]})]})});function B1(e){const t=Math.max(0,e.input??0),n=Math.max(0,e.cacheRead??0),r=Math.max(0,e.cacheWrite??0),a=t+n+r;return{totalInput:a,miss:t,read:n,write:r,hitRate:a>0?Math.min(n/a,1):0,writeRate:a>0?Math.min(r/a,1):0}}const Eu=2e3;function F1(e,t,n=Eu){return e.filter(r=>t-r.t<=n)}function H1(e,t=Eu){if(e.length<2)return 0;const n=e[e.length-1],r=e.find(c=>c.t>=n.t-t)??e[0],a=(n.t-r.t)/1e3;return a<=0?0:Math.max(0,(n.out-r.out)/a)}function el(e){if(!e)return 0;let t=0;for(let r=0;r<e.length;r++){const a=e.charCodeAt(r);(a>=12352&&a<=12543||a>=13312&&a<=19903||a>=19968&&a<=40959||a>=63744&&a<=64255||a>=65280&&a<=65519||a===12288)&&t++}const n=e.length-t;return Math.round(t+n/4)}function U1(e){let t=0;for(const n of e)n.type==="text"&&typeof n.text=="string"&&n.text?t+=el(n.text):n.type==="thinking"&&typeof n.thinking=="string"&&n.thinking&&(t+=el(n.thinking));return t}const ts="@root",$1=["host:conn","host:engine","host:ctx","host:cost","host:cache","host:msg-count","host:plugin-status","host:working","host:cwd"];function q1({chat:e,bottombarItems:t,onUiAction:n}){const r=He(),{engine:a}=Qr(),c=$t("workspaceRoots"),l=e.state,[u,d]=o.useState(!1),[m,f]=o.useState(""),[h,b]=o.useState(""),[E,N]=o.useState(!1),[g,R]=o.useState(""),[M,B]=o.useState(-1),j=o.useRef(null),Y=o.useRef(null),q=e.pathCompletions.filter(ce=>ce.type==="dir"),C=ce=>ce.endsWith("/")?ce:ce+"/",Te=ce=>{let pe=ce.endsWith("/")&&ce!=="/"?ce.slice(0,-1):ce;if(pe===ts||pe==="/")return null;const Fe=pe.lastIndexOf("/");if(Fe<0)return/^[A-Za-z]:$/.test(pe)?ts:null;if(Fe===0)return"/";const Ae=pe.slice(0,Fe);return/^[A-Za-z]:$/.test(Ae)?Ae+"/":Ae};o.useEffect(()=>{if(!u)return;const ce=setTimeout(()=>{J({type:"complete_path",path:C(m)})},60);return()=>clearTimeout(ce)},[m,u]),o.useEffect(()=>{if(!u||h===m)return;const ce=setTimeout(()=>{J({type:"complete_path",path:h})},150);return()=>clearTimeout(ce)},[h,m,u]);const xe=o.useRef([]),G=l?.isStreaming??!1,ee=l?.streamingMessage?U1(l.streamingMessage.content):0;if(o.useEffect(()=>{if(!G){xe.current=[];return}const ce=Date.now(),pe=xe.current,Fe=pe[pe.length-1];Fe&&ce-Fe.t<250||(xe.current=F1([...pe,{t:ce,out:ee}],ce))},[G,ee]),!l)return null;const Q=l.stats,O=B1(Q.tokens),F=O.hitRate*100,w=O.totalInput===0?"":O.hitRate>=.7?"ok":O.hitRate>=.4?"mid":"warn",se=O.totalInput>0?`${F.toFixed(1)}%`:"—",z=G?H1(xe.current):0,A=e.ready?"ok":"busy",ue=e.ready?r("connected"):r("connecting"),P=Q.contextUsage,ie=P.tokens!==null&&P.percent!==null?`${P.estimated?"~":""}${Fs(P.tokens)} / ${Fs(P.contextWindow)}`:"—",I=P.percent??null,he=I===null?"":I>=80?"warn":I>=50?"mid":"ok",_=l.queue.steering.length+l.queue.followUp.length,re=()=>{const ce=l.cwd.replace(/\\/g,"/");b(ce),f(ce),N(!1),R(""),d(!0)},le=ce=>{const pe=ce.trim();pe!==ts&&(pe&&pe!==l.cwd&&J({type:"set_cwd",path:pe}),d(!1))},Ee=()=>{const ce=g.trim();ce&&(J({type:"make_dir",path:`${C(m)}${ce}`}),setTimeout(()=>{J({type:"complete_path",path:C(m)})},80),R(""),N(!1))},Ne=ce=>{if(ce.key==="Escape")ce.stopPropagation(),d(!1);else if(ce.key==="Enter"&&!ce.nativeEvent.isComposing)le(h);else if(ce.key==="Tab"){if(q.length===0)return;ce.preventDefault();const pe=M>=0?(M+1)%q.length:0;B(pe),b(q[pe].path),f(q[pe].path)}},Ue=Te(m),ke={"host:conn":s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`status-dot ${A}`,title:ue}),s.jsx("span",{className:"status-item",children:ue})]}),"host:engine":a!=="pi"?s.jsx("span",{className:`status-item engine-badge engine-${a}`,title:`${r("engineBadge")}: ${a}`,children:a==="dsh"?"DSH":a}):null,"host:ctx":s.jsxs("span",{className:"status-item status-ctx",title:r("contextUsage"),children:[s.jsx("span",{className:"ctx-label",children:r("context")}),s.jsx("span",{className:`ctx-bar ${he}`,children:I!==null&&s.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(I,100)}%`}})}),ie]}),"host:cost":s.jsxs("span",{className:"status-item",title:r("cumulativeCost"),children:["$",W1(Q.cost)]}),"host:cache":s.jsxs("span",{className:"status-item status-cache",title:r("cacheHitTip",{read:Fs(O.read),write:Fs(O.write),miss:Fs(O.miss),input:Fs(O.totalInput)}),children:[r("cacheHit"),s.jsx("b",{className:`cache-pct ${w}`,children:se})]}),"host:msg-count":s.jsxs("span",{className:"status-item",title:r("sessionMessages"),children:[r("messages")," ",Q.totalMessages]}),"host:plugin-status":e.statuses.length>0?s.jsx("span",{className:"status-item ext-status",title:r("pluginStatus"),children:e.statuses.map(ce=>ce.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"}),r("working"),_>0&&s.jsxs("span",{className:"status-queue",children:["⏳ ",_," ",r("queued")]})]}),s.jsxs("span",{className:"status-item status-rate",title:r("rateTip"),children:[s.jsx("span",{className:"working-spin rate-spin"}),z>0?`${Math.round(z)}${r("tps")}`:"…"]})]}):null,"host:cwd":u?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"status-cwd-backdrop",onClick:()=>d(!1)}),s.jsxs("div",{className:"cwd-picker",children:[s.jsxs("div",{className:"cwd-picker-head",children:[s.jsxs("span",{className:"cwd-picker-title",title:m===ts?r("computer"):m,children:[m===ts?"💻":s.jsx(is,{}),s.jsx("span",{children:m===ts?r("computer"):m})]}),s.jsx("button",{type:"button",className:"cwd-up",disabled:m===ts,title:r("computer"),onClick:()=>{f(ts),b(ts),B(-1)},children:"💻"}),s.jsxs("button",{type:"button",className:"cwd-up",disabled:!Ue,title:r("cwdGoUp"),onClick:()=>{Ue&&(f(Ue),b(Ue),B(-1))},children:["↑ ",r("cwdGoUp")]}),(()=>{const ce=Ae=>{const et=Ae.replace(/\\/g,"/").replace(/\/+$/,"");return/^[A-Za-z]:/.test(et)?et.toLowerCase():et},pe=ce(m),Fe=!!m&&m!==ts&&pe!==ce(l.cwd)&&!c.some(Ae=>ce(Ae)===pe);return s.jsxs("button",{type:"button",className:"cwd-up",disabled:!Fe,title:r("addWorkspaceRootHint"),onClick:()=>{Fe&&J({type:"set_workspace_roots",roots:[...c,m]})},children:["+ ",r("addWorkspaceRoot")]})})()]}),s.jsxs("div",{className:"cwd-picker-row",children:[s.jsx("input",{ref:j,className:"status-cwd-input cwd-picker-input",value:h,placeholder:r("enterPath"),spellCheck:!1,onChange:ce=>{b(ce.target.value),B(-1)},onKeyDown:Ne}),s.jsx("button",{type:"button",className:"cwd-choose-btn primary",title:r("cwdPickCurrent"),disabled:m===ts,onClick:()=>le(m),children:r("cwdPickCurrent")})]}),s.jsxs("div",{className:"cwd-list",children:[q.length===0&&s.jsx("div",{className:"cwd-empty",children:r("cwdEmpty")}),q.map(ce=>s.jsxs("div",{className:"cwd-item",children:[s.jsxs("button",{type:"button",className:"cwd-enter",title:`${r("cwdEnter")} ${ce.path}`,onClick:()=>{f(ce.path),b(ce.path),B(-1)},children:[s.jsx(is,{}),s.jsx("span",{className:"cwd-name",children:ce.name})]}),s.jsx("button",{type:"button",className:"cwd-choose-btn",title:r("cwdChoose"),onClick:()=>le(ce.path),children:r("cwdChoose")})]},ce.path))]}),s.jsx("div",{className:"cwd-picker-foot",children:E?s.jsxs("div",{className:"cwd-newrow",children:[s.jsx("input",{ref:Y,value:g,autoFocus:!0,spellCheck:!1,placeholder:r("cwdNewName"),onChange:ce=>R(ce.target.value),onKeyDown:ce=>{ce.key==="Enter"&&!ce.nativeEvent.isComposing?(ce.preventDefault(),Ee()):ce.key==="Escape"&&(ce.stopPropagation(),N(!1),R(""))}}),s.jsx("button",{type:"button",className:"cwd-choose-btn primary",onClick:Ee,children:r("cwdCreate")}),s.jsx("button",{type:"button",className:"cwd-choose-btn",onClick:()=>{N(!1),R("")},children:r("cwdCancel")})]}):s.jsxs("button",{type:"button",className:"cwd-newbtn",onClick:()=>N(!0),children:["+ ",r("cwdNewFolder")]})})]})]}):s.jsxs("button",{type:"button",className:"status-item status-cwd",title:r("cwdTip",{path:l.cwd}),onClick:re,children:["📁 ",l.cwd]})},Ke=t?t.map(ce=>({id:ce.id,entry:ce})):$1.map(ce=>({id:ce,entry:null})),Ie=[];for(const{id:ce,entry:pe}of Ke)if(!pe?.hidden){if(ce.startsWith("host:")){const Fe=ke[ce];Fe&&Ie.push({key:ce,node:Fe});continue}pe&&Ie.push({key:ce,node:s.jsxs("button",{type:"button",className:"status-action",title:pe.hint??pe.label,onClick:()=>n?.(pe),children:[pe.icon?`${pe.icon} `:"",pe.label,pe.badge?s.jsx("span",{className:"status-badge",children:pe.badge}):null]})})}return s.jsx("footer",{className:"statusbar",children:Ie.map((ce,pe)=>s.jsxs(o.Fragment,{children:[pe>0&&s.jsx("span",{className:"status-sep",children:"·"}),ce.node]},ce.key))})}function Fs(e){return e>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(e)}function W1(e){return e<=0?"0":e<1e-4?"<0.0001":e.toFixed(4).replace(/\.?0+$/,"")}function K1({dialog:e}){const t=He(),[n,r]=o.useState(""),[a,c]=o.useState(0),l=m=>{J({type:"dialog_response",id:e.id,value:m})};o.useEffect(()=>{r(""),c(0);const m=f=>{f.key==="Escape"&&l(null)};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[e.id]);const u=Array.isArray(e.args[0])?e.args[0]:[],d=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((m,f)=>s.jsx("button",{type:"button",className:`dialog-option ${f===a?"sel":""}`,onMouseEnter:()=>c(f),onClick:()=>l(m),children:s.jsx(Ot,{text:m,rawHtml:!0})},f)),u.length===0&&s.jsx("div",{className:"dialog-hint",children:t("noOptions")})]}),e.kind==="confirm"&&s.jsxs("div",{className:"dialog-body",children:[s.jsx(Ot,{text:d,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:d||t("inputPlaceholder"),autoFocus:!0,onChange:m=>r(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.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 G1=150;function Y1({anchorRef:e,enabled:t=!0,className:n,children:r}){const a=o.useRef(null),c=o.useRef(null),[l,u]=o.useState(!1),[d,m]=o.useState({left:0,top:0}),f=o.useCallback(()=>{c.current!==null&&(clearTimeout(c.current),c.current=null)},[]),h=o.useCallback(()=>{f(),c.current=setTimeout(()=>u(!1),G1)},[f]);return o.useEffect(()=>{const b=e.current;if(!b)return;const E=()=>{f(),u(!0)};b.addEventListener("mouseenter",E);const N=g=>{const R=g.relatedTarget;R&&a.current?.contains(R)||h()};return b.addEventListener("mouseleave",N),t&&(b.addEventListener("focus",E),b.addEventListener("blur",h)),()=>{f(),b.removeEventListener("mouseenter",E),b.removeEventListener("mouseleave",N),b.removeEventListener("focus",E),b.removeEventListener("blur",h)}},[e,t,f,h]),o.useLayoutEffect(()=>{if(!l)return;const b=e.current?.getBoundingClientRect();if(!b)return;const E={left:Math.max(ss,b.left-ss),top:b.bottom+ss};m(N=>N.left===E.left&&N.top===E.top?N:E)},[l,e]),o.useLayoutEffect(()=>{if(!l)return;const b=a.current,E=e.current;if(!b||!E)return;const N=oc(E.getBoundingClientRect(),b.getBoundingClientRect(),{width:window.innerWidth,height:window.innerHeight});m(g=>g.left===N.left&&g.top===N.top?g:N)},[l,e,r]),o.useEffect(()=>{if(!l)return;const b=()=>u(!1);return window.addEventListener("scroll",b,!0),window.addEventListener("resize",b),()=>{window.removeEventListener("scroll",b,!0),window.removeEventListener("resize",b)}},[l]),l?In.createPortal(s.jsx("div",{ref:a,className:`set-tip-bubble open${n?` ${n}`:""}`,role:"tooltip",style:{position:"fixed",left:d.left,top:d.top},onMouseEnter:f,onMouseLeave:h,children:r}),document.body):null}function z1({question:e}){const t=He(),[n,r]=o.useState({}),[a,c]=o.useState({}),[l,u]=o.useState(0),[d,m]=o.useState(()=>e.deadline?Math.max(0,Math.ceil((e.deadline-Date.now())/1e3)):-1);o.useEffect(()=>{r({}),c({}),u(0),m(e.deadline?Math.max(0,Math.ceil((e.deadline-Date.now())/1e3)):-1)},[e.id,e.deadline]),o.useEffect(()=>{if(!e.deadline)return;const j=setInterval(()=>{m(Y=>{const q=Math.max(0,Math.ceil((e.deadline-Date.now())/1e3));return q<=0&&Y>0&&J({type:"question_answer",id:e.id,answers:[],cancelled:!0}),q})},1e3);return()=>clearInterval(j)},[e.id,e.deadline]),o.useEffect(()=>{const j=Y=>{Y.key==="Escape"&&E()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[e.id]);const f=e.questions.length,h=e.questions[l];if(!h)return null;const b=j=>{const Y=e.questions.map(q=>{const C=j[q.id]??[],Te=(a[q.id]??"").trim();return{id:q.id,selected:C,...Te?{custom:Te}:{}}});J({type:"question_answer",id:e.id,answers:Y})},E=()=>{J({type:"question_answer",id:e.id,answers:[],cancelled:!0})},N=(j,Y)=>{r(q=>{const C=q[j]??[];return{...q,[j]:C.includes(Y)?C.filter(Te=>Te!==Y):[...C,Y]}})},g=(j,Y,q)=>{if(q){N(j,Y);return}const C={...n,[j]:[Y]};r(C),l===f-1?b(C):u(l+1)},R=()=>{l===f-1?b(n):u(l+1)},M=j=>(e.questions.find(q=>q.id===j)?.options?.length??0)===0?!0:(n[j]?.length??0)>0||(a[j]??"").trim()!=="",B=(h.options??[]).filter(j=>(n[h.id]??[]).includes(j.label)&&j.preview).map(j=>j.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")}),f>1&&s.jsx("span",{className:"question-progress",children:t("questionStep",{cur:l+1,total:f})}),d>=0&&s.jsx("span",{className:"question-timer",children:d>0?t("questionTimeout",{s:d}):t("questionTimeoutExpired")}),s.jsx("button",{type:"button",className:"dialog-dismiss",title:t("cancel"),onClick:E,children:"✕"})]}),s.jsxs("div",{className:"set-section",children:[s.jsx("div",{className:"set-section-title",children:h.header??`${t("modelQuestion")} ${l+1}`}),s.jsx("div",{className:"question-head",children:s.jsx(Ot,{text:h.question,rawHtml:!0})}),h.detail&&s.jsx("div",{className:"set-hint",children:s.jsx(Ot,{text:h.detail,rawHtml:!0})}),(h.options?.length??0)>0&&s.jsx("div",{className:"set-list",children:h.options.map(j=>{const Y=(n[h.id]??[]).includes(j.label);return s.jsx(V1,{label:j.label,description:j.description,mark:h.multiSelect?Y?"☑ ":"☐ ":Y?"● ":"○ ",active:Y,onPick:()=>g(h.id,j.label,!!h.multiSelect)},j.label)})}),B.length>0&&s.jsxs("div",{className:"question-preview",children:[s.jsx("div",{className:"question-preview-label",children:t("optionPreview")}),B.map((j,Y)=>s.jsx("div",{className:"question-preview-body",children:s.jsx(Ot,{text:j,rawHtml:!0})},Y))]}),s.jsx("input",{className:"set-prompt-input question-custom",placeholder:t("modelQuestionCustom"),value:a[h.id]??"",onChange:j=>c(Y=>({...Y,[h.id]:j.target.value})),onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),M(h.id)&&R())}})]},h.id),s.jsxs("div",{className:"dialog-nav",children:[s.jsx("button",{type:"button",className:"dialog-dismiss-inline",onClick:E,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:!M(h.id),onClick:R,children:l===f-1?t("modelQuestionSubmit"):t("next")})]})]})]})}function V1({label:e,description:t,mark:n,active:r,onPick:a}){const c=o.useRef(null);return s.jsxs("button",{type:"button",ref:c,className:`set-row question-option${r?" active":""}`,onClick:a,children:[s.jsxs("div",{className:"set-row-name",children:[s.jsx("span",{className:"question-mark",children:n}),s.jsx(Ot,{text:e,rawHtml:!0})]}),t&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"set-row-desc",children:s.jsx(Ot,{text:t,rawHtml:!0})}),s.jsx(Y1,{anchorRef:c,enabled:Km(),className:"question-desc-tip",children:s.jsx(Ot,{text:t,rawHtml:!0})})]})]})}const tl=e=>`'${e.replace(/'/g,"'\\''")}'`,Sa=300,sl=200,nl=720,Q1=220,al="pi-web-ui:scm-sidebar-width";function yu(e,t=0){if(!Number.isFinite(e))return Sa;const n=Math.max(sl,Math.min(nl,t>0?t-Q1:nl));return Math.min(n,Math.max(sl,Math.round(e)))}function X1(e){return e===null||e.trim()===""?Sa:yu(Number(e))}function J1(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 Z1({chat:e,terminal:t,active:n,onSwitchToTerminal:r,uiScmToolbar:a,onUiAction:c}){const l=He(),[u,d]=o.useState(null),[m,f]=o.useState([]),[h,b]=o.useState(""),[E,N]=o.useState(new Map),[g,R]=o.useState("changes"),[M,B]=o.useState([]),[j,Y]=o.useState(null),[q,C]=o.useState(""),[Te,xe]=o.useState(!1),[G,ee]=o.useState(null),[Q,O]=o.useState(null),[F,w]=o.useState(!1),[se,z]=o.useState(!1),[A,ue]=o.useState(!1),[P,ie]=o.useState(null),[I,he]=o.useState(!1),[_,re]=o.useState(()=>X1(localStorage.getItem(al))),[le,Ee]=o.useState(""),Ne=o.useRef(0),Ue=o.useRef(-1),ke=o.useRef(-1),Ke=o.useRef(-1),Ie=o.useRef(-1),ce=o.useRef(void 0),pe=o.useRef(null),Fe=o.useRef([]),Ae=o.useRef(_);Ae.current=_;const et=o.useRef(null),dt=o.useCallback(U=>{try{localStorage.setItem(al,String(U))}catch{}},[]),Ve=o.useCallback(U=>{U.preventDefault();const Pe=U.clientX,Le=Ae.current,ot=et.current?.getBoundingClientRect().width??0;let Ye=Le;const ct=Mt=>{Ye=yu(Le+(Mt.clientX-Pe),ot),re(Ye)},mt=()=>{window.removeEventListener("pointermove",ct),window.removeEventListener("pointerup",mt),document.body.classList.remove("panel-resizing"),dt(Ye)};window.addEventListener("pointermove",ct),window.addEventListener("pointerup",mt),document.body.classList.add("panel-resizing")},[dt]),X=o.useCallback(()=>{re(Sa),dt(Sa)},[dt]),we=o.useCallback(U=>{if(U.reqId===Ue.current){if(Ue.current=-1,z(!1),ie(null),!U.ok){ie(U.error??l("scmQueryFailedShort"));return}if(U.notRepo){he(!0),d(null),f([]),N(new Map),B([]),Y(null),C(""),O(null);return}he(!1);const Pe={branch:U.branch??"",detached:!!U.detached,upstream:U.upstream??null,ahead:U.ahead??0,behind:U.behind??0,upstreamGone:!!U.upstreamGone,files:(U.files??[]).map(Ye=>({...Ye}))},Le=(U.branches??[]).map(Ye=>({...Ye})),ot=new Map;for(const[Ye,ct]of Object.entries(U.stats??{}))ot.set(Ye,{add:ct[0],del:ct[1]});d(Pe),f(Le),N(ot),b(Ye=>Pe.detached?Ye||"":Pe.branch&&Le.some(ct=>ct.name===Pe.branch)?Pe.branch:Ye&&Le.some(ct=>ct.name===Ye)?Ye:Le[0]?.name??""),O(Ye=>Ye&&!Pe.files.some(ct=>ct.path===Ye.file.path)?null:Ye)}else if(U.reqId===ke.current){if(ke.current=-1,w(!1),!U.ok){ie(U.error??l("scmQueryFailedShort"));return}const Pe=pe.current;if(!Pe)return;O({file:Pe,staged:U.stagedText??"",worktree:U.worktreeText??"",untracked:!1})}else if(U.reqId===Ie.current){if(Ie.current=-1,ue(!1),!U.ok){ie(U.error??l("scmQueryFailedShort"));return}B((U.history??[]).map(Pe=>({...Pe})))}else if(U.reqId===Ke.current){if(Ke.current=-1,xe(!1),!U.ok){ie(U.error??l("scmQueryFailedShort"));return}C(U.text??"")}},[]);o.useEffect(()=>{const U=e.scmData;U&&U.type==="scm_data"&&we(U)},[e.scmData,we]);const L=o.useCallback((U,Pe)=>{if(!e.ready||e.status!=="open")return!1;const Le=++Ne.current;return J({...U,reqId:Le})?(Pe.current=Le,!0):(Ne.current-=1,!1)},[e.ready,e.status]),W=o.useCallback((U=!1,Pe=!1)=>{!e.ready||e.status!=="open"||e.state?.cwd&&(ce.current!==void 0&&ce.current!==e.state.cwd&&(d(null),f([]),N(new Map),B([]),ue(!1),Ie.current=-1,Y(null),C(""),O(null),ee(null)),ce.current=e.state.cwd,ie(null),L({type:"scm_status"},Ue)&&(Pe||z(!0)))},[e.ready,e.state?.cwd,e.status,L]),oe=o.useCallback(U=>{if(ee(U),Y(null),pe.current=U,U.x==="?"&&U.y==="?"){O({file:U,staged:"",worktree:"",untracked:!0});return}w(!0),ie(null),L({type:"scm_filediff",path:U.path},ke)||w(!1)},[L]),fe=o.useCallback(U=>{Y(U),ee(null),O(null),C(""),xe(!0),ie(null),L({type:"scm_commit",hash:U.hash},Ke)||xe(!1)},[L]),de=o.useCallback((U,Pe)=>{if(!e.ready)return;const Le={name:U,command:Pe,cwd:"${pwd}"};let ot;const Ye=e.terminals.find(ct=>ct.title===U);Ye?(t.restart(Ye.id),J({type:"run_command",terminalId:Ye.id,conversationId:Ye.conversationId,command:Le,cols:80,rows:24}),ot=Ye.id):(ot=qt(),t.create({id:ot,conversationId:e.activeConversationId||e.state?.conversationId||"",title:U,cwd:e.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:Le})),t.select(ot),r()},[e.ready,e.state?.cwd,e.terminals,r,t]),ge=o.useCallback(()=>{const U=le.trim();if(!U||I)return;const Pe=U.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");de("git commit",`git commit -m "${Pe}"`),Ee("")},[le,I,de]),Qe=o.useCallback(()=>{const U=le.trim();if(!U||I)return;const Pe=U.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");de("git commit",`git add -A && git commit -m "${Pe}"`),Ee("")},[le,I,de]),ye=o.useCallback(U=>{I||de("git add",`git add -- ${tl(U.path)}`)},[I,de]),Oe=o.useCallback(U=>{I||de("git reset",`git reset HEAD -- ${tl(U.path)}`)},[I,de]),rt=o.useCallback(()=>{if(!h||I)return;const U=m.find(Pe=>Pe.name===h);if(U?.remote&&typeof U.remote=="string"){const Pe=h.slice(U.remote.length+1);de("git checkout",`git checkout -b ${Pe} ${h} || git checkout ${h}`)}else de("git checkout",`git checkout ${h}`)},[h,m,I,de]),Ge=o.useCallback(()=>de("git push","git push"),[de]),D=o.useCallback(()=>de("git pull","git pull"),[de]),$e=o.useCallback(()=>{L({type:"scm_history"},Ie)||(Ie.current=-1)},[L]);o.useEffect(()=>{n&&W()},[n,W]),o.useEffect(()=>{g==="history"&&u&&$e()},[g,u,$e]),o.useEffect(()=>{e.scmDirty>0&&n&&W(!1,!0)},[e.scmDirty]),o.useEffect(()=>{if(!n||!e.ready||e.status!=="open")return;const U=setInterval(()=>{document.visibilityState!=="hidden"&&W(!1,!0)},3e4);return()=>clearInterval(U)},[n,e.ready,e.status,W]),o.useEffect(()=>{const U=Fe.current;if(Fe.current=e.terminals,!n)return;e.terminals.some(Le=>Le.running!==!1?!1:U.find(Ye=>Ye.id===Le.id)?.running===!0&&Le.title.startsWith("git "))&&e.ready&&e.status==="open"&&(W(!1,!0),g==="history"&&u&&$e())},[e.terminals,n,e.ready,e.status,W,g,u,$e]);const it={staged:l("scmStaged"),unstaged:l("scmUnstaged"),untracked:l("scmUntracked"),both:l("scmStagedUnstaged")},Xe=U=>{const Pe=U.split(`
|
|
354
|
+
`);return s.jsx("pre",{className:"scm-diff-pre",children:Pe.map((Le,ot)=>{let Ye="";return Le.startsWith("diff --git")||Le.startsWith("index ")||Le.startsWith("new file")||Le.startsWith("deleted file")||Le.startsWith("old mode")||Le.startsWith("new mode")||Le.startsWith("similarity index")||Le.startsWith("rename ")||Le.startsWith("copy ")||Le.startsWith("Binary files")||Le.startsWith("---")||Le.startsWith("+++")?Ye="hdr":Le.startsWith("@@")?Ye="hunk":Le.startsWith("+")?Ye="add":Le.startsWith("-")&&(Ye="del"),s.jsx("div",{className:`scm-diff-line ${Ye}`,children:Le||" "},ot)})})};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(Yn,{}),l("scmTitle")]}),s.jsxs("div",{className:"scm-view-tabs",role:"tablist",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":g==="changes",className:g==="changes"?"active":"",onClick:()=>{R("changes"),ie(null)},children:l("scmChanges")}),s.jsx("button",{type:"button",role:"tab","aria-selected":g==="history",className:g==="history"?"active":"",onClick:()=>{R("history"),ie(null)},children:l("scmHistory")})]}),s.jsx("button",{type:"button",className:"panel-refresh",title:l("scmRefreshTip"),disabled:se,onClick:()=>W(!0),children:s.jsx(Yt,{className:se?"scm-spin":""})}),As(a,c)]}),s.jsxs("div",{className:"scm-row",children:[s.jsxs("span",{className:"scm-branch-current",title:l("scmCurrentBranch"),children:[s.jsx(Yn,{}),u?u.detached?l("scmDetached"):u.branch:"…",u?.upstream&&s.jsx("span",{className:"scm-upstream",children:u.upstreamGone?l("scmUpstreamGone"):u.ahead>0||u.behind>0?l("scmAheadBehind",{ahead:u.ahead,behind:u.behind}):u.upstream})]}),s.jsxs("select",{className:"scm-select",value:h,disabled:I||m.length===0,title:l("scmSwitchBranch"),onChange:U=>b(U.target.value),children:[s.jsx("option",{value:"",disabled:!0,children:l("scmSelectBranch")}),m.filter(U=>!U.remote).map(U=>s.jsx("option",{value:U.name,children:U.current?`* ${U.name}`:U.name},U.name)),m.some(U=>U.remote)&&s.jsx("optgroup",{label:l("scmRemoteBranches"),children:m.filter(U=>U.remote).map(U=>s.jsx("option",{value:U.name,children:U.name},U.name))})]}),s.jsxs("button",{type:"button",className:"btn",disabled:!h||h===u?.branch||I,title:l("scmSwitchBranchTip",{branch:h}),onClick:rt,children:[s.jsx(Yn,{}),l("scmSwitch")]}),s.jsxs("button",{type:"button",className:"btn",disabled:!u||u.detached||I,title:l("scmPushTip"),onClick:Ge,children:[s.jsx(mr,{}),l("scmPush")]}),s.jsxs("button",{type:"button",className:"btn",disabled:!u||u.detached||I,title:l("scmPullTip"),onClick:D,children:[s.jsx(wl,{}),l("scmPull")]}),s.jsx("input",{className:"scm-commit-input",value:le,placeholder:l("scmCommitPlaceholder"),disabled:I,onChange:U=>Ee(U.target.value),onKeyDown:U=>{U.key==="Enter"&&!U.nativeEvent.isComposing&&ge()}}),s.jsxs("button",{type:"button",className:"btn primary",disabled:!le.trim()||I,title:l("scmCommitTip"),onClick:ge,children:[s.jsx(os,{}),l("scmCommit")]}),s.jsx("button",{type:"button",className:"btn",disabled:!le.trim()||I,title:l("scmCommitAllTip"),onClick:Qe,children:l("scmCommitAll")})]})]}),s.jsxs("div",{className:"scm-body",ref:et,style:{"--scm-sidebar-w":`${_}px`},children:[g==="history"?s.jsxs("div",{className:"scm-history",children:[s.jsxs("div",{className:"scm-files-header",children:[s.jsx("span",{children:l("scmHistory")}),M.length>0&&s.jsx("span",{className:"scm-files-count",children:M.length})]}),s.jsx("div",{className:"scm-history-list",children:I?s.jsx("div",{className:"scm-empty",children:l("scmNotGitRepo")}):!u||A?s.jsx("div",{className:"scm-empty",children:e.status==="open"?l("scmLoading"):l("scmConnecting")}):M.length===0?s.jsx("div",{className:"scm-empty",children:l("scmNoHistory")}):M.map(U=>s.jsxs("button",{type:"button",className:`scm-commit ${j?.hash===U.hash?"active":""}`,onClick:()=>fe(U),title:U.hash,children:[s.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:U.graph||"* "}),s.jsxs("span",{className:"scm-commit-info",children:[s.jsx("span",{className:"scm-commit-subject",children:U.subject}),s.jsxs("span",{className:"scm-commit-meta",children:[U.shortHash," · ",U.author," · ",U.date]}),U.decorations&&s.jsx("span",{className:"scm-commit-refs",children:U.decorations})]})]},U.hash))})]}):s.jsxs("div",{className:"scm-files",children:[s.jsxs("div",{className:"scm-files-header",children:[s.jsx("span",{children:l("scmChanges")}),u&&u.files.length>0&&s.jsx("span",{className:"scm-files-count",children:u.files.length})]}),s.jsx("div",{className:"scm-files-list",children:I?s.jsx("div",{className:"scm-empty",children:l("scmNotGitRepo")}):u?u.files.length===0?s.jsx("div",{className:"scm-empty",children:l("scmNoChanges")}):u.files.map(U=>{const Pe=J1(U),Le=E.get(U.path);return s.jsxs("div",{className:`scm-file ${G?.path===U.path?"active":""}`,title:it[Pe],onClick:()=>oe(U),children:[s.jsx("span",{className:`scm-file-xy ${Pe==="untracked"?"q":"x"}`,children:U.x!==" "?U.x:" "}),s.jsx("span",{className:`scm-file-xy ${Pe==="untracked"?"q":"y"}`,children:U.y!==" "?U.y:" "}),s.jsx("span",{className:"scm-file-path",children:U.path}),Le&&(Le.add>0||Le.del>0)&&s.jsxs("span",{className:"scm-file-stat",children:[Le.add>0&&s.jsxs("span",{className:"add",children:["+",Le.add]}),Le.del>0&&s.jsxs("span",{className:"del",children:["-",Le.del]})]}),s.jsxs("span",{className:"scm-file-actions",children:[(U.y!==" "||Pe==="untracked")&&s.jsx("button",{type:"button",className:"scm-act",title:l("scmStageTip",{path:U.path}),onClick:ot=>{ot.stopPropagation(),ye(U)},children:"+"}),Pe==="staged"||Pe==="both"?s.jsx("button",{type:"button",className:"scm-act",title:l("scmUnstageTip",{path:U.path}),onClick:ot=>{ot.stopPropagation(),Oe(U)},children:"−"}):null]})]},U.path)}):s.jsx("div",{className:"scm-empty",children:e.status==="open"?l("scmLoading"):l("scmConnecting")})})]}),s.jsx("div",{className:"scm-divider",role:"separator","aria-orientation":"vertical",title:l("dragToResize"),onPointerDown:Ve,onDoubleClick:X}),s.jsxs("div",{className:"scm-diff",children:[s.jsxs("div",{className:"scm-diff-header",children:[s.jsx("span",{children:g==="history"?j?`${j.shortHash} ${j.subject}`:l("scmCommitDetail"):G?G.path:l("scmDiff")}),(g==="history"?Te:F)&&s.jsx("span",{className:"scm-diff-loading",children:l("scmLoading")})]}),s.jsx("div",{className:"scm-diff-body",children:g==="history"?s.jsxs(s.Fragment,{children:[P&&s.jsx("div",{className:"scm-error",children:P}),!j&&!P&&s.jsx("div",{className:"scm-empty",children:l("scmSelectCommitHint")}),j&&Te&&!P&&s.jsx("div",{className:"scm-empty",children:l("scmLoading")}),j&&!Te&&!P&&q?Xe(q):null]}):s.jsxs(s.Fragment,{children:[P&&s.jsx("div",{className:"scm-error",children:P}),!G&&!P&&s.jsx("div",{className:"scm-empty",children:l("scmSelectFileHint")}),G&&!Q&&!P&&s.jsx("div",{className:"scm-empty",children:l("scmLoading")}),G&&Q&&Q.untracked&&s.jsx("div",{className:"scm-empty",children:l("scmUntrackedNote")}),G&&Q&&!Q.untracked&&s.jsxs(s.Fragment,{children:[Q.staged&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"scm-diff-section",children:l("scmStaged")}),Xe(Q.staged)]}),Q.worktree&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"scm-diff-section",children:l("scmUnstaged")}),Xe(Q.worktree)]}),!Q.staged&&!Q.worktree&&s.jsx("div",{className:"scm-empty",children:l("scmNoDiff")})]})]})})]})]}),s.jsxs("div",{className:"scm-hint",children:[s.jsx(Rn,{}),s.jsx("span",{children:l("scmRunsInTerminal")}),s.jsx("button",{type:"button",className:"scm-goto-term",onClick:r,children:l("scmViewTerminal")})]})]})}function ex({entry:e}){const t=o.useRef(null),n=He();return o.useEffect(()=>{const r=t.current;if(!r)return;let a;try{a=e.module.mount(r,ac(e.info.id,c=>J(c)))}catch(c){console.error(`[plugin:${e.info.id}] mount failed:`,c),r.textContent=n("pluginMountFailed",{name:e.info.name})}return()=>{if(typeof a=="function")try{a()}catch(c){console.error(`[plugin:${e.info.id}] cleanup failed:`,c)}r.textContent=""}},[e]),s.jsx("div",{className:"plugin-view",ref:t})}function tx({onAction:e}){const t=Dp(),n=o.useMemo(()=>t?fa(t.entries):[],[t]),r=o.useMemo(()=>Fi(n),[n]),a=o.useRef(null),c=o.useRef(null),[l,u]=o.useState(null),[d,m]=o.useState(-1),[f,h]=o.useState(-1),[b,E]=o.useState(!1),[N,g]=o.useState(0),R=o.useRef(-1),M=G=>{R.current=G,m(G)},B=o.useMemo(()=>f>=0?fa(n[f]?.children??[]):[],[n,f]),j=o.useMemo(()=>Fi(B),[B]),Y=G=>{const ee=n[G];if(!(!t||!ee||Jn(ee))){if(ee.children?.length){h(G);return}q(ee,t)||vs()}},q=(G,ee)=>G.source==="host"&&ee.onHostAction?ee.onHostAction(G,ee.target)===!0:(e(G,ee.target),!1),C=o.useRef(Y);if(o.useLayoutEffect(()=>{C.current=Y}),o.useEffect(()=>{if(!t){R.current=-1,m(-1),h(-1);return}const G=Hi(n,-1,1);R.current=G,m(G),h(-1),a.current?.focus()},[t,n]),o.useLayoutEffect(()=>{if(!t){u(null);return}const G=a.current;if(!G)return;const ee=G.getBoundingClientRect();u(Op(t.x,t.y,ee.width,ee.height,window.innerWidth,window.innerHeight))},[t,n]),o.useLayoutEffect(()=>{const G=c.current,ee=a.current;if(f<0||!G||!ee){E(!1),g(0);return}const Q=G.getBoundingClientRect(),O=ee.getBoundingClientRect(),F=window.innerWidth-O.right,w=O.left;E(F<Q.width+ps&&w>F);const se=Q.bottom-(window.innerHeight-ps);g(se>0?-Math.min(se,Math.max(0,Q.top-ps)):0)},[f,n]),o.useEffect(()=>{if(!t)return;const G=F=>a.current&&F instanceof Node&&a.current.contains(F),ee=F=>{G(F.target)||vs()},Q=F=>{G(F.target)||vs()},O=()=>vs();return document.addEventListener("mousedown",ee,!0),window.addEventListener("wheel",Q,!0),window.addEventListener("resize",O),()=>{document.removeEventListener("mousedown",ee,!0),window.removeEventListener("wheel",Q,!0),window.removeEventListener("resize",O)}},[t]),o.useEffect(()=>{if(!t)return;const G=Q=>{const O=Hi(n,R.current,Q);R.current=O,m(O)},ee=Q=>{switch(Q.key){case"Escape":Q.preventDefault(),vs();return;case"Tab":vs();return;case"ArrowDown":Q.preventDefault(),G(1);return;case"ArrowUp":Q.preventDefault(),G(-1);return;case"ArrowRight":n[R.current]?.children?.length&&(Q.preventDefault(),h(R.current));return;case"ArrowLeft":f>=0&&(Q.preventDefault(),h(-1));return;case"Enter":case" ":Q.preventDefault(),C.current(R.current);return;default:return}};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[t,n,f]),o.useEffect(()=>{d<0||a.current?.querySelector('[data-ctx-active="true"]')?.scrollIntoView?.({block:"nearest"})},[d]),!t)return null;const Te=G=>{Jn(G)||q(G,t)||vs()},xe=(G,ee,Q)=>{const O=Jn(G),F=!!G.children?.length,w=Fp(G.icon),se=Q&&d===ee;return s.jsxs("div",{className:"ctx-menu-itemwrap",role:"none",children:[s.jsxs("button",{type:"button",role:"menuitem",className:`ctx-menu-item${O?" disabled":""}${se?" active":""}${F?" has-sub":""}`,"aria-label":G.label,title:G.hint,"aria-disabled":O||void 0,"aria-haspopup":F?"menu":void 0,"aria-expanded":F?f===ee:void 0,"data-ctx-active":se?"true":void 0,onMouseEnter:Q?()=>{M(ee),F&&!O&&h(ee)}:void 0,onClick:()=>Q?Y(ee):Te(G),children:[w?s.jsx("span",{className:"ctx-menu-icon","aria-hidden":"true",children:w}):null,s.jsx("span",{className:"ctx-menu-label",children:G.label}),G.badge?s.jsx("span",{className:"ctx-menu-badge",children:G.badge}):null,F?s.jsx("span",{className:"ctx-menu-caret","aria-hidden":"true",children:"▸"}):null]}),Q&&F&&f===ee?s.jsx("div",{ref:c,className:`ctx-menu-sub${b?" left":""}`,role:"menu","aria-label":G.label,style:N?{marginTop:N}:void 0,children:j.map(z=>z.kind==="sep"?s.jsx("div",{className:"ctx-menu-sep",role:"separator"},z.key):xe(z.entry,z.index,!1))}):null]},`${G.id}#${ee}`)};return In.createPortal(s.jsx("div",{ref:a,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:G=>{G.preventDefault(),G.stopPropagation()},children:r.map(G=>G.kind==="sep"?s.jsx("div",{className:"ctx-menu-sep",role:"separator"},G.key):xe(G.entry,G.index,!0))}),document.body)}function Tu({provider:e,flow:t,result:n}){const r=He(),a=t?.event,c=e.oauthName??e.name,[l,u]=o.useState("");return o.useEffect(()=>u(""),[t?.promptId]),e.usingOAuth?s.jsxs("div",{className:"provider-oauth",children:[s.jsx("span",{className:"provider-oauth-status",children:r("oauthConnected",{name:c})}),s.jsx("button",{type:"button",className:"btn sm danger","data-provider-oauth-logout":e.id,onClick:()=>J({type:"provider_oauth_logout",provider:e.id}),children:r("oauthLogout")}),n?.error&&s.jsx("div",{className:"provider-oauth-error",children:n.error})]}):s.jsxs("div",{className:"provider-oauth",children:[t?s.jsxs(s.Fragment,{children:[a?.type==="device_code"&&s.jsxs("div",{className:"provider-oauth-device",children:[s.jsx("div",{children:r("oauthDeviceCode")}),s.jsx("code",{"data-oauth-device-code":!0,children:a.userCode}),s.jsx("a",{"data-oauth-verification-url":!0,href:a.verificationUri,target:"_blank",rel:"noreferrer",children:r("oauthOpenVerification")})]}),a?.type==="auth_url"&&s.jsxs("div",{className:"provider-oauth-event",children:[a.instructions&&s.jsx("div",{children:a.instructions}),s.jsx("a",{href:a.url,target:"_blank",rel:"noreferrer",children:r("oauthOpenVerification")})]}),a?.type==="progress"&&s.jsx("div",{className:"provider-oauth-message",children:a.message}),a?.type==="info"&&s.jsxs("div",{className:"provider-oauth-event",children:[s.jsx("div",{children:a.message}),a.links?.map(d=>s.jsx("a",{href:d.url,target:"_blank",rel:"noreferrer",children:d.label??d.url},d.url))]}),t.prompt&&s.jsx("div",{className:"provider-oauth-message",children:t.prompt.message}),t.prompt?.type==="select"&&t.promptId&&s.jsx("div",{className:"provider-oauth-options",children:t.prompt.options.map(d=>s.jsx("button",{type:"button",className:"btn sm","data-oauth-option":d.id,onClick:()=>J({type:"provider_oauth_reply",flowId:t.flowId,promptId:t.promptId,value:d.id}),children:d.label},d.id))}),t.prompt&&t.prompt.type!=="select"&&t.promptId&&s.jsxs("form",{className:"provider-oauth-prompt",onSubmit:d=>{d.preventDefault(),l.trim()&&J({type:"provider_oauth_reply",flowId:t.flowId,promptId:t.promptId,value:l.trim()})},children:[s.jsx("input",{"data-oauth-prompt-input":!0,type:t.prompt.type==="secret"?"password":"text",className:"key-input",placeholder:t.prompt.placeholder,value:l,onChange:d=>u(d.target.value)}),s.jsx("button",{type:"submit",className:"btn primary sm","data-oauth-prompt-submit":!0,disabled:!l.trim(),children:r("oauthContinue")})]}),s.jsx("button",{type:"button",className:"btn sm danger","data-oauth-cancel":t.flowId,onClick:()=>J({type:"provider_oauth_cancel",flowId:t.flowId}),children:r("cancel")})]}):s.jsx("button",{type:"button",className:"btn primary sm","data-provider-oauth-login":e.id,onClick:()=>J({type:"provider_oauth_start",provider:e.id}),children:r("oauthLogin",{name:c})}),n?.error&&s.jsx("div",{className:"provider-oauth-error",children:n.error})]})}function sx({piConfigured:e,piAgentInstalled:t,providers:n,providerOAuthFlows:r,providerOAuthResults:a,installResult:c,onClose:l}){const u=He(),d=Gl(),[m,f]=o.useState(!1),[h,b]=o.useState(""),[E,N]=o.useState(""),[g,R]=o.useState(!1);o.useEffect(()=>{J({type:"list_providers"}),J({type:"list_provider_oauth_flows"})},[]),o.useEffect(()=>{e&&l()},[e,l]),o.useEffect(()=>{c&&f(!1)},[c]),o.useEffect(()=>{!h&&n.length>0&&b(n.find(C=>!C.configured)?.id??n[0].id)},[n,h]);const M=()=>{m||(f(!0),J({type:"install_pi_agent"}))},B=()=>{!E.trim()||g||(R(!0),J({type:"set_provider_api_key",provider:h.trim(),apiKey:E.trim()}),setTimeout(()=>R(!1),3e3))},j=()=>{J({type:"get_state"}),J({type:"list_providers"})},Y=n.find(C=>C.id===h),q=c!==null&&!c.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":u("close"),onClick:l,children:s.jsx(bt,{})}),s.jsxs("div",{className:"modal-head",children:[s.jsx(Ts,{className:"modal-head-icon"}),s.jsx("h2",{children:u("setupTitle")})]}),s.jsx("p",{className:"modal-desc",children:u("setupDesc")}),q?s.jsxs("div",{className:"setup-failed",children:[s.jsx("div",{className:"setup-done",children:u("installFailed")}),s.jsx("pre",{className:"setup-detail",children:c.detail}),s.jsxs("div",{className:"setup-actions",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:m,onClick:M,children:u("retryInstall")}),s.jsx("button",{type:"button",className:"btn",onClick:l,children:u("skip")})]})]}):t||c?.ok?s.jsxs("div",{className:"setup-key-form",children:[s.jsx("div",{className:"setup-done",children:c?.ok?u("installDone"):u("cliReadyHint")}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:u("provider")}),s.jsxs("select",{value:h,onChange:C=>b(C.target.value),children:[n.length===0&&s.jsx("option",{value:"",children:u("loading")}),n.map(C=>s.jsxs("option",{value:C.id,children:[C.name,"(",C.id,")",C.configured?` · ${u("configured")}`:""]},C.id))]}),Y?.configured&&s.jsx("div",{className:"field-hint",children:u("providerKeyReady")})]}),Y?.supportsOAuth&&s.jsx(Tu,{provider:Y,flow:r.find(C=>C.provider===Y.id),result:a[Y.id]}),Y?.supportsApiKey&&s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:u("apiKey")}),s.jsx("input",{type:"password",value:E,onChange:C=>N(C.target.value),placeholder:"sk-…"})]}),s.jsxs("div",{className:"setup-actions",children:[Y?.supportsApiKey&&s.jsx("button",{type:"button",className:"btn primary",disabled:!E.trim()||g||!h,onClick:B,children:u(g?"saving":"saveAndStart")}),s.jsxs("button",{type:"button",className:"btn",onClick:j,children:[s.jsx(Yt,{})," ",u("recheck")]})]})]}):d?s.jsxs("div",{className:"setup-actions",children:[s.jsx("div",{className:"setup-done",children:u("updatesManaged")}),s.jsx("button",{type:"button",className:"btn",onClick:l,children:u("skip")})]}):s.jsxs("div",{className:"setup-actions",children:[s.jsx("button",{type:"button",className:"btn primary",disabled:m,onClick:M,children:u(m?"installing":"autoInstall")}),s.jsx("button",{type:"button",className:"btn",onClick:l,children:u("skip")})]})]})})}const nx=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],oi=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),ax=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[oi()]});function ar(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:[oi()]).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 rx({providers:e,providerStatus:t,providerKeys:n,providerOAuthFlows:r,providerOAuthResults:a,fetchModelsResult:c,cloneProviderResult:l,onClose:u}){const d=He(),[m,f]=o.useState(null),[h,b]=o.useState({}),[E,N]=o.useState({}),[g,R]=o.useState(null),[M,B]=o.useState(!1),[j,Y]=o.useState(0),[q,C]=o.useState(null),Te=o.useRef(0),[xe,G]=o.useState(null),[ee,Q]=o.useState(""),[O,F]=o.useState(null);o.useEffect(()=>{J({type:"list_models_config"}),J({type:"list_providers"}),J({type:"list_provider_keys"}),J({type:"list_provider_oauth_flows"})},[]);const w=()=>{if(!m)return;const _=m.baseUrl.trim();if(!_){C({ok:!1,text:d("fetchModelsNeedBaseUrl")});return}if(M)return;B(!0),C(null);const re=j+1;Y(re),J({type:"fetch_models",reqId:re,baseUrl:_,apiKey:m.apiKey.trim()||void 0,authHeader:m.authHeader,api:m.api})};o.useEffect(()=>{if(!(!c||c.reqId===Te.current))if(Te.current=c.reqId,B(!1),c.ok&&c.models?.length){const _=c.models;f(re=>{if(!re)return re;const le=re.models.map(ke=>{if(!ke.id.trim())return ke;const Ke=_.find(ce=>ce.id===ke.id.trim());if(!Ke)return ke;const Ie={...ke};return!Ie.name&&Ke.name&&(Ie.name=Ke.name),!Ie.contextWindow&&Ke.contextWindow&&(Ie.contextWindow=String(Ke.contextWindow)),!Ie.maxTokens&&Ke.maxTokens&&(Ie.maxTokens=String(Ke.maxTokens)),Ie.input==="text"&&Ke.input?.includes("image")&&(Ie.input="text-image"),!Ie.reasoning&&Ke.reasoning&&(Ie.reasoning=!0),Ie}),Ee=new Set(le.map(ke=>ke.id.trim()).filter(Boolean)),Ne=_.filter(ke=>!Ee.has(ke.id)).map(ke=>({id:ke.id,name:ke.name??"",reasoning:ke.reasoning??!1,input:ke.input?.includes("image")?"text-image":"text",contextWindow:ke.contextWindow?String(ke.contextWindow):"",maxTokens:ke.maxTokens?String(ke.maxTokens):""})),Ue=[...le,...Ne];return Ue.some(ke=>ke.id.trim())?{...re,models:Ue.filter(ke=>ke.id.trim())}:re}),C({ok:!0,text:d("fetchModelsOk",{n:_.length})})}else C({ok:!1,text:c.error||d("fetchModelsEmpty")})},[c]);const se=_=>{const re=(h[_.id]??"").trim();!re||g||(R(_.id),J({type:"add_provider_key",provider:_.id,apiKey:re,name:(E[_.id]??"").trim()||void 0}),setTimeout(()=>{R(null),b(le=>({...le,[_.id]:""})),N(le=>({...le,[_.id]:""})),J({type:"list_providers"}),J({type:"list_provider_keys"})},1500))},z=(_,re)=>{J({type:"activate_provider_key",provider:_,keyName:re}),J({type:"list_provider_keys"})},A=(_,re)=>{window.confirm(d("removeKeyConfirm"))&&(J({type:"remove_provider_key",provider:_,keyName:re}),J({type:"list_provider_keys"}))},ue=()=>{if(!O)return;const _=O.providerId.trim();if(!_||!O.apiKey.trim())return;const re=O.models.filter(Ee=>Ee.id.trim()).map(Ee=>({id:Ee.id.trim(),name:Ee.name.trim()||void 0,reasoning:Ee.reasoning||void 0,input:Ee.input==="text-image"?["text","image"]:void 0,contextWindow:Ee.contextWindow?Number(Ee.contextWindow):void 0,maxTokens:Ee.maxTokens?Number(Ee.maxTokens):void 0})),le={providerId:_,name:O.name.trim()||void 0,api:O.api.trim()||void 0,baseUrl:O.baseUrl.trim()||void 0,apiKey:O.apiKey.trim()||void 0,authHeader:O.authHeader||void 0,models:re};J({type:"save_model_config",providerId:_,config:le}),F(null),u()},P=()=>{if(!m)return;const _=m.providerId.trim(),re=m.models.filter(Ee=>Ee.id.trim()).map(Ee=>({id:Ee.id.trim(),name:Ee.name.trim()||void 0,reasoning:Ee.reasoning||void 0,input:Ee.input==="text-image"?["text","image"]:void 0,contextWindow:Ee.contextWindow?Number(Ee.contextWindow):void 0,maxTokens:Ee.maxTokens?Number(Ee.maxTokens):void 0})),le={providerId:_,name:m.name.trim()||void 0,api:m.api.trim()||void 0,baseUrl:m.baseUrl.trim()||void 0,apiKey:m.apiKey.trim()||void 0,authHeader:m.authHeader||void 0,models:re};J({type:"save_model_config",providerId:_,config:le}),u()};o.useEffect(()=>{if(l&&l.ok){const _=l.configs;if(_&&_.length>1){G(_.map(re=>ar({...re,apiKey:""}))),Q("");return}if(l.config){F(ar({...l.config,apiKey:""}));return}}},[l]);const ie=_=>{window.confirm(d("clearKeyConfirm",{id:_}))&&J({type:"clear_provider_api_key",provider:_})},I=_=>{window.confirm(d("deleteProviderConfirm",{id:_.providerId,n:_.models.length}))&&J({type:"delete_model_config",providerId:_.providerId})},he=(_,re)=>{m&&f({...m,models:m.models.map((le,Ee)=>Ee===_?{...le,...re}:le)})};return s.jsx("div",{className:"modal-backdrop",onClick:u,children:s.jsxs("div",{className:"modal model-modal",onClick:_=>_.stopPropagation(),children:[s.jsx("button",{type:"button",className:"modal-close","aria-label":d("close"),onClick:u,children:s.jsx(bt,{})}),s.jsx("div",{className:"modal-head",children:s.jsx("h2",{children:O?d("addKey"):xe?d("batchCreateProviders",{n:xe.length}):d(m?"editProvider":"manageModelsTitle")})}),O?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:d("secondKeyTitle",{api:O.api,baseUrl:O.baseUrl||d("noBaseUrlShort"),n:O.models.length})}),s.jsxs("div",{className:"form-grid",children:[s.jsxs("label",{className:"field",children:[s.jsxs("span",{className:"field-label",children:[d("providerNameLabel")," ",s.jsx("em",{children:d("providerNameHint")})]}),s.jsx("input",{type:"text",value:O.providerId,onChange:_=>F({...O,providerId:_.target.value}),placeholder:"opencode-2"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:d("apiKeyLabel")}),s.jsx("input",{type:"password",value:O.apiKey,onChange:_=>F({...O,apiKey:_.target.value}),placeholder:d("secondKeyPlaceholder")})]})]}),s.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:8},children:[O.models.slice(0,5).map(_=>_.id).join(", "),O.models.length>5?` … +${O.models.length-5}`:""]})]})}),s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>F(null),children:d("cancel")}),s.jsx("button",{type:"button",className:"btn",onClick:()=>{const _=O;F(null),f(_)},children:d("advancedEdit")}),s.jsx("button",{type:"button",className:"btn primary",disabled:!O.providerId.trim()||!O.apiKey.trim(),onClick:ue,children:d("save")})]})]}):xe?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:d("batchDesc",{apis:xe.map(_=>_.api).join("、"),n:xe.length})}),s.jsxs("label",{className:"field",style:{marginBottom:16},children:[s.jsx("span",{className:"field-label",children:d("batchKeyLabel",{n:xe.length})}),s.jsx("input",{type:"password",value:ee,onChange:_=>Q(_.target.value),placeholder:d("secondKeyPlaceholder")})]}),s.jsx("div",{className:"provider-list",style:{marginBottom:16},children:xe.map((_,re)=>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:_.providerId}),s.jsx("span",{style:{opacity:.7},children:_.api})]}),s.jsxs("div",{className:"provider-sub",style:{fontSize:12,opacity:.7},children:[_.baseUrl||d("noBaseUrlShort")," · ",d("modelsCountShort",{n:_.models.length}),_.models.slice(0,3).map(le=>le.id).join(", "),_.models.length>3?` … +${_.models.length-3}`:""]}),s.jsx("input",{type:"text",value:_.providerId,onChange:le=>G(Ee=>Ee.map((Ne,Ue)=>Ue===re?{...Ne,providerId:le.target.value}:Ne)),placeholder:d("providerIdPlaceholder"),style:{fontSize:12}}),s.jsx("input",{type:"text",value:_.baseUrl,onChange:le=>G(Ee=>Ee.map((Ne,Ue)=>Ue===re?{...Ne,baseUrl:le.target.value}:Ne)),placeholder:d("baseUrlExamplePh"),style:{fontSize:12}})]},re))})]})}),s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>G(null),children:d("cancel")}),s.jsx("button",{type:"button",className:"btn primary",disabled:!ee.trim(),onClick:()=>{for(const _ of xe){const re=_.providerId.trim();if(!re)continue;const le=_.models.filter(Ne=>Ne.id.trim()).map(Ne=>({id:Ne.id.trim(),name:Ne.name.trim()||void 0,reasoning:Ne.reasoning||void 0,input:Ne.input==="text-image"?["text","image"]:void 0,contextWindow:Ne.contextWindow?Number(Ne.contextWindow):void 0,maxTokens:Ne.maxTokens?Number(Ne.maxTokens):void 0})),Ee={providerId:re,name:_.name.trim()||void 0,api:_.api.trim()||void 0,baseUrl:_.baseUrl.trim()||void 0,apiKey:ee.trim()||void 0,authHeader:_.authHeader||void 0,models:le};J({type:"save_model_config",providerId:re,config:Ee})}G(null),u()},children:d("saveAllBatch",{n:xe.length})})]})]}):m?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:[d("providerId")," ",s.jsx("em",{children:d("providerIdHint")})]}),s.jsx("input",{type:"text",value:m.providerId,disabled:e.some(_=>_.providerId===m.providerId),onChange:_=>f({...m,providerId:_.target.value}),placeholder:"my-proxy"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:d("displayName")}),s.jsx("input",{type:"text",value:m.name,onChange:_=>f({...m,name:_.target.value}),placeholder:d("displayNamePh")})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:d("apiType")}),s.jsx("select",{value:m.api,onChange:_=>f({...m,api:_.target.value}),children:nx.map(_=>s.jsx("option",{value:_,children:_},_))})]}),s.jsxs("label",{className:"field",children:[s.jsxs("span",{className:"field-label",children:["baseUrl ",s.jsx("em",{children:d("baseUrlHint")})]}),s.jsx("input",{type:"text",value:m.baseUrl,onChange:_=>f({...m,baseUrl:_.target.value}),placeholder:"http://localhost:11434/v1"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{className:"field-label",children:d("apiKey")}),s.jsx("input",{type:"password",value:m.apiKey,onChange:_=>f({...m,apiKey:_.target.value}),placeholder:d("apiKeyHint")})]}),s.jsxs("label",{className:"field check",children:[s.jsx("input",{type:"checkbox",checked:m.authHeader,onChange:_=>f({...m,authHeader:_.target.checked})}),s.jsx("span",{children:d("authHeader")})]})]}),s.jsxs("div",{className:"model-section-head",children:[s.jsx("span",{className:"form-section-title",children:d("modelsTitle")}),s.jsxs("span",{className:"model-section-actions",children:[q&&s.jsx("span",{className:`fetch-msg ${q.ok?"ok":"err"}`,title:q.text,children:q.text}),s.jsxs("button",{type:"button",className:"btn sm",disabled:M||!m.baseUrl.trim(),title:d("fetchModelsHint"),onClick:w,children:[s.jsx(Rs,{})," ",d(M?"fetchingModels":"fetchModels")]})]})]}),m.models.map((_,re)=>s.jsxs("div",{className:"model-row",children:[s.jsx("input",{type:"text",value:_.id,onChange:le=>he(re,{id:le.target.value}),placeholder:d("modelIdReq")}),s.jsx("input",{type:"text",value:_.name,onChange:le=>he(re,{name:le.target.value}),placeholder:d("displayName")}),s.jsxs("select",{value:_.input,onChange:le=>he(re,{input:le.target.value}),children:[s.jsx("option",{value:"text",children:d("text")}),s.jsx("option",{value:"text-image",children:d("textImage")})]}),s.jsxs("label",{className:"check",children:[s.jsx("input",{type:"checkbox",checked:_.reasoning,onChange:le=>he(re,{reasoning:le.target.checked})}),s.jsx("span",{children:d("reasoning")})]}),s.jsx("input",{type:"number",value:_.contextWindow,onChange:le=>he(re,{contextWindow:le.target.value}),placeholder:d("contextWindow"),title:"contextWindow"}),s.jsx("input",{type:"number",value:_.maxTokens,onChange:le=>he(re,{maxTokens:le.target.value}),placeholder:d("maxOutput"),title:"maxTokens"}),s.jsx("button",{type:"button",className:"iconbtn danger",title:d("removeModel"),onClick:()=>f({...m,models:m.models.filter((le,Ee)=>Ee!==re)}),children:s.jsx(Rt,{})})]},re)),s.jsxs("button",{type:"button",className:"btn",onClick:()=>f({...m,models:[...m.models,oi()]}),children:[s.jsx(Dt,{})," ",d("addModel")]})]})}),s.jsxs("div",{className:"modal-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>f(null),children:d("cancel")}),s.jsx("button",{type:"button",className:"btn primary",disabled:!m.providerId.trim()||!m.models.some(_=>_.id.trim()),onClick:P,children:d("save")})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"model-modal-fixed-hint",children:s.jsxs("div",{className:"form-section-title",children:[d("builtinProviders")," ",s.jsx("em",{className:"section-hint",children:d("providerAuthHint")})]})}),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:d("loading")}),t.map(_=>{const re=n[_.id]??[],le=r.find(Ne=>Ne.provider===_.id),Ee=a[_.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:_.name}),s.jsxs("span",{className:"provider-sub",children:[_.id,_.configured&&s.jsx("span",{className:"auth-badge",children:d("configuredBadge")}),_.source&&!_.configured&&s.jsx("span",{className:"auth-badge dim",children:_.source})]})]}),_.supportsApiKey&&_.source==="stored"&&!_.usingOAuth&&s.jsxs("button",{type:"button",className:"btn sm danger",title:d("clearKeyTitle"),onClick:()=>ie(_.id),children:[s.jsx(Rt,{})," ",d("clearKey")]})]}),_.supportsOAuth&&s.jsx(Tu,{provider:_,flow:le,result:Ee}),_.supportsApiKey&&s.jsxs("div",{className:"provider-keys",children:[re.length===0&&s.jsx("div",{className:"provider-key-empty",children:d("noKeyYet")}),re.map(Ne=>s.jsxs("div",{className:`provider-key-item ${Ne.active?"active":""}`,children:[s.jsx("span",{className:"provider-key-dot",children:Ne.active?"●":"○"}),s.jsx("span",{className:"provider-key-label",children:Ne.name}),!Ne.active&&s.jsx("button",{type:"button",className:"iconbtn",title:d("activateKey"),onClick:()=>z(_.id,Ne.name),children:s.jsx(os,{})}),s.jsx("button",{type:"button",className:"iconbtn danger",title:d("removeKey"),onClick:()=>A(_.id,Ne.name),children:s.jsx(Rt,{})})]},Ne.name)),s.jsxs("div",{className:"provider-add-key",children:[s.jsx("input",{type:"text",className:"key-input key-input-name",placeholder:d("keyNamePh"),value:E[_.id]??"",onChange:Ne=>N(Ue=>({...Ue,[_.id]:Ne.target.value}))}),s.jsx("input",{type:"password",className:"key-input key-input-value",placeholder:d("addKeyPlaceholder"),value:h[_.id]??"",onChange:Ne=>b(Ue=>({...Ue,[_.id]:Ne.target.value}))}),s.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(h[_.id]??"").trim()||g===_.id,onClick:()=>se(_),children:[s.jsx(Dt,{})," ",g===_.id?d("savingKey"):d("addKey")]})]})]})]},_.id)})]}),s.jsx("div",{className:"form-section-title",children:d("customProviders")}),s.jsx("p",{className:"modal-desc",children:d("customDesc")}),s.jsx("p",{className:"modal-desc",children:d("reloadModelsHint")}),e.length===0&&s.jsx("div",{className:"dd-loading",children:d("noCustomProviders")}),s.jsx("div",{className:"provider-list",children:e.map(_=>s.jsxs("div",{className:"provider-row",children:[s.jsxs("div",{className:"provider-info",children:[s.jsx("span",{className:"provider-name",children:_.providerId}),s.jsxs("span",{className:"provider-sub",children:[_.api??"—",_.baseUrl?` · ${_.baseUrl}`:"",_.models.length>0&&` · ${d("modelsCount",{n:_.models.length})}`]})]}),s.jsxs("div",{className:"provider-actions",children:[s.jsx("button",{type:"button",className:"iconbtn",title:d("edit"),onClick:()=>f(ar(_)),children:s.jsx(zs,{})}),s.jsx("button",{type:"button",className:"iconbtn danger",title:d("delete"),onClick:()=>I(_),children:s.jsx(Rt,{})})]})]},_.providerId))})]}),s.jsxs("div",{className:"modal-actions",children:[s.jsxs("button",{type:"button",className:"btn",onClick:()=>J({type:"reload_models_config"}),children:[s.jsx(Yt,{})," ",d("reloadModelsConfig")]}),s.jsxs("button",{type:"button",className:"btn primary",onClick:()=>f(ax()),children:[s.jsx(Dt,{})," ",d("addProvider")]})]})]})]})})}function ix({plugin:e}){const t=He(),n=e.settingsSchema??[],[r,a]=o.useState(()=>({...e.settingsValues})),[c,l]=o.useState(!1);if(n.length===0)return null;const u=(h,b)=>a(E=>({...E,[h]:b})),d=n.some(h=>r[h.key]!==e.settingsValues?.[h.key]),m=()=>{l(!0),J({type:"plugin_settings",pluginId:e.id,values:r}),setTimeout(()=>l(!1),800)},f=()=>a({...e.settingsValues});return s.jsxs("div",{className:"plugin-settings-form",children:[s.jsx("div",{className:"plugin-settings-fields",children:n.map(h=>s.jsxs("label",{className:"plugin-settings-field",title:h.hint,children:[s.jsx("span",{className:"plugin-settings-label",children:h.label}),h.type==="boolean"?s.jsx("input",{type:"checkbox",checked:!!r[h.key],onChange:b=>u(h.key,b.target.checked)}):h.type==="select"?s.jsx("select",{value:String(r[h.key]??""),onChange:b=>u(h.key,b.target.value),children:(h.options??[]).map(b=>s.jsx("option",{value:b,children:b},b))}):s.jsx("input",{type:h.type==="password"?"password":h.type==="number"?"number":"text",value:String(r[h.key]??""),min:h.min,max:h.max,onChange:b=>u(h.key,h.type==="number"?Number(b.target.value):b.target.value)})]},h.key))}),s.jsxs("div",{className:"plugin-settings-actions",children:[s.jsx("button",{type:"button",className:"btn plugin-settings-save",disabled:!d||c,onClick:m,children:t(c?"pluginSettingsSaving":"pluginSettingsSave")}),s.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:f,children:t("pluginSettingsReset")})]})]})}const ku="pi-web-ui:wide-chat",_a={wide:!1};function Nu(e){if(!e||typeof e!="object")return{..._a};const t=e;return{wide:typeof t.wide=="boolean"?t.wide:_a.wide}}function ox(){try{const e=localStorage.getItem(ku);return e?Nu(JSON.parse(e)):{..._a}}catch{return{..._a}}}function lx(e){const t=Nu(e);try{localStorage.setItem(ku,JSON.stringify(t))}catch{}sa=t;for(const n of qr)n()}let sa=null;const qr=new Set;function cx(e){return qr.add(e),()=>{qr.delete(e)}}function ux(){return sa||(sa=ox()),sa.wide}function vu(){return o.useSyncExternalStore(cx,ux)}const Cu="pi-web-ui:project-title",Aa={projectName:!0};function wu(e){if(!e||typeof e!="object")return{...Aa};const t=e;return{projectName:typeof t.projectName=="boolean"?t.projectName:Aa.projectName}}function dx(e){return e?e.replace(/[\\/]+$/,"").split(/[\\/]/).pop()??"":""}function px(){try{const e=localStorage.getItem(Cu);return e?wu(JSON.parse(e)):{...Aa}}catch{return{...Aa}}}function mx(e){const t=wu(e);try{localStorage.setItem(Cu,JSON.stringify(t))}catch{}na=t;for(const n of Wr)n()}let na=null;const Wr=new Set;function hx(e){return Wr.add(e),()=>{Wr.delete(e)}}function fx(){return na||(na=px()),na.projectName}function Su(){return o.useSyncExternalStore(hx,fx)}const _u="pi-web-ui:wallpaper",gx="has-wallpaper",wn={url:"",dim:78,blur:0},bx=2e3,xx=28e5;function Kr(e){if(typeof e!="string")return"";const t=e.trim();if(!t)return"";const n=t.toLowerCase().startsWith("data:image/")?xx:bx;return t.length>n?"":/^https?:\/\//i.test(t)||/^blob:/i.test(t)||/^data:image\//i.test(t)||t.startsWith("/")&&!t.startsWith("//")?t:""}const rl=(e,t,n,r)=>typeof e!="number"||!Number.isFinite(e)?r:Math.min(n,Math.max(t,Math.round(e)));function Au(e){if(!e||typeof e!="object")return{...wn};const t=e;return{url:Kr(t.url),dim:rl(t.dim,0,95,wn.dim),blur:rl(t.blur,0,24,wn.blur)}}function ju(){try{const e=localStorage.getItem(_u);return e?Au(JSON.parse(e)):{...wn}}catch{return{...wn}}}function Ex(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/[\r\n]/g,"")}async function yx(e){const t=await ri(e);return t?`data:${t.mimeType};base64,${t.data}`:null}function aa(){const e=Sn??ju(),t=document.documentElement;e.url?(t.style.setProperty("--bg-image",`url("${Ex(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(gx,e.url!==""||n!==""&&n!=="none")}function rn(e){const t=Au(e);Sn=t;try{localStorage.setItem(_u,JSON.stringify(t))}catch{}for(const n of Gr)n();aa()}let Sn=null;const Gr=new Set;function Tx(e){return Gr.add(e),()=>{Gr.delete(e)}}function kx(){return Sn||(Sn=ju()),Sn}function Iu(){return o.useSyncExternalStore(Tx,kx)}function Nx(){const e=Iu();o.useEffect(()=>{aa()},[e]),o.useEffect(()=>{const t=()=>aa();return window.addEventListener(ls,t),aa(),()=>window.removeEventListener(ls,t)},[])}const ja={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"]},Ru=["soul","tools","guidelines","pi_docs","append","persona","terminal","markers","context","skills","cwd"],vx=["tools","pi_docs","persona","terminal","markers","context","skills","cwd"];function Pu(e){return vx.includes(e)}const Kn=Ru.map(e=>`{{${e}}}`).join(`
|
|
355
|
+
|
|
356
|
+
`),Lu="pi-web-ui:catalog-sync-urls",Du=8;function Yr(){try{const e=localStorage.getItem(Lu);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.trim()!=="").slice(0,Du):[]}catch{return[]}}function Cx(e){const t=e.trim();if(!t)return Yr();const n=[t,...Yr().filter(r=>r!==t)].slice(0,Du);try{localStorage.setItem(Lu,JSON.stringify(n))}catch{}return n}function wx(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function il(e){return e==="append"?0:Pu(e)?2:1}function ft({title:e,subtitle:t,tip:n,enabled:r,onToggle:a,action:c}){const l=He();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(Et,{text:n})]}),t&&s.jsx("div",{className:"set-row-desc",children:t})]}),c,s.jsx("button",{type:"button",className:`set-switch ${r?"on":""}`,role:"switch","aria-checked":r,title:l(r?"settingsEnabled":"settingsDisabled"),onClick:a,children:s.jsx("span",{className:"set-switch-knob"})})]})}function Sx({chat:e,terminal:t,onSwitchToTerminal:n,onClose:r}){const a=He(),{locale:c}=Vt(),l=p=>a(p),u=e.settings,{engine:d,managed:m}=Qr(),f=d==="dsh",[h,b]=o.useState("prompt"),E=o.useRef(null);o.useEffect(()=>{E.current?.scrollTo({top:0})},[h]),o.useEffect(()=>{h==="plugins"&&f&&J({type:"dsh_patches_list"})},[h,f]);const[N,g]=o.useState(""),[R,M]=o.useState({}),B=o.useRef(!1),j=o.useRef(null),Y=[...Ru].sort((p,K)=>il(p)-il(K)),[q,C]=o.useState(null),[Te,xe]=o.useState({}),[G,ee]=o.useState(""),[Q,O]=o.useState("append"),F=o.useRef(!1),[w,se]=o.useState(""),z=o.useRef(!1),[A,ue]=o.useState(""),[P,ie]=o.useState(null),[I,he]=o.useState(null),[_,re]=o.useState(!1),[le,Ee]=o.useState(!1),Ne=vu(),Ue=Su(),ke=Iu(),[Ke,Ie]=o.useState(ke.url),ce=o.useRef(!1),pe=o.useRef(null),[Fe,Ae]=o.useState(!1),[et,dt]=o.useState(!1);o.useEffect(()=>{ce.current||Ie(ke.url.startsWith("data:")?"":ke.url)},[ke.url]);const Ve=async p=>{const K=p.target.files?.[0];if(p.target.value="",!!K){Ae(!0),dt(!1);try{const ve=await yx(K),st=ve?Kr(ve):"";if(!st){dt(!0);return}Ie(""),rn({...ke,url:st})}finally{Ae(!1)}}},[X,we]=o.useState(()=>du()),[L,W]=o.useState(()=>{try{return jn().length}catch{return 0}}),[oe,fe]=o.useState(!1),de=()=>{try{W(jn().length)}catch{W(0)}};o.useEffect(()=>{h==="prompt-history"&&de()},[h]),o.useEffect(()=>{if(!oe)return;const p=window.setTimeout(()=>fe(!1),3e3);return()=>window.clearTimeout(p)},[oe]);const[ge,Qe]=o.useState(null),[ye,Oe]=o.useState(null),[rt,Ge]=o.useState(""),[D,$e]=o.useState(""),[it,Xe]=o.useState(""),[U,Pe]=o.useState(""),[Le,ot]=o.useState(""),[Ye,ct]=o.useState(!1),[mt,Mt]=o.useState(!1),[$,Z]=o.useState(!1),[Re,je]=o.useState(""),[Je,qe]=o.useState(!1),[At,Lt]=o.useState(!1),[jt,us]=o.useState(null),[Qt,Ut]=o.useState(""),[v,te]=o.useState(()=>Yr()),[Be,ht]=o.useState(""),[nt,yt]=o.useState(null);o.useEffect(()=>{u&&(B.current||g(u.promptTemplate??""),M(p=>{const K={};for(const[ve,st]of Object.entries(u.promptOverrides??{}))K[ve]=st??"";return j.current&&(K[j.current]=p[j.current]??""),K}),O(u.visionBridgePromptMode),!F.current&&(ee(Q==="append"||u.visionBridgePrompt?u.visionBridgePrompt:u.visionBridgeDefaultPrompt||""),z.current||se(u.reviewPrompt)))},[u,Q]);const[Xt,k]=o.useState(String(u?.terminalBashIdleMs??15e3));o.useEffect(()=>{k(String(u?.terminalBashIdleMs??15e3))},[u?.terminalBashIdleMs]);const[ae,Se]=o.useState(String(u?.retryMaxAttempts??6));o.useEffect(()=>{Se(String(u?.retryMaxAttempts??6))},[u?.retryMaxAttempts]);const Me=bu(e.plugins,{locale:c,t:p=>a(p),disabledPlugins:e.settings?.disabledPlugins??[],layout:e.settings?.uiLayout}),We=[];for(const p of Me["settings.pages"]){if(p.source==="host"||p.hidden||p.kind==="divider")continue;const K=e.plugins.find(ve=>ve.id===p.source.slice(7));K&&We.push({entry:p,plugin:K})}const De=p=>`plugin-page:${p}`;if(o.useEffect(()=>{h.startsWith("plugin-page:")&&(We.some(p=>De(p.entry.id)===h)||b("prompt"))},[h,We]),!u)return null;const at=new Set(u.disabledAgentTools??[]),xt=at.size,Jt=[{id:"prompt",icon:s.jsx(Nl,{}),label:a("settingsSystemPrompt")},{id:"prompt-history",icon:s.jsx(pr,{}),label:a("settingsPromptHistory"),count:L},...f?[{id:"question",icon:s.jsx(ki,{}),label:a("settingsQuestionnaire")}]:[{id:"tools",icon:s.jsx(Ei,{}),label:a("settingsTools"),count:xt+(u.disabledMarkers?.length??0)||void 0}],{id:"display",icon:s.jsx(Is,{}),label:a("settingsMessageDisplay")},{id:"quick",icon:s.jsx(lr,{}),label:a("quickPhrases"),count:u.quickPhrases.length},{id:"skills",icon:s.jsx(Ts,{}),label:a("settingsSkills"),count:u.skills.length},{id:"extensions",icon:s.jsx(Gn,{}),label:a("settingsExtensions"),count:u.extensions.length},{id:"plugins",icon:s.jsx(Un,{}),label:a("settingsUiPlugins"),count:e.plugins.length},{id:"review",icon:s.jsx(qs,{}),label:a("settingsReview"),count:u.reviewSkills.length},...f?[]:[{id:"vision",icon:s.jsx(da,{}),label:a("settingsVisionBridge")}],{id:"presets",icon:s.jsx(Ti,{}),label:a("settingsPresets"),count:u.presets.length},...f?[]:[{id:"subagent-templates",icon:s.jsx(xi,{}),label:a("settingsSubagentTemplates"),count:u.subagentTemplates.length}],...We.map(p=>({id:De(p.entry.id),icon:p.entry.icon&&!/[a-z]/i.test(p.entry.icon)?s.jsx("span",{children:p.entry.icon}):s.jsx(Un,{}),label:p.entry.label,pluginPage:{plugin:p.plugin,entry:p.entry}}))],Nt=h.startsWith("plugin-page:")?We.find(p=>De(p.entry.id)===h)??null:null,lt=new Set(u.disabledSkills),It=new Set(u.disabledExtensions),ze=p=>J({type:"set_settings",...p}),Ns=()=>{if(!nt||!u)return;const p=nt.value.trim(),K=nt.index;if(yt(null),!p||p===u.quickPhrases[K])return;const ve=[...u.quickPhrases];ve[K]=p,ze({quickPhrases:ve})},ds=p=>{const K=new Set(lt);K.has(p.name)?K.delete(p.name):K.add(p.name),ze({disabledSkills:[...K]})},as=new Set(u.skillsFullText??[]),Ba=p=>{const K=new Set(as);K.has(p)?K.delete(p):K.add(p),ze({skillsFullText:[...K]})},On=new Set(u.disabledPlugins??[]),gs=new Set(e.plugins.map(p=>p.id)),Mn=p=>{const K=new Set(On);K.has(p.id)?K.delete(p.id):K.add(p.id),ze({disabledPlugins:[...K]})},Bn=p=>{const K=new Set(It);K.has(p.id)?K.delete(p.id):K.add(p.id),ze({disabledExtensions:[...K]})},Fa={subagent_spawn:a("toolDescSubagentSpawn"),subagent_get_result:a("toolDescSubagentGetResult"),subagent_steer:a("toolDescSubagentSteer"),subagent_list:a("toolDescSubagentList"),subagent_stop:a("toolDescSubagentStop"),subagent_wait_all:a("toolDescSubagentWaitAll"),subagent_templates:a("toolDescSubagentTemplates")},Zt=p=>{const K=new Set(at);K.has(p)?K.delete(p):K.add(p),ze({disabledAgentTools:[...K]})},T=u.markersEnabled??!0,ne=new Set(u.disabledMarkers??[]),Ce=p=>{const K=new Set(ne);!K.has(p)?K.add(p):K.delete(p),ze({disabledMarkers:[...K]})},tt=(p,K)=>{const ve={name:p,command:K,cwd:"${pwd}"};let st;const kt=e.terminals.find(ut=>ut.title===p);kt?(t.restart(kt.id),J({type:"run_command",terminalId:kt.id,conversationId:kt.conversationId,command:ve,cols:80,rows:24}),st=kt.id):(st=qt(),t.create({id:st,conversationId:e.activeConversationId||e.state?.conversationId||"",title:p,cwd:e.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:ve})),t.select(st),n(),r()},pt=p=>{Qe(null),tt(`${a("uninstallTitle")} ${p}`,`pi remove npm:${p}`)},Bt=(p,K,ve)=>{J({type:"plugin_job",jobId:qt(),action:p,id:K,...ve?{source:ve}:{},...p!=="uninstall"&&mt?{build:!0}:{}})},Ft=p=>{let K=null;for(const ve of Object.values(e.pluginJobs??{}))ve.pluginId===p&&(!K||ve.startedAt>=K.startedAt)&&(K=ve);return K},Wt=p=>{const K=Ft(p);if(!K)return null;if(K.phase!=="done"){const ve=K.lines[K.lines.length-1]??"";return s.jsxs("div",{className:"set-catalog-job running",title:ve,children:[s.jsx(Yt,{className:"set-job-spin"}),a("pluginJobRunning"),s.jsx("span",{className:"set-catalog-job-line",children:ve})]})}return K.ok?s.jsxs("div",{className:"set-catalog-job ok",children:["✓ ",a("pluginJobDone")]}):s.jsxs("div",{className:"set-catalog-job error",children:[s.jsxs("span",{children:["✗ ",K.error||a("pluginJobFailed")]}),K.output?s.jsx("pre",{className:"set-catalog-job-out",children:K.output}):null]})},en=[{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"}],Fn=e.settings?.uiLayout,li=p=>ze({uiLayout:{...Fn,...p}}),Ku=p=>{const K=new Set(Fn?.hidden??[]),ve=new Set(Fn?.shown??[]);p.hidden?(K.delete(p.id),ve.add(p.id)):(K.add(p.id),ve.delete(p.id)),li({hidden:[...K],shown:[...ve]})},ci=(p,K,ve)=>{const st=p.map(nd=>nd.id),kt=st.indexOf(K),ut=kt+ve;if(kt<0||ut<0||ut>=st.length)return;const vt=[...st],[pi]=vt.splice(kt,1);pi!==void 0&&(vt.splice(ut,0,pi),li({order:vt}))},Gu=p=>ze({uiLayout:w1(Fn,p)}),Yu=()=>ze({uiLayout:S1()}),ui=p=>{Oe(null),Bt("uninstall",p)},di=(p,K)=>{Bt("update",p,K)},zu=p=>{Bt("install",p.id,p.source)},Vu=p=>{J({type:"plugin_catalog_remove",id:p})},Qu=()=>{const p=rt.trim();p&&(J({type:"plugin_catalog_add",entry:{source:p,...D.trim()?{id:D.trim()}:{},...it.trim()?{name:it.trim()}:{},...U.trim()?{description:U.trim()}:{},...Le.trim()?{icon:Le.trim()}:{}}}),Ge(""),$e(""),Xe(""),Pe(""),ot(""),ct(!1))},Ha=p=>{const K=p.trim();if(!K)return;const ve=qt();us(ve),Ut(K),J({type:"plugin_catalog_sync",requestId:ve,source:K,...Je?{install:!0}:{},...At?{replace:!0}:{}})},Kt=e.catalogSync&&e.catalogSync.requestId===jt?e.catalogSync:null;o.useEffect(()=>{Kt?.ok&&Qt&&te(Cx(Qt))},[Kt?.requestId,Kt?.ok]);const Xu=p=>{const K=new Set(u.reviewSkills.filter(ve=>!ve.enabled).map(ve=>ve.name));K.has(p.name)?K.delete(p.name):K.add(p.name),ze({reviewDisabledSkills:[...K]})},Ju=()=>ze({promptTemplate:N}),Zu=p=>{ze({promptOverrides:{[p]:R[p]??""}})},Ua=p=>{j.current===p&&(j.current=null),C(null),M(K=>{const ve={...K};return delete ve[p],ve}),ze({promptOverrides:{[p]:""}})},tn=p=>xe(K=>({...K,[p]:!K[p]})),$a=(p,K)=>{M(ve=>({...ve,[p]:K})),C(p)},ed=()=>{B.current=!1,j.current=null,g(Kn),M({}),ze({promptTemplate:Kn,promptOverrides:{}})},td=p=>{g(K=>K.trim()?`${K}
|
|
357
|
+
|
|
358
|
+
{{${p}}}`:`{{${p}}}`)},sd=N.trim()&&N.trim()!==Kn||Object.values(R).some(p=>p.trim());return s.jsx("div",{className:"modal-backdrop",onClick:r,children:s.jsxs("div",{className:"modal settings-modal",onClick:p=>p.stopPropagation(),children:[s.jsx("button",{type:"button",className:"modal-close","aria-label":a("close"),onClick:r,children:s.jsx(bt,{})}),s.jsxs("div",{className:"modal-head",children:[s.jsx(la,{className:"modal-head-icon"}),s.jsx("h2",{children:a("settingsTitle")}),s.jsx(Et,{text:a("settingsDesc")})]}),s.jsxs("div",{className:"settings-layout",children:[s.jsx("nav",{className:"settings-rail","aria-label":a("settingsTitle"),children:Jt.map(p=>s.jsxs("button",{type:"button",className:`settings-tab${h===p.id?" active":""}`,"aria-current":h===p.id?"true":void 0,title:p.hint??p.label,onClick:()=>b(p.id),children:[s.jsx("span",{className:"settings-tab-icon",children:p.icon}),s.jsx("span",{className:"settings-tab-label",children:p.label}),p.count!==void 0&&s.jsx("span",{className:"set-count",children:p.count})]},p.id))}),s.jsxs("div",{className:"modal-body",ref:E,children:[h==="prompt"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(qs,{className:"set-section-icon"}),a("settingsSystemPrompt"),s.jsx(Et,{text:`${a("promptComposeHint")}
|
|
359
|
+
${a("promptComposeDesc")}`})]}),s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",children:a("promptTemplateLabel")}),s.jsx("textarea",{className:"set-prompt-input",rows:8,spellCheck:!1,placeholder:Kn,value:N,onFocus:()=>B.current=!0,onBlur:()=>{B.current=!1,Ju()},onChange:p=>g(p.target.value)}),s.jsxs("div",{className:"compose-toolbar",children:[s.jsx("span",{className:"set-field-label set-muted",children:a("promptInsertTokens")}),Y.map(p=>s.jsx("button",{type:"button",className:"token-chip",title:l(`promptTok_${p}_desc`),onClick:()=>td(p),children:`{{${p}}}`},p))]})]}),s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",children:a("promptSourcesLabel")}),Y.map(p=>{const K=R[p]??"",ve=u.promptSourceDefaults?.[p]??"",st=q===p,kt=ve.split(`
|
|
360
|
+
`).length>6||ve.length>480;if(Pu(p)){const ut=K.trim()?K:ve;return s.jsxs("div",{className:"override-row readonly",children:[s.jsxs("div",{className:"override-row-head",children:[`{{${p}}}`,s.jsxs("span",{className:"set-muted",children:[l(`promptTok_${p}`)," ",s.jsx(Et,{text:l(`promptTok_${p}_desc`)})]}),K.trim()?s.jsx("button",{type:"button",className:"set-btn-mini",title:a("promptReadonlyLockedHint"),onClick:()=>Ua(p),children:a("promptResetSource")}):s.jsx("span",{className:"set-muted",children:a("promptReadonlyBadge")})]}),s.jsx("div",{className:`source-default readonly${ut.trim()?"":" empty"}`,title:a("promptReadonlyTitle"),children:ut.trim()?s.jsxs(s.Fragment,{children:[s.jsx("pre",{className:`source-default-text${kt?Te[p]?" expanded":" clamped":""}`,children:ut}),kt&&s.jsx("span",{className:"source-default-toggle",role:"button",tabIndex:0,onClick:vt=>{vt.stopPropagation(),tn(p)},onKeyDown:vt=>{(vt.key==="Enter"||vt.key===" ")&&(vt.preventDefault(),vt.stopPropagation(),tn(p))},children:Te[p]?a("promptSourceCollapse"):a("promptSourceExpand")})]}):s.jsx("span",{className:"source-default-empty",children:a("promptSourceDefaultEmpty")})})]},p)}return s.jsxs("div",{className:"override-row",children:[s.jsxs("div",{className:"override-row-head",children:[`{{${p}}}`,s.jsxs("span",{className:"set-muted",children:[l(`promptTok_${p}`)," ",s.jsx(Et,{text:l(`promptTok_${p}_desc`)})]}),K.trim()?s.jsx("button",{type:"button",className:"set-btn-mini",onClick:()=>Ua(p),children:a("promptResetSource")}):s.jsx("span",{className:"set-muted",children:a("promptAutoBadge")})]}),K.trim()||st?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{className:"set-prompt-input override-input",rows:Math.min(10,Math.max(1,K.split(`
|
|
361
|
+
`).length)),autoFocus:st,placeholder:a("promptOverridePlaceholder"),value:K,onFocus:ut=>{j.current=p,C(p);const vt=ut.currentTarget;vt.value&&vt.value===ve&&vt.setSelectionRange(vt.value.length,vt.value.length)},onBlur:()=>{j.current===p&&(j.current=null);const ut=R[p]??"";if(ut.trim()&&ut===ve){Ua(p);return}Zu(p),ut.trim()||C(null)},onChange:ut=>M(vt=>({...vt,[p]:ut.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:a("promptSourceRefLabel")}),kt&&s.jsx("button",{type:"button",className:"source-default-toggle",onClick:()=>tn(p),children:Te[p]?a("promptSourceCollapse"):a("promptSourceExpand")})]}),ve.trim()?s.jsx("pre",{className:`source-default-text${kt?Te[p]?" expanded":" clamped":""}`,children:ve}):s.jsx("span",{className:"source-default-empty",children:a("promptSourceDefaultEmpty")}),!K.trim()&&ve.trim()&&s.jsx("button",{type:"button",className:"override-seed-btn",title:a("promptSourceSeedTip"),onClick:()=>$a(p,ve),children:a("promptSourceSeedButton")})]})]}):s.jsx("div",{className:"source-default",title:a("promptSourceDefaultEditHint"),role:"button",tabIndex:0,onClick:()=>$a(p,ve),onKeyDown:ut=>{(ut.key==="Enter"||ut.key===" ")&&(ut.preventDefault(),$a(p,ve))},children:ve.trim()?s.jsxs(s.Fragment,{children:[s.jsx("pre",{className:`source-default-text${kt?Te[p]?" expanded":" clamped":""}`,children:ve}),kt&&s.jsx("span",{className:"source-default-toggle",role:"button",tabIndex:0,onClick:ut=>{ut.stopPropagation(),tn(p)},onKeyDown:ut=>{(ut.key==="Enter"||ut.key===" ")&&(ut.preventDefault(),ut.stopPropagation(),tn(p))},children:Te[p]?a("promptSourceCollapse"):a("promptSourceExpand")})]}):s.jsx("span",{className:"source-default-empty",children:a("promptSourceDefaultEmpty")})})]},p)}),s.jsx("div",{className:"compose-toolbar",children:s.jsx("button",{type:"button",className:"set-btn",onClick:ed,disabled:!sd,children:a("promptResetAll")})})]}),s.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":_,onClick:()=>re(p=>!p),children:[a("settingsViewPrompt")," ",_?"▴":"▾"]}),_&&s.jsxs("div",{className:"set-prompt-view",children:[s.jsxs("div",{className:"set-prompt-view-head",children:[s.jsx("span",{children:a("settingsViewPrompt")}),s.jsx(Et,{text:a("settingsViewPromptHint")}),s.jsx(Na,{text:u.effectiveSystemPrompt})]}),u.effectiveSystemPrompt?s.jsx("pre",{className:"set-prompt-view-text",children:u.effectiveSystemPrompt}):s.jsx("p",{className:"set-empty",children:a("settingsViewPromptEmpty")})]}),s.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":le,onClick:()=>Ee(p=>!p),children:[a("settingsViewToolsSchema")," ",le?"▴":"▾"]}),le&&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:a("settingsViewToolsSchema")}),s.jsx(Et,{text:a("settingsViewToolsSchemaHint")}),s.jsx(Na,{text:u.toolsSchema})]}),u.toolsSchema?s.jsx("pre",{className:"set-prompt-view-text",children:u.toolsSchema}):s.jsx("p",{className:"set-empty",children:a("settingsViewToolsSchemaEmpty")})]})})]}),h==="prompt-history"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(pr,{className:"set-section-icon"}),a("settingsPromptHistory"),s.jsx(Et,{text:a("settingsPromptHistoryDesc")}),s.jsx("span",{className:"set-count",children:a("promptHistoryCount",{n:String(L)})})]}),L===0?s.jsx("p",{className:"set-empty",children:a("promptHistoryEmpty")}):s.jsx("p",{className:"set-hint",children:a("promptHistoryCount",{n:String(L)})}),s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",htmlFor:"ph-max",children:a("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(X.maxEntries),onChange:p=>{const K=Math.floor(Number(p.target.value)||0),ve={...X,maxEntries:K};we(ve)},onBlur:()=>{const p={...X};(!Number.isFinite(p.maxEntries)||p.maxEntries<1)&&(p.maxEntries=1),p.maxEntries>500&&(p.maxEntries=500),p.maxEntries=Math.floor(p.maxEntries),we(p),sr(p),de()}}),s.jsx(Et,{text:a("promptHistoryMaxHint")})]})]}),s.jsx(ft,{title:a("promptHistoryCharLimit"),tip:a("promptHistoryCharLimitHint"),enabled:X.charLimitEnabled,onToggle:()=>{const p={...X,charLimitEnabled:!X.charLimitEnabled};we(p),sr(p),de()}}),X.charLimitEnabled&&s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",htmlFor:"ph-char-limit",children:a("promptHistoryCharLimit")}),s.jsx("input",{id:"ph-char-limit",className:"set-input",type:"number",min:100,max:2e4,step:100,placeholder:a("promptHistoryCharLimitPlaceholder"),value:String(X.charLimit),onChange:p=>{const K=Math.floor(Number(p.target.value)||0);we({...X,charLimit:K})},onBlur:()=>{let p=Math.floor(Number(X.charLimit)||0);(!Number.isFinite(p)||p<100)&&(p=100),p>2e4&&(p=2e4);const K={...X,charLimit:p};we(K),sr(K),de()}})]}),s.jsxs("div",{className:"set-field",style:{marginTop:12},children:[s.jsxs("button",{type:"button",className:`set-uninstall${oe?" confirm":""}`,disabled:L===0,title:a(L===0?"promptHistoryEmpty":"promptHistoryClear"),onClick:()=>{if(!oe){fe(!0);return}o1(),fe(!1),de()},children:[s.jsx(Rt,{})," ",a(oe?"promptHistoryClearConfirm":"promptHistoryClear")]}),L>0&&s.jsx("span",{className:"set-hint",style:{marginLeft:8},children:a("promptHistoryCount",{n:String(L)})})]}),s.jsxs("p",{className:"set-hint",children:[s.jsx(Sl,{style:{verticalAlign:"-2px",marginRight:4}}),a("settingsPromptHistoryDesc")]})]}),h==="tools"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Ei,{className:"set-section-icon"}),a("settingsTools")]}),s.jsx("div",{className:"set-field-label",children:a("toolsSectionTerminal")}),Ml.map(p=>s.jsx(ft,{title:p,tip:a("settingsTerminalToolsDesc"),enabled:!at.has(p),onToggle:()=>Zt(p)},p)),s.jsx(ft,{title:a("terminalBashTakeover"),tip:a("terminalBashTakeoverDesc"),enabled:u.terminalBash,onToggle:()=>ze({terminalBash:!u.terminalBash})}),u.terminalBash&&s.jsxs("div",{className:"set-field",children:[s.jsx("label",{className:"set-field-label",htmlFor:"tb-idle-ms",children:a("terminalBashIdleMs")}),s.jsx("input",{id:"tb-idle-ms",className:"set-input",type:"number",min:0,step:1e3,value:Xt,onChange:p=>k(p.target.value),onBlur:()=>{const p=Math.max(0,Math.floor(Number(Xt)||0));k(String(p)),p!==u.terminalBashIdleMs&&ze({terminalBashIdleMs:p})}})]}),s.jsx("div",{className:"set-field-label",children:a("toolsSectionSubagent")}),s.jsx("div",{className:"set-row-desc",children:a("toolsSubagentDepHint")}),Bl.map(p=>s.jsx(ft,{title:p,tip:Fa[p],enabled:!at.has(p),onToggle:()=>Zt(p)},p)),s.jsxs("div",{className:"set-field-label",children:[a("settingsMarkers"),s.jsx(Et,{text:`${a("settingsMarkersDesc")}
|
|
362
|
+
${a("markerRenameTip")}`})]}),s.jsx(ft,{title:a("markersEnabled"),tip:`${a("markersEnabledDesc")}
|
|
363
|
+
${a("markersOffHint")}`,enabled:T,onToggle:()=>ze({markersEnabled:!T})}),T&&(u.markers?.length??0)===0&&s.jsxs("p",{className:"set-empty",children:[a("loading"),"..."]}),T&&u.markers&&u.markers.length>0&&u.markers.map(p=>s.jsx(ft,{title:p.name==="todo"?a("markerGroupTodo"):p.name==="notify"?a("markerGroupNotify"):p.name==="conv"?a("markerGroupRename"):p.name,tip:p.guidance.join(`
|
|
364
|
+
`),enabled:p.enabled,onToggle:()=>Ce(p.name)},p.name)),s.jsx(ft,{title:Xn,tip:`${a("todoListEnabledDesc")}
|
|
365
|
+
${a("todoListOffHint")}`,enabled:!at.has(Xn),onToggle:()=>Zt(Xn)}),s.jsx("div",{className:"set-field-label",children:a("toolsSectionOther")}),s.jsx(ft,{title:zn,tip:`${a("editSoftEnabledDesc")}
|
|
366
|
+
${a("editSoftOffHint")}`,enabled:!at.has(zn),onToggle:()=>Zt(zn)}),s.jsx(ft,{title:Vn,tip:`${a("delegateTaskEnabledDesc")}
|
|
367
|
+
${a("delegateTaskOffHint")}`,enabled:!at.has(Vn),onToggle:()=>Zt(Vn)}),s.jsx(ft,{title:Qn,tip:`${a("questionnaireEnabledDesc")}
|
|
368
|
+
${a("questionnaireOffHint")}`,enabled:!at.has(Qn),onToggle:()=>Zt(Qn)}),s.jsx(ft,{title:mn,tip:`${a("browserPageEnabledDesc")}
|
|
369
|
+
${a("browserPageOffHint")}`,enabled:!at.has(mn),onToggle:()=>Zt(mn)})]}),h==="question"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(ki,{className:"set-section-icon"}),a("settingsQuestionnaire")]}),s.jsx(ft,{title:a("questionnaireEnabled"),tip:`${a("questionnaireEnabledDesc")}
|
|
370
|
+
${a("questionnaireOffHint")}`,enabled:u.questionnaireEnabled,onToggle:()=>ze({questionnaireEnabled:!u.questionnaireEnabled})})]}),h==="display"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Is,{className:"set-section-icon"}),a("settingsMessageDisplay")]}),s.jsxs("div",{className:"set-field",children:[s.jsxs("label",{className:"set-field-label",htmlFor:"model-retry-max",children:[a("modelRetryAttempts")," ",s.jsx(Et,{text:a("modelRetryHint")})]}),s.jsx("input",{id:"model-retry-max",className:"set-input",type:"number",min:0,max:100,step:1,value:ae,onChange:p=>Se(p.target.value),onBlur:()=>{const p=Math.min(100,Math.max(0,Math.floor(Number(ae)||0)));Se(String(p)),p!==u.retryMaxAttempts&&ze({retryMaxAttempts:p})},onKeyDown:p=>{p.key==="Enter"&&p.target.blur()}})]}),s.jsx("hr",{className:"set-sep"}),s.jsx(ft,{title:a("thinkingWrap"),tip:a("thinkingWrapDesc"),enabled:u.thinkingWrap??!0,onToggle:()=>ze({thinkingWrap:!(u.thinkingWrap??!0)})}),s.jsx(ft,{title:a("toolsWrap"),tip:a("toolsWrapDesc"),enabled:u.toolsWrap??!0,onToggle:()=>ze({toolsWrap:!(u.toolsWrap??!0)})}),s.jsx(ft,{title:a("devNoCache"),tip:a("devNoCacheDesc"),enabled:u.devNoCache??!0,onToggle:()=>ze({devNoCache:!(u.devNoCache??!0)})}),s.jsx(ft,{title:a("autoReload"),tip:a("autoReloadDesc"),enabled:u.autoReload??!0,onToggle:()=>ze({autoReload:!(u.autoReload??!0)})}),s.jsx("hr",{className:"set-sep"}),s.jsx(ft,{title:a("wideChat"),tip:a("wideChatDesc"),enabled:Ne,onToggle:()=>lx({wide:!Ne})}),s.jsx(ft,{title:a("projectTitle"),tip:a("projectTitleDesc"),enabled:Ue,onToggle:()=>mx({projectName:!Ue})}),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:[a("wallpaperTitle"),s.jsx(Et,{text:a("wallpaperDesc")})]}),s.jsxs("div",{className:"wallpaper-url-row",children:[s.jsx("input",{className:"set-input wallpaper-url",placeholder:a("wallpaperUrlPh"),value:Ke,maxLength:2e3,spellCheck:!1,onFocus:()=>{ce.current=!0},onChange:p=>Ie(p.target.value),onBlur:()=>{if(ce.current=!1,!Ke.trim()&&ke.url.startsWith("data:")){Ie("");return}const p=Kr(Ke);Ie(p),p!==ke.url&&rn({...ke,url:p})},onKeyDown:p=>{p.key==="Enter"?p.target.blur():p.key==="Escape"&&(Ie(ke.url.startsWith("data:")?"":ke.url),p.target.blur())}}),s.jsxs("button",{type:"button",className:"set-save-btn",disabled:Fe,onClick:()=>pe.current?.click(),children:[s.jsx(Ad,{})," ",a("wallpaperUpload")]}),s.jsx("input",{ref:pe,type:"file",accept:"image/*",hidden:!0,onChange:Ve})]}),et&&s.jsx("p",{className:"set-hint",children:a("wallpaperUploadFailed")}),s.jsxs("div",{className:"wallpaper-sliders",children:[s.jsxs("label",{className:"wallpaper-slider",children:[s.jsx("span",{children:a("wallpaperDim")}),s.jsx("input",{type:"range",min:0,max:95,step:1,value:ke.dim,onChange:p=>rn({...ke,dim:Number(p.target.value)})}),s.jsxs("output",{children:[ke.dim,"%"]})]}),s.jsxs("label",{className:"wallpaper-slider",children:[s.jsx("span",{children:a("wallpaperBlur")}),s.jsx("input",{type:"range",min:0,max:24,step:1,value:ke.blur,onChange:p=>rn({...ke,blur:Number(p.target.value)})}),s.jsxs("output",{children:[ke.blur,"px"]})]})]})]}),ke.url&&s.jsxs("div",{className:"wallpaper-current",children:[s.jsx("img",{className:"wallpaper-preview",src:ke.url,alt:""}),s.jsx("button",{type:"button",className:"wallpaper-clear",onClick:()=>{Ie(""),rn({...ke,url:""})},children:a("wallpaperClear")})]})]})]}),h==="quick"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(lr,{className:"set-section-icon"}),a("quickPhrases"),s.jsx(Et,{text:a("quickPhrasesDesc")}),s.jsx("span",{className:"set-count",children:u.quickPhrases.length})]}),s.jsx(ft,{title:a("quickPhrasesEnabled"),tip:a("quickPhrasesDesc"),enabled:u.quickPhrasesEnabled,onToggle:()=>ze({quickPhrasesEnabled:!u.quickPhrasesEnabled})}),!u.quickPhrasesEnabled&&s.jsx("p",{className:"set-hint",children:a("quickPhrasesOffHint")}),s.jsxs("div",{className:"set-preset-save",children:[s.jsx("input",{className:"set-input",placeholder:a("quickPhrasesPlaceholder"),value:Be,maxLength:200,onChange:p=>ht(p.target.value),onKeyDown:p=>{p.key==="Enter"&&Be.trim()&&(ze({quickPhrases:[...u.quickPhrases,Be.trim()]}),ht(""))}}),s.jsxs("button",{type:"button",className:"set-save-btn",disabled:!Be.trim(),onClick:()=>{ze({quickPhrases:[...u.quickPhrases,Be.trim()]}),ht("")},children:[s.jsx(Dt,{})," ",a("quickPhrasesAdd")]})]}),u.quickPhrases.length===0?s.jsx("p",{className:"set-empty",children:a("quickPhrasesEmpty")}):s.jsx("div",{className:"set-list",children:u.quickPhrases.map((p,K)=>s.jsx("div",{className:"set-row",children:nt?.index===K?s.jsx("div",{className:"set-row-info",children:s.jsx("input",{className:"set-input",autoFocus:!0,value:nt.value,maxLength:200,placeholder:a("quickPhrasesEditPh"),onChange:ve=>yt({index:K,value:ve.target.value}),onKeyDown:ve=>{ve.key==="Enter"?Ns():ve.key==="Escape"&&yt(null)},onBlur:Ns})}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"set-row-info",children:s.jsx("div",{className:"set-row-name",title:p,children:p})}),s.jsxs("div",{className:"set-row-actions",children:[s.jsx("button",{type:"button",className:"set-icon-btn",title:a("quickPhrasesEdit"),onClick:()=>yt({index:K,value:p}),children:s.jsx(_n,{})}),s.jsx("button",{type:"button",className:"set-icon-btn",title:a("quickPhrasesMoveUp"),disabled:K===0,onClick:()=>{const ve=[...u.quickPhrases];[ve[K-1],ve[K]]=[ve[K],ve[K-1]],ze({quickPhrases:ve})},children:"↑"}),s.jsx("button",{type:"button",className:"set-icon-btn",title:a("quickPhrasesMoveDown"),disabled:K===u.quickPhrases.length-1,onClick:()=>{const ve=[...u.quickPhrases];[ve[K],ve[K+1]]=[ve[K+1],ve[K]],ze({quickPhrases:ve})},children:"↓"}),s.jsx("button",{type:"button",className:"set-icon-btn danger",title:a("quickPhrasesDelete"),onClick:()=>ze({quickPhrases:u.quickPhrases.filter((ve,st)=>st!==K)}),children:s.jsx(Rt,{})})]})]})},`${K}:${p}`))}),s.jsx("div",{className:"compose-toolbar",children:s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{yt(null),ze({quickPhrases:ja[c]??ja.en})},children:a("quickPhrasesReset")})})]}),h==="skills"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Ts,{className:"set-section-icon"}),a("settingsSkills"),s.jsx(Et,{text:`${a("skillFullTextLabel")}:${a("skillFullTextDesc")}`}),s.jsx("span",{className:"set-count",children:u.skills.length})]}),u.skills.length===0?s.jsx("p",{className:"set-empty",children:a(f?"dshSkillsNote":"noSkills")}):s.jsx("div",{className:"set-list",children:u.skills.map(p=>s.jsx(ft,{title:p.name,subtitle:p.description,enabled:p.enabled,onToggle:()=>ds(p),action:s.jsx("button",{type:"button",className:`tpl-chip${as.has(p.name)?" on":""}`,title:a("skillFullTextDesc"),onClick:()=>Ba(p.name),children:a("skillFullTextShort")})},p.name))})]}),h==="extensions"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Gn,{className:"set-section-icon"}),a("settingsExtensions"),s.jsx("span",{className:"set-count",children:u.extensions.length})]}),u.extensions.length===0?s.jsx("p",{className:"set-empty",children:a(f?"dshExtensionsNote":"noExtensions")}):s.jsx("div",{className:"set-list",children:u.extensions.map(p=>{const K=p.id.startsWith("npm:")?p.id.slice(4):null;return s.jsx(ft,{title:p.name,subtitle:p.path,enabled:p.enabled,onToggle:()=>Bn(p),action:K?ge===p.id?s.jsx("button",{type:"button",className:"set-uninstall confirm",title:a("uninstallConfirmHint"),onClick:()=>pt(K),children:a("uninstallConfirm")}):s.jsxs("button",{type:"button",className:"set-uninstall",title:a("uninstallHint"),onClick:()=>Qe(p.id),children:[s.jsx(Rt,{}),a("uninstallExt")]}):void 0},p.id)})})]}),h==="plugins"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Ti,{className:"set-section-icon"}),a("uiLayoutTitle"),s.jsx("button",{type:"button",className:"set-uninstall",onClick:Yu,children:a("uiLayoutRestoreAll")})]}),s.jsx("div",{className:"set-note",children:a("uiLayoutHint")}),en.map(({slot:p,labelKey:K})=>{const ve=Me[p]??[];return s.jsxs("div",{className:"set-ui-slot",children:[s.jsx("div",{className:"set-ui-slot-title",children:a(K)}),ve.length===0?s.jsx("div",{className:"set-empty",children:a("uiLayoutEmpty")}):ve.map((st,kt)=>s.jsxs("div",{className:"set-row",children:[s.jsxs("label",{className:"set-toggle",title:st.id,children:[s.jsx("input",{type:"checkbox",checked:!st.hidden,onChange:()=>Ku(st)}),s.jsxs("span",{children:[st.icon?`${st.icon} `:"",st.label]})]}),s.jsxs("div",{className:"set-row-actions",children:[st.arrangedBy.length>0&&s.jsx("span",{className:"set-ui-source",title:st.arrangedBy.join(", "),children:a("uiLayoutArranged")}),st.userOverrides.length>0&&s.jsx("button",{type:"button",className:"set-uninstall",onClick:()=>Gu(st.id),children:a("uiLayoutRestore")}),s.jsx("button",{type:"button",className:"set-uninstall",disabled:kt===0,onClick:()=>ci(ve,st.id,-1),children:"↑"}),s.jsx("button",{type:"button",className:"set-uninstall",disabled:kt===ve.length-1,onClick:()=>ci(ve,st.id,1),children:"↓"})]})]},st.id))]},p)})]}),h==="plugins"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(is,{className:"set-section-icon"}),a("pluginGrantsTitle"),s.jsx("span",{className:"set-count",children:e.pluginGrants.reduce((p,K)=>p+K.paths.length,0)})]}),s.jsx("div",{className:"set-note",children:a("pluginGrantsHint")}),e.pluginGrants.length===0?s.jsx("p",{className:"set-empty",children:a("pluginGrantsEmpty")}):s.jsx("div",{className:"set-list",children:e.pluginGrants.map(p=>s.jsxs("div",{className:"set-grant-row",children:[s.jsx("div",{className:"set-catalog-title",children:s.jsx("span",{children:p.pluginId})}),p.paths.map(K=>s.jsxs("div",{className:"set-grant-path",children:[s.jsx("span",{className:"set-catalog-source",children:K}),s.jsx("button",{type:"button",className:"set-uninstall",onClick:()=>J({type:"plugin_path_revoke",pluginId:p.pluginId,path:K}),children:a("pluginGrantsRevoke")})]},K))]},p.pluginId))})]}),h==="plugins"&&m&&s.jsx("div",{className:"set-section",children:s.jsx("div",{className:"set-note",children:a("updatesManaged")})}),h==="plugins"&&!m&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Gn,{className:"set-section-icon"}),a("pluginMarket"),s.jsx("span",{className:"set-count",children:e.pluginCatalog.length}),s.jsxs("label",{className:"set-catalog-build",title:a("pluginBuildHint"),children:[s.jsx("input",{type:"checkbox",checked:mt,onChange:p=>Mt(p.target.checked)}),a("pluginBuildSource")]}),s.jsxs("button",{type:"button",className:"set-uninstall",title:a("pluginCatalogSyncHint"),onClick:()=>Z(p=>!p),children:[s.jsx(Yt,{}),a("pluginCatalogSync")]}),s.jsxs("button",{type:"button",className:"set-uninstall",title:a("pluginCatalogAddHint"),onClick:()=>ct(p=>!p),children:[s.jsx(Dt,{}),a("pluginCatalogAdd")]})]}),$&&s.jsxs("div",{className:"set-catalog-add",children:[s.jsx("div",{className:"set-note",children:a("pluginCatalogSyncHint")}),s.jsx("input",{className:"set-input",placeholder:a("pluginCatalogSyncSource"),value:Re,onChange:p=>je(p.target.value),onKeyDown:p=>{p.key==="Enter"&&Ha(Re)}}),s.jsxs("label",{className:"set-catalog-build",title:a("pluginCatalogSyncInstall"),children:[s.jsx("input",{type:"checkbox",checked:Je,onChange:p=>qe(p.target.checked)}),a("pluginCatalogSyncInstall")]}),s.jsxs("label",{className:"set-catalog-build",title:a("pluginCatalogSyncReplace"),children:[s.jsx("input",{type:"checkbox",checked:At,onChange:p=>Lt(p.target.checked)}),a("pluginCatalogSyncReplace")]}),v.length>0&&s.jsxs("div",{className:"set-catalog-recent",children:[s.jsx("span",{className:"set-catalog-recent-label",children:a("pluginCatalogSyncRecent")}),v.map(p=>s.jsx("button",{type:"button",className:"set-catalog-recent-item",title:p,onClick:()=>{je(p),Ha(p)},children:p},p))]}),s.jsxs("div",{className:"set-catalog-add-actions",children:[s.jsx("button",{type:"button",className:"set-uninstall confirm",disabled:!Re.trim(),onClick:()=>Ha(Re),children:a("pluginCatalogSyncSubmit")}),s.jsx("button",{type:"button",className:"set-uninstall",onClick:()=>Z(!1),children:a("cancel")})]}),Kt&&(Kt.ok?s.jsxs("div",{className:"set-catalog-job ok",children:[s.jsxs("span",{children:["✓ ",a("pluginCatalogSyncOk",{n:Kt.entryCount??0}),Kt.installed?` · ${a("pluginCatalogSyncInstalled",{ok:Kt.installed.filter(p=>p.ok).length,fail:Kt.installed.filter(p=>!p.ok).length})}`:null]}),Kt.installed?.some(p=>!p.ok)&&s.jsx("pre",{className:"set-catalog-job-out",children:Kt.installed.filter(p=>!p.ok).map(p=>`${p.id}:${p.error??"?"}`).join(`
|
|
371
|
+
`)})]}):s.jsx("div",{className:"set-catalog-job error",children:s.jsxs("span",{children:["✗ ",Kt.error||a("pluginJobFailed")]})}))]}),Ye&&s.jsxs("div",{className:"set-catalog-add",children:[s.jsx("input",{className:"set-input",placeholder:a("pluginCatalogSource"),value:rt,onChange:p=>Ge(p.target.value)}),s.jsx("input",{className:"set-input",placeholder:a("pluginCatalogId"),value:D,onChange:p=>$e(p.target.value)}),s.jsx("input",{className:"set-input",placeholder:a("pluginCatalogName"),value:it,onChange:p=>Xe(p.target.value)}),s.jsx("input",{className:"set-input",placeholder:a("pluginCatalogIcon"),value:Le,onChange:p=>ot(p.target.value)}),s.jsx("textarea",{className:"set-input",rows:2,placeholder:a("pluginCatalogDesc"),value:U,onChange:p=>Pe(p.target.value)}),s.jsxs("div",{className:"set-catalog-add-actions",children:[s.jsx("button",{type:"button",className:"set-uninstall confirm",disabled:!rt.trim(),onClick:Qu,children:a("pluginCatalogAddSubmit")}),s.jsx("button",{type:"button",className:"set-uninstall",onClick:()=>ct(!1),children:a("cancel")})]})]}),e.pluginCatalog.length===0?s.jsx("p",{className:"set-empty",children:a("noPluginCatalog")}):s.jsx("div",{className:"set-list",children:e.pluginCatalog.map(p=>{const K=gs.has(p.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:[p.icon?`${p.icon} `:"",p.name]}),K&&s.jsx("span",{className:"set-catalog-installed",children:a("pluginInstalled")}),!p.builtin&&s.jsx("span",{className:"set-catalog-custom",children:a("pluginCatalogCustom")})]}),p.description&&s.jsx("div",{className:"set-catalog-desc",children:p.description}),s.jsx("div",{className:"set-catalog-source",children:p.source}),Wt(p.id)]}),s.jsxs("div",{className:"set-row-actions",children:[K?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"set-uninstall",title:a("pluginUpdateHint"),onClick:()=>di(p.id,p.source),children:[s.jsx(Yt,{}),a("pluginUpdate")]}),ye===p.id?s.jsx("button",{type:"button",className:"set-uninstall confirm",title:a("pluginUninstallHint"),onClick:()=>ui(p.id),children:a("uninstallConfirm")}):s.jsxs("button",{type:"button",className:"set-uninstall",title:a("pluginUninstallHint"),onClick:()=>Oe(p.id),children:[s.jsx(Rt,{}),a("uninstallExt")]})]}):s.jsxs("button",{type:"button",className:"set-uninstall",title:a("pluginInstallHint"),onClick:()=>zu(p),children:[s.jsx(Rs,{}),a("pluginInstall")]}),!p.builtin&&s.jsx("button",{type:"button",className:"set-uninstall",title:a("pluginCatalogRemoveHint"),onClick:()=>Vu(p.id),children:s.jsx(bt,{})})]})]},p.id)})})]}),h==="plugins"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Un,{className:"set-section-icon"}),a("settingsUiPlugins"),s.jsx("span",{className:"set-count",children:e.plugins.length})]}),e.plugins.length===0?s.jsx("p",{className:"set-empty",children:a("noUiPlugins")}):s.jsx("div",{className:"set-list",children:e.plugins.map(p=>s.jsxs(s.Fragment,{children:[s.jsx(ft,{title:`${p.icon?`${p.icon} `:""}${p.name}`,subtitle:(p.error?`${p.id} · ${p.error}`:p.source?`${p.id} · ${p.source}`:`${p.id} · ${a("uiPluginNoSource")}`)+(p.permissions?.length?` · ${a("uiPluginPerms")}: ${p.permissions.join(", ")}`:""),enabled:!On.has(p.id)&&!p.error,onToggle:()=>!p.error&&Mn(p),action:s.jsxs("div",{className:"set-row-actions",children:[p.source&&s.jsxs("button",{type:"button",className:"set-uninstall",title:a("pluginUpdateHint"),onClick:()=>di(p.id,p.source),children:[s.jsx(Yt,{}),a("pluginUpdate")]}),ye===p.id?s.jsx("button",{type:"button",className:"set-uninstall confirm",title:a("pluginUninstallHint"),onClick:()=>ui(p.id),children:a("uninstallConfirm")}):s.jsxs("button",{type:"button",className:"set-uninstall",title:a("pluginUninstallHint"),onClick:()=>Oe(p.id),children:[s.jsx(Rt,{}),a("uninstallExt")]})]})},p.id),p.wantsDom&&s.jsxs("div",{className:"set-row",title:a("pluginDomDesc"),children:[s.jsx("span",{className:"set-ui-source",children:p.domGranted?a("pluginDomGranted"):a("pluginDomNeed")}),s.jsx("div",{className:"set-row-actions",children:s.jsx("button",{type:"button",className:`set-uninstall${p.domGranted?"":" confirm"}`,title:a("pluginDomDesc"),onClick:()=>J({type:"plugin_dom_consent",pluginId:p.id,granted:!p.domGranted}),children:p.domGranted?a("pluginDomRevoke"):a("pluginDomGrant")})})]}),p.settingsSchema&&p.settingsSchema.length>0&&s.jsx(ix,{plugin:p})]}))})]}),h==="plugins"&&f&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Un,{className:"set-section-icon"}),a("dshPatches"),s.jsx(Et,{text:a("dshPatchesDesc")}),s.jsx("span",{className:"set-count",children:e.dshPatches?.files.length??0}),s.jsxs("button",{type:"button",className:"set-uninstall",title:a("dshPatchesRescanHint"),onClick:()=>J({type:"dsh_patches_rescan"}),children:[s.jsx(Yt,{}),a("dshPatchesRescan")]})]}),(e.dshPatches?.files.length??0)===0?s.jsx("p",{className:"set-empty",children:a("dshPatchesEmpty")}):s.jsx("div",{className:"set-list",children:e.dshPatches.files.map(p=>s.jsx("div",{className:"set-row",children:s.jsxs("div",{className:"set-row-info",children:[s.jsx("div",{className:"set-row-name",children:p.name}),s.jsxs("div",{className:"set-row-desc",children:[wx(p.size)," · ",new Date(p.mtimeMs).toLocaleString()]})]})},p.name))}),s.jsxs("p",{className:"set-hint",children:[a("dshPatchesPath")," ",e.dshPatches?.patchDir??""]})]}),h==="review"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(qs,{className:"set-section-icon"}),a("settingsReview"),s.jsx(Et,{text:a("settingsReviewDesc")}),s.jsx("span",{className:"set-count",children:u.reviewSkills.length})]}),s.jsx(ft,{title:a("goalModeEnabled"),tip:`${a("goalModeEnabledDesc")}
|
|
372
|
+
${a("goalModeOffHint")}`,enabled:u.goalModeEnabled,onToggle:()=>ze({goalModeEnabled:!u.goalModeEnabled})}),s.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:a("reviewPromptPlaceholder"),value:w,onFocus:()=>z.current=!0,onBlur:()=>{z.current=!1,ze({reviewPrompt:w})},onChange:p=>se(p.target.value)}),s.jsxs("div",{className:"set-field-label",children:[a("settingsReviewSkills"),f&&s.jsxs(s.Fragment,{children:[" ",s.jsx(Et,{text:a("dshReviewPromptNote")})]})]}),u.reviewSkills.length===0?s.jsx("p",{className:"set-empty",children:a("noSkills")}):s.jsx("div",{className:"set-list",children:u.reviewSkills.map(p=>s.jsx(ft,{title:p.name,subtitle:p.description,enabled:p.enabled,onToggle:()=>Xu(p)},`review-${p.name}`))})]}),h==="vision"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(da,{className:"set-section-icon"}),a("settingsVisionBridge")]}),s.jsx(ft,{title:a("visionBridgeEnabled"),tip:`${a("settingsVisionBridgeDesc")}
|
|
373
|
+
${a("visionBridgeOffHint")}`,enabled:u.visionBridgeEnabled,onToggle:()=>ze({visionBridgeEnabled:!u.visionBridgeEnabled})}),u.visionBridgeEnabled&&s.jsxs("div",{className:"set-mode-row",children:[s.jsx("label",{className:"set-field-label",children:a("visionBridgeModel")}),s.jsxs("select",{className:"set-select",value:u.visionBridgeModel??"",onChange:p=>ze({visionBridgeModel:p.target.value||null}),children:[s.jsx("option",{value:"",children:a("visionBridgeAuto")}),u.visionModels.map(p=>s.jsx("option",{value:`${p.provider}/${p.id}`,children:p.label},`${p.provider}/${p.id}`))]})]}),u.visionBridgeEnabled&&s.jsxs("div",{className:"set-mode-row",children:[s.jsx("label",{className:"set-field-label",children:a("visionBridgePromptMode")}),s.jsxs("select",{className:"set-select",value:Q,onChange:p=>{const K=p.target.value;O(K),ze({visionBridgePromptMode:K})},children:[s.jsx("option",{value:"append",children:a("promptModeAppend")}),s.jsx("option",{value:"replace",children:a("promptModeReplace")})]})]}),u.visionBridgeEnabled&&s.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:a("visionBridgePromptPlaceholder"),value:G,onFocus:()=>F.current=!0,onBlur:()=>{F.current=!1;const p=Q==="replace"&&u.visionBridgeDefaultPrompt&&G===u.visionBridgeDefaultPrompt?"":G;ze({visionBridgePromptMode:Q,visionBridgePrompt:p})},onChange:p=>ee(p.target.value)}),u.visionBridgeEnabled&&(u.visionModels.length===0?s.jsx("p",{className:"set-hint",children:a("visionBridgeNoModels")}):s.jsx("p",{className:"set-hint",children:a("visionBridgeCurrent",{model:u.visionBridgeModel??a("visionBridgeAuto")})}))]}),h==="presets"&&f&&e.dshPresets&&e.dshPresets.presets.length>0&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(Ts,{className:"set-section-icon"}),a("dshPreset"),s.jsx(Et,{text:a("dshDefaultPresetDesc")}),s.jsx("span",{className:"set-count",children:e.dshPresets.presets.length})]}),s.jsxs("div",{className:"set-mode-row",children:[s.jsx("label",{className:"set-field-label",children:a("dshDefaultPreset")}),s.jsx("select",{className:"set-select",value:e.dshPresets.defaultPreset,onChange:p=>J({type:"dsh_preset_default",preset:p.target.value}),children:$r(e.dshPresets.presets).map(p=>s.jsxs("option",{value:p.id,disabled:!!p.broken,children:[p.name??p.id,p.trust==="user"?` · ${a("dshPresetUser")}`:""]},p.id))})]}),s.jsx("div",{className:"set-list",children:$r(e.dshPresets.presets).map(p=>s.jsx("div",{className:"set-row",children:s.jsxs("div",{className:"set-row-info",children:[s.jsxs("div",{className:"set-row-name",children:[p.name??p.id,p.trust==="user"&&s.jsx("span",{className:"dd-preset-tag",children:a("dshPresetUser")}),p.id===e.dshPresets.defaultPreset&&s.jsx("span",{className:"dd-preset-tag",children:a("dshPresetDefaultTag")}),p.broken&&s.jsx("span",{className:"dd-preset-tag warn",children:a("dshPresetBroken")})]}),p.description&&!p.broken&&s.jsx("div",{className:"set-row-desc",children:p.description}),p.broken&&s.jsx("div",{className:"set-row-desc",children:p.broken})]})},p.id))}),s.jsx("p",{className:"set-hint",children:a("dshPresetUserNote")})]}),h==="presets"&&f&&e.dshPermission&&e.dshPermission.options.length>0&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(or,{className:"set-section-icon"}),a("dshPerm"),s.jsx(Et,{text:a("dshPermDefaultDesc")})]}),s.jsxs("div",{className:"set-mode-row",children:[s.jsx("label",{className:"set-field-label",children:a("dshPermDefault")}),s.jsx("select",{className:"set-select",value:e.dshPermission.defaultPreset,onChange:p=>J({type:"dsh_permission_default",preset:p.target.value}),children:Xo.filter(p=>e.dshPermission.options.some(K=>K.value===p)).map(p=>s.jsx("option",{value:p,children:a($s(p))},p))})]}),s.jsx("div",{className:"set-list",children:Xo.filter(p=>e.dshPermission.options.some(K=>K.value===p)).map(p=>s.jsx("div",{className:"set-row",children:s.jsxs("div",{className:"set-row-info",children:[s.jsxs("div",{className:"set-row-name",children:[a($s(p)),p===e.dshPermission.defaultPreset&&s.jsx("span",{className:"dd-preset-tag",children:a("dshPresetDefaultTag")})]}),s.jsx("div",{className:"set-row-desc",children:a(Cs(p))})]})},p))})]}),h==="presets"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(la,{className:"set-section-icon"}),a("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:a("presetNamePlaceholder"),value:A,onChange:p=>ue(p.target.value),onKeyDown:p=>{p.key==="Enter"&&A.trim()&&(J({type:"save_preset",name:A.trim()}),ue(""))}}),s.jsxs("button",{type:"button",className:"set-save-btn",disabled:!A.trim(),onClick:()=>{J({type:"save_preset",name:A.trim()}),ue("")},children:[s.jsx(Dt,{})," ",a("saveAsPreset")]})]}),u.presets.length===0?s.jsx("p",{className:"set-empty",children:a("noPresets")}):s.jsx("div",{className:"set-list",children:u.presets.map(p=>s.jsxs("div",{className:"set-row",children:[s.jsxs("div",{className:"set-row-info",children:[s.jsx("div",{className:"set-row-name",children:p.name}),s.jsxs("div",{className:"set-row-desc",children:[p.promptMode==="replace"?a("promptModeReplace"):a("promptModeAppend"),p.disabledSkills.length>0&&` · ${a("settingsSkills")} ${p.disabledSkills.length}`,p.disabledExtensions.length>0&&` · ${a("settingsExtensions")} ${p.disabledExtensions.length}`]})]}),s.jsxs("div",{className:"set-row-actions",children:[s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>J({type:"apply_preset",name:p.name}),children:a("applyPreset")}),s.jsx("button",{type:"button",className:"set-icon-btn danger",title:a("deletePreset"),onClick:()=>J({type:"delete_preset",name:p.name}),children:s.jsx(Rt,{})})]})]},p.name))})]}),h==="subagent-templates"&&s.jsxs("div",{className:"set-section",children:[s.jsxs("div",{className:"set-section-title",children:[s.jsx(xi,{className:"set-section-icon"}),a("settingsSubagentTemplates"),s.jsx(Et,{text:a("settingsSubagentTemplatesDesc")}),s.jsx("span",{className:"set-count",children:u.subagentTemplates.length}),s.jsxs("button",{type:"button",className:"set-save-btn",title:a("subagentTemplateNew"),onClick:()=>ie({name:"",description:"",promptMode:"replace",systemPrompt:"",enabledSkills:[],enabledExtensions:[],model:"",thinkingLevel:"",enabled:!0}),children:[s.jsx(Dt,{})," ",a("subagentTemplateNew")]})]}),s.jsxs("div",{className:"set-mode-row",children:[s.jsxs("label",{className:"set-field-label",children:[a("subagentDefaultModelLabel")," ",s.jsx(Et,{text:a("subagentDefaultModelHint")})]}),s.jsxs("select",{className:"set-select",value:u.subagentDefaultModel??"",onChange:p=>ze({subagentDefaultModel:p.target.value||null}),children:[s.jsx("option",{value:"",children:a("subagentFollowMain")}),u.subagentModels.map(p=>s.jsx("option",{value:`${p.provider}/${p.id}`,children:p.label},`${p.provider}/${p.id}`))]})]}),u.subagentModels.length===0&&s.jsx("p",{className:"set-hint",children:a("subagentNoModels")}),P&&s.jsxs("div",{className:"tpl-editor",children:[s.jsxs("div",{className:"tpl-fields",children:[s.jsx("input",{className:"set-input",placeholder:a("tplNamePlaceholder"),value:P.name,onChange:p=>ie({...P,name:p.target.value})}),s.jsx("input",{className:"set-input",placeholder:a("tplDescriptionPlaceholder"),value:P.description,onChange:p=>ie({...P,description:p.target.value})}),s.jsx("input",{className:"set-input",placeholder:a("tplDescriptionEnPlaceholder"),value:P.descriptionEn??"",onChange:p=>ie({...P,descriptionEn:p.target.value})})]}),s.jsxs("div",{className:"set-mode-row",children:[s.jsx("label",{className:"set-field-label",children:a("tplPromptModeLabel")}),s.jsxs("select",{className:"set-select",value:P.promptMode,onChange:p=>ie({...P,promptMode:p.target.value}),children:[s.jsx("option",{value:"replace",children:a("promptModeReplace")}),s.jsx("option",{value:"append",children:a("promptModeAppend")})]})]}),s.jsxs("div",{className:"set-mode-row",children:[s.jsx("label",{className:"set-field-label",children:a("tplModelLabel")}),s.jsxs("select",{className:"set-select",value:P.model??"",onChange:p=>ie({...P,model:p.target.value}),children:[s.jsx("option",{value:"",children:a("subagentFollowMain")}),u.subagentModels.map(p=>s.jsx("option",{value:`${p.provider}/${p.id}`,children:p.label},`${p.provider}/${p.id}`))]})]}),s.jsxs("div",{className:"set-mode-row",children:[s.jsxs("label",{className:"set-field-label",children:[a("tplThinkingLabel")," ",s.jsx(Et,{text:a("tplThinkingHint")})]}),s.jsxs("select",{className:"set-select",value:P.thinkingLevel??"",onChange:p=>ie({...P,thinkingLevel:p.target.value}),children:[s.jsx("option",{value:"",children:a("tplThinkingFollowMain")}),xu.map(p=>s.jsx("option",{value:p,children:a(`thinking.${p}`)},p))]})]}),s.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:`${a("tplSystemPromptLabel")}${c==="zh"?":":": "}${a("tplSystemPromptPlaceholder")}`,value:P.systemPrompt,onChange:p=>ie({...P,systemPrompt:p.target.value})}),s.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:`${a("tplSystemPromptLabel")}: ${a("tplSystemPromptEnPlaceholder")}`,value:P.systemPromptEn??"",onChange:p=>ie({...P,systemPromptEn:p.target.value})}),s.jsxs("div",{className:"tpl-pick-block",children:[s.jsx("div",{className:"tpl-pick-head",children:s.jsxs("span",{children:[a("tplSkillsLabel")," · ",a("tplWhitelistHint")]})}),u.skills.length===0?s.jsx("p",{className:"set-hint",children:a("noSkills")}):s.jsx("div",{className:"tpl-pick",children:u.skills.map(p=>s.jsxs("label",{className:`tpl-chip${P.enabledSkills.includes(p.name)?" on":""}`,children:[s.jsx("input",{type:"checkbox",checked:P.enabledSkills.includes(p.name),onChange:K=>{const ve=K.target.checked;ie({...P,enabledSkills:ve?[...P.enabledSkills,p.name]:P.enabledSkills.filter(st=>st!==p.name)})}}),p.name]},p.name))})]}),s.jsxs("div",{className:"tpl-pick-block",children:[s.jsx("div",{className:"tpl-pick-head",children:s.jsxs("span",{children:[a("tplExtensionsLabel")," · ",a("tplWhitelistHint")]})}),u.extensions.length===0?s.jsx("p",{className:"set-hint",children:a("noExtensions")}):s.jsx("div",{className:"tpl-pick",children:u.extensions.map(p=>s.jsxs("label",{className:`tpl-chip${P.enabledExtensions.includes(p.id)?" on":""}`,children:[s.jsx("input",{type:"checkbox",checked:P.enabledExtensions.includes(p.id),onChange:K=>{const ve=K.target.checked;ie({...P,enabledExtensions:ve?[...P.enabledExtensions,p.id]:P.enabledExtensions.filter(st=>st!==p.id)})}}),p.name]},p.id))})]}),s.jsxs("div",{className:"tpl-actions",children:[s.jsx("button",{type:"button",className:"set-save-btn",disabled:!P.name.trim(),onClick:()=>{J({type:"save_subagent_template",template:{...P,name:P.name.trim()}}),ie(null)},children:a("tplSave")}),s.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>ie(null),children:a("tplCancel")})]})]}),u.subagentTemplates.length===0?s.jsx("p",{className:"set-empty",children:a("noSubagentTemplates")}):s.jsx("div",{className:"set-list",children:u.subagentTemplates.map(p=>s.jsxs("div",{className:"set-row",children:[s.jsxs("div",{className:"set-row-info",children:[s.jsxs("div",{className:"set-row-name",children:[p.name,u.subagentDefaultTemplates.includes(p.name)&&s.jsx("span",{className:"tpl-badge default",children:a("tplDefaultBadge")}),!p.enabled&&s.jsx("span",{className:"tpl-badge",children:a("subagentTemplateClosed")})]}),s.jsxs("div",{className:"set-row-desc",children:[(c!=="zh"&&p.descriptionEn?p.descriptionEn:p.description)||`${p.promptMode==="replace"?a("promptModeReplace"):a("promptModeAppend")}`,p.model?` · ${a("tplModelLabel")} ${p.model}`:` · ${a("subagentFollowMain")}`,p.thinkingLevel?` · ${a("tplThinkingLabel")} ${l(`thinking.${p.thinkingLevel}`)}`:"",p.enabledSkills.length>0&&` · ${a("tplSkillsLabel")} ${p.enabledSkills.length}`,p.enabledExtensions.length>0&&` · ${a("tplExtensionsLabel")} ${p.enabledExtensions.length}`,!p.description&&p.enabledSkills.length===0&&p.enabledExtensions.length===0&&` · ${a("tplInherit")}`]})]}),s.jsxs("div",{className:"set-row-actions",children:[s.jsx("button",{type:"button",className:`set-switch${p.enabled?" on":""}`,role:"switch","aria-checked":p.enabled,title:`${p.enabled?a("subagentTemplateDisable"):a("subagentTemplateEnable")} · ${a("subagentTemplateOffHint")}`,onClick:()=>J({type:"save_subagent_template",template:{...p,enabled:!p.enabled}}),children:s.jsx("span",{className:"set-switch-knob"})}),s.jsx("button",{type:"button",className:"dd-refresh",title:a("subagentTemplateEdit"),onClick:()=>ie({...p}),children:a("subagentTemplateEdit")}),I===p.name?s.jsx("button",{type:"button",className:"set-uninstall confirm",title:a("uninstallConfirmHint"),onClick:()=>{J({type:"delete_subagent_template",name:p.name}),he(null)},children:a("uninstallConfirm")}):s.jsx("button",{type:"button",className:"set-icon-btn danger",title:a("tplDelete"),onClick:()=>he(p.name),children:s.jsx(Rt,{})})]})]},p.name))})]}),Nt&&s.jsx(lc,{plugin:Nt.plugin,epoch:e.pluginsEpoch,send:J,className:"set-plugin-page"})]})]}),s.jsx("div",{className:"modal-actions",children:s.jsx("button",{type:"button",className:"dd-refresh",onClick:r,children:a("close")})})]})})}function _x(e,t){const n=Math.max(0,Date.now()-e),r=Math.floor(n/6e4);if(r<1)return t("bgTaskJustNow");if(r<60)return t("bgTaskMinutes",{n:r});const a=Math.floor(r/60);return a<24?t("bgTaskHours",{n:a}):t("bgTaskDays",{n:Math.floor(a/24)})}function Ax({servers:e,onClose:t}){const n=He(),[r,a]=o.useState(new Set),c=l=>a(u=>{const d=new Set(u);return d.has(l)?d.delete(l):d.add(l),d});return o.useEffect(()=>{J({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(ua,{})," ",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(bt,{})})]}),e.length===0?s.jsxs("div",{className:"bg-task-empty",children:[s.jsx(ua,{}),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,d=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")," ",_x(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 ${r.has(d)?"open":""}`,title:`${n("bgTaskCommand")}: ${l.command}`,onClick:()=>c(d),children:[s.jsx(Rn,{}),s.jsx("code",{children:l.command})]})]}),s.jsxs("button",{type:"button",className:"btn bg-task-stop",title:n("bgTaskStop"),onClick:()=>J(u?{type:"kill_background_server",taskId:l.taskId}:{type:"kill_background_server",port:l.port}),children:[s.jsx(oa,{}),s.jsx("span",{children:n("bgTaskStop")})]})]},d)})}),s.jsxs("div",{className:"bg-task-foot",children:[s.jsxs("button",{type:"button",className:"btn",title:n("bgTaskRefresh"),onClick:()=>J({type:"list_bg_servers"}),children:[s.jsx(Yt,{}),s.jsx("span",{children:n("bgTaskRefresh")})]}),s.jsxs("button",{type:"button",className:"btn bg-task-stopall",disabled:e.length===0,title:n("bgTaskStopAll"),onClick:()=>J({type:"kill_background_servers"}),children:[s.jsx(oa,{}),s.jsx("span",{children:n("bgTaskStopAll")})]})]})]})})}function jx(e,t){return e.toLowerCase().includes(t)}function Ix({open:e,projects:t,fileSearch:n,sessionSearch:r,onClose:a,onSwitchSession:c,onSwitchProject:l,onPreviewFile:u}){const d=He(),{locale:m}=Vt(),f=m==="en"?"Plugins":"插件",h=$t("cwd"),b=o.useRef(null),[E,N]=o.useState(""),g=o.useDeferredValue(E),[R,M]=o.useState(0),B=o.useRef(1),j=o.useRef(0),Y=o.useRef(null);o.useEffect(()=>{if(!e)return;J({type:"list_sessions"}),J({type:"list_projects"});const P=E.trim();if(P){const ie=++B.current;j.current=ie,C(!0),J({type:"search_files",reqId:ie,query:P}),J({type:"search_sessions",reqId:ie,query:P})}requestAnimationFrame(()=>b.current?.select())},[e]);const[q,C]=o.useState(!1);o.useEffect(()=>{Y.current&&clearTimeout(Y.current);const P=g.trim();if(!P){C(!1);return}return Y.current=setTimeout(()=>{const ie=++B.current;j.current=ie,C(!0),J({type:"search_files",reqId:ie,query:P}),J({type:"search_sessions",reqId:ie,query:P})},300),()=>{Y.current&&clearTimeout(Y.current)}},[g]);const Te=g.trim().toLowerCase(),xe=o.useMemo(()=>!Te||!r||r.reqId!==j.current||!r.ok?[]:r.results,[r,Te]),G=o.useMemo(()=>Te?t.filter(P=>jx(P.path,Te)).slice(0,10):[],[t,Te]),ee=o.useMemo(()=>!Te||!n||n.reqId!==j.current||!n.ok?[]:n.results,[n,Te]);o.useEffect(()=>{n&&n.reqId===j.current&&r&&r.reqId===j.current&&j.current!==0&&C(!1)},[n,r]);const Q=!!n&&n.ok&&n.truncated,[O,F]=o.useState([]);o.useEffect(()=>{if(!e)return;const P=g.trim();if(!P){F([]);return}let ie=!1,I=[];try{const _=window,re=_.__piWebUiHost?.searchProviders?.list;if(typeof re=="function"){const le=re.call(_.__piWebUiHost);Array.isArray(le)&&(I=le)}else typeof Tr=="function"&&(I=Tr())}catch{I=[]}const he=I.filter(_=>_&&typeof _.id=="string").map(_=>{if(typeof _.search=="function")return _;try{const re=fm(_.id);return re&&typeof re.search=="function"?{..._,search:re.search}:null}catch{return null}}).filter(_=>!!_);if(he.length===0){F([]);return}return Promise.allSettled(he.map(_=>Promise.race([_.search(P),new Promise((re,le)=>setTimeout(()=>le(new Error("timeout")),3e3))]).then(re=>({provider:_,items:Array.isArray(re)?re:[]}),()=>({provider:_,items:[]})))).then(_=>{if(ie)return;const re=[];for(const le of _)if(le.status==="fulfilled")for(const Ee of le.value.items){if(!Ee||typeof Ee!="object")continue;const Ne=Ee;typeof Ne.title!="string"||typeof Ne.action!="string"||re.push({providerId:le.value.provider.id,providerLabel:le.value.provider.label,title:Ne.title,...typeof Ne.hint=="string"?{hint:Ne.hint}:{},action:Ne.action})}F(re.slice(0,20))}),()=>{ie=!0}},[e,g]);const w=o.useMemo(()=>[...xe.map(P=>({kind:"session",path:P.path,anchors:P.anchors})),...G.map(P=>({kind:"project",path:P.path})),...ee.filter(P=>P.type==="file").map(P=>({kind:"file",path:P.path,name:P.name})),...O.map(P=>({kind:"plugin",providerId:P.providerId,providerLabel:P.providerLabel,title:P.title,action:P.action}))],[xe,G,ee,O]);o.useEffect(()=>{M(0)},[g]);const se=o.useCallback(P=>{if(P)if(P.kind==="session")c(P.path,P.anchors),a();else if(P.kind==="project"){l(P.path),J({type:"list_sessions"}),J({type:"list_projects"});const ie=g.trim();if(ie){const I=++B.current;j.current=I,C(!0),J({type:"search_files",reqId:I,query:ie}),J({type:"search_sessions",reqId:I,query:ie})}}else P.kind==="plugin"?Jl(P.providerId,P.action,P.action).catch(()=>{}):u(P.path,P.name)},[c,l,u,g]);o.useEffect(()=>{if(!e)return;const P=ie=>{ie.key==="Escape"?(ie.preventDefault(),ie.stopPropagation(),a()):ie.key==="ArrowDown"?(ie.preventDefault(),M(I=>Math.min(I+1,w.length-1))):ie.key==="ArrowUp"?(ie.preventDefault(),M(I=>Math.max(I-1,0))):ie.key==="Enter"&&(ie.preventDefault(),se(w[R]))};return window.addEventListener("keydown",P,!0),()=>window.removeEventListener("keydown",P,!0)},[w,R,se,a,e]);const z=xe.length+G.length+ee.length+O.length,A=(P,ie,I)=>s.jsxs("div",{className:"gs-section-head",children:[I,s.jsx("span",{children:P}),s.jsx("em",{children:ie})]});let ue=-1;return e?s.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:a,children:s.jsxs("div",{className:"gs-modal",onClick:P=>P.stopPropagation(),children:[s.jsxs("div",{className:"gs-input-row",children:[s.jsx(ca,{}),s.jsx("input",{ref:b,type:"text",value:E,placeholder:d("gsPlaceholder"),onChange:P=>N(P.target.value)}),s.jsx("button",{type:"button",className:"gs-close",title:d("close"),onClick:a,children:s.jsx(bt,{})})]}),s.jsxs("div",{className:"gs-results",children:[!Te&&s.jsx("div",{className:"gs-empty",children:d("gsHint")}),Te&&z===0&&!Q&&s.jsx("div",{className:"gs-empty",children:d(q?"gsSearching":"gsNoResults")}),xe.length>0&&s.jsxs("div",{className:"gs-section",children:[A(d("gsSessions"),xe.length,s.jsx(Is,{})),xe.map(P=>{ue++;const ie=ue;return s.jsxs("button",{type:"button",className:ie===R?"gs-item active":"gs-item",onMouseEnter:()=>M(ie),onClick:()=>se({kind:"session",path:P.path,anchors:P.anchors}),children:[s.jsxs("span",{className:"gs-item-title",children:[P.name||P.path.split(/[\\/]/).pop(),s.jsx("em",{className:"gs-item-meta",children:P.messageCount})]}),s.jsx("span",{className:"gs-item-sub",children:P.firstMessage})]},P.path)})]}),G.length>0&&s.jsxs("div",{className:"gs-section",children:[A(d("gsProjects"),G.length,s.jsx(is,{})),G.map(P=>{ue++;const ie=ue,I=h&&P.path===h;return s.jsxs("button",{type:"button",className:ie===R?"gs-item active":"gs-item",onMouseEnter:()=>M(ie),onClick:()=>se({kind:"project",path:P.path}),children:[s.jsxs("span",{className:"gs-item-title",children:[P.path.split(/[\\/]/).pop(),I&&s.jsx("em",{className:"gs-item-meta",children:d("gsCurrentProject")})]}),s.jsx("span",{className:"gs-item-sub",children:P.path})]},P.path)})]}),(ee.length>0||Te&&Q)&&s.jsxs("div",{className:"gs-section",children:[A(d("gsFiles"),ee.length,s.jsx(Nl,{})),ee.map(P=>{ue++;const ie=ue;return s.jsxs("button",{type:"button",className:ie===R?"gs-item active":"gs-item",disabled:P.type==="dir",title:P.type==="dir"?void 0:d("gsOpenPreview"),onMouseEnter:()=>M(ie),onClick:()=>{P.type==="file"&&se({kind:"file",path:P.path,name:P.name})},children:[s.jsx("span",{className:"gs-item-title",children:P.name}),s.jsx("span",{className:"gs-item-sub",children:P.path})]},`${P.type}:${P.path}`)}),Q&&s.jsx("div",{className:"gs-truncated",children:d("gsTruncated")})]}),O.length>0&&s.jsxs("div",{className:"gs-section",children:[A(f,O.length,s.jsx(Gn,{})),O.map((P,ie)=>{ue++;const I=ue;return s.jsxs("button",{type:"button",className:I===R?"gs-item active":"gs-item",title:P.providerLabel,onMouseEnter:()=>M(I),onClick:()=>se({kind:"plugin",providerId:P.providerId,providerLabel:P.providerLabel,title:P.title,action:P.action}),children:[s.jsx("span",{className:"gs-item-title",children:P.title}),s.jsx("span",{className:"gs-item-sub",children:P.hint??P.providerLabel})]},`${P.providerId}:${P.action}:${ie}`)})]})]}),s.jsxs("div",{className:"gs-foot",children:[s.jsxs("span",{children:["↑↓ ",d("gsNavigate")]}),s.jsxs("span",{children:["Enter ",d("gsOpen")]}),s.jsxs("span",{children:["Esc ",d("gsCloseHint")]})]})]})}):null}const rr=5e3;function Rx({file:e,content:t,onAddLines:n,onAttach:r,onClose:a}){const c=He(),[l,u]=o.useState(null),[d,m]=o.useState(!1),[f,h]=o.useState(null),[b,E]=o.useState(!1),[N,g]=o.useState(!1),[R,M]=o.useState(!1),[B,j]=o.useState(""),[Y,q]=o.useState(!0),[C,Te]=o.useState(!0),[xe,G]=o.useState(!1),ee=o.useRef(!1),[Q,O]=o.useState(!0),[F,w]=o.useState(!1),[se,z]=o.useState(100),A=o.useRef(0),ue=o.useRef(!1),P=o.useRef(null);o.useEffect(()=>{m(!0),u(null),h(null),M(!1),j(""),q(!0),Te(!0),G(!1),ee.current=!1,J({type:"read_file",path:e.path})},[e.path]),o.useEffect(()=>{t&&t.path===e.path&&(u(t),R||j(t.text),m(!1))},[t,R,e.path]),o.useEffect(()=>{const W=oe=>{if(oe.key==="Escape"){Ke();return}if((oe.ctrlKey||oe.metaKey)&&oe.key.toLowerCase()==="s"&&R){oe.preventDefault(),ke();return}const fe=oe.target,de=fe&&(fe.tagName==="INPUT"||fe.tagName==="TEXTAREA"||fe.isContentEditable);(oe.ctrlKey||oe.metaKey)&&oe.key.toLowerCase()==="a"&&!de&&(oe.preventDefault(),re())};return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)},[a,l,R,B]),o.useEffect(()=>{const W=()=>{ue.current=!1,E(!1)};return window.addEventListener("mouseup",W),()=>window.removeEventListener("mouseup",W)},[]);const ie=o.useMemo(()=>{if(!l)return[];const W=l.text.split(`
|
|
374
|
+
`);return W.length>0&&W[W.length-1]===""&&W.pop(),W.slice(0,rr)},[l]),I=l?.lines??0,he=I>rr,_=(W,oe)=>{if(oe){const fe=A.current>0?A.current:W;h({start:Math.min(fe,W),end:Math.max(fe,W)})}else A.current=W,h({start:W,end:W})},re=()=>{ie.length!==0&&(A.current=1,h({start:1,end:ie.length}))},le=()=>{f&&(n(e.path,e.name,f.start,f.end),g(!0),P.current&&clearTimeout(P.current),P.current=setTimeout(()=>g(!1),1400))},Ee=l!==null&&l.kind==="text"&&!l.binary&&!l.truncated,Ne=()=>{j(l?.text??""),M(!1),ee.current&&(on(e.name)&&q(!0),ln(e.name)&&Te(!0))},Ue=()=>{if(R){if(B!==(l?.text??"")&&!window.confirm(c("discardFileChanges")))return;Ne();return}!Ee||!l||(ee.current=on(e.name)&&Y||ln(e.name)&&C,on(e.name)&&q(!1),ln(e.name)&&Te(!1),h(null),j(l.text),M(!0))},ke=()=>{!R||!l||!Ee||J({type:"write_file",path:e.path,text:B})&&(M(!1),ee.current&&(on(e.name)&&q(!0),ln(e.name)&&Te(!0)),h(null))},Ke=()=>{R&&B!==(l?.text??"")&&!window.confirm(c("discardFileChanges"))||a()},Ie=W=>{z(Math.min(200,Math.max(50,W)))},ce=f?f.end-f.start+1:0,pe=l?.binary??!1,Fe=l?.truncated??!1,Ae=l?.kind??"text",et=on(e.name),dt=ln(e.name),Ve=et&&Y&&!R&&Ae==="text"&&!pe,X=dt&&C&&!R&&Ae==="text"&&!pe,we=W=>hs(_t(`/api/file?clientId=${encodeURIComponent(Ea())}&path=${encodeURIComponent(W)}`)),L=W=>{const oe=W.split("/").map(ge=>encodeURIComponent(ge)).join("/"),de=/^[A-Za-z]:([\\/]|$)/.test(W)||W.startsWith("/")?`/api/preview/__abs__/${oe}`:`/api/preview/${oe}`;return hs(_t(`${de}?clientId=${encodeURIComponent(Ea())}${xe?"&allowJs=1":""}`))};return s.jsx("div",{className:`fp-overlay ${F?"fullscreen":""}`,onMouseDown:W=>{W.target===W.currentTarget&&Ke()},children:s.jsxs("div",{className:`fp ${F?"fullscreen":""}`,style:{"--fp-zoom":se/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&&Ae==="text"&&!pe&&c("fileLines",{n:I}),l&&` · ${Px(l.size)}`]}),s.jsxs("span",{className:"fp-head-actions",children:[et&&Ae==="text"&&!pe&&l&&s.jsx("button",{type:"button",className:`fp-attach markdown ${Y?"on":""}`,"data-tip":c(Y?"showMarkdownSource":"showMarkdownPreview"),disabled:R,onClick:()=>q(W=>!W),children:Y?s.jsx(da,{}):s.jsx(Ci,{})}),dt&&Ae==="text"&&!pe&&l&&s.jsx("button",{type:"button",className:`fp-attach html ${C?"on":""}`,"data-tip":c(C?"showHtmlSource":"showHtmlPreview"),disabled:R,onClick:()=>Te(W=>!W),children:C?s.jsx(Ci,{}):s.jsx(da,{})}),Ae==="text"&&!pe&&l&&s.jsx("button",{type:"button",className:`fp-attach edit ${R?"on":""}`,"data-tip":c(Fe?"fileEditTruncated":R?"exitEditFile":"editFile"),disabled:!Ee&&!R,onClick:Ue,children:s.jsx(_n,{})}),Ae==="text"&&!pe&&!Ve&&!X&&s.jsx("button",{type:"button",className:`fp-attach wrap ${Q?"on":""}`,"data-tip":c(Q?"disableWrap":"enableWrap"),onClick:()=>O(W=>!W),children:s.jsx(Kd,{})}),Ae==="text"&&l&&s.jsxs("span",{className:"fp-zoom",children:[s.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":c("zoomOut"),disabled:se<=50,onClick:()=>Ie(se-10),children:s.jsx(Sd,{})}),s.jsxs("button",{type:"button",className:"fp-zoom-val",title:c("resetZoom"),onClick:()=>z(100),children:[se,"%"]}),s.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":c("zoomIn"),disabled:se>=200,onClick:()=>Ie(se+10),children:s.jsx(_d,{})})]}),Ae!=="video"&&Ae!=="none"&&s.jsx("button",{type:"button",className:"fp-attach inline","data-tip":c("attachInlineTip"),onClick:()=>r(e.path,e.name,"inline"),children:s.jsx(Dt,{})}),s.jsx("button",{type:"button",className:"fp-attach ref","data-tip":c("referenceTip"),onClick:()=>r(e.path,e.name,"reference"),children:s.jsx(dr,{})}),s.jsx("button",{type:"button",className:`fp-attach full ${F?"on":""}`,"data-tip":c(F?"exitFullscreen":"fullscreen"),onClick:()=>w(W=>!W),children:F?s.jsx(Md,{}):s.jsx(Bd,{})}),s.jsx("button",{type:"button",className:"fp-close",title:c("close"),onClick:Ke,children:s.jsx(bt,{})})]})]}),Fe&&Ae==="text"&&!pe&&s.jsx("div",{className:"fp-notice",children:c("previewTruncated")}),d&&!l&&s.jsx("div",{className:"fp-empty",children:c("loading")}),!d&&Ae==="none"&&!pe&&s.jsx("div",{className:"fp-empty",children:c("previewNotSupported")}),!d&&Ae==="image"&&s.jsx("div",{className:"fp-media-wrap",children:s.jsx("img",{className:"fp-media",src:we(e.path),alt:e.name})}),!d&&Ae==="video"&&s.jsx("div",{className:"fp-media-wrap",children:s.jsx("video",{className:"fp-media",src:we(e.path),controls:!0,preload:"metadata"})}),!d&&X&&l&&s.jsxs("div",{className:"fp-html",children:[s.jsxs("div",{className:"fp-html-bar",children:[s.jsx("span",{className:"fp-html-hint",title:c(xe?"htmlJsOnTip":"htmlJsOffTip"),children:c(xe?"htmlJsOn":"htmlJsOff")}),s.jsx("button",{type:"button",className:`fp-html-js ${xe?"on":""}`,"data-tip":c(xe?"htmlDisableJs":"htmlEnableJs"),onClick:()=>G(W=>!W),children:c(xe?"htmlDisableJs":"htmlEnableJs")})]}),s.jsx("iframe",{className:"fp-html-frame",src:L(e.path),title:e.name,sandbox:xe?"allow-scripts":"",referrerPolicy:"no-referrer"},xe?"js":"nojs")]}),!d&&Ve&&l&&s.jsx("div",{className:"fp-markdown msg-text",children:s.jsx("div",{className:"fp-markdown-zoom",children:s.jsx(Ot,{text:l.text})})}),!d&&pe&&Ae!=="image"&&Ae!=="video"&&l&&s.jsxs("div",{className:"fp-hex-wrap",children:[s.jsxs("div",{className:"fp-notice",children:[c("binaryFile"),l.truncated&&c("binaryHexTruncated")]}),s.jsx("pre",{className:"fp-hex",children:l.text})]}),!d&&R&&Ae==="text"&&!pe&&l&&s.jsx("textarea",{className:`fp-editor ${Q?"":"no-wrap"}`,value:B,onChange:W=>j(W.target.value),wrap:Q?"soft":"off",spellCheck:!1,autoFocus:!0}),!d&&!Ve&&!X&&!R&&Ae==="text"&&!pe&&l&&ie.length===0&&s.jsx("div",{className:"fp-empty",children:c("emptyFile")}),!d&&!Ve&&!X&&!R&&Ae==="text"&&!pe&&ie.length>0&&s.jsxs("div",{className:`fp-code ${b?"dragging":""} ${Q?"":"no-wrap"}`,onMouseDown:W=>{W.button===0&&W.preventDefault()},children:[ie.map((W,oe)=>{const fe=oe+1,de=f!==null&&fe>=f.start&&fe<=f.end;return s.jsxs("div",{className:`fp-line ${de?"sel":""}`,onMouseDown:ge=>{ge.button===0&&(_(fe,ge.shiftKey),ue.current=!0,E(!0))},onMouseEnter:()=>{ue.current&&_(fe,!0)},children:[s.jsx("span",{className:"fp-num",children:fe}),s.jsx("span",{className:"fp-code-text",children:W})]},fe)}),he&&s.jsx("div",{className:"fp-lines-note",children:c("previewLinesTruncated",{n:rr})})]}),s.jsx("div",{className:"fp-foot",children:R?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"fp-hint",children:c("editFile")}),s.jsxs("div",{className:"fp-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:Ue,children:c("cancel")}),s.jsxs("button",{type:"button",className:"btn primary",disabled:B===(l?.text??""),onClick:ke,children:[s.jsx(Rd,{})," ",c("saveFile")]})]})]}):!Ve&&!X&&Ae==="text"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"fp-hint",children:f?c("selectedRange",{n:ce,start:f.start,end:f.end}):c("selectLinesHint")}),s.jsxs("div",{className:"fp-actions",children:[s.jsx("button",{type:"button",className:"btn",disabled:ie.length===0,onClick:re,children:c("selectAll")}),s.jsx("button",{type:"button",className:"btn",disabled:!f,onClick:()=>h(null),children:c("clearSelection")}),s.jsxs("button",{type:"button",className:"btn primary",disabled:!f||pe,onClick:le,children:[N?s.jsx(os,{}):null,c(N?"addedToChat":"addToChat")]})]})]})})]})})}function on(e){const t=e.toLowerCase();return t.endsWith(".md")||t.endsWith(".markdown")}function ln(e){const t=e.toLowerCase();return t.endsWith(".html")||t.endsWith(".htm")||t.endsWith(".xhtml")}function Px(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}const Ou="pi-web-sounds",cn={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function Mu(){try{const e=localStorage.getItem(Ou);if(!e)return{...cn};const t=JSON.parse(e),n={...cn,...t};for(const r of["enabled","question","done","start","error"])typeof n[r]!="boolean"&&(n[r]=cn[r]);return typeof n.volume!="number"||!Number.isFinite(n.volume)?n.volume=cn.volume:n.volume=Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...cn}}}function Lx(e){try{localStorage.setItem(Ou,JSON.stringify(e))}catch{}}let un=null;function Dx(){try{if(!un){const e=window.AudioContext??window.webkitAudioContext;if(!e)return null;un=new e}return un.state==="suspended"&&un.resume(),un}catch{return null}}const Ox=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],Mx=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],Bx=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],Fx=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],Hx={question:Ox,done:Mx,start:Bx,error:Fx};function Ux(e,t,n){const r=e.createOscillator(),a=e.createGain();r.type=t.type,r.frequency.value=t.freq;const c=e.currentTime+t.start,l=Math.max(1e-4,t.peak*n);a.gain.setValueAtTime(1e-4,c),a.gain.exponentialRampToValueAtTime(l,c+.012),a.gain.exponentialRampToValueAtTime(1e-4,c+t.dur),r.connect(a),a.connect(e.destination),r.start(c),r.stop(c+t.dur+.05)}function Hs(e,t=Mu()){if(!t.enabled||!t[e])return;const n=Dx();if(!n)return;const r=Math.max(0,Math.min(1,t.volume/100));for(const a of Hx[e])Ux(n,a,r)}const $x=o.lazy(()=>Ed(()=>Promise.resolve().then(()=>O1),[]).then(e=>({default:e.TerminalPanel})));function qx({notice:e,onDismiss:t}){const n=He(),{locale:r}=Vt(),a=r!=="zh"&&e.textEn?e.textEn:e.text,[c,l]=o.useState(!1);o.useEffect(()=>{if(c)return;const d=setTimeout(()=>t(e.id),e.level==="error"?12e3:7e3);return()=>clearTimeout(d)},[c,e.id,e.level,t]);const u=e.level==="error"?Vd:e.level==="warning"?hr:$d;return s.jsxs("div",{className:`notice notice-${e.level}${c?" paused":""}`,role:"status",onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[s.jsx(u,{className:"notice-icon"}),s.jsx("span",{className:"notice-text",children:a}),s.jsx("button",{type:"button",className:"notice-close",title:n("close"),onClick:()=>t(e.id),children:s.jsx(bt,{})})]})}const Wx=[],Bu=180,Fu=520,Hu=240,Uu=e=>`pi-web-ui:${e}-panel-width`;function ol(e){const t=Number(localStorage.getItem(Uu(e)));return Number.isFinite(t)&&t>=Bu&&t<=Fu?t:Hu}const zr=e=>`pi-web-ui:${e}-panel-collapsed`;function ll(e){return localStorage.getItem(zr(e))==="1"}function cl({side:e,width:t,onResize:n}){const r=He(),a=o.useCallback(c=>{c.preventDefault();const l=c.clientX,u=t;let d=u;const m=h=>{const b=e==="left"?h.clientX-l:l-h.clientX;d=Math.min(Fu,Math.max(Bu,Math.round(u+b))),n(d)},f=()=>{window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",f),document.body.classList.remove("panel-resizing"),localStorage.setItem(Uu(e),String(d))};window.addEventListener("pointermove",m),window.addEventListener("pointerup",f),document.body.classList.add("panel-resizing")},[e,t,n]);return s.jsx("div",{className:`resize-handle resize-${e}`,title:r("dragToResize"),onPointerDown:a,onDoubleClick:()=>n(Hu)})}function ul({side:e,onClick:t}){const n=He();return s.jsx("button",{type:"button",className:`panel-rail panel-rail-${e}`,title:n("expandPanel"),onClick:t,children:e==="left"?s.jsx(vl,{}):s.jsx(Cl,{})})}const $u="pi-web-ui:plugin-path-grants";function qu(){try{const e=localStorage.getItem($u),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function Kx(e){try{const t=[...new Set([...qu(),e])];localStorage.setItem($u,JSON.stringify(t))}catch{}}function Gx(){const e=He(),{locale:t}=Vt(),{chat:n,send:r,dismissNotice:a,pushNotice:c,terminal:l}=Om(),u=o.useRef(!1);o.useEffect(()=>{!n.ready||!n.settings||u.current||n.settings.quickPhrasesSeeded||(u.current=!0,n.settings.quickPhrases.length===0&&r({type:"set_settings",quickPhrases:ja[t]??ja.en,quickPhrasesSeeded:!0}))},[n.ready,n.settings,r,t]);const d=n.state?.cwd??"",m=Su();o.useEffect(()=>{const T=m?dx(d):"";document.title=T?`${T} — pi-web-ui`:e("docTitle")},[d,m,e]);const[f,h]=o.useState([]);o.useEffect(()=>(ji(T=>h(ne=>Qb(ne,T))),()=>ji(null)),[]);const[b,E]=o.useState(null),[N,g]=o.useState(!1);o.useEffect(()=>{const T=()=>g(!1);return window.addEventListener("drop",T,!0),()=>window.removeEventListener("drop",T,!0)},[]);const[R,M]=o.useState("chat"),B=T=>!n.tabs||T==="chat"||n.tabs.includes(T),j=R.startsWith("plugin:")?"plugins":R,Y=B(j)?R:"chat",q=o.useMemo(()=>n.plugins.filter(T=>!n.settings?.disabledPlugins?.includes(T.id)),[n.plugins,n.settings?.disabledPlugins]),C=o.useMemo(()=>bu(n.plugins,{locale:t,t:T=>e(T),disabledPlugins:n.settings?.disabledPlugins??[],layout:n.settings?.uiLayout}),[n.plugins,n.settings?.disabledPlugins,n.settings?.uiLayout,t,e]),Te=o.useMemo(()=>C["topbar.primary"].filter(T=>!T.hidden),[C]),xe=o.useMemo(()=>[...C["topbar.primary"].filter(T=>T.hidden),...C["topbar.overflow"]],[C]),G=o.useMemo(()=>C["leftpanel.sessions"].filter(T=>!T.hidden),[C]),ee=o.useMemo(()=>C["terminal.toolbar"].filter(T=>!T.hidden),[C]),Q=o.useMemo(()=>C["scm.toolbar"].filter(T=>!T.hidden),[C]),O=o.useMemo(()=>C["goalbar.actions"].filter(T=>!T.hidden),[C]),F=o.useMemo(()=>Object.fromEntries((n.dshPresets?.presets??[]).map(T=>[T.id,T.name??T.id])),[n.dshPresets]),w=o.useMemo(()=>C["notice.actions"].filter(T=>!T.hidden),[C]),se=o.useCallback(T=>{const ne=(T.action??"").trim();if(T.kind==="view"||(!ne||ne==="view")&&T.source!=="host"){M(T.view??`plugin:${T.source.startsWith("plugin:")?T.source.slice(7):""}`);return}if(!ne)return;const Ce=T.source.startsWith("plugin:")?T.source.slice(7):"";Jl(Ce,ne,T.id,{loadBundle:async tt=>{const pt=ue.current.plugins.find(Bt=>Bt.id===tt);return pt?Sr(pt,ue.current.pluginsEpoch):!1}}).then(tt=>{tt||c("info",e("pluginUiNoHandler"))})},[e,c]),[z,A]=o.useState([]);o.useEffect(()=>km(A),[]),o.useEffect(()=>{b0(r),x0(q,n.pluginsEpoch),T0(q,n.pluginsEpoch),Nm(q,n.pluginsEpoch)},[q,n.pluginsEpoch,r]);const ue=o.useRef(n);ue.current=n;const P=o.useRef(M);P.current=M,o.useEffect(()=>(Yi(rm({send:r,isReady:()=>!!ue.current.state,setView:T=>P.current(T),getCwd:()=>ue.current.state?.cwd??"",getWorkspaceRoots:()=>ue.current.state?.workspaceRoots??[],listSessions:()=>{const T=ue.current,ne=T.state?.cwd??"";return[...T.conversations.map(Ce=>({id:Ce.id,title:Ce.title,cwd:Ce.cwd||ne,kind:"running",isStreaming:Ce.isStreaming})),...T.sessions.map(Ce=>({id:Ce.path,title:Ce.name||Ce.firstMessage||Ce.path,cwd:ne,kind:"history"}))]},getConversationId:()=>ue.current.state?.conversationId??null,isConversationBlank:()=>(ue.current.state?.messages.length??0)===0,listProjects:()=>ue.current.projects.map(T=>T.path),grantedPaths:qu,grantPath:Kx,confirm:T=>new Promise(ne=>oe({path:T.path,resolve:ne})),dialogConfirm:T=>new Promise(ne=>{if(ge.current){ne(!1);return}const Ce={kind:"confirm",title:T.title,resolve:ne};ge.current=Ce,de(Ce)}),select:T=>new Promise(ne=>{if(ge.current){ne({ok:!1,error:"busy"});return}const Ce={kind:"select",title:T.title,options:T.options,...T.multi?{multi:!0}:{},resolve:ne};ge.current=Ce,ye([]),de(Ce)}),input:T=>new Promise(ne=>{if(ge.current){ne({ok:!1,error:"busy"});return}const Ce={kind:"input",title:T.title,...typeof T.placeholder=="string"?{placeholder:T.placeholder}:{},...typeof T.initial=="string"?{initial:T.initial}:{},resolve:ne};ge.current=Ce,rt(T.initial??""),de(Ce)}),notifyAction:T=>new Promise(ne=>{try{const Ce=$e.current;$e.current=null,D(null);try{Ce?.resolve(null)}catch{}const tt={text:T.text,actions:T.actions,resolve:ne};$e.current=tt,D(tt)}catch{ne(null)}}),loadPluginBundle:T=>{const ne=ue.current.plugins.find(Ce=>Ce.id===T);return ne?Sr(ne,ue.current.pluginsEpoch):Promise.resolve(!1)}})),()=>Yi(null)),[r]);const[ie,I]=o.useState(()=>ol("left")),[he,_]=o.useState(()=>ol("right")),re=o.useCallback(T=>I(T),[]),le=o.useCallback(T=>_(T),[]),[Ee,Ne]=o.useState(()=>ll("left")),[Ue,ke]=o.useState(()=>ll("right")),Ke=o.useCallback(()=>{Ne(T=>(localStorage.setItem(zr("left"),T?"0":"1"),!T))},[]),Ie=o.useCallback(()=>{ke(T=>(localStorage.setItem(zr("right"),T?"0":"1"),!T))},[]),[ce,pe]=o.useState(null),[Fe,Ae]=o.useState(()=>window.matchMedia("(max-width: 768px)").matches);o.useEffect(()=>{const T=window.matchMedia("(max-width: 768px)"),ne=Ce=>Ae(Ce.matches);return T.addEventListener("change",ne),()=>T.removeEventListener("change",ne)},[]);const[et,dt]=o.useState(!1),[Ve,X]=o.useState(!1),[we,L]=o.useState(!1),[W,oe]=o.useState(null),[fe,de]=o.useState(null),ge=o.useRef(null),[Qe,ye]=o.useState([]),[Oe,rt]=o.useState(""),[Ge,D]=o.useState(null),$e=o.useRef(null),[it,Xe]=o.useState(()=>new Set),U=(T,ne)=>{r({type:"plugin_path_response",id:T,ok:ne}),Xe(Ce=>new Set(Ce).add(T))},Pe=n.pathRequests.find(T=>!it.has(T.id))??null,Le=vu(),[ot,Ye]=o.useState(!1),[ct,mt]=o.useState(!1),[Mt,$]=o.useState(null);o.useEffect(()=>{if(!Mt)return;const T=setTimeout(()=>$(null),15e3);return()=>clearTimeout(T)},[Mt]),o.useEffect(()=>{const T=Ce=>{const tt=Ce.detail,pt=tt?.title||e("pluginCommandFallback"),Bt=tt?.command;if(!Bt||!n.ready)return;const Ft={name:pt,command:Bt,cwd:"${pwd}"},Wt=n.terminals.find(en=>en.title===pt);if(Wt)l.restart(Wt.id),r({type:"run_command",terminalId:Wt.id,conversationId:Wt.conversationId,command:Ft,cols:80,rows:24});else{const en=qt();l.create({id:en,conversationId:n.activeConversationId||n.state?.conversationId||"",title:pt,cwd:n.state?.cwd??"",cols:80,rows:24,running:!0,exitCode:null,command:Ft})}M("terminal")};window.addEventListener("pi-web-ui:plugin-run-command",T);const ne=Ce=>{const tt=Ce.detail;typeof tt=="string"&&tt&&r({type:"switch_conversation",id:tt})};return window.addEventListener("pi-web-ui:switch-conversation",ne),()=>{window.removeEventListener("pi-web-ui:plugin-run-command",T),window.removeEventListener("pi-web-ui:switch-conversation",ne)}},[n,l,r]),o.useEffect(()=>{const T=ne=>{!(ne.ctrlKey||ne.metaKey)||ne.key.toLowerCase()!=="k"||(ne.preventDefault(),mt(Ce=>!Ce))};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[]);const[Z,Re]=o.useState(Mu),{themes:je,theme:Je,switchTheme:qe,reloadThemes:At}=v0();Nx(),o.useEffect(()=>{try{typeof Vi=="function"&&Vi(Je??"")}catch{}},[Je]),o.useEffect(()=>{try{typeof Qi=="function"&&Qi(t)}catch{}},[t]),o.useEffect(()=>{try{typeof Xi=="function"&&Xi(Y)}catch{}},[Y]),o.useEffect(()=>{if(!fe)return;const T=ne=>{if(ne.key!=="Escape")return;const Ce=ge.current;ge.current=null,de(null);try{if(!Ce)return;Ce.kind==="confirm"?Ce.resolve(!1):Ce.resolve({ok:!1})}catch{}};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[fe]),o.useEffect(()=>{if(!Ge)return;const T=setTimeout(()=>{const ne=$e.current;$e.current=null,D(null);try{ne?.resolve(null)}catch{}},8e3);return()=>clearTimeout(T)},[Ge]);const Lt=o.useRef(null),jt=o.useRef(null),us=o.useRef(null),Qt=o.useRef(0),Ut=o.useRef(!1),v=o.useRef(n.terminals);o.useEffect(()=>{Lx(Z)},[Z]),o.useEffect(()=>{const T=v.current;v.current=n.terminals;for(const ne of n.terminals){const Ce=ne.command?.command??"";!T.find(pt=>pt.id===ne.id)?.running||ne.running||(Ce.startsWith("pi remove ")?r({type:"extensions_reload"}):Ce.startsWith("pi-web-ui install ")||Ce.startsWith("pi-web-ui uninstall ")?r({type:"plugins_reload"}):Ce.startsWith("npm i -g ")&&(r({type:"extensions_reload"}),r({type:"plugins_reload"}),r({type:"check_updates_all",force:!0})))}},[n.terminals,r]),o.useEffect(()=>{const T=n.state?.isStreaming??!1,ne=Lt.current;Lt.current=T,ne!==null&&(!ne&&T?Hs("start",Z):ne&&!T&&(Hs("done",Z),$n(e("notifyDoneTitle"),e("notifyDoneBody"))))},[n.state?.isStreaming,Z]),o.useEffect(()=>{const T=n.dialog?.id??null;T!==null&&T!==jt.current&&(Hs("question",Z),$n(e("notifyQuestionTitle"),e("notifyQuestionBody"))),jt.current=T},[n.dialog,Z]),o.useEffect(()=>{const T=n.question?.id??null;T!==null&&T!==us.current&&(Hs("question",Z),$n(e("notifyQuestionTitle"),e("notifyQuestionBody"))),us.current=T},[n.question,Z]),o.useEffect(()=>{const T=[...n.notices].reverse().find(ne=>ne.level==="error");T&&T.id!==Qt.current&&(Qt.current=T.id,Hs("error",Z),$n(e("notifyErrorTitle"),e("notifyErrorBody")))},[n.notices,Z]);const te=(T,ne,Ce,tt=!1,pt)=>{const Bt=`${T}|${Ce}|${pt?`${pt.start}-${pt.end}`:""}`;h(Ft=>Ft.some(Wt=>`${Wt.path}|${Wt.mode}|${Wt.lines?`${Wt.lines.start}-${Wt.lines.end}`:""}`===Bt)?Ft:[...Ft,{path:T,name:ne,mode:Ce,isDir:tt,...pt?{lines:pt}:{}}])},Be=T=>h(ne=>ne.filter(Ce=>Ce.key?Ce.key!==T:Ce.path!==T)),ht=o.useCallback(T=>(!T.type.startsWith("list_")&&!T.type.startsWith("get_")&&pe(null),r(T)),[r]),nt=o.useRef(0),yt=o.useRef(0),Xt=T=>{const ne=Date.now();n.state?.model&&!n.state.model.vision&&ne-yt.current>1e4&&(yt.current=ne,c("warning",e("imageNotSupported")));const Ce=`paste-${++nt.current}`;h(tt=>[...tt,{path:"",key:Ce,name:T.name,mode:"inline",imageData:T.data,mimeType:T.mimeType}])},k=async T=>{for(const ne of T){const Ce=await ri(ne);if(!Ce){c("error",e("imageLoadFailed",{name:ne.name}));continue}Xt(Ce)}},ae=20*1024*1024,Se=o.useRef(0),Me=async T=>{if(T.size>ae){c("warning",e("fileTooLarge",{name:T.name,size:ae/1024/1024}));return}let ne;try{ne=(await new Promise((pt,Bt)=>{const Ft=new FileReader;Ft.onload=()=>pt(Ft.result),Ft.onerror=()=>Bt(Ft.error??new Error("read failed")),Ft.readAsDataURL(T)})).replace(/^data:[^;]*;base64,/,"")}catch{c("error",e("fileLoadFailed",{name:T.name}));return}const Ce=`upload-${++Se.current}`;h(tt=>[...tt,{path:"",key:Ce,name:T.name,mode:"inline",fileData:ne,size:T.size,mimeType:T.type||void 0}])},We=async T=>{for(const ne of T)fs(ne.type)?await k([ne]):await Me(ne)},De=o.useCallback((T,ne,Ce)=>{r({type:"edit_message",messageId:T,text:ne,attachments:Ce})},[r]),at=o.useCallback((T,ne)=>{r({type:"queue_remove",kind:T,text:ne})},[r]),[xt,Jt]=o.useState([]),Nt=o.useRef(0),lt=o.useCallback((T,ne)=>{r({type:"queue_remove",kind:T,text:ne}),Nt.current+=1;const Ce={text:ne,seq:Nt.current};Jt(tt=>[...tt.slice(-9),Ce])},[r]),It=o.useCallback(()=>X(!0),[]),ze=o.useCallback(()=>h([]),[]),Ns=o.useCallback(Be,[]),ds=o.useCallback(k,[k]),as=o.useCallback(We,[We]),Ba=o.useCallback((T,ne)=>r({type:"search_files",reqId:T,query:ne}),[r]),On=o.useCallback(T=>te(T.path,T.name,T.mode??"reference",T.isDir??!1,T.lines),[]),gs=n.state?.model,Mn=n.state?.thinkingLevel,Bn=n.state?.availableThinkingLevels,Fa=o.useMemo(()=>gs?{model:gs,thinkingLevel:Mn??"off",availableThinkingLevels:Bn??[]}:null,[gs,Mn,Bn]),Zt=o.useCallback(()=>!n.ready||n.terminals.length!==0?!1:(l.create({id:qt(),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 o.useEffect(()=>{if(Ut.current){if(Y!=="terminal"||n.terminals.length!==0){Ut.current=!1;return}Zt()&&(Ut.current=!1)}},[n.terminals.length,Zt,Y]),s.jsxs("div",{className:"app","data-pi-anchor":"app",onDragOver:T=>{Array.from(T.dataTransfer?.types??[]).includes("Files")&&(T.preventDefault(),g(!0))},onDragLeave:T=>{T.currentTarget.contains(T.relatedTarget)||g(!1)},onDrop:T=>{if(g(!1),!Array.from(T.dataTransfer?.types??[]).includes("Files"))return;T.preventDefault();const ne=Array.from(T.dataTransfer?.files??[]);if(ne.length===0){c("warning",e("foldersNotSupported"));return}const Ce=ne.filter(pt=>fs(pt.type)),tt=ne.filter(pt=>!fs(pt.type));Ce.length>0&&k(Ce),tt.length>0&&We(tt)},children:[N&&s.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:s.jsxs("span",{children:["📎 ",e("dropHereToAttach")]})}),s.jsx(Gp,{chat:n,terminal:l,view:Y,plugins:q,uiPrimary:Te,uiOverflow:xe,uiContextTopbar:C["contextmenu.topbar"],onUiAction:se,onViewChange:T=>{Ut.current=T==="terminal"&&n.terminals.length===0,Ut.current&&Zt()&&(Ut.current=!1),M(T),pe(null)},onOpenPanel:pe,onOpenSettings:()=>L(!0),onOpenBgTasks:()=>Ye(!0),onOpenGlobalSearch:()=>mt(!0),sound:Z,onSoundChange:Re,onSoundPreview:T=>Hs(T,Z),themes:je,theme:Je,onThemeChange:qe,reloadThemes:At}),n.protocolMismatch&&s.jsxs("div",{className:"protocol-banner",children:["⚠ ",e("protocolMismatch")]}),s.jsxs("div",{className:"notices",children:[n.notices.map(T=>s.jsx(qx,{notice:T,onDismiss:a},T.id)),Ge&&s.jsxs("div",{className:"notice notice-info",role:"status",children:[s.jsx("span",{className:"notice-text",children:Ge.text}),Ge.actions.map(T=>s.jsx("button",{type:"button",className:"btn",onClick:()=>{const ne=$e.current;$e.current=null,D(null);try{ne?.resolve(T.id)}catch{}},children:T.label},T.id)),s.jsx("button",{type:"button",className:"notice-close",title:e("close"),onClick:()=>{const T=$e.current;$e.current=null,D(null);try{T?.resolve(null)}catch{}},children:s.jsx(bt,{})})]}),w.length>0&&s.jsx("div",{className:"notice-actions",role:"toolbar",children:w.map(T=>s.jsxs("button",{type:"button",className:"btn btn-slot",title:T.hint??T.label,onClick:()=>se(T),children:[T.icon?`${T.icon} `:"",T.badge??T.label]},T.id))})]}),s.jsx($b,{currentModelId:gs?`${gs.provider}/${gs.id}`:null,children:s.jsxs("div",{className:"layout",style:{"--left-w":`${ie}px`,"--right-w":`${he}px`},children:[ce&&s.jsx("div",{className:"drawer-backdrop",onClick:()=>pe(null)}),s.jsxs("div",{className:`view-pane ${Y==="chat"?"":"hidden"}`,children:[!Fe&&Ee&&s.jsx(ul,{side:"left",onClick:Ke}),s.jsx("div",{className:`panel-drawer drawer-left ${ce==="left"?"open":""}${Fe?"":Ee?" hidden":""}`,children:s.jsx(em,{collapsible:!Fe,onToggleCollapse:Ke,panelSend:ht,active:!Fe||ce==="left",sessionFile:n.state?.sessionFile??null,conversations:n.conversations,elsewhere:n.elsewhere,sessions:n.sessions,projects:n.projects,activeConversationId:n.activeConversationId,uiContextSession:C["contextmenu.session"],uiLeftSessions:G,onUiAction:se,presetNames:F})}),!Fe&&s.jsx(cl,{side:"left",width:ie,onResize:re}),s.jsxs("main",{className:Le?"main wide-chat":"main",children:[n.state?s.jsx(Vb,{uiMessageActions:C["message.actions"],uiContextMessage:C["contextmenu.message"],onUiAction:se,state:n.state,liveOutputs:n.liveOutputs,toolStatuses:n.toolStatuses,onEdit:De,onKillBash:()=>r({type:"abort_bash"}),onRetry:()=>{if(r({type:"retry_last"})){const T=n.state?.model;T&&wa(`${T.provider}/${T.id}`)}},onRemoveQueued:at,onRecallQueued:lt,thinkingWrap:n.settings?.thinkingWrap??!0,toolsWrap:n.settings?.toolsWrap??!0,jumpTarget:Mt,onJumpDone:()=>$(null)},n.state.conversationId??"boot"):s.jsx("div",{className:"boot-wait",children:n.ready?e("loadingSession"):e("connectingServer")}),n.settings?.goalModeEnabled!==!1&&s.jsx(M1,{goal:n.goal,models:n.models,modelsLoading:n.modelsLoading,activeConversationId:n.activeConversationId,uiGoalbarActions:O,onUiAction:se}),s.jsx(tx,{onAction:T=>se(T)}),n.dialog&&s.jsx(K1,{dialog:n.dialog}),fe&&s.jsxs("div",{className:"dialog-inline","data-dialog-kind":fe.kind,children:[s.jsxs("div",{className:"dialog-head",children:[s.jsx("span",{className:"dialog-badge",children:e("pluginRequest")}),fe.title&&s.jsx("span",{className:"dialog-title",children:fe.title}),s.jsx("button",{type:"button",className:"dialog-dismiss",title:e("cancel"),onClick:()=>{const T=ge.current;ge.current=null,de(null);try{T?.kind==="confirm"?T.resolve(!1):T?.resolve({ok:!1})}catch{}},children:"✕"})]}),fe.kind==="select"&&s.jsxs("div",{className:"dialog-options",children:[(fe.options??[]).map((T,ne)=>{const Ce=fe.multi?Qe.includes(ne):!1;return s.jsxs("button",{type:"button",className:`dialog-option ${Ce?"sel":""}`,title:T.description,onClick:()=>{if(fe.multi){ye(pt=>pt.includes(ne)?pt.filter(Bt=>Bt!==ne):[...pt,ne]);return}const tt=ge.current;ge.current=null,de(null);try{tt?.resolve({ok:!0,selected:[T.label]})}catch{}},children:[T.label,T.description&&s.jsx("span",{className:"dialog-hint",children:T.description})]},ne)}),(fe.options??[]).length===0&&s.jsx("div",{className:"dialog-hint",children:e("noOptions")}),fe.multi&&s.jsx("div",{className:"dialog-actions",children:s.jsx("button",{type:"button",className:"btn primary",onClick:()=>{const T=ge.current,ne=(T?.options??[]).filter((Ce,tt)=>Qe.includes(tt)).map(Ce=>Ce.label);ge.current=null,de(null);try{T?.resolve({ok:!0,selected:ne})}catch{}},children:e("ok")})})]}),fe.kind==="confirm"&&s.jsx("div",{className:"dialog-body",children:s.jsxs("div",{className:"dialog-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>{const T=ge.current;ge.current=null,de(null);try{T?.resolve(!1)}catch{}},children:e("cancel")}),s.jsx("button",{type:"button",className:"btn primary",onClick:()=>{const T=ge.current;ge.current=null,de(null);try{T?.resolve(!0)}catch{}},children:e("ok")})]})}),fe.kind==="input"&&s.jsxs("div",{className:"dialog-body",children:[s.jsx("input",{className:"dialog-input",value:Oe,placeholder:fe.placeholder||e("inputPlaceholder"),autoFocus:!0,onChange:T=>rt(T.target.value),onKeyDown:T=>{if(T.key==="Enter"&&!T.nativeEvent.isComposing){const ne=ge.current;ge.current=null,de(null);try{ne?.resolve({ok:!0,value:Oe})}catch{}}}}),s.jsxs("div",{className:"dialog-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>{const T=ge.current;ge.current=null,de(null);try{T?.resolve({ok:!1})}catch{}},children:e("cancel")}),s.jsx("button",{type:"button",className:"btn primary",onClick:()=>{const T=ge.current;ge.current=null,de(null);try{T?.resolve({ok:!0,value:Oe})}catch{}},children:e("ok")})]})]})]}),Pe&&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:()=>U(Pe.id,!1),children:"✕"})]}),s.jsxs("div",{className:"dialog-body",children:[e("pluginGrantRequestBody").replace("{plugin}",Pe.pluginId).replace("{path}",Pe.path),Pe.reason&&s.jsx("div",{className:"dialog-hint",children:Pe.reason}),s.jsxs("div",{className:"dialog-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>U(Pe.id,!1),children:e("pluginGrantDeny")}),s.jsx("button",{type:"button",className:"btn primary",onClick:()=>U(Pe.id,!0),children:e("pluginGrantAllow")})]})]})]}),W&&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:()=>{W.resolve(!1),oe(null)},children:"✕"})]}),s.jsxs("div",{className:"dialog-body",children:[e("pluginSessionGrantBody").replace("{path}",W.path),s.jsxs("div",{className:"dialog-actions",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>{W.resolve(!1),oe(null)},children:e("cancel")}),s.jsx("button",{type:"button",className:"btn primary",onClick:()=>{W.resolve(!0),oe(null)},children:e("ok")})]})]})]}),n.question&&s.jsx(z1,{question:n.question}),s.jsx(R1,{composerActions:C["composer.actions"],onUiAction:se,streaming:n.state?.isStreaming??!1,messages:n.state?.messages??Wx,slashCommands:n.slashCommands,modelState:Fa,models:n.models,modelsLoading:n.modelsLoading,providerKeys:n.providerKeys,attachments:f,onRemoveAttachment:Ns,onAddImageFiles:ds,onAddLocalFiles:as,onAddPathAttachment:On,fileSearch:n.fileSearch,onSearchFiles:Ba,onNotice:c,onManageModels:It,onSent:ze,quickPhrases:n.settings?.quickPhrases??[],quickPhrasesEnabled:n.settings?.quickPhrasesEnabled??!0,recallDrafts:xt,dshPermCurrent:n.engine==="dsh"?n.state?.permission??null:void 0,dshPermOptions:n.engine==="dsh"?n.dshPermission?.options??void 0:void 0,dshPermDefault:n.engine==="dsh"?n.dshPermission?.defaultPreset:void 0,dshPreset:n.engine==="dsh"?n.state?.agentPreset??null:void 0,dshPresets:n.engine==="dsh"?n.dshPresets?.presets??void 0:void 0,dshPresetDefault:n.engine==="dsh"?n.dshPresets?.defaultPreset:void 0,dshBlank:(n.state?.messages?.length??0)===0,conversationId:n.activeConversationId||n.state?.conversationId||"",sessionDraft:n.engine==="pi"?n.state?.draft??null:null,sessionId:n.state?.sessionId??""})]}),!Fe&&s.jsx(cl,{side:"right",width:he,onResize:le}),s.jsx("div",{className:`panel-drawer drawer-right ${ce==="right"?"open":""}${Fe?"":Ue?" hidden":""}`,children:s.jsx(nh,{collapsible:!Fe,onToggleCollapse:Ie,panelSend:ht,files:n.files,fileChanged:n.fileChanged,widgets:n.widgets,onAttach:(T,ne,Ce,tt)=>{pe(null),te(T,ne,Ce,tt)},onPreview:(T,ne)=>{pe(null),E({path:T,name:ne})},onNotice:(T,ne)=>c(T,ne),uiRightPanelTabs:C["rightpanel.tabs"],uiContextFile:C["contextmenu.file"],plugins:q,pluginsEpoch:n.pluginsEpoch,send:r})}),!Fe&&Ue&&s.jsx(ul,{side:"right",onClick:Ie})]}),s.jsx("div",{className:`view-pane ${Y==="terminal"?"":"hidden"}`,children:s.jsx(o.Suspense,{fallback:null,children:s.jsx($x,{chat:n,terminal:l,uiTerminalToolbar:ee,onUiAction:se})})}),s.jsx("div",{className:`view-pane ${Y==="git"?"":"hidden"}`,children:s.jsx(Z1,{chat:n,terminal:l,active:Y==="git",onSwitchToTerminal:()=>M("terminal"),uiScmToolbar:Q,onUiAction:se})}),z.map(T=>{const ne=`plugin:${T.info.id}`;return s.jsx("div",{className:`view-pane ${Y===ne?"":"hidden"}`,children:s.jsx(ex,{entry:T})},T.info.id)})]})}),s.jsx(q1,{chat:n,bottombarItems:C.bottombar,onUiAction:se}),b&&s.jsx(Rx,{file:b,content:n.fileContent,onAddLines:(T,ne,Ce,tt)=>te(T,ne,"lines",!1,{start:Ce,end:tt}),onAttach:(T,ne,Ce)=>te(T,ne,Ce),onClose:()=>E(null)}),n.ready&&n.state&&n.state.piConfigured===!1&&!et&&!Ve&&s.jsx(sx,{piConfigured:n.state.piConfigured,piAgentInstalled:n.state.piAgentInstalled,providers:n.providers,providerOAuthFlows:n.providerOAuthFlows,providerOAuthResults:n.providerOAuthResults,installResult:n.installResult,onClose:()=>dt(!0)}),Ve&&s.jsx(rx,{providers:n.modelsConfig,providerStatus:n.providers,providerKeys:n.providerKeys,providerOAuthFlows:n.providerOAuthFlows,providerOAuthResults:n.providerOAuthResults,fetchModelsResult:n.fetchModelsResult,cloneProviderResult:n.cloneProviderResult,onClose:()=>X(!1)}),we&&s.jsx(Sx,{chat:n,terminal:l,onSwitchToTerminal:()=>M("terminal"),onClose:()=>L(!1)}),ot&&s.jsx(Ax,{servers:n.bgServers,onClose:()=>Ye(!1)}),s.jsx(Ix,{open:ct,projects:n.projects,fileSearch:n.fileSearch,sessionSearch:n.sessionSearch,onClose:()=>mt(!1),onSwitchSession:(T,ne)=>{r({type:"switch_session",path:T});const Ce=ne&&ne[0];$(Ce?{path:T,role:Ce.role,timestamp:Ce.timestamp}:null)},onSwitchProject:T=>{r({type:"set_cwd",path:T})},onPreviewFile:(T,ne)=>{E({path:T,name:ne})}})]})}function Yx(){typeof document>"u"||(Wu(zx()),Qx())}function Wu(e){!Number.isFinite(e)||e<0||document.documentElement.style.setProperty("--msgs-gutter",`${Math.round(e*100)/100}px`)}function zx(){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 Vx(e){const t=document.createElement("div");t.style.cssText="width:0;height:0;pointer-events:none;",e.appendChild(t);const n=getComputedStyle(e),r=e.getBoundingClientRect(),a=t.getBoundingClientRect(),c=Number.parseFloat(n.borderLeftWidth)||0,l=Number.parseFloat(n.paddingLeft)||0,u=a.left-(r.left+c+l);return t.remove(),u}function Qx(){const e=()=>{const r=document.querySelector(".messages");return r?(Wu(Vx(r)),!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)}Zd();Vc(zc());Yx();gd.createRoot(document.getElementById("root")).render(s.jsx(o.StrictMode,{children:s.jsx(up,{children:s.jsx(Gx,{})})}));"serviceWorker"in navigator&&window.addEventListener("load",()=>{const e=_l();navigator.serviceWorker.register(`${e}sw.js`,{scope:e}).catch(t=>{console.warn("Service worker registration failed:",t)})});
|