@chainingintention/pi-web-cn 1.202606.23 → 1.202606.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,27 +1,27 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-B1z_k75G.js","assets/vendor-editor-core-Bc1A7SO7.js","assets/vendor-editor-languages-D0CnB2js.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-CqG27wd5.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
- import{Q as Ao,w as rt,J as Ji,R as el,S as tl,G as il,U as sl,V as ol,A as rl,W as nl,X as al,Y as ll,Z as Mo,x as Eo,_ as cl}from"./vendor-editor-core-Bc1A7SO7.js";import{m as dl,i as pl,d as hl}from"./vendor-editor-languages-D0CnB2js.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const n of r.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(o){if(o.ep)return;o.ep=!0;const r=i(o);fetch(o.href,r)}})();const oi=globalThis,Hs=oi.ShadowRoot&&(oi.ShadyCSS===void 0||oi.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,qs=Symbol(),Do=new WeakMap;let mn=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==qs)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=i}get styleSheet(){let t=this.o;const i=this.t;if(Hs&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=Do.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&Do.set(i,t))}return t}toString(){return this.cssText}};const ul=e=>new mn(typeof e=="string"?e:e+"",void 0,qs),D=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,o,r)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+e[r+1],e[0]);return new mn(i,e,qs)},fl=(e,t)=>{if(Hs)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),o=oi.litNonce;o!==void 0&&s.setAttribute("nonce",o),s.textContent=i.cssText,e.appendChild(s)}},Wo=Hs?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return ul(i)})(e):e;const{is:gl,defineProperty:ml,getOwnPropertyDescriptor:vl,getOwnPropertyNames:bl,getOwnPropertySymbols:wl,getPrototypeOf:yl}=Object,Di=globalThis,Oo=Di.trustedTypes,Sl=Oo?Oo.emptyScript:"",xl=Di.reactiveElementPolyfillSupport,At=(e,t)=>e,pi={toAttribute(e,t){switch(t){case Boolean:e=e?Sl:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=e!==null;break;case Number:i=e===null?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch{i=null}}return i}},Ks=(e,t)=>!gl(e,t),_o={attribute:!0,type:String,converter:pi,reflect:!1,useDefault:!1,hasChanged:Ks};Symbol.metadata??=Symbol("metadata"),Di.litPropertyMetadata??=new WeakMap;let ct=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=_o){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const s=Symbol(),o=this.getPropertyDescriptor(t,s,i);o!==void 0&&ml(this.prototype,t,o)}}static getPropertyDescriptor(t,i,s){const{get:o,set:r}=vl(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:o,set(n){const a=o?.call(this);r?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??_o}static _$Ei(){if(this.hasOwnProperty(At("elementProperties")))return;const t=yl(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(At("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(At("properties"))){const i=this.properties,s=[...bl(i),...wl(i)];for(const o of s)this.createProperty(o,i[o])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,o]of i)this.elementProperties.set(s,o)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const o=this._$Eu(i,s);o!==void 0&&this._$Eh.set(o,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const i=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const o of s)i.unshift(Wo(o))}else t!==void 0&&i.push(Wo(t));return i}static _$Eu(t,i){const s=i.attribute;return s===!1?void 0:typeof s=="string"?s:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,i=this.constructor.elementProperties;for(const s of i.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return fl(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$ET(t,i){const s=this.constructor.elementProperties.get(t),o=this.constructor._$Eu(t,s);if(o!==void 0&&s.reflect===!0){const r=(s.converter?.toAttribute!==void 0?s.converter:pi).toAttribute(i,s.type);this._$Em=t,r==null?this.removeAttribute(o):this.setAttribute(o,r),this._$Em=null}}_$AK(t,i){const s=this.constructor,o=s._$Eh.get(t);if(o!==void 0&&this._$Em!==o){const r=s.getPropertyOptions(o),n=typeof r.converter=="function"?{fromAttribute:r.converter}:r.converter?.fromAttribute!==void 0?r.converter:pi;this._$Em=o;const a=n.fromAttribute(i,r.type);this[o]=a??this._$Ej?.get(o)??a,this._$Em=null}}requestUpdate(t,i,s,o=!1,r){if(t!==void 0){const n=this.constructor;if(o===!1&&(r=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??Ks)(r,i)||s.useDefault&&s.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:o,wrapped:r},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),r!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),o===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[o,r]of this._$Ep)this[o]=r;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,r]of s){const{wrapped:n}=r,a=this[o];n!==!0||this._$AL.has(o)||a===void 0||this.C(o,void 0,r,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};ct.elementStyles=[],ct.shadowRootOptions={mode:"open"},ct[At("elementProperties")]=new Map,ct[At("finalized")]=new Map,xl?.({ReactiveElement:ct}),(Di.reactiveElementVersions??=[]).push("2.1.2");const Vs=globalThis,Lo=e=>e,hi=Vs.trustedTypes,jo=hi?hi.createPolicy("lit-html",{createHTML:e=>e}):void 0,vn="$lit$",Be=`lit$${Math.random().toFixed(9).slice(2)}$`,bn="?"+Be,kl=`<${bn}>`,Ze=document,Dt=()=>Ze.createComment(""),Wt=e=>e===null||typeof e!="object"&&typeof e!="function",Gs=Array.isArray,$l=e=>Gs(e)||typeof e?.[Symbol.iterator]=="function",Qi=`[
3
- \f\r]`,wt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Fo=/-->/g,No=/>/g,qe=RegExp(`>|${Qi}(?:([^\\s"'>=/]+)(${Qi}*=${Qi}*(?:[^
4
- \f\r"'\`<>=]|("|')|))|$)`,"g"),zo=/'/g,Bo=/"/g,wn=/^(?:script|style|textarea|title)$/i,yn=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=yn(1),he=yn(2),Ue=Symbol.for("lit-noChange"),F=Symbol.for("lit-nothing"),Uo=new WeakMap,Je=Ze.createTreeWalker(Ze,129);function Sn(e,t){if(!Gs(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return jo!==void 0?jo.createHTML(t):t}const Pl=(e,t)=>{const i=e.length-1,s=[];let o,r=t===2?"<svg>":t===3?"<math>":"",n=wt;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,g=0;for(;g<c.length&&(n.lastIndex=g,u=n.exec(c),u!==null);)g=n.lastIndex,n===wt?u[1]==="!--"?n=Fo:u[1]!==void 0?n=No:u[2]!==void 0?(wn.test(u[2])&&(o=RegExp("</"+u[2],"g")),n=qe):u[3]!==void 0&&(n=qe):n===qe?u[0]===">"?(n=o??wt,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?qe:u[3]==='"'?Bo:zo):n===Bo||n===zo?n=qe:n===Fo||n===No?n=wt:(n=qe,o=void 0);const w=n===qe&&e[a+1].startsWith("/>")?" ":"";r+=n===wt?c+kl:h>=0?(s.push(p),c.slice(0,h)+vn+c.slice(h)+Be+w):c+Be+(h===-2?a:w)}return[Sn(e,r+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Ot{constructor({strings:t,_$litType$:i},s){let o;this.parts=[];let r=0,n=0;const a=t.length-1,c=this.parts,[p,u]=Pl(t,i);if(this.el=Ot.createElement(p,s),Je.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(o=Je.nextNode())!==null&&c.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const h of o.getAttributeNames())if(h.endsWith(vn)){const g=u[n++],w=o.getAttribute(h).split(Be),P=/([.?@])?(.*)/.exec(g);c.push({type:1,index:r,name:P[2],strings:w,ctor:P[1]==="."?Il:P[1]==="?"?Cl:P[1]==="@"?Tl:Wi}),o.removeAttribute(h)}else h.startsWith(Be)&&(c.push({type:6,index:r}),o.removeAttribute(h));if(wn.test(o.tagName)){const h=o.textContent.split(Be),g=h.length-1;if(g>0){o.textContent=hi?hi.emptyScript:"";for(let w=0;w<g;w++)o.append(h[w],Dt()),Je.nextNode(),c.push({type:2,index:++r});o.append(h[g],Dt())}}}else if(o.nodeType===8)if(o.data===bn)c.push({type:2,index:r});else{let h=-1;for(;(h=o.data.indexOf(Be,h+1))!==-1;)c.push({type:7,index:r}),h+=Be.length-1}r++}}static createElement(t,i){const s=Ze.createElement("template");return s.innerHTML=t,s}}function pt(e,t,i=e,s){if(t===Ue)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const r=Wt(t)?void 0:t._$litDirective$;return o?.constructor!==r&&(o?._$AO?.(!1),r===void 0?o=void 0:(o=new r(e),o._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=o:i._$Cl=o),o!==void 0&&(t=pt(e,o._$AS(e,t.values),o,s)),t}class Rl{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,o=(t?.creationScope??Ze).importNode(i,!0);Je.currentNode=o;let r=Je.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new ft(r,r.nextSibling,this,t):c.type===1?p=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(p=new Al(r,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(r=Je.nextNode(),n++)}return Je.currentNode=Ze,o}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class ft{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=F,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=o,this._$Cv=o?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=pt(this,t,i),Wt(t)?t===F||t==null||t===""?(this._$AH!==F&&this._$AR(),this._$AH=F):t!==this._$AH&&t!==Ue&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):$l(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==F&&Wt(this._$AH)?this._$AA.nextSibling.data=t:this.T(Ze.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,o=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Ot.createElement(Sn(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const r=new Rl(o,this),n=r.u(this.options);r.p(i),this.T(n),this._$AH=r}}_$AC(t){let i=Uo.get(t.strings);return i===void 0&&Uo.set(t.strings,i=new Ot(t)),i}k(t){Gs(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,o=0;for(const r of t)o===i.length?i.push(s=new ft(this.O(Dt()),this.O(Dt()),this,this.options)):s=i[o],s._$AI(r),o++;o<i.length&&(this._$AR(s&&s._$AB.nextSibling,o),i.length=o)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=Lo(t).nextSibling;Lo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Wi=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,r){this.type=1,this._$AH=F,this._$AN=void 0,this.element=t,this.name=i,this._$AM=o,this.options=r,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=F}_$AI(t,i=this,s,o){const r=this.strings;let n=!1;if(r===void 0)t=pt(this,t,i,0),n=!Wt(t)||t!==this._$AH&&t!==Ue,n&&(this._$AH=t);else{const a=t;let c,p;for(t=r[0],c=0;c<r.length-1;c++)p=pt(this,a[s+c],i,c),p===Ue&&(p=this._$AH[c]),n||=!Wt(p)||p!==this._$AH[c],p===F?t=F:t!==F&&(t+=(p??"")+r[c+1]),this._$AH[c]=p}n&&!o&&this.j(t)}j(t){t===F?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Il=class extends Wi{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===F?void 0:t}},Cl=class extends Wi{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==F)}},Tl=class extends Wi{constructor(t,i,s,o,r){super(t,i,s,o,r),this.type=5}_$AI(t,i=this){if((t=pt(this,t,i,0)??F)===Ue)return;const s=this._$AH,o=t===F&&s!==F||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==F&&(s===F||o);o&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Al=class{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){pt(this,t)}};const Ml={I:ft},El=Vs.litHtmlPolyfillSupport;El?.(Ot,ft),(Vs.litHtmlVersions??=[]).push("3.3.3");const Dl=(e,t,i)=>{const s=i?.renderBefore??t;let o=s._$litPart$;if(o===void 0){const r=i?.renderBefore??null;s._$litPart$=o=new ft(t.insertBefore(Dt(),r),r,void 0,i??{})}return o._$AI(e),o};const Js=globalThis;let C=class extends ct{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=Dl(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ue}};C._$litElement$=!0,C.finalized=!0,Js.litElementHydrateSupport?.({LitElement:C});const Wl=Js.litElementPolyfillSupport;Wl?.({LitElement:C});(Js.litElementVersions??=[]).push("4.2.2");const W=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const Ol={attribute:!0,type:String,converter:pi,reflect:!1,hasChanged:Ks},_l=(e=Ol,t,i)=>{const{kind:s,metadata:o}=i;let r=globalThis.litPropertyMetadata.get(o);if(r===void 0&&globalThis.litPropertyMetadata.set(o,r=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,c,e,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,e,a),a}}}if(s==="setter"){const{name:n}=i;return function(a){const c=this[n];t.call(this,a),this.requestUpdate(n,c,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?_l(e,t,i):((s,o,r)=>{const n=o.hasOwnProperty(r);return o.constructor.createProperty(r,s),n?Object.getOwnPropertyDescriptor(o,r):void 0})(e,t,i)}function k(e){return d({...e,state:!0,attribute:!1})}const Ll=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function B(e,t){return(i,s,o)=>{const r=n=>n.renderRoot?.querySelector(e)??null;return Ll(i,s,{get(){return r(this)}})}}function xn(e,t=Fl()){if(t===void 0)return e;const i=jl(t);if(i===void 0)return e;const s=new URL(e,t.origin);return s.searchParams.set("embed",i.embed),s.searchParams.set("token",i.token),`${s.pathname}${s.search}${s.hash}`}function jl(e){const t=e.searchParams.get("embed"),i=e.searchParams.get("token")?.trim();if(!(t!=="management"||i===void 0||i===""))return{embed:t,token:i}}function Fl(){if(typeof globalThis.location>"u")return;const e=globalThis.location;if(typeof e.href=="string"&&e.href!=="")return new URL(e.href);const t=typeof e.protocol=="string"&&e.protocol!==""?e.protocol:"http:",i=typeof e.host=="string"&&e.host!==""?e.host:"localhost",s=typeof e.search=="string"?e.search:"";return new URL(`${t}//${i}/${s}`)}async function v(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const o=await fetch(xn(e),{...i,headers:s});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(Nl(n)??o.statusText)}const r=await o.json();return t(r)}function Nl(e){if(zl(e))return typeof e.error=="string"?e.error:void 0}function zl(e){return typeof e=="object"&&e!==null}const ht={sessionsDeleteArchived:"sessions.deleteArchived",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments"},Bl=Object.values(ht),Ul=new Set(Bl);function Hl(e){return typeof e=="string"&&Ul.has(e)}function _t(e,t){return e?.capabilities?.includes(t)===!0}function Mt(e){return typeof e=="object"&&e!==null}function b(e){if(!Mt(e))throw new Error("Expected object response");return e}function m(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function $(e,t){const i=e[t];if(i!==void 0){if(typeof i!="string")throw new Error(`Expected optional string field: ${t}`);return i}}function ee(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function E(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function N(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function ql(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function Kl(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function Vl(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=b(e);return{messages:ql(t.messages),start:ee(t,"start"),total:ee(t,"total")}}function Gl(e){const t=b(e);return N(kn)(t.machines)}function kn(e){const t=b(e),i=Zl(t,"kind"),s=$(t,"baseUrl"),o=$n(t,"status"),r=$(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...o===void 0?{}:{status:o},...r===void 0?{}:{statusMessage:r}}}function Jl(e){const t=b(e),i=$n(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:ui(t.web)},...t.sessiond===void 0?{}:{sessiond:ui(t.sessiond)},...s===void 0?{}:{error:s}}}function Ql(e){const t=b(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...y("packageName",$(t,"packageName")),...y("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:In(t.components)},...t.capabilities===void 0?{}:{capabilities:Qs(t.capabilities)},...i===void 0?{}:{error:i}}}function Zl(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function $n(e,t){const i=$(e,t);if(i!==void 0){if(i!=="unknown"&&i!=="online"&&i!=="offline"&&i!=="error")throw new Error(`Expected machine status field: ${t}`);return i}}function Ho(e){const t=b(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function Xl(e){const t=b(e),i=$(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:E(t,"isMain"),isGitRepo:E(t,"isGitRepo"),isGitWorktree:E(t,"isGitWorktree")}}function ks(e){const t=b(e);return{path:m(t,"path"),size:ee(t,"size"),modifiedAt:m(t,"modifiedAt")}}function Zi(e){const t=b(e);return{path:m(t,"path")}}function qo(e){const t=b(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function $s(e){const t=b(e),i=$(t,"name"),s=$(t,"parentSessionPath"),o=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:ee(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function yt(e){const t=b(e);return{sessionId:m(t,"sessionId"),isStreaming:E(t,"isStreaming"),isCompacting:E(t,"isCompacting"),isBashRunning:E(t,"isBashRunning"),pendingMessageCount:ee(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:N(Yl)(t.queuedMessages),...y("messageCount",Pe(t,"messageCount")),tokens:ec(t.tokens),cost:ee(t,"cost"),...sc(t.model),...mc(t.contextUsage),...y("thinkingLevel",$(t,"thinkingLevel"))}}function Yl(e){const t=b(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text"),...y("imageCount",Pe(t,"imageCount"))}}function ec(e){const t=b(e);return{input:ee(t,"input"),output:ee(t,"output"),cacheRead:ee(t,"cacheRead"),cacheWrite:ee(t,"cacheWrite"),total:ee(t,"total")}}function Pn(e){const t=b(e);return{...y("provider",$(t,"provider")),...y("id",$(t,"id")),...y("name",$(t,"name")),...y("contextWindow",Pe(t,"contextWindow")),...y("reasoning",t.reasoning),...y("input",tc(t.input))}}function tc(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Invalid model input");return e.map(ic)}}function ic(e){if(e==="text"||e==="image")return e;throw new Error("Invalid model input")}function sc(e){return e===void 0?{}:{model:Pn(e)}}function oc(e){const t=b(e);return{models:N(Pn)(t.models)}}function rc(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function nc(e){const t=b(e);return{levels:N(rc)(t.levels)}}function ac(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function lc(e){if(e!=="stored"&&e!=="runtime"&&e!=="environment"&&e!=="fallback"&&e!=="models_json_key"&&e!=="models_json_command")throw new Error("Invalid auth status source");return e}function cc(e){const t=b(e),i=t.source===void 0?void 0:lc(t.source);return{configured:E(t,"configured"),...y("source",i),...y("label",$(t,"label"))}}function dc(e){const t=b(e);return{id:m(t,"id"),name:m(t,"name"),authType:ac(t.authType),status:cc(t.status)}}function pc(e){const t=b(e);return{providers:N(dc)(t.providers)}}function Vt(e){const t=b(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:hc(t.status),progress:N(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...y("error",$(t,"error")),...y("auth",uc(t.auth)),...y("prompt",fc(t.prompt)),...y("select",gc(t.select))}}function hc(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function uc(e){if(e===void 0)return;const t=b(e);return{url:m(t,"url"),...y("instructions",$(t,"instructions"))}}function fc(e){if(e===void 0)return;const t=b(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...y("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function gc(e){if(e===void 0)return;const t=b(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:N(Tn)(t.options)}}function mc(e){if(e===void 0)return{};const t=b(e);return{contextUsage:{tokens:Yo(t,"tokens"),contextWindow:ee(t,"contextWindow"),percent:Yo(t,"percent")}}}function vc(e){const t=b(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...y("description",$(t,"description"))}}function Rn(e){const t=b(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function bc(e){const t=b(e);return{path:m(t,"path"),entries:N(wc)(t.entries),scannedAt:m(t,"scannedAt"),truncated:E(t,"truncated")}}function wc(e){const t=b(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...y("size",Pe(t,"size")),...y("modifiedAt",$(t,"modifiedAt"))}}function yc(e){const t=b(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...y("language",$(t,"language")),...y("mediaType",Sc(t.mediaType)),...y("mimeType",$(t,"mimeType")),encoding:i,size:ee(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:E(t,"truncated"),binary:E(t,"binary")}}function Sc(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function xc(e){const t=b(e);return{isGitRepo:E(t,"isGitRepo"),hash:m(t,"hash"),...y("branch",$(t,"branch")),...y("upstream",$(t,"upstream")),...y("ahead",Pe(t,"ahead")),...y("behind",Pe(t,"behind")),files:N(kc)(t.files)}}function kc(e){const t=b(e);return{path:m(t,"path"),...y("oldPath",$(t,"oldPath")),index:Ko(t.index),workingTree:Ko(t.workingTree)}}function Ko(e){switch(e){case"unmodified":case"modified":case"added":case"deleted":case"renamed":case"copied":case"untracked":case"ignored":case"conflicted":return e;default:throw new Error("Invalid git file state")}}function $c(e){const t=b(e);return{...y("path",$(t,"path")),staged:E(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:E(t,"truncated")}}function Xi(e){const t=b(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:E(t,"exited"),...y("exitCode",Pe(t,"exitCode")),...y("commandRunId",$(t,"commandRunId"))}}function Et(e){const t=b(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:Pc(t.status),...y("exitCode",Pe(t,"exitCode")),createdAt:m(t,"createdAt"),...y("startedAt",$(t,"startedAt")),...y("completedAt",$(t,"completedAt")),metadata:Rc(t.metadata,"metadata")}}function Pc(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function Rc(e,t){const i=b(e);return Object.fromEntries(Object.entries(i).map(([s,o])=>{if(typeof o!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,o]}))}function Ic(e){const t=b(e);return{cwd:m(t,"cwd"),hasSessionActivity:E(t,"hasSessionActivity"),hasTerminalActivity:E(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function Cc(e){const t=b(e);return{workspaces:N(Ic)(t.workspaces),generatedAt:m(t,"generatedAt")}}function Vo(e){const t=b(e);return{path:m(t,"path"),exists:E(t,"exists"),config:Go(t.config),effectiveConfig:Go(t.effectiveConfig),envOverrides:Ec(t.envOverrides)}}function Go(e){const t=b(e);return{...y("host",$(t,"host")),...y("port",Pe(t,"port")),...y("allowedHosts",Tc(t.allowedHosts)),...y("shortcuts",Ac(t.shortcuts)),...y("plugins",Mc(t.plugins)),...y("spawnSessions",Xo(t,"spawnSessions")),...y("subsessions",Xo(t,"subsessions"))}}function Tc(e){if(e!==void 0){if(e===!0)return!0;if(Array.isArray(e)&&e.every(t=>typeof t=="string"))return e;throw new Error("Invalid PI WEB allowedHosts field")}}function Ac(e){if(e!==void 0){if(!Mt(e)||Array.isArray(e))throw new Error("Invalid PI WEB shortcuts field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(i!==null&&(typeof i!="string"||i===""))throw new Error("Invalid PI WEB shortcut field");return[t,i]}))}}function Mc(e){if(e!==void 0){if(!Mt(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!Mt(i)||Array.isArray(i))throw new Error("Invalid PI WEB plugin config field");const s=i.enabled;if(s!==void 0&&typeof s!="boolean")throw new Error("Invalid PI WEB plugin enabled field");const o=i.settings;if(o!==void 0&&(!Mt(o)||Array.isArray(o)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Ec(e){const t=b(e);return{host:E(t,"host"),port:E(t,"port"),allowedHosts:E(t,"allowedHosts"),spawnSessions:E(t,"spawnSessions"),subsessions:E(t,"subsessions")}}function Dc(e){const t=b(e);return{plugins:N(Wc)(t.plugins)}}function Wc(e){const t=b(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:Oc(t.scope),machineSpecific:_c(t.machineSpecific,"machineSpecific")??!1,enabled:E(t,"enabled")}}function Oc(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function _c(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function Lc(e){const t=b(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:Fc(t.components),release:zc(t.release),commands:Bc(t.commands),messages:N(Uc)(t.messages)}}function jc(e){const t=b(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:In(t.components),capabilities:Qs(t.capabilities)}}function Fc(e){const t=b(e);return{web:ui(t.web),sessiond:ui(t.sessiond)}}function In(e){const t=b(e);return{web:Jo(t.web),sessiond:Jo(t.sessiond)}}function Jo(e){const t=b(e);return{component:Cn(t.component),label:m(t,"label"),...y("runtimeVersion",$(t,"runtimeVersion")),available:E(t,"available"),capabilities:Qs(t.capabilities),...y("error",$(t,"error"))}}function ui(e){const t=b(e);return{component:Cn(t.component),label:m(t,"label"),...y("runtimeVersion",$(t,"runtimeVersion")),...y("installedVersion",$(t,"installedVersion")),stale:E(t,"stale"),available:E(t,"available"),...y("installation",Nc(t.installation)),...y("error",$(t,"error"))}}function Nc(e){if(e===void 0)return;const t=b(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");return{kind:i,...y("path",$(t,"path")),...y("source",$(t,"source")),...s===void 0?{}:{scope:s},...y("npmRoot",$(t,"npmRoot"))}}function zc(e){const t=b(e);return{packageName:m(t,"packageName"),...y("latestVersion",$(t,"latestVersion")),updateAvailable:E(t,"updateAvailable"),...y("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...y("error",$(t,"error"))}}function Bc(e){const t=b(e);return{...y("update",$(t,"update")),...y("restart",$(t,"restart")),...y("restartWeb",$(t,"restartWeb")),...y("restartSessiond",$(t,"restartSessiond")),...y("status",$(t,"status"))}}function Uc(e){const t=b(e);return{id:m(t,"id"),severity:Hc(t.severity),title:m(t,"title"),body:m(t,"body"),...y("command",$(t,"command"))}}function Cn(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Qs(e){if(!Array.isArray(e)||!e.every(Hl))throw new Error("Invalid PI WEB capabilities");return e}function Hc(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Qo(e){const t=b(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:N(Tn)(t.options)};if(i==="done")return{type:i,...y("message",$(t,"message")),...qc(t.session),...y("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function Tn(e){const t=b(e);return{value:m(t,"value"),label:m(t,"label"),...y("description",$(t,"description"))}}function qc(e){return e===void 0?{}:{session:$s(e)}}function Gt(e){if(b(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function Kc(e){const t=b(e);return N(Vc)(t.attachments)}function Vc(e){const t=b(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:ee(t,"size")}}function Ps(e){if(b(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function Gc(e){if(b(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function Jc(e){if(b(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Zo(e){const t=b(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:Kl(t.sessionIds,"sessionIds"),s=Pe(t,"archivedCount"),o=Pe(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...o===void 0?{}:{skippedAlreadyArchivedCount:o}}}function Qc(e){if(b(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function Zc(e){if(b(e).deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0}}function Xc(e){if(b(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Yc(e){if(b(e).reloaded!==!0)throw new Error("Expected reloaded response");return{reloaded:!0}}function Xo(e,t){const i=e[t];if(i!==void 0){if(typeof i!="boolean")throw new Error(`Invalid PI WEB ${t} field`);return i}}function Pe(e,t){const i=e[t];if(i!==void 0){if(typeof i!="number")throw new Error(`Expected optional number field: ${t}`);return i}}function Yo(e,t){const i=e[t];if(i===null)return null;if(typeof i!="number")throw new Error(`Expected number|null field: ${t}`);return i}function y(e,t){return t===void 0?{}:{[e]:t}}function ed(e){return typeof e=="string"?e:e.id}function td(e){return typeof e=="string"?void 0:e.cwd}function id(e,t,i,s){const o=new URLSearchParams;s?.path!==void 0&&o.set("path",s.path),s?.staged===!0&&o.set("staged","true");const r=o.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${r?`?${r}`:""}`}function sd(e,t,i="local"){const s=new URLSearchParams,o=td(e);o!==void 0&&o!==""&&s.set("cwd",o),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const r=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(ed(e))}/messages${r===""?"":`?${r}`}`}function od(e,t,i,s){const o=new URLSearchParams;return o.set("path",i),s?.modifiedAt!==void 0&&o.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${o.toString()}`}function An(e,t,i,s){const o=new URLSearchParams;o.set("path",i);const r=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return xn(`${r}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${o.toString()}`)}const R=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function rd(e){return typeof e=="string"?e:e.id}function Mn(e){return typeof e=="string"?void 0:e.cwd}function En(e,t="local"){return`${R(t)}/sessions/${encodeURIComponent(rd(e))}`}function K(e,t,i="local"){return`${En(e,i)}/${t}`}function Jt(e,t,i="local"){return`${K(e,t,i)}${Dn(e)}`}function nd(e,t="local"){return`${En(e,t)}${Dn(e)}`}function Dn(e){const t=Mn(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function V(e,t={}){const i=Mn(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}const Wn={piWebStatus:(e="local")=>v(e==="local"?"/api/pi-web/status":`${R(e)}/pi-web/status`,Lc),piWebRuntime:()=>v("/api/pi-web/runtime",jc)},ad={machines:()=>v("/api/machines",Gl),addMachine:e=>v("/api/machines",kn,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>v(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>v(`/api/machines/${encodeURIComponent(e)}/health`,Jl),runtime:e=>v(`/api/machines/${encodeURIComponent(e)}/runtime`,Ql)},fi={config:()=>v("/api/config",Vo),saveConfig:e=>v("/api/config",Vo,{method:"PUT",body:JSON.stringify({config:e})})},Rs={plugins:()=>v("/api/plugins",Dc)},On={workspaceActivity:(e="local")=>v(`${R(e)}/activity`,Cc)},ld={projects:(e="local")=>v(`${R(e)}/projects`,N(Ho)),addProject:(e,t,i,s="local")=>v(`${R(s)}/projects`,Ho,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>v(`${R(t)}/projects/${encodeURIComponent(e)}`,Ps,{method:"DELETE"}),projectDirectories:(e,t="local")=>v(`${R(t)}/project-directories?q=${encodeURIComponent(e)}`,N(Rn))},Is={workspaces:(e,t="local")=>v(`${R(t)}/projects/${e}/workspaces`,N(Xl)),deleteWorkspace:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Et,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,bc),workspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,yc),uploadWorkspaceFile:async(e,t,i,s,o="local")=>o==="local"?fd(e,t,i,s):v(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,ks,{method:"POST",body:JSON.stringify({path:i,contentBase64:await hd(s)})}),createWorkspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,ks,{method:"POST",body:JSON.stringify({path:i,contentBase64:""})}),moveWorkspaceFile:(e,t,i,s,o="local")=>v(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Zi,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,qo,{method:"DELETE"}),createWorkspaceDirectory:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Zi,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,o="local")=>v(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Zi,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,qo,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>An(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>gd(e,t,i,s)},cd={sessions:(e,t="local")=>v(`${R(t)}/sessions?cwd=${encodeURIComponent(e)}`,N($s)),startSession:(e,t="local")=>v(`${R(t)}/sessions`,$s,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>v(sd(e,t,i),Vl),status:(e,t="local")=>v(Jt(e,"status",t),yt),models:(e,t="local")=>v(Jt(e,"models",t),oc),setModel:(e,t,i,s="local")=>v(K(e,"model",s),yt,{method:"POST",body:V(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>v(K(e,"model/cycle",i),yt,{method:"POST",body:V(e,{direction:t})}),thinkingLevels:(e,t="local")=>v(Jt(e,"thinking-levels",t),nc),setThinkingLevel:(e,t,i="local")=>v(K(e,"thinking-level",i),yt,{method:"POST",body:V(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>v(K(e,"thinking-level/cycle",t),yt,{method:"POST",body:V(e)}),commands:(e,t="local")=>v(Jt(e,"commands",t),N(vc)),prompt:(e,t,i,s="local",o)=>v(K(e,"prompt",s),Gt,{method:"POST",body:V(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...o!==void 0&&o.length>0?{attachments:o}:{}})}),saveAttachments:(e,t,i="local",s)=>v(K(e,"attachments",i),Kc,{method:"POST",body:V(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>v(K(e,"shell",i),Gt,{method:"POST",body:V(e,{text:t})}),runCommand:(e,t,i="local")=>v(K(e,"commands/run",i),Qo,{method:"POST",body:V(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>v(K(e,"commands/respond",s),Qo,{method:"POST",body:V(e,{requestId:t,value:i})}),abort:(e,t="local")=>v(K(e,"abort",t),Gc,{method:"POST",body:V(e)}),stop:(e,t="local")=>v(K(e,"stop",t),Jc,{method:"POST",body:V(e)}),archive:(e,t="local")=>v(K(e,"archive",t),Zo,{method:"POST",body:V(e)}),archiveWithDescendants:(e,t="local")=>v(K(e,"archive-tree",t),Zo,{method:"POST",body:V(e)}),restore:(e,t="local")=>v(K(e,"restore",t),Qc,{method:"POST",body:V(e)}),deleteArchived:(e,t="local")=>v(nd(e,t),Zc,{method:"DELETE"}),detachParent:(e,t="local")=>v(K(e,"detach-parent",t),Xc,{method:"POST",body:V(e)}),reloadSession:(e,t="local")=>v(K(e,"reload",t),Yc,{method:"POST",body:V(e)}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return v(`${R(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,pc)},saveApiKey:(e,t,i="local")=>v(`${R(i)}/auth/api-key`,Gt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>v(`${R(t)}/auth/logout`,Gt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>v(`${R(t)}/auth/oauth`,Vt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>v(`${R(t)}/auth/oauth/${encodeURIComponent(e)}`,Vt),respondOAuthFlow:(e,t,i,s="local")=>v(`${R(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Vt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>v(`${R(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Vt,{method:"POST"})},dt={terminals:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,N(Xi)),startTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Xi,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Ps,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,Ps,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Xi,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Et,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>v(`${R(t)}/terminal-command-runs${pd(e)}`,N(Et)),getCommandRun:(e,t="local")=>dd(e,t),cancelCommandRun:(e,t="local")=>v(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Et,{method:"POST"})};async function dd(e,t){const i=await fetch(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Zs(s)??i.statusText)}return Et(await i.json())}}function pd(e){if(e===void 0)return"";const t=new URLSearchParams;e.projectId!==void 0&&t.set("projectId",e.projectId),e.workspaceId!==void 0&&t.set("workspaceId",e.workspaceId),e.terminalId!==void 0&&t.set("terminalId",e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set("statuses",e.statuses.join(",")),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set("metadata",JSON.stringify(e.metadata));const i=t.toString();return i===""?"":`?${i}`}function Zs(e){if(!md(e))return;const t=e.error;return typeof t=="string"?t:void 0}async function hd(e){return ud(await e.arrayBuffer())}function ud(e){const t=new Uint8Array(e);let i="";for(const s of t)i+=String.fromCharCode(s);return btoa(i)}async function fd(e,t,i,s){const o=new FormData;o.set("path",i),o.set("file",s,s.name);const r=await fetch(`${R("local")}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,{method:"POST",body:o});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(Zs(n)??r.statusText)}return ks(await r.json())}async function gd(e,t,i,s){const o=await fetch(An(e,t,i,{machineId:s}));if(!o.ok){const p=await o.json().catch(()=>({}));throw new Error(Zs(p)??o.statusText)}const r=await o.blob(),n=URL.createObjectURL(r),a=document.createElement("a");a.href=n;const c=i.split("/").pop();a.download=c===void 0||c===""?"download":c,document.body.append(a),a.click(),a.remove(),URL.revokeObjectURL(n)}function md(e){return typeof e=="object"&&e!==null}const vd={files:(e,t,i={})=>{const s=new URLSearchParams({cwd:e,q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),v(`${R(i.machineId)}/files?${s.toString()}`,N(Rn))}},bd={gitStatus:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,xc),gitDiff:(e,t,i,s="local")=>v(id(s,e,t,i),$c)},z={...Wn,...ad,...fi,...Rs,...On,...ld,...Is,...cd,...dt,...vd,...bd};function wd(e,t="local"){const i=typeof e=="string"?void 0:e.cwd,s=i===void 0||i===""?"":`?${new URLSearchParams({cwd:i}).toString()}`,o=typeof e=="string"?e:e.id;return new WebSocket(`${Ys()}${Xs(t)}/sessions/${encodeURIComponent(o)}/events${s}`)}function ry(e,t,i,s,o="local"){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Ys()}${Xs(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`)}function yd(e="local"){return new WebSocket(`${Ys()}${Xs(e)}/events`)}function Xs(e){return`/api/machines/${encodeURIComponent(e)}`}function Ys(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function ri(){return{sessions:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:""}}function Sd(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Xe(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function _n(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const Ln="local";function Yi(e,t){return`${e}:${t}`}function jn(e,t){return`${e}:${t}`}function f(e){return e.selectedMachine?.id??Ln}class xd{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??On}async refresh(t=f(this.getState())){this.applyMachineActivitySnapshot(t,kd(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=f(this.getState())){const s=this.getState(),o=f(s)===i,r=s.machineActivities[i]??(o?s.workspaceActivities:{}),n=$d(r,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...o?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...f(s)===t?{workspaceActivities:i}:{}})}}function kd(e){const t={};for(const i of e.workspaces)_n(i)&&(t[i.cwd]=i);return t}function $d(e,t){const i={...e};return _n(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class Pd{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??z,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=Rd(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:f(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const o=s.providers.find(r=>r.id===t&&(i===void 0||r.authType===i));o!==void 0&&(o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({authDialog:{...t,saving:!1,error:String(o)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:f(this.getState())});if(t!==void 0&&t!==""){const s=i.find(o=>o.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(o=>o.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({error:String(o)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const o=t??i.inputValue??"",r={...i};delete r.error,this.setState({authDialog:{...r,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,o,f(this.getState()));this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...i,responding:!1,error:String(n)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,f(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:f(this.getState())}),s=i.filter(r=>r.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const o=s[0];if(o===void 0)return;o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,f(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const o=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${o}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",o=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,r=t.prompt?.requestId??t.select?.requestId,n=o!==void 0&&o===r,a=n?s:"",c=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:c}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t,f(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.session();if(t!==void 0)try{this.applyStatus(await this.api.status(t,f(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function Rd(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const o=i[2];return o===void 0||o===""?{command:s}:{command:s,providerId:o}}function Ft(e){return e.replaceAll(":",".")}function Id(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[o,r]of t.entries()){if(!o.startsWith(i))continue;const n=o.slice(i.length),a=s[n];a===void 0?s[n]=r:Array.isArray(a)?a.push(r):s[n]=[a,r]}return s}function es(e,t){const i=Id(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function ae(e,t,i,s){const o=new URL(window.location.href),r=`${e}--${t}`;if(o.searchParams.delete(r),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)o.searchParams.append(r,String(n));else o.searchParams.set(r,String(i));Cd(o,s)}function Cd(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}const Qt=Ft("core:workspace.files");class Td{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.api=o.api??z}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=f(this.getState()),o=await this.api.workspaceTree(t.id,i.id,"",s),r=await Promise.all(Object.keys(this.getState().expandedDirs).map(async a=>{try{const c=await this.api.workspaceTree(t.id,i.id,a,s);return[a,c.entries]}catch(c){if(er(c))return;throw c}})),n=Object.fromEntries(r.filter(a=>a!==void 0));this.setState({fileTree:o.entries,expandedDirs:n,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:Ad(this.getState().expandedDirs,t)});return}try{const o=await this.api.workspaceTree(i.id,s.id,t,f(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:o.entries},error:""})}catch(o){this.setState({error:String(o)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),ae(Qt,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}selectDirectory(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),ae(Qt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}async restoreFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){this.setState({selectedFilePath:t,selectedFileContent:void 0});try{const o=await this.api.workspaceFile(i.id,s.id,t,f(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(er(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),ae(Qt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}async uploadFiles(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t.length===0))try{const o=f(this.getState()),r=Md(this.getState()),n=[];for(const c of t){const p=Dd(r,Ed(c));await this.api.uploadWorkspaceFile(i.id,s.id,p,c,o),n.push(p)}await this.refreshFiles();const a=n.at(-1);a!==void 0&&await this.selectFile(a),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async createFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceFile(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),await this.selectFile(t),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async createDirectory(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceDirectory(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),this.selectDirectory(t),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async moveSelectedPath(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace,o=this.getState().selectedFilePath;if(!(i===void 0||s===void 0||o===void 0||o===""||t===""))try{const r=f(this.getState());ts(this.getState())==="directory"?(await this.api.moveWorkspaceDirectory(i.id,s.id,o,t,r),await this.refreshFiles(),this.selectDirectory(t)):(await this.api.moveWorkspaceFile(i.id,s.id,o,t,r),await this.refreshFiles(),await this.selectFile(t)),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async deleteSelectedPath(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""))try{const o=f(this.getState());ts(this.getState())==="directory"?await this.api.deleteWorkspaceDirectory(t.id,i.id,s,o):await this.api.deleteWorkspaceFile(t.id,i.id,s,o),await this.refreshFiles(),this.clearSelection(),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async downloadSelectedFile(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""||ts(this.getState())==="directory"))try{await this.api.downloadWorkspaceFile(t.id,i.id,s,f(this.getState())),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),ae(Qt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}}function er(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function Ad(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Md(e){const t=e.selectedFilePath;if(t===void 0||t==="")return"";if(Fn(e.fileTree,e.expandedDirs,t)?.type==="directory")return t;const s=t.lastIndexOf("/");return s===-1?"":t.slice(0,s)}function ts(e){const t=e.selectedFilePath;return t===void 0?"file":Fn(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function Fn(e,t,i){const s=e.find(o=>o.path===i);if(s!==void 0)return s;for(const o of Object.values(t)){const r=o.find(n=>n.path===i);if(r!==void 0)return r}}function Ed(e){return e.name.split(/[\\/]+/u).filter(t=>t!=="").at(-1)??e.name}function Dd(e,t){return e===""?t:`${e}/${t}`}const tr=Ft("core:workspace.git");class Wd{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await z.gitStatus(t.id,i.id,f(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const o=this.getState().selectedDiffPath;o!==void 0&&(s.files.some(r=>r.path===o)?await this.refreshDiff(o):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),ae(tr,"diff",void 0,{replace:!0})))}catch(s){this.setState({error:String(s)})}}async selectDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),ae(tr,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[o,r]=await Promise.all([z.gitDiff(i.id,s.id,{path:t},f(this.getState())),z.gitDiff(i.id,s.id,{path:t,staged:!0},f(this.getState()))]);this.setState({selectedDiff:o,selectedStagedDiff:r,error:""})}catch(o){this.setState({error:String(o)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class Od{constructor(t,i,s,o){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=o}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await z.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(r=>r.id));this.setState({machines:i,selectedMachine:s,machineActivities:ir(this.getState().machineActivities,o),machineRuntimes:ir(this.getState().machineRuntimes,o)}),this.refreshMachineHealthFor(i),this.refreshMachineRuntimeFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...ri()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await z.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await z.deleteMachine(t.id);const o=this.getState().machines.filter(n=>n.id!==t.id),r=o.find(n=>n.id==="local")??o[0];return this.setState({machines:o,machineStatuses:is(this.getState().machineStatuses,t.id),machineRuntimes:is(this.getState().machineRuntimes,t.id),machineActivities:is(this.getState().machineActivities,t.id)}),s&&r!==void 0?(i.selectFallback===!1||await this.selectMachine(r),r):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await z.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await z.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(r=>r.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const o=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[o.machineId]:o},...o.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await z.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(o=>z.health(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(o=>z.runtime(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function is(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function ir(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class _d{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=f(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await z.projects(t);if(f(this.getState())!==t)return;const s=new Set(i.map(r=>r.id)),o=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([r])=>s.has(r)));this.setState({projects:i,workspacesByProjectId:o})}catch(i){f(this.getState())===t&&this.setState({error:String(i)})}finally{f(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await z.addProject(t.trim(),void 0,i,f(this.getState())),o=this.getState().projects;this.setState({projects:[...o.filter(r=>r.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await z.closeProject(t,f(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const Cs="pi-web:cached-new-sessions:v1",Ld="browserCachedNew",gt="local";function Nt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function sr(e,t=gt,i=Nt()){if(e.messageCount!==0||e.archived===!0)return;const s=eo(i).filter(o=>o.id!==e.id||o.machineId!==t);to([Ts(e,t),...s],i)}function Ts(e,t=gt){return{...e,browserCachedNew:!0,machineId:t}}function or(e,t=gt,i=Nt()){const s=eo(i).filter(o=>o.id!==e||o.machineId!==t);to(s,i)}function jd(e,t,i=gt,s=Nt()){const o=new Set(t.map(c=>c.id)),r=eo(s),n=r.filter(c=>c.machineId!==i||!o.has(c.id));return n.length!==r.length&&to(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function Z(e){return e===void 0?!1:zd(e)&&e.browserCachedNew===!0}function Fd(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:gt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function eo(e=Nt()){try{const t=e?.getItem(Cs);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>Nd(s)):[]}catch{return[]}}function to(e,t=Nt()){try{e.length===0?t?.removeItem(Cs):t?.setItem(Cs,JSON.stringify(e))}catch{}}function Nd(e){if(!Bd(e))return[];const t=nt(e,"id"),i=nt(e,"path"),s=nt(e,"cwd"),o=nt(e,"created"),r=nt(e,"modified"),n=nt(e,"firstMessage"),a=Ud(e,"messageCount");if(t===void 0||i===void 0||s===void 0||o===void 0||r===void 0||n===void 0||a!==0)return[];const c=ss(e,"name"),p=ss(e,"parentSessionPath"),u=ss(e,"machineId")??gt;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:o,modified:r,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function zd(e){return Ld in e}function Bd(e){return typeof e=="object"&&e!==null}function nt(e,t){const i=e[t];return typeof i=="string"?i:void 0}function ss(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Ud(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Hd(e){return np(e.flatMap(io)).filter(t=>t.parts.length>0)}function Me(e,t){return{role:e,parts:[{type:"text",text:t}]}}function St(e,t){const i=Xd(t);return i===void 0?e:{...e,meta:i}}function qd(e,t,i){if(i==="")return e;const s=e.at(-1),o=s?.parts.at(-1);return s?.role===t&&o?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...o,text:o.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,Me(t,i)]}function Kd(e,t){if(t==="")return e;const i=e.at(-1),s=i?.parts.at(-1);return i?.role==="assistant"&&s?.type==="thinking"?[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+t}]}]:i?.role==="assistant"?[...e.slice(0,-1),{...i,parts:[...i.parts,{type:"thinking",text:t}]}]:[...e,{role:"assistant",parts:[{type:"thinking",text:t}]}]}function io(e){if(Gd(e))return[e];if(O(e,"role")==="bashExecution")return[St(tp(e),e)];const t=ip(O(e,"role")),i=sp(fe(e,"content"),e),s=t==="user"?Jd(i):void 0;if(s!==void 0)return s.map(p=>St(p,e));const o=Zd(e);if(t==="tool")return[St({role:t,parts:i,...o===void 0?{}:{source:o}},e)];const r=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&r.length>0&&r.every(p=>p.type==="skillRead")?"skill":t,a=r.length>0?[St({role:n,parts:r,...o===void 0?{}:{source:o}},e)]:[],c=Vd(e);return c===void 0?a:[...a,St(c,e)]}function Vd(e){if(O(e,"role")!=="assistant"||O(e,"stopReason")!=="error")return;const t=O(e,"errorMessage")?.trim();return Me("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function Gd(e){const t=O(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(fe(e,"parts"))}function Jd(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Qd(e[0].text);if(t!==void 0)return[{role:"user",parts:[{type:"skillInvocation",name:t.name,location:t.location,content:t.content}]},...t.userMessage===void 0?[]:[{role:"user",parts:[{type:"text",text:t.userMessage}]}]]}function Qd(e){const t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;const i=t[4]?.trim();return{name:t[1]??"skill",location:t[2]??"",content:t[3]??"",...i===void 0||i===""?{}:{userMessage:i}}}function Zd(e){const t=O(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Xd(e){const t=Yd(fe(e,"timestamp")),i=ep(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Yd(e){if(typeof e=="number"&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!="string"||e==="")return;const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function ep(e){if(O(e,"role")!=="assistant")return;const t=O(e,"provider"),i=O(e,"model"),s=O(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function tp(e){const t=O(e,"command")??"",i=ni(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=fe(e,"output");s!=null&&i.push("",mi(s));const o=fe(e,"exitCode");o!=null&&i.push("",`exit ${mi(o)}`),ni(e,"cancelled")===!0&&i.push("","cancelled"),ni(e,"truncated")===!0&&i.push("","output truncated");const r=O(e,"fullOutputPath");return r!==void 0&&r!==""&&i.push("",`full output: ${r}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
- `)}]}}function ip(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function sp(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=O(i,"type"),o=O(i,"text");if(s==="text")return o!==void 0&&o!==""?[{type:"text",text:o}]:[];if(s==="thinking"){const r=O(i,"thinking")??o;return r!==void 0&&r!==""?[{type:"thinking",text:r}]:[]}if(s==="toolCall"){const r=O(i,"name")??"tool",n=fe(i,"arguments"),a=O(i,"id"),c=r==="read"?rp(O(n,"path")):void 0;return c!==void 0?[{type:"skillRead",...c,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:r,summary:zt(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const r=O(i,"data"),n=O(i,"mimeType");return r!==void 0&&r!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:r}]:[{type:"text",text:"[image]"}]}return rr(i)}).map(i=>i.type==="text"&&O(t,"role")==="toolResult"?op(i.text,t):i):rr(e)}function op(e,t){const i=O(t,"toolCallId"),s=fe(t,"content"),o=fe(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:O(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...o===void 0?{}:{details:o},isError:ni(t,"isError")===!0}}function rp(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function np(e){const t=[],i=new Map;for(const s of e){let o=[];const r={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{o.length!==0&&(t.push({role:s.role,parts:o,...r}),o=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=ap(a),p=t.length;t.push({role:"tool",parts:[c],...r}),c.toolCallId!==void 0&&i.set(c.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const c=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(c!==void 0&&lp(t,c,a)){i.delete(a.toolCallId??"");continue}}o.push(a)}n()}return t}function ap(e){return{type:"toolExecution",...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.args===void 0?{}:{args:e.args},status:"pending"}}function lp(e,t,i){const s=e[t.lineIndex],o=s?.parts[t.partIndex];if(s===void 0||o?.type!=="toolExecution")return!1;const r=gi(i.details)??o.preview,n={...o,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...r===void 0?{}:{preview:r}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function gi(e){const t=fe(e,"preview");if(!so(t))return;const i=O(t,"diff"),s=O(t,"error"),o=dp(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&o===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...o===void 0?{}:{firstChangedLine:o}}}function rr(e){return e==null?[]:typeof e=="object"?[{type:"text",text:zt(e)}]:[{type:"text",text:mi(e)}]}function zt(e){if(!so(e))return mi(e);const t=O(e,"command");if(t!==void 0)return t;const i=O(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} edit${s.length===1?"":"s"}`:Object.entries(e).filter(([,r])=>r!=null).slice(0,3).map(([r,n])=>`${r}: ${cp(n)}`).join(" · ")}function cp(e){return typeof e=="string"?e.length>80?`${e.slice(0,77)}…`:e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?"":"s"}`:typeof e=="object"&&e!==null?"object":""}function so(e){return typeof e=="object"&&e!==null}function fe(e,t){return so(e)?e[t]:void 0}function O(e,t){const i=fe(e,t);return typeof i=="string"?i:void 0}function ni(e,t){const i=fe(e,t);return typeof i=="boolean"?i:void 0}function dp(e,t){const i=fe(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function mi(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const pp="pi-web:prompt-draft:";function vi(e){return`${pp}${e}`}function Oi(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Nn(e,t=Oi()){try{return t?.getItem(vi(e))??""}catch{return""}}function bi(e,t,i=Oi()){try{t?i?.setItem(vi(e),t):i?.removeItem(vi(e))}catch{}}function oo(e,t=Oi()){try{t?.removeItem(vi(e))}catch{}}function hp(e,t,i=Oi()){const s=Nn(e,i);s!==""&&(bi(t,s,i),oo(e,i))}function up(e,t){return Me("bash",`${t===!0?`不加入上下文
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-BmIwBtZe.js","assets/vendor-editor-core-Bc1A7SO7.js","assets/vendor-editor-languages-D0CnB2js.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-6pE_JF7k.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
+ import{Q as Mo,w as nt,J as Qi,R as tl,S as il,G as sl,U as ol,V as rl,A as nl,W as al,X as ll,Y as cl,Z as Eo,x as Do,_ as dl}from"./vendor-editor-core-Bc1A7SO7.js";import{m as pl,i as hl,d as ul}from"./vendor-editor-languages-D0CnB2js.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const n of r.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(o){if(o.ep)return;o.ep=!0;const r=i(o);fetch(o.href,r)}})();const ri=globalThis,qs=ri.ShadowRoot&&(ri.ShadyCSS===void 0||ri.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Ks=Symbol(),Wo=new WeakMap;let vn=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==Ks)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=i}get styleSheet(){let t=this.o;const i=this.t;if(qs&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=Wo.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&Wo.set(i,t))}return t}toString(){return this.cssText}};const fl=e=>new vn(typeof e=="string"?e:e+"",void 0,Ks),D=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,o,r)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+e[r+1],e[0]);return new vn(i,e,Ks)},gl=(e,t)=>{if(qs)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),o=ri.litNonce;o!==void 0&&s.setAttribute("nonce",o),s.textContent=i.cssText,e.appendChild(s)}},Oo=qs?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return fl(i)})(e):e;const{is:ml,defineProperty:vl,getOwnPropertyDescriptor:bl,getOwnPropertyNames:wl,getOwnPropertySymbols:yl,getPrototypeOf:Sl}=Object,Wi=globalThis,_o=Wi.trustedTypes,xl=_o?_o.emptyScript:"",kl=Wi.reactiveElementPolyfillSupport,Mt=(e,t)=>e,hi={toAttribute(e,t){switch(t){case Boolean:e=e?xl:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=e!==null;break;case Number:i=e===null?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch{i=null}}return i}},Vs=(e,t)=>!ml(e,t),Lo={attribute:!0,type:String,converter:hi,reflect:!1,useDefault:!1,hasChanged:Vs};Symbol.metadata??=Symbol("metadata"),Wi.litPropertyMetadata??=new WeakMap;let dt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=Lo){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const s=Symbol(),o=this.getPropertyDescriptor(t,s,i);o!==void 0&&vl(this.prototype,t,o)}}static getPropertyDescriptor(t,i,s){const{get:o,set:r}=bl(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:o,set(n){const a=o?.call(this);r?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Lo}static _$Ei(){if(this.hasOwnProperty(Mt("elementProperties")))return;const t=Sl(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Mt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Mt("properties"))){const i=this.properties,s=[...wl(i),...yl(i)];for(const o of s)this.createProperty(o,i[o])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,o]of i)this.elementProperties.set(s,o)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const o=this._$Eu(i,s);o!==void 0&&this._$Eh.set(o,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const i=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const o of s)i.unshift(Oo(o))}else t!==void 0&&i.push(Oo(t));return i}static _$Eu(t,i){const s=i.attribute;return s===!1?void 0:typeof s=="string"?s:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,i=this.constructor.elementProperties;for(const s of i.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return gl(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$ET(t,i){const s=this.constructor.elementProperties.get(t),o=this.constructor._$Eu(t,s);if(o!==void 0&&s.reflect===!0){const r=(s.converter?.toAttribute!==void 0?s.converter:hi).toAttribute(i,s.type);this._$Em=t,r==null?this.removeAttribute(o):this.setAttribute(o,r),this._$Em=null}}_$AK(t,i){const s=this.constructor,o=s._$Eh.get(t);if(o!==void 0&&this._$Em!==o){const r=s.getPropertyOptions(o),n=typeof r.converter=="function"?{fromAttribute:r.converter}:r.converter?.fromAttribute!==void 0?r.converter:hi;this._$Em=o;const a=n.fromAttribute(i,r.type);this[o]=a??this._$Ej?.get(o)??a,this._$Em=null}}requestUpdate(t,i,s,o=!1,r){if(t!==void 0){const n=this.constructor;if(o===!1&&(r=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??Vs)(r,i)||s.useDefault&&s.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:o,wrapped:r},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),r!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),o===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[o,r]of this._$Ep)this[o]=r;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,r]of s){const{wrapped:n}=r,a=this[o];n!==!0||this._$AL.has(o)||a===void 0||this.C(o,void 0,r,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};dt.elementStyles=[],dt.shadowRootOptions={mode:"open"},dt[Mt("elementProperties")]=new Map,dt[Mt("finalized")]=new Map,kl?.({ReactiveElement:dt}),(Wi.reactiveElementVersions??=[]).push("2.1.2");const Gs=globalThis,jo=e=>e,ui=Gs.trustedTypes,Fo=ui?ui.createPolicy("lit-html",{createHTML:e=>e}):void 0,bn="$lit$",Be=`lit$${Math.random().toFixed(9).slice(2)}$`,wn="?"+Be,$l=`<${wn}>`,Xe=document,Wt=()=>Xe.createComment(""),Ot=e=>e===null||typeof e!="object"&&typeof e!="function",Js=Array.isArray,Pl=e=>Js(e)||typeof e?.[Symbol.iterator]=="function",Zi=`[
3
+ \f\r]`,yt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,No=/-->/g,zo=/>/g,Ke=RegExp(`>|${Zi}(?:([^\\s"'>=/]+)(${Zi}*=${Zi}*(?:[^
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Bo=/'/g,Uo=/"/g,yn=/^(?:script|style|textarea|title)$/i,Sn=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=Sn(1),he=Sn(2),Ue=Symbol.for("lit-noChange"),F=Symbol.for("lit-nothing"),Ho=new WeakMap,Qe=Xe.createTreeWalker(Xe,129);function xn(e,t){if(!Js(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Fo!==void 0?Fo.createHTML(t):t}const Rl=(e,t)=>{const i=e.length-1,s=[];let o,r=t===2?"<svg>":t===3?"<math>":"",n=yt;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,g=0;for(;g<c.length&&(n.lastIndex=g,u=n.exec(c),u!==null);)g=n.lastIndex,n===yt?u[1]==="!--"?n=No:u[1]!==void 0?n=zo:u[2]!==void 0?(yn.test(u[2])&&(o=RegExp("</"+u[2],"g")),n=Ke):u[3]!==void 0&&(n=Ke):n===Ke?u[0]===">"?(n=o??yt,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?Ke:u[3]==='"'?Uo:Bo):n===Uo||n===Bo?n=Ke:n===No||n===zo?n=yt:(n=Ke,o=void 0);const b=n===Ke&&e[a+1].startsWith("/>")?" ":"";r+=n===yt?c+$l:h>=0?(s.push(p),c.slice(0,h)+bn+c.slice(h)+Be+b):c+Be+(h===-2?a:b)}return[xn(e,r+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class _t{constructor({strings:t,_$litType$:i},s){let o;this.parts=[];let r=0,n=0;const a=t.length-1,c=this.parts,[p,u]=Rl(t,i);if(this.el=_t.createElement(p,s),Qe.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(o=Qe.nextNode())!==null&&c.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const h of o.getAttributeNames())if(h.endsWith(bn)){const g=u[n++],b=o.getAttribute(h).split(Be),P=/([.?@])?(.*)/.exec(g);c.push({type:1,index:r,name:P[2],strings:b,ctor:P[1]==="."?Cl:P[1]==="?"?Tl:P[1]==="@"?Al:Oi}),o.removeAttribute(h)}else h.startsWith(Be)&&(c.push({type:6,index:r}),o.removeAttribute(h));if(yn.test(o.tagName)){const h=o.textContent.split(Be),g=h.length-1;if(g>0){o.textContent=ui?ui.emptyScript:"";for(let b=0;b<g;b++)o.append(h[b],Wt()),Qe.nextNode(),c.push({type:2,index:++r});o.append(h[g],Wt())}}}else if(o.nodeType===8)if(o.data===wn)c.push({type:2,index:r});else{let h=-1;for(;(h=o.data.indexOf(Be,h+1))!==-1;)c.push({type:7,index:r}),h+=Be.length-1}r++}}static createElement(t,i){const s=Xe.createElement("template");return s.innerHTML=t,s}}function ht(e,t,i=e,s){if(t===Ue)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const r=Ot(t)?void 0:t._$litDirective$;return o?.constructor!==r&&(o?._$AO?.(!1),r===void 0?o=void 0:(o=new r(e),o._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=o:i._$Cl=o),o!==void 0&&(t=ht(e,o._$AS(e,t.values),o,s)),t}class Il{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,o=(t?.creationScope??Xe).importNode(i,!0);Qe.currentNode=o;let r=Qe.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new gt(r,r.nextSibling,this,t):c.type===1?p=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(p=new Ml(r,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(r=Qe.nextNode(),n++)}return Qe.currentNode=Xe,o}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class gt{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=F,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=o,this._$Cv=o?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=ht(this,t,i),Ot(t)?t===F||t==null||t===""?(this._$AH!==F&&this._$AR(),this._$AH=F):t!==this._$AH&&t!==Ue&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Pl(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==F&&Ot(this._$AH)?this._$AA.nextSibling.data=t:this.T(Xe.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,o=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=_t.createElement(xn(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const r=new Il(o,this),n=r.u(this.options);r.p(i),this.T(n),this._$AH=r}}_$AC(t){let i=Ho.get(t.strings);return i===void 0&&Ho.set(t.strings,i=new _t(t)),i}k(t){Js(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,o=0;for(const r of t)o===i.length?i.push(s=new gt(this.O(Wt()),this.O(Wt()),this,this.options)):s=i[o],s._$AI(r),o++;o<i.length&&(this._$AR(s&&s._$AB.nextSibling,o),i.length=o)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=jo(t).nextSibling;jo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Oi=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,r){this.type=1,this._$AH=F,this._$AN=void 0,this.element=t,this.name=i,this._$AM=o,this.options=r,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=F}_$AI(t,i=this,s,o){const r=this.strings;let n=!1;if(r===void 0)t=ht(this,t,i,0),n=!Ot(t)||t!==this._$AH&&t!==Ue,n&&(this._$AH=t);else{const a=t;let c,p;for(t=r[0],c=0;c<r.length-1;c++)p=ht(this,a[s+c],i,c),p===Ue&&(p=this._$AH[c]),n||=!Ot(p)||p!==this._$AH[c],p===F?t=F:t!==F&&(t+=(p??"")+r[c+1]),this._$AH[c]=p}n&&!o&&this.j(t)}j(t){t===F?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Cl=class extends Oi{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===F?void 0:t}},Tl=class extends Oi{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==F)}},Al=class extends Oi{constructor(t,i,s,o,r){super(t,i,s,o,r),this.type=5}_$AI(t,i=this){if((t=ht(this,t,i,0)??F)===Ue)return;const s=this._$AH,o=t===F&&s!==F||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==F&&(s===F||o);o&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Ml=class{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){ht(this,t)}};const El={I:gt},Dl=Gs.litHtmlPolyfillSupport;Dl?.(_t,gt),(Gs.litHtmlVersions??=[]).push("3.3.3");const Wl=(e,t,i)=>{const s=i?.renderBefore??t;let o=s._$litPart$;if(o===void 0){const r=i?.renderBefore??null;s._$litPart$=o=new gt(t.insertBefore(Wt(),r),r,void 0,i??{})}return o._$AI(e),o};const Qs=globalThis;let C=class extends dt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=Wl(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ue}};C._$litElement$=!0,C.finalized=!0,Qs.litElementHydrateSupport?.({LitElement:C});const Ol=Qs.litElementPolyfillSupport;Ol?.({LitElement:C});(Qs.litElementVersions??=[]).push("4.2.2");const W=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const _l={attribute:!0,type:String,converter:hi,reflect:!1,hasChanged:Vs},Ll=(e=_l,t,i)=>{const{kind:s,metadata:o}=i;let r=globalThis.litPropertyMetadata.get(o);if(r===void 0&&globalThis.litPropertyMetadata.set(o,r=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,c,e,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,e,a),a}}}if(s==="setter"){const{name:n}=i;return function(a){const c=this[n];t.call(this,a),this.requestUpdate(n,c,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?Ll(e,t,i):((s,o,r)=>{const n=o.hasOwnProperty(r);return o.constructor.createProperty(r,s),n?Object.getOwnPropertyDescriptor(o,r):void 0})(e,t,i)}function k(e){return d({...e,state:!0,attribute:!1})}const jl=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function B(e,t){return(i,s,o)=>{const r=n=>n.renderRoot?.querySelector(e)??null;return jl(i,s,{get(){return r(this)}})}}function kn(e,t=Nl()){if(t===void 0)return e;const i=Fl(t);if(i===void 0)return e;const s=new URL(e,t.origin);return s.searchParams.set("embed",i.embed),s.searchParams.set("token",i.token),`${s.pathname}${s.search}${s.hash}`}function Fl(e){const t=e.searchParams.get("embed"),i=e.searchParams.get("token")?.trim();if(!(t!=="management"||i===void 0||i===""))return{embed:t,token:i}}function Nl(){if(typeof globalThis.location>"u")return;const e=globalThis.location;if(typeof e.href=="string"&&e.href!=="")return new URL(e.href);const t=typeof e.protocol=="string"&&e.protocol!==""?e.protocol:"http:",i=typeof e.host=="string"&&e.host!==""?e.host:"localhost",s=typeof e.search=="string"?e.search:"";return new URL(`${t}//${i}/${s}`)}async function v(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const o=await fetch(kn(e),{...i,headers:s});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(zl(n)??o.statusText)}const r=await o.json();return t(r)}function zl(e){if(Bl(e))return typeof e.error=="string"?e.error:void 0}function Bl(e){return typeof e=="object"&&e!==null}function Et(e){return typeof e=="object"&&e!==null}function S(e){if(!Et(e))throw new Error("Expected object response");return e}function m(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function $(e,t){const i=e[t];if(i!==void 0){if(typeof i!="string")throw new Error(`Expected optional string field: ${t}`);return i}}function ee(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function Pe(e,t){const i=e[t];if(i!==void 0){if(typeof i!="number")throw new Error(`Expected optional number field: ${t}`);return i}}function E(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function N(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function He(e,t){if(S(e)[t]!==!0)throw new Error(`Expected ${t} response`);return!0}function w(e,t){return t===void 0?{}:{[e]:t}}const ut={sessionsDeleteArchived:"sessions.deleteArchived",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments"},Ul=Object.values(ut),Hl=new Set(Ul);function ql(e){return typeof e=="string"&&Hl.has(e)}function Lt(e,t){return e?.capabilities?.includes(t)===!0}function qo(e){const t=S(e);return{path:m(t,"path"),exists:E(t,"exists"),config:Ko(t.config),effectiveConfig:Ko(t.effectiveConfig),envOverrides:Jl(t.envOverrides)}}function Ko(e){const t=S(e);return{...w("host",$(t,"host")),...w("port",Pe(t,"port")),...w("allowedHosts",Kl(t.allowedHosts)),...w("shortcuts",Vl(t.shortcuts)),...w("plugins",Gl(t.plugins)),...w("spawnSessions",Go(t,"spawnSessions")),...w("subsessions",Go(t,"subsessions"))}}function Kl(e){if(e!==void 0){if(e===!0)return!0;if(Array.isArray(e)&&e.every(t=>typeof t=="string"))return e;throw new Error("Invalid PI WEB allowedHosts field")}}function Vl(e){if(e!==void 0){if(!Et(e)||Array.isArray(e))throw new Error("Invalid PI WEB shortcuts field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(i!==null&&(typeof i!="string"||i===""))throw new Error("Invalid PI WEB shortcut field");return[t,i]}))}}function Gl(e){if(e!==void 0){if(!Et(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!Et(i)||Array.isArray(i))throw new Error("Invalid PI WEB plugin config field");const s=i.enabled;if(s!==void 0&&typeof s!="boolean")throw new Error("Invalid PI WEB plugin enabled field");const o=i.settings;if(o!==void 0&&(!Et(o)||Array.isArray(o)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Jl(e){const t=S(e);return{host:E(t,"host"),port:E(t,"port"),allowedHosts:E(t,"allowedHosts"),spawnSessions:E(t,"spawnSessions"),subsessions:E(t,"subsessions")}}function Ql(e){const t=S(e);return{plugins:N(Zl)(t.plugins)}}function Zl(e){const t=S(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:Xl(t.scope),machineSpecific:ac(t.machineSpecific,"machineSpecific")??!1,enabled:E(t,"enabled")}}function Xl(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function Yl(e){const t=S(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:tc(t.components),release:sc(t.release),commands:oc(t.commands),messages:N(rc)(t.messages)}}function ec(e){const t=S(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:$n(t.components),capabilities:Zs(t.capabilities)}}function tc(e){const t=S(e);return{web:fi(t.web),sessiond:fi(t.sessiond)}}function $n(e){const t=S(e);return{web:Vo(t.web),sessiond:Vo(t.sessiond)}}function Vo(e){const t=S(e);return{component:Pn(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),available:E(t,"available"),capabilities:Zs(t.capabilities),...w("error",$(t,"error"))}}function fi(e){const t=S(e);return{component:Pn(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),...w("installedVersion",$(t,"installedVersion")),stale:E(t,"stale"),available:E(t,"available"),...w("installation",ic(t.installation)),...w("error",$(t,"error"))}}function ic(e){if(e===void 0)return;const t=S(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");return{kind:i,...w("path",$(t,"path")),...w("source",$(t,"source")),...s===void 0?{}:{scope:s},...w("npmRoot",$(t,"npmRoot"))}}function sc(e){const t=S(e);return{packageName:m(t,"packageName"),...w("latestVersion",$(t,"latestVersion")),updateAvailable:E(t,"updateAvailable"),...w("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...w("error",$(t,"error"))}}function oc(e){const t=S(e);return{...w("update",$(t,"update")),...w("restart",$(t,"restart")),...w("restartWeb",$(t,"restartWeb")),...w("restartSessiond",$(t,"restartSessiond")),...w("status",$(t,"status"))}}function rc(e){const t=S(e);return{id:m(t,"id"),severity:nc(t.severity),title:m(t,"title"),body:m(t,"body"),...w("command",$(t,"command"))}}function Pn(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Zs(e){if(!Array.isArray(e)||!e.every(ql))throw new Error("Invalid PI WEB capabilities");return e}function nc(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function ac(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function Go(e,t){const i=e[t];if(i!==void 0){if(typeof i!="boolean")throw new Error(`Invalid PI WEB ${t} field`);return i}}function lc(e){const t=S(e);return N(Rn)(t.machines)}function Rn(e){const t=S(e),i=pc(t,"kind"),s=$(t,"baseUrl"),o=In(t,"status"),r=$(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...o===void 0?{}:{status:o},...r===void 0?{}:{statusMessage:r}}}function cc(e){const t=S(e),i=In(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:fi(t.web)},...t.sessiond===void 0?{}:{sessiond:fi(t.sessiond)},...s===void 0?{}:{error:s}}}function dc(e){const t=S(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...w("packageName",$(t,"packageName")),...w("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:$n(t.components)},...t.capabilities===void 0?{}:{capabilities:Zs(t.capabilities)},...i===void 0?{}:{error:i}}}function pc(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function In(e,t){const i=$(e,t);if(i!==void 0){if(i!=="unknown"&&i!=="online"&&i!=="offline"&&i!=="error")throw new Error(`Expected machine status field: ${t}`);return i}}function hc(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function uc(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function fc(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=S(e);return{messages:hc(t.messages),start:ee(t,"start"),total:ee(t,"total")}}function Jo(e){const t=S(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function gc(e){const t=S(e),i=$(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:E(t,"isMain"),isGitRepo:E(t,"isGitRepo"),isGitWorktree:E(t,"isGitWorktree")}}function $s(e){const t=S(e);return{path:m(t,"path"),size:ee(t,"size"),modifiedAt:m(t,"modifiedAt")}}function Xi(e){const t=S(e);return{path:m(t,"path")}}function Qo(e){const t=S(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function Ps(e){const t=S(e),i=$(t,"name"),s=$(t,"parentSessionPath"),o=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:ee(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function St(e){const t=S(e);return{sessionId:m(t,"sessionId"),isStreaming:E(t,"isStreaming"),isCompacting:E(t,"isCompacting"),isBashRunning:E(t,"isBashRunning"),pendingMessageCount:ee(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:N(mc)(t.queuedMessages),...w("messageCount",Pe(t,"messageCount")),tokens:vc(t.tokens),cost:ee(t,"cost"),...yc(t.model),...Dc(t.contextUsage),...w("thinkingLevel",$(t,"thinkingLevel"))}}function mc(e){const t=S(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text"),...w("imageCount",Pe(t,"imageCount"))}}function vc(e){const t=S(e);return{input:ee(t,"input"),output:ee(t,"output"),cacheRead:ee(t,"cacheRead"),cacheWrite:ee(t,"cacheWrite"),total:ee(t,"total")}}function Cn(e){const t=S(e);return{...w("provider",$(t,"provider")),...w("id",$(t,"id")),...w("name",$(t,"name")),...w("contextWindow",Pe(t,"contextWindow")),...w("reasoning",t.reasoning),...w("input",bc(t.input))}}function bc(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Invalid model input");return e.map(wc)}}function wc(e){if(e==="text"||e==="image")return e;throw new Error("Invalid model input")}function yc(e){return e===void 0?{}:{model:Cn(e)}}function Sc(e){const t=S(e);return{models:N(Cn)(t.models)}}function xc(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function kc(e){const t=S(e);return{levels:N(xc)(t.levels)}}function $c(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Pc(e){if(e!=="stored"&&e!=="runtime"&&e!=="environment"&&e!=="fallback"&&e!=="models_json_key"&&e!=="models_json_command")throw new Error("Invalid auth status source");return e}function Rc(e){const t=S(e),i=t.source===void 0?void 0:Pc(t.source);return{configured:E(t,"configured"),...w("source",i),...w("label",$(t,"label"))}}function Ic(e){const t=S(e);return{id:m(t,"id"),name:m(t,"name"),authType:$c(t.authType),status:Rc(t.status)}}function Cc(e){const t=S(e);return{providers:N(Ic)(t.providers)}}function Gt(e){const t=S(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:Tc(t.status),progress:N(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...w("error",$(t,"error")),...w("auth",Ac(t.auth)),...w("prompt",Mc(t.prompt)),...w("select",Ec(t.select))}}function Tc(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Ac(e){if(e===void 0)return;const t=S(e);return{url:m(t,"url"),...w("instructions",$(t,"instructions"))}}function Mc(e){if(e===void 0)return;const t=S(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...w("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function Ec(e){if(e===void 0)return;const t=S(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:N(An)(t.options)}}function Dc(e){if(e===void 0)return{};const t=S(e);return{contextUsage:{tokens:er(t,"tokens"),contextWindow:ee(t,"contextWindow"),percent:er(t,"percent")}}}function Wc(e){const t=S(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...w("description",$(t,"description"))}}function Tn(e){const t=S(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function Oc(e){const t=S(e);return{path:m(t,"path"),entries:N(_c)(t.entries),scannedAt:m(t,"scannedAt"),truncated:E(t,"truncated")}}function _c(e){const t=S(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...w("size",Pe(t,"size")),...w("modifiedAt",$(t,"modifiedAt"))}}function Lc(e){const t=S(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...w("language",$(t,"language")),...w("mediaType",jc(t.mediaType)),...w("mimeType",$(t,"mimeType")),encoding:i,size:ee(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:E(t,"truncated"),binary:E(t,"binary")}}function jc(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function Fc(e){const t=S(e);return{isGitRepo:E(t,"isGitRepo"),hash:m(t,"hash"),...w("branch",$(t,"branch")),...w("upstream",$(t,"upstream")),...w("ahead",Pe(t,"ahead")),...w("behind",Pe(t,"behind")),files:N(Nc)(t.files)}}function Nc(e){const t=S(e);return{path:m(t,"path"),...w("oldPath",$(t,"oldPath")),index:Zo(t.index),workingTree:Zo(t.workingTree)}}function Zo(e){switch(e){case"unmodified":case"modified":case"added":case"deleted":case"renamed":case"copied":case"untracked":case"ignored":case"conflicted":return e;default:throw new Error("Invalid git file state")}}function zc(e){const t=S(e);return{...w("path",$(t,"path")),staged:E(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:E(t,"truncated")}}function Yi(e){const t=S(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:E(t,"exited"),...w("exitCode",Pe(t,"exitCode")),...w("commandRunId",$(t,"commandRunId"))}}function Dt(e){const t=S(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:Bc(t.status),...w("exitCode",Pe(t,"exitCode")),createdAt:m(t,"createdAt"),...w("startedAt",$(t,"startedAt")),...w("completedAt",$(t,"completedAt")),metadata:Uc(t.metadata,"metadata")}}function Bc(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function Uc(e,t){const i=S(e);return Object.fromEntries(Object.entries(i).map(([s,o])=>{if(typeof o!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,o]}))}function Hc(e){const t=S(e);return{cwd:m(t,"cwd"),hasSessionActivity:E(t,"hasSessionActivity"),hasTerminalActivity:E(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function qc(e){const t=S(e);return{workspaces:N(Hc)(t.workspaces),generatedAt:m(t,"generatedAt")}}function Xo(e){const t=S(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:N(An)(t.options)};if(i==="done")return{type:i,...w("message",$(t,"message")),...Kc(t.session),...w("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function An(e){const t=S(e);return{value:m(t,"value"),label:m(t,"label"),...w("description",$(t,"description"))}}function Kc(e){return e===void 0?{}:{session:Ps(e)}}function Jt(e){return{accepted:He(e,"accepted")}}function Vc(e){const t=S(e);return N(Gc)(t.attachments)}function Gc(e){const t=S(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:ee(t,"size")}}function Rs(e){return{closed:He(e,"closed")}}function Jc(e){return{aborted:He(e,"aborted")}}function Qc(e){return{stopped:He(e,"stopped")}}function Yo(e){const t=S(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:uc(t.sessionIds,"sessionIds"),s=Pe(t,"archivedCount"),o=Pe(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...o===void 0?{}:{skippedAlreadyArchivedCount:o}}}function Zc(e){return{restored:He(e,"restored")}}function Xc(e){return{deleted:He(e,"deleted")}}function Yc(e){return{detached:He(e,"detached")}}function ed(e){return{reloaded:He(e,"reloaded")}}function er(e,t){const i=e[t];if(i===null)return null;if(typeof i!="number")throw new Error(`Expected number|null field: ${t}`);return i}function td(e){return typeof e=="string"?e:e.id}function id(e){return typeof e=="string"?void 0:e.cwd}function sd(e,t,i,s){const o=new URLSearchParams;s?.path!==void 0&&o.set("path",s.path),s?.staged===!0&&o.set("staged","true");const r=o.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${r?`?${r}`:""}`}function od(e,t,i="local"){const s=new URLSearchParams,o=id(e);o!==void 0&&o!==""&&s.set("cwd",o),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const r=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(td(e))}/messages${r===""?"":`?${r}`}`}function rd(e,t,i,s){const o=new URLSearchParams;return o.set("path",i),s?.modifiedAt!==void 0&&o.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${o.toString()}`}function Mn(e,t,i,s){const o=new URLSearchParams;o.set("path",i);const r=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return kn(`${r}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${o.toString()}`)}const R=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function nd(e){return typeof e=="string"?e:e.id}function En(e){return typeof e=="string"?void 0:e.cwd}function Dn(e,t="local"){return`${R(t)}/sessions/${encodeURIComponent(nd(e))}`}function K(e,t,i="local"){return`${Dn(e,i)}/${t}`}function Qt(e,t,i="local"){return`${K(e,t,i)}${Wn(e)}`}function ad(e,t="local"){return`${Dn(e,t)}${Wn(e)}`}function Wn(e){const t=En(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function V(e,t={}){const i=En(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}const On={piWebStatus:(e="local")=>v(e==="local"?"/api/pi-web/status":`${R(e)}/pi-web/status`,Yl),piWebRuntime:()=>v("/api/pi-web/runtime",ec)},ld={machines:()=>v("/api/machines",lc),addMachine:e=>v("/api/machines",Rn,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>v(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>v(`/api/machines/${encodeURIComponent(e)}/health`,cc),runtime:e=>v(`/api/machines/${encodeURIComponent(e)}/runtime`,dc)},gi={config:()=>v("/api/config",qo),saveConfig:e=>v("/api/config",qo,{method:"PUT",body:JSON.stringify({config:e})})},Is={plugins:()=>v("/api/plugins",Ql)},_n={workspaceActivity:(e="local")=>v(`${R(e)}/activity`,qc)},cd={projects:(e="local")=>v(`${R(e)}/projects`,N(Jo)),addProject:(e,t,i,s="local")=>v(`${R(s)}/projects`,Jo,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>v(`${R(t)}/projects/${encodeURIComponent(e)}`,Rs,{method:"DELETE"}),projectDirectories:(e,t="local")=>v(`${R(t)}/project-directories?q=${encodeURIComponent(e)}`,N(Tn))},Cs={workspaces:(e,t="local")=>v(`${R(t)}/projects/${e}/workspaces`,N(gc)),deleteWorkspace:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Dt,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Oc),workspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Lc),uploadWorkspaceFile:async(e,t,i,s,o="local")=>o==="local"?gd(e,t,i,s):v(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,$s,{method:"POST",body:JSON.stringify({path:i,contentBase64:await ud(s)})}),createWorkspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,$s,{method:"POST",body:JSON.stringify({path:i,contentBase64:""})}),moveWorkspaceFile:(e,t,i,s,o="local")=>v(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Xi,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Qo,{method:"DELETE"}),createWorkspaceDirectory:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Xi,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,o="local")=>v(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Xi,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,Qo,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>Mn(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>md(e,t,i,s)},dd={sessions:(e,t="local")=>v(`${R(t)}/sessions?cwd=${encodeURIComponent(e)}`,N(Ps)),startSession:(e,t="local")=>v(`${R(t)}/sessions`,Ps,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>v(od(e,t,i),fc),status:(e,t="local")=>v(Qt(e,"status",t),St),models:(e,t="local")=>v(Qt(e,"models",t),Sc),setModel:(e,t,i,s="local")=>v(K(e,"model",s),St,{method:"POST",body:V(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>v(K(e,"model/cycle",i),St,{method:"POST",body:V(e,{direction:t})}),thinkingLevels:(e,t="local")=>v(Qt(e,"thinking-levels",t),kc),setThinkingLevel:(e,t,i="local")=>v(K(e,"thinking-level",i),St,{method:"POST",body:V(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>v(K(e,"thinking-level/cycle",t),St,{method:"POST",body:V(e)}),commands:(e,t="local")=>v(Qt(e,"commands",t),N(Wc)),prompt:(e,t,i,s="local",o)=>v(K(e,"prompt",s),Jt,{method:"POST",body:V(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...o!==void 0&&o.length>0?{attachments:o}:{}})}),saveAttachments:(e,t,i="local",s)=>v(K(e,"attachments",i),Vc,{method:"POST",body:V(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>v(K(e,"shell",i),Jt,{method:"POST",body:V(e,{text:t})}),runCommand:(e,t,i="local")=>v(K(e,"commands/run",i),Xo,{method:"POST",body:V(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>v(K(e,"commands/respond",s),Xo,{method:"POST",body:V(e,{requestId:t,value:i})}),abort:(e,t="local")=>v(K(e,"abort",t),Jc,{method:"POST",body:V(e)}),stop:(e,t="local")=>v(K(e,"stop",t),Qc,{method:"POST",body:V(e)}),archive:(e,t="local")=>v(K(e,"archive",t),Yo,{method:"POST",body:V(e)}),archiveWithDescendants:(e,t="local")=>v(K(e,"archive-tree",t),Yo,{method:"POST",body:V(e)}),restore:(e,t="local")=>v(K(e,"restore",t),Zc,{method:"POST",body:V(e)}),deleteArchived:(e,t="local")=>v(ad(e,t),Xc,{method:"DELETE"}),detachParent:(e,t="local")=>v(K(e,"detach-parent",t),Yc,{method:"POST",body:V(e)}),reloadSession:(e,t="local")=>v(K(e,"reload",t),ed,{method:"POST",body:V(e)}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return v(`${R(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Cc)},saveApiKey:(e,t,i="local")=>v(`${R(i)}/auth/api-key`,Jt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>v(`${R(t)}/auth/logout`,Jt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>v(`${R(t)}/auth/oauth`,Gt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>v(`${R(t)}/auth/oauth/${encodeURIComponent(e)}`,Gt),respondOAuthFlow:(e,t,i,s="local")=>v(`${R(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Gt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>v(`${R(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Gt,{method:"POST"})},pt={terminals:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,N(Yi)),startTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Yi,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Rs,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,Rs,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Yi,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Dt,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>v(`${R(t)}/terminal-command-runs${hd(e)}`,N(Dt)),getCommandRun:(e,t="local")=>pd(e,t),cancelCommandRun:(e,t="local")=>v(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Dt,{method:"POST"})};async function pd(e,t){const i=await fetch(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Xs(s)??i.statusText)}return Dt(await i.json())}}function hd(e){if(e===void 0)return"";const t=new URLSearchParams;e.projectId!==void 0&&t.set("projectId",e.projectId),e.workspaceId!==void 0&&t.set("workspaceId",e.workspaceId),e.terminalId!==void 0&&t.set("terminalId",e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set("statuses",e.statuses.join(",")),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set("metadata",JSON.stringify(e.metadata));const i=t.toString();return i===""?"":`?${i}`}function Xs(e){if(!vd(e))return;const t=e.error;return typeof t=="string"?t:void 0}async function ud(e){return fd(await e.arrayBuffer())}function fd(e){const t=new Uint8Array(e);let i="";for(const s of t)i+=String.fromCharCode(s);return btoa(i)}async function gd(e,t,i,s){const o=new FormData;o.set("path",i),o.set("file",s,s.name);const r=await fetch(`${R("local")}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,{method:"POST",body:o});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(Xs(n)??r.statusText)}return $s(await r.json())}async function md(e,t,i,s){const o=await fetch(Mn(e,t,i,{machineId:s}));if(!o.ok){const p=await o.json().catch(()=>({}));throw new Error(Xs(p)??o.statusText)}const r=await o.blob(),n=URL.createObjectURL(r),a=document.createElement("a");a.href=n;const c=i.split("/").pop();a.download=c===void 0||c===""?"download":c,document.body.append(a),a.click(),a.remove(),URL.revokeObjectURL(n)}function vd(e){return typeof e=="object"&&e!==null}const bd={files:(e,t,i={})=>{const s=new URLSearchParams({cwd:e,q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),v(`${R(i.machineId)}/files?${s.toString()}`,N(Tn))}},wd={gitStatus:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Fc),gitDiff:(e,t,i,s="local")=>v(sd(s,e,t,i),zc)},z={...On,...ld,...gi,...Is,..._n,...cd,...Cs,...dd,...pt,...bd,...wd};function yd(e,t="local"){const i=typeof e=="string"?void 0:e.cwd,s=i===void 0||i===""?"":`?${new URLSearchParams({cwd:i}).toString()}`,o=typeof e=="string"?e:e.id;return new WebSocket(`${eo()}${Ys(t)}/sessions/${encodeURIComponent(o)}/events${s}`)}function ny(e,t,i,s,o="local"){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${eo()}${Ys(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`)}function Sd(e="local"){return new WebSocket(`${eo()}${Ys(e)}/events`)}function Ys(e){return`/api/machines/${encodeURIComponent(e)}`}function eo(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function ni(){return{sessions:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:""}}function xd(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Ye(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Ln(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const jn="local";function es(e,t){return`${e}:${t}`}function Fn(e,t){return`${e}:${t}`}function f(e){return e.selectedMachine?.id??jn}class kd{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??_n}async refresh(t=f(this.getState())){this.applyMachineActivitySnapshot(t,$d(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=f(this.getState())){const s=this.getState(),o=f(s)===i,r=s.machineActivities[i]??(o?s.workspaceActivities:{}),n=Pd(r,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...o?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...f(s)===t?{workspaceActivities:i}:{}})}}function $d(e){const t={};for(const i of e.workspaces)Ln(i)&&(t[i.cwd]=i);return t}function Pd(e,t){const i={...e};return Ln(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class Rd{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??z,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=Id(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:f(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const o=s.providers.find(r=>r.id===t&&(i===void 0||r.authType===i));o!==void 0&&(o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({authDialog:{...t,saving:!1,error:String(o)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:f(this.getState())});if(t!==void 0&&t!==""){const s=i.find(o=>o.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(o=>o.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({error:String(o)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const o=t??i.inputValue??"",r={...i};delete r.error,this.setState({authDialog:{...r,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,o,f(this.getState()));this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...i,responding:!1,error:String(n)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,f(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:f(this.getState())}),s=i.filter(r=>r.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const o=s[0];if(o===void 0)return;o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,f(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const o=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${o}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",o=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,r=t.prompt?.requestId??t.select?.requestId,n=o!==void 0&&o===r,a=n?s:"",c=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:c}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t,f(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.session();if(t!==void 0)try{this.applyStatus(await this.api.status(t,f(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function Id(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const o=i[2];return o===void 0||o===""?{command:s}:{command:s,providerId:o}}function Nt(e){return e.replaceAll(":",".")}function Cd(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[o,r]of t.entries()){if(!o.startsWith(i))continue;const n=o.slice(i.length),a=s[n];a===void 0?s[n]=r:Array.isArray(a)?a.push(r):s[n]=[a,r]}return s}function ts(e,t){const i=Cd(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function ae(e,t,i,s){const o=new URL(window.location.href),r=`${e}--${t}`;if(o.searchParams.delete(r),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)o.searchParams.append(r,String(n));else o.searchParams.set(r,String(i));Td(o,s)}function Td(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}const Zt=Nt("core:workspace.files");class Ad{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.api=o.api??z}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=f(this.getState()),o=await this.api.workspaceTree(t.id,i.id,"",s),r=await Promise.all(Object.keys(this.getState().expandedDirs).map(async a=>{try{const c=await this.api.workspaceTree(t.id,i.id,a,s);return[a,c.entries]}catch(c){if(tr(c))return;throw c}})),n=Object.fromEntries(r.filter(a=>a!==void 0));this.setState({fileTree:o.entries,expandedDirs:n,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:Md(this.getState().expandedDirs,t)});return}try{const o=await this.api.workspaceTree(i.id,s.id,t,f(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:o.entries},error:""})}catch(o){this.setState({error:String(o)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),ae(Zt,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}selectDirectory(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),ae(Zt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}async restoreFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){this.setState({selectedFilePath:t,selectedFileContent:void 0});try{const o=await this.api.workspaceFile(i.id,s.id,t,f(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(tr(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),ae(Zt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}async uploadFiles(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t.length===0))try{const o=f(this.getState()),r=Ed(this.getState()),n=[];for(const c of t){const p=Wd(r,Dd(c));await this.api.uploadWorkspaceFile(i.id,s.id,p,c,o),n.push(p)}await this.refreshFiles();const a=n.at(-1);a!==void 0&&await this.selectFile(a),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async createFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceFile(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),await this.selectFile(t),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async createDirectory(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceDirectory(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),this.selectDirectory(t),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async moveSelectedPath(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace,o=this.getState().selectedFilePath;if(!(i===void 0||s===void 0||o===void 0||o===""||t===""))try{const r=f(this.getState());is(this.getState())==="directory"?(await this.api.moveWorkspaceDirectory(i.id,s.id,o,t,r),await this.refreshFiles(),this.selectDirectory(t)):(await this.api.moveWorkspaceFile(i.id,s.id,o,t,r),await this.refreshFiles(),await this.selectFile(t)),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async deleteSelectedPath(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""))try{const o=f(this.getState());is(this.getState())==="directory"?await this.api.deleteWorkspaceDirectory(t.id,i.id,s,o):await this.api.deleteWorkspaceFile(t.id,i.id,s,o),await this.refreshFiles(),this.clearSelection(),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async downloadSelectedFile(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""||is(this.getState())==="directory"))try{await this.api.downloadWorkspaceFile(t.id,i.id,s,f(this.getState())),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),ae(Zt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}}function tr(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function Md(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Ed(e){const t=e.selectedFilePath;if(t===void 0||t==="")return"";if(Nn(e.fileTree,e.expandedDirs,t)?.type==="directory")return t;const s=t.lastIndexOf("/");return s===-1?"":t.slice(0,s)}function is(e){const t=e.selectedFilePath;return t===void 0?"file":Nn(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function Nn(e,t,i){const s=e.find(o=>o.path===i);if(s!==void 0)return s;for(const o of Object.values(t)){const r=o.find(n=>n.path===i);if(r!==void 0)return r}}function Dd(e){return e.name.split(/[\\/]+/u).filter(t=>t!=="").at(-1)??e.name}function Wd(e,t){return e===""?t:`${e}/${t}`}const ir=Nt("core:workspace.git");class Od{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await z.gitStatus(t.id,i.id,f(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const o=this.getState().selectedDiffPath;o!==void 0&&(s.files.some(r=>r.path===o)?await this.refreshDiff(o):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),ae(ir,"diff",void 0,{replace:!0})))}catch(s){this.setState({error:String(s)})}}async selectDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),ae(ir,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[o,r]=await Promise.all([z.gitDiff(i.id,s.id,{path:t},f(this.getState())),z.gitDiff(i.id,s.id,{path:t,staged:!0},f(this.getState()))]);this.setState({selectedDiff:o,selectedStagedDiff:r,error:""})}catch(o){this.setState({error:String(o)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class _d{constructor(t,i,s,o){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=o}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await z.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(r=>r.id));this.setState({machines:i,selectedMachine:s,machineActivities:sr(this.getState().machineActivities,o),machineRuntimes:sr(this.getState().machineRuntimes,o)}),this.refreshMachineHealthFor(i),this.refreshMachineRuntimeFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...ni()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await z.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await z.deleteMachine(t.id);const o=this.getState().machines.filter(n=>n.id!==t.id),r=o.find(n=>n.id==="local")??o[0];return this.setState({machines:o,machineStatuses:ss(this.getState().machineStatuses,t.id),machineRuntimes:ss(this.getState().machineRuntimes,t.id),machineActivities:ss(this.getState().machineActivities,t.id)}),s&&r!==void 0?(i.selectFallback===!1||await this.selectMachine(r),r):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await z.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await z.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(r=>r.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const o=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[o.machineId]:o},...o.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await z.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(o=>z.health(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(o=>z.runtime(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function ss(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function sr(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class Ld{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=f(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await z.projects(t);if(f(this.getState())!==t)return;const s=new Set(i.map(r=>r.id)),o=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([r])=>s.has(r)));this.setState({projects:i,workspacesByProjectId:o})}catch(i){f(this.getState())===t&&this.setState({error:String(i)})}finally{f(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await z.addProject(t.trim(),void 0,i,f(this.getState())),o=this.getState().projects;this.setState({projects:[...o.filter(r=>r.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await z.closeProject(t,f(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const Ts="pi-web:cached-new-sessions:v1",jd="browserCachedNew",mt="local";function zt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function or(e,t=mt,i=zt()){if(e.messageCount!==0||e.archived===!0)return;const s=to(i).filter(o=>o.id!==e.id||o.machineId!==t);io([As(e,t),...s],i)}function As(e,t=mt){return{...e,browserCachedNew:!0,machineId:t}}function rr(e,t=mt,i=zt()){const s=to(i).filter(o=>o.id!==e||o.machineId!==t);io(s,i)}function Fd(e,t,i=mt,s=zt()){const o=new Set(t.map(c=>c.id)),r=to(s),n=r.filter(c=>c.machineId!==i||!o.has(c.id));return n.length!==r.length&&io(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function Z(e){return e===void 0?!1:Bd(e)&&e.browserCachedNew===!0}function Nd(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:mt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function to(e=zt()){try{const t=e?.getItem(Ts);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>zd(s)):[]}catch{return[]}}function io(e,t=zt()){try{e.length===0?t?.removeItem(Ts):t?.setItem(Ts,JSON.stringify(e))}catch{}}function zd(e){if(!Ud(e))return[];const t=at(e,"id"),i=at(e,"path"),s=at(e,"cwd"),o=at(e,"created"),r=at(e,"modified"),n=at(e,"firstMessage"),a=Hd(e,"messageCount");if(t===void 0||i===void 0||s===void 0||o===void 0||r===void 0||n===void 0||a!==0)return[];const c=os(e,"name"),p=os(e,"parentSessionPath"),u=os(e,"machineId")??mt;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:o,modified:r,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function Bd(e){return jd in e}function Ud(e){return typeof e=="object"&&e!==null}function at(e,t){const i=e[t];return typeof i=="string"?i:void 0}function os(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Hd(e,t){const i=e[t];return typeof i=="number"?i:void 0}function qd(e){return ap(e.flatMap(so)).filter(t=>t.parts.length>0)}function Me(e,t){return{role:e,parts:[{type:"text",text:t}]}}function xt(e,t){const i=Yd(t);return i===void 0?e:{...e,meta:i}}function Kd(e,t,i){if(i==="")return e;const s=e.at(-1),o=s?.parts.at(-1);return s?.role===t&&o?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...o,text:o.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,Me(t,i)]}function Vd(e,t){if(t==="")return e;const i=e.at(-1),s=i?.parts.at(-1);return i?.role==="assistant"&&s?.type==="thinking"?[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+t}]}]:i?.role==="assistant"?[...e.slice(0,-1),{...i,parts:[...i.parts,{type:"thinking",text:t}]}]:[...e,{role:"assistant",parts:[{type:"thinking",text:t}]}]}function so(e){if(Jd(e))return[e];if(O(e,"role")==="bashExecution")return[xt(ip(e),e)];const t=sp(O(e,"role")),i=op(fe(e,"content"),e),s=t==="user"?Qd(i):void 0;if(s!==void 0)return s.map(p=>xt(p,e));const o=Xd(e);if(t==="tool")return[xt({role:t,parts:i,...o===void 0?{}:{source:o}},e)];const r=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&r.length>0&&r.every(p=>p.type==="skillRead")?"skill":t,a=r.length>0?[xt({role:n,parts:r,...o===void 0?{}:{source:o}},e)]:[],c=Gd(e);return c===void 0?a:[...a,xt(c,e)]}function Gd(e){if(O(e,"role")!=="assistant"||O(e,"stopReason")!=="error")return;const t=O(e,"errorMessage")?.trim();return Me("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function Jd(e){const t=O(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(fe(e,"parts"))}function Qd(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Zd(e[0].text);if(t!==void 0)return[{role:"user",parts:[{type:"skillInvocation",name:t.name,location:t.location,content:t.content}]},...t.userMessage===void 0?[]:[{role:"user",parts:[{type:"text",text:t.userMessage}]}]]}function Zd(e){const t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;const i=t[4]?.trim();return{name:t[1]??"skill",location:t[2]??"",content:t[3]??"",...i===void 0||i===""?{}:{userMessage:i}}}function Xd(e){const t=O(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Yd(e){const t=ep(fe(e,"timestamp")),i=tp(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function ep(e){if(typeof e=="number"&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!="string"||e==="")return;const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function tp(e){if(O(e,"role")!=="assistant")return;const t=O(e,"provider"),i=O(e,"model"),s=O(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function ip(e){const t=O(e,"command")??"",i=ai(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=fe(e,"output");s!=null&&i.push("",vi(s));const o=fe(e,"exitCode");o!=null&&i.push("",`exit ${vi(o)}`),ai(e,"cancelled")===!0&&i.push("","cancelled"),ai(e,"truncated")===!0&&i.push("","output truncated");const r=O(e,"fullOutputPath");return r!==void 0&&r!==""&&i.push("",`full output: ${r}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
+ `)}]}}function sp(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function op(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=O(i,"type"),o=O(i,"text");if(s==="text")return o!==void 0&&o!==""?[{type:"text",text:o}]:[];if(s==="thinking"){const r=O(i,"thinking")??o;return r!==void 0&&r!==""?[{type:"thinking",text:r}]:[]}if(s==="toolCall"){const r=O(i,"name")??"tool",n=fe(i,"arguments"),a=O(i,"id"),c=r==="read"?np(O(n,"path")):void 0;return c!==void 0?[{type:"skillRead",...c,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:r,summary:Bt(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const r=O(i,"data"),n=O(i,"mimeType");return r!==void 0&&r!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:r}]:[{type:"text",text:"[image]"}]}return nr(i)}).map(i=>i.type==="text"&&O(t,"role")==="toolResult"?rp(i.text,t):i):nr(e)}function rp(e,t){const i=O(t,"toolCallId"),s=fe(t,"content"),o=fe(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:O(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...o===void 0?{}:{details:o},isError:ai(t,"isError")===!0}}function np(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function ap(e){const t=[],i=new Map;for(const s of e){let o=[];const r={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{o.length!==0&&(t.push({role:s.role,parts:o,...r}),o=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=lp(a),p=t.length;t.push({role:"tool",parts:[c],...r}),c.toolCallId!==void 0&&i.set(c.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const c=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(c!==void 0&&cp(t,c,a)){i.delete(a.toolCallId??"");continue}}o.push(a)}n()}return t}function lp(e){return{type:"toolExecution",...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.args===void 0?{}:{args:e.args},status:"pending"}}function cp(e,t,i){const s=e[t.lineIndex],o=s?.parts[t.partIndex];if(s===void 0||o?.type!=="toolExecution")return!1;const r=mi(i.details)??o.preview,n={...o,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...r===void 0?{}:{preview:r}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function mi(e){const t=fe(e,"preview");if(!oo(t))return;const i=O(t,"diff"),s=O(t,"error"),o=pp(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&o===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...o===void 0?{}:{firstChangedLine:o}}}function nr(e){return e==null?[]:typeof e=="object"?[{type:"text",text:Bt(e)}]:[{type:"text",text:vi(e)}]}function Bt(e){if(!oo(e))return vi(e);const t=O(e,"command");if(t!==void 0)return t;const i=O(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} edit${s.length===1?"":"s"}`:Object.entries(e).filter(([,r])=>r!=null).slice(0,3).map(([r,n])=>`${r}: ${dp(n)}`).join(" · ")}function dp(e){return typeof e=="string"?e.length>80?`${e.slice(0,77)}…`:e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?"":"s"}`:typeof e=="object"&&e!==null?"object":""}function oo(e){return typeof e=="object"&&e!==null}function fe(e,t){return oo(e)?e[t]:void 0}function O(e,t){const i=fe(e,t);return typeof i=="string"?i:void 0}function ai(e,t){const i=fe(e,t);return typeof i=="boolean"?i:void 0}function pp(e,t){const i=fe(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function vi(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const hp="pi-web:prompt-draft:";function bi(e){return`${hp}${e}`}function _i(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function zn(e,t=_i()){try{return t?.getItem(bi(e))??""}catch{return""}}function wi(e,t,i=_i()){try{t?i?.setItem(bi(e),t):i?.removeItem(bi(e))}catch{}}function ro(e,t=_i()){try{t?.removeItem(bi(e))}catch{}}function up(e,t,i=_i()){const s=zn(e,i);s!==""&&(wi(t,s,i),ro(e,i))}function fp(e,t){return Me("bash",`${t===!0?`不加入上下文
6
6
 
7
- `:""}$ ${e}`)}function fp(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Me("bash",t)];const o=mp(s.text)?"":`
7
+ `:""}$ ${e}`)}function gp(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Me("bash",t)];const o=vp(s.text)?"":`
8
8
 
9
- `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+o+t}]}]}function gp(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const o=[];return!s.text.includes(`
9
+ `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+o+t}]}]}function mp(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const o=[];return!s.text.includes(`
10
10
 
11
11
  `)&&(t.output===void 0||t.output==="")&&o.push("(no output)"),t.isError===!0&&o.push(t.output??"Bash 命令失败"),t.exitCode!=null&&o.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&o.push("cancelled"),t.truncated===!0&&o.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&o.push(`完整输出:${t.fullOutputPath}`),o.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
12
12
 
13
13
  ${o.join(`
14
- `)}`}]}]}function mp(e){const t=e.lastIndexOf(`
14
+ `)}`}]}]}function vp(e){const t=e.lastIndexOf(`
15
15
 
16
- `),i=e.lastIndexOf("$ ");return t>i}function vp(e,t){if(t.type==="message.append")return Mp(e,t.message);if(t.type==="assistant.delta")return qd(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return Kd(e,t.text);if(t.type==="tool.start")return xp(e,t);if(t.type==="tool.update")return Bn(e,t.toolCallId,i=>kp(i,t));if(t.type==="tool.end")return zn(e,t.toolCallId,t.toolName,zt(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,up(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return fp(e,t.chunk);if(t.type==="shell.end")return gp(e,t);if(t.type==="command.output")return[...e,Me(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,Me("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:bp(e,t.message)}function bp(e,t){const i=$p(t);if(i!==void 0)return zn(e,i.toolCallId,i.toolName,zt(i.content),i.text,i.isError,i.content,i.details);const s=io(t);if(s.length===0)return;const o=s.map(r=>r.role==="assistant"?yp(r):r).filter(r=>r.parts.length>0);return o.length===0?e:o.reduce((r,n)=>wp(r,n),e)}function wp(e,t){const i=Pp(e,t);if(i.length>0)return Rp(e,i,t);const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||Ap(s,t)?[...e.slice(0,-1),t]:[...e,t]}function yp(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function Sp(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function xp(e,t){const i=t.toolName==="read"?Sp(Qe(t.args,"path")):void 0;if(i!==void 0)return Ep(e,{role:"skill",parts:[{type:"skillRead",...i,...t.toolCallId===""?{}:{toolCallId:t.toolCallId}}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||zt(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function kp(e,t){const i=gi(t.details)??e.preview;return{...e,status:e.status==="pending"?"running":e.status,...t.text===""?{}:{resultText:t.text},...t.content===void 0?{}:{content:t.content},...t.details===void 0?{}:{details:t.details},...i===void 0?{}:{preview:i}}}function zn(e,t,i,s,o,r,n,a){const c=Bn(e,t,h=>{const g=gi(a)??h.preview;return{...h,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...g===void 0?{}:{preview:g}}});if(c!==e)return c;const p=gi(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function Bn(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const o=e[s];if(o===void 0)continue;const r=o.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(r<0)continue;const n=o.parts[r];if(n?.type!=="toolExecution")continue;const a={...o,parts:[...o.parts.slice(0,r),i(n),...o.parts.slice(r+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function $p(e){if(Qe(e,"role")!=="toolResult")return;const t=Qe(e,"toolCallId"),i=yi(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:Qe(e,"toolName")??"tool",text:Un(i),isError:_p(e,"isError")===!0,content:i,details:yi(e,"details")}}function Un(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Un).filter(t=>t!=="").join(`
17
- `);if(typeof e=="object"&&e!==null){const t=Qe(e,"text")??Qe(e,"content")??Qe(e,"output");if(t!==void 0)return t}return""}function Pp(e,t){const i=wi(t);if(i.length===0)return[];const s=[];let o=i.length;const r=qn(e)+1;for(let n=e.length-1;n>=r;n--){const a=wi(e[n]);if(a.length===0)continue;const c=o-a.length;if(!(c<0)&&Tp(a,i.slice(c,o))&&(s.unshift(n),o=c,o===0))return s}return[]}function Rp(e,t,i){const s=Ip(e,t,i),o=s[0];if(o===void 0)return e;const r=new Set(s),n=[];for(let a=0;a<e.length;a++){a===o&&n.push(i);const c=e[a];c!==void 0&&!r.has(a)&&n.push(c)}return n}function Ip(e,t,i){const s=t[0];if(i.role!=="assistant"||s===void 0)return t;const o=s-1;return Cp(e[o])?[o,...t]:t}function Cp(e){return e?.role==="assistant"&&e.parts.length>0&&e.parts.every(t=>t.type==="text"||t.type==="thinking")}function wi(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function Tp(e,t){return e.length===t.length&&e.every((i,s)=>Hn(i,t[s]))}function Hn(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:nr(e.path)===nr(t.path)||e.name===t.name}function nr(e){return e.replace(/\\/g,"/")}function Ap(e,t){return ar(e)===ar(t)}function ar(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
16
+ `),i=e.lastIndexOf("$ ");return t>i}function bp(e,t){if(t.type==="message.append")return Ep(e,t.message);if(t.type==="assistant.delta")return Kd(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return Vd(e,t.text);if(t.type==="tool.start")return kp(e,t);if(t.type==="tool.update")return Un(e,t.toolCallId,i=>$p(i,t));if(t.type==="tool.end")return Bn(e,t.toolCallId,t.toolName,Bt(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,fp(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return gp(e,t.chunk);if(t.type==="shell.end")return mp(e,t);if(t.type==="command.output")return[...e,Me(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,Me("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:wp(e,t.message)}function wp(e,t){const i=Pp(t);if(i!==void 0)return Bn(e,i.toolCallId,i.toolName,Bt(i.content),i.text,i.isError,i.content,i.details);const s=so(t);if(s.length===0)return;const o=s.map(r=>r.role==="assistant"?Sp(r):r).filter(r=>r.parts.length>0);return o.length===0?e:o.reduce((r,n)=>yp(r,n),e)}function yp(e,t){const i=Rp(e,t);if(i.length>0)return Ip(e,i,t);const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||Mp(s,t)?[...e.slice(0,-1),t]:[...e,t]}function Sp(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function xp(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function kp(e,t){const i=t.toolName==="read"?xp(Ze(t.args,"path")):void 0;if(i!==void 0)return Dp(e,{role:"skill",parts:[{type:"skillRead",...i,...t.toolCallId===""?{}:{toolCallId:t.toolCallId}}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||Bt(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function $p(e,t){const i=mi(t.details)??e.preview;return{...e,status:e.status==="pending"?"running":e.status,...t.text===""?{}:{resultText:t.text},...t.content===void 0?{}:{content:t.content},...t.details===void 0?{}:{details:t.details},...i===void 0?{}:{preview:i}}}function Bn(e,t,i,s,o,r,n,a){const c=Un(e,t,h=>{const g=mi(a)??h.preview;return{...h,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...g===void 0?{}:{preview:g}}});if(c!==e)return c;const p=mi(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function Un(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const o=e[s];if(o===void 0)continue;const r=o.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(r<0)continue;const n=o.parts[r];if(n?.type!=="toolExecution")continue;const a={...o,parts:[...o.parts.slice(0,r),i(n),...o.parts.slice(r+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function Pp(e){if(Ze(e,"role")!=="toolResult")return;const t=Ze(e,"toolCallId"),i=Si(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:Ze(e,"toolName")??"tool",text:Hn(i),isError:Lp(e,"isError")===!0,content:i,details:Si(e,"details")}}function Hn(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Hn).filter(t=>t!=="").join(`
17
+ `);if(typeof e=="object"&&e!==null){const t=Ze(e,"text")??Ze(e,"content")??Ze(e,"output");if(t!==void 0)return t}return""}function Rp(e,t){const i=yi(t);if(i.length===0)return[];const s=[];let o=i.length;const r=Kn(e)+1;for(let n=e.length-1;n>=r;n--){const a=yi(e[n]);if(a.length===0)continue;const c=o-a.length;if(!(c<0)&&Ap(a,i.slice(c,o))&&(s.unshift(n),o=c,o===0))return s}return[]}function Ip(e,t,i){const s=Cp(e,t,i),o=s[0];if(o===void 0)return e;const r=new Set(s),n=[];for(let a=0;a<e.length;a++){a===o&&n.push(i);const c=e[a];c!==void 0&&!r.has(a)&&n.push(c)}return n}function Cp(e,t,i){const s=t[0];if(i.role!=="assistant"||s===void 0)return t;const o=s-1;return Tp(e[o])?[o,...t]:t}function Tp(e){return e?.role==="assistant"&&e.parts.length>0&&e.parts.every(t=>t.type==="text"||t.type==="thinking")}function yi(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function Ap(e,t){return e.length===t.length&&e.every((i,s)=>qn(i,t[s]))}function qn(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:ar(e.path)===ar(t.path)||e.name===t.name}function ar(e){return e.replace(/\\/g,"/")}function Mp(e,t){return lr(e)===lr(t)}function lr(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
18
18
 
19
- `)}function Mp(e,t){const i=io(t);return i.length===0?e:[...e,...i]}function Ep(e,t){const i=e.at(-1);return Dp(e,t)?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Dp(e,t){const i=wi(t);if(t.role!=="skill"||i.length===0)return!1;const s=qn(e)+1;return i.every(o=>Wp(e,o,s))}function Wp(e,t,i){for(let s=e.length-1;s>=i;s--)if(wi(e[s]).some(o=>Hn(o,t)))return!0;return!1}function qn(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="user")return t;return-1}function Op(e){return typeof e=="object"&&e!==null}function yi(e,t){return Op(e)?e[t]:void 0}function Qe(e,t){const i=yi(e,t);return typeof i=="string"?i:void 0}function _p(e,t){const i=yi(e,t);return typeof i=="boolean"?i:void 0}const Lp="pi-web:chat-history:v2:",jp=1800*1e3;function Fp(e){try{const t=sessionStorage.getItem(Si(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!qp(i))return;if(Date.now()-i.savedAt>jp){sessionStorage.removeItem(Si(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function Np(e,t){try{sessionStorage.setItem(Si(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function zp(e){try{sessionStorage.removeItem(Si(e))}catch{}}function Bp(e,t){if(e===void 0||!As(e))return t;if(!As(t))return e;if(Up(e,t))return t;const i=Math.min(e.start,t.start),s=Math.max(e.start+e.messages.length,t.start+t.messages.length),o=new Array(s-i);return lr(o,i,e),lr(o,i,t),Hp(o)?t:{start:i,total:Math.max(e.total,t.total),messages:o}}function Up(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Hp(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function lr(e,t,i){i.messages.forEach((s,o)=>{e[i.start-t+o]=s})}function Si(e){return`${Lp}${e}`}function qp(e){if(typeof e!="object"||e===null||!("messages"in e)||!("start"in e)||!("total"in e)||!("savedAt"in e))return!1;const{messages:t,start:i,total:s,savedAt:o}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof o=="number"&&As({messages:t,start:i,total:s})}function As(e){return Number.isInteger(e.start)&&Number.isInteger(e.total)&&e.start>=0&&e.total>=e.start&&e.messages.length<=e.total-e.start&&!e.messages.some(Kp)}function Kp(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&!("content"in e)&&typeof e.role=="string"&&Array.isArray(e.parts)}const Vp={read:Fp,write:Np,remove:zp};class Gp{constructor(t=Vp){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return cr(this.rawHistoryPage(t))}mergeHistory(t,i){const s=Bp(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),cr(s)}applyLiveEvent(t,i){return vp(t,i)}discard(t){this.rawHistoryPages.delete(t),this.cache.remove?.(t)}rawHistoryPage(t){const i=this.rawHistoryPages.get(t)??this.cache.read(t);return i!==void 0&&this.rawHistoryPages.set(t,i),i}}function cr(e){const t=e?.start??0;return{messages:Hd(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Kn(e,t=e.length){const i=e.slice(0,t),s=Jp(i,t);if(s!==void 0)return s;const o=Qp(i,t);if(o!==void 0)return o;const r=Math.max(i.lastIndexOf(" "),i.lastIndexOf(`
20
- `))+1,n=i.slice(r);if(i.slice(0,r).endsWith("@ "))return{kind:"file",query:n,from:r-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&r===0)return{kind:"command",query:n.slice(1),from:r,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:r,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:r,to:t,fileScope:"tracked"}}function Vn(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Jp(e,t){const i=e.lastIndexOf('"');if(i===-1)return;const s=e.slice(0,i);if(s.endsWith("!@"))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"!@",quoted:!0};if(s.endsWith("@"))return{kind:"file",query:e.slice(i+1),from:s.length-1,to:t,fileScope:"tracked",quoted:!0};if(s.endsWith("@ "))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"@ ",quoted:!0}}function Qp(e,t){const i=e.lastIndexOf(`
21
- `)+1,s=e.slice(i),o=dr(s,"@ "),r=dr(s,"!@"),n=Math.max(o,r);if(n===-1)return;const a=n===r?"!@":"@ ",c=i+n,p=c+a.length;return{kind:"file",query:e.slice(p),from:c,to:t,fileScope:"all",allPrefix:a}}function dr(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||Zp(e[i-1]))return i;return-1}function Zp(e){return e===" "||e===" "}function ro(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Yp(e).startsWith("/")?{kind:"command"}:Kn(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function Xp(e){return ro(e).kind==="shell"}function Yp(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
- `))+1;return e.slice(t)}class eh{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,o="local"){this.close(),this.machineId=o,this.session=t,this.onEvent=i,this.onReconnect=s,this.shouldReconnect=!0,this.open()}setHandler(t){this.onEvent=t}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Jn(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.session===void 0||this.session.id===""||this.session.cwd===""||!this.shouldReconnect)return;const t=wd(this.session,this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Gn(t);th(i)&&this.onEvent?.(i)}}class pr{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Jn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=yd(this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Gn(t);sh(i)&&this.onEvent?.(i)}}function th(e){const t=no(e);return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","agent.start","agent.end","message.end","status.update","activity.update","command.output","session.error","session.name","session.created","pi.event"].includes(t)}function ih(e){const t=no(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function sh(e){const t=no(e);return ih(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function no(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Gn(e){try{return typeof e=="string"?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function Jn(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}function Bt(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class _i{constructor(t,i,s=Bt()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[o,r]of oh(t,i,s))this.values.set(o,r)}get(t){return this.values.get(t)}set(t,i){this.values.set(t,i),this.save()}delete(t){this.values.delete(t),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}const t={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(t))}catch{}}}function ao(e){return typeof e=="string"&&e!==""?e:void 0}function oh(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const o=JSON.parse(s);if(!rh(o))return[];const r=[];for(const n of o.entries){const a=n[0],c=t(n[1]);c!==void 0&&r.push([a,c])}return r}catch{return[]}}function rh(e){return!nh(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string"&&t[0]!=="")}function nh(e){return typeof e=="object"&&e!==null}class ah{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}const lh="pi-web:session-selection:v1";class ch{constructor(t=Bt()){this.sessionIdsByCwd=new _i(lh,ao,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function dh(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return hh(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>o.archived!==!0):e.find(o=>o.archived!==!0)}function ph(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function hh(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function uh(e,t,i){return Ms(e,[t],i)}function Ms(e,t,i){const s=new Set(t);return e.map(o=>s.has(o.id)?{...o,archived:!0,archivedAt:i}:o)}function fh(e,t,i){return Es(e,t,[i])}function Es(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),o=e.find(r=>!s.has(r.id)&&r.archived!==!0);return o===void 0?{type:"clear"}:{type:"select",session:o}}const xt=100;class gh{constructor(t,i,s,o=new ah,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=o,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=r.socket??new eh,this.api=r.api??z,this.transcripts=r.transcripts??new Gp}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0,availableThinkingLevels:[]})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();ph(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=f(this.getState()),s=await this.api.startSession(t.path,i);sr(s,i);const o=Ts(s,i);this.setState({sessions:[o,...this.getState().sessions.filter(r=>r.id!==o.id)]}),await this.selectSession(o)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return dh(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const o=this.sessionCacheKey(t.id),r=this.transcripts.cachedView(o);this.setState({selectedSession:t,...r,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const u=await this.api.messages(t,{limit:xt},f(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(o,u);this.setState({...h,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t,u=>n.push(u),()=>{this.refreshSelectedSession(t.id)},f(this.getState()));const[a,c]=await Promise.all([this.api.messages(t,{limit:xt},f(this.getState())),this.api.status(t,f(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(o,a);this.setState({...p,isLoadingEarlierMessages:!1,...this.setStreamCatchup(c.isStreaming?t.id:void 0),status:c,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(c),this.refreshAvailableThinkingLevels();for(const u of n)this.applyEvent(u);this.socket.setHandler(u=>{this.applyEvent(u)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(Z(t)&&$h(n)){await this.recreateCachedNewSession(t,i);return}this.setState({error:String(n)})}}async loadEarlierMessages(){const t=this.getState(),i=t.selectedSession;if(!(!i||t.isLoadingEarlierMessages||t.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{const s=await this.api.messages(i,{before:t.messagePageStart,limit:xt},f(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(o)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i,s,o="inline"){const r=t.trim(),n=s!==void 0&&s.length>0;if(!n&&r.startsWith("/"))return this.runCommand(t);if(!n&&Xp(t))return this.runShell(t);const a=this.getState().selectedSession;if(!a||a.archived===!0)return;const c=a.id,p=f(this.getState());n&&this.markSendingPrompt(c,!0);try{if(n&&o==="folder"){const h=(await this.api.saveAttachments(a,s,p)).map(w=>Vn(w.path,!1)).join(" "),g=t===""?h:`${t}
19
+ `)}function Ep(e,t){const i=so(t);return i.length===0?e:[...e,...i]}function Dp(e,t){const i=e.at(-1);return Wp(e,t)?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Wp(e,t){const i=yi(t);if(t.role!=="skill"||i.length===0)return!1;const s=Kn(e)+1;return i.every(o=>Op(e,o,s))}function Op(e,t,i){for(let s=e.length-1;s>=i;s--)if(yi(e[s]).some(o=>qn(o,t)))return!0;return!1}function Kn(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="user")return t;return-1}function _p(e){return typeof e=="object"&&e!==null}function Si(e,t){return _p(e)?e[t]:void 0}function Ze(e,t){const i=Si(e,t);return typeof i=="string"?i:void 0}function Lp(e,t){const i=Si(e,t);return typeof i=="boolean"?i:void 0}const jp="pi-web:chat-history:v2:",Fp=1800*1e3;function Np(e){try{const t=sessionStorage.getItem(xi(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!Kp(i))return;if(Date.now()-i.savedAt>Fp){sessionStorage.removeItem(xi(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function zp(e,t){try{sessionStorage.setItem(xi(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Bp(e){try{sessionStorage.removeItem(xi(e))}catch{}}function Up(e,t){if(e===void 0||!Ms(e))return t;if(!Ms(t))return e;if(Hp(e,t))return t;const i=Math.min(e.start,t.start),s=Math.max(e.start+e.messages.length,t.start+t.messages.length),o=new Array(s-i);return cr(o,i,e),cr(o,i,t),qp(o)?t:{start:i,total:Math.max(e.total,t.total),messages:o}}function Hp(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function qp(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function cr(e,t,i){i.messages.forEach((s,o)=>{e[i.start-t+o]=s})}function xi(e){return`${jp}${e}`}function Kp(e){if(typeof e!="object"||e===null||!("messages"in e)||!("start"in e)||!("total"in e)||!("savedAt"in e))return!1;const{messages:t,start:i,total:s,savedAt:o}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof o=="number"&&Ms({messages:t,start:i,total:s})}function Ms(e){return Number.isInteger(e.start)&&Number.isInteger(e.total)&&e.start>=0&&e.total>=e.start&&e.messages.length<=e.total-e.start&&!e.messages.some(Vp)}function Vp(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&!("content"in e)&&typeof e.role=="string"&&Array.isArray(e.parts)}const Gp={read:Np,write:zp,remove:Bp};class Jp{constructor(t=Gp){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return dr(this.rawHistoryPage(t))}mergeHistory(t,i){const s=Up(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),dr(s)}applyLiveEvent(t,i){return bp(t,i)}discard(t){this.rawHistoryPages.delete(t),this.cache.remove?.(t)}rawHistoryPage(t){const i=this.rawHistoryPages.get(t)??this.cache.read(t);return i!==void 0&&this.rawHistoryPages.set(t,i),i}}function dr(e){const t=e?.start??0;return{messages:qd(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Vn(e,t=e.length){const i=e.slice(0,t),s=Qp(i,t);if(s!==void 0)return s;const o=Zp(i,t);if(o!==void 0)return o;const r=Math.max(i.lastIndexOf(" "),i.lastIndexOf(`
20
+ `))+1,n=i.slice(r);if(i.slice(0,r).endsWith("@ "))return{kind:"file",query:n,from:r-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&r===0)return{kind:"command",query:n.slice(1),from:r,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:r,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:r,to:t,fileScope:"tracked"}}function Gn(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Qp(e,t){const i=e.lastIndexOf('"');if(i===-1)return;const s=e.slice(0,i);if(s.endsWith("!@"))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"!@",quoted:!0};if(s.endsWith("@"))return{kind:"file",query:e.slice(i+1),from:s.length-1,to:t,fileScope:"tracked",quoted:!0};if(s.endsWith("@ "))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"@ ",quoted:!0}}function Zp(e,t){const i=e.lastIndexOf(`
21
+ `)+1,s=e.slice(i),o=pr(s,"@ "),r=pr(s,"!@"),n=Math.max(o,r);if(n===-1)return;const a=n===r?"!@":"@ ",c=i+n,p=c+a.length;return{kind:"file",query:e.slice(p),from:c,to:t,fileScope:"all",allPrefix:a}}function pr(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||Xp(e[i-1]))return i;return-1}function Xp(e){return e===" "||e===" "}function no(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:eh(e).startsWith("/")?{kind:"command"}:Vn(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function Yp(e){return no(e).kind==="shell"}function eh(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
+ `))+1;return e.slice(t)}class th{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,o="local"){this.close(),this.machineId=o,this.session=t,this.onEvent=i,this.onReconnect=s,this.shouldReconnect=!0,this.open()}setHandler(t){this.onEvent=t}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Qn(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.session===void 0||this.session.id===""||this.session.cwd===""||!this.shouldReconnect)return;const t=yd(this.session,this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Jn(t);ih(i)&&this.onEvent?.(i)}}class hr{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Qn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Sd(this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Jn(t);oh(i)&&this.onEvent?.(i)}}function ih(e){const t=ao(e);return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","agent.start","agent.end","message.end","status.update","activity.update","command.output","session.error","session.name","session.created","pi.event"].includes(t)}function sh(e){const t=ao(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function oh(e){const t=ao(e);return sh(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function ao(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Jn(e){try{return typeof e=="string"?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function Qn(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}function Ut(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class Li{constructor(t,i,s=Ut()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[o,r]of rh(t,i,s))this.values.set(o,r)}get(t){return this.values.get(t)}set(t,i){this.values.set(t,i),this.save()}delete(t){this.values.delete(t),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}const t={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(t))}catch{}}}function lo(e){return typeof e=="string"&&e!==""?e:void 0}function rh(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const o=JSON.parse(s);if(!nh(o))return[];const r=[];for(const n of o.entries){const a=n[0],c=t(n[1]);c!==void 0&&r.push([a,c])}return r}catch{return[]}}function nh(e){return!ah(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string"&&t[0]!=="")}function ah(e){return typeof e=="object"&&e!==null}class lh{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}const ch="pi-web:session-selection:v1";class dh{constructor(t=Ut()){this.sessionIdsByCwd=new Li(ch,lo,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function ph(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return uh(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>o.archived!==!0):e.find(o=>o.archived!==!0)}function hh(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function uh(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function fh(e,t,i){return Es(e,[t],i)}function Es(e,t,i){const s=new Set(t);return e.map(o=>s.has(o.id)?{...o,archived:!0,archivedAt:i}:o)}function gh(e,t,i){return Ds(e,t,[i])}function Ds(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),o=e.find(r=>!s.has(r.id)&&r.archived!==!0);return o===void 0?{type:"clear"}:{type:"select",session:o}}const kt=100;class mh{constructor(t,i,s,o=new lh,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=o,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=r.socket??new th,this.api=r.api??z,this.transcripts=r.transcripts??new Jp}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0,availableThinkingLevels:[]})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();hh(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=f(this.getState()),s=await this.api.startSession(t.path,i);or(s,i);const o=As(s,i);this.setState({sessions:[o,...this.getState().sessions.filter(r=>r.id!==o.id)]}),await this.selectSession(o)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return ph(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const o=this.sessionCacheKey(t.id),r=this.transcripts.cachedView(o);this.setState({selectedSession:t,...r,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const u=await this.api.messages(t,{limit:kt},f(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(o,u);this.setState({...h,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t,u=>n.push(u),()=>{this.refreshSelectedSession(t.id)},f(this.getState()));const[a,c]=await Promise.all([this.api.messages(t,{limit:kt},f(this.getState())),this.api.status(t,f(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(o,a);this.setState({...p,isLoadingEarlierMessages:!1,...this.setStreamCatchup(c.isStreaming?t.id:void 0),status:c,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(c),this.refreshAvailableThinkingLevels();for(const u of n)this.applyEvent(u);this.socket.setHandler(u=>{this.applyEvent(u)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(Z(t)&&Ph(n)){await this.recreateCachedNewSession(t,i);return}this.setState({error:String(n)})}}async loadEarlierMessages(){const t=this.getState(),i=t.selectedSession;if(!(!i||t.isLoadingEarlierMessages||t.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{const s=await this.api.messages(i,{before:t.messagePageStart,limit:kt},f(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(o)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i,s,o="inline"){const r=t.trim(),n=s!==void 0&&s.length>0;if(!n&&r.startsWith("/"))return this.runCommand(t);if(!n&&Yp(t))return this.runShell(t);const a=this.getState().selectedSession;if(!a||a.archived===!0)return;const c=a.id,p=f(this.getState());n&&this.markSendingPrompt(c,!0);try{if(n&&o==="folder"){const h=(await this.api.saveAttachments(a,s,p)).map(b=>Gn(b.path,!1)).join(" "),g=t===""?h:`${t}
23
23
 
24
- ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.markCachedNewSessionPersisted(a)}catch(u){this.setState({error:String(u)})}finally{n&&this.markSendingPrompt(c,!1)}}markSendingPrompt(t,i){const s=this.getState().sendingPrompts;i?s[t]!==!0&&this.setState({sendingPrompts:{...s,[t]:!0}}):t in s&&this.setState({sendingPrompts:Qn(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Me("user",t)]});try{await this.api.shell(i,t,f(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Me("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!i||i.archived===!0)return;const s=i.id;this.markSendingPrompt(s,!0);try{this.applyCommandResult(await this.api.runCommand(i,t,f(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(o){this.setState({messages:[...this.getState().messages,Me("system",String(o))],error:String(o)})}finally{this.markSendingPrompt(s,!1)}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s,t,i,f(this.getState())))}catch(o){this.setState({error:String(o)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(Z(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,f(this.getState()));const i=this.getState(),s=uh(i.sessions,t.id,new Date().toISOString()),o=fh(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),o.type==="select"?await this.selectSession(o.session):o.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||Z(t)))try{const i=await this.api.archiveWithDescendants(t,f(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],o=this.getState(),r=Ms(o.sessions,s,new Date().toISOString()),n=Es(r,o.selectedSession?.id,s);this.setState({sessions:r}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async archiveSessions(t){const i=hr(t).filter(n=>n.archived!==!0&&!Z(n));if(i.length===0)return;const s=f(this.getState()),o=await Promise.allSettled(i.map(async n=>(await this.api.archive(n,s),n.id))),r=ur(o);if(r.length>0){const n=this.getState(),a=Ms(n.sessions,r,new Date().toISOString()),c=Es(a,n.selectedSession?.id,r);this.setState({sessions:a}),c.type==="select"?await this.selectSession(c.session):c.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionError("Archive",o)}async deleteArchivedSessions(t){const i=hr(t).filter(a=>a.archived===!0);if(i.length===0)return;const s=f(this.getState()),o=this.getState().machineRuntimes[s];if(o?.ok!==!0||!_t(o,ht.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}const r=await Promise.allSettled(i.map(async a=>(await this.api.deleteArchived(a,s),a.id))),n=ur(r);if(n.length>0){const a=new Set(n),c=this.getState(),p=c.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),c.selectedSession!==void 0&&a.has(c.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionError("Delete",r)}async deleteCachedNewSession(t=this.getState().selectedSession){if(!Z(t))return;this.api.stop(t,f(this.getState())).catch(()=>{}),or(t.id,f(this.getState())),oo(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(o=>o.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(o=>o.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t,f(this.getState()));const i={...t};delete i.archived,delete i.archivedAt,this.replaceSession(i),this.getState().selectedSession?.id===i.id&&await this.selectSession(i)}catch(i){this.setState({error:String(i)})}}async reloadSession(t=this.getState().selectedSession){if(t===void 0||Z(t)||t.archived===!0)return;const i=f(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!_t(s,ht.sessionsReload)){this.setState({error:"Reloading sessions requires an updated Pi-Web runtime on this machine."});return}try{await this.api.reloadSession(t.id,i),this.transcripts.discard(this.sessionCacheKey(t.id)),this.getState().selectedSession?.id===t.id&&await this.selectSession(t,{updateUrl:!1})}catch(o){this.setState({error:String(o)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t,f(this.getState()));const i={...t};delete i.parentSessionPath,this.replaceSession(i)}catch(i){this.setState({error:String(i)})}}async listModels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.models(t,f(this.getState()))).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s,t,i,f(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(o){this.setState({error:String(o)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,f(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(s){this.setState({error:String(s)})}}async listThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.thinkingLevels(t,f(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async refreshAvailableThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}const i=await this.listThinkingLevels();this.getState().selectedSession?.id===t.id&&this.setState({availableThinkingLevels:i})}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i,t,f(this.getState())))}catch(s){this.setState({error:String(s)})}}async cycleThinkingLevel(){const t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(t,f(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,f(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingTranscriptEvents();const[s,o]=await Promise.all([this.api.messages(i,{limit:xt},f(this.getState())),this.api.status(i,f(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...r,status:o,activity:this.getState().sessionActivities[t],...this.setStreamCatchup(o.isStreaming?t:void 0)}),this.applyStatus(o)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionError(t,i){const s=vh(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return jn(f(this.getState()),t)}workspaceSelectionKey(t){return`${f(this.getState())}:${t}`}replaceSession(t){const i=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s=>s.id===t.id?t:s),selectedSession:i?.id===t.id?t:i})}async recreateCachedNewSession(t,i){try{const s=f(this.getState()),o=await this.api.startSession(t.cwd,s);sr(o,s),hp(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),or(t.id,s);const r=Ts(o,s);this.setState({sessions:[r,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(r,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!Z(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Fd(i))}applyCommandResult(t){if(t.type==="select"){this.setState({commandDialog:t});return}const i=(t.type==="unsupported",t.message);if(i!==void 0&&i!==""&&this.setState({messages:[...this.getState().messages,Me(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&bi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,o=[t.session,...this.getState().sessions.filter(r=>r.id!==t.session?.id)];this.setState({sessions:o,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();i.selectedWorkspace?.path===t.cwd&&(i.sessions.some(s=>s.id===t.id)||this.setState({sessions:[t,...i.sessions]}))}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Xe(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...Sh(i,t.sessionId,t.messageCount),...s?{sessionActivities:mh(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),t.isStreaming||this.finishStreamCatchup(t.sessionId)}applySessionName(t,i){const s=r=>{if(r.id!==t)return r;const n={...r};return i===void 0||i===""?delete n.name:n.name=i,n},o=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:o===void 0?void 0:s(o)})}applyEvent(t){const i=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===i){if(t.type==="message.end"||t.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(xh(t))return}if(kh(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}setStreamCatchup(t){return this.catchupStreamSessionId=t,{isReceivingPartialStream:t!==void 0}}finishStreamCatchup(t){const i=this.getState().selectedSession?.id===t;(this.catchupStreamSessionId===t||i&&this.getState().isReceivingPartialStream)&&(this.catchupStreamSessionId=void 0,i&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:xt},f(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),s))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function mh(e,t){return Qn(e,t)}function Qn(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function hr(e){const t=new Set,i=[];for(const s of e)t.has(s.id)||(t.add(s.id),i.push(s));return i}function ur(e){return e.filter(bh).map(t=>t.value)}function vh(e){return e.filter(wh).map(t=>yh(t.reason))}function bh(e){return e.status==="fulfilled"}function wh(e){return e.status==="rejected"}function yh(e){return e instanceof Error?e.message:String(e)}function Sh(e,t,i){if(i===void 0)return{};const o=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,r=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...o===void 0?{}:{sessions:o},...r!==e.selectedSession?{selectedSession:r}:{}}}function xh(e){return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","command.output","session.error"].includes(e.type)}function kh(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function $h(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class Ph{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}const Rh="pi-web:workspace-selection:v1";class Ih{constructor(t=Bt()){this.workspaceIdsByProject=new _i(Rh,ao,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function Ch(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e[0]:e[0]}class Th{constructor(t,i,s,o,r=new Ph,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??z}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...ri()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Yi(f(this.getState()),t));const i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([s])=>s!==t));this.setState({workspacesByProjectId:i})}async selectProject(t,i){const s=f(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...ri()});try{const o=await this.api.workspaces(t.id,s);if(f(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:o,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:o},isLoadingWorkspaces:!1});const r=Ch(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Yi(s,t.id))});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){f(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(o),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=f(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:Yi(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...ri()});try{const o=jd(t.path,await this.api.sessions(t.path,s),s);if(f(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:o});const r=this.sessions.preferredSession(t.path,o,i?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){f(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(o)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(o=>o.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,f(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),o=this.getState();if(o.selectedProject?.id!==t||o.selectedWorkspace?.id!==i)return;const r=Mh(s);r!==void 0?await this.selectWorkspace(r):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),o={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:o}):this.setState({workspacesByProjectId:o})}}function Ah(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function Mh(e){return e.find(t=>t.isMain)??e[0]}const Eh="pi-web:machine-navigation:v1";class Dh{constructor(t=Bt()){this.snapshotsByMachine=new _i(Eh,Oh,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?mr(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,mr(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Wh(e){return{machineId:e,surface:{}}}function fr(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??Ln,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,tool:e.workspaceTool,view:e.mainView,surface:{selectedFilePath:t?e.selectedFilePath:void 0,selectedDiffPath:t?e.selectedDiffPath:void 0,selectedTerminalId:t?e.selectedTerminalId:void 0}}}function gr(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view==="navigation"?void 0:e.view}}function mr(e){return{...e,surface:{...e.surface}}}function Oh(e){if(!Xn(e))return;const t=_e(e,"machineId");if(t===void 0)return;const i=Zn(_e(e,"tool")),s=Lh(_e(e,"view"));return{machineId:t,projectId:_e(e,"projectId"),workspaceId:_e(e,"workspaceId"),sessionId:_e(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:_h(e.surface)}}function _h(e){return Xn(e)?{selectedFilePath:_e(e,"selectedFilePath"),selectedDiffPath:_e(e,"selectedDiffPath"),selectedTerminalId:_e(e,"selectedTerminalId")}:{}}function Lh(e){return e==="navigation"||e==="chat"?e:Zn(e)}function Zn(e){return jh(e)?e:void 0}function jh(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function _e(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Xn(e){return typeof e=="object"&&e!==null}const Fh="pi-web:terminal-selection:v1";class Nh{constructor(t=Bt()){this.terminalIdsByCwd=new _i(Fh,ao,t)}latestTerminalId(t){return this.terminalIdsByCwd.get(t)}rememberTerminal(t,i){this.terminalIdsByCwd.set(t,i)}forgetWorkspace(t){this.terminalIdsByCwd.delete(t)}forgetTerminal(t){for(const[i,s]of this.terminalIdsByCwd.entries())s===t&&this.terminalIdsByCwd.delete(i)}}function ny(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>!o.exited)??e[0]:e.find(o=>!o.exited)??e[0]}function ay(e){return e.find(t=>!t.exited)??e[0]}const Yn=1200,zh=["mod","alt","shift"];class Bh{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=ta(t);if(o===void 0)return!1;const r=lo(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,o],r))return!0;if(this.clearPending(),!Lt(o))return!1}else if(!Lt(o))return!1;return this.handleSequence([o],r)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(r=>Xh(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>co(r.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Yn)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function lo(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Uh(p,t,u);return h===void 0?[]:[h]}),o=new Map;for(const p of s)o.set(p.key,[...o.get(p.key)??[],p]);const r=new Map;for(const p of o.values()){const u=[...p].sort(Ds)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort(Kh),a=new Map,c=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=Vh(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,g=u===void 0||h?void 0:vr(u),w=h?[...a.get(p)??[]].sort(Ds).map(vr):[];return{...p,active:h,shadows:w,...g===void 0?{}:{shadowedBy:g}}}).sort((p,u)=>p.order-u.order)}function os(e){return ia(e,{requireFirstChordActivator:!0})}function ea(e){const t=ia(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function ai(e){return ea(e).map(t=>t.split("+").map(oa).join("+")).join(" ")}function ta(e){if(e.isComposing)return;const t=Qh(e.key);if(t===void 0)return;const i=[];return(e.metaKey||e.ctrlKey)&&i.push("mod"),e.altKey&&i.push("alt"),e.shiftKey&&i.push("shift"),i.push(t),i.join("+")}function Lt(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Uh(e,t,i){const s=Hh(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=ea(o),n=r[0];if(!(n===void 0||!Lt(n)))return{action:e,shortcut:r.join(" "),source:s===void 0?"default":"custom",tokens:r,key:qh(r),order:i}}function Hh(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function qh(e){return e.join("\0")}function vr(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Ds(e,t){return br(e.source)-br(t.source)||wr(e.action.id,t.action.id)||wr(e.action.title,t.action.title)||e.order-t.order}function Kh(e,t){return e.tokens.length-t.tokens.length||Ds(e,t)}function Vh(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&co(e.tokens,i.tokens))}function br(e){switch(e){case"custom":return 0;case"default":return 1}}function wr(e,t){return e<t?-1:e>t?1:0}function ia(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"请输入快捷键,选择无,或重置为默认值。"};const s=[],o=i.split(/\s+/u).filter(r=>r!=="");for(const[r,n]of o.entries()){const a=Gh(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!Lt(a.token))return{ok:!1,message:"快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。"};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Gh(e){const t=e.split("+").filter(r=>r!=="");if(t.length===0)return{ok:!1,message:"快捷键组合必须包含一个按键。"};const i=new Set;let s;for(const r of t){const n=Jh(r);if(n!==void 0){if(i.has(n))return{ok:!1,message:`快捷键包含重复的 ${oa(n)} 修饰键。`};i.add(n);continue}const a=sa(r);if(a===void 0)return{ok:!1,message:`不支持的快捷键按键:${r}`};if(s!==void 0)return{ok:!1,message:"每个快捷键组合只能包含一个非修饰键。"};s=a}return s===void 0?{ok:!1,message:"快捷键组合必须包含一个按键。"}:{ok:!0,token:[...zh.filter(r=>i.has(r)),s].join("+")}}function Jh(e){switch(e){case"mod":case"meta":case"cmd":case"command":case"ctrl":case"control":case"primary":return"mod";case"alt":case"option":case"opt":return"alt";case"shift":return"shift";default:return}}function sa(e){const t=Zh(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function Qh(e){if(e===" ")return"space";const t=e.toLowerCase();return sa(t)}function Zh(e){switch(e){case" ":case"spacebar":case"space":return"space";case"esc":case"escape":return"escape";case"return":case"enter":return"enter";case"del":case"delete":return"delete";case"backspace":return"backspace";case"tab":return"tab";case"up":case"arrowup":return"arrowup";case"down":case"arrowdown":return"arrowdown";case"left":case"arrowleft":return"arrowleft";case"right":case"arrowright":return"arrowright";case"pageup":case"pagedown":case"home":case"end":return e;case"+":case"plus":return"plus";case"period":case"dot":return".";case"comma":return",";case"slash":return"/";case"backslash":return"\\";case"minus":return"-";default:return}}function oa(e){return e==="mod"?yr()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?yr()?"⌥":"Alt":e==="enter"?"Enter":e==="escape"?"Esc":e==="space"?"Space":e==="tab"?"Tab":e==="backspace"?"Backspace":e==="delete"?"Delete":e==="arrowup"?"↑":e==="arrowdown"?"↓":e==="arrowleft"?"←":e==="arrowright"?"→":e==="pageup"?"PageUp":e==="pagedown"?"PageDown":e==="home"?"Home":e==="end"?"End":e==="plus"?"+":/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function Xh(e,t){return e.length===t.length&&co(e,t)}function co(e,t){return t.every((i,s)=>e[s]===i)}function yr(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const po="themes:classic",Yh="themes:pi-web-dark",eu={themeId:Yh,auto:!0},ra="pi-web-app-theme",tu=["--pi-bg","--pi-surface","--pi-surface-hover","--pi-terminal-bg","--pi-terminal-text","--pi-border","--pi-border-muted","--pi-text","--pi-text-secondary","--pi-text-bright","--pi-muted","--pi-dim","--pi-accent","--pi-accent-border","--pi-selection-bg","--pi-success","--pi-success-border","--pi-success-bg","--pi-success-surface","--pi-success-ring","--pi-warning","--pi-warning-border","--pi-warning-surface","--pi-danger","--pi-purple","--pi-purple-border","--pi-purple-surface","--pi-overlay","--pi-shadow-soft","--pi-shadow","--pi-shadow-strong","--pi-bg-overlay-soft","--pi-bg-overlay","--pi-success-bg-overlay","--pi-terminal-selection"],iu=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function su(){try{const e=window.localStorage.getItem(ra);return e===null?void 0:lu(e)}catch{return}}function ou(e){try{window.localStorage.setItem(ra,JSON.stringify(e))}catch{}}function ru(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of tu){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function nu(e){const t=au(e.themes,e.fallbackThemeId??po),i=e.themes.find(n=>n.id===e.preference.themeId)??t;if(i===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};const s=na(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const o=e.prefersLight?s.light:s.dark,r=e.themes.find(n=>n.id===o)??i;return{selectedTheme:i,activeTheme:r,selectedThemePair:s,fallbackTheme:t}}function au(e,t=po){return e.find(i=>i.id===t)??e[0]}function na(e,t){return e.find(i=>i.light===t||i.dark===t)}function lu(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return cu(i)?i:void 0}catch{return}}function cu(e){if(!du(e))return!1;const t=e.themeId,i=e.auto;return pu(t)&&typeof i=="boolean"}function du(e){return typeof e=="object"&&e!==null}function pu(e){return typeof e=="string"&&iu.test(e)}const hu="management";function uu(e){return fu(gu())===hu}function fu(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function gu(){return typeof window>"u"?void 0:window.location.search}const mu="workspace.delete",vu="pi.operation",bu="target.workspaceId";function wu(e){return{...e===void 0?{}:{projectId:e},metadata:{[vu]:mu}}}function yu(e){const t={};for(const i of e){const s=Ws(i);if(s===void 0)continue;const o=t[s];(o===void 0||i.createdAt.localeCompare(o.createdAt)>=0)&&(t[s]=i)}return t}function Su(e){return Object.entries(e).filter(([,t])=>xi(t)).map(([t])=>t)}function aa(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&xi(i)}function Ws(e){return e.metadata[bu]}function xi(e){return e.status==="queued"||e.status==="running"}function Sr(){return[{id:"actions.show",title:"显示操作",description:"打开命令面板",shortcut:"mod+k",group:"通用",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"聚焦提示词输入框",description:"将键盘焦点移动到消息编辑器",shortcut:"mod+g c",group:"通用",enabled:e=>e.state.selectedSession!==void 0,run:e=>{e.focusPrompt()}},{id:"machine.add",title:"添加机器",description:"注册另一个可从当前网关访问的 PI WEB 运行时",group:"机器",run:e=>e.addMachine()},{id:"machine.refresh",title:"刷新所选机器",description:"检查所选 PI WEB 运行时是否在线",group:"机器",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"打开所选机器的 PI WEB",description:"在新标签页中直接打开所选远程 PI WEB",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"移除所选机器",description:"从当前网关移除所选远程机器",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{id:"project.add",title:"添加项目",group:"项目",run:e=>e.addProject()},{id:"auth.login",title:"配置提供商认证",description:"运行 /login,但不将认证绑定到某个会话",group:"通用",run:e=>e.configureAuth()},{id:"auth.logout",title:"移除提供商认证",description:"针对已保存的 pi 凭据运行 /logout",group:"通用",run:e=>e.logoutAuth()},{id:"theme.select",title:"选择主题",description:"选择 PI WEB 颜色主题",group:"偏好设置",run:e=>{e.openThemePicker()}},{id:"settings.open",title:"打开设置",description:"管理 PI WEB 配置和键盘快捷键",shortcut:"mod+,",group:"偏好设置",run:e=>{e.piWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"完整重载页面",description:"重新加载 PI WEB 浏览器页面",group:"通用",run:e=>{e.reloadPage()}},{id:"view.chat",title:"转到聊天",shortcut:"mod+1",group:"导航",run:e=>{e.focusPrompt()}},{id:"view.files",title:"转到文件",shortcut:"mod+2",group:"导航",enabled:kt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:xr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:kt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:kt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:xr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:kt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"删除工作区",description:"移除所选 Git worktree",group:"工作区",enabled:xu,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:kt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:ku,run:e=>e.archiveSession()},{id:"session.reload",title:"重新加载会话",description:"从磁盘重新读取所选会话,以获取其他进程写入的条目",group:"会话",enabled:Pu,run:e=>e.reloadSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:$u,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&Xe(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function kt(e){return e.state.selectedWorkspace!==void 0}function xr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function xu(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!aa(e.state,t)}function ku(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!Z(t)}function $u(e){return Z(e.state.selectedSession)}function Pu(e){const t=e.state.selectedSession;if(t===void 0||t.archived===!0||Z(t))return!1;const i=e.state.machineRuntimes[f(e.state)];return i?.ok!==!0||!_t(i,ht.sessionsReload)?!1:!Xe(e.state.status,e.state.activity)}const Ru="modulepreload",Iu=function(e){return"/"+e},kr={},la=function(t,i,s){let o=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");o=c(i.map(p=>{if(p=Iu(p),p in kr)return;kr[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const g=document.createElement("link");if(g.rel=u?"stylesheet":Ru,u||(g.as="script"),g.crossOrigin="",g.href=p,a&&g.setAttribute("nonce",a),document.head.appendChild(g),u)return new Promise((w,P)=>{g.addEventListener("load",w),g.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function r(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return o.then(n=>{for(const a of n||[])a.status==="rejected"&&r(a.reason);return t().catch(r)})},Cu=10*1024*1024,Tu="10 MB";function Au(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:li(e)}function li(e){switch(e){case"navigation":return he`
24
+ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.markCachedNewSessionPersisted(a)}catch(u){this.setState({error:String(u)})}finally{n&&this.markSendingPrompt(c,!1)}}markSendingPrompt(t,i){const s=this.getState().sendingPrompts;i?s[t]!==!0&&this.setState({sendingPrompts:{...s,[t]:!0}}):t in s&&this.setState({sendingPrompts:Zn(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Me("user",t)]});try{await this.api.shell(i,t,f(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Me("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!i||i.archived===!0)return;const s=i.id;this.markSendingPrompt(s,!0);try{this.applyCommandResult(await this.api.runCommand(i,t,f(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(o){this.setState({messages:[...this.getState().messages,Me("system",String(o))],error:String(o)})}finally{this.markSendingPrompt(s,!1)}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s,t,i,f(this.getState())))}catch(o){this.setState({error:String(o)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(Z(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,f(this.getState()));const i=this.getState(),s=fh(i.sessions,t.id,new Date().toISOString()),o=gh(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),o.type==="select"?await this.selectSession(o.session):o.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||Z(t)))try{const i=await this.api.archiveWithDescendants(t,f(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],o=this.getState(),r=Es(o.sessions,s,new Date().toISOString()),n=Ds(r,o.selectedSession?.id,s);this.setState({sessions:r}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async archiveSessions(t){const i=ur(t).filter(n=>n.archived!==!0&&!Z(n));if(i.length===0)return;const s=f(this.getState()),o=await Promise.allSettled(i.map(async n=>(await this.api.archive(n,s),n.id))),r=fr(o);if(r.length>0){const n=this.getState(),a=Es(n.sessions,r,new Date().toISOString()),c=Ds(a,n.selectedSession?.id,r);this.setState({sessions:a}),c.type==="select"?await this.selectSession(c.session):c.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionError("Archive",o)}async deleteArchivedSessions(t){const i=ur(t).filter(a=>a.archived===!0);if(i.length===0)return;const s=f(this.getState()),o=this.getState().machineRuntimes[s];if(o?.ok!==!0||!Lt(o,ut.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}const r=await Promise.allSettled(i.map(async a=>(await this.api.deleteArchived(a,s),a.id))),n=fr(r);if(n.length>0){const a=new Set(n),c=this.getState(),p=c.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),c.selectedSession!==void 0&&a.has(c.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionError("Delete",r)}async deleteCachedNewSession(t=this.getState().selectedSession){if(!Z(t))return;this.api.stop(t,f(this.getState())).catch(()=>{}),rr(t.id,f(this.getState())),ro(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(o=>o.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(o=>o.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t,f(this.getState()));const i={...t};delete i.archived,delete i.archivedAt,this.replaceSession(i),this.getState().selectedSession?.id===i.id&&await this.selectSession(i)}catch(i){this.setState({error:String(i)})}}async reloadSession(t=this.getState().selectedSession){if(t===void 0||Z(t)||t.archived===!0)return;const i=f(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!Lt(s,ut.sessionsReload)){this.setState({error:"Reloading sessions requires an updated Pi-Web runtime on this machine."});return}try{await this.api.reloadSession(t.id,i),this.transcripts.discard(this.sessionCacheKey(t.id)),this.getState().selectedSession?.id===t.id&&await this.selectSession(t,{updateUrl:!1})}catch(o){this.setState({error:String(o)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t,f(this.getState()));const i={...t};delete i.parentSessionPath,this.replaceSession(i)}catch(i){this.setState({error:String(i)})}}async listModels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.models(t,f(this.getState()))).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s,t,i,f(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(o){this.setState({error:String(o)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,f(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(s){this.setState({error:String(s)})}}async listThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.thinkingLevels(t,f(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async refreshAvailableThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}const i=await this.listThinkingLevels();this.getState().selectedSession?.id===t.id&&this.setState({availableThinkingLevels:i})}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i,t,f(this.getState())))}catch(s){this.setState({error:String(s)})}}async cycleThinkingLevel(){const t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(t,f(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,f(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingTranscriptEvents();const[s,o]=await Promise.all([this.api.messages(i,{limit:kt},f(this.getState())),this.api.status(i,f(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...r,status:o,activity:this.getState().sessionActivities[t],...this.setStreamCatchup(o.isStreaming?t:void 0)}),this.applyStatus(o)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionError(t,i){const s=bh(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return Fn(f(this.getState()),t)}workspaceSelectionKey(t){return`${f(this.getState())}:${t}`}replaceSession(t){const i=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s=>s.id===t.id?t:s),selectedSession:i?.id===t.id?t:i})}async recreateCachedNewSession(t,i){try{const s=f(this.getState()),o=await this.api.startSession(t.cwd,s);or(o,s),up(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),rr(t.id,s);const r=As(o,s);this.setState({sessions:[r,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(r,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!Z(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Nd(i))}applyCommandResult(t){if(t.type==="select"){this.setState({commandDialog:t});return}const i=(t.type==="unsupported",t.message);if(i!==void 0&&i!==""&&this.setState({messages:[...this.getState().messages,Me(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&wi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,o=[t.session,...this.getState().sessions.filter(r=>r.id!==t.session?.id)];this.setState({sessions:o,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();i.selectedWorkspace?.path===t.cwd&&(i.sessions.some(s=>s.id===t.id)||this.setState({sessions:[t,...i.sessions]}))}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Ye(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...xh(i,t.sessionId,t.messageCount),...s?{sessionActivities:vh(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),t.isStreaming||this.finishStreamCatchup(t.sessionId)}applySessionName(t,i){const s=r=>{if(r.id!==t)return r;const n={...r};return i===void 0||i===""?delete n.name:n.name=i,n},o=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:o===void 0?void 0:s(o)})}applyEvent(t){const i=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===i){if(t.type==="message.end"||t.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(kh(t))return}if($h(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}setStreamCatchup(t){return this.catchupStreamSessionId=t,{isReceivingPartialStream:t!==void 0}}finishStreamCatchup(t){const i=this.getState().selectedSession?.id===t;(this.catchupStreamSessionId===t||i&&this.getState().isReceivingPartialStream)&&(this.catchupStreamSessionId=void 0,i&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:kt},f(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),s))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function vh(e,t){return Zn(e,t)}function Zn(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function ur(e){const t=new Set,i=[];for(const s of e)t.has(s.id)||(t.add(s.id),i.push(s));return i}function fr(e){return e.filter(wh).map(t=>t.value)}function bh(e){return e.filter(yh).map(t=>Sh(t.reason))}function wh(e){return e.status==="fulfilled"}function yh(e){return e.status==="rejected"}function Sh(e){return e instanceof Error?e.message:String(e)}function xh(e,t,i){if(i===void 0)return{};const o=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,r=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...o===void 0?{}:{sessions:o},...r!==e.selectedSession?{selectedSession:r}:{}}}function kh(e){return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","command.output","session.error"].includes(e.type)}function $h(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function Ph(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("session not found")||t.includes("未找到会话")}class Rh{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}const Ih="pi-web:workspace-selection:v1";class Ch{constructor(t=Ut()){this.workspaceIdsByProject=new Li(Ih,lo,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function Th(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e[0]:e[0]}class Ah{constructor(t,i,s,o,r=new Rh,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??z}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...ni()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(es(f(this.getState()),t));const i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([s])=>s!==t));this.setState({workspacesByProjectId:i})}async selectProject(t,i){const s=f(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...ni()});try{const o=await this.api.workspaces(t.id,s);if(f(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:o,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:o},isLoadingWorkspaces:!1});const r=Th(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(es(s,t.id))});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){f(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(o),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=f(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:es(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...ni()});try{const o=Fd(t.path,await this.api.sessions(t.path,s),s);if(f(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:o});const r=this.sessions.preferredSession(t.path,o,i?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){f(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(o)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(o=>o.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,f(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),o=this.getState();if(o.selectedProject?.id!==t||o.selectedWorkspace?.id!==i)return;const r=Eh(s);r!==void 0?await this.selectWorkspace(r):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),o={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:o}):this.setState({workspacesByProjectId:o})}}function Mh(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function Eh(e){return e.find(t=>t.isMain)??e[0]}const Dh="pi-web:machine-navigation:v1";class Wh{constructor(t=Ut()){this.snapshotsByMachine=new Li(Dh,_h,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?vr(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,vr(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Oh(e){return{machineId:e,surface:{}}}function gr(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??jn,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,tool:e.workspaceTool,view:e.mainView,surface:{selectedFilePath:t?e.selectedFilePath:void 0,selectedDiffPath:t?e.selectedDiffPath:void 0,selectedTerminalId:t?e.selectedTerminalId:void 0}}}function mr(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view==="navigation"?void 0:e.view}}function vr(e){return{...e,surface:{...e.surface}}}function _h(e){if(!Yn(e))return;const t=_e(e,"machineId");if(t===void 0)return;const i=Xn(_e(e,"tool")),s=jh(_e(e,"view"));return{machineId:t,projectId:_e(e,"projectId"),workspaceId:_e(e,"workspaceId"),sessionId:_e(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:Lh(e.surface)}}function Lh(e){return Yn(e)?{selectedFilePath:_e(e,"selectedFilePath"),selectedDiffPath:_e(e,"selectedDiffPath"),selectedTerminalId:_e(e,"selectedTerminalId")}:{}}function jh(e){return e==="navigation"||e==="chat"?e:Xn(e)}function Xn(e){return Fh(e)?e:void 0}function Fh(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function _e(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Yn(e){return typeof e=="object"&&e!==null}const Nh="pi-web:terminal-selection:v1";class zh{constructor(t=Ut()){this.terminalIdsByCwd=new Li(Nh,lo,t)}latestTerminalId(t){return this.terminalIdsByCwd.get(t)}rememberTerminal(t,i){this.terminalIdsByCwd.set(t,i)}forgetWorkspace(t){this.terminalIdsByCwd.delete(t)}forgetTerminal(t){for(const[i,s]of this.terminalIdsByCwd.entries())s===t&&this.terminalIdsByCwd.delete(i)}}function ay(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>!o.exited)??e[0]:e.find(o=>!o.exited)??e[0]}function ly(e){return e.find(t=>!t.exited)??e[0]}const ea=1200,Bh=["mod","alt","shift"];class Uh{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=ia(t);if(o===void 0)return!1;const r=co(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,o],r))return!0;if(this.clearPending(),!jt(o))return!1}else if(!jt(o))return!1;return this.handleSequence([o],r)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(r=>Yh(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>po(r.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},ea)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function co(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Hh(p,t,u);return h===void 0?[]:[h]}),o=new Map;for(const p of s)o.set(p.key,[...o.get(p.key)??[],p]);const r=new Map;for(const p of o.values()){const u=[...p].sort(Ws)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort(Vh),a=new Map,c=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=Gh(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,g=u===void 0||h?void 0:br(u),b=h?[...a.get(p)??[]].sort(Ws).map(br):[];return{...p,active:h,shadows:b,...g===void 0?{}:{shadowedBy:g}}}).sort((p,u)=>p.order-u.order)}function rs(e){return sa(e,{requireFirstChordActivator:!0})}function ta(e){const t=sa(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function li(e){return ta(e).map(t=>t.split("+").map(ra).join("+")).join(" ")}function ia(e){if(e.isComposing)return;const t=Zh(e.key);if(t===void 0)return;const i=[];return(e.metaKey||e.ctrlKey)&&i.push("mod"),e.altKey&&i.push("alt"),e.shiftKey&&i.push("shift"),i.push(t),i.join("+")}function jt(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Hh(e,t,i){const s=qh(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=ta(o),n=r[0];if(!(n===void 0||!jt(n)))return{action:e,shortcut:r.join(" "),source:s===void 0?"default":"custom",tokens:r,key:Kh(r),order:i}}function qh(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Kh(e){return e.join("\0")}function br(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Ws(e,t){return wr(e.source)-wr(t.source)||yr(e.action.id,t.action.id)||yr(e.action.title,t.action.title)||e.order-t.order}function Vh(e,t){return e.tokens.length-t.tokens.length||Ws(e,t)}function Gh(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&po(e.tokens,i.tokens))}function wr(e){switch(e){case"custom":return 0;case"default":return 1}}function yr(e,t){return e<t?-1:e>t?1:0}function sa(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"请输入快捷键,选择无,或重置为默认值。"};const s=[],o=i.split(/\s+/u).filter(r=>r!=="");for(const[r,n]of o.entries()){const a=Jh(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!jt(a.token))return{ok:!1,message:"快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。"};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Jh(e){const t=e.split("+").filter(r=>r!=="");if(t.length===0)return{ok:!1,message:"快捷键组合必须包含一个按键。"};const i=new Set;let s;for(const r of t){const n=Qh(r);if(n!==void 0){if(i.has(n))return{ok:!1,message:`快捷键包含重复的 ${ra(n)} 修饰键。`};i.add(n);continue}const a=oa(r);if(a===void 0)return{ok:!1,message:`不支持的快捷键按键:${r}`};if(s!==void 0)return{ok:!1,message:"每个快捷键组合只能包含一个非修饰键。"};s=a}return s===void 0?{ok:!1,message:"快捷键组合必须包含一个按键。"}:{ok:!0,token:[...Bh.filter(r=>i.has(r)),s].join("+")}}function Qh(e){switch(e){case"mod":case"meta":case"cmd":case"command":case"ctrl":case"control":case"primary":return"mod";case"alt":case"option":case"opt":return"alt";case"shift":return"shift";default:return}}function oa(e){const t=Xh(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function Zh(e){if(e===" ")return"space";const t=e.toLowerCase();return oa(t)}function Xh(e){switch(e){case" ":case"spacebar":case"space":return"space";case"esc":case"escape":return"escape";case"return":case"enter":return"enter";case"del":case"delete":return"delete";case"backspace":return"backspace";case"tab":return"tab";case"up":case"arrowup":return"arrowup";case"down":case"arrowdown":return"arrowdown";case"left":case"arrowleft":return"arrowleft";case"right":case"arrowright":return"arrowright";case"pageup":case"pagedown":case"home":case"end":return e;case"+":case"plus":return"plus";case"period":case"dot":return".";case"comma":return",";case"slash":return"/";case"backslash":return"\\";case"minus":return"-";default:return}}function ra(e){return e==="mod"?Sr()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?Sr()?"⌥":"Alt":e==="enter"?"Enter":e==="escape"?"Esc":e==="space"?"Space":e==="tab"?"Tab":e==="backspace"?"Backspace":e==="delete"?"Delete":e==="arrowup"?"↑":e==="arrowdown"?"↓":e==="arrowleft"?"←":e==="arrowright"?"→":e==="pageup"?"PageUp":e==="pagedown"?"PageDown":e==="home"?"Home":e==="end"?"End":e==="plus"?"+":/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function Yh(e,t){return e.length===t.length&&po(e,t)}function po(e,t){return t.every((i,s)=>e[s]===i)}function Sr(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const ho="themes:classic",eu="themes:pi-web-dark",tu={themeId:eu,auto:!0},na="pi-web-app-theme",iu=["--pi-bg","--pi-surface","--pi-surface-hover","--pi-terminal-bg","--pi-terminal-text","--pi-border","--pi-border-muted","--pi-text","--pi-text-secondary","--pi-text-bright","--pi-muted","--pi-dim","--pi-accent","--pi-accent-border","--pi-selection-bg","--pi-success","--pi-success-border","--pi-success-bg","--pi-success-surface","--pi-success-ring","--pi-warning","--pi-warning-border","--pi-warning-surface","--pi-danger","--pi-purple","--pi-purple-border","--pi-purple-surface","--pi-overlay","--pi-shadow-soft","--pi-shadow","--pi-shadow-strong","--pi-bg-overlay-soft","--pi-bg-overlay","--pi-success-bg-overlay","--pi-terminal-selection"],su=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function ou(){try{const e=window.localStorage.getItem(na);return e===null?void 0:cu(e)}catch{return}}function ru(e){try{window.localStorage.setItem(na,JSON.stringify(e))}catch{}}function nu(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of iu){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function au(e){const t=lu(e.themes,e.fallbackThemeId??ho),i=e.themes.find(n=>n.id===e.preference.themeId)??t;if(i===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};const s=aa(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const o=e.prefersLight?s.light:s.dark,r=e.themes.find(n=>n.id===o)??i;return{selectedTheme:i,activeTheme:r,selectedThemePair:s,fallbackTheme:t}}function lu(e,t=ho){return e.find(i=>i.id===t)??e[0]}function aa(e,t){return e.find(i=>i.light===t||i.dark===t)}function cu(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return du(i)?i:void 0}catch{return}}function du(e){if(!pu(e))return!1;const t=e.themeId,i=e.auto;return hu(t)&&typeof i=="boolean"}function pu(e){return typeof e=="object"&&e!==null}function hu(e){return typeof e=="string"&&su.test(e)}const uu="management";function fu(e){return gu(mu())===uu}function gu(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function mu(){return typeof window>"u"?void 0:window.location.search}const vu="workspace.delete",bu="pi.operation",wu="target.workspaceId";function yu(e){return{...e===void 0?{}:{projectId:e},metadata:{[bu]:vu}}}function Su(e){const t={};for(const i of e){const s=Os(i);if(s===void 0)continue;const o=t[s];(o===void 0||i.createdAt.localeCompare(o.createdAt)>=0)&&(t[s]=i)}return t}function xu(e){return Object.entries(e).filter(([,t])=>ki(t)).map(([t])=>t)}function la(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&ki(i)}function Os(e){return e.metadata[wu]}function ki(e){return e.status==="queued"||e.status==="running"}function xr(){return[{id:"actions.show",title:"显示操作",description:"打开命令面板",shortcut:"mod+k",group:"通用",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"聚焦提示词输入框",description:"将键盘焦点移动到消息编辑器",shortcut:"mod+g c",group:"通用",enabled:e=>e.state.selectedSession!==void 0,run:e=>{e.focusPrompt()}},{id:"machine.add",title:"添加机器",description:"注册另一个可从当前网关访问的 PI WEB 运行时",group:"机器",run:e=>e.addMachine()},{id:"machine.refresh",title:"刷新所选机器",description:"检查所选 PI WEB 运行时是否在线",group:"机器",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"打开所选机器的 PI WEB",description:"在新标签页中直接打开所选远程 PI WEB",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"移除所选机器",description:"从当前网关移除所选远程机器",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{id:"project.add",title:"添加项目",group:"项目",run:e=>e.addProject()},{id:"auth.login",title:"配置提供商认证",description:"运行 /login,但不将认证绑定到某个会话",group:"通用",run:e=>e.configureAuth()},{id:"auth.logout",title:"移除提供商认证",description:"针对已保存的 pi 凭据运行 /logout",group:"通用",run:e=>e.logoutAuth()},{id:"theme.select",title:"选择主题",description:"选择 PI WEB 颜色主题",group:"偏好设置",run:e=>{e.openThemePicker()}},{id:"settings.open",title:"打开设置",description:"管理 PI WEB 配置和键盘快捷键",shortcut:"mod+,",group:"偏好设置",run:e=>{e.piWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"完整重载页面",description:"重新加载 PI WEB 浏览器页面",group:"通用",run:e=>{e.reloadPage()}},{id:"view.chat",title:"转到聊天",shortcut:"mod+1",group:"导航",run:e=>{e.focusPrompt()}},{id:"view.files",title:"转到文件",shortcut:"mod+2",group:"导航",enabled:$t,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:kr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:$t,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:$t,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:kr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:$t,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"删除工作区",description:"移除所选 Git worktree",group:"工作区",enabled:ku,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:$t,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:$u,run:e=>e.archiveSession()},{id:"session.reload",title:"重新加载会话",description:"从磁盘重新读取所选会话,以获取其他进程写入的条目",group:"会话",enabled:Ru,run:e=>e.reloadSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:Pu,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&Ye(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function $t(e){return e.state.selectedWorkspace!==void 0}function kr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function ku(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!la(e.state,t)}function $u(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!Z(t)}function Pu(e){return Z(e.state.selectedSession)}function Ru(e){const t=e.state.selectedSession;if(t===void 0||t.archived===!0||Z(t))return!1;const i=e.state.machineRuntimes[f(e.state)];return i?.ok!==!0||!Lt(i,ut.sessionsReload)?!1:!Ye(e.state.status,e.state.activity)}const Iu="modulepreload",Cu=function(e){return"/"+e},$r={},ca=function(t,i,s){let o=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");o=c(i.map(p=>{if(p=Cu(p),p in $r)return;$r[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const g=document.createElement("link");if(g.rel=u?"stylesheet":Iu,u||(g.as="script"),g.crossOrigin="",g.href=p,a&&g.setAttribute("nonce",a),document.head.appendChild(g),u)return new Promise((b,P)=>{g.addEventListener("load",b),g.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function r(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return o.then(n=>{for(const a of n||[])a.status==="rejected"&&r(a.reason);return t().catch(r)})},Tu=10*1024*1024,Au="10 MB";function Mu(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:ci(e)}function ci(e){switch(e){case"navigation":return he`
25
25
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
26
26
  <circle cx="6" cy="7" r="1.5"></circle>
27
27
  <path d="M10 7h8"></path>
@@ -55,53 +55,53 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
55
55
  <path d="m7 10 3 3-3 3"></path>
56
56
  <path d="M12 16h5"></path>
57
57
  </svg>
58
- `}}function $r(){return[{id:"workspace.files",title:"文件",icon:li("files"),order:10,render:Mu},{id:"workspace.git",title:"Git",icon:li("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:Uu},{id:"workspace.terminal",title:"终端",icon:li("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Bu}]}function Mu(e){const t=e.machine.kind==="local";return l`
58
+ `}}function Pr(){return[{id:"workspace.files",title:"文件",icon:ci("files"),order:10,render:Eu},{id:"workspace.git",title:"Git",icon:ci("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:Hu},{id:"workspace.terminal",title:"终端",icon:ci("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Uu}]}function Eu(e){const t=e.machine.kind==="local";return l`
59
59
  <section class="toolbar">
60
60
  <strong>文件</strong>
61
61
  ${e.fileTreeStale?l`<span class="stale">过期</span>`:null}
62
62
  <div class="toolbar-actions">
63
63
  <button @click=${e.onRefreshFiles}>刷新</button>
64
- <button @click=${()=>{Wu(e)}}>新建文件</button>
65
- <button @click=${()=>{Ou(e)}}>新建目录</button>
64
+ <button @click=${()=>{Ou(e)}}>新建文件</button>
65
+ <button @click=${()=>{_u(e)}}>新建目录</button>
66
66
  ${e.selectedFilePath===void 0?null:l`
67
- ${Ut(e)==="file"?l`<button @click=${()=>{e.onDownloadSelectedFile()}}>下载</button>`:null}
68
- <button @click=${()=>{_u(e)}}>移动</button>
69
- <button class="danger" @click=${()=>{Lu(e)}}>删除</button>
67
+ ${Ht(e)==="file"?l`<button @click=${()=>{e.onDownloadSelectedFile()}}>下载</button>`:null}
68
+ <button @click=${()=>{Lu(e)}}>移动</button>
69
+ <button class="danger" @click=${()=>{ju(e)}}>删除</button>
70
70
  `}
71
71
  ${t?l`
72
- <label class="file-upload-button" role="button" tabindex="0" aria-label="上传文件" @keydown=${Eu}>
72
+ <label class="file-upload-button" role="button" tabindex="0" aria-label="上传文件" @keydown=${Du}>
73
73
  上传
74
- <input type="file" multiple hidden @change=${i=>{Du(e,i)}} />
74
+ <input type="file" multiple hidden @change=${i=>{Wu(e,i)}} />
75
75
  </label>
76
76
  `:l`<span class="file-upload-button disabled" title="远端机器暂不支持上传" aria-disabled="true">上传</span>`}
77
77
  </div>
78
78
  </section>
79
79
  <section class="split">
80
80
  <div class="list tree">
81
- ${e.fileTree.length===0?l`<p class="muted">尚未加载文件。</p>`:e.fileTree.map(i=>ca(e,i,0))}
81
+ ${e.fileTree.length===0?l`<p class="muted">尚未加载文件。</p>`:e.fileTree.map(i=>da(e,i,0))}
82
82
  </div>
83
83
  <div class="viewer">
84
- ${Nu(e)}
84
+ ${zu(e)}
85
85
  </div>
86
86
  </section>
87
- `}function Eu(e){if(e.key!=="Enter"&&e.key!==" ")return;e.preventDefault();const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=t.querySelector("input[type='file']");i instanceof HTMLInputElement&&i.click()}function Du(e,t){const i=t.currentTarget;!(i instanceof HTMLInputElement)||i.files===null||(e.onUploadFiles(Array.from(i.files)),i.value="")}function Wu(e){const t=window.prompt("新建文件路径",da(e,"new-file.txt"));t===null||t.trim()===""||e.onCreateFile(t.trim())}function Ou(e){const t=window.prompt("新建目录路径",da(e,"new-folder"));t===null||t.trim()===""||e.onCreateDirectory(t.trim())}function _u(e){const t=e.selectedFilePath;if(t===void 0||t==="")return;const i=window.prompt(Ut(e)==="directory"?"移动或重命名目录到":"移动或重命名文件到",t);i===null||i.trim()===""||i.trim()===t||e.onMoveSelectedPath(i.trim())}function Lu(e){const t=e.selectedFilePath;if(t===void 0||t==="")return;const i=Ut(e)==="directory"?"空目录":"文件";window.confirm(`删除${i} ${t}?`)&&e.onDeleteSelectedPath()}function ca(e,t,i){const s=e.expandedDirs[t.path],o=s!==void 0,r=e.selectedFilePath===t.path;return l`
88
- <button class=${r?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{ju(e,t)}}>
87
+ `}function Du(e){if(e.key!=="Enter"&&e.key!==" ")return;e.preventDefault();const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=t.querySelector("input[type='file']");i instanceof HTMLInputElement&&i.click()}function Wu(e,t){const i=t.currentTarget;!(i instanceof HTMLInputElement)||i.files===null||(e.onUploadFiles(Array.from(i.files)),i.value="")}function Ou(e){const t=window.prompt("新建文件路径",pa(e,"new-file.txt"));t===null||t.trim()===""||e.onCreateFile(t.trim())}function _u(e){const t=window.prompt("新建目录路径",pa(e,"new-folder"));t===null||t.trim()===""||e.onCreateDirectory(t.trim())}function Lu(e){const t=e.selectedFilePath;if(t===void 0||t==="")return;const i=window.prompt(Ht(e)==="directory"?"移动或重命名目录到":"移动或重命名文件到",t);i===null||i.trim()===""||i.trim()===t||e.onMoveSelectedPath(i.trim())}function ju(e){const t=e.selectedFilePath;if(t===void 0||t==="")return;const i=Ht(e)==="directory"?"空目录":"文件";window.confirm(`删除${i} ${t}?`)&&e.onDeleteSelectedPath()}function da(e,t,i){const s=e.expandedDirs[t.path],o=s!==void 0,r=e.selectedFilePath===t.path;return l`
88
+ <button class=${r?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{Fu(e,t)}}>
89
89
  <span>${t.type==="directory"?o?"▾":"▸":"·"}</span>
90
90
  <span>${t.name}</span>
91
91
  </button>
92
- ${o?s.map(n=>ca(e,n,i+1)):null}
93
- `}function ju(e,t){t.type==="directory"?(e.onSelectDirectory(t.path),e.onExpandDir(t.path)):e.onSelectFile(t.path)}function Ut(e){const t=e.selectedFilePath;return t===void 0?"file":Fu(e,t)?.type??"file"}function da(e,t){const i=e.selectedFilePath;if(i===void 0||i==="")return t;if(Ut(e)==="directory")return`${i}/${t}`;const s=i.lastIndexOf("/");return s===-1?t:`${i.slice(0,s)}/${t}`}function Fu(e,t){const i=e.fileTree.find(s=>s.path===t);if(i!==void 0)return i;for(const s of Object.values(e.expandedDirs)){const o=s.find(r=>r.path===t);if(o!==void 0)return o}}function Nu(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">请选择文件。</p>`:Ut(e)==="directory"?l`<p class="muted">已选择目录 ${e.selectedFilePath}。</p>`:t===void 0?l`<p class="muted">正在加载 ${e.selectedFilePath}…</p>`:t.mediaType==="image"?zu(e,t):t.binary?l`<p class="muted">二进制文件:${t.path} · ${Os(t.size)}</p>`:(pa(),l`
92
+ ${o?s.map(n=>da(e,n,i+1)):null}
93
+ `}function Fu(e,t){t.type==="directory"?(e.onSelectDirectory(t.path),e.onExpandDir(t.path)):e.onSelectFile(t.path)}function Ht(e){const t=e.selectedFilePath;return t===void 0?"file":Nu(e,t)?.type??"file"}function pa(e,t){const i=e.selectedFilePath;if(i===void 0||i==="")return t;if(Ht(e)==="directory")return`${i}/${t}`;const s=i.lastIndexOf("/");return s===-1?t:`${i.slice(0,s)}/${t}`}function Nu(e,t){const i=e.fileTree.find(s=>s.path===t);if(i!==void 0)return i;for(const s of Object.values(e.expandedDirs)){const o=s.find(r=>r.path===t);if(o!==void 0)return o}}function zu(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">请选择文件。</p>`:Ht(e)==="directory"?l`<p class="muted">已选择目录 ${e.selectedFilePath}。</p>`:t===void 0?l`<p class="muted">正在加载 ${e.selectedFilePath}…</p>`:t.mediaType==="image"?Bu(e,t):t.binary?l`<p class="muted">二进制文件:${t.path} · ${_s(t.size)}</p>`:(ha(),l`
94
94
  <div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"文本"}${t.truncated?" · 已截断":""}</small></div>
95
95
  <code-viewer .content=${t.content} .language=${t.language}></code-viewer>
96
- `)}function zu(e,t){const i=`${t.mimeType??"image"} · ${Os(t.size)}`;if(t.size>Cu)return l`
96
+ `)}function Bu(e,t){const i=`${t.mimeType??"image"} · ${_s(t.size)}`;if(t.size>Tu)return l`
97
97
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
98
- <p class="muted">图片过大,无法预览:${Os(t.size)} · 限制 ${Tu}</p>
99
- `;const s=od(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
98
+ <p class="muted">图片过大,无法预览:${_s(t.size)} · 限制 ${Au}</p>
99
+ `;const s=rd(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
100
100
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
101
101
  <div class="image-preview">
102
102
  <img src=${s} alt=${t.path} decoding="async" />
103
103
  </div>
104
- `}function Bu(e){return Ku(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Uu(e){const t=e.gitStatus;return l`
104
+ `}function Uu(e){return Vu(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Hu(e){const t=e.gitStatus;return l`
105
105
  <section class="toolbar">
106
106
  <strong>Git</strong>
107
107
  ${e.gitStale?l`<span class="stale">过期</span>`:null}
@@ -110,29 +110,29 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
110
110
  <section class="split">
111
111
  <div class="list">
112
112
  ${t===void 0?l`<p class="muted">尚未加载状态。</p>`:t.isGitRepo?l`
113
- <p class="summary">${Vu(t)}</p>
113
+ <p class="summary">${Gu(t)}</p>
114
114
  ${t.files.length===0?l`<p class="muted">没有变更。</p>`:t.files.map(i=>l`
115
115
  <button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
116
- <span>${Gu(i.index,i.workingTree)}</span>
116
+ <span>${Ju(i.index,i.workingTree)}</span>
117
117
  <span>${i.path}</span>
118
118
  </button>
119
119
  `)}
120
120
  `:l`<p class="muted">不是 Git 仓库。</p>`}
121
121
  </div>
122
122
  <div class="viewer">
123
- ${Hu(e)}
123
+ ${qu(e)}
124
124
  </div>
125
125
  </section>
126
- `}function Hu(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return l`<p class="muted">请选择一个已变更文件。</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return l`<p class="muted">正在加载 diff…</p>`;const s=[i,t].filter(o=>o.diff!=="");return s.length===0?l`<p class="muted">没有 staged 或 unstaged diff。</p>`:l`
126
+ `}function qu(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return l`<p class="muted">请选择一个已变更文件。</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return l`<p class="muted">正在加载 diff…</p>`;const s=[i,t].filter(o=>o.diff!=="");return s.length===0?l`<p class="muted">没有 staged 或 unstaged diff。</p>`:l`
127
127
  <div class=${s.length===1?"diffs single":"diffs"}>
128
- ${s.map(o=>qu(o))}
128
+ ${s.map(o=>Ku(o))}
129
129
  </div>
130
- `}function qu(e){return pa(),l`
130
+ `}function Ku(e){return ha(),l`
131
131
  <section class="diff-section">
132
132
  <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"已暂存":"未暂存"}${e.truncated?" · 已截断":""}</small></div>
133
133
  <code-viewer .content=${e.diff} .language=${"diff"}></code-viewer>
134
134
  </section>
135
- `}function pa(){la(()=>import("./CodeViewer-B1z_k75G.js"),__vite__mapDeps([0,1,2,3]))}function Ku(){la(()=>import("./TerminalPanel-CqG27wd5.js"),__vite__mapDeps([4,5,6,1,2]))}function Vu(e){const t=e.branch??"分离 HEAD",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function Gu(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function Os(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${rs(t)} KB`;const i=t/1024;return i<1024?`${rs(i)} MB`:`${rs(i/1024)} GB`}function rs(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const Ju={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!uu();return{contributions:{actions:e?Sr():Sr().filter(t=>t.id!=="view.terminal"),workspacePanels:e?$r():$r().filter(t=>t.id!=="workspace.terminal")}}}},Qu={"--pi-bg":"#0d1117","--pi-surface":"#161b22","--pi-surface-hover":"#21262d","--pi-terminal-bg":"#05070a","--pi-terminal-text":"#e6edf3","--pi-border":"#30363d","--pi-border-muted":"#21262d","--pi-text":"#e6edf3","--pi-text-secondary":"#c9d1d9","--pi-text-bright":"#f0f6fc","--pi-muted":"#8b949e","--pi-dim":"#6e7681","--pi-accent":"#58a6ff","--pi-accent-border":"#2f81f7","--pi-selection-bg":"#0d2847","--pi-success":"#3fb950","--pi-success-border":"#238636","--pi-success-bg":"#0f1b12","--pi-success-surface":"#0f2a16","--pi-success-ring":"#3fb95055","--pi-warning":"#d29922","--pi-warning-border":"#6e5200","--pi-warning-surface":"#1f1a10","--pi-danger":"#ff7b72","--pi-purple":"#d2a8ff","--pi-purple-border":"#a371f7","--pi-purple-surface":"#21132f","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#0d1117dd","--pi-bg-overlay":"#0d1117e6","--pi-success-bg-overlay":"#0f1b12ee","--pi-terminal-selection":"#264f78"},Zu={"--pi-bg":"#070912","--pi-surface":"#101527","--pi-surface-hover":"#151b31","--pi-terminal-bg":"#050710","--pi-terminal-text":"#f7f4ff","--pi-border":"#26304f","--pi-border-muted":"#26304f","--pi-text":"#f7f4ff","--pi-text-secondary":"#aaa4bd","--pi-text-bright":"#ffffff","--pi-muted":"#aaa4bd","--pi-dim":"#817a99","--pi-accent":"#7c3cff","--pi-accent-border":"#5a47b0","--pi-selection-bg":"#1d2547","--pi-success":"#00f0d8","--pi-success-border":"#00f0d8","--pi-success-bg":"#071e22","--pi-success-surface":"#092d31","--pi-success-ring":"#00f0d855","--pi-warning":"#ffb000","--pi-warning-border":"#ffb000","--pi-warning-surface":"#16140d","--pi-danger":"#ff4f7b","--pi-purple":"#b7a2ff","--pi-purple-border":"#7c3cff","--pi-purple-surface":"#181026","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#070912dd","--pi-bg-overlay":"#070912e6","--pi-success-bg-overlay":"#071e22ee","--pi-terminal-selection":"#3d4a78"},Xu={"--pi-bg":"#f7f1e6","--pi-surface":"#fff9ee","--pi-surface-hover":"#f0e6d6","--pi-terminal-bg":"#15131b","--pi-terminal-text":"#fff9ee","--pi-border":"#c9bca8","--pi-border-muted":"#d8cdbc","--pi-text":"#15131b","--pi-text-secondary":"#15131b","--pi-text-bright":"#15131b","--pi-muted":"#5f586a","--pi-dim":"#766f7e","--pi-accent":"#6430d8","--pi-accent-border":"#6430d8","--pi-selection-bg":"#eadff8","--pi-success":"#008c82","--pi-success-border":"#008c82","--pi-success-bg":"#e1f4ef","--pi-success-surface":"#d7f0ec","--pi-success-ring":"#008c8255","--pi-warning":"#b05f00","--pi-warning-border":"#b05f00","--pi-warning-surface":"#fff2d2","--pi-danger":"#b51d49","--pi-purple":"#6430d8","--pi-purple-border":"#6430d8","--pi-purple-surface":"#eadff8","--pi-overlay":"#15131b66","--pi-shadow-soft":"#15131b22","--pi-shadow":"#15131b33","--pi-shadow-strong":"#15131b44","--pi-bg-overlay-soft":"#f7f1e6dd","--pi-bg-overlay":"#f7f1e6e6","--pi-success-bg-overlay":"#e1f4efee","--pi-terminal-selection":"#8d7b64"},Yu={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:Zu},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Xu},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Qu}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},ef=/^[a-z][a-z0-9.-]*$/u;function tf(e){return ef.test(e)}const sf="machine.";function of(e,t){if(e==="")throw new Error("Machine id is required");if(!tf(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${sf}${rf(e)}.${t}`}function rf(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function Pr(e="/pi-web-plugins/manifest.json",t={}){const i=await nf(e);if(i===void 0)return[];const s=[];for(const o of i.plugins)if(t.shouldLoadPlugin?.(o)!==!1)try{const r=new URL(o.module,new URL(e,window.location.href)).toString(),n=await import(r),a=cf(n,r);s.push({id:t.machineId===void 0?o.id:of(t.machineId,o.id),plugin:a,machineSpecific:o.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:o.id}})}catch(r){console.warn(`Failed to load PI WEB plugin ${o.module}`,r)}return s}async function nf(e){const t=await fetch(e,{cache:"no-store"});if(t.status!==404){if(!t.ok)throw new Error(`Failed to load plugin manifest: ${t.statusText}`);return af(await t.json())}}function af(e){if(!ki(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!ki(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module,machineSpecific:lf(t.machineSpecific)}})}}function lf(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function cf(e,t){if(!ki(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!df(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function df(e){return ki(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function ki(e){return typeof e=="object"&&e!==null}const pf=/^[a-z][a-z0-9.-]*$/u,hf=/^[a-z][a-z0-9.-]*$/u,ha=new WeakMap,ua=new WeakMap;class uf{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;this.validatePluginId(i);const o=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,o))return;this.pluginIds.add(i);const r=s.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(r)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:he}).contributions;for(const c of a.actions??[])this.actions.push(this.qualifyAction(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,c,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const c of a.themes??[])this.themes.push(this.qualifyTheme(i,c));for(const c of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,c));this.gatewayPluginIds.add(i),o&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&o&&vf(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=wf(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const o=ff(t,s.pluginId),r=s.enabled?.(o),n={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(o)};return s.description!==void 0&&(n.description=s.description),s.shortcut!==void 0&&(n.shortcut=s.shortcut),s.group!==void 0&&(n.group=s.group),r!==void 0&&(n.enabled=r),n})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,o){const r=this.qualify(t,i.id);return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...o===void 0?{}:{sourcePluginId:o}}}qualifyWorkspacePanel(t,i,s,o){const r=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(a?.(ns(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,o)?n(ns(c,t)):void 0},render:c=>i.render(ns(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,o){const r=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(n?.(c)??!0),items:c=>this.isContributionActive(t,s,c.machine.id,o)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}isContributionActive(t,i,s,o){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(o,i)}isRemoteDuplicateHiddenByGateway(t,i,s){return t!==void 0&&i!==void 0&&this.gatewayPluginIds.has(t)&&!this.gatewayMachineSpecificPluginIds.has(t)&&!s}isRemotePluginHiddenByGateway(t,i){return t===void 0||this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0?!1:this.gatewayPluginIds.has(t)}isGatewayPluginHiddenForMachine(t,i){return i!=="local"&&(this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0)}validatePluginId(t){if(!pf.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!hf.test(t))throw new Error(`Invalid contribution id: ${t}`)}parseMachineSpecific(t,i){if(i===void 0)return!1;if(typeof i!="boolean")throw new Error(`Invalid plugin machineSpecific value for ${t}: ${bf(i)}`);return i}}function ff(e,t){return ha.get(e)?.(t)??e}function ns(e,t){return ua.get(e)?.(t)??e}function gf(e,t){return ha.set(e,t),e}function mf(e,t){return ua.set(e,t),e}function vf(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function bf(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"||typeof e=="symbol"||typeof e=="function"||e===null||e===void 0)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function wf(e){return e.state.selectedMachine?.id??"local"}const yf=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function Sf(){return typeof window>"u"||!("matchMedia"in window)?[]:yf.map(e=>window.matchMedia(e))}function Rr(e,t=xf()){return e.some(i=>i.matches)||kf(t)}function xf(){return typeof navigator>"u"?void 0:navigator}function kf(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const $f=250;class Pf{constructor(t=Rf()){this.scheduler=t}repair(t){if(!t){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},$f)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);const t=this.scheduler.documentElement;t!==void 0&&(t.scrollTop=0);const i=this.scheduler.body;i!==void 0&&(i.scrollTop=0)}}function Rf(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>"u"?void 0:document.documentElement},get body(){return typeof document>"u"?void 0:document.body}}}const If="(max-width: 760px)",Cf="(max-width: 1180px)";class Tf{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onStackedWorkspaceMediaChange=s=>{this.isStackedWorkspaceLayout!==s.matches&&(this.isStackedWorkspaceLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=Rr(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Af(),this.stackedWorkspaceMedia=i.stackedWorkspaceMedia??Mf(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??Sf(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Pf,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=Rr(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.addEventListener("change",this.onStackedWorkspaceMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.removeEventListener("change",this.onStackedWorkspaceMediaChange);for(const t of this.pwaDisplayModeMedia)t.removeEventListener("change",this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.normalizedMainView(void 0,!1)}normalizedMainView(t,i){return Ef(t,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:i})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Af(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(If)}function Mf(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Cf)}function Ef(e,t){const i=e??(t.isMobileNavigationLayout?"navigation":"chat");return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||i==="navigation"||i==="chat"?i:"chat"}const $i=["machines","projects","workspaces","sessions"];function Df(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function ho(e,t){if(e!=="none")return e??Df(t)}function Wf(e,t){return t.isMobileLayout?ho(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Of(e,t,i){return ho(e,i.state)===t?"none":t}function _f(e,t,i){return i?t:e}function Lf(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Nf(i)}function jf(e){return $i[$i.indexOf(e)+1]}class Ff{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return ho(this.expanded,this.getState())}isCollapsed(t){return Wf(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Of(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Lf(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(_f(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=jf(t);i!==void 0&&this.expand(i)}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}setCollapsedSections(t){zf(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Nf(e){const t=new Set(e);return $i.filter(i=>t.has(i))}function zf(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class Bf{constructor(t){this.host=t,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,t.addController(this)}hostConnected(){}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(t){return["shell",fa(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function fa(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const _s="pi-web:panel-sizes:v1",Uf={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Hf{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??uo(),this.panelSizes=Gf(this.storage)}hostConnected(){}constraints(t){return Ht(t)}panelWidth(t,i){return ue(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const o=ue(t,i);this.storedPanelWidth(t)!==o&&(this.panelSizes=Zf(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Xf(this.panelSizes,t),i.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(t={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){Jf(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${Cr(ue("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${Cr(ue("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Ht(e){return Uf[e]}function qf(e,t,i){return e==="navigation"?i-t:t-i}function Kf(e,t,i,s,o=Ht(e)){return ue(e,t+qf(e,i,s),o)}function Vf(e,t,i,s={}){const o=s.constraints??Ht(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=Yf(e,i,r);if(n!==void 0)return ue(e,t+n,o)}function ue(e,t,i=Ht(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Gf(e=uo()){try{const t=e?.getItem(_s);if(t==null||t==="")return{};const i=JSON.parse(t);return Qf(i)}catch{return{}}}function Jf(e,t=uo()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(_s);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=ue("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=ue("workspace",e.workspacePanelWidth)),t.setItem(_s,JSON.stringify(i))}catch{}}function Qf(e){if(!eg(e)||e.version!==1)return{};const t={},i=Ir(e.navigationPanelWidth),s=Ir(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=ue("navigation",i)),s!==void 0&&(t.workspacePanelWidth=ue("workspace",s)),t}function Ir(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Zf(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Xf(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Yf(e,t,i){if(e==="navigation")return t==="ArrowRight"?i:t==="ArrowLeft"?-i:void 0;if(t==="ArrowLeft")return i;if(t==="ArrowRight")return-i}function Cr(e){return`${String(Math.round(e))}px`}function uo(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function eg(e){return typeof e=="object"&&e!==null}function Tr(){const e=new URLSearchParams(window.location.search);return{machineId:e.get("machine")??void 0,projectId:e.get("project")??void 0,workspaceId:e.get("workspace")??void 0,sessionId:e.get("session")??void 0,tool:tg(e.get("tool")),view:ig(e.get("view"))}}function as(e,t){const i=new URL(window.location.href);i.searchParams.delete("machine"),i.searchParams.delete("project"),i.searchParams.delete("workspace"),i.searchParams.delete("session"),i.searchParams.delete("tool"),i.searchParams.delete("view"),e.machineId!==void 0&&e.machineId!==""&&e.machineId!=="local"&&i.searchParams.set("machine",e.machineId),e.projectId!==void 0&&e.projectId!==""&&i.searchParams.set("project",e.projectId),e.workspaceId!==void 0&&e.workspaceId!==""&&i.searchParams.set("workspace",e.workspaceId),e.sessionId!==void 0&&e.sessionId!==""&&i.searchParams.set("session",e.sessionId),e.tool!==void 0&&i.searchParams.set("tool",e.tool),e.view!==void 0&&i.searchParams.set("view",e.view);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function tg(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":ga(e)?e:void 0}function ig(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":ga(e)?e:void 0}function ga(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Ar(){return sg(new URLSearchParams(window.location.search).get("settings"))}function ls(e,t){const i=new URL(window.location.href);e===void 0?i.searchParams.delete("settings"):i.searchParams.set("settings",e);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&window.history.pushState({},"",i)}function sg(e){if(e==="general")return"general";if(e==="sessiond"||e==="sessions")return"sessiond";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function og(e,t){return t===void 0?e:e.map(i=>ng(i,t))}function rg(e,t){const i=new Set(lo(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return og(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?ma(s):s)}function ng(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?ma(e):{...e,shortcut:i}}function ma(e){const t={...e};return delete t.shortcut,t}function ag(e,t){const i=t.api??dt,s=t.pollIntervalMs??1e3,o=t.setTimeout??cg(),r=t.clearTimeout??dg();return{async runCommand(n){const a=await i.runTerminalCommand(e,n);return n.open===!0&&t.openTerminal(n.workspace,{terminalId:a.terminalId}),{run:a,completed:lg(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function lg(e,t,i,s,o){return Mr(e)?Promise.resolve(e):new Promise((r,n)=>{let a,c=!1;const p=g=>{c||(c=!0,a!==void 0&&o(a),r(g))},u=g=>{c||(c=!0,a!==void 0&&o(a),n(g instanceof Error?g:new Error(String(g))))},h=()=>{t.getCommandRun(e.id).then(g=>{if(g!==void 0&&Mr(g)){p(g);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function Mr(e){return e.status==="succeeded"||e.status==="failed"}function cg(){return(e,t)=>globalThis.setTimeout(e,t)}function dg(){return e=>{globalThis.clearTimeout(e)}}function pg(e,t){return t[e.path]}function hg(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function ug(e,t,i){return ba(fg(e,t,i))}function va(e){return ba(Object.values(e??{}))}function ba(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function fg(e,t,i){const s=new Set(t.filter(r=>r.projectId===e.id).map(r=>r.path)),o=new Map;for(const r of s){const n=i[r];n!==void 0&&o.set(n.cwd,n)}for(const r of Object.values(i))(r.cwd===e.path||r.cwd.startsWith(`${e.path}/`))&&o.set(r.cwd,r);return[...o.values()]}function wa(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Li(e,t="活跃"){const i=wa(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const Zt=0,gg=120;function ya(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?Sa():mg(e),o=window.innerWidth,r=window.innerHeight,n=Math.max(0,s.left),a=Math.min(o,s.right),c=Math.max(0,s.top),p=Math.min(r,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Zt,g=i.top-c-Zt;return[...h<gg&&g>h?[`bottom: ${at(r-i.top+Zt)};`,`max-height: ${at(Math.max(0,g))};`]:[`top: ${at(i.bottom+Zt)};`,`max-height: ${at(Math.max(0,h))};`],`right: ${at(Math.max(0,o-u))};`,`max-width: ${at(Math.max(0,u-n))};`].join(" ")}function mg(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Sa()}function Sa(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function at(e){return`${String(Math.round(e))}px`}class ji{constructor(t){this.host=t,this.menuStyle="",this.onDocumentClick=i=>{i.composedPath().includes(this.host)||this.close()},t.addController(this)}hostConnected(){document.addEventListener("click",this.onDocumentClick)}hostDisconnected(){document.removeEventListener("click",this.onDocumentClick)}isOpen(t){return this.openId===t}toggle(t,i){if(this.openId===t){this.close();return}this.menuStyle=ya(i,{constrainTo:"viewport"}),this.openId=t,this.host.requestUpdate()}close(){this.openId===void 0&&this.menuStyle===""||(this.openId=void 0,this.menuStyle="",this.host.requestUpdate())}closeIfOpenIdMissing(t){this.openId!==void 0&&!t(this.openId)&&this.close()}closeIf(t){t&&this.close()}closeForEscape(t,i){return t.key!=="Escape"||this.openId!==i?!1:(t.preventDefault(),t.stopPropagation(),this.close(),!0)}}const vg=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function xa(e){return e.composedPath().some(t=>bg(t,vg))}function bg(e,t){if(typeof Element<"u"&&e instanceof Element)return e.matches(t);if(!("matches"in e))return!1;const{matches:i}=e;return typeof i=="function"&&i.call(e,t)===!0}function Fi(e,t){xa(e)||t()}function Ni(e,t){return xa(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?Ke(e,()=>{Er(e.currentTarget,-1)}):e.key==="ArrowDown"?Ke(e,()=>{Er(e.currentTarget,1)}):e.key==="Home"?Ke(e,()=>{Dr(e.currentTarget,0)}):e.key==="End"?Ke(e,()=>{Dr(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?Ke(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?Ke(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?Ke(e,t.cancel):!1}function zi(e,t={}){const i=e.querySelector(".action-row.selected")??e.querySelector(".action-row")??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return i==null?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}function Ke(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function Er(e,t){const i=$a(e),s=Pa(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||ka(i,o+t)}function Dr(e,t){const i=$a(e);i.length!==0&&ka(i,t<0?i.length-1:t)}function ka(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function $a(e){const t=Pa(e)?.getRootNode();return t===void 0||!wg(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function wg(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function Pa(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const Bi=D`
135
+ `}function ha(){ca(()=>import("./CodeViewer-BmIwBtZe.js"),__vite__mapDeps([0,1,2,3]))}function Vu(){ca(()=>import("./TerminalPanel-6pE_JF7k.js"),__vite__mapDeps([4,5,6,1,2]))}function Gu(e){const t=e.branch??"分离 HEAD",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function Ju(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function _s(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${ns(t)} KB`;const i=t/1024;return i<1024?`${ns(i)} MB`:`${ns(i/1024)} GB`}function ns(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const Qu={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!fu();return{contributions:{actions:e?xr():xr().filter(t=>t.id!=="view.terminal"),workspacePanels:e?Pr():Pr().filter(t=>t.id!=="workspace.terminal")}}}},Zu={"--pi-bg":"#0d1117","--pi-surface":"#161b22","--pi-surface-hover":"#21262d","--pi-terminal-bg":"#05070a","--pi-terminal-text":"#e6edf3","--pi-border":"#30363d","--pi-border-muted":"#21262d","--pi-text":"#e6edf3","--pi-text-secondary":"#c9d1d9","--pi-text-bright":"#f0f6fc","--pi-muted":"#8b949e","--pi-dim":"#6e7681","--pi-accent":"#58a6ff","--pi-accent-border":"#2f81f7","--pi-selection-bg":"#0d2847","--pi-success":"#3fb950","--pi-success-border":"#238636","--pi-success-bg":"#0f1b12","--pi-success-surface":"#0f2a16","--pi-success-ring":"#3fb95055","--pi-warning":"#d29922","--pi-warning-border":"#6e5200","--pi-warning-surface":"#1f1a10","--pi-danger":"#ff7b72","--pi-purple":"#d2a8ff","--pi-purple-border":"#a371f7","--pi-purple-surface":"#21132f","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#0d1117dd","--pi-bg-overlay":"#0d1117e6","--pi-success-bg-overlay":"#0f1b12ee","--pi-terminal-selection":"#264f78"},Xu={"--pi-bg":"#070912","--pi-surface":"#101527","--pi-surface-hover":"#151b31","--pi-terminal-bg":"#050710","--pi-terminal-text":"#f7f4ff","--pi-border":"#26304f","--pi-border-muted":"#26304f","--pi-text":"#f7f4ff","--pi-text-secondary":"#aaa4bd","--pi-text-bright":"#ffffff","--pi-muted":"#aaa4bd","--pi-dim":"#817a99","--pi-accent":"#7c3cff","--pi-accent-border":"#5a47b0","--pi-selection-bg":"#1d2547","--pi-success":"#00f0d8","--pi-success-border":"#00f0d8","--pi-success-bg":"#071e22","--pi-success-surface":"#092d31","--pi-success-ring":"#00f0d855","--pi-warning":"#ffb000","--pi-warning-border":"#ffb000","--pi-warning-surface":"#16140d","--pi-danger":"#ff4f7b","--pi-purple":"#b7a2ff","--pi-purple-border":"#7c3cff","--pi-purple-surface":"#181026","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#070912dd","--pi-bg-overlay":"#070912e6","--pi-success-bg-overlay":"#071e22ee","--pi-terminal-selection":"#3d4a78"},Yu={"--pi-bg":"#f7f1e6","--pi-surface":"#fff9ee","--pi-surface-hover":"#f0e6d6","--pi-terminal-bg":"#15131b","--pi-terminal-text":"#fff9ee","--pi-border":"#c9bca8","--pi-border-muted":"#d8cdbc","--pi-text":"#15131b","--pi-text-secondary":"#15131b","--pi-text-bright":"#15131b","--pi-muted":"#5f586a","--pi-dim":"#766f7e","--pi-accent":"#6430d8","--pi-accent-border":"#6430d8","--pi-selection-bg":"#eadff8","--pi-success":"#008c82","--pi-success-border":"#008c82","--pi-success-bg":"#e1f4ef","--pi-success-surface":"#d7f0ec","--pi-success-ring":"#008c8255","--pi-warning":"#b05f00","--pi-warning-border":"#b05f00","--pi-warning-surface":"#fff2d2","--pi-danger":"#b51d49","--pi-purple":"#6430d8","--pi-purple-border":"#6430d8","--pi-purple-surface":"#eadff8","--pi-overlay":"#15131b66","--pi-shadow-soft":"#15131b22","--pi-shadow":"#15131b33","--pi-shadow-strong":"#15131b44","--pi-bg-overlay-soft":"#f7f1e6dd","--pi-bg-overlay":"#f7f1e6e6","--pi-success-bg-overlay":"#e1f4efee","--pi-terminal-selection":"#8d7b64"},ef={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:Xu},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Yu},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Zu}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},tf=/^[a-z][a-z0-9.-]*$/u;function sf(e){return tf.test(e)}const of="machine.";function rf(e,t){if(e==="")throw new Error("Machine id is required");if(!sf(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${of}${nf(e)}.${t}`}function nf(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function Rr(e="/pi-web-plugins/manifest.json",t={}){const i=await af(e);if(i===void 0)return[];const s=[];for(const o of i.plugins)if(t.shouldLoadPlugin?.(o)!==!1)try{const r=new URL(o.module,new URL(e,window.location.href)).toString(),n=await import(r),a=df(n,r);s.push({id:t.machineId===void 0?o.id:rf(t.machineId,o.id),plugin:a,machineSpecific:o.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:o.id}})}catch(r){console.warn(`Failed to load PI WEB plugin ${o.module}`,r)}return s}async function af(e){const t=await fetch(e,{cache:"no-store"});if(t.status!==404){if(!t.ok)throw new Error(`Failed to load plugin manifest: ${t.statusText}`);return lf(await t.json())}}function lf(e){if(!$i(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!$i(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module,machineSpecific:cf(t.machineSpecific)}})}}function cf(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function df(e,t){if(!$i(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!pf(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function pf(e){return $i(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function $i(e){return typeof e=="object"&&e!==null}const hf=/^[a-z][a-z0-9.-]*$/u,uf=/^[a-z][a-z0-9.-]*$/u,ua=new WeakMap,fa=new WeakMap;class ff{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;this.validatePluginId(i);const o=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,o))return;this.pluginIds.add(i);const r=s.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(r)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:he}).contributions;for(const c of a.actions??[])this.actions.push(this.qualifyAction(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,c,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const c of a.themes??[])this.themes.push(this.qualifyTheme(i,c));for(const c of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,c));this.gatewayPluginIds.add(i),o&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&o&&bf(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=yf(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const o=gf(t,s.pluginId),r=s.enabled?.(o),n={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(o)};return s.description!==void 0&&(n.description=s.description),s.shortcut!==void 0&&(n.shortcut=s.shortcut),s.group!==void 0&&(n.group=s.group),r!==void 0&&(n.enabled=r),n})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,o){const r=this.qualify(t,i.id);return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...o===void 0?{}:{sourcePluginId:o}}}qualifyWorkspacePanel(t,i,s,o){const r=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(a?.(as(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,o)?n(as(c,t)):void 0},render:c=>i.render(as(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,o){const r=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,o)&&(n?.(c)??!0),items:c=>this.isContributionActive(t,s,c.machine.id,o)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}isContributionActive(t,i,s,o){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(o,i)}isRemoteDuplicateHiddenByGateway(t,i,s){return t!==void 0&&i!==void 0&&this.gatewayPluginIds.has(t)&&!this.gatewayMachineSpecificPluginIds.has(t)&&!s}isRemotePluginHiddenByGateway(t,i){return t===void 0||this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0?!1:this.gatewayPluginIds.has(t)}isGatewayPluginHiddenForMachine(t,i){return i!=="local"&&(this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0)}validatePluginId(t){if(!hf.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!uf.test(t))throw new Error(`Invalid contribution id: ${t}`)}parseMachineSpecific(t,i){if(i===void 0)return!1;if(typeof i!="boolean")throw new Error(`Invalid plugin machineSpecific value for ${t}: ${wf(i)}`);return i}}function gf(e,t){return ua.get(e)?.(t)??e}function as(e,t){return fa.get(e)?.(t)??e}function mf(e,t){return ua.set(e,t),e}function vf(e,t){return fa.set(e,t),e}function bf(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function wf(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"||typeof e=="symbol"||typeof e=="function"||e===null||e===void 0)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function yf(e){return e.state.selectedMachine?.id??"local"}const Sf=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function xf(){return typeof window>"u"||!("matchMedia"in window)?[]:Sf.map(e=>window.matchMedia(e))}function Ir(e,t=kf()){return e.some(i=>i.matches)||$f(t)}function kf(){return typeof navigator>"u"?void 0:navigator}function $f(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const Pf=250;class Rf{constructor(t=If()){this.scheduler=t}repair(t){if(!t){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},Pf)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);const t=this.scheduler.documentElement;t!==void 0&&(t.scrollTop=0);const i=this.scheduler.body;i!==void 0&&(i.scrollTop=0)}}function If(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>"u"?void 0:document.documentElement},get body(){return typeof document>"u"?void 0:document.body}}}const Cf="(max-width: 760px)",Tf="(max-width: 1180px)";class Af{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onStackedWorkspaceMediaChange=s=>{this.isStackedWorkspaceLayout!==s.matches&&(this.isStackedWorkspaceLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=Ir(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Mf(),this.stackedWorkspaceMedia=i.stackedWorkspaceMedia??Ef(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??xf(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Rf,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=Ir(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.addEventListener("change",this.onStackedWorkspaceMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.removeEventListener("change",this.onStackedWorkspaceMediaChange);for(const t of this.pwaDisplayModeMedia)t.removeEventListener("change",this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.normalizedMainView(void 0,!1)}normalizedMainView(t,i){return Df(t,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:i})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Mf(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Cf)}function Ef(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Tf)}function Df(e,t){const i=e??(t.isMobileNavigationLayout?"navigation":"chat");return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||i==="navigation"||i==="chat"?i:"chat"}const Pi=["machines","projects","workspaces","sessions"];function Wf(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function uo(e,t){if(e!=="none")return e??Wf(t)}function Of(e,t){return t.isMobileLayout?uo(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function _f(e,t,i){return uo(e,i.state)===t?"none":t}function Lf(e,t,i){return i?t:e}function jf(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),zf(i)}function Ff(e){return Pi[Pi.indexOf(e)+1]}class Nf{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return uo(this.expanded,this.getState())}isCollapsed(t){return Of(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(_f(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(jf(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(Lf(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=Ff(t);i!==void 0&&this.expand(i)}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}setCollapsedSections(t){Bf(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function zf(e){const t=new Set(e);return Pi.filter(i=>t.has(i))}function Bf(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class Uf{constructor(t){this.host=t,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,t.addController(this)}hostConnected(){}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(t){return["shell",ga(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function ga(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const Ls="pi-web:panel-sizes:v1",Hf={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class qf{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??fo(),this.panelSizes=Jf(this.storage)}hostConnected(){}constraints(t){return qt(t)}panelWidth(t,i){return ue(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const o=ue(t,i);this.storedPanelWidth(t)!==o&&(this.panelSizes=Xf(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Yf(this.panelSizes,t),i.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(t={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){Qf(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${Tr(ue("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${Tr(ue("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function qt(e){return Hf[e]}function Kf(e,t,i){return e==="navigation"?i-t:t-i}function Vf(e,t,i,s,o=qt(e)){return ue(e,t+Kf(e,i,s),o)}function Gf(e,t,i,s={}){const o=s.constraints??qt(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=eg(e,i,r);if(n!==void 0)return ue(e,t+n,o)}function ue(e,t,i=qt(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Jf(e=fo()){try{const t=e?.getItem(Ls);if(t==null||t==="")return{};const i=JSON.parse(t);return Zf(i)}catch{return{}}}function Qf(e,t=fo()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Ls);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=ue("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=ue("workspace",e.workspacePanelWidth)),t.setItem(Ls,JSON.stringify(i))}catch{}}function Zf(e){if(!tg(e)||e.version!==1)return{};const t={},i=Cr(e.navigationPanelWidth),s=Cr(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=ue("navigation",i)),s!==void 0&&(t.workspacePanelWidth=ue("workspace",s)),t}function Cr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Xf(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Yf(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function eg(e,t,i){if(e==="navigation")return t==="ArrowRight"?i:t==="ArrowLeft"?-i:void 0;if(t==="ArrowLeft")return i;if(t==="ArrowRight")return-i}function Tr(e){return`${String(Math.round(e))}px`}function fo(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function tg(e){return typeof e=="object"&&e!==null}function Ar(){const e=new URLSearchParams(window.location.search);return{machineId:e.get("machine")??void 0,projectId:e.get("project")??void 0,workspaceId:e.get("workspace")??void 0,sessionId:e.get("session")??void 0,tool:ig(e.get("tool")),view:sg(e.get("view"))}}function ls(e,t){const i=new URL(window.location.href);i.searchParams.delete("machine"),i.searchParams.delete("project"),i.searchParams.delete("workspace"),i.searchParams.delete("session"),i.searchParams.delete("tool"),i.searchParams.delete("view"),e.machineId!==void 0&&e.machineId!==""&&e.machineId!=="local"&&i.searchParams.set("machine",e.machineId),e.projectId!==void 0&&e.projectId!==""&&i.searchParams.set("project",e.projectId),e.workspaceId!==void 0&&e.workspaceId!==""&&i.searchParams.set("workspace",e.workspaceId),e.sessionId!==void 0&&e.sessionId!==""&&i.searchParams.set("session",e.sessionId),e.tool!==void 0&&i.searchParams.set("tool",e.tool),e.view!==void 0&&i.searchParams.set("view",e.view);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function ig(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":ma(e)?e:void 0}function sg(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":ma(e)?e:void 0}function ma(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Mr(){return og(new URLSearchParams(window.location.search).get("settings"))}function cs(e,t){const i=new URL(window.location.href);e===void 0?i.searchParams.delete("settings"):i.searchParams.set("settings",e);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&window.history.pushState({},"",i)}function og(e){if(e==="general")return"general";if(e==="sessiond"||e==="sessions")return"sessiond";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function rg(e,t){return t===void 0?e:e.map(i=>ag(i,t))}function ng(e,t){const i=new Set(co(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return rg(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?va(s):s)}function ag(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?va(e):{...e,shortcut:i}}function va(e){const t={...e};return delete t.shortcut,t}function lg(e,t){const i=t.api??pt,s=t.pollIntervalMs??1e3,o=t.setTimeout??dg(),r=t.clearTimeout??pg();return{async runCommand(n){const a=await i.runTerminalCommand(e,n);return n.open===!0&&t.openTerminal(n.workspace,{terminalId:a.terminalId}),{run:a,completed:cg(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function cg(e,t,i,s,o){return Er(e)?Promise.resolve(e):new Promise((r,n)=>{let a,c=!1;const p=g=>{c||(c=!0,a!==void 0&&o(a),r(g))},u=g=>{c||(c=!0,a!==void 0&&o(a),n(g instanceof Error?g:new Error(String(g))))},h=()=>{t.getCommandRun(e.id).then(g=>{if(g!==void 0&&Er(g)){p(g);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function Er(e){return e.status==="succeeded"||e.status==="failed"}function dg(){return(e,t)=>globalThis.setTimeout(e,t)}function pg(){return e=>{globalThis.clearTimeout(e)}}function hg(e,t){return t[e.path]}function ug(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function fg(e,t,i){return wa(gg(e,t,i))}function ba(e){return wa(Object.values(e??{}))}function wa(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function gg(e,t,i){const s=new Set(t.filter(r=>r.projectId===e.id).map(r=>r.path)),o=new Map;for(const r of s){const n=i[r];n!==void 0&&o.set(n.cwd,n)}for(const r of Object.values(i))(r.cwd===e.path||r.cwd.startsWith(`${e.path}/`))&&o.set(r.cwd,r);return[...o.values()]}function ya(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function ji(e,t="活跃"){const i=ya(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const Xt=0,mg=120;function Sa(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?xa():vg(e),o=window.innerWidth,r=window.innerHeight,n=Math.max(0,s.left),a=Math.min(o,s.right),c=Math.max(0,s.top),p=Math.min(r,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Xt,g=i.top-c-Xt;return[...h<mg&&g>h?[`bottom: ${lt(r-i.top+Xt)};`,`max-height: ${lt(Math.max(0,g))};`]:[`top: ${lt(i.bottom+Xt)};`,`max-height: ${lt(Math.max(0,h))};`],`right: ${lt(Math.max(0,o-u))};`,`max-width: ${lt(Math.max(0,u-n))};`].join(" ")}function vg(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():xa()}function xa(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function lt(e){return`${String(Math.round(e))}px`}class Fi{constructor(t){this.host=t,this.menuStyle="",this.onDocumentClick=i=>{i.composedPath().includes(this.host)||this.close()},t.addController(this)}hostConnected(){document.addEventListener("click",this.onDocumentClick)}hostDisconnected(){document.removeEventListener("click",this.onDocumentClick)}isOpen(t){return this.openId===t}toggle(t,i){if(this.openId===t){this.close();return}this.menuStyle=Sa(i,{constrainTo:"viewport"}),this.openId=t,this.host.requestUpdate()}close(){this.openId===void 0&&this.menuStyle===""||(this.openId=void 0,this.menuStyle="",this.host.requestUpdate())}closeIfOpenIdMissing(t){this.openId!==void 0&&!t(this.openId)&&this.close()}closeIf(t){t&&this.close()}closeForEscape(t,i){return t.key!=="Escape"||this.openId!==i?!1:(t.preventDefault(),t.stopPropagation(),this.close(),!0)}}const bg=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function ka(e){return e.composedPath().some(t=>wg(t,bg))}function wg(e,t){if(typeof Element<"u"&&e instanceof Element)return e.matches(t);if(!("matches"in e))return!1;const{matches:i}=e;return typeof i=="function"&&i.call(e,t)===!0}function Ni(e,t){ka(e)||t()}function zi(e,t){return ka(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?Ve(e,()=>{Dr(e.currentTarget,-1)}):e.key==="ArrowDown"?Ve(e,()=>{Dr(e.currentTarget,1)}):e.key==="Home"?Ve(e,()=>{Wr(e.currentTarget,0)}):e.key==="End"?Ve(e,()=>{Wr(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?Ve(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?Ve(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?Ve(e,t.cancel):!1}function Bi(e,t={}){const i=e.querySelector(".action-row.selected")??e.querySelector(".action-row")??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return i==null?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}function Ve(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function Dr(e,t){const i=Pa(e),s=Ra(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||$a(i,o+t)}function Wr(e,t){const i=Pa(e);i.length!==0&&$a(i,t<0?i.length-1:t)}function $a(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function Pa(e){const t=Ra(e)?.getRootNode();return t===void 0||!yg(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function yg(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function Ra(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const Ui=D`
136
136
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
137
137
  :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
138
138
  section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
@@ -193,7 +193,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
193
193
  .workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
194
194
  .workspace-detail-row .workspace-label-base, .workspace-detail-row .workspace-label-item, .workspace-detail-row .workspace-label-render { overflow: visible; text-overflow: clip; overflow-wrap: anywhere; white-space: normal; }
195
195
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
196
- `;var yg=Object.defineProperty,Sg=Object.getOwnPropertyDescriptor,be=(e,t,i,s)=>{for(var o=s>1?void 0:s?Sg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&yg(t,i,o),o};let te=class extends C{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menu=new ji(this)}updated(e){e.has("machines")&&this.menu.closeIfOpenIdMissing(t=>this.machines.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,zi(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
196
+ `;var Sg=Object.defineProperty,xg=Object.getOwnPropertyDescriptor,be=(e,t,i,s)=>{for(var o=s>1?void 0:s?xg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Sg(t,i,o),o};let te=class extends C{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menu=new Fi(this)}updated(e){e.has("machines")&&this.menu.closeIfOpenIdMissing(t=>this.machines.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,Bi(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
197
197
  <section>
198
198
  <h2>${this.renderHeading()}</h2>
199
199
  ${this.collapsed?null:l`
@@ -202,12 +202,12 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
202
202
  </div>
203
203
  `}
204
204
  </section>
205
- `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=Ra(e)&&this.onRemove!==void 0;return l`
205
+ `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=Ia(e)&&this.onRemove!==void 0;return l`
206
206
  <div
207
207
  class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
208
208
  tabindex="0"
209
209
  title=${e.baseUrl??e.name}
210
- @click=${o=>{Fi(o,()=>this.onSelect?.(e))}}
210
+ @click=${o=>{Ni(o,()=>this.onSelect?.(e))}}
211
211
  @keydown=${o=>{this.handleMachineKeydown(o,e)}}
212
212
  >
213
213
  <div class="action-main">
@@ -215,7 +215,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
215
215
  </div>
216
216
  ${s?this.renderMachineMenu(e):null}
217
217
  </div>
218
- `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=va(this.activities[e.id]);return Li(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.menu.isOpen(e.id),i=xg(e.id);return l`
218
+ `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=ba(this.activities[e.id]);return ji(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.menu.isOpen(e.id),i=kg(e.id);return l`
219
219
  <div class="action-menu">
220
220
  <button
221
221
  class="action-menu-toggle"
@@ -231,13 +231,13 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
231
231
  </div>
232
232
  `:null}
233
233
  </div>
234
- `}renderHeading(){if(!this.collapsible)return"机器";const e=this.selected?.name??"未选择机器",t=this.selected?.baseUrl??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 机器</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}removeMachine(e){this.menu.close(),this.onRemove?.(e)}handleMachineKeydown(e,t){this.menu.closeForEscape(e,t.id)||Ni(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};te.styles=[Bi,D`
234
+ `}renderHeading(){if(!this.collapsible)return"机器";const e=this.selected?.name??"未选择机器",t=this.selected?.baseUrl??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 机器</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}removeMachine(e){this.menu.close(),this.onRemove?.(e)}handleMachineKeydown(e,t){this.menu.closeForEscape(e,t.id)||zi(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};te.styles=[Ui,D`
235
235
  .machine-row.no-actions .action-main { border-radius: 8px; }
236
236
  .machine-primary { display: flex; align-items: baseline; gap: 6px; }
237
237
  .machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
238
238
  .machine-menu-panel button.danger { color: var(--pi-danger); }
239
239
  .machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
240
- `];be([d({attribute:!1})],te.prototype,"machines",2);be([d({attribute:!1})],te.prototype,"selected",2);be([d({attribute:!1})],te.prototype,"statuses",2);be([d({attribute:!1})],te.prototype,"activities",2);be([d({type:Boolean,reflect:!0})],te.prototype,"collapsible",2);be([d({type:Boolean,reflect:!0})],te.prototype,"collapsed",2);be([d({attribute:!1})],te.prototype,"onSelect",2);be([d({attribute:!1})],te.prototype,"onRemove",2);be([d({attribute:!1})],te.prototype,"onToggleCollapsed",2);be([d({attribute:!1})],te.prototype,"onFocusNextSection",2);be([d({attribute:!1})],te.prototype,"onCancelKeyboardNavigation",2);te=be([W("machine-list")],te);function Ra(e){return e.kind==="remote"}function xg(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var kg=Object.defineProperty,$g=Object.getOwnPropertyDescriptor,de=(e,t,i,s)=>{for(var o=s>1?void 0:s?$g(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&kg(t,i,o),o};let X=class extends C{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menu=new ji(this)}updated(e){e.has("projects")&&this.menu.closeIfOpenIdMissing(t=>this.projects.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,zi(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
240
+ `];be([d({attribute:!1})],te.prototype,"machines",2);be([d({attribute:!1})],te.prototype,"selected",2);be([d({attribute:!1})],te.prototype,"statuses",2);be([d({attribute:!1})],te.prototype,"activities",2);be([d({type:Boolean,reflect:!0})],te.prototype,"collapsible",2);be([d({type:Boolean,reflect:!0})],te.prototype,"collapsed",2);be([d({attribute:!1})],te.prototype,"onSelect",2);be([d({attribute:!1})],te.prototype,"onRemove",2);be([d({attribute:!1})],te.prototype,"onToggleCollapsed",2);be([d({attribute:!1})],te.prototype,"onFocusNextSection",2);be([d({attribute:!1})],te.prototype,"onCancelKeyboardNavigation",2);te=be([W("machine-list")],te);function Ia(e){return e.kind==="remote"}function kg(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var $g=Object.defineProperty,Pg=Object.getOwnPropertyDescriptor,de=(e,t,i,s)=>{for(var o=s>1?void 0:s?Pg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&$g(t,i,o),o};let X=class extends C{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menu=new Fi(this)}updated(e){e.has("projects")&&this.menu.closeIfOpenIdMissing(t=>this.projects.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,Bi(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
241
241
  <section>
242
242
  <h2>${this.renderHeading()}</h2>
243
243
  ${this.collapsed?null:l`
@@ -252,7 +252,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
252
252
  class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
253
253
  tabindex="0"
254
254
  title=${e.path}
255
- @click=${t=>{Fi(t,()=>this.onSelect?.(e))}}
255
+ @click=${t=>{Ni(t,()=>this.onSelect?.(e))}}
256
256
  @keydown=${t=>{this.handleProjectKeydown(t,e)}}
257
257
  >
258
258
  <div class="action-main">
@@ -272,19 +272,19 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
272
272
  </div>
273
273
  `}
274
274
  </section>
275
- `}handleProjectKeydown(e,t){Ni(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return"项目";const e=this.selected?.name??"未选择项目",t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 项目</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=ug(e,this.workspacesByProjectId[e.id]??[],this.activities);return Li(t,t==="terminal"?"项目终端活跃":"项目活跃")}close(e){this.menu.close(),confirm(`关闭 ${e.name}?
275
+ `}handleProjectKeydown(e,t){zi(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return"项目";const e=this.selected?.name??"未选择项目",t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 项目</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=fg(e,this.workspacesByProjectId[e.id]??[],this.activities);return ji(t,t==="terminal"?"项目终端活跃":"项目活跃")}close(e){this.menu.close(),confirm(`关闭 ${e.name}?
276
276
 
277
- 这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};X.styles=Bi;de([d({attribute:!1})],X.prototype,"projects",2);de([d({attribute:!1})],X.prototype,"selected",2);de([d({attribute:!1})],X.prototype,"activities",2);de([d({attribute:!1})],X.prototype,"workspacesByProjectId",2);de([d({type:Boolean,reflect:!0})],X.prototype,"collapsible",2);de([d({type:Boolean,reflect:!0})],X.prototype,"collapsed",2);de([d({attribute:!1})],X.prototype,"onSelect",2);de([d({attribute:!1})],X.prototype,"onClose",2);de([d({attribute:!1})],X.prototype,"onToggleCollapsed",2);de([d({attribute:!1})],X.prototype,"onFocusPreviousSection",2);de([d({attribute:!1})],X.prototype,"onFocusNextSection",2);de([d({attribute:!1})],X.prototype,"onCancelKeyboardNavigation",2);X=de([W("project-list")],X);function Wr(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Pg(t)}`)}function Pg(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&Rg(e.href)){const t=e.target??"_blank",i=t==="_blank"?"noopener noreferrer":void 0;return l`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${i??void 0}>${e.text}</a>`}return l`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function Rg(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var Ig=Object.defineProperty,Cg=Object.getOwnPropertyDescriptor,ne=(e,t,i,s)=>{for(var o=s>1?void 0:s?Cg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ig(t,i,o),o};let J=class extends C{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menu=new ji(this)}updated(e){e.has("workspaces")&&this.menu.closeIfOpenIdMissing(t=>this.workspaces.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,zi(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
277
+ 这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};X.styles=Ui;de([d({attribute:!1})],X.prototype,"projects",2);de([d({attribute:!1})],X.prototype,"selected",2);de([d({attribute:!1})],X.prototype,"activities",2);de([d({attribute:!1})],X.prototype,"workspacesByProjectId",2);de([d({type:Boolean,reflect:!0})],X.prototype,"collapsible",2);de([d({type:Boolean,reflect:!0})],X.prototype,"collapsed",2);de([d({attribute:!1})],X.prototype,"onSelect",2);de([d({attribute:!1})],X.prototype,"onClose",2);de([d({attribute:!1})],X.prototype,"onToggleCollapsed",2);de([d({attribute:!1})],X.prototype,"onFocusPreviousSection",2);de([d({attribute:!1})],X.prototype,"onFocusNextSection",2);de([d({attribute:!1})],X.prototype,"onCancelKeyboardNavigation",2);X=de([W("project-list")],X);function Or(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Rg(t)}`)}function Rg(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&Ig(e.href)){const t=e.target??"_blank",i=t==="_blank"?"noopener noreferrer":void 0;return l`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${i??void 0}>${e.text}</a>`}return l`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function Ig(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var Cg=Object.defineProperty,Tg=Object.getOwnPropertyDescriptor,ne=(e,t,i,s)=>{for(var o=s>1?void 0:s?Tg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Cg(t,i,o),o};let J=class extends C{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menu=new Fi(this)}updated(e){e.has("workspaces")&&this.menu.closeIfOpenIdMissing(t=>this.workspaces.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Bi(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
278
278
  <section>
279
279
  <h2>${this.renderHeading()}</h2>
280
280
  ${this.collapsed?null:l`
281
281
  <div class="list-body">
282
- ${this.workspaces.map(e=>{const t=Tg(e),i=this.workspaceLabelItems(e);return l`
282
+ ${this.workspaces.map(e=>{const t=Ag(e),i=this.workspaceLabelItems(e);return l`
283
283
  <div
284
284
  class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
285
285
  tabindex="0"
286
286
  title=${t}
287
- @click=${s=>{Fi(s,()=>this.onSelect?.(e))}}
287
+ @click=${s=>{Ni(s,()=>this.onSelect?.(e))}}
288
288
  @keydown=${s=>{this.handleWorkspaceKeydown(s,e)}}
289
289
  >
290
290
  <div class="action-main">
@@ -296,18 +296,18 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
296
296
  </div>
297
297
  `}
298
298
  </section>
299
- `}renderHeading(){if(!this.collapsible)return"工作区";const e=this.selected===void 0?"未选择工作区":`${this.selected.label}${this.selected.isMain?" · 主工作区":""} · ${this.selected.path}`,t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 工作区</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=hg(pg(e,this.activities));return Li(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return l`
299
+ `}renderHeading(){if(!this.collapsible)return"工作区";const e=this.selected===void 0?"未选择工作区":`${this.selected.label}${this.selected.isMain?" · 主工作区":""} · ${this.selected.path}`,t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 工作区</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=ug(hg(e,this.activities));return ji(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return l`
300
300
  <span class="workspace-primary">
301
301
  <span class="workspace-primary-label">${e}</span>
302
302
  ${this.isDeleting(i)?l`<span class="workspace-status">正在删除…</span>`:null}
303
303
  </span>
304
304
  ${t.length===0?null:l`
305
305
  <small class="workspace-secondary">
306
- <span class="workspace-label">${Wr(t)}</span>
306
+ <span class="workspace-label">${Or(t)}</span>
307
307
  </small>
308
308
  `}
309
309
  ${this.renderActivity(i)}
310
- `}renderWorkspaceMenu(e,t,i){const s=this.menu.isOpen(i.id),o=Mg(i.id);return l`
310
+ `}renderWorkspaceMenu(e,t,i){const s=this.menu.isOpen(i.id),o=Eg(i.id);return l`
311
311
  <div class="action-menu">
312
312
  <button
313
313
  class="action-menu-toggle"
@@ -324,7 +324,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
324
324
  </div>
325
325
  `:null}
326
326
  </div>
327
- `}renderWorkspaceActions(e){if(!Ag(e))return;const t=this.isDeleting(e);return l`
327
+ `}renderWorkspaceActions(e){if(!Mg(e))return;const t=this.isDeleting(e);return l`
328
328
  <div class="workspace-menu-actions">
329
329
  <button class="danger" title=${t?"正在删除工作区":"删除工作区"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"正在删除…":"删除工作区"}</button>
330
330
  </div>
@@ -341,11 +341,11 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
341
341
  ${t.length===0?null:l`
342
342
  <div class="workspace-detail-row">
343
343
  <dt>详情</dt>
344
- <dd><span class="workspace-label">${Wr(t)}</span></dd>
344
+ <dd><span class="workspace-label">${Or(t)}</span></dd>
345
345
  </div>
346
346
  `}
347
347
  </dl>
348
- `}delete(e){this.isDeleting(e)||(this.menu.close(),this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}handleWorkspaceKeydown(e,t){this.menu.closeForEscape(e,t.id)||Ni(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};J.styles=Bi;ne([d({attribute:!1})],J.prototype,"workspaces",2);ne([d({attribute:!1})],J.prototype,"selected",2);ne([d({type:Boolean,reflect:!0})],J.prototype,"collapsible",2);ne([d({type:Boolean,reflect:!0})],J.prototype,"collapsed",2);ne([d({attribute:!1})],J.prototype,"workspaceLabelItems",2);ne([d({attribute:!1})],J.prototype,"activities",2);ne([d({attribute:!1})],J.prototype,"deletingWorkspaceIds",2);ne([d({attribute:!1})],J.prototype,"onSelect",2);ne([d({attribute:!1})],J.prototype,"onDelete",2);ne([d({attribute:!1})],J.prototype,"onToggleCollapsed",2);ne([d({attribute:!1})],J.prototype,"onFocusPreviousSection",2);ne([d({attribute:!1})],J.prototype,"onFocusNextSection",2);ne([d({attribute:!1})],J.prototype,"onCancelKeyboardNavigation",2);J=ne([W("workspace-list")],J);function Tg(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function Ag(e){return e.isGitWorktree&&!e.isMain}function Mg(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Eg=Object.defineProperty,Dg=Object.getOwnPropertyDescriptor,A=(e,t,i,s)=>{for(var o=s>1?void 0:s?Dg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Eg(t,i,o),o};function $t(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let T=class extends C{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.collapsible=!1,this.collapsed=!1,this.menu=new ji(this),this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set}updated(e){e.has("sessions")&&(this.menu.closeIfOpenIdMissing(i=>this.sessions.some(s=>s.id===i)),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.menu.closeIf(this.collapsed);const t=e.get("selected");if(e.has("selected")&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(e.has("selected")||e.has("sessions")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,zi(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=_g(this.sessions),t=new Set(e.map(r=>r.session.id)),i=e.map(r=>r.session).filter(r=>Pt(r)==="current"),s=Ia(this.sessions.filter(r=>r.archived===!0&&!t.has(r.id))),o=Wg(this.sessions);return l`
348
+ `}delete(e){this.isDeleting(e)||(this.menu.close(),this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}handleWorkspaceKeydown(e,t){this.menu.closeForEscape(e,t.id)||zi(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};J.styles=Ui;ne([d({attribute:!1})],J.prototype,"workspaces",2);ne([d({attribute:!1})],J.prototype,"selected",2);ne([d({type:Boolean,reflect:!0})],J.prototype,"collapsible",2);ne([d({type:Boolean,reflect:!0})],J.prototype,"collapsed",2);ne([d({attribute:!1})],J.prototype,"workspaceLabelItems",2);ne([d({attribute:!1})],J.prototype,"activities",2);ne([d({attribute:!1})],J.prototype,"deletingWorkspaceIds",2);ne([d({attribute:!1})],J.prototype,"onSelect",2);ne([d({attribute:!1})],J.prototype,"onDelete",2);ne([d({attribute:!1})],J.prototype,"onToggleCollapsed",2);ne([d({attribute:!1})],J.prototype,"onFocusPreviousSection",2);ne([d({attribute:!1})],J.prototype,"onFocusNextSection",2);ne([d({attribute:!1})],J.prototype,"onCancelKeyboardNavigation",2);J=ne([W("workspace-list")],J);function Ag(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function Mg(e){return e.isGitWorktree&&!e.isMain}function Eg(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Dg=Object.defineProperty,Wg=Object.getOwnPropertyDescriptor,A=(e,t,i,s)=>{for(var o=s>1?void 0:s?Wg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Dg(t,i,o),o};function Pt(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let T=class extends C{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.collapsible=!1,this.collapsed=!1,this.menu=new Fi(this),this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set}updated(e){e.has("sessions")&&(this.menu.closeIfOpenIdMissing(i=>this.sessions.some(s=>s.id===i)),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.menu.closeIf(this.collapsed);const t=e.get("selected");if(e.has("selected")&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(e.has("selected")||e.has("sessions")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Bi(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=Lg(this.sessions),t=new Set(e.map(r=>r.session.id)),i=e.map(r=>r.session).filter(r=>Rt(r)==="current"),s=Ca(this.sessions.filter(r=>r.archived===!0&&!t.has(r.id))),o=Og(this.sessions);return l`
349
349
  <section>
350
350
  ${this.renderHeading(e.length+s.length,i)}
351
351
  ${this.collapsed?null:l`
@@ -368,7 +368,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
368
368
  ${this.renderCurrentSelectionButton(t)}
369
369
  <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button>
370
370
  </h2>
371
- `;const i=this.selected===void 0?"未选择会话":$t(this.selected),s=this.selected?.path??i;return l`
371
+ `;const i=this.selected===void 0?"未选择会话":Pt(this.selected),s=this.selected?.path??i;return l`
372
372
  <h2>
373
373
  <button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 会话</span>${this.collapsed?l`<small class="section-selected" title=${s}>${i}</small>`:null}</span></button>
374
374
  ${this.renderCurrentSelectionButton(t)}
@@ -398,18 +398,18 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
398
398
  <button @click=${()=>{this.closeSelection("archived")}}>完成</button>
399
399
  ${this.canDeleteArchived?null:l`<small class="capability-hint">${this.archivedDeleteUnavailableMessage}</small>`}
400
400
  </div>
401
- `}renderSession(e,t,i){const{session:s}=e,o=Math.min(e.depth,2),r=Pt(s)===i,n=this.selectionScopes.has(i),a=n&&r,c=a&&this.selectedSessionIds.has(s.id);return l`
401
+ `}renderSession(e,t,i){const{session:s}=e,o=Math.min(e.depth,2),r=Rt(s)===i,n=this.selectionScopes.has(i),a=n&&r,c=a&&this.selectedSessionIds.has(s.id);return l`
402
402
  <div
403
403
  class="action-row ${this.selected?.id===s.id?"selected":""} ${c?"bulk-selected":""} ${s.archived===!0?"archived":""} ${n?"selecting":""}"
404
404
  style=${`--depth:${String(o)}`}
405
405
  tabindex="0"
406
406
  title=${s.path}
407
- @click=${p=>{Fi(p,()=>{this.activateSessionRow(s,i)})}}
407
+ @click=${p=>{Ni(p,()=>{this.activateSessionRow(s,i)})}}
408
408
  @keydown=${p=>{this.handleSessionKeydown(p,s,i)}}
409
409
  >
410
410
  <div class="action-main ${n?"selecting":""}">
411
- ${a?l`<input class="session-checkbox" type="checkbox" aria-label=${`选择 ${$t(s)}`} .checked=${c} @click=${p=>{p.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
412
- <span class="action-name">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${$t(s)}${e.depth>2?l` <span class="badge">深度 ${e.depth}</span>`:null}${e.hasMissingParent?l` <span class="badge">父会话不可用</span>`:null}</span><small>${this.renderSessionMetaPrefix(s)}${String(s.messageCount)} 条消息</small>
411
+ ${a?l`<input class="session-checkbox" type="checkbox" aria-label=${`选择 ${Pt(s)}`} .checked=${c} @click=${p=>{p.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
412
+ <span class="action-name">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${Pt(s)}${e.depth>2?l` <span class="badge">深度 ${e.depth}</span>`:null}${e.hasMissingParent?l` <span class="badge">父会话不可用</span>`:null}</span><small>${this.renderSessionMetaPrefix(s)}${String(s.messageCount)} 条消息</small>
413
413
  ${this.renderActivity(s)}
414
414
  </div>
415
415
  <div class="action-menu">
@@ -420,7 +420,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
420
420
  <button title="恢复会话" @click=${()=>{this.menu.close(),this.onRestore?.(s)}}>恢复</button>
421
421
  <button class="danger" title=${this.canDeleteArchived?"永久删除已归档会话":this.archivedDeleteUnavailableMessage} ?disabled=${!this.canDeleteArchived} @click=${()=>{this.menu.close(),this.confirmDeleteArchived(s)}}>删除已归档会话</button>
422
422
  `:l`
423
- ${this.canReload?l`<button title=${Xe(this.statuses[s.id],this.activities[s.id])?"当前会话活动结束后才能重新加载":"从磁盘重新加载会话"} ?disabled=${Xe(this.statuses[s.id],this.activities[s.id])} @click=${()=>{this.menu.close(),this.onReload?.(s)}}>重新加载</button>`:null}
423
+ ${this.canReload?l`<button title=${Ye(this.statuses[s.id],this.activities[s.id])?"当前会话活动结束后才能重新加载":"从磁盘重新加载会话"} ?disabled=${Ye(this.statuses[s.id],this.activities[s.id])} @click=${()=>{this.menu.close(),this.onReload?.(s)}}>重新加载</button>`:null}
424
424
  ${s.parentSessionPath!==void 0?l`<button title="从父会话分离" @click=${()=>{this.menu.close(),this.onDetachParent?.(s)}}>从父会话分离</button>`:null}
425
425
  <button title="归档会话" @click=${()=>{this.menu.close(),this.onArchive?.(s)}}>归档</button>
426
426
  ${t>0?l`<button title="归档此会话及其后代会话" @click=${()=>{this.menu.close(),this.confirmArchiveWithDescendants(s,t)}}>连同后代归档(${t})</button>`:null}
@@ -429,7 +429,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
429
429
  `:null}
430
430
  </div>
431
431
  </div>
432
- `}handleSessionKeydown(e,t,i){Ni(e,{activate:()=>{this.activateSessionRow(t,i)},previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}activateSessionRow(e,t){if(this.selectionScopes.has(t)&&Pt(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){confirm(`归档“${$t(e)}”及其 ${String(t)} 个后代会话?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`永久删除已归档会话“${$t(e)}”?此操作无法撤销。`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");e.length!==0&&confirm(`永久删除 ${String(e.length)} 个所选已归档会话?此操作无法撤销。`)&&(this.selectedSessionIds=cs(this.selectedSessionIds,e.map(t=>t.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>!Z(t));this.selectedSessionIds=cs(this.selectedSessionIds,e.map(t=>t.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){if(this.selectionScopes.has(e)){this.closeSelection(e);return}this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);const i=t.length===1?t[0]:void 0;i!==void 0&&(this.selectedSessionIds=new Set([...this.selectedSessionIds,i.id]))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){const t=this.sessions.filter(i=>Pt(i)===e).map(i=>i.id);this.selectedSessionIds=cs(this.selectedSessionIds,t)}toggleSelected(e){const t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}toggleVisibleSelection(e,t){const i=new Set(this.selectedSessionIds);for(const s of e)t?i.add(s.id):i.delete(s.id);this.selectedSessionIds=i}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&Pt(t)===e)}pruneSelectedSessionIds(){const e=new Set(this.sessions.map(i=>i.id)),t=new Set([...this.selectedSessionIds].filter(i=>e.has(i)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has("archived")&&!this.sessions.some(i=>i.archived===!0)&&this.closeSelection("archived"),this.selectionScopes.has("current")&&!this.sessions.some(i=>i.archived!==!0)&&this.closeSelection("current")}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.menu.close(),this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return Z(e)?"新建 · ":e.archived===!0?"只读 · ":""}renderActivity(e){const t=Og(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return Li(t,t==="sending"?"正在发送消息":"会话活跃")}};T.styles=[Bi,D`
432
+ `}handleSessionKeydown(e,t,i){zi(e,{activate:()=>{this.activateSessionRow(t,i)},previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}activateSessionRow(e,t){if(this.selectionScopes.has(t)&&Rt(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){confirm(`归档“${Pt(e)}”及其 ${String(t)} 个后代会话?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`永久删除已归档会话“${Pt(e)}”?此操作无法撤销。`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");e.length!==0&&confirm(`永久删除 ${String(e.length)} 个所选已归档会话?此操作无法撤销。`)&&(this.selectedSessionIds=ds(this.selectedSessionIds,e.map(t=>t.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>!Z(t));this.selectedSessionIds=ds(this.selectedSessionIds,e.map(t=>t.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){if(this.selectionScopes.has(e)){this.closeSelection(e);return}this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);const i=t.length===1?t[0]:void 0;i!==void 0&&(this.selectedSessionIds=new Set([...this.selectedSessionIds,i.id]))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){const t=this.sessions.filter(i=>Rt(i)===e).map(i=>i.id);this.selectedSessionIds=ds(this.selectedSessionIds,t)}toggleSelected(e){const t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}toggleVisibleSelection(e,t){const i=new Set(this.selectedSessionIds);for(const s of e)t?i.add(s.id):i.delete(s.id);this.selectedSessionIds=i}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&Rt(t)===e)}pruneSelectedSessionIds(){const e=new Set(this.sessions.map(i=>i.id)),t=new Set([...this.selectedSessionIds].filter(i=>e.has(i)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has("archived")&&!this.sessions.some(i=>i.archived===!0)&&this.closeSelection("archived"),this.selectionScopes.has("current")&&!this.sessions.some(i=>i.archived!==!0)&&this.closeSelection("current")}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.menu.close(),this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return Z(e)?"新建 · ":e.archived===!0?"只读 · ":""}renderActivity(e){const t=_g(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return ji(t,t==="sending"?"正在发送消息":"会话活跃")}};T.styles=[Ui,D`
433
433
  h2 { min-height: 30px; }
434
434
  h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
435
435
  .bulk-select-entry { box-sizing: border-box; flex: 0 0 auto; display: inline-grid; place-items: center; width: 30px; height: 30px; padding: 0; font-size: 13px; line-height: 1; text-transform: none; }
@@ -443,7 +443,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
443
443
  .action-row.bulk-selected .action-main { border-color: var(--pi-accent); box-shadow: inset 3px 0 0 var(--pi-accent); }
444
444
  .action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
445
445
  .session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
446
- `];A([d({attribute:!1})],T.prototype,"sessions",2);A([d({attribute:!1})],T.prototype,"statuses",2);A([d({attribute:!1})],T.prototype,"activities",2);A([d({attribute:!1})],T.prototype,"sending",2);A([d({attribute:!1})],T.prototype,"selected",2);A([d({type:Boolean})],T.prototype,"canStart",2);A([d({type:Boolean})],T.prototype,"canDeleteArchived",2);A([d({type:Boolean})],T.prototype,"canReload",2);A([d({type:String})],T.prototype,"archivedDeleteUnavailableMessage",2);A([d({type:Boolean,reflect:!0})],T.prototype,"collapsible",2);A([d({type:Boolean,reflect:!0})],T.prototype,"collapsed",2);A([d({attribute:!1})],T.prototype,"onSelect",2);A([d({attribute:!1})],T.prototype,"onStart",2);A([d({attribute:!1})],T.prototype,"onToggleCollapsed",2);A([d({attribute:!1})],T.prototype,"onArchivedCollapsed",2);A([d({attribute:!1})],T.prototype,"onFocusPreviousSection",2);A([d({attribute:!1})],T.prototype,"onFocusNextSection",2);A([d({attribute:!1})],T.prototype,"onCancelKeyboardNavigation",2);A([d({attribute:!1})],T.prototype,"onArchive",2);A([d({attribute:!1})],T.prototype,"onArchiveWithDescendants",2);A([d({attribute:!1})],T.prototype,"onArchiveMany",2);A([d({attribute:!1})],T.prototype,"onRestore",2);A([d({attribute:!1})],T.prototype,"onDelete",2);A([d({attribute:!1})],T.prototype,"onDeleteArchived",2);A([d({attribute:!1})],T.prototype,"onDeleteArchivedMany",2);A([d({attribute:!1})],T.prototype,"onDetachParent",2);A([d({attribute:!1})],T.prototype,"onReload",2);A([k()],T.prototype,"archivedExpanded",2);A([k()],T.prototype,"selectionScopes",2);A([k()],T.prototype,"selectedSessionIds",2);T=A([W("session-list")],T);function Pt(e){return e.archived===!0?"archived":"current"}function cs(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function Wg(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const o=t.get(s.parentSessionPath)??[];o.push(s),t.set(s.parentSessionPath,o)}const i=(s,o)=>{if(o.has(s.path))return 0;const r=new Set(o);r.add(s.path);let n=0;for(const a of t.get(s.path)??[])r.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,r));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function Og(e,t,i,s){if(!(Z(e)||e.archived===!0))return s?"sending":Xe(t,i)?"session":void 0}function _g(e){const t=new Map(e.map(s=>[s.path,s])),i=new Set;for(const s of e){if(s.archived===!0)continue;i.add(s.id);let o=s.parentSessionPath;const r=new Set([s.path]);for(;o!==void 0&&!r.has(o);){r.add(o);const n=t.get(o);if(n===void 0)break;i.add(n.id),o=n.parentSessionPath}}return Ia(e.filter(s=>i.has(s.id)))}function Ia(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,c=a===void 0?void 0:t.get(a);if(c===void 0){s.push(n);continue}const p=i.get(c.path)??[];p.push(n),i.set(c.path,p)}const o=[],r=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;o.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])r(h,a+1,u)};for(const n of s)r(n,0,new Set);return o}const fo={CHILD:2,ELEMENT:6},go=e=>(...t)=>({_$litDirective$:e,values:t});let mo=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,i,s){this._$Ct=t,this._$AM=i,this._$Ci=s}_$AS(t,i){return this.update(t,i)}update(t,i){return this.render(...i)}};const{I:Lg}=Ml,Or=e=>e,_r=()=>document.createComment(""),Rt=(e,t,i)=>{const s=e._$AA.parentNode,o=t===void 0?e._$AB:t._$AA;if(i===void 0){const r=s.insertBefore(_r(),o),n=s.insertBefore(_r(),o);i=new Lg(r,n,e,e.options)}else{const r=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let c;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(c=e._$AU)!==n._$AU&&i._$AP(c)}if(r!==o||a){let c=i._$AA;for(;c!==r;){const p=Or(c).nextSibling;Or(s).insertBefore(c,o),c=p}}}return i},Ve=(e,t,i=e)=>(e._$AI(t,i),e),jg={},Fg=(e,t=jg)=>e._$AH=t,Ng=e=>e._$AH,ds=e=>{e._$AR(),e._$AA.remove()};const Lr=(e,t,i)=>{const s=new Map;for(let o=t;o<=i;o++)s.set(e[o],o);return s},zg=go(class extends mo{constructor(e){if(super(e),e.type!==fo.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let s;i===void 0?i=t:t!==void 0&&(s=t);const o=[],r=[];let n=0;for(const a of e)o[n]=s?s(a,n):n,r[n]=i(a,n),n++;return{values:r,keys:o}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const o=Ng(e),{values:r,keys:n}=this.dt(t,i,s);if(!Array.isArray(o))return this.ut=n,r;const a=this.ut??=[],c=[];let p,u,h=0,g=o.length-1,w=0,P=r.length-1;for(;h<=g&&w<=P;)if(o[h]===null)h++;else if(o[g]===null)g--;else if(a[h]===n[w])c[w]=Ve(o[h],r[w]),h++,w++;else if(a[g]===n[P])c[P]=Ve(o[g],r[P]),g--,P--;else if(a[h]===n[P])c[P]=Ve(o[h],r[P]),Rt(e,c[P+1],o[h]),h++,P--;else if(a[g]===n[w])c[w]=Ve(o[g],r[w]),Rt(e,o[h],o[g]),g--,w++;else if(p===void 0&&(p=Lr(n,w,P),u=Lr(a,h,g)),p.has(a[h]))if(p.has(a[g])){const H=u.get(n[w]),ot=H!==void 0?o[H]:null;if(ot===null){const vt=Rt(e,o[h]);Ve(vt,r[w]),c[w]=vt}else c[w]=Ve(ot,r[w]),Rt(e,o[h],ot),o[H]=null;w++}else ds(o[g]),g--;else ds(o[h]),h++;for(;w<=P;){const H=Rt(e,c[P+1]);Ve(H,r[w]),c[w++]=H}for(;h<=g;){const H=o[h++];H!==null&&ds(H)}return this.ut=n,Fg(e,c),Ue}}),Bg="pi-web:chat-groups:",Ug={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(jr(e));return t===null||t===""?void 0:qg(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(jr(e),JSON.stringify(t))}catch{}}};class Hg{constructor(t=Ug){this.storage=t,this.sessionId="",this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(t){if(this.sessionId===t)return;this.sessionId=t;const i=t===""?void 0:this.storage.read(t);this.openGroupKeys=new Set(i?.open??[]),this.closedDefaultOpenGroupKeys=new Set(i?.closedDefaultOpen??[])}isOpen(t,i){return i?!this.closedDefaultOpenGroupKeys.has(t):this.openGroupKeys.has(t)}applyToggle(t,i,s){const o=this.isOpen(t,s),r=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(r.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?r.add(t):r.delete(t)),(s?!n.has(t):r.has(t))===o&&Fr(r,this.openGroupKeys)&&Fr(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=r,this.closedDefaultOpenGroupKeys=n,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==""&&this.storage.write(this.sessionId,this.snapshot())}}function jr(e){return`${Bg}${e}`}function qg(e){if(Array.isArray(e))return{open:ps(e),closedDefaultOpen:[]};if(Kg(e))return{open:Array.isArray(e.open)?ps(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?ps(e.closedDefaultOpen):[]}}function ps(e){return e.filter(t=>typeof t=="string")}function Fr(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Kg(e){return typeof e=="object"&&e!==null}function Vg(e,t=0){const i=[];let s=[],o=0;const r=(a,c)=>{s.length||(o=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:o,endIndex:o+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(w=>Nr(a,w)),u=a.parts.filter(w=>!Nr(a,w)),h=t+c,g={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&r({role:a.role,parts:u,...g},h),p.length){n();const w=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:w,parts:p,...g},index:h})}}),n(),i}function Gg(e){if(e.every(s=>s.source==="compaction"))return`${String(e.length)} 条历史压缩摘要`;if(e.every(s=>s.source==="branch_summary"))return`${String(e.length)} 条分支摘要`;const t=e.reduce((s,o)=>(s[o.role]=(s[o.role]??0)+1,s),{}),i=Object.entries(t).map(([s,o])=>`${String(o)} ${Jg(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Jg(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Nr(e,t){return e.source==="compaction"||e.source==="branch_summary"?!1:t.type==="skillInvocation"||t.type==="skillRead"?!0:t.type==="text"&&(e.role==="user"||e.role==="assistant"||e.role==="system"||e.role==="bash")}const Qg=30;function Zg(e,t){const i=Yg(im(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Xg(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=em(s,t.markerOffset);return}e.scrollTop=tm(e.scrollHeight,t.distanceFromBottom)}function Yg(e){let t,i=Number.NEGATIVE_INFINITY,s,o=Number.POSITIVE_INFINITY;for(const r of e)r.offset<=0&&r.offset>=i?(t=r,i=r.offset):r.offset>0&&r.offset<o&&(s=r,o=r.offset);return t??s}function em(e,t){return e-t}function tm(e,t){return Math.max(0,e-t)}function im(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const o=s.dataset.markerId;return o===void 0?[]:[{id:o,offset:s.getBoundingClientRect().top-i}]})}const sm=600,om=1;function rm(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:nm(e)||am(e)}function nm(e){return e.scrollTop<(e.topThreshold??Math.max(sm,e.clientHeight))}function am(e){return e.scrollHeight<=e.clientHeight+om}const lm="pi-web:chat-scroll:",cm=180,dm=48,pm=2,hm={getItem(e){return typeof localStorage>"u"?null:localStorage.getItem(e)},setItem(e,t){typeof localStorage>"u"||localStorage.setItem(e,t)},removeItem(e){typeof localStorage>"u"||localStorage.removeItem(e)}},um={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class fm{constructor(t=hm,i=um){this.storage=t,this.scheduler=i}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(t,i,s=cm){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,o=pm){if(t===""||i===void 0||!us(i))return"skipped";try{if(Ta(i,o)){const a={mode:"bottom"};return this.storage.setItem(hs(t),JSON.stringify(a)),"saved"}const r=vm(i,s);if(r===void 0)return"skipped";const n=mm(i,r);return this.storage.setItem(hs(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,o){const r=this.readPosition(t);return r===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(r,i,s,o)}restoreExplicitPosition(t,i,s,o){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!us(i))return{status:"skipped"};const r=bm(s,t.anchorId);if(r===void 0)return o?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=r.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(hs(t));if(i===null||i==="")return;const s=JSON.parse(i);return gm(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!us(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function hs(e){return`${lm}${e}`}function gm(e){return typeof e!="object"||e===null||!("mode"in e)?!1:e.mode==="bottom"?!0:e.mode==="anchor"&&"anchorId"in e&&typeof e.anchorId=="string"&&e.anchorId!==""&&"offset"in e&&typeof e.offset=="number"}function us(e){return e.clientHeight>0&&e.scrollHeight>0}function Ca(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function Ta(e,t=dm){return Ca(e)<t}function mm(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:vo(t)??"",offset:t.getBoundingClientRect().top-i}}function vm(e,t){const i=e.getBoundingClientRect();let s,o=Number.NEGATIVE_INFINITY,r,n=Number.POSITIVE_INFINITY;for(const a of t){if(vo(a)===void 0)continue;const c=a.getBoundingClientRect();if(c.bottom<=c.top||c.bottom<i.top||c.top>i.bottom)continue;const p=c.top-i.top;p<=0&&p>=o?(s=a,o=p):p>0&&p<n&&(r=a,n=p)}return s??r}function zr(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const o=s.getBoundingClientRect();return o.bottom>=i.top&&o.top<=i.bottom})}function bm(e,t){return e.find(i=>vo(i)===t)}function vo(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}const wm=D`
446
+ `];A([d({attribute:!1})],T.prototype,"sessions",2);A([d({attribute:!1})],T.prototype,"statuses",2);A([d({attribute:!1})],T.prototype,"activities",2);A([d({attribute:!1})],T.prototype,"sending",2);A([d({attribute:!1})],T.prototype,"selected",2);A([d({type:Boolean})],T.prototype,"canStart",2);A([d({type:Boolean})],T.prototype,"canDeleteArchived",2);A([d({type:Boolean})],T.prototype,"canReload",2);A([d({type:String})],T.prototype,"archivedDeleteUnavailableMessage",2);A([d({type:Boolean,reflect:!0})],T.prototype,"collapsible",2);A([d({type:Boolean,reflect:!0})],T.prototype,"collapsed",2);A([d({attribute:!1})],T.prototype,"onSelect",2);A([d({attribute:!1})],T.prototype,"onStart",2);A([d({attribute:!1})],T.prototype,"onToggleCollapsed",2);A([d({attribute:!1})],T.prototype,"onArchivedCollapsed",2);A([d({attribute:!1})],T.prototype,"onFocusPreviousSection",2);A([d({attribute:!1})],T.prototype,"onFocusNextSection",2);A([d({attribute:!1})],T.prototype,"onCancelKeyboardNavigation",2);A([d({attribute:!1})],T.prototype,"onArchive",2);A([d({attribute:!1})],T.prototype,"onArchiveWithDescendants",2);A([d({attribute:!1})],T.prototype,"onArchiveMany",2);A([d({attribute:!1})],T.prototype,"onRestore",2);A([d({attribute:!1})],T.prototype,"onDelete",2);A([d({attribute:!1})],T.prototype,"onDeleteArchived",2);A([d({attribute:!1})],T.prototype,"onDeleteArchivedMany",2);A([d({attribute:!1})],T.prototype,"onDetachParent",2);A([d({attribute:!1})],T.prototype,"onReload",2);A([k()],T.prototype,"archivedExpanded",2);A([k()],T.prototype,"selectionScopes",2);A([k()],T.prototype,"selectedSessionIds",2);T=A([W("session-list")],T);function Rt(e){return e.archived===!0?"archived":"current"}function ds(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function Og(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const o=t.get(s.parentSessionPath)??[];o.push(s),t.set(s.parentSessionPath,o)}const i=(s,o)=>{if(o.has(s.path))return 0;const r=new Set(o);r.add(s.path);let n=0;for(const a of t.get(s.path)??[])r.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,r));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function _g(e,t,i,s){if(!(Z(e)||e.archived===!0))return s?"sending":Ye(t,i)?"session":void 0}function Lg(e){const t=new Map(e.map(s=>[s.path,s])),i=new Set;for(const s of e){if(s.archived===!0)continue;i.add(s.id);let o=s.parentSessionPath;const r=new Set([s.path]);for(;o!==void 0&&!r.has(o);){r.add(o);const n=t.get(o);if(n===void 0)break;i.add(n.id),o=n.parentSessionPath}}return Ca(e.filter(s=>i.has(s.id)))}function Ca(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,c=a===void 0?void 0:t.get(a);if(c===void 0){s.push(n);continue}const p=i.get(c.path)??[];p.push(n),i.set(c.path,p)}const o=[],r=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;o.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])r(h,a+1,u)};for(const n of s)r(n,0,new Set);return o}const go={CHILD:2,ELEMENT:6},mo=e=>(...t)=>({_$litDirective$:e,values:t});let vo=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,i,s){this._$Ct=t,this._$AM=i,this._$Ci=s}_$AS(t,i){return this.update(t,i)}update(t,i){return this.render(...i)}};const{I:jg}=El,_r=e=>e,Lr=()=>document.createComment(""),It=(e,t,i)=>{const s=e._$AA.parentNode,o=t===void 0?e._$AB:t._$AA;if(i===void 0){const r=s.insertBefore(Lr(),o),n=s.insertBefore(Lr(),o);i=new jg(r,n,e,e.options)}else{const r=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let c;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(c=e._$AU)!==n._$AU&&i._$AP(c)}if(r!==o||a){let c=i._$AA;for(;c!==r;){const p=_r(c).nextSibling;_r(s).insertBefore(c,o),c=p}}}return i},Ge=(e,t,i=e)=>(e._$AI(t,i),e),Fg={},Ng=(e,t=Fg)=>e._$AH=t,zg=e=>e._$AH,ps=e=>{e._$AR(),e._$AA.remove()};const jr=(e,t,i)=>{const s=new Map;for(let o=t;o<=i;o++)s.set(e[o],o);return s},Bg=mo(class extends vo{constructor(e){if(super(e),e.type!==go.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let s;i===void 0?i=t:t!==void 0&&(s=t);const o=[],r=[];let n=0;for(const a of e)o[n]=s?s(a,n):n,r[n]=i(a,n),n++;return{values:r,keys:o}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const o=zg(e),{values:r,keys:n}=this.dt(t,i,s);if(!Array.isArray(o))return this.ut=n,r;const a=this.ut??=[],c=[];let p,u,h=0,g=o.length-1,b=0,P=r.length-1;for(;h<=g&&b<=P;)if(o[h]===null)h++;else if(o[g]===null)g--;else if(a[h]===n[b])c[b]=Ge(o[h],r[b]),h++,b++;else if(a[g]===n[P])c[P]=Ge(o[g],r[P]),g--,P--;else if(a[h]===n[P])c[P]=Ge(o[h],r[P]),It(e,c[P+1],o[h]),h++,P--;else if(a[g]===n[b])c[b]=Ge(o[g],r[b]),It(e,o[h],o[g]),g--,b++;else if(p===void 0&&(p=jr(n,b,P),u=jr(a,h,g)),p.has(a[h]))if(p.has(a[g])){const H=u.get(n[b]),rt=H!==void 0?o[H]:null;if(rt===null){const bt=It(e,o[h]);Ge(bt,r[b]),c[b]=bt}else c[b]=Ge(rt,r[b]),It(e,o[h],rt),o[H]=null;b++}else ps(o[g]),g--;else ps(o[h]),h++;for(;b<=P;){const H=It(e,c[P+1]);Ge(H,r[b]),c[b++]=H}for(;h<=g;){const H=o[h++];H!==null&&ps(H)}return this.ut=n,Ng(e,c),Ue}}),Ug="pi-web:chat-groups:",Hg={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(Fr(e));return t===null||t===""?void 0:Kg(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(Fr(e),JSON.stringify(t))}catch{}}};class qg{constructor(t=Hg){this.storage=t,this.sessionId="",this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(t){if(this.sessionId===t)return;this.sessionId=t;const i=t===""?void 0:this.storage.read(t);this.openGroupKeys=new Set(i?.open??[]),this.closedDefaultOpenGroupKeys=new Set(i?.closedDefaultOpen??[])}isOpen(t,i){return i?!this.closedDefaultOpenGroupKeys.has(t):this.openGroupKeys.has(t)}applyToggle(t,i,s){const o=this.isOpen(t,s),r=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(r.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?r.add(t):r.delete(t)),(s?!n.has(t):r.has(t))===o&&Nr(r,this.openGroupKeys)&&Nr(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=r,this.closedDefaultOpenGroupKeys=n,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==""&&this.storage.write(this.sessionId,this.snapshot())}}function Fr(e){return`${Ug}${e}`}function Kg(e){if(Array.isArray(e))return{open:hs(e),closedDefaultOpen:[]};if(Vg(e))return{open:Array.isArray(e.open)?hs(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?hs(e.closedDefaultOpen):[]}}function hs(e){return e.filter(t=>typeof t=="string")}function Nr(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Vg(e){return typeof e=="object"&&e!==null}function Gg(e,t=0){const i=[];let s=[],o=0;const r=(a,c)=>{s.length||(o=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:o,endIndex:o+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(b=>zr(a,b)),u=a.parts.filter(b=>!zr(a,b)),h=t+c,g={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&r({role:a.role,parts:u,...g},h),p.length){n();const b=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:b,parts:p,...g},index:h})}}),n(),i}function Jg(e){if(e.every(s=>s.source==="compaction"))return`${String(e.length)} 条历史压缩摘要`;if(e.every(s=>s.source==="branch_summary"))return`${String(e.length)} 条分支摘要`;const t=e.reduce((s,o)=>(s[o.role]=(s[o.role]??0)+1,s),{}),i=Object.entries(t).map(([s,o])=>`${String(o)} ${Qg(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Qg(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function zr(e,t){return e.source==="compaction"||e.source==="branch_summary"?!1:t.type==="skillInvocation"||t.type==="skillRead"?!0:t.type==="text"&&(e.role==="user"||e.role==="assistant"||e.role==="system"||e.role==="bash")}const Zg=30;function Xg(e,t){const i=em(sm(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Yg(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=tm(s,t.markerOffset);return}e.scrollTop=im(e.scrollHeight,t.distanceFromBottom)}function em(e){let t,i=Number.NEGATIVE_INFINITY,s,o=Number.POSITIVE_INFINITY;for(const r of e)r.offset<=0&&r.offset>=i?(t=r,i=r.offset):r.offset>0&&r.offset<o&&(s=r,o=r.offset);return t??s}function tm(e,t){return e-t}function im(e,t){return Math.max(0,e-t)}function sm(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const o=s.dataset.markerId;return o===void 0?[]:[{id:o,offset:s.getBoundingClientRect().top-i}]})}const om=600,rm=1;function nm(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:am(e)||lm(e)}function am(e){return e.scrollTop<(e.topThreshold??Math.max(om,e.clientHeight))}function lm(e){return e.scrollHeight<=e.clientHeight+rm}const cm="pi-web:chat-scroll:",dm=180,pm=48,hm=2,um={getItem(e){return typeof localStorage>"u"?null:localStorage.getItem(e)},setItem(e,t){typeof localStorage>"u"||localStorage.setItem(e,t)},removeItem(e){typeof localStorage>"u"||localStorage.removeItem(e)}},fm={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class gm{constructor(t=um,i=fm){this.storage=t,this.scheduler=i}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(t,i,s=dm){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,o=hm){if(t===""||i===void 0||!fs(i))return"skipped";try{if(Aa(i,o)){const a={mode:"bottom"};return this.storage.setItem(us(t),JSON.stringify(a)),"saved"}const r=bm(i,s);if(r===void 0)return"skipped";const n=vm(i,r);return this.storage.setItem(us(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,o){const r=this.readPosition(t);return r===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(r,i,s,o)}restoreExplicitPosition(t,i,s,o){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!fs(i))return{status:"skipped"};const r=wm(s,t.anchorId);if(r===void 0)return o?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=r.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(us(t));if(i===null||i==="")return;const s=JSON.parse(i);return mm(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!fs(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function us(e){return`${cm}${e}`}function mm(e){return typeof e!="object"||e===null||!("mode"in e)?!1:e.mode==="bottom"?!0:e.mode==="anchor"&&"anchorId"in e&&typeof e.anchorId=="string"&&e.anchorId!==""&&"offset"in e&&typeof e.offset=="number"}function fs(e){return e.clientHeight>0&&e.scrollHeight>0}function Ta(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function Aa(e,t=pm){return Ta(e)<t}function vm(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:bo(t)??"",offset:t.getBoundingClientRect().top-i}}function bm(e,t){const i=e.getBoundingClientRect();let s,o=Number.NEGATIVE_INFINITY,r,n=Number.POSITIVE_INFINITY;for(const a of t){if(bo(a)===void 0)continue;const c=a.getBoundingClientRect();if(c.bottom<=c.top||c.bottom<i.top||c.top>i.bottom)continue;const p=c.top-i.top;p<=0&&p>=o?(s=a,o=p):p>0&&p<n&&(r=a,n=p)}return s??r}function Br(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const o=s.getBoundingClientRect();return o.bottom>=i.top&&o.top<=i.bottom})}function wm(e,t){return e.find(i=>bo(i)===t)}function bo(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}const ym=D`
447
447
  :host { position: relative; z-index: 0; display: flex; flex: 1 1 0; flex-direction: column; min-height: 0; max-height: 100%; overflow: hidden; contain: size layout; color: var(--pi-text); font: 14px system-ui, sans-serif; }
448
448
  .chat-wrap { position: relative; flex: 1 1 0; min-height: 0; max-height: 100%; overflow: hidden; }
449
449
  .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
@@ -532,7 +532,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
532
532
  pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
533
533
  .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
534
534
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
535
- `;var ym=Object.defineProperty,Sm=Object.getOwnPropertyDescriptor,bo=(e,t,i,s)=>{for(var o=s>1?void 0:s?Sm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&ym(t,i,o),o};let jt=class extends C{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=Br(this.positionPercent),t=Br(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return l`
535
+ `;var Sm=Object.defineProperty,xm=Object.getOwnPropertyDescriptor,wo=(e,t,i,s)=>{for(var o=s>1?void 0:s?xm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Sm(t,i,o),o};let Ft=class extends C{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=Ur(this.positionPercent),t=Ur(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return l`
536
536
  <div
537
537
  class="meter"
538
538
  style=${`--position:${e.toFixed(2)}%;`}
@@ -548,19 +548,19 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
548
548
  <div class="marker"></div>
549
549
  </div>
550
550
  </div>
551
- `}};jt.styles=D`
551
+ `}};Ft.styles=D`
552
552
  :host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
553
553
  :host(:hover), :host(:focus-within) { opacity: .92; }
554
554
  .meter { height: 100%; }
555
555
  .track { position: relative; height: 4px; margin-top: 4px; border-radius: 999px; background: color-mix(in srgb, var(--pi-border-muted) 34%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--pi-bg) 55%, transparent); }
556
556
  .progress { position: absolute; left: 0; width: var(--position); top: 0; bottom: 0; border-radius: 999px; background: color-mix(in srgb, var(--pi-accent) 42%, var(--pi-border-muted)); }
557
557
  .marker { position: absolute; left: var(--position); top: 50%; width: 10px; height: 10px; border: 2px solid var(--pi-bg); border-radius: 50%; background: var(--pi-accent); box-shadow: 0 2px 8px var(--pi-shadow); transform: translate(-50%, -50%); }
558
- `;bo([d({type:Number})],jt.prototype,"positionPercent",2);bo([d({type:Number})],jt.prototype,"loadedPercent",2);jt=bo([W("conversation-meter")],jt);function Br(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class Ls extends mo{constructor(t){if(super(t),this.it=F,t.type!==fo.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===F||t==null)return this._t=void 0,this.it=t;if(t===Ue)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const i=[t];return i.raw=i,this._t={_$litType$:this.constructor.resultType,strings:i,values:[]}}}Ls.directiveName="unsafeHTML",Ls.resultType=1;const xm=go(Ls);function wo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var tt=wo();function Aa(e){tt=e}var Ge={exec:()=>null};function lt(e){let t=[];return i=>{let s=Math.max(0,Math.min(3,i-1)),o=t[s];return o||(o=e(s),t[s]=o),o}}function I(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(o,r)=>{let n=typeof r=="string"?r:r.source;return n=n.replace(G.caret,"$1"),i=i.replace(o,n),s},getRegex:()=>new RegExp(i,t)};return s}var km=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),G={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:lt(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:lt(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:lt(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:lt(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:lt(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:lt(e=>new RegExp(`^ {0,${e}}>`))},$m=/^(?:[ \t]*(?:\n|$))+/,Pm=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Rm=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,qt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Im=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,yo=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ma=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ea=I(Ma).replace(/bull/g,yo).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Cm=I(Ma).replace(/bull/g,yo).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),So=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Tm=/^[^\n]+/,xo=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Am=I(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",xo).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Mm=I(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,yo).getRegex(),Ui="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",ko=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Em=I("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",ko).replace("tag",Ui).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Da=I(So).replace("hr",qt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ui).getRegex(),Dm=I(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Da).getRegex(),$o={blockquote:Dm,code:Pm,def:Am,fences:Rm,heading:Im,hr:qt,html:Em,lheading:Ea,list:Mm,newline:$m,paragraph:Da,table:Ge,text:Tm},Ur=I("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",qt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ui).getRegex(),Wm={...$o,lheading:Cm,table:Ur,paragraph:I(So).replace("hr",qt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Ur).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ui).getRegex()},Om={...$o,html:I(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ko).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ge,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:I(So).replace("hr",qt).replace("heading",` *#{1,6} *[^
559
- ]`).replace("lheading",Ea).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},_m=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Lm=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Wa=/^( {2,}|\\)\n(?!\s*$)/,jm=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,mt=/[\p{P}\p{S}]/u,Hi=/[\s\p{P}\p{S}]/u,Po=/[^\s\p{P}\p{S}]/u,Fm=I(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Hi).getRegex(),Oa=/(?!~)[\p{P}\p{S}]/u,Nm=/(?!~)[\s\p{P}\p{S}]/u,zm=/(?:[^\s\p{P}\p{S}]|~)/u,Bm=I(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",km?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),_a=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Um=I(_a,"u").replace(/punct/g,mt).getRegex(),Hm=I(_a,"u").replace(/punct/g,Oa).getRegex(),La="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",qm=I(La,"gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Hi).replace(/punct/g,mt).getRegex(),Km=I(La,"gu").replace(/notPunctSpace/g,zm).replace(/punctSpace/g,Nm).replace(/punct/g,Oa).getRegex(),Vm=I("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Hi).replace(/punct/g,mt).getRegex(),Gm=I(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,mt).getRegex(),Jm="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Qm=I(Jm,"gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Hi).replace(/punct/g,mt).getRegex(),Zm=I(/\\(punct)/,"gu").replace(/punct/g,mt).getRegex(),Xm=I(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Ym=I(ko).replace("(?:-->|$)","-->").getRegex(),ev=I("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Ym).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Pi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,tv=I(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Pi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ja=I(/^!?\[(label)\]\[(ref)\]/).replace("label",Pi).replace("ref",xo).getRegex(),Fa=I(/^!?\[(ref)\](?:\[\])?/).replace("ref",xo).getRegex(),iv=I("reflink|nolink(?!\\()","g").replace("reflink",ja).replace("nolink",Fa).getRegex(),Hr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ro={_backpedal:Ge,anyPunctuation:Zm,autolink:Xm,blockSkip:Bm,br:Wa,code:Lm,del:Ge,delLDelim:Ge,delRDelim:Ge,emStrongLDelim:Um,emStrongRDelimAst:qm,emStrongRDelimUnd:Vm,escape:_m,link:tv,nolink:Fa,punctuation:Fm,reflink:ja,reflinkSearch:iv,tag:ev,text:jm,url:Ge},sv={...Ro,link:I(/^!?\[(label)\]\((.*?)\)/).replace("label",Pi).getRegex(),reflink:I(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Pi).getRegex()},js={...Ro,emStrongRDelimAst:Km,emStrongLDelim:Hm,delLDelim:Gm,delRDelim:Qm,url:I(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Hr).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:I(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Hr).getRegex()},ov={...js,br:I(Wa).replace("{2,}","*").getRegex(),text:I(js.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Xt={normal:$o,gfm:Wm,pedantic:Om},It={normal:Ro,gfm:js,breaks:ov,pedantic:sv},rv={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},qr=e=>rv[e];function Ae(e,t){if(t){if(G.escapeTest.test(e))return e.replace(G.escapeReplace,qr)}else if(G.escapeTestNoEncode.test(e))return e.replace(G.escapeReplaceNoEncode,qr);return e}function Kr(e){try{e=encodeURI(e).replace(G.percentDecode,"%")}catch{return null}return e}function Vr(e,t){let i=e.replace(G.findPipe,(r,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(G.splitPipe),o=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;o<s.length;o++)s[o]=s[o].trim().replace(G.slashPipe,"|");return s}function ze(e,t,i){let s=e.length;if(s===0)return"";let o=0;for(;o<s&&e.charAt(s-o-1)===t;)o++;return e.slice(0,s-o)}function Gr(e){let t=e.split(`
558
+ `;wo([d({type:Number})],Ft.prototype,"positionPercent",2);wo([d({type:Number})],Ft.prototype,"loadedPercent",2);Ft=wo([W("conversation-meter")],Ft);function Ur(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class js extends vo{constructor(t){if(super(t),this.it=F,t.type!==go.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===F||t==null)return this._t=void 0,this.it=t;if(t===Ue)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const i=[t];return i.raw=i,this._t={_$litType$:this.constructor.resultType,strings:i,values:[]}}}js.directiveName="unsafeHTML",js.resultType=1;const km=mo(js);function yo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var it=yo();function Ma(e){it=e}var Je={exec:()=>null};function ct(e){let t=[];return i=>{let s=Math.max(0,Math.min(3,i-1)),o=t[s];return o||(o=e(s),t[s]=o),o}}function I(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(o,r)=>{let n=typeof r=="string"?r:r.source;return n=n.replace(G.caret,"$1"),i=i.replace(o,n),s},getRegex:()=>new RegExp(i,t)};return s}var $m=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),G={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:ct(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:ct(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:ct(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:ct(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:ct(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:ct(e=>new RegExp(`^ {0,${e}}>`))},Pm=/^(?:[ \t]*(?:\n|$))+/,Rm=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Im=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Kt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Cm=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,So=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ea=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Da=I(Ea).replace(/bull/g,So).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Tm=I(Ea).replace(/bull/g,So).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),xo=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Am=/^[^\n]+/,ko=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Mm=I(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ko).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Em=I(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,So).getRegex(),Hi="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",$o=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Dm=I("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",$o).replace("tag",Hi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Wa=I(xo).replace("hr",Kt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Hi).getRegex(),Wm=I(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Wa).getRegex(),Po={blockquote:Wm,code:Rm,def:Mm,fences:Im,heading:Cm,hr:Kt,html:Dm,lheading:Da,list:Em,newline:Pm,paragraph:Wa,table:Je,text:Am},Hr=I("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Kt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Hi).getRegex(),Om={...Po,lheading:Tm,table:Hr,paragraph:I(xo).replace("hr",Kt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Hr).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Hi).getRegex()},_m={...Po,html:I(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",$o).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Je,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:I(xo).replace("hr",Kt).replace("heading",` *#{1,6} *[^
559
+ ]`).replace("lheading",Da).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Lm=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,jm=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Oa=/^( {2,}|\\)\n(?!\s*$)/,Fm=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,vt=/[\p{P}\p{S}]/u,qi=/[\s\p{P}\p{S}]/u,Ro=/[^\s\p{P}\p{S}]/u,Nm=I(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,qi).getRegex(),_a=/(?!~)[\p{P}\p{S}]/u,zm=/(?!~)[\s\p{P}\p{S}]/u,Bm=/(?:[^\s\p{P}\p{S}]|~)/u,Um=I(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",$m?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),La=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Hm=I(La,"u").replace(/punct/g,vt).getRegex(),qm=I(La,"u").replace(/punct/g,_a).getRegex(),ja="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Km=I(ja,"gu").replace(/notPunctSpace/g,Ro).replace(/punctSpace/g,qi).replace(/punct/g,vt).getRegex(),Vm=I(ja,"gu").replace(/notPunctSpace/g,Bm).replace(/punctSpace/g,zm).replace(/punct/g,_a).getRegex(),Gm=I("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ro).replace(/punctSpace/g,qi).replace(/punct/g,vt).getRegex(),Jm=I(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,vt).getRegex(),Qm="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Zm=I(Qm,"gu").replace(/notPunctSpace/g,Ro).replace(/punctSpace/g,qi).replace(/punct/g,vt).getRegex(),Xm=I(/\\(punct)/,"gu").replace(/punct/g,vt).getRegex(),Ym=I(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),ev=I($o).replace("(?:-->|$)","-->").getRegex(),tv=I("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",ev).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ri=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,iv=I(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Ri).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Fa=I(/^!?\[(label)\]\[(ref)\]/).replace("label",Ri).replace("ref",ko).getRegex(),Na=I(/^!?\[(ref)\](?:\[\])?/).replace("ref",ko).getRegex(),sv=I("reflink|nolink(?!\\()","g").replace("reflink",Fa).replace("nolink",Na).getRegex(),qr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Io={_backpedal:Je,anyPunctuation:Xm,autolink:Ym,blockSkip:Um,br:Oa,code:jm,del:Je,delLDelim:Je,delRDelim:Je,emStrongLDelim:Hm,emStrongRDelimAst:Km,emStrongRDelimUnd:Gm,escape:Lm,link:iv,nolink:Na,punctuation:Nm,reflink:Fa,reflinkSearch:sv,tag:tv,text:Fm,url:Je},ov={...Io,link:I(/^!?\[(label)\]\((.*?)\)/).replace("label",Ri).getRegex(),reflink:I(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Ri).getRegex()},Fs={...Io,emStrongRDelimAst:Vm,emStrongLDelim:qm,delLDelim:Jm,delRDelim:Zm,url:I(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",qr).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:I(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",qr).getRegex()},rv={...Fs,br:I(Oa).replace("{2,}","*").getRegex(),text:I(Fs.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Yt={normal:Po,gfm:Om,pedantic:_m},Ct={normal:Io,gfm:Fs,breaks:rv,pedantic:ov},nv={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Kr=e=>nv[e];function Ae(e,t){if(t){if(G.escapeTest.test(e))return e.replace(G.escapeReplace,Kr)}else if(G.escapeTestNoEncode.test(e))return e.replace(G.escapeReplaceNoEncode,Kr);return e}function Vr(e){try{e=encodeURI(e).replace(G.percentDecode,"%")}catch{return null}return e}function Gr(e,t){let i=e.replace(G.findPipe,(r,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(G.splitPipe),o=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;o<s.length;o++)s[o]=s[o].trim().replace(G.slashPipe,"|");return s}function ze(e,t,i){let s=e.length;if(s===0)return"";let o=0;for(;o<s&&e.charAt(s-o-1)===t;)o++;return e.slice(0,s-o)}function Jr(e){let t=e.split(`
560
560
  `),i=t.length-1;for(;i>=0&&G.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
561
- `)}function nv(e,t){if(e.indexOf(t[1])===-1)return-1;let i=0;for(let s=0;s<e.length;s++)if(e[s]==="\\")s++;else if(e[s]===t[0])i++;else if(e[s]===t[1]&&(i--,i<0))return s;return i>0?-2:-1}function av(e,t=0){let i=t,s="";for(let o of e)if(o===" "){let r=4-i%4;s+=" ".repeat(r),i+=r}else s+=o,i++;return s}function Jr(e,t,i,s,o){let r=t.href,n=t.title||null,a=e[1].replace(o.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:r,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function lv(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let o=s[1];return t.split(`
561
+ `)}function av(e,t){if(e.indexOf(t[1])===-1)return-1;let i=0;for(let s=0;s<e.length;s++)if(e[s]==="\\")s++;else if(e[s]===t[0])i++;else if(e[s]===t[1]&&(i--,i<0))return s;return i>0?-2:-1}function lv(e,t=0){let i=t,s="";for(let o of e)if(o===" "){let r=4-i%4;s+=" ".repeat(r),i+=r}else s+=o,i++;return s}function Qr(e,t,i,s,o){let r=t.href,n=t.title||null,a=e[1].replace(o.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:r,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function cv(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let o=s[1];return t.split(`
562
562
  `).map(r=>{let n=r.match(i.other.beginningSpace);if(n===null)return r;let[a]=n;return a.length>=o.length?r.slice(o.length):r}).join(`
563
- `)}var Ri=class{options;rules;lexer;constructor(e){this.options=e||tt}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:Gr(t[0]),s=i.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:i,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let i=t[0],s=lv(i,t[3]||"",this.rules);return{type:"code",raw:i,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let i=t[2].trim();if(this.rules.other.endingHash.test(i)){let s=ze(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:ze(t[0],`
563
+ `)}var Ii=class{options;rules;lexer;constructor(e){this.options=e||it}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:Jr(t[0]),s=i.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:i,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let i=t[0],s=cv(i,t[3]||"",this.rules);return{type:"code",raw:i,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let i=t[2].trim();if(this.rules.other.endingHash.test(i)){let s=ze(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:ze(t[0],`
564
564
  `),depth:t[1].length,text:i,tokens:this.lexer.inline(i)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:ze(t[0],`
565
565
  `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=ze(t[0],`
566
566
  `).split(`
@@ -568,24 +568,24 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
568
568
  `),u=p.replace(this.rules.other.blockquoteSetextReplace,`
569
569
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
570
570
  ${p}`:p,o=o?`${o}
571
- ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,r,!0),this.lexer.state.top=h,i.length===0)break;let g=r.at(-1);if(g?.type==="code")break;if(g?.type==="blockquote"){let w=g,P=w.raw+`
571
+ ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,r,!0),this.lexer.state.top=h,i.length===0)break;let g=r.at(-1);if(g?.type==="code")break;if(g?.type==="blockquote"){let b=g,P=b.raw+`
572
572
  `+i.join(`
573
- `),H=this.blockquote(P);r[r.length-1]=H,s=s.substring(0,s.length-w.raw.length)+H.raw,o=o.substring(0,o.length-w.text.length)+H.text;break}else if(g?.type==="list"){let w=g,P=w.raw+`
573
+ `),H=this.blockquote(P);r[r.length-1]=H,s=s.substring(0,s.length-b.raw.length)+H.raw,o=o.substring(0,o.length-b.text.length)+H.text;break}else if(g?.type==="list"){let b=g,P=b.raw+`
574
574
  `+i.join(`
575
- `),H=this.list(P);r[r.length-1]=H,s=s.substring(0,s.length-g.raw.length)+H.raw,o=o.substring(0,o.length-w.raw.length)+H.raw,i=P.substring(r.at(-1).raw.length).split(`
576
- `);continue}}return{type:"blockquote",raw:s,tokens:r,text:o}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,o={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let r=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=av(t[2].split(`
575
+ `),H=this.list(P);r[r.length-1]=H,s=s.substring(0,s.length-g.raw.length)+H.raw,o=o.substring(0,o.length-b.raw.length)+H.raw,i=P.substring(r.at(-1).raw.length).split(`
576
+ `);continue}}return{type:"blockquote",raw:s,tokens:r,text:o}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,o={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let r=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=lv(t[2].split(`
577
577
  `,1)[0],t[1].length),g=e.split(`
578
- `,1)[0],w=!h.trim(),P=0;if(this.options.pedantic?(P=2,u=h.trimStart()):w?P=t[1].length+1:(P=h.search(this.rules.other.nonSpaceChar),P=P>4?1:P,u=h.slice(P),P+=t[1].length),w&&this.rules.other.blankLine.test(g)&&(p+=g+`
579
- `,e=e.substring(g.length+1),c=!0),!c){let H=this.rules.other.nextBulletRegex(P),ot=this.rules.other.hrRegex(P),vt=this.rules.other.fencesBeginRegex(P),To=this.rules.other.headingBeginRegex(P),Xa=this.rules.other.htmlBeginRegex(P),Ya=this.rules.other.blockquoteBeginRegex(P);for(;e;){let Gi=e.split(`
580
- `,1)[0],bt;if(g=Gi,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),bt=g):bt=g.replace(this.rules.other.tabCharGlobal," "),vt.test(g)||To.test(g)||Xa.test(g)||Ya.test(g)||H.test(g)||ot.test(g))break;if(bt.search(this.rules.other.nonSpaceChar)>=P||!g.trim())u+=`
581
- `+bt.slice(P);else{if(w||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||vt.test(h)||To.test(h)||ot.test(h))break;u+=`
582
- `+g}w=!g.trim(),p+=Gi+`
583
- `,e=e.substring(Gi.length+1),h=bt.slice(P)}}o.loose||(n?o.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),o.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),o.raw+=p}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let c of o.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let p=c.tokens[0];if(c.task&&(p?.type==="text"||p?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=h.checked,o.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=h.raw+c.tokens[0].raw,c.tokens[0].text=h.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(h)):c.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):c.tokens.unshift(h)}}else c.task&&(c.task=!1);if(!o.loose){let u=c.tokens.filter(g=>g.type==="space"),h=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));o.loose=h}}if(o.loose)for(let c of o.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return o}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Gr(t[0]);return{type:"html",block:!0,raw:i,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:i}}}def(e){let t=this.rules.block.def.exec(e);if(t){let i=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:ze(t[0],`
584
- `),href:s,title:o}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Vr(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
578
+ `,1)[0],b=!h.trim(),P=0;if(this.options.pedantic?(P=2,u=h.trimStart()):b?P=t[1].length+1:(P=h.search(this.rules.other.nonSpaceChar),P=P>4?1:P,u=h.slice(P),P+=t[1].length),b&&this.rules.other.blankLine.test(g)&&(p+=g+`
579
+ `,e=e.substring(g.length+1),c=!0),!c){let H=this.rules.other.nextBulletRegex(P),rt=this.rules.other.hrRegex(P),bt=this.rules.other.fencesBeginRegex(P),Ao=this.rules.other.headingBeginRegex(P),Ya=this.rules.other.htmlBeginRegex(P),el=this.rules.other.blockquoteBeginRegex(P);for(;e;){let Ji=e.split(`
580
+ `,1)[0],wt;if(g=Ji,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),wt=g):wt=g.replace(this.rules.other.tabCharGlobal," "),bt.test(g)||Ao.test(g)||Ya.test(g)||el.test(g)||H.test(g)||rt.test(g))break;if(wt.search(this.rules.other.nonSpaceChar)>=P||!g.trim())u+=`
581
+ `+wt.slice(P);else{if(b||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||bt.test(h)||Ao.test(h)||rt.test(h))break;u+=`
582
+ `+g}b=!g.trim(),p+=Ji+`
583
+ `,e=e.substring(Ji.length+1),h=wt.slice(P)}}o.loose||(n?o.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),o.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),o.raw+=p}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let c of o.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let p=c.tokens[0];if(c.task&&(p?.type==="text"||p?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=h.checked,o.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=h.raw+c.tokens[0].raw,c.tokens[0].text=h.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(h)):c.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):c.tokens.unshift(h)}}else c.task&&(c.task=!1);if(!o.loose){let u=c.tokens.filter(g=>g.type==="space"),h=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));o.loose=h}}if(o.loose)for(let c of o.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return o}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Jr(t[0]);return{type:"html",block:!0,raw:i,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:i}}}def(e){let t=this.rules.block.def.exec(e);if(t){let i=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:ze(t[0],`
584
+ `),href:s,title:o}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Gr(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
585
585
  `):[],r={type:"table",raw:ze(t[0],`
586
- `),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?r.align.push("right"):this.rules.other.tableAlignCenter.test(n)?r.align.push("center"):this.rules.other.tableAlignLeft.test(n)?r.align.push("left"):r.align.push(null);for(let n=0;n<i.length;n++)r.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:r.align[n]});for(let n of o)r.rows.push(Vr(n,r.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[c]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:ze(t[0],`
586
+ `),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?r.align.push("right"):this.rules.other.tableAlignCenter.test(n)?r.align.push("center"):this.rules.other.tableAlignLeft.test(n)?r.align.push("left"):r.align.push(null);for(let n=0;n<i.length;n++)r.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:r.align[n]});for(let n of o)r.rows.push(Gr(n,r.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[c]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:ze(t[0],`
587
587
  `),depth:t[2].charAt(0)==="="?1:2,text:i,tokens:this.lexer.inline(i)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let i=t[1].charAt(t[1].length-1)===`
588
- `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let r=ze(i.slice(0,-1),"\\");if((i.length-r.length)%2===0)return}else{let r=nv(t[2],"()");if(r===-2)return;if(r>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+r;t[2]=t[2].substring(0,r),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],o="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],o=r[3])}else o=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(i)?s=s.slice(1):s=s.slice(1,-1)),Jr(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let s=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=t[s.toLowerCase()];if(!o){let r=i[0].charAt(0);return{type:"text",raw:r,text:r}}return Jr(i,o,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&i.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+o);(s=p.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(n=[...r].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&o%3&&!((o+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let u=[...s[0]][0].length,h=e.slice(0,o+s.index+u+n);if(Math.min(o,n)%2){let w=h.slice(1,-1);return{type:"em",raw:h,text:w,tokens:this.lexer.inlineTokens(w)}}let g=h.slice(2,-2);return{type:"strong",raw:h,text:g,tokens:this.lexer.inlineTokens(g)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(i),o=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&o&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+o);(s=c.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r||(n=[...r].length,n!==o))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,u=e.slice(0,o+s.index+p+n),h=u.slice(o,-o);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,s;return t[2]==="@"?(i=t[1],s="mailto:"+i):(i=t[1],s=i),{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let o;do o=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(o!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:i}}}},ke=class Fs{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||tt,this.options.tokenizer=this.options.tokenizer||new Ri,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let i={other:G,block:Xt.normal,inline:It.normal};this.options.pedantic?(i.block=Xt.pedantic,i.inline=It.pedantic):this.options.gfm&&(i.block=Xt.gfm,this.options.breaks?i.inline=It.breaks:i.inline=It.gfm),this.tokenizer.rules=i}static get rules(){return{block:Xt,inline:It}}static lex(t,i){return new Fs(i).lex(t)}static lexInline(t,i){return new Fs(i).inlineTokens(t)}lex(t){t=t.replace(G.carriageReturn,`
588
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let r=ze(i.slice(0,-1),"\\");if((i.length-r.length)%2===0)return}else{let r=av(t[2],"()");if(r===-2)return;if(r>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+r;t[2]=t[2].substring(0,r),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],o="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],o=r[3])}else o=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(i)?s=s.slice(1):s=s.slice(1,-1)),Qr(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let s=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=t[s.toLowerCase()];if(!o){let r=i[0].charAt(0);return{type:"text",raw:r,text:r}}return Qr(i,o,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&i.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+o);(s=p.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(n=[...r].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&o%3&&!((o+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let u=[...s[0]][0].length,h=e.slice(0,o+s.index+u+n);if(Math.min(o,n)%2){let b=h.slice(1,-1);return{type:"em",raw:h,text:b,tokens:this.lexer.inlineTokens(b)}}let g=h.slice(2,-2);return{type:"strong",raw:h,text:g,tokens:this.lexer.inlineTokens(g)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(i),o=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&o&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+o);(s=c.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r||(n=[...r].length,n!==o))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,u=e.slice(0,o+s.index+p+n),h=u.slice(o,-o);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,s;return t[2]==="@"?(i=t[1],s="mailto:"+i):(i=t[1],s=i),{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let o;do o=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(o!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:i}}}},ke=class Ns{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||it,this.options.tokenizer=this.options.tokenizer||new Ii,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let i={other:G,block:Yt.normal,inline:Ct.normal};this.options.pedantic?(i.block=Yt.pedantic,i.inline=Ct.pedantic):this.options.gfm&&(i.block=Yt.gfm,this.options.breaks?i.inline=Ct.breaks:i.inline=Ct.gfm),this.tokenizer.rules=i}static get rules(){return{block:Yt,inline:Ct}}static lex(t,i){return new Ns(i).lex(t)}static lexInline(t,i){return new Ns(i).inlineTokens(t)}lex(t){t=t.replace(G.carriageReturn,`
589
589
  `),this.blockTokens(t,this.tokens);for(let i=0;i<this.inlineQueue.length;i++){let s=this.inlineQueue[i];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,i=[],s=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(G.tabCharGlobal," ").replace(G.spaceLine,""));let o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(a=>(r=a.call({lexer:this},t,i))?(t=t.substring(r.raw.length),i.push(r),!0):!1))continue;if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length);let a=i.at(-1);r.raw.length===1&&a!==void 0?a.raw+=`
590
590
  `:i.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
591
591
  `)?"":`
@@ -599,7 +599,7 @@ ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
599
599
  `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r),s=n.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
600
600
  `)?"":`
601
601
  `)+r.raw,a.text+=`
602
- `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,o=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,o.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)r=o[2]?o[2].length:0,s=s.slice(0,o.index+r)+"["+"a".repeat(o[0].length-r-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",c=1/0;for(;t;){if(t.length<c)c=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let u=t;if(this.options.extensions?.startInline){let h=1/0,g=t.slice(1),w;this.options.extensions.startInline.forEach(P=>{w=P.call({lexer:this},g),typeof w=="number"&&w>=0&&(h=Math.min(h,w))}),h<1/0&&h>=0&&(u=t.substring(0,h+1))}if(p=this.tokenizer.inlineText(u)){t=t.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),n=!0;let h=i.at(-1);h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},Ii=class{options;parser;constructor(e){this.options=e||tt}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(G.notSpaceStart)?.[0],o=e.replace(G.endingNewline,"")+`
602
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,o=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,o.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)r=o[2]?o[2].length:0,s=s.slice(0,o.index+r)+"["+"a".repeat(o[0].length-r-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",c=1/0;for(;t;){if(t.length<c)c=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let u=t;if(this.options.extensions?.startInline){let h=1/0,g=t.slice(1),b;this.options.extensions.startInline.forEach(P=>{b=P.call({lexer:this},g),typeof b=="number"&&b>=0&&(h=Math.min(h,b))}),h<1/0&&h>=0&&(u=t.substring(0,h+1))}if(p=this.tokenizer.inlineText(u)){t=t.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),n=!0;let h=i.at(-1);h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},Ci=class{options;parser;constructor(e){this.options=e||it}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(G.notSpaceStart)?.[0],o=e.replace(G.endingNewline,"")+`
603
603
  `;return s?'<pre><code class="language-'+Ae(s)+'">'+(i?o:Ae(o,!0))+`</code></pre>
604
604
  `:"<pre><code>"+(i?o:Ae(o,!0))+`</code></pre>
605
605
  `}blockquote({tokens:e}){return`<blockquote>
@@ -617,8 +617,8 @@ ${this.parser.parse(e)}</blockquote>
617
617
  `}tablerow({text:e}){return`<tr>
618
618
  ${e}</tr>
619
619
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
620
- `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Ae(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:i}){let s=this.parser.parseInline(i),o=Kr(e);if(o===null)return s;e=o;let r='<a href="'+e+'"';return t&&(r+=' title="'+Ae(t)+'"'),r+=">"+s+"</a>",r}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let o=Kr(e);if(o===null)return Ae(i);e=o;let r=`<img src="${e}" alt="${Ae(i)}"`;return t&&(r+=` title="${Ae(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Ae(e.text)}},Io=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},$e=class Ns{options;renderer;textRenderer;constructor(t){this.options=t||tt,this.options.renderer=this.options.renderer||new Ii,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Io}static parse(t,i){return new Ns(i).parse(t)}static parseInline(t,i){return new Ns(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let o=t[s];if(this.options.extensions?.renderers?.[o.type]){let n=o,a=this.options.extensions.renderers[n.type].call({parser:this},n);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(n.type)){i+=a||"";continue}}let r=o;switch(r.type){case"space":{i+=this.renderer.space(r);break}case"hr":{i+=this.renderer.hr(r);break}case"heading":{i+=this.renderer.heading(r);break}case"code":{i+=this.renderer.code(r);break}case"table":{i+=this.renderer.table(r);break}case"blockquote":{i+=this.renderer.blockquote(r);break}case"list":{i+=this.renderer.list(r);break}case"checkbox":{i+=this.renderer.checkbox(r);break}case"html":{i+=this.renderer.html(r);break}case"def":{i+=this.renderer.def(r);break}case"paragraph":{i+=this.renderer.paragraph(r);break}case"text":{i+=this.renderer.text(r);break}default:{let n='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(n),"";throw new Error(n)}}}return i}parseInline(t,i=this.renderer){this.renderer.parser=this;let s="";for(let o=0;o<t.length;o++){let r=t[o];if(this.options.extensions?.renderers?.[r.type]){let a=this.options.extensions.renderers[r.type].call({parser:this},r);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){s+=a||"";continue}}let n=r;switch(n.type){case"escape":{s+=i.text(n);break}case"html":{s+=i.html(n);break}case"link":{s+=i.link(n);break}case"image":{s+=i.image(n);break}case"checkbox":{s+=i.checkbox(n);break}case"strong":{s+=i.strong(n);break}case"em":{s+=i.em(n);break}case"codespan":{s+=i.codespan(n);break}case"br":{s+=i.br(n);break}case"del":{s+=i.del(n);break}case"text":{s+=i.text(n);break}default:{let a='Token with "'+n.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return s}},Tt=class{options;block;constructor(e){this.options=e||tt}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?ke.lex:ke.lexInline}provideParser(e=this.block){return e?$e.parse:$e.parseInline}},cv=class{defaults=wo();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=$e;Renderer=Ii;TextRenderer=Io;Lexer=ke;Tokenizer=Ri;Hooks=Tt;constructor(...e){this.use(...e)}walkTokens(e,t){let i=[];for(let s of e)switch(i=i.concat(t.call(this,s)),s.type){case"table":{let o=s;for(let r of o.header)i=i.concat(this.walkTokens(r.tokens,t));for(let r of o.rows)for(let n of r)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let o=s;i=i.concat(this.walkTokens(o.items,t));break}default:{let o=s;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(r=>{let n=o[r].flat(1/0);i=i.concat(this.walkTokens(n,t))}):o.tokens&&(i=i.concat(this.walkTokens(o.tokens,t)))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let s={...i};if(s.async=this.defaults.async||s.async||!1,i.extensions&&(i.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let r=t.renderers[o.name];r?t.renderers[o.name]=function(...n){let a=o.renderer.apply(this,n);return a===!1&&(a=r.apply(this,n)),a}:t.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[o.level];r?r.unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),s.extensions=t),i.renderer){let o=this.defaults.renderer||new Ii(this.defaults);for(let r in i.renderer){if(!(r in o))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let n=r,a=i.renderer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u||""}}s.renderer=o}if(i.tokenizer){let o=this.defaults.tokenizer||new Ri(this.defaults);for(let r in i.tokenizer){if(!(r in o))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let n=r,a=i.tokenizer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.tokenizer=o}if(i.hooks){let o=this.defaults.hooks||new Tt;for(let r in i.hooks){if(!(r in o))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let n=r,a=i.hooks[n],c=o[n];Tt.passThroughHooks.has(r)?o[n]=p=>{if(this.defaults.async&&Tt.passThroughHooksRespectAsync.has(r))return(async()=>{let h=await a.call(o,p);return c.call(o,h)})();let u=a.call(o,p);return c.call(o,u)}:o[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(o,p);return h===!1&&(h=await c.apply(o,p)),h})();let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.hooks=o}if(i.walkTokens){let o=this.defaults.walkTokens,r=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(r.call(this,n)),o&&(a=a.concat(o.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ke.lex(e,t??this.defaults)}parser(e,t){return $e.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},o={...this.defaults,...s},r=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&s.async===!1)return r(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return r(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let n=o.hooks?await o.hooks.preprocess(t):t,a=await(o.hooks?await o.hooks.provideLexer(e):e?ke.lex:ke.lexInline)(n,o),c=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(c,o.walkTokens));let p=await(o.hooks?await o.hooks.provideParser(e):e?$e.parse:$e.parseInline)(c,o);return o.hooks?await o.hooks.postprocess(p):p})().catch(r);try{o.hooks&&(t=o.hooks.preprocess(t));let n=(o.hooks?o.hooks.provideLexer(e):e?ke.lex:ke.lexInline)(t,o);o.hooks&&(n=o.hooks.processAllTokens(n)),o.walkTokens&&this.walkTokens(n,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(e):e?$e.parse:$e.parseInline)(n,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(n){return r(n)}}}onError(e,t){return i=>{if(i.message+=`
621
- Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Ae(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},Ye=new cv;function M(e,t){return Ye.parse(e,t)}M.options=M.setOptions=function(e){return Ye.setOptions(e),M.defaults=Ye.defaults,Aa(M.defaults),M};M.getDefaults=wo;M.defaults=tt;M.use=function(...e){return Ye.use(...e),M.defaults=Ye.defaults,Aa(M.defaults),M};M.walkTokens=function(e,t){return Ye.walkTokens(e,t)};M.parseInline=Ye.parseInline;M.Parser=$e;M.parser=$e.parse;M.Renderer=Ii;M.TextRenderer=Io;M.Lexer=ke;M.lexer=ke.lex;M.Tokenizer=Ri;M.Hooks=Tt;M.parse=M;M.options;M.setOptions;M.use;M.walkTokens;M.parseInline;$e.parse;ke.lex;const Na=new M.Renderer;Na.html=({text:e})=>hv(e);const dv=300,Ct=new Map;function pv(e){const t=Ct.get(e);if(t!==void 0)return t;const i=M.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:Na}),s=uv(i);if(Ct.set(e,s),Ct.size>dv){const o=Ct.keys().next().value;o!==void 0&&Ct.delete(o)}return s}function hv(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function uv(e){const t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("script, style, iframe, object, embed").forEach(i=>{i.remove()}),t.content.querySelectorAll("*").forEach(i=>{for(const s of[...i.attributes]){const o=s.name.toLowerCase();o.startsWith("on")&&i.removeAttribute(s.name),(o==="href"||o==="src")&&!fv(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function fv(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var gv=Object.defineProperty,mv=Object.getOwnPropertyDescriptor,za=(e,t,i,s)=>{for(var o=s>1?void 0:s?mv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&gv(t,i,o),o};const vv=D`
620
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Ae(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:i}){let s=this.parser.parseInline(i),o=Vr(e);if(o===null)return s;e=o;let r='<a href="'+e+'"';return t&&(r+=' title="'+Ae(t)+'"'),r+=">"+s+"</a>",r}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let o=Vr(e);if(o===null)return Ae(i);e=o;let r=`<img src="${e}" alt="${Ae(i)}"`;return t&&(r+=` title="${Ae(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Ae(e.text)}},Co=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},$e=class zs{options;renderer;textRenderer;constructor(t){this.options=t||it,this.options.renderer=this.options.renderer||new Ci,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Co}static parse(t,i){return new zs(i).parse(t)}static parseInline(t,i){return new zs(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let o=t[s];if(this.options.extensions?.renderers?.[o.type]){let n=o,a=this.options.extensions.renderers[n.type].call({parser:this},n);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(n.type)){i+=a||"";continue}}let r=o;switch(r.type){case"space":{i+=this.renderer.space(r);break}case"hr":{i+=this.renderer.hr(r);break}case"heading":{i+=this.renderer.heading(r);break}case"code":{i+=this.renderer.code(r);break}case"table":{i+=this.renderer.table(r);break}case"blockquote":{i+=this.renderer.blockquote(r);break}case"list":{i+=this.renderer.list(r);break}case"checkbox":{i+=this.renderer.checkbox(r);break}case"html":{i+=this.renderer.html(r);break}case"def":{i+=this.renderer.def(r);break}case"paragraph":{i+=this.renderer.paragraph(r);break}case"text":{i+=this.renderer.text(r);break}default:{let n='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(n),"";throw new Error(n)}}}return i}parseInline(t,i=this.renderer){this.renderer.parser=this;let s="";for(let o=0;o<t.length;o++){let r=t[o];if(this.options.extensions?.renderers?.[r.type]){let a=this.options.extensions.renderers[r.type].call({parser:this},r);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){s+=a||"";continue}}let n=r;switch(n.type){case"escape":{s+=i.text(n);break}case"html":{s+=i.html(n);break}case"link":{s+=i.link(n);break}case"image":{s+=i.image(n);break}case"checkbox":{s+=i.checkbox(n);break}case"strong":{s+=i.strong(n);break}case"em":{s+=i.em(n);break}case"codespan":{s+=i.codespan(n);break}case"br":{s+=i.br(n);break}case"del":{s+=i.del(n);break}case"text":{s+=i.text(n);break}default:{let a='Token with "'+n.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return s}},At=class{options;block;constructor(e){this.options=e||it}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?ke.lex:ke.lexInline}provideParser(e=this.block){return e?$e.parse:$e.parseInline}},dv=class{defaults=yo();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=$e;Renderer=Ci;TextRenderer=Co;Lexer=ke;Tokenizer=Ii;Hooks=At;constructor(...e){this.use(...e)}walkTokens(e,t){let i=[];for(let s of e)switch(i=i.concat(t.call(this,s)),s.type){case"table":{let o=s;for(let r of o.header)i=i.concat(this.walkTokens(r.tokens,t));for(let r of o.rows)for(let n of r)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let o=s;i=i.concat(this.walkTokens(o.items,t));break}default:{let o=s;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(r=>{let n=o[r].flat(1/0);i=i.concat(this.walkTokens(n,t))}):o.tokens&&(i=i.concat(this.walkTokens(o.tokens,t)))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let s={...i};if(s.async=this.defaults.async||s.async||!1,i.extensions&&(i.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let r=t.renderers[o.name];r?t.renderers[o.name]=function(...n){let a=o.renderer.apply(this,n);return a===!1&&(a=r.apply(this,n)),a}:t.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[o.level];r?r.unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),s.extensions=t),i.renderer){let o=this.defaults.renderer||new Ci(this.defaults);for(let r in i.renderer){if(!(r in o))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let n=r,a=i.renderer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u||""}}s.renderer=o}if(i.tokenizer){let o=this.defaults.tokenizer||new Ii(this.defaults);for(let r in i.tokenizer){if(!(r in o))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let n=r,a=i.tokenizer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.tokenizer=o}if(i.hooks){let o=this.defaults.hooks||new At;for(let r in i.hooks){if(!(r in o))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let n=r,a=i.hooks[n],c=o[n];At.passThroughHooks.has(r)?o[n]=p=>{if(this.defaults.async&&At.passThroughHooksRespectAsync.has(r))return(async()=>{let h=await a.call(o,p);return c.call(o,h)})();let u=a.call(o,p);return c.call(o,u)}:o[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(o,p);return h===!1&&(h=await c.apply(o,p)),h})();let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.hooks=o}if(i.walkTokens){let o=this.defaults.walkTokens,r=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(r.call(this,n)),o&&(a=a.concat(o.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ke.lex(e,t??this.defaults)}parser(e,t){return $e.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},o={...this.defaults,...s},r=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&s.async===!1)return r(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return r(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let n=o.hooks?await o.hooks.preprocess(t):t,a=await(o.hooks?await o.hooks.provideLexer(e):e?ke.lex:ke.lexInline)(n,o),c=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(c,o.walkTokens));let p=await(o.hooks?await o.hooks.provideParser(e):e?$e.parse:$e.parseInline)(c,o);return o.hooks?await o.hooks.postprocess(p):p})().catch(r);try{o.hooks&&(t=o.hooks.preprocess(t));let n=(o.hooks?o.hooks.provideLexer(e):e?ke.lex:ke.lexInline)(t,o);o.hooks&&(n=o.hooks.processAllTokens(n)),o.walkTokens&&this.walkTokens(n,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(e):e?$e.parse:$e.parseInline)(n,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(n){return r(n)}}}onError(e,t){return i=>{if(i.message+=`
621
+ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Ae(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},et=new dv;function M(e,t){return et.parse(e,t)}M.options=M.setOptions=function(e){return et.setOptions(e),M.defaults=et.defaults,Ma(M.defaults),M};M.getDefaults=yo;M.defaults=it;M.use=function(...e){return et.use(...e),M.defaults=et.defaults,Ma(M.defaults),M};M.walkTokens=function(e,t){return et.walkTokens(e,t)};M.parseInline=et.parseInline;M.Parser=$e;M.parser=$e.parse;M.Renderer=Ci;M.TextRenderer=Co;M.Lexer=ke;M.lexer=ke.lex;M.Tokenizer=Ii;M.Hooks=At;M.parse=M;M.options;M.setOptions;M.use;M.walkTokens;M.parseInline;$e.parse;ke.lex;const za=new M.Renderer;za.html=({text:e})=>uv(e);const pv=300,Tt=new Map;function hv(e){const t=Tt.get(e);if(t!==void 0)return t;const i=M.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:za}),s=fv(i);if(Tt.set(e,s),Tt.size>pv){const o=Tt.keys().next().value;o!==void 0&&Tt.delete(o)}return s}function uv(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function fv(e){const t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("script, style, iframe, object, embed").forEach(i=>{i.remove()}),t.content.querySelectorAll("*").forEach(i=>{for(const s of[...i.attributes]){const o=s.name.toLowerCase();o.startsWith("on")&&i.removeAttribute(s.name),(o==="href"||o==="src")&&!gv(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function gv(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var mv=Object.defineProperty,vv=Object.getOwnPropertyDescriptor,Ba=(e,t,i,s)=>{for(var o=s>1?void 0:s?vv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&mv(t,i,o),o};const bv=D`
622
622
  :host { display: block; }
623
623
  .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
624
624
  p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
@@ -643,18 +643,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
643
643
  table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
644
644
  th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
645
645
  th { background: var(--pi-surface); }
646
- `;let Ci=class extends C{constructor(){super(...arguments),this.text="",this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;const t=e.target.closest(".code-copy-button");if(!(t instanceof HTMLButtonElement))return;const i=t.closest(".code-block-wrapper");if(!(i instanceof HTMLElement))return;const s=i.querySelector("pre code");s instanceof HTMLElement&&this.copyCode(s.textContent,t)}}render(){return l`<div class="formatted" @click=${this.onFormattedClick}>${xm(pv(this.text))}</div>`}updated(){this.enhanceCodeBlocks()}enhanceCodeBlocks(){this.renderRoot.querySelectorAll("pre").forEach(e=>{if(!(e instanceof HTMLPreElement)||e.parentElement?.classList.contains("code-block-wrapper")===!0||!(e.querySelector("code")instanceof HTMLElement))return;const i=document.createElement("div");i.className="code-block-wrapper";const s=document.createElement("button");s.type="button",s.className="code-copy-button",s.title="复制代码块",s.setAttribute("aria-label","复制代码块");const o=document.createElement("span");o.setAttribute("aria-hidden","true"),o.textContent="⧉",s.append(o),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await bv(e);this.setCopyButtonState(t,i?"copied":"failed"),window.setTimeout(()=>{this.setCopyButtonState(t,"idle")},1200)}setCopyButtonState(e,t){const i=e.querySelector("span");i!==null&&(i.textContent=t==="copied"?"✓":"⧉");const s=t==="copied"?"已复制代码块":t==="failed"?"复制代码块失败":"复制代码块";e.title=s,e.setAttribute("aria-label",s)}};Ci.styles=vv;za([d()],Ci.prototype,"text",2);Ci=za([W("formatted-text")],Ci);async function bv(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var wv=Object.defineProperty,yv=Object.getOwnPropertyDescriptor,Kt=(e,t,i,s)=>{for(var o=s>1?void 0:s?yv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&wv(t,i,o),o};const Qr=180;let et=class extends C{constructor(){super(...arguments),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){const e=this.execution;if(e===void 0)return null;const t=e.toolName==="edit",i=Sv(e.args),s=xv(e.details),o=e.preview,r=s??o?.diff,n=r===void 0?void 0:kv(r),a=s!==void 0&&o?.diff!==void 0&&s!==o.diff,c=e.status==="error"?e.resultText:o?.error,p=r===void 0?e.resultText:void 0;return l`
646
+ `;let Ti=class extends C{constructor(){super(...arguments),this.text="",this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;const t=e.target.closest(".code-copy-button");if(!(t instanceof HTMLButtonElement))return;const i=t.closest(".code-block-wrapper");if(!(i instanceof HTMLElement))return;const s=i.querySelector("pre code");s instanceof HTMLElement&&this.copyCode(s.textContent,t)}}render(){return l`<div class="formatted" @click=${this.onFormattedClick}>${km(hv(this.text))}</div>`}updated(){this.enhanceCodeBlocks()}enhanceCodeBlocks(){this.renderRoot.querySelectorAll("pre").forEach(e=>{if(!(e instanceof HTMLPreElement)||e.parentElement?.classList.contains("code-block-wrapper")===!0||!(e.querySelector("code")instanceof HTMLElement))return;const i=document.createElement("div");i.className="code-block-wrapper";const s=document.createElement("button");s.type="button",s.className="code-copy-button",s.title="复制代码块",s.setAttribute("aria-label","复制代码块");const o=document.createElement("span");o.setAttribute("aria-hidden","true"),o.textContent="⧉",s.append(o),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await wv(e);this.setCopyButtonState(t,i?"copied":"failed"),window.setTimeout(()=>{this.setCopyButtonState(t,"idle")},1200)}setCopyButtonState(e,t){const i=e.querySelector("span");i!==null&&(i.textContent=t==="copied"?"✓":"⧉");const s=t==="copied"?"已复制代码块":t==="failed"?"复制代码块失败":"复制代码块";e.title=s,e.setAttribute("aria-label",s)}};Ti.styles=bv;Ba([d()],Ti.prototype,"text",2);Ti=Ba([W("formatted-text")],Ti);async function wv(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var yv=Object.defineProperty,Sv=Object.getOwnPropertyDescriptor,Vt=(e,t,i,s)=>{for(var o=s>1?void 0:s?Sv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&yv(t,i,o),o};const Zr=180;let tt=class extends C{constructor(){super(...arguments),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){const e=this.execution;if(e===void 0)return null;const t=e.toolName==="edit",i=xv(e.args),s=kv(e.details),o=e.preview,r=s??o?.diff,n=r===void 0?void 0:$v(r),a=s!==void 0&&o?.diff!==void 0&&s!==o.diff,c=e.status==="error"?e.resultText:o?.error,p=r===void 0?e.resultText:void 0;return l`
647
647
  <section class=${`tool-card ${e.status}`}>
648
648
  <div class="tool-header">
649
649
  <div class="tool-title">
650
- <span class="status-icon" aria-hidden="true">${Pv(e.status)}</span>
650
+ <span class="status-icon" aria-hidden="true">${Rv(e.status)}</span>
651
651
  <strong>${e.toolName}</strong>
652
652
  ${i===void 0?l`<span class="summary">${e.summary}</span>`:l`<span class="path">${i}</span>`}
653
653
  </div>
654
654
  <div class="tool-meta">
655
- ${Zr(e)===void 0?null:l`<span>${Zr(e)}</span>`}
655
+ ${Xr(e)===void 0?null:l`<span>${Xr(e)}</span>`}
656
656
  ${n===void 0?null:l`<span class="diff-stats"><b class="added">+${n.added}</b><span>/</span><b class="removed">-${n.removed}</b></span>`}
657
- <span class="status-label">${Rv(e.status)}</span>
657
+ <span class="status-label">${Iv(e.status)}</span>
658
658
  </div>
659
659
  </div>
660
660
 
@@ -669,7 +669,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
669
669
  <pre>${e}</pre>
670
670
  </details>
671
671
  `}renderDiffBody(e,t){const i=e.split(`
672
- `),s=!this.showFullDiff&&i.length>Qr,o=s?i.slice(0,Qr):i;return l`
672
+ `),s=!this.showFullDiff&&i.length>Zr,o=s?i.slice(0,Zr):i;return l`
673
673
  <details class="diff-details" ?open=${this.diffOpen} @toggle=${r=>{this.onDiffToggle(r)}}>
674
674
  <summary>
675
675
  <span>${t}</span>
@@ -679,14 +679,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
679
679
  <span>${s?`显示 ${String(o.length)} / ${String(i.length)} 行`:"完整 diff"}</span>
680
680
  <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"已复制":"复制 diff"}</button>
681
681
  </div>
682
- <pre class="diff" aria-label=${t}><code class="diff-content">${o.map(r=>l`<span class=${$v(r)}>${r}</span>`)}</code></pre>
682
+ <pre class="diff" aria-label=${t}><code class="diff-content">${o.map(r=>l`<span class=${Pv(r)}>${r}</span>`)}</code></pre>
683
683
  ${s?l`
684
684
  <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
685
685
  显示全部 ${String(i.length)} 行 diff
686
686
  </button>
687
687
  `:null}
688
688
  </details>
689
- `}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){try{await navigator.clipboard.writeText(e),this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}catch{this.copied=!1}}};et.styles=D`
689
+ `}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){try{await navigator.clipboard.writeText(e),this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}catch{this.copied=!1}}};tt.styles=D`
690
690
  :host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
691
691
  .tool-card { display: grid; gap: 8px; width: 100%; max-width: 100%; min-width: 0; box-sizing: border-box; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 9px; color: var(--pi-text); }
692
692
  .tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
@@ -726,19 +726,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
726
726
  .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
727
727
  .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
728
728
  .show-more { justify-self: start; }
729
- `;Kt([d({attribute:!1})],et.prototype,"execution",2);Kt([k()],et.prototype,"showFullDiff",2);Kt([k()],et.prototype,"copied",2);Kt([k()],et.prototype,"diffOpen",2);et=Kt([W("tool-execution-view")],et);function Sv(e){return zs(e,"path")??zs(e,"file_path")}function Zr(e){if(e.toolName!=="edit")return;const t=ci(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof ci(e.args,"oldText")=="string"&&typeof ci(e.args,"newText")=="string")return"1 处编辑"}function xv(e){return zs(e,"diff")}function kv(e){let t=0,i=0;for(const s of e.split(`
730
- `))Ba(s)?t++:Ua(s)&&i++;return{added:t,removed:i}}function $v(e){return Ba(e)?"added":Ua(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function Ba(e){return e.startsWith("+")&&!e.startsWith("+++")}function Ua(e){return e.startsWith("-")&&!e.startsWith("---")}function Pv(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function Rv(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function Iv(e){return typeof e=="object"&&e!==null}function ci(e,t){return Iv(e)?e[t]:void 0}function zs(e,t){const i=ci(e,t);return typeof i=="string"?i:void 0}var Cv=Object.defineProperty,Tv=Object.getOwnPropertyDescriptor,U=(e,t,i,s)=>{for(var o=s>1?void 0:s?Tv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Cv(t,i,o),o};const Av=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Mv=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),fs=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"],Ev={active:"活跃","agent running":"助手运行中","bash complete":"Shell 已完成","bash failed":"Shell 失败","compaction complete":"压缩已完成","compaction failed":"压缩失败",compacting:"正在压缩","duplicate queued message ignored":"已忽略重复排队消息",error:"错误",idle:"空闲","message complete":"消息已完成","message queued":"消息已排队","message queued during compaction":"压缩期间消息已排队","message started":"消息已开始","prompt accepted":"提示已接受",queued:"已排队","receiving response":"正在接收回复","running bash":"Shell 运行中","running tool":"工具运行中","steering queued":"引导已排队",stopped:"已停止","tool complete":"工具已完成","tool failed":"工具失败","turn complete":"回合已完成"};function Xr(){return fs[Math.floor(Math.random()*fs.length)]??fs[0]}function Yr(e){return di(e,0,100)}function di(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let L=class extends C{constructor(){super(...arguments),this.messages=[],this.sessionId="",this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isReceivingPartialStream=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.disclosures=new Hg,this.scrollController=new fm,this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onPageHide=()=>{this.saveScrollPosition()}}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.onViewportResize),window.addEventListener("pagehide",this.onPageHide),window.visualViewport?.addEventListener("resize",this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),window.removeEventListener("resize",this.onViewportResize),window.removeEventListener("pagehide",this.onPageHide),window.visualViewport?.removeEventListener("resize",this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!="string"||e===""||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has("sessionId")&&(this.savePreviousSessionScrollPosition(e.get("sessionId")),this.prepareSessionUiState()),(e.has("isReceivingPartialStream")||e.has("sessionId")&&this.isReceivingPartialStream)&&this.syncPartialStreamNoticeBody(),e.has("messages")&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){const t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),t!==void 0&&this.restorePrependScrollAnchor(t)}updated(e){e.has("loadingMore")&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has("hasMore")&&!this.hasMore&&(this.loadMoreRequested=!1),e.has("sessionId")&&this.restoreScrollPosition(),!e.has("sessionId")&&e.has("messages")&&this.pinnedToBottom&&this.scrollToBottom(),(e.has("messages")||e.has("messageStart")||e.has("messageTotal")||e.has("hasMore")||e.has("loadingMore"))&&this.scheduleConversationRailUpdate(),(e.has("messages")||e.has("messageStart")||e.has("hasMore")||e.has("loadingMore"))&&this.continuePendingScrollRestore(),(e.has("messages")||e.has("hasMore")||e.has("loadingMore"))&&this.requestLoadMoreIfNeeded()}render(){const e=this.groupedMessages();return l`
729
+ `;Vt([d({attribute:!1})],tt.prototype,"execution",2);Vt([k()],tt.prototype,"showFullDiff",2);Vt([k()],tt.prototype,"copied",2);Vt([k()],tt.prototype,"diffOpen",2);tt=Vt([W("tool-execution-view")],tt);function xv(e){return Bs(e,"path")??Bs(e,"file_path")}function Xr(e){if(e.toolName!=="edit")return;const t=di(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof di(e.args,"oldText")=="string"&&typeof di(e.args,"newText")=="string")return"1 处编辑"}function kv(e){return Bs(e,"diff")}function $v(e){let t=0,i=0;for(const s of e.split(`
730
+ `))Ua(s)?t++:Ha(s)&&i++;return{added:t,removed:i}}function Pv(e){return Ua(e)?"added":Ha(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function Ua(e){return e.startsWith("+")&&!e.startsWith("+++")}function Ha(e){return e.startsWith("-")&&!e.startsWith("---")}function Rv(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function Iv(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function Cv(e){return typeof e=="object"&&e!==null}function di(e,t){return Cv(e)?e[t]:void 0}function Bs(e,t){const i=di(e,t);return typeof i=="string"?i:void 0}var Tv=Object.defineProperty,Av=Object.getOwnPropertyDescriptor,U=(e,t,i,s)=>{for(var o=s>1?void 0:s?Av(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Tv(t,i,o),o};const Mv=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Ev=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),gs=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"],Dv={active:"活跃","agent running":"助手运行中","bash complete":"Shell 已完成","bash failed":"Shell 失败","compaction complete":"压缩已完成","compaction failed":"压缩失败",compacting:"正在压缩","duplicate queued message ignored":"已忽略重复排队消息",error:"错误",idle:"空闲","message complete":"消息已完成","message queued":"消息已排队","message queued during compaction":"压缩期间消息已排队","message started":"消息已开始","prompt accepted":"提示已接受",queued:"已排队","receiving response":"正在接收回复","running bash":"Shell 运行中","running tool":"工具运行中","steering queued":"引导已排队",stopped:"已停止","tool complete":"工具已完成","tool failed":"工具失败","turn complete":"回合已完成"};function Yr(){return gs[Math.floor(Math.random()*gs.length)]??gs[0]}function en(e){return pi(e,0,100)}function pi(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let L=class extends C{constructor(){super(...arguments),this.messages=[],this.sessionId="",this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isReceivingPartialStream=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.disclosures=new qg,this.scrollController=new gm,this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onPageHide=()=>{this.saveScrollPosition()}}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.onViewportResize),window.addEventListener("pagehide",this.onPageHide),window.visualViewport?.addEventListener("resize",this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),window.removeEventListener("resize",this.onViewportResize),window.removeEventListener("pagehide",this.onPageHide),window.visualViewport?.removeEventListener("resize",this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!="string"||e===""||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has("sessionId")&&(this.savePreviousSessionScrollPosition(e.get("sessionId")),this.prepareSessionUiState()),(e.has("isReceivingPartialStream")||e.has("sessionId")&&this.isReceivingPartialStream)&&this.syncPartialStreamNoticeBody(),e.has("messages")&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){const t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),t!==void 0&&this.restorePrependScrollAnchor(t)}updated(e){e.has("loadingMore")&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has("hasMore")&&!this.hasMore&&(this.loadMoreRequested=!1),e.has("sessionId")&&this.restoreScrollPosition(),!e.has("sessionId")&&e.has("messages")&&this.pinnedToBottom&&this.scrollToBottom(),(e.has("messages")||e.has("messageStart")||e.has("messageTotal")||e.has("hasMore")||e.has("loadingMore"))&&this.scheduleConversationRailUpdate(),(e.has("messages")||e.has("messageStart")||e.has("hasMore")||e.has("loadingMore"))&&this.continuePendingScrollRestore(),(e.has("messages")||e.has("hasMore")||e.has("loadingMore"))&&this.requestLoadMoreIfNeeded()}render(){const e=this.groupedMessages();return l`
731
731
  <div class="chat-wrap">
732
732
  ${this.renderConversationRail()}
733
733
  <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
734
734
  ${this.renderHistoryBoundary()}
735
- ${zg(e,t=>t.kind==="message"?this.messageAnchorKey(t.index):this.groupRenderKey(t.startIndex),(t,i)=>t.kind==="message"?this.renderMessage(t.message,t.index):this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,i)))}
735
+ ${Bg(e,t=>t.kind==="message"?this.messageAnchorKey(t.index):this.groupRenderKey(t.startIndex),(t,i)=>t.kind==="message"?this.renderMessage(t.message,t.index):this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,i)))}
736
736
  ${this.renderQueuedMessages()}
737
737
  ${this.renderSessionActivity()}
738
738
  </div>
739
739
  ${this.renderActivityDock()}
740
740
  </div>
741
- `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Vg(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){if(this.isSendingPrompt)return l`
741
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Gg(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){if(this.isSendingPrompt)return l`
742
742
  <div class="activity-dock active" aria-live="polite">
743
743
  <span class="dot"></span>
744
744
  <span class="activity-text">正在发送你的消息…</span>
@@ -773,7 +773,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
773
773
  <span>助手正在总结早前上下文。压缩完成前,新提示会排队等待。</span>
774
774
  ${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} 条消息已排队</small>`:null}
775
775
  </aside>
776
- `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Xr():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Xr(),this.partialStreamNoticeBody}activityState(){const e=this.status;return e===void 0?this.activity?.label:e.isCompacting?"compacting":e.isBashRunning?"bash":e.isStreaming?"running":e.pendingMessageCount>0?"queued":"idle"}activityText(e){const t=this.activity;if(t===void 0||e!=="idle"&&t.phase==="idle")return gs(e);const i=gs(t.label);return t.detail!==void 0&&t.detail!==""?`${i}: ${t.detail}`:i}renderConversationRail(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.conversationDisplayTotal(),t=this.conversationPositionPercent(e),i=this.hasMore?Yr(this.messages.length/e*100):100;return l`<conversation-meter .positionPercent=${t} .loadedPercent=${i}></conversation-meter>`}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;const t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,i=di(this.currentConversationIndex??t,0,e-1);return Yr(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?l`
776
+ `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Yr():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Yr(),this.partialStreamNoticeBody}activityState(){const e=this.status;return e===void 0?this.activity?.label:e.isCompacting?"compacting":e.isBashRunning?"bash":e.isStreaming?"running":e.pendingMessageCount>0?"queued":"idle"}activityText(e){const t=this.activity;if(t===void 0||e!=="idle"&&t.phase==="idle")return ms(e);const i=ms(t.label);return t.detail!==void 0&&t.detail!==""?`${i}: ${t.detail}`:i}renderConversationRail(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.conversationDisplayTotal(),t=this.conversationPositionPercent(e),i=this.hasMore?en(this.messages.length/e*100):100;return l`<conversation-meter .positionPercent=${t} .loadedPercent=${i}></conversation-meter>`}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;const t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,i=pi(this.currentConversationIndex??t,0,e-1);return en(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?l`
777
777
  <div class="history-boundary">
778
778
  <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>加载更早的消息</button>
779
779
  <span>向上滚动加载更早的消息</span>
@@ -790,7 +790,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
790
790
  <details class=${s?"msg event-group live":"msg event-group"} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${r} @toggle=${n=>{this.onGroupToggle(o,n,s)}}>
791
791
  <summary>
792
792
  <b class="label">${s?"实时事件":"事件"}</b>
793
- <span>${Gg(e)}</span>
793
+ <span>${Jg(e)}</span>
794
794
  </summary>
795
795
  <div class="group-body">
796
796
  ${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
@@ -803,7 +803,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
803
803
  </details>
804
804
  `}renderScrollMarker(e){return l`<span class="scroll-marker" data-marker-id=${e} aria-hidden="true"></span>`}renderMessageHeader(e,t){const i=this.messageMetaLabel(e),s=this.expandedMetaKey===t;return l`
805
805
  <div class="msg-header">
806
- <b class="label">${en(e.role)}</b>
806
+ <b class="label">${tn(e.role)}</b>
807
807
  <div class="msg-header-trailing">
808
808
  ${this.renderMessageActions(e,t)}
809
809
  <span class=${s?"msg-meta expanded":"msg-meta"} role="button" tabindex="0" title=${i.full} aria-label=${i.full} aria-expanded=${String(s)} @click=${()=>{this.expandedMetaKey=s?void 0:t}} @keydown=${o=>{this.onMetaKeydown(o,t,s)}}>${i.short}</span>
@@ -811,13 +811,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
811
811
  </div>
812
812
  `}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return l`
813
813
  <div class="msg-actions" aria-label="消息操作">
814
- <button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${en(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
814
+ <button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${tn(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
815
815
  <span aria-hidden="true">${i?"✓":"⧉"}</span>
816
816
  </button>
817
817
  </div>
818
818
  `}onMetaKeydown(e,t,i){e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),this.expandedMetaKey=i?void 0:t)}isCopyableMessage(e){return(e.role==="user"||e.role==="assistant")&&this.messageCopyText(e)!==""}messageCopyText(e){const t=this.messageCopyTextCache.get(e);if(t!==void 0)return t;const i=e.parts.filter(s=>s.type==="text").map(s=>s.text.trim()).filter(s=>s!=="").join(`
819
819
 
820
- `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await this.writeClipboard(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const c={short:"无信息",full:"没有可用的 Pi 消息元数据"};return this.messageMetaCache.set(e,c),c}const o=i===void 0?void 0:this.formatTimestamp(i),r=[o?.short,s].filter(c=>c!==void 0&&c!==""),n=[o?.full,s===void 0?void 0:`模型:${s}`].filter(c=>c!==void 0&&c!==""),a={short:r.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:Av.format(t),full:Mv.format(t)}}modelLabel(e){const t=e.meta?.model;if(t===void 0)return;const i=t.responseId??t.id;return i===void 0||i===""?t.provider:t.provider!==void 0&&t.provider!==""?`${t.provider}/${i}`:i}renderPart(e,t){return e.type==="text"&&t?.role==="bash"?l`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?l`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="image"?l`<figure class="part chat-image"><img src=${`data:${e.mimeType};base64,${e.data}`} alt="用户上传的图片" loading="lazy"></figure>`:e.type==="thinking"?l`<details class="part"><summary>思考</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
820
+ `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await this.writeClipboard(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const c={short:"无信息",full:"没有可用的 Pi 消息元数据"};return this.messageMetaCache.set(e,c),c}const o=i===void 0?void 0:this.formatTimestamp(i),r=[o?.short,s].filter(c=>c!==void 0&&c!==""),n=[o?.full,s===void 0?void 0:`模型:${s}`].filter(c=>c!==void 0&&c!==""),a={short:r.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:Mv.format(t),full:Ev.format(t)}}modelLabel(e){const t=e.meta?.model;if(t===void 0)return;const i=t.responseId??t.id;return i===void 0||i===""?t.provider:t.provider!==void 0&&t.provider!==""?`${t.provider}/${i}`:i}renderPart(e,t){return e.type==="text"&&t?.role==="bash"?l`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?l`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="image"?l`<figure class="part chat-image"><img src=${`data:${e.mimeType};base64,${e.data}`} alt="用户上传的图片" loading="lazy"></figure>`:e.type==="thinking"?l`<details class="part"><summary>思考</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
821
821
  <details class="part skill-invocation">
822
822
  <summary><b>[技能]</b> ${e.name}</summary>
823
823
  <small>${e.location}</small>
@@ -833,31 +833,31 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
833
833
  <summary>${e.isError?"✖":"✓"} ${e.toolName} 结果</summary>
834
834
  <formatted-text .text=${e.text}></formatted-text>
835
835
  </details>
836
- `:null}onGroupToggle(e,t,i){const s=t.currentTarget;s instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,s.open,i)&&this.requestUpdate()}onScroll(){this.requestLoadMoreIfNeeded(),this.updatePinnedToBottomFromScroll(),this.scheduleConversationRailUpdate(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(e){e.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(e){this.touchStartY=e.touches[0]?.clientY}onTouchMove(e){const t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){const e=this.chat;if(!e)return;const t=this.didChatHeightChange(),i=this.pinnedToBottom,s=e.scrollTop<this.lastScrollTop;if(t&&i){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:s?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){const e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){const t=e.get("messageStart");return typeof t=="number"&&this.messageStart<t}requestLoadMoreIfNeeded(){this.loadMoreCheckFrame===void 0&&(this.loadMoreCheckFrame=requestAnimationFrame(()=>{if(this.loadMoreCheckFrame=void 0,this.suppressLoadMoreRequests)return;const e=this.chat;e&&rm({hasMore:this.hasMore,loadingMore:this.loadingMore||this.loadMoreRequested,canRequest:this.onLoadMore!==void 0,scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})&&this.requestLoadMore()}))}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}isNearBottom(){const e=this.chat;return e?Ta(e):!0}isAtBottom(){const e=this.chat;return e?Ca(e)<2:!0}canScrollUp(){const e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;const e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){const e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){const e=this.pendingScrollRestoreSessionId,t=this.pendingScrollRestorePosition;e===void 0||t===void 0||e!==this.sessionId||this.restoreScrollFrame!==void 0||(this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const i=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,i)})}))}handleScrollRestoreResult(e,t){if(this.syncScrollMetrics(),t.status!=="missing"){this.updatePinnedToBottomAfterRestore(t.status),(t.status==="restored"||t.status==="bottom")&&this.cancelPrependRestore(),this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0;return}this.pinnedToBottom=!1,this.pendingScrollRestoreSessionId=e,this.pendingScrollRestorePosition=t.position;const i=this.chat;i===void 0||!this.hasMore||this.loadingMore||(i.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore&&!this.isReceivingPartialStream}updatePinnedToBottomAfterRestore(e){e==="bottom"?this.pinnedToBottom=!0:e==="restored"&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){const e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){const e=this.chat;if(e)return Zg(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;const t=this.prependRestoreToken+1;this.prependRestoreToken=t;let i=0;const s=()=>{const o=this.chat;if(!(!o||t!==this.prependRestoreToken)){if(Xg(o,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=o.scrollTop,i+=1,i<Qg){requestAnimationFrame(s);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};s()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){const e=this.sessionId;this.scrollController.scheduleSave(e,t=>{this.sessionId===t&&this.saveScrollPosition(t)})}scheduleConversationRailUpdate(){this.conversationRailFrame===void 0&&(this.conversationRailFrame=requestAnimationFrame(()=>{this.conversationRailFrame=void 0,this.updateConversationRailPosition()}))}updateConversationRailPosition(){if(!this.messages.length||this.messageTotal<=0){this.currentConversationIndex=void 0;return}const e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),i=Number(t?.dataset.index);if(Number.isFinite(i)){this.currentConversationIndex=di(i,0,Math.max(0,e-1));return}this.currentConversationIndex=di(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(".scroll-marker"))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}firstVisibleArticle(){const e=this.chat;if(e===void 0)return;const t=Array.from(this.renderRoot.querySelectorAll("article.msg"));return zr(e,t)??zr(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll("[data-scroll-anchor-id]"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,i){return i?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return`m:${String(e)}`}groupRenderKey(e){return`g:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}eventAnchorKey(e){return`e:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}};L.styles=wm;U([d({attribute:!1})],L.prototype,"messages",2);U([d()],L.prototype,"sessionId",2);U([d({type:Number})],L.prototype,"messageStart",2);U([d({type:Number})],L.prototype,"messageEnd",2);U([d({type:Number})],L.prototype,"messageTotal",2);U([d({type:Boolean})],L.prototype,"hasMore",2);U([d({type:Boolean})],L.prototype,"loadingMore",2);U([d({type:Boolean})],L.prototype,"isReceivingPartialStream",2);U([d({type:Boolean})],L.prototype,"isSendingPrompt",2);U([d({type:Boolean})],L.prototype,"isCompacting",2);U([d({type:Number})],L.prototype,"pendingMessageCount",2);U([d({attribute:!1})],L.prototype,"status",2);U([d({attribute:!1})],L.prototype,"activity",2);U([d({attribute:!1})],L.prototype,"onLoadMore",2);U([B(".chat")],L.prototype,"chat",2);U([k()],L.prototype,"pinnedToBottom",2);U([k()],L.prototype,"expandedMetaKey",2);U([k()],L.prototype,"copiedMessageKey",2);U([k()],L.prototype,"currentConversationIndex",2);U([k()],L.prototype,"loadMoreRequested",2);L=U([W("chat-view")],L);function en(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function gs(e){return e==="bash"?"Shell 运行中":e==="running"?"运行中":Ev[e]??e}const Dv=["image/jpeg","image/png","image/gif","image/webp"],Wv=new Set(Dv);function Ov(e){return typeof e=="string"&&Wv.has(e)}function _v(e){switch(e){case"image/jpeg":return"jpg";case"image/png":return"png";case"image/gif":return"gif";case"image/webp":return"webp";default:return"bin"}}const Lv="Only PNG, JPEG, GIF, and WebP images are supported.",jv="读取附件失败。";async function Fv(e,t){const i=[];let s;for(const o of e){if(!Ov(o.type)){s=Lv;continue}try{const r=await t(o);i.push({name:Nv(o),mimeType:o.type,data:r,size:o.size})}catch{s=jv}}return{attachments:i,...s===void 0?{}:{error:s}}}function Nv(e){return e.name!==""?e.name:`pasted-image.${_v(e.type)}`}const Ha="pi-web:attachment-delivery";function qa(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function zv(e=qa()){try{return e?.getItem(Ha)==="folder"?"folder":"inline"}catch{return"inline"}}function Bv(e,t=qa()){try{t?.setItem(Ha,e)}catch{}}function Uv(){return he`
836
+ `:null}onGroupToggle(e,t,i){const s=t.currentTarget;s instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,s.open,i)&&this.requestUpdate()}onScroll(){this.requestLoadMoreIfNeeded(),this.updatePinnedToBottomFromScroll(),this.scheduleConversationRailUpdate(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(e){e.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(e){this.touchStartY=e.touches[0]?.clientY}onTouchMove(e){const t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){const e=this.chat;if(!e)return;const t=this.didChatHeightChange(),i=this.pinnedToBottom,s=e.scrollTop<this.lastScrollTop;if(t&&i){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:s?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){const e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){const t=e.get("messageStart");return typeof t=="number"&&this.messageStart<t}requestLoadMoreIfNeeded(){this.loadMoreCheckFrame===void 0&&(this.loadMoreCheckFrame=requestAnimationFrame(()=>{if(this.loadMoreCheckFrame=void 0,this.suppressLoadMoreRequests)return;const e=this.chat;e&&nm({hasMore:this.hasMore,loadingMore:this.loadingMore||this.loadMoreRequested,canRequest:this.onLoadMore!==void 0,scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})&&this.requestLoadMore()}))}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}isNearBottom(){const e=this.chat;return e?Aa(e):!0}isAtBottom(){const e=this.chat;return e?Ta(e)<2:!0}canScrollUp(){const e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;const e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){const e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){const e=this.pendingScrollRestoreSessionId,t=this.pendingScrollRestorePosition;e===void 0||t===void 0||e!==this.sessionId||this.restoreScrollFrame!==void 0||(this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const i=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,i)})}))}handleScrollRestoreResult(e,t){if(this.syncScrollMetrics(),t.status!=="missing"){this.updatePinnedToBottomAfterRestore(t.status),(t.status==="restored"||t.status==="bottom")&&this.cancelPrependRestore(),this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0;return}this.pinnedToBottom=!1,this.pendingScrollRestoreSessionId=e,this.pendingScrollRestorePosition=t.position;const i=this.chat;i===void 0||!this.hasMore||this.loadingMore||(i.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore&&!this.isReceivingPartialStream}updatePinnedToBottomAfterRestore(e){e==="bottom"?this.pinnedToBottom=!0:e==="restored"&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){const e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){const e=this.chat;if(e)return Xg(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;const t=this.prependRestoreToken+1;this.prependRestoreToken=t;let i=0;const s=()=>{const o=this.chat;if(!(!o||t!==this.prependRestoreToken)){if(Yg(o,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=o.scrollTop,i+=1,i<Zg){requestAnimationFrame(s);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};s()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){const e=this.sessionId;this.scrollController.scheduleSave(e,t=>{this.sessionId===t&&this.saveScrollPosition(t)})}scheduleConversationRailUpdate(){this.conversationRailFrame===void 0&&(this.conversationRailFrame=requestAnimationFrame(()=>{this.conversationRailFrame=void 0,this.updateConversationRailPosition()}))}updateConversationRailPosition(){if(!this.messages.length||this.messageTotal<=0){this.currentConversationIndex=void 0;return}const e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),i=Number(t?.dataset.index);if(Number.isFinite(i)){this.currentConversationIndex=pi(i,0,Math.max(0,e-1));return}this.currentConversationIndex=pi(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(".scroll-marker"))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}firstVisibleArticle(){const e=this.chat;if(e===void 0)return;const t=Array.from(this.renderRoot.querySelectorAll("article.msg"));return Br(e,t)??Br(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll("[data-scroll-anchor-id]"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,i){return i?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return`m:${String(e)}`}groupRenderKey(e){return`g:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}eventAnchorKey(e){return`e:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}};L.styles=ym;U([d({attribute:!1})],L.prototype,"messages",2);U([d()],L.prototype,"sessionId",2);U([d({type:Number})],L.prototype,"messageStart",2);U([d({type:Number})],L.prototype,"messageEnd",2);U([d({type:Number})],L.prototype,"messageTotal",2);U([d({type:Boolean})],L.prototype,"hasMore",2);U([d({type:Boolean})],L.prototype,"loadingMore",2);U([d({type:Boolean})],L.prototype,"isReceivingPartialStream",2);U([d({type:Boolean})],L.prototype,"isSendingPrompt",2);U([d({type:Boolean})],L.prototype,"isCompacting",2);U([d({type:Number})],L.prototype,"pendingMessageCount",2);U([d({attribute:!1})],L.prototype,"status",2);U([d({attribute:!1})],L.prototype,"activity",2);U([d({attribute:!1})],L.prototype,"onLoadMore",2);U([B(".chat")],L.prototype,"chat",2);U([k()],L.prototype,"pinnedToBottom",2);U([k()],L.prototype,"expandedMetaKey",2);U([k()],L.prototype,"copiedMessageKey",2);U([k()],L.prototype,"currentConversationIndex",2);U([k()],L.prototype,"loadMoreRequested",2);L=U([W("chat-view")],L);function tn(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function ms(e){return e==="bash"?"Shell 运行中":e==="running"?"运行中":Dv[e]??e}const Wv=["image/jpeg","image/png","image/gif","image/webp"],Ov=new Set(Wv);function _v(e){return typeof e=="string"&&Ov.has(e)}function Lv(e){switch(e){case"image/jpeg":return"jpg";case"image/png":return"png";case"image/gif":return"gif";case"image/webp":return"webp";default:return"bin"}}const jv="Only PNG, JPEG, GIF, and WebP images are supported.",Fv="读取附件失败。";async function Nv(e,t){const i=[];let s;for(const o of e){if(!_v(o.type)){s=jv;continue}try{const r=await t(o);i.push({name:zv(o),mimeType:o.type,data:r,size:o.size})}catch{s=Fv}}return{attachments:i,...s===void 0?{}:{error:s}}}function zv(e){return e.name!==""?e.name:`pasted-image.${Lv(e.type)}`}const qa="pi-web:attachment-delivery";function Ka(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Bv(e=Ka()){try{return e?.getItem(qa)==="folder"?"folder":"inline"}catch{return"inline"}}function Uv(e,t=Ka()){try{t?.setItem(qa,e)}catch{}}function Hv(){return he`
837
837
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
838
838
  <path d="M20 11.5 12.5 19a4 4 0 0 1-5.66-5.66l7.07-7.07a2.5 2.5 0 0 1 3.54 3.54l-7.07 7.07a1 1 0 0 1-1.42-1.42l6.37-6.36"></path>
839
839
  </svg>
840
- `}function Ka(){return he`
840
+ `}function Va(){return he`
841
841
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
842
842
  <path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
843
843
  <path d="M21 3 11.5 12.5"></path>
844
844
  </svg>
845
- `}function Hv(){return he`
845
+ `}function qv(){return he`
846
846
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
847
847
  <path d="M4 7h11"></path>
848
848
  <path d="M4 12h7"></path>
849
849
  <path d="M4 17h7"></path>
850
850
  <path d="m15 14 5 3-5 3z"></path>
851
851
  </svg>
852
- `}function qv(){return Ka()}function Kv(){return he`
852
+ `}function Kv(){return Va()}function Vv(){return he`
853
853
  <svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
854
854
  <rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
855
855
  </svg>
856
- `}function Vv(e){const t=Math.max(e.total,1),i=t>1?1.2:0,s=3,n=(21-s-i*(t-1))/t,a=Array.from({length:t},(c,p)=>{const u=s+p*(n+i),h=4+(p+1)/t*12,g=20-h,w=p<e.filled;return he`<rect class=${w?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${g} width=${n} height=${h} rx="1"></rect>`});return he`
856
+ `}function Gv(e){const t=Math.max(e.total,1),i=t>1?1.2:0,s=3,n=(21-s-i*(t-1))/t,a=Array.from({length:t},(c,p)=>{const u=s+p*(n+i),h=4+(p+1)/t*12,g=20-h,b=p<e.filled;return he`<rect class=${b?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${g} width=${n} height=${h} rx="1"></rect>`});return he`
857
857
  <svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
858
858
  ${a}
859
859
  </svg>
860
- `}const Gv=["off","minimal","low","medium","high","xhigh"];function Bs(e){return e===void 0||e===""?"off":e}function Jv(e,t){const i=t.length>=2?t:Gv,s=i.length-1,o=Bs(e),r=i.indexOf(o),n=r<=0?0:Math.min(r,s);return{total:s,filled:n}}class Qv extends mo{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===fo.ELEMENT}update(t,[i,s]){if(!this.isElementPart)throw new Error("scrollWhenSelected must be used on an element");if(i&&(!this.wasSelected||s!==this.previousKey)){const o="element"in t?t.element:void 0;requestAnimationFrame(()=>{o instanceof HTMLElement&&o.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const Co=go(Qv);var Zv=Object.defineProperty,Xv=Object.getOwnPropertyDescriptor,qi=(e,t,i,s)=>{for(var o=s>1?void 0:s?Xv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Zv(t,i,o),o};const Yv=D`
860
+ `}const Jv=["off","minimal","low","medium","high","xhigh"];function Us(e){return e===void 0||e===""?"off":e}function Qv(e,t){const i=t.length>=2?t:Jv,s=i.length-1,o=Us(e),r=i.indexOf(o),n=r<=0?0:Math.min(r,s);return{total:s,filled:n}}class Zv extends vo{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===go.ELEMENT}update(t,[i,s]){if(!this.isElementPart)throw new Error("scrollWhenSelected must be used on an element");if(i&&(!this.wasSelected||s!==this.previousKey)){const o="element"in t?t.element:void 0;requestAnimationFrame(()=>{o instanceof HTMLElement&&o.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const To=mo(Zv);var Xv=Object.defineProperty,Yv=Object.getOwnPropertyDescriptor,Ki=(e,t,i,s)=>{for(var o=s>1?void 0:s?Yv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Xv(t,i,o),o};const eb=D`
861
861
  :host { display: block; }
862
862
  .menu { position: absolute; left: 0; right: 0; bottom: calc(100% + 6px); z-index: 10; max-height: 260px; overflow: auto; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 10px 30px var(--pi-shadow); }
863
863
  button { display: grid; grid-template-columns: minmax(120px, 1fr) auto; gap: 4px 10px; width: 100%; border: 0; border-bottom: 1px solid var(--pi-border); border-radius: 0; background: transparent; color: var(--pi-text); padding: 8px 10px; text-align: left; cursor: pointer; }
@@ -865,17 +865,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
865
865
  button.selected, button:hover { background: var(--pi-selection-bg); }
866
866
  span { color: var(--pi-muted); font-size: 12px; }
867
867
  small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
868
- `;let ut=class extends C{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
868
+ `;let ft=class extends C{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
869
869
  <div class="menu">
870
870
  ${this.items.map((e,t)=>l`
871
- <button class=${t===this.selectedIndex?"selected":""} ${Co(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
871
+ <button class=${t===this.selectedIndex?"selected":""} ${To(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
872
872
  <strong>${e.insertText}</strong>
873
873
  <span>${e.detail}</span>
874
874
  ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
875
875
  </button>
876
876
  `)}
877
877
  </div>
878
- `:null}};ut.styles=Yv;qi([d({attribute:!1})],ut.prototype,"items",2);qi([d({type:Number})],ut.prototype,"selectedIndex",2);qi([d({attribute:!1})],ut.prototype,"onPick",2);ut=qi([W("autocomplete-menu")],ut);var eb=Object.defineProperty,tb=Object.getOwnPropertyDescriptor,j=(e,t,i,s)=>{for(var o=s>1?void 0:s?tb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&eb(t,i,o),o};const ib=D`
878
+ `:null}};ft.styles=eb;Ki([d({attribute:!1})],ft.prototype,"items",2);Ki([d({type:Number})],ft.prototype,"selectedIndex",2);Ki([d({attribute:!1})],ft.prototype,"onPick",2);ft=Ki([W("autocomplete-menu")],ft);var tb=Object.defineProperty,ib=Object.getOwnPropertyDescriptor,j=(e,t,i,s)=>{for(var o=s>1?void 0:s?ib(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&tb(t,i,o),o};const sb=D`
879
879
  :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
880
880
  footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
881
881
  footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
@@ -923,12 +923,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
923
923
  button { padding: 5px 7px; }
924
924
  .icon-button { width: 34px; height: 34px; }
925
925
  }
926
- `;let _=class extends C{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft="",this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=zv(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new Ao,this.readOnlyCompartment=new Ao}willUpdate(e){if(!e.has("sessionId")&&!e.has("machineId"))return;const t=e.has("sessionId")?e.get("sessionId"):this.sessionId,i=e.has("machineId")?e.get("machineId"):this.machineId,s=Yt(i,t);s!==void 0&&bi(s,this.draft);const o=Yt(this.machineId,this.sessionId);this.draft=o!==void 0?Nn(o):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("draft")||e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=ro(this.draft),t=e.kind==="shell",i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return l`
926
+ `;let _=class extends C{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft="",this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=Bv(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new Mo,this.readOnlyCompartment=new Mo}willUpdate(e){if(!e.has("sessionId")&&!e.has("machineId"))return;const t=e.has("sessionId")?e.get("sessionId"):this.sessionId,i=e.has("machineId")?e.get("machineId"):this.machineId,s=ei(i,t);s!==void 0&&wi(s,this.draft);const o=ei(this.machineId,this.sessionId);this.draft=o!==void 0?zn(o):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("draft")||e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=no(this.draft),t=e.kind==="shell",i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return l`
927
927
  <footer class=${t?"shell-mode":""} @paste=${o=>{this.handlePaste(o)}} @dragover=${o=>{this.handleDragOver(o)}} @drop=${o=>{this.handleDrop(o)}}>
928
928
  <div class="editor-wrap">
929
929
  <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="给 pi 发送消息" aria-disabled=${this.disabled?"true":"false"}></div>
930
930
  <input class="attachment-input" type="file" accept="image/png,image/jpeg,image/gif,image/webp" multiple hidden @change=${o=>{this.handleFileInput(o)}} />
931
- <button class="editor-attach icon-button" ?disabled=${s} title="附加图片" aria-label="附加图片" @click=${()=>{this.attachmentInput?.click()}}>${Uv()}</button>
931
+ <button class="editor-attach icon-button" ?disabled=${s} title="附加图片" aria-label="附加图片" @click=${()=>{this.attachmentInput?.click()}}>${Hv()}</button>
932
932
  ${t?l`<div class="mode-hint">Shell 命令${e.excludeFromContext?" · 已排除上下文":""}</div>`:null}
933
933
  ${this.isCompacting&&!t?l`<div class="mode-hint">正在压缩历史 · 消息将排队发送</div>`:null}
934
934
  ${this.renderAttachments()}
@@ -936,15 +936,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
936
936
  </div>
937
937
  <div class="actions">
938
938
  ${this.renderCompactStatus()}
939
- <button class="icon-button send-button" ?disabled=${s} title=${i?"当前活动结束后排队发送":"发送"} aria-label=${i?"排队发送":"发送"} @click=${()=>{this.send("followUp")}}>${i?Hv():Ka()}</button>
940
- ${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send("steer")}}>${qv()}</button>`:null}
941
- <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} aria-label="停止" @click=${()=>this.onStop?.()}>${Kv()}</button>
939
+ <button class="icon-button send-button" ?disabled=${s} title=${i?"当前活动结束后排队发送":"发送"} aria-label=${i?"排队发送":"发送"} @click=${()=>{this.send("followUp")}}>${i?qv():Va()}</button>
940
+ ${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send("steer")}}>${Kv()}</button>`:null}
941
+ <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} aria-label="停止" @click=${()=>this.onStop?.()}>${Vv()}</button>
942
942
  </div>
943
943
  </footer>
944
944
  `}focusInput(){this.editor?.focus()}renderCompactStatus(){const e=this.status;if(e===void 0)return null;const t=e.model?.id??"无模型",i=e.model?.provider!==void 0&&e.model.provider!==""?`${e.model.provider}/`:"";return l`
945
945
  <div class="compact-status" aria-label="会话状态">
946
946
  <button class="select-model" title="选择模型" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
947
- <button class="select-thinking icon-button" title=${`思考级别:${Bs(e.thinkingLevel)}`} aria-label=${`思考级别:${Bs(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${Vv(Jv(e.thinkingLevel,this.availableThinkingLevels))}</button>
947
+ <button class="select-thinking icon-button" title=${`思考级别:${Us(e.thinkingLevel)}`} aria-label=${`思考级别:${Us(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${Gv(Qv(e.thinkingLevel,this.availableThinkingLevels))}</button>
948
948
  </div>
949
949
  `}renderAttachments(){return this.attachments.length===0&&this.attachmentError===void 0?null:l`
950
950
  <div class="attachments" aria-label="待发送附件">
@@ -964,7 +964,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
964
964
  `:null}
965
965
  ${this.attachmentError!==void 0?l`<div class="attachment-error">${this.attachmentError}</div>`:null}
966
966
  </div>
967
- `}changeDelivery(e){e.target instanceof HTMLSelectElement&&(this.attachmentDelivery=e.target.value==="folder"?"folder":"inline",Bv(this.attachmentDelivery))}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=tn(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&Array.from(e.dataTransfer.items).some(t=>t.kind==="file"&&t.type.startsWith("image/"))&&e.preventDefault()}async handleDrop(e){const t=tn(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;const t=Array.from(e.target.files);e.target.value="",await this.addAttachmentFiles(t)}async addAttachmentFiles(e){this.attachmentError=void 0;const{attachments:t,error:i}=await Fv(e,rb);t.length>0&&(this.attachments=[...this.attachments,...t.map(s=>({id:`attachment-${String(++this.attachmentSeq)}`,...s}))]),i!==void 0&&(this.attachmentError=i)}currentAttachments(){return this.attachments.map(e=>({kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}))}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new rt({parent:this.editorHost,state:Ji.create({doc:this.draft,extensions:[el(),dl(),tl(),il.of(" "),sl(cl,{fallback:!0}),rt.lineWrapping,rt.contentAttributes.of(e=>lb(e.state.sliceDoc(0,e.state.selection.main.head))),ol("给 pi 发送消息... 使用 / 输入命令,@ 输入已跟踪文件,@ 空格显示所有文件"),this.editableCompartment.of(rt.editable.of(!this.disabled)),this.readOnlyCompartment.of(Ji.readOnly.of(this.disabled)),rt.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),rl.of([{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Enter",run:()=>this.handleEditorEnter()},{key:"Shift-Enter",run:e=>pl(e)||ll(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>Mo.shift?.(e)??!1},{key:"Backspace",run:e=>hl(e)},...nl,...al])]})}))}syncEditorDoc(){const e=this.editor;if(!e)return;const t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:Eo.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(rt.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(Ji.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Yt(this.machineId,this.sessionId);t!==void 0&&bi(t,this.draft),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""&&this.cwd!==void 0&&this.cwd!==""){const i=await z.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(sb);if(t!==this.requestVersion)return;this.completions=i.filter(s=>s.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(s=>({kind:"command",replaceFrom:e.from,replaceTo:e.to,insertText:`/${s.name}`,detail:s.source,...s.description===void 0?{}:{description:s.description}}))}else if(e.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const i=await z.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId}).catch(ob);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const o=Vn(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:o,detail:s.kind,...s.path.endsWith("/")&&o.endsWith('"')?{cursorOffset:o.length-1}:{}}})}}currentTrigger(){return Kn(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorEnter(){if(this.completions.length){const e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):Mo.run?.(e)??!1}pick(e){const t=this.editor;if(!t)return;const i=e.kind==="file"&&(e.insertText.endsWith("/")||e.cursorOffset!==void 0)?"":" ",s=e.replaceFrom+(e.cursorOffset??e.insertText.length)+i.length,o=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:o,insert:`${e.insertText}${i}`},selection:Eo.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;const t=this.draft.trim(),i=this.attachments;if(t===""&&i.length===0)return;const s=this.canSteer||this.isCompacting?e:void 0,o=i.length>0?this.currentAttachments():void 0,r=this.attachmentDelivery;this.resetComposer(),this.onSend?.(t,s,o,o===void 0?void 0:r)}resetComposer(){this.draft="";const e=Yt(this.machineId,this.sessionId);e!==void 0&&oo(e),this.completions=[],this.attachments=[],this.attachmentError=void 0}};_.styles=ib;j([d({type:Boolean})],_.prototype,"disabled",2);j([d()],_.prototype,"sessionId",2);j([d()],_.prototype,"cwd",2);j([d()],_.prototype,"machineId",2);j([d({type:Boolean})],_.prototype,"canSteer",2);j([d({type:Boolean})],_.prototype,"isCompacting",2);j([d({type:Boolean})],_.prototype,"canStop",2);j([d({attribute:!1})],_.prototype,"status",2);j([d({type:Boolean})],_.prototype,"sending",2);j([d({attribute:!1})],_.prototype,"onSend",2);j([d({attribute:!1})],_.prototype,"onStop",2);j([d({attribute:!1})],_.prototype,"onSelectModel",2);j([d({attribute:!1})],_.prototype,"onSelectThinking",2);j([d({attribute:!1})],_.prototype,"availableThinkingLevels",2);j([B(".markdown-editor")],_.prototype,"editorHost",2);j([B(".attachment-input")],_.prototype,"attachmentInput",2);j([k()],_.prototype,"draft",2);j([k()],_.prototype,"completions",2);j([k()],_.prototype,"selectedIndex",2);j([k()],_.prototype,"attachments",2);j([k()],_.prototype,"attachmentDelivery",2);j([k()],_.prototype,"attachmentError",2);_=j([W("prompt-editor")],_);function Yt(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return jn(e,t)}function sb(){return[]}function ob(){return[]}function tn(e){return e===null?[]:Array.from(e.files).filter(t=>t.type.startsWith("image/"))}function rb(e){return new Promise((t,i)=>{const s=new FileReader;s.onerror=()=>{i(s.error??new Error("读取文件失败"))},s.onload=()=>{const o=s.result;if(typeof o!="string"){i(new Error("文件读取结果异常"));return}const r=o.indexOf(",");t(r===-1?o:o.slice(r+1))},s.readAsDataURL(e)})}const nb={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},ab={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function lb(e){return ro(e).kind==="normal"?nb:ab}function ei(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:"0"}function cb(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var db=Object.defineProperty,pb=Object.getOwnPropertyDescriptor,Va=(e,t,i,s)=>{for(var o=s>1?void 0:s?pb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&db(t,i,o),o};const hb=D`
967
+ `}changeDelivery(e){e.target instanceof HTMLSelectElement&&(this.attachmentDelivery=e.target.value==="folder"?"folder":"inline",Uv(this.attachmentDelivery))}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=sn(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&Array.from(e.dataTransfer.items).some(t=>t.kind==="file"&&t.type.startsWith("image/"))&&e.preventDefault()}async handleDrop(e){const t=sn(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;const t=Array.from(e.target.files);e.target.value="",await this.addAttachmentFiles(t)}async addAttachmentFiles(e){this.attachmentError=void 0;const{attachments:t,error:i}=await Nv(e,nb);t.length>0&&(this.attachments=[...this.attachments,...t.map(s=>({id:`attachment-${String(++this.attachmentSeq)}`,...s}))]),i!==void 0&&(this.attachmentError=i)}currentAttachments(){return this.attachments.map(e=>({kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}))}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new nt({parent:this.editorHost,state:Qi.create({doc:this.draft,extensions:[tl(),pl(),il(),sl.of(" "),ol(dl,{fallback:!0}),nt.lineWrapping,nt.contentAttributes.of(e=>cb(e.state.sliceDoc(0,e.state.selection.main.head))),rl("给 pi 发送消息... 使用 / 输入命令,@ 输入已跟踪文件,@ 空格显示所有文件"),this.editableCompartment.of(nt.editable.of(!this.disabled)),this.readOnlyCompartment.of(Qi.readOnly.of(this.disabled)),nt.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),nl.of([{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Enter",run:()=>this.handleEditorEnter()},{key:"Shift-Enter",run:e=>hl(e)||cl(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>Eo.shift?.(e)??!1},{key:"Backspace",run:e=>ul(e)},...al,...ll])]})}))}syncEditorDoc(){const e=this.editor;if(!e)return;const t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:Do.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(nt.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(Qi.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=ei(this.machineId,this.sessionId);t!==void 0&&wi(t,this.draft),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""&&this.cwd!==void 0&&this.cwd!==""){const i=await z.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(ob);if(t!==this.requestVersion)return;this.completions=i.filter(s=>s.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(s=>({kind:"command",replaceFrom:e.from,replaceTo:e.to,insertText:`/${s.name}`,detail:s.source,...s.description===void 0?{}:{description:s.description}}))}else if(e.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const i=await z.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId}).catch(rb);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const o=Gn(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:o,detail:s.kind,...s.path.endsWith("/")&&o.endsWith('"')?{cursorOffset:o.length-1}:{}}})}}currentTrigger(){return Vn(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorEnter(){if(this.completions.length){const e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):Eo.run?.(e)??!1}pick(e){const t=this.editor;if(!t)return;const i=e.kind==="file"&&(e.insertText.endsWith("/")||e.cursorOffset!==void 0)?"":" ",s=e.replaceFrom+(e.cursorOffset??e.insertText.length)+i.length,o=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:o,insert:`${e.insertText}${i}`},selection:Do.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;const t=this.draft.trim(),i=this.attachments;if(t===""&&i.length===0)return;const s=this.canSteer||this.isCompacting?e:void 0,o=i.length>0?this.currentAttachments():void 0,r=this.attachmentDelivery;this.resetComposer(),this.onSend?.(t,s,o,o===void 0?void 0:r)}resetComposer(){this.draft="";const e=ei(this.machineId,this.sessionId);e!==void 0&&ro(e),this.completions=[],this.attachments=[],this.attachmentError=void 0}};_.styles=sb;j([d({type:Boolean})],_.prototype,"disabled",2);j([d()],_.prototype,"sessionId",2);j([d()],_.prototype,"cwd",2);j([d()],_.prototype,"machineId",2);j([d({type:Boolean})],_.prototype,"canSteer",2);j([d({type:Boolean})],_.prototype,"isCompacting",2);j([d({type:Boolean})],_.prototype,"canStop",2);j([d({attribute:!1})],_.prototype,"status",2);j([d({type:Boolean})],_.prototype,"sending",2);j([d({attribute:!1})],_.prototype,"onSend",2);j([d({attribute:!1})],_.prototype,"onStop",2);j([d({attribute:!1})],_.prototype,"onSelectModel",2);j([d({attribute:!1})],_.prototype,"onSelectThinking",2);j([d({attribute:!1})],_.prototype,"availableThinkingLevels",2);j([B(".markdown-editor")],_.prototype,"editorHost",2);j([B(".attachment-input")],_.prototype,"attachmentInput",2);j([k()],_.prototype,"draft",2);j([k()],_.prototype,"completions",2);j([k()],_.prototype,"selectedIndex",2);j([k()],_.prototype,"attachments",2);j([k()],_.prototype,"attachmentDelivery",2);j([k()],_.prototype,"attachmentError",2);_=j([W("prompt-editor")],_);function ei(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return Fn(e,t)}function ob(){return[]}function rb(){return[]}function sn(e){return e===null?[]:Array.from(e.files).filter(t=>t.type.startsWith("image/"))}function nb(e){return new Promise((t,i)=>{const s=new FileReader;s.onerror=()=>{i(s.error??new Error("读取文件失败"))},s.onload=()=>{const o=s.result;if(typeof o!="string"){i(new Error("文件读取结果异常"));return}const r=o.indexOf(",");t(r===-1?o:o.slice(r+1))},s.readAsDataURL(e)})}const ab={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},lb={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function cb(e){return no(e).kind==="normal"?ab:lb}function ti(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:"0"}function db(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var pb=Object.defineProperty,hb=Object.getOwnPropertyDescriptor,Ga=(e,t,i,s)=>{for(var o=s>1?void 0:s?hb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&pb(t,i,o),o};const ub=D`
968
968
  :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
969
969
  .bar { display: flex; justify-content: flex-end; gap: 12px; align-items: center; min-width: 0; padding: 7px 12px; border-top: 1px solid var(--pi-border); background: var(--pi-bg); white-space: nowrap; overflow: hidden; }
970
970
  span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
@@ -974,15 +974,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
974
974
  .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
975
975
  .muted { color: var(--pi-dim); }
976
976
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
977
- `;let Ti=class extends C{render(){const e=this.status;if(e===void 0)return l`<div class="bar muted">暂无会话状态</div>`;const t=e.contextUsage,i=t?t.percent==null?`上下文 ${ei(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${ei(t.contextWindow)}`:"上下文未知",s=e.tokens;return l`
977
+ `;let Ai=class extends C{render(){const e=this.status;if(e===void 0)return l`<div class="bar muted">暂无会话状态</div>`;const t=e.contextUsage,i=t?t.percent==null?`上下文 ${ti(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${ti(t.contextWindow)}`:"上下文未知",s=e.tokens;return l`
978
978
  <div class="bar">
979
- <span>↑${ei(s.input)}</span>
980
- <span>↓${ei(s.output)}</span>
979
+ <span>↑${ti(s.input)}</span>
980
+ <span>↓${ti(s.output)}</span>
981
981
  <span class="context">${i}</span>
982
- <span>${cb(e.cost)}</span>
982
+ <span>${db(e.cost)}</span>
983
983
  ${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} 条排队</span>`:null}
984
984
  </div>
985
- `}};Ti.styles=hb;Va([d({attribute:!1})],Ti.prototype,"status",2);Ti=Va([W("status-bar")],Ti);const Ga=D`
985
+ `}};Ai.styles=ub;Ga([d({attribute:!1})],Ai.prototype,"status",2);Ai=Ga([W("status-bar")],Ai);const Ja=D`
986
986
  :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
987
987
  .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
988
988
  section { width: min(720px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -996,7 +996,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
996
996
  .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
997
997
  small { display: block; margin-top: 4px; color: var(--pi-muted); }
998
998
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
999
- `;var ub=Object.defineProperty,fb=Object.getOwnPropertyDescriptor,Fe=(e,t,i,s)=>{for(var o=s>1?void 0:s?fb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&ub(t,i,o),o};let Re=class extends C{constructor(){super(...arguments),this.title="选择",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
999
+ `;var fb=Object.defineProperty,gb=Object.getOwnPropertyDescriptor,Fe=(e,t,i,s)=>{for(var o=s>1?void 0:s?gb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&fb(t,i,o),o};let Re=class extends C{constructor(){super(...arguments),this.title="选择",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
1000
1000
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1001
1001
  <section @mousedown=${t=>{t.stopPropagation()}}>
1002
1002
  <header>
@@ -1006,7 +1006,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1006
1006
  ${this.searchable?l`<input placeholder="搜索" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
1007
1007
  <div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
1008
1008
  ${e.map((t,i)=>l`
1009
- <button class=${i===this.selectedIndex?"selected":""} ${Co(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1009
+ <button class=${i===this.selectedIndex?"selected":""} ${To(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1010
1010
  <span>${t.label}</span>
1011
1011
  ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1012
1012
  </button>
@@ -1015,7 +1015,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1015
1015
  </div>
1016
1016
  </section>
1017
1017
  </div>
1018
- `}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const e=this.filteredOptions().findIndex(t=>t.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){const e=this.query.trim().toLowerCase();return e===""?this.options:this.options.filter(t=>`${t.label} ${t.description??""} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredOptions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i&&this.onPick?.(i.value)}}};Re.styles=Ga;Fe([d()],Re.prototype,"title",2);Fe([d({type:Boolean})],Re.prototype,"searchable",2);Fe([d({attribute:!1})],Re.prototype,"options",2);Fe([d({attribute:!1})],Re.prototype,"selectedValue",2);Fe([d({attribute:!1})],Re.prototype,"onPick",2);Fe([d({attribute:!1})],Re.prototype,"onCancel",2);Fe([k()],Re.prototype,"selectedIndex",2);Fe([k()],Re.prototype,"query",2);Re=Fe([W("command-picker")],Re);var gb=Object.defineProperty,mb=Object.getOwnPropertyDescriptor,it=(e,t,i,s)=>{for(var o=s>1?void 0:s?mb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&gb(t,i,o),o};const vb=D`
1018
+ `}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const e=this.filteredOptions().findIndex(t=>t.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){const e=this.query.trim().toLowerCase();return e===""?this.options:this.options.filter(t=>`${t.label} ${t.description??""} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredOptions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i&&this.onPick?.(i.value)}}};Re.styles=Ja;Fe([d()],Re.prototype,"title",2);Fe([d({type:Boolean})],Re.prototype,"searchable",2);Fe([d({attribute:!1})],Re.prototype,"options",2);Fe([d({attribute:!1})],Re.prototype,"selectedValue",2);Fe([d({attribute:!1})],Re.prototype,"onPick",2);Fe([d({attribute:!1})],Re.prototype,"onCancel",2);Fe([k()],Re.prototype,"selectedIndex",2);Fe([k()],Re.prototype,"query",2);Re=Fe([W("command-picker")],Re);var mb=Object.defineProperty,vb=Object.getOwnPropertyDescriptor,st=(e,t,i,s)=>{for(var o=s>1?void 0:s?vb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&mb(t,i,o),o};const bb=D`
1019
1019
  :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1020
1020
  .backdrop { --palette-top: min(12dvh, 90px); --palette-bottom: max(20px, env(safe-area-inset-bottom)); display: grid; align-items: start; justify-items: center; width: 100%; height: 100dvh; background: var(--pi-overlay); padding: var(--palette-top) 20px var(--palette-bottom); box-sizing: border-box; overflow: hidden; }
1021
1021
  section { width: min(720px, 100%); max-height: min(640px, calc(100dvh - var(--palette-top) - var(--palette-bottom))); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -1046,19 +1046,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1046
1046
  </header>
1047
1047
  <div class="options">
1048
1048
  ${e.length===0?l`<div class="empty">未找到操作。</div>`:e.map((t,i)=>l`
1049
- <button class=${i===this.selectedIndex?"selected":""} ${Co(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1049
+ <button class=${i===this.selectedIndex?"selected":""} ${To(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1050
1050
  <span class="main">
1051
1051
  <strong>${t.title}</strong>
1052
1052
  ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1053
1053
  </span>
1054
- ${t.shortcut!==void 0?l`<kbd>${ai(t.shortcut)}</kbd>`:null}
1054
+ ${t.shortcut!==void 0?l`<kbd>${li(t.shortcut)}</kbd>`:null}
1055
1055
  ${t.group!==void 0&&t.group!==""?l`<small class="group">${t.group}</small>`:null}
1056
1056
  </button>
1057
1057
  `)}
1058
1058
  </div>
1059
1059
  </section>
1060
1060
  </div>
1061
- `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){const e=this.queryText.trim().toLowerCase();return this.actions.filter(t=>t.enabled!==!1).filter(t=>e===""?!0:[t.title,t.description??"",t.group??"",t.shortcut??""].join(" ").toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){this.onRun?.(e)}};Le.styles=vb;it([d({attribute:!1})],Le.prototype,"actions",2);it([d({attribute:!1})],Le.prototype,"onRun",2);it([d({attribute:!1})],Le.prototype,"onCancel",2);it([B("input")],Le.prototype,"input",2);it([k()],Le.prototype,"queryText",2);it([k()],Le.prototype,"selectedIndex",2);Le=it([W("action-palette")],Le);var bb=Object.defineProperty,wb=Object.getOwnPropertyDescriptor,we=(e,t,i,s)=>{for(var o=s>1?void 0:s?wb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&bb(t,i,o),o};let ie=class extends C{render(){const e=this.state;return e===void 0?null:l`
1061
+ `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){const e=this.queryText.trim().toLowerCase();return this.actions.filter(t=>t.enabled!==!1).filter(t=>e===""?!0:[t.title,t.description??"",t.group??"",t.shortcut??""].join(" ").toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){this.onRun?.(e)}};Le.styles=bb;st([d({attribute:!1})],Le.prototype,"actions",2);st([d({attribute:!1})],Le.prototype,"onRun",2);st([d({attribute:!1})],Le.prototype,"onCancel",2);st([B("input")],Le.prototype,"input",2);st([k()],Le.prototype,"queryText",2);st([k()],Le.prototype,"selectedIndex",2);Le=st([W("action-palette")],Le);var wb=Object.defineProperty,yb=Object.getOwnPropertyDescriptor,we=(e,t,i,s)=>{for(var o=s>1?void 0:s?yb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&wb(t,i,o),o};let ie=class extends C{render(){const e=this.state;return e===void 0?null:l`
1062
1062
  <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
1063
1063
  <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1064
1064
  <header>
@@ -1081,11 +1081,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1081
1081
  <div class="actions"><button @click=${()=>{this.cancel()}}>取消</button><button class="primary" ?disabled=${e.saving===!0} @click=${()=>{this.onSaveApiKey?.()}}>${e.saving===!0?"正在保存…":"保存 API key"}</button></div>
1082
1082
  </div>
1083
1083
  `;case"oauth":return this.renderOAuth(e);case"logout":return l`<div class="options">${e.providers.length===0?l`<div class="empty">没有已保存的凭据。环境变量和 models.json 设置不会变化。</div>`:e.providers.map(t=>l`
1084
- <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${sn(t.authType)}</small></button>
1084
+ <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${on(t.authType)}</small></button>
1085
1085
  `)}</div>`}}renderProviderButton(e){return l`
1086
1086
  <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
1087
- <span>${e.name}${e.status.source!==void 0?l` <em>${Sb(e)}</em>`:null}</span>
1088
- <small>${e.id} · ${sn(e.authType)}</small>
1087
+ <span>${e.name}${e.status.source!==void 0?l` <em>${xb(e)}</em>`:null}</span>
1088
+ <small>${e.id} · ${on(e.authType)}</small>
1089
1089
  </button>
1090
1090
  `}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
1091
1091
  <div class="form">
@@ -1105,10 +1105,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1105
1105
  <div class="inline-options">${s.options.map(o=>l`<button @click=${()=>{this.onOAuthRespond?.(o.value)}}>${o.label}</button>`)}</div>
1106
1106
  `:null}
1107
1107
  ${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
1108
- ${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??xb(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
1108
+ ${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??kb(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
1109
1109
  ${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button></div>`:null}
1110
1110
  </div>
1111
- `}focusInputIfNeeded(){const e=yb(this.state);if(e===void 0){this.lastFocusedInputKey=void 0;return}e!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=e,this.input?.focus())}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.cancel();return}if(e.key!=="Enter")return;const t=this.state;t?.step==="apiKey"?(e.preventDefault(),this.onSaveApiKey?.()):t?.step==="oauth"&&t.flow.prompt!==void 0&&(e.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step==="oauth"?this.onOAuthCancel?.():this.onCancel?.()}};ie.styles=[Ga,D`
1111
+ `}focusInputIfNeeded(){const e=Sb(this.state);if(e===void 0){this.lastFocusedInputKey=void 0;return}e!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=e,this.input?.focus())}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.cancel();return}if(e.key!=="Enter")return;const t=this.state;t?.step==="apiKey"?(e.preventDefault(),this.onSaveApiKey?.()):t?.step==="oauth"&&t.flow.prompt!==void 0&&(e.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step==="oauth"?this.onOAuthCancel?.():this.onCancel?.()}};ie.styles=[Ja,D`
1112
1112
  .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
1113
1113
  .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
1114
1114
  .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
@@ -1123,7 +1123,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1123
1123
  .progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
1124
1124
  .inline-options { display: grid; gap: 8px; }
1125
1125
  em { color: var(--pi-success); font-style: normal; font-size: 12px; }
1126
- `];we([d({attribute:!1})],ie.prototype,"state",2);we([d({attribute:!1})],ie.prototype,"onChooseMethod",2);we([d({attribute:!1})],ie.prototype,"onSelectProvider",2);we([d({attribute:!1})],ie.prototype,"onApiKeyInput",2);we([d({attribute:!1})],ie.prototype,"onSaveApiKey",2);we([d({attribute:!1})],ie.prototype,"onLogoutProvider",2);we([d({attribute:!1})],ie.prototype,"onOAuthInput",2);we([d({attribute:!1})],ie.prototype,"onOAuthRespond",2);we([d({attribute:!1})],ie.prototype,"onOAuthCancel",2);we([d({attribute:!1})],ie.prototype,"onCancel",2);we([B("input")],ie.prototype,"input",2);ie=we([W("auth-dialog")],ie);function sn(e){return e==="oauth"?"订阅":"API key"}function yb(e){if(e?.step==="apiKey")return`api-key:${e.provider.authType}:${e.provider.id}`;if(e?.step==="oauth"&&e.flow.prompt!==void 0)return`oauth:${e.flow.flowId}:${e.flow.prompt.requestId}`}function Sb(e){if(e.status.source===void 0)return"";switch(e.status.source){case"stored":return"✓ 已配置";case"environment":return`✓ 环境变量${e.status.label===void 0?"":`: ${e.status.label}`}`;case"runtime":return"✓ 运行时";case"fallback":return"✓ 自定义 key";case"models_json_key":return"✓ models.json key";case"models_json_command":return"✓ models.json command";default:return""}}function xb(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var kb=Object.defineProperty,$b=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var o=s>1?void 0:s?$b(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&kb(t,i,o),o};let ge=class extends C{constructor(){super(...arguments),this.machineId="local",this.path="",this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}firstUpdated(){this.pathInput?.focus()}async loadSuggestions(){const e=++this.requestId;this.loading=!0;try{const t=await z.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==""&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="Enter")e.preventDefault(),this.submit();else if(e.key==="ArrowDown")e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key==="ArrowUp")e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key==="Tab"){const t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return l`
1126
+ `];we([d({attribute:!1})],ie.prototype,"state",2);we([d({attribute:!1})],ie.prototype,"onChooseMethod",2);we([d({attribute:!1})],ie.prototype,"onSelectProvider",2);we([d({attribute:!1})],ie.prototype,"onApiKeyInput",2);we([d({attribute:!1})],ie.prototype,"onSaveApiKey",2);we([d({attribute:!1})],ie.prototype,"onLogoutProvider",2);we([d({attribute:!1})],ie.prototype,"onOAuthInput",2);we([d({attribute:!1})],ie.prototype,"onOAuthRespond",2);we([d({attribute:!1})],ie.prototype,"onOAuthCancel",2);we([d({attribute:!1})],ie.prototype,"onCancel",2);we([B("input")],ie.prototype,"input",2);ie=we([W("auth-dialog")],ie);function on(e){return e==="oauth"?"订阅":"API key"}function Sb(e){if(e?.step==="apiKey")return`api-key:${e.provider.authType}:${e.provider.id}`;if(e?.step==="oauth"&&e.flow.prompt!==void 0)return`oauth:${e.flow.flowId}:${e.flow.prompt.requestId}`}function xb(e){if(e.status.source===void 0)return"";switch(e.status.source){case"stored":return"✓ 已配置";case"environment":return`✓ 环境变量${e.status.label===void 0?"":`: ${e.status.label}`}`;case"runtime":return"✓ 运行时";case"fallback":return"✓ 自定义 key";case"models_json_key":return"✓ models.json key";case"models_json_command":return"✓ models.json command";default:return""}}function kb(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var $b=Object.defineProperty,Pb=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var o=s>1?void 0:s?Pb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&$b(t,i,o),o};let ge=class extends C{constructor(){super(...arguments),this.machineId="local",this.path="",this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}firstUpdated(){this.pathInput?.focus()}async loadSuggestions(){const e=++this.requestId;this.loading=!0;try{const t=await z.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==""&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="Enter")e.preventDefault(),this.submit();else if(e.key==="ArrowDown")e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key==="ArrowUp")e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key==="Tab"){const t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return l`
1127
1127
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1128
1128
  <section @click=${e=>{e.stopPropagation()}}>
1129
1129
  <header>
@@ -1173,7 +1173,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1173
1173
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1174
1174
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1175
1175
  button:disabled { opacity: .5; cursor: not-allowed; }
1176
- `;De([d({attribute:!1})],ge.prototype,"onSubmit",2);De([d({attribute:!1})],ge.prototype,"onCancel",2);De([d()],ge.prototype,"machineId",2);De([k()],ge.prototype,"path",2);De([k()],ge.prototype,"createMissing",2);De([k()],ge.prototype,"suggestions",2);De([k()],ge.prototype,"selected",2);De([k()],ge.prototype,"loading",2);De([B("input")],ge.prototype,"pathInput",2);ge=De([W("project-dialog")],ge);var Pb=Object.defineProperty,Rb=Object.getOwnPropertyDescriptor,We=(e,t,i,s)=>{for(var o=s>1?void 0:s?Rb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Pb(t,i,o),o};let me=class extends C{constructor(){super(...arguments),this.error="",this.url="",this.name="",this.token="",this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=""}firstUpdated(){this.urlInput?.focus()}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;const t=e.target.value,i=Ib(t);(!this.nameEdited||this.name.trim()===""||this.name===this.previousSuggestedName)&&(this.name=i),this.previousSuggestedName=i,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.onCancel?.();return}e.key==="Enter"&&e.target instanceof HTMLInputElement&&e.target.name==="baseUrl"&&ms(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){const e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){const e=this.url.trim(),t=this.name.trim();if(e===""||t===""||ms(e)!==void 0)return;const i=this.token.trim();return{name:t,baseUrl:e,...i===""?{}:{token:i}}}render(){const e=this.url.trim()!=="",t=e?ms(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1176
+ `;De([d({attribute:!1})],ge.prototype,"onSubmit",2);De([d({attribute:!1})],ge.prototype,"onCancel",2);De([d()],ge.prototype,"machineId",2);De([k()],ge.prototype,"path",2);De([k()],ge.prototype,"createMissing",2);De([k()],ge.prototype,"suggestions",2);De([k()],ge.prototype,"selected",2);De([k()],ge.prototype,"loading",2);De([B("input")],ge.prototype,"pathInput",2);ge=De([W("project-dialog")],ge);var Rb=Object.defineProperty,Ib=Object.getOwnPropertyDescriptor,We=(e,t,i,s)=>{for(var o=s>1?void 0:s?Ib(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Rb(t,i,o),o};let me=class extends C{constructor(){super(...arguments),this.error="",this.url="",this.name="",this.token="",this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=""}firstUpdated(){this.urlInput?.focus()}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;const t=e.target.value,i=Cb(t);(!this.nameEdited||this.name.trim()===""||this.name===this.previousSuggestedName)&&(this.name=i),this.previousSuggestedName=i,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.onCancel?.();return}e.key==="Enter"&&e.target instanceof HTMLInputElement&&e.target.name==="baseUrl"&&vs(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){const e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){const e=this.url.trim(),t=this.name.trim();if(e===""||t===""||vs(e)!==void 0)return;const i=this.token.trim();return{name:t,baseUrl:e,...i===""?{}:{token:i}}}render(){const e=this.url.trim()!=="",t=e?vs(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1177
1177
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1178
1178
  <section @click=${s=>{s.stopPropagation()}}>
1179
1179
  <form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
@@ -1228,8 +1228,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1228
1228
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1229
1229
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1230
1230
  button:disabled { opacity: .5; cursor: not-allowed; }
1231
- `;We([d({attribute:!1})],me.prototype,"onSubmit",2);We([d({attribute:!1})],me.prototype,"onCancel",2);We([d()],me.prototype,"error",2);We([k()],me.prototype,"url",2);We([k()],me.prototype,"name",2);We([k()],me.prototype,"token",2);We([k()],me.prototype,"submitting",2);We([B("input[name='baseUrl']")],me.prototype,"urlInput",2);We([B("input[name='name']")],me.prototype,"nameInput",2);me=We([W("machine-dialog")],me);function Ib(e){const t=e.trim();if(t==="")return"";const i=on(t)??on(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):Cb(t)}function ms(e){const t=e.trim();if(t==="")return"必须填写远程 PI WEB URL。";let i;try{i=new URL(t)}catch{return"请输入包含 http:// 或 https:// 的有效 URL。"}if(i.protocol!=="http:"&&i.protocol!=="https:")return"请使用 http:// 或 https:// URL。";if(i.username!==""||i.password!=="")return"机器 URL 中不要包含凭据。";if(i.search!==""||i.hash!=="")return"不要包含查询字符串或片段。"}function on(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function Cb(e){const t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,""),s=t.slice(t.lastIndexOf("@")+1).split(/[/?#]/u)[0]??"";return s.startsWith("[")&&s.includes("]")?s.slice(1,s.indexOf("]")):s.replace(/:\d+$/u,"")}function Tb(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function Ab(e){return{host:e.host??"",port:e.port===void 0?"":String(e.port),allowedHostsMode:e.allowedHosts===!0?"all":"list",allowedHostsText:Array.isArray(e.allowedHosts)?e.allowedHosts.join(`
1232
- `):""}}function Mb(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins},...t.spawnSessions===void 0?{}:{spawnSessions:t.spawnSessions},...t.subsessions===void 0?{}:{subsessions:t.subsessions}},s=e.host.trim(),o=e.port.trim();if(s!==""&&(i.host=s),o!==""){const r=Number(o);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("端口必须是 1 到 65535 之间的整数。");i.port=r}return i.allowedHosts=e.allowedHostsMode==="all"?!0:Eb(e.allowedHostsText),i}function Eb(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}function Ki(e,t){return e!==""?l`<div class="message error-message">${e}</div>`:t!==""?l`<div class="message success-message">${t}</div>`:null}const Vi=D`
1231
+ `;We([d({attribute:!1})],me.prototype,"onSubmit",2);We([d({attribute:!1})],me.prototype,"onCancel",2);We([d()],me.prototype,"error",2);We([k()],me.prototype,"url",2);We([k()],me.prototype,"name",2);We([k()],me.prototype,"token",2);We([k()],me.prototype,"submitting",2);We([B("input[name='baseUrl']")],me.prototype,"urlInput",2);We([B("input[name='name']")],me.prototype,"nameInput",2);me=We([W("machine-dialog")],me);function Cb(e){const t=e.trim();if(t==="")return"";const i=rn(t)??rn(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):Tb(t)}function vs(e){const t=e.trim();if(t==="")return"必须填写远程 PI WEB URL。";let i;try{i=new URL(t)}catch{return"请输入包含 http:// 或 https:// 的有效 URL。"}if(i.protocol!=="http:"&&i.protocol!=="https:")return"请使用 http:// 或 https:// URL。";if(i.username!==""||i.password!=="")return"机器 URL 中不要包含凭据。";if(i.search!==""||i.hash!=="")return"不要包含查询字符串或片段。"}function rn(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function Tb(e){const t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,""),s=t.slice(t.lastIndexOf("@")+1).split(/[/?#]/u)[0]??"";return s.startsWith("[")&&s.includes("]")?s.slice(1,s.indexOf("]")):s.replace(/:\d+$/u,"")}function Ab(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function Mb(e){return{host:e.host??"",port:e.port===void 0?"":String(e.port),allowedHostsMode:e.allowedHosts===!0?"all":"list",allowedHostsText:Array.isArray(e.allowedHosts)?e.allowedHosts.join(`
1232
+ `):""}}function Eb(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins},...t.spawnSessions===void 0?{}:{spawnSessions:t.spawnSessions},...t.subsessions===void 0?{}:{subsessions:t.subsessions}},s=e.host.trim(),o=e.port.trim();if(s!==""&&(i.host=s),o!==""){const r=Number(o);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("端口必须是 1 到 65535 之间的整数。");i.port=r}return i.allowedHosts=e.allowedHostsMode==="all"?!0:Db(e.allowedHostsText),i}function Db(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}function Vi(e,t){return e!==""?l`<div class="message error-message">${e}</div>`:t!==""?l`<div class="message success-message">${t}</div>`:null}const Gi=D`
1233
1233
  :host { display: block; }
1234
1234
  .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1235
1235
  .section-heading > div { display: grid; gap: 6px; min-width: 0; }
@@ -1265,7 +1265,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1265
1265
  .section-heading .secondary { justify-self: start; }
1266
1266
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1267
1267
  }
1268
- `;var Db=Object.defineProperty,Wb=Object.getOwnPropertyDescriptor,Oe=(e,t,i,s)=>{for(var o=s>1?void 0:s?Wb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Db(t,i,o),o};let ve=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=Tb(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=Ab(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
1268
+ `;var Wb=Object.defineProperty,Ob=Object.getOwnPropertyDescriptor,Oe=(e,t,i,s)=>{for(var o=s>1?void 0:s?Ob(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Wb(t,i,o),o};let ve=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=Ab(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=Mb(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
1269
1269
  <div class="section-heading">
1270
1270
  <div>
1271
1271
  <h2>通用配置</h2>
@@ -1286,7 +1286,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1286
1286
  <span>Host</span>
1287
1287
  ${this.renderOverrideBadge("host")}
1288
1288
  </span>
1289
- <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:rn(t)})}}>
1289
+ <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:nn(t)})}}>
1290
1290
  <small>Web 服务器应绑定的地址。留空则使用 PI WEB 默认值。</small>
1291
1291
  </label>
1292
1292
 
@@ -1295,7 +1295,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1295
1295
  <span>Port</span>
1296
1296
  ${this.renderOverrideBadge("port")}
1297
1297
  </span>
1298
- <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:rn(t)})}}>
1298
+ <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:nn(t)})}}>
1299
1299
  <small>TCP 端口,范围 1 到 65535。留空则使用 PI WEB 默认值。</small>
1300
1300
  </label>
1301
1301
 
@@ -1304,11 +1304,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1304
1304
  <span>允许的 hosts</span>
1305
1305
  ${this.renderOverrideBadge("allowedHosts")}
1306
1306
  </span>
1307
- <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:_b(t)==="all"?"all":"list"})}}>
1307
+ <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:Lb(t)==="all"?"all":"list"})}}>
1308
1308
  <option value="list">仅允许列出的 hosts</option>
1309
1309
  <option value="all">允许所有 host</option>
1310
1310
  </select>
1311
- <textarea .value=${this.draft.allowedHostsText} ?disabled=${this.draft.allowedHostsMode==="all"} rows="4" placeholder="example.local&#10;192.168.1.20" spellcheck="false" @input=${t=>{this.updateDraft({allowedHostsText:Lb(t)})}}></textarea>
1311
+ <textarea .value=${this.draft.allowedHostsText} ?disabled=${this.draft.allowedHostsMode==="all"} rows="4" placeholder="example.local&#10;192.168.1.20" spellcheck="false" @input=${t=>{this.updateDraft({allowedHostsText:jb(t)})}}></textarea>
1312
1312
  <small>每行输入一个 host,或选择“允许所有 host”写入 <code>true</code>。</small>
1313
1313
  </div>
1314
1314
 
@@ -1319,23 +1319,23 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1319
1319
  </footer>
1320
1320
  </form>
1321
1321
  `}
1322
- `}renderMessages(){const e=this.localError||this.error;return Ki(e,this.savedMessage)}renderOverrideBadge(e){return this.configResponse?.envOverrides[e]!==!0?null:l`<span class="override-badge">环境变量覆盖</span>`}renderEffectiveConfig(){const e=this.configResponse?.effectiveConfig??{};return l`
1322
+ `}renderMessages(){const e=this.localError||this.error;return Vi(e,this.savedMessage)}renderOverrideBadge(e){return this.configResponse?.envOverrides[e]!==!0?null:l`<span class="override-badge">环境变量覆盖</span>`}renderEffectiveConfig(){const e=this.configResponse?.effectiveConfig??{};return l`
1323
1323
  <section class="effective-card" aria-label="最终生效配置摘要">
1324
1324
  <h3>环境变量覆盖后的生效配置</h3>
1325
1325
  <dl>
1326
1326
  <div><dt>Host</dt><dd>${e.host??l`<span class="muted">默认 127.0.0.1</span>`}</dd></div>
1327
1327
  <div><dt>端口</dt><dd>${e.port??l`<span class="muted">默认 8504</span>`}</dd></div>
1328
- <div><dt>允许的 hosts</dt><dd>${Ob(e.allowedHosts)}</dd></div>
1328
+ <div><dt>允许的 hosts</dt><dd>${_b(e.allowedHosts)}</dd></div>
1329
1329
  </dl>
1330
1330
  </section>
1331
- `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(Mb(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=jb(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};ve.styles=[Vi,D`
1331
+ `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(Eb(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=Fb(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};ve.styles=[Gi,D`
1332
1332
  .config-form { display: grid; gap: 14px; }
1333
1333
  input, select, textarea { box-sizing: border-box; width: 100%; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px 10px; outline: none; }
1334
1334
  input:focus, select:focus, textarea:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
1335
1335
  textarea { resize: vertical; min-height: 94px; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1336
1336
  textarea:disabled { opacity: .55; }
1337
1337
  .form-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 2px; }
1338
- `];Oe([d({attribute:!1})],ve.prototype,"configResponse",2);Oe([d({type:Boolean})],ve.prototype,"loading",2);Oe([d({type:Boolean})],ve.prototype,"saving",2);Oe([d()],ve.prototype,"error",2);Oe([d()],ve.prototype,"savedMessage",2);Oe([d({attribute:!1})],ve.prototype,"onReload",2);Oe([d({attribute:!1})],ve.prototype,"onSave",2);Oe([k()],ve.prototype,"draft",2);Oe([k()],ve.prototype,"localError",2);ve=Oe([W("settings-general-panel")],ve);function Ob(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?l`<span class="muted">未列出</span>`:e.join(", "):l`<span class="muted">未设置</span>`}function rn(e){return e.target instanceof HTMLInputElement?e.target.value:""}function _b(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function Lb(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function jb(e){return e instanceof Error?e.message:String(e)}var Fb=Object.defineProperty,Nb=Object.getOwnPropertyDescriptor,He=(e,t,i,s)=>{for(var o=s>1?void 0:s?Nb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Fb(t,i,o),o};let Ee=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,i=e?.effectiveConfig.spawnSessions!==!1,s=e?.envOverrides.subsessions===!0,o=e?.effectiveConfig.subsessions===!0&&i;return l`
1338
+ `];Oe([d({attribute:!1})],ve.prototype,"configResponse",2);Oe([d({type:Boolean})],ve.prototype,"loading",2);Oe([d({type:Boolean})],ve.prototype,"saving",2);Oe([d()],ve.prototype,"error",2);Oe([d()],ve.prototype,"savedMessage",2);Oe([d({attribute:!1})],ve.prototype,"onReload",2);Oe([d({attribute:!1})],ve.prototype,"onSave",2);Oe([k()],ve.prototype,"draft",2);Oe([k()],ve.prototype,"localError",2);ve=Oe([W("settings-general-panel")],ve);function _b(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?l`<span class="muted">未列出</span>`:e.join(", "):l`<span class="muted">未设置</span>`}function nn(e){return e.target instanceof HTMLInputElement?e.target.value:""}function Lb(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function jb(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function Fb(e){return e instanceof Error?e.message:String(e)}var Nb=Object.defineProperty,zb=Object.getOwnPropertyDescriptor,qe=(e,t,i,s)=>{for(var o=s>1?void 0:s?zb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Nb(t,i,o),o};let Ee=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,i=e?.effectiveConfig.spawnSessions!==!1,s=e?.envOverrides.subsessions===!0,o=e?.effectiveConfig.subsessions===!0&&i;return l`
1339
1339
  <div class="section-heading">
1340
1340
  <div>
1341
1341
  <h2>会话守护进程</h2>
@@ -1391,7 +1391,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1391
1391
  </dl>
1392
1392
  </section>
1393
1393
  `}
1394
- `}renderMessages(){return Ki(this.error,this.savedMessage)}async toggleSpawnSessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,spawnSessions:t})}async toggleSubsessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,subsessions:t})}};Ee.styles=[Vi,D`
1394
+ `}renderMessages(){return Vi(this.error,this.savedMessage)}async toggleSpawnSessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,spawnSessions:t})}async toggleSubsessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,subsessions:t})}};Ee.styles=[Gi,D`
1395
1395
  .restart-note { margin-bottom: 14px; border: 1px solid var(--pi-warning-border); border-radius: 10px; background: var(--pi-warning-surface); color: var(--pi-warning); padding: 12px; line-height: 1.45; }
1396
1396
  .field { margin-bottom: 14px; }
1397
1397
  .field small { line-height: 1.45; }
@@ -1399,7 +1399,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1399
1399
  .toggle input { width: 16px; height: 16px; }
1400
1400
  .toggle input:disabled { cursor: not-allowed; }
1401
1401
  .beta-badge { border: 1px solid var(--pi-border); border-radius: 999px; color: var(--pi-muted); background: var(--pi-bg); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: .04em; }
1402
- `];He([d({attribute:!1})],Ee.prototype,"configResponse",2);He([d({type:Boolean})],Ee.prototype,"loading",2);He([d({type:Boolean})],Ee.prototype,"saving",2);He([d()],Ee.prototype,"error",2);He([d()],Ee.prototype,"savedMessage",2);He([d({attribute:!1})],Ee.prototype,"onReload",2);He([d({attribute:!1})],Ee.prototype,"onSave",2);Ee=He([W("settings-sessiond-panel")],Ee);var zb=Object.defineProperty,Bb=Object.getOwnPropertyDescriptor,Ne=(e,t,i,s)=>{for(var o=s>1?void 0:s?Bb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&zb(t,i,o),o};let Ie=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
1402
+ `];qe([d({attribute:!1})],Ee.prototype,"configResponse",2);qe([d({type:Boolean})],Ee.prototype,"loading",2);qe([d({type:Boolean})],Ee.prototype,"saving",2);qe([d()],Ee.prototype,"error",2);qe([d()],Ee.prototype,"savedMessage",2);qe([d({attribute:!1})],Ee.prototype,"onReload",2);qe([d({attribute:!1})],Ee.prototype,"onSave",2);Ee=qe([W("settings-sessiond-panel")],Ee);var Bb=Object.defineProperty,Ub=Object.getOwnPropertyDescriptor,Ne=(e,t,i,s)=>{for(var o=s>1?void 0:s?Ub(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Bb(t,i,o),o};let Ie=class extends C{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
1403
1403
  <div class="section-heading">
1404
1404
  <div>
1405
1405
  <h2>插件</h2>
@@ -1414,7 +1414,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1414
1414
  ${e.map(t=>this.renderPlugin(t))}
1415
1415
  </div>
1416
1416
  `}
1417
- `}renderMessages(){return Ki(this.error,this.savedMessage===""?"":`${this.savedMessage} 重新加载浏览器标签页以应用插件更改。`)}renderPlugin(e){const t=this.configResponse?.config.plugins?.[e.id],i=t?.enabled===!1?"配置已禁用":t?.enabled===!0?"配置已启用":"默认启用";return l`
1417
+ `}renderMessages(){return Vi(this.error,this.savedMessage===""?"":`${this.savedMessage} 重新加载浏览器标签页以应用插件更改。`)}renderPlugin(e){const t=this.configResponse?.config.plugins?.[e.id],i=t?.enabled===!1?"配置已禁用":t?.enabled===!0?"配置已启用":"默认启用";return l`
1418
1418
  <article class=${`plugin-card${e.enabled?"":" disabled"}`}>
1419
1419
  <div class="plugin-main">
1420
1420
  <strong>${e.id}</strong>
@@ -1426,7 +1426,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1426
1426
  <span>${e.enabled?"已启用":"已禁用"}</span>
1427
1427
  </label>
1428
1428
  </article>
1429
- `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};Ie.styles=[Vi,D`
1429
+ `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};Ie.styles=[Gi,D`
1430
1430
  .plugin-note, .plugin-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1431
1431
  .plugin-note { color: var(--pi-muted); }
1432
1432
  .plugin-note { margin-bottom: 14px; }
@@ -1443,7 +1443,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1443
1443
  .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
1444
1444
  .toggle { justify-self: start; }
1445
1445
  }
1446
- `];Ne([d({attribute:!1})],Ie.prototype,"pluginsResponse",2);Ne([d({attribute:!1})],Ie.prototype,"configResponse",2);Ne([d({type:Boolean})],Ie.prototype,"loading",2);Ne([d({type:Boolean})],Ie.prototype,"saving",2);Ne([d()],Ie.prototype,"error",2);Ne([d()],Ie.prototype,"savedMessage",2);Ne([d({attribute:!1})],Ie.prototype,"onReload",2);Ne([d({attribute:!1})],Ie.prototype,"onTogglePlugin",2);Ie=Ne([W("settings-plugins-panel")],Ie);var Ub=Object.defineProperty,Hb=Object.getOwnPropertyDescriptor,ye=(e,t,i,s)=>{for(var o=s>1?void 0:s?Hb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ub(t,i,o),o};const nn={capture:!0};let se=class extends C{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{const t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key==="Escape"){this.stopRecording();return}const i=ta(e);if(i===void 0){this.localError="Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.";return}if(t.tokens.length===0&&!Lt(i)){this.localError="Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.";return}const s=[...t.tokens,i];this.localError="",this.drafts={[t.actionId]:s.join(" ")},this.recording={actionId:t.actionId,tokens:s},this.armRecordingTimer()}}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.drafts={},this.localError="",this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){const e=Gb(this.actions),t=this.shortcutResolutions();return l`
1446
+ `];Ne([d({attribute:!1})],Ie.prototype,"pluginsResponse",2);Ne([d({attribute:!1})],Ie.prototype,"configResponse",2);Ne([d({type:Boolean})],Ie.prototype,"loading",2);Ne([d({type:Boolean})],Ie.prototype,"saving",2);Ne([d()],Ie.prototype,"error",2);Ne([d()],Ie.prototype,"savedMessage",2);Ne([d({attribute:!1})],Ie.prototype,"onReload",2);Ne([d({attribute:!1})],Ie.prototype,"onTogglePlugin",2);Ie=Ne([W("settings-plugins-panel")],Ie);var Hb=Object.defineProperty,qb=Object.getOwnPropertyDescriptor,ye=(e,t,i,s)=>{for(var o=s>1?void 0:s?qb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Hb(t,i,o),o};const an={capture:!0};let se=class extends C{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{const t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key==="Escape"){this.stopRecording();return}const i=ia(e);if(i===void 0){this.localError="Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.";return}if(t.tokens.length===0&&!jt(i)){this.localError="Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.";return}const s=[...t.tokens,i];this.localError="",this.drafts={[t.actionId]:s.join(" ")},this.recording={actionId:t.actionId,tokens:s},this.armRecordingTimer()}}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.drafts={},this.localError="",this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){const e=Jb(this.actions),t=this.shortcutResolutions();return l`
1447
1447
  <div class="section-heading">
1448
1448
  <div>
1449
1449
  <h2>键盘快捷键</h2>
@@ -1467,19 +1467,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1467
1467
  </section>
1468
1468
  `)}
1469
1469
  `}
1470
- `}renderMessages(){const e=this.localError||this.error;return Ki(e,this.savedMessage)}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=Ai(e.id,i),o=Xb(e,i),r=this.shortcutInputText(e),n=r.trim()===""?void 0:os(r),a=n?.ok===!0?n.shortcut:Zb(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&r.trim()!==""?"custom":o,h=this.recordingHint(e.id),g=Vb(t);return l`
1471
- <article class=${qb(t)}>
1470
+ `}renderMessages(){const e=this.localError||this.error;return Vi(e,this.savedMessage)}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=Mi(e.id,i),o=Yb(e,i),r=this.shortcutInputText(e),n=r.trim()===""?void 0:rs(r),a=n?.ok===!0?n.shortcut:Xb(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&r.trim()!==""?"custom":o,h=this.recordingHint(e.id),g=Gb(t);return l`
1471
+ <article class=${Kb(t)}>
1472
1472
  <div class="shortcut-main">
1473
1473
  <strong>${e.title}</strong>
1474
1474
  ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1475
1475
  <small class="shortcut-id">${e.id}</small>
1476
- <small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${ai(e.shortcut)}</kbd>`:"No default shortcut"}</small>
1476
+ <small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${li(e.shortcut)}</kbd>`:"No default shortcut"}</small>
1477
1477
  </div>
1478
1478
  <div class="shortcut-editor">
1479
1479
  <div class="shortcut-status">
1480
- ${a!==void 0&&a!==""?l`<kbd>${ai(a)}</kbd>`:l`<span class="unassigned">${o==="disabled"?"已禁用":"未分配"}</span>`}
1481
- <small class=${u}>${Yb(u)}${p?" · 未保存":""}</small>
1482
- ${g===void 0?null:l`<small class=${Kb(t)}>${g}</small>`}
1480
+ ${a!==void 0&&a!==""?l`<kbd>${li(a)}</kbd>`:l`<span class="unassigned">${o==="disabled"?"已禁用":"未分配"}</span>`}
1481
+ <small class=${u}>${ew(u)}${p?" · 未保存":""}</small>
1482
+ ${g===void 0?null:l`<small class=${Vb(t)}>${g}</small>`}
1483
1483
  </div>
1484
1484
  <label class="shortcut-input-label">
1485
1485
  <span>快捷键</span>
@@ -1492,7 +1492,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1492
1492
  autocapitalize="off"
1493
1493
  spellcheck="false"
1494
1494
  ?disabled=${this.saving}
1495
- @input=${w=>{this.updateDraft(e.id,ew(w))}}
1495
+ @input=${b=>{this.updateDraft(e.id,tw(b))}}
1496
1496
  >
1497
1497
  </label>
1498
1498
  ${h!==""?l`<small class="recording-hint">${h}</small>`:null}
@@ -1504,7 +1504,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1504
1504
  </div>
1505
1505
  </div>
1506
1506
  </article>
1507
- `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=Ai(e.id,this.configResponse?.config.shortcuts);return i===null?"":i??e.shortcut??""}recordingHint(e){const t=this.recording;return t?.actionId!==e?"":t.tokens.length===0?"Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.":`Recording: ${ai(t.tokens.join(" "))}. Press another key to add a sequence, or wait to finish.`}updateDraft(e,t){this.drafts={[e]:t},this.localError=""}async saveShortcut(e){this.stopRecording();const t=this.shortcutInputText(e).trim(),i=os(t);if(!i.ok){this.localError=i.message;return}this.localError="",await this.saveShortcutPreference(e.id,i.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){const i={...this.configResponse?.config??{}},s=i.shortcuts??{},o=t===void 0?Qb(s,e):{...s,[e]:t};Object.keys(o).length===0?delete i.shortcuts:i.shortcuts=o,await this.onSave?.(i)}shortcutResolutions(){return new Map(lo(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){const e={...this.configResponse?.config.shortcuts??{}};for(const[t,i]of Object.entries(this.drafts)){const s=i.trim();if(s==="")continue;const o=os(s);o.ok&&(e[t]=o.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError="",this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(const t of this.renderRoot.querySelectorAll(".shortcut-input"))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},Yn)}stopRecording(){this.clearRecordingTimer(),this.removeRecordingListener(),this.recording=void 0}clearRecordingTimer(){this.recordingTimer!==void 0&&(window.clearTimeout(this.recordingTimer),this.recordingTimer=void 0)}ensureRecordingListener(){this.recordingListenerActive||(window.addEventListener("keydown",this.onRecordKeyDown,nn),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,nn),this.recordingListenerActive=!1)}};se.styles=[Vi,D`
1507
+ `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=Mi(e.id,this.configResponse?.config.shortcuts);return i===null?"":i??e.shortcut??""}recordingHint(e){const t=this.recording;return t?.actionId!==e?"":t.tokens.length===0?"Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.":`Recording: ${li(t.tokens.join(" "))}. Press another key to add a sequence, or wait to finish.`}updateDraft(e,t){this.drafts={[e]:t},this.localError=""}async saveShortcut(e){this.stopRecording();const t=this.shortcutInputText(e).trim(),i=rs(t);if(!i.ok){this.localError=i.message;return}this.localError="",await this.saveShortcutPreference(e.id,i.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){const i={...this.configResponse?.config??{}},s=i.shortcuts??{},o=t===void 0?Zb(s,e):{...s,[e]:t};Object.keys(o).length===0?delete i.shortcuts:i.shortcuts=o,await this.onSave?.(i)}shortcutResolutions(){return new Map(co(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){const e={...this.configResponse?.config.shortcuts??{}};for(const[t,i]of Object.entries(this.drafts)){const s=i.trim();if(s==="")continue;const o=rs(s);o.ok&&(e[t]=o.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError="",this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(const t of this.renderRoot.querySelectorAll(".shortcut-input"))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},ea)}stopRecording(){this.clearRecordingTimer(),this.removeRecordingListener(),this.recording=void 0}clearRecordingTimer(){this.recordingTimer!==void 0&&(window.clearTimeout(this.recordingTimer),this.recordingTimer=void 0)}ensureRecordingListener(){this.recordingListenerActive||(window.addEventListener("keydown",this.onRecordKeyDown,an),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,an),this.recordingListenerActive=!1)}};se.styles=[Gi,D`
1508
1508
  .shortcut-group { margin: 0 0 16px; }
1509
1509
  .shortcut-group h3 { margin: 0 0 8px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
1510
1510
  .shortcut-list { border: 1px solid var(--pi-border); border-radius: 10px; overflow: hidden; }
@@ -1537,7 +1537,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1537
1537
  .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
1538
1538
  .shortcut-status, .shortcut-actions { justify-content: flex-start; }
1539
1539
  }
1540
- `];ye([d({attribute:!1})],se.prototype,"actions",2);ye([d({attribute:!1})],se.prototype,"configResponse",2);ye([d({type:Boolean})],se.prototype,"loading",2);ye([d({type:Boolean})],se.prototype,"saving",2);ye([d()],se.prototype,"error",2);ye([d()],se.prototype,"savedMessage",2);ye([d({attribute:!1})],se.prototype,"onReload",2);ye([d({attribute:!1})],se.prototype,"onSave",2);ye([k()],se.prototype,"drafts",2);ye([k()],se.prototype,"localError",2);ye([k()],se.prototype,"recording",2);se=ye([W("settings-shortcuts-panel")],se);function qb(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function Kb(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function Vb(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??"another action"}`;const t=e.shadows.length;if(t===0)return;const i=e.shadows.slice(0,2).map(o=>o.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function Gb(e){const t=new Map;for(const i of[...e].sort(Jb)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function Jb(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function Ai(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Qb(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Zb(e,t){const i=Ai(e.id,t);if(i!==null)return i??e.shortcut}function Xb(e,t){const i=Ai(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function Yb(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}function ew(e){return e.target instanceof HTMLInputElement?e.target.value:""}var tw=Object.defineProperty,iw=Object.getOwnPropertyDescriptor,Se=(e,t,i,s)=>{for(var o=s>1?void 0:s?iw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&tw(t,i,o),o};let oe=class extends C{constructor(){super(...arguments),this.section="general",this.actions=[],this.loading=!0,this.saving=!1,this.error="",this.savedMessage=""}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}render(){return l`
1540
+ `];ye([d({attribute:!1})],se.prototype,"actions",2);ye([d({attribute:!1})],se.prototype,"configResponse",2);ye([d({type:Boolean})],se.prototype,"loading",2);ye([d({type:Boolean})],se.prototype,"saving",2);ye([d()],se.prototype,"error",2);ye([d()],se.prototype,"savedMessage",2);ye([d({attribute:!1})],se.prototype,"onReload",2);ye([d({attribute:!1})],se.prototype,"onSave",2);ye([k()],se.prototype,"drafts",2);ye([k()],se.prototype,"localError",2);ye([k()],se.prototype,"recording",2);se=ye([W("settings-shortcuts-panel")],se);function Kb(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function Vb(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function Gb(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??"another action"}`;const t=e.shadows.length;if(t===0)return;const i=e.shadows.slice(0,2).map(o=>o.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function Jb(e){const t=new Map;for(const i of[...e].sort(Qb)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function Qb(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function Mi(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Zb(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Xb(e,t){const i=Mi(e.id,t);if(i!==null)return i??e.shortcut}function Yb(e,t){const i=Mi(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function ew(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}function tw(e){return e.target instanceof HTMLInputElement?e.target.value:""}var iw=Object.defineProperty,sw=Object.getOwnPropertyDescriptor,Se=(e,t,i,s)=>{for(var o=s>1?void 0:s?sw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&iw(t,i,o),o};let oe=class extends C{constructor(){super(...arguments),this.section="general",this.actions=[],this.loading=!0,this.saving=!1,this.error="",this.savedMessage=""}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}render(){return l`
1541
1541
  <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
1542
1542
  <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB 设置" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
1543
1543
  <header class="settings-header">
@@ -1607,7 +1607,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1607
1607
  <strong>${t}</strong>
1608
1608
  <small>${i}</small>
1609
1609
  </button>
1610
- `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([fi.config(),Rs.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`加载设置失败:${vs(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},o=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...o,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await fi.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.config),this.showSavedMessage()}catch(t){this.error=`保存配置失败:${vs(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await Rs.plugins()}catch(e){this.error=`刷新插件失败:${vs(e)}`}}showSavedMessage(){this.savedMessage="配置已保存。",this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage==="配置已保存。"&&(this.savedMessage=""),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};oe.styles=D`
1610
+ `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([gi.config(),Is.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`加载设置失败:${bs(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},o=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...o,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await gi.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.config),this.showSavedMessage()}catch(t){this.error=`保存配置失败:${bs(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await Is.plugins()}catch(e){this.error=`刷新插件失败:${bs(e)}`}}showSavedMessage(){this.savedMessage="配置已保存。",this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage==="配置已保存。"&&(this.savedMessage=""),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};oe.styles=D`
1611
1611
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1612
1612
  .backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
1613
1613
  .settings-shell { width: min(980px, 100%); max-height: min(760px, 100%); min-height: min(620px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr); border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -1634,7 +1634,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1634
1634
  .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
1635
1635
  .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
1636
1636
  }
1637
- `;Se([d({attribute:!1})],oe.prototype,"section",2);Se([d({attribute:!1})],oe.prototype,"actions",2);Se([d({attribute:!1})],oe.prototype,"onNavigate",2);Se([d({attribute:!1})],oe.prototype,"onClose",2);Se([d({attribute:!1})],oe.prototype,"onConfigSaved",2);Se([k()],oe.prototype,"configResponse",2);Se([k()],oe.prototype,"pluginsResponse",2);Se([k()],oe.prototype,"loading",2);Se([k()],oe.prototype,"saving",2);Se([k()],oe.prototype,"error",2);Se([k()],oe.prototype,"savedMessage",2);oe=Se([W("settings-dialog")],oe);function vs(e){return e instanceof Error?e.message:String(e)}var sw=Object.defineProperty,ow=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var o=s>1?void 0:s?ow(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&sw(t,i,o),o};const rw=D`
1637
+ `;Se([d({attribute:!1})],oe.prototype,"section",2);Se([d({attribute:!1})],oe.prototype,"actions",2);Se([d({attribute:!1})],oe.prototype,"onNavigate",2);Se([d({attribute:!1})],oe.prototype,"onClose",2);Se([d({attribute:!1})],oe.prototype,"onConfigSaved",2);Se([k()],oe.prototype,"configResponse",2);Se([k()],oe.prototype,"pluginsResponse",2);Se([k()],oe.prototype,"loading",2);Se([k()],oe.prototype,"saving",2);Se([k()],oe.prototype,"error",2);Se([k()],oe.prototype,"savedMessage",2);oe=Se([W("settings-dialog")],oe);function bs(e){return e instanceof Error?e.message:String(e)}var ow=Object.defineProperty,rw=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var o=s>1?void 0:s?rw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&ow(t,i,o),o};const nw=D`
1638
1638
  :host { display: flex; flex-direction: column; min-height: 0; color: var(--pi-text); background: var(--pi-bg); font: 13px system-ui, sans-serif; container-type: inline-size; }
1639
1639
  header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
1640
1640
  .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
@@ -1723,32 +1723,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1723
1723
  <h2>${e.title}</h2>
1724
1724
  ${e.body===void 0?null:l`<p>${e.body}</p>`}
1725
1725
  </section>
1726
- `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?" can-scroll-left":""}${this.workspaceHeaderCanScrollRight?" can-scroll-right":""}`}observeWorkspaceHeaderStrip(){const e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){const e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==i&&(this.workspaceHeaderCanScrollLeft=i),this.workspaceHeaderCanScrollRight!==s&&(this.workspaceHeaderCanScrollRight=s)}workspaceHeaderStripElement(){const e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}};le.styles=rw;Ce([d({attribute:!1})],le.prototype,"workspace",2);Ce([d({attribute:!1})],le.prototype,"panelContext",2);Ce([d({attribute:!1})],le.prototype,"emptyState",2);Ce([d()],le.prototype,"tool",2);Ce([d({attribute:!1})],le.prototype,"panels",2);Ce([d({type:Boolean})],le.prototype,"hideToolTabs",2);Ce([d({attribute:!1})],le.prototype,"onSelectTool",2);Ce([B(".workspace-header-strip")],le.prototype,"workspaceHeaderStrip",2);Ce([k()],le.prototype,"workspaceHeaderCanScrollLeft",2);Ce([k()],le.prototype,"workspaceHeaderCanScrollRight",2);le=Ce([W("workspace-panel")],le);var nw=Object.defineProperty,aw=Object.getOwnPropertyDescriptor,xe=(e,t,i,s)=>{for(var o=s>1?void 0:s?aw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&nw(t,i,o),o};let re=class extends C{constructor(){super(...arguments),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){const e=lw(this.machines),t=cw(this.machine),i=pw(this.project),s=uw(this.workspace),o=gw(this.session);return l`
1726
+ `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?" can-scroll-left":""}${this.workspaceHeaderCanScrollRight?" can-scroll-right":""}`}observeWorkspaceHeaderStrip(){const e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){const e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==i&&(this.workspaceHeaderCanScrollLeft=i),this.workspaceHeaderCanScrollRight!==s&&(this.workspaceHeaderCanScrollRight=s)}workspaceHeaderStripElement(){const e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}};le.styles=nw;Ce([d({attribute:!1})],le.prototype,"workspace",2);Ce([d({attribute:!1})],le.prototype,"panelContext",2);Ce([d({attribute:!1})],le.prototype,"emptyState",2);Ce([d()],le.prototype,"tool",2);Ce([d({attribute:!1})],le.prototype,"panels",2);Ce([d({type:Boolean})],le.prototype,"hideToolTabs",2);Ce([d({attribute:!1})],le.prototype,"onSelectTool",2);Ce([B(".workspace-header-strip")],le.prototype,"workspaceHeaderStrip",2);Ce([k()],le.prototype,"workspaceHeaderCanScrollLeft",2);Ce([k()],le.prototype,"workspaceHeaderCanScrollRight",2);le=Ce([W("workspace-panel")],le);var aw=Object.defineProperty,lw=Object.getOwnPropertyDescriptor,xe=(e,t,i,s)=>{for(var o=s>1?void 0:s?lw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&aw(t,i,o),o};let re=class extends C{constructor(){super(...arguments),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){const e=cw(this.machines),t=dw(this.machine),i=hw(this.project),s=fw(this.workspace),o=mw(this.session);return l`
1727
1727
  <nav class=${this.contextBarClass()} aria-label="当前位置">
1728
1728
  <span class="context-bar-label">位置</span>
1729
1729
  <ol class="context-items" @scroll=${this.onContextScroll}>
1730
1730
  ${e?l`
1731
1731
  <li class="context-item">
1732
- <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${dw(this.machine)} aria-label=${`机器:${t}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
1732
+ <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${pw(this.machine)} aria-label=${`机器:${t}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
1733
1733
  <span class="context-kind">机器</span>
1734
1734
  <span class="context-value">${t}</span>
1735
1735
  </button>
1736
1736
  </li>
1737
1737
  `:null}
1738
1738
  <li class="context-item">
1739
- <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${hw(this.project)} aria-label=${`项目:${i}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
1739
+ <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${uw(this.project)} aria-label=${`项目:${i}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
1740
1740
  <span class="context-kind">项目</span>
1741
1741
  <span class="context-value">${i}</span>
1742
1742
  </button>
1743
1743
  </li>
1744
1744
  <li class="context-item">
1745
- <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${fw(this.workspace)} aria-label=${`工作区:${s}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
1745
+ <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${gw(this.workspace)} aria-label=${`工作区:${s}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
1746
1746
  <span class="context-kind">工作区</span>
1747
1747
  <span class="context-value">${s}</span>
1748
1748
  </button>
1749
1749
  </li>
1750
1750
  <li class="context-item">
1751
- <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${mw(this.session)} aria-label=${`会话:${o}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
1751
+ <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${vw(this.session)} aria-label=${`会话:${o}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
1752
1752
  <span class="context-kind">会话</span>
1753
1753
  <span class="context-value">${o}</span>
1754
1754
  </button>
@@ -1788,7 +1788,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1788
1788
  .context-kind { display: none; }
1789
1789
  .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
1790
1790
  button { cursor: pointer; }
1791
- `;xe([d({attribute:!1})],re.prototype,"machines",2);xe([d({attribute:!1})],re.prototype,"machine",2);xe([d({attribute:!1})],re.prototype,"project",2);xe([d({attribute:!1})],re.prototype,"workspace",2);xe([d({attribute:!1})],re.prototype,"session",2);xe([d({attribute:!1})],re.prototype,"refreshControl",2);xe([d({attribute:!1})],re.prototype,"onOpenSection",2);xe([d({attribute:!1})],re.prototype,"onShowActions",2);xe([B(".context-items")],re.prototype,"contextItems",2);xe([k()],re.prototype,"canScrollLeft",2);xe([k()],re.prototype,"canScrollRight",2);re=xe([W("app-context-bar")],re);function lw(e){return e.length>1}function cw(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function dw(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function pw(e){return e?.name??"未选择项目"}function hw(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function uw(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function fw(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function gw(e){const t=e?.name?.trim(),i=e?.firstMessage.trim();return t!==void 0&&t!==""?t:i!==void 0&&i!==""?i:e?.id.slice(0,8)??"未选择会话"}function mw(e){return e===void 0?"未选择会话":e.path}var vw=Object.defineProperty,bw=Object.getOwnPropertyDescriptor,st=(e,t,i,s)=>{for(var o=s>1?void 0:s?bw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&vw(t,i,o),o};let je=class extends C{constructor(){super(...arguments),this.tabs=[],this.selectedView="chat",this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){const e=this.fallbackLabels();return l`
1791
+ `;xe([d({attribute:!1})],re.prototype,"machines",2);xe([d({attribute:!1})],re.prototype,"machine",2);xe([d({attribute:!1})],re.prototype,"project",2);xe([d({attribute:!1})],re.prototype,"workspace",2);xe([d({attribute:!1})],re.prototype,"session",2);xe([d({attribute:!1})],re.prototype,"refreshControl",2);xe([d({attribute:!1})],re.prototype,"onOpenSection",2);xe([d({attribute:!1})],re.prototype,"onShowActions",2);xe([B(".context-items")],re.prototype,"contextItems",2);xe([k()],re.prototype,"canScrollLeft",2);xe([k()],re.prototype,"canScrollRight",2);re=xe([W("app-context-bar")],re);function cw(e){return e.length>1}function dw(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function pw(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function hw(e){return e?.name??"未选择项目"}function uw(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function fw(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function gw(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function mw(e){const t=e?.name?.trim(),i=e?.firstMessage.trim();return t!==void 0&&t!==""?t:i!==void 0&&i!==""?i:e?.id.slice(0,8)??"未选择会话"}function vw(e){return e===void 0?"未选择会话":e.path}var bw=Object.defineProperty,ww=Object.getOwnPropertyDescriptor,ot=(e,t,i,s)=>{for(var o=s>1?void 0:s?ww(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&bw(t,i,o),o};let je=class extends C{constructor(){super(...arguments),this.tabs=[],this.selectedView="chat",this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){const e=this.fallbackLabels();return l`
1792
1792
  <div class=${this.frameClass()}>
1793
1793
  <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
1794
1794
  ${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
@@ -1800,7 +1800,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1800
1800
  `})}
1801
1801
  </div>
1802
1802
  </div>
1803
- `}frameClass(){return`mobile-tabs-frame${this.canScrollLeft?" can-scroll-left":""}${this.canScrollRight?" can-scroll-right":""}`}tabClass(e){return[...e.className===void 0?[]:[e.className],...this.selectedView===e.id?["selected"]:[]].join(" ")}tabAriaLabel(e){if(typeof e.badge!="string"&&typeof e.badge!="number")return e.label;const t=String(e.badge).trim();return t===""?e.label:`${e.label}, ${t}`}isEmptyBadge(e){return e===void 0||e===""}renderTabMark(e,t){return e.icon===void 0?l`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:Au(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const o=this.initialsLabel(s.label);t.set(o,(t.get(o)??0)+1)}const i=new Map;for(const s of e){const o=this.initialsLabel(s.label);i.set(s.id,(t.get(o)??0)>1?this.fullFallbackLabel(s.label):o)}return i}initialsLabel(e){const i=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(s=>Array.from(s)[0]??"").join("").toLocaleUpperCase();return i===""?"?":i}fullFallbackLabel(e){const t=e.trim();return t===""?"?":t}observeMobileTabs(){const e=this.mobileTabsElement();this.observedMobileTabs!==e&&(this.mobileTabsResizeObserver?.disconnect(),this.observedMobileTabs=e,this.mobileTabsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.mobileTabsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.mobileTabsResizeObserver.observe(e)))}updateScrollState(){const e=this.mobileTabsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}mobileTabsElement(){const e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}};je.styles=D`
1803
+ `}frameClass(){return`mobile-tabs-frame${this.canScrollLeft?" can-scroll-left":""}${this.canScrollRight?" can-scroll-right":""}`}tabClass(e){return[...e.className===void 0?[]:[e.className],...this.selectedView===e.id?["selected"]:[]].join(" ")}tabAriaLabel(e){if(typeof e.badge!="string"&&typeof e.badge!="number")return e.label;const t=String(e.badge).trim();return t===""?e.label:`${e.label}, ${t}`}isEmptyBadge(e){return e===void 0||e===""}renderTabMark(e,t){return e.icon===void 0?l`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:Mu(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const o=this.initialsLabel(s.label);t.set(o,(t.get(o)??0)+1)}const i=new Map;for(const s of e){const o=this.initialsLabel(s.label);i.set(s.id,(t.get(o)??0)>1?this.fullFallbackLabel(s.label):o)}return i}initialsLabel(e){const i=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(s=>Array.from(s)[0]??"").join("").toLocaleUpperCase();return i===""?"?":i}fullFallbackLabel(e){const t=e.trim();return t===""?"?":t}observeMobileTabs(){const e=this.mobileTabsElement();this.observedMobileTabs!==e&&(this.mobileTabsResizeObserver?.disconnect(),this.observedMobileTabs=e,this.mobileTabsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.mobileTabsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.mobileTabsResizeObserver.observe(e)))}updateScrollState(){const e=this.mobileTabsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}mobileTabsElement(){const e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}};je.styles=D`
1804
1804
  :host { flex: 0 0 auto; min-width: 0; }
1805
1805
  .mobile-tabs-frame { position: relative; display: flex; flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg); }
1806
1806
  .mobile-tabs-frame::before, .mobile-tabs-frame::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
@@ -1826,12 +1826,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1826
1826
  .tab-label { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; }
1827
1827
  .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
1828
1828
  }
1829
- `;st([d({attribute:!1})],je.prototype,"tabs",2);st([d({attribute:!1})],je.prototype,"selectedView",2);st([d({attribute:!1})],je.prototype,"onSelect",2);st([B(".mobile-tabs")],je.prototype,"mobileTabs",2);st([k()],je.prototype,"canScrollLeft",2);st([k()],je.prototype,"canScrollRight",2);je=st([W("app-mobile-main-tabs")],je);var ww=Object.defineProperty,yw=Object.getOwnPropertyDescriptor,pe=(e,t,i,s)=>{for(var o=s>1?void 0:s?yw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&ww(t,i,o),o};let Y=class extends C{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.open=!1,this.menuStyle="",this.actionMenuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has("machines")&&this.openActionsMachineId!==void 0&&!this.machines.some(t=>t.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){const e=this.switcherButton();return e===null?!1:await this.openMenuAndFocusOption(e)}render(){const e=this.selectedMachine();if(e===void 0)return null;const t=bs(e,this.statuses),i=e.name;return l`
1829
+ `;ot([d({attribute:!1})],je.prototype,"tabs",2);ot([d({attribute:!1})],je.prototype,"selectedView",2);ot([d({attribute:!1})],je.prototype,"onSelect",2);ot([B(".mobile-tabs")],je.prototype,"mobileTabs",2);ot([k()],je.prototype,"canScrollLeft",2);ot([k()],je.prototype,"canScrollRight",2);je=ot([W("app-mobile-main-tabs")],je);var yw=Object.defineProperty,Sw=Object.getOwnPropertyDescriptor,pe=(e,t,i,s)=>{for(var o=s>1?void 0:s?Sw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&yw(t,i,o),o};let Y=class extends C{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.open=!1,this.menuStyle="",this.actionMenuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has("machines")&&this.openActionsMachineId!==void 0&&!this.machines.some(t=>t.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){const e=this.switcherButton();return e===null?!1:await this.openMenuAndFocusOption(e)}render(){const e=this.selectedMachine();if(e===void 0)return null;const t=ws(e,this.statuses),i=e.name;return l`
1830
1830
  <div class="machine-switcher">
1831
1831
  <button
1832
1832
  type="button"
1833
1833
  class="machine-switcher-button"
1834
- title=${ln(e)}
1834
+ title=${cn(e)}
1835
1835
  aria-label=${`Machine: ${i}. Switch machine.`}
1836
1836
  aria-expanded=${String(this.open)}
1837
1837
  @click=${s=>{this.toggleMenu(s.currentTarget)}}
@@ -1842,7 +1842,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1842
1842
  <span class="machine-switcher-kicker">Machine</span>
1843
1843
  <span class="machine-switcher-label">${i}</span>
1844
1844
  </span>
1845
- <span class=${`machine-status ${t}`}>${an(t)}</span>
1845
+ <span class=${`machine-status ${t}`}>${ln(t)}</span>
1846
1846
  <span class="machine-chevron" aria-hidden="true">▾</span>
1847
1847
  </button>
1848
1848
  ${this.open?l`
@@ -1851,18 +1851,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1851
1851
  </div>
1852
1852
  `:null}
1853
1853
  </div>
1854
- `}renderMachineOption(e){const t=this.selected?.id===e.id,i=bs(e,this.statuses),s=Ra(e)&&this.onRemove!==void 0,o=this.openActionsMachineId===e.id;return l`
1854
+ `}renderMachineOption(e){const t=this.selected?.id===e.id,i=ws(e,this.statuses),s=Ia(e)&&this.onRemove!==void 0,o=this.openActionsMachineId===e.id;return l`
1855
1855
  <div class=${`machine-option ${t?"selected":""} ${s?"":"no-actions"}`}>
1856
1856
  <button
1857
1857
  type="button"
1858
1858
  class="machine-option-main"
1859
- title=${ln(e)}
1859
+ title=${cn(e)}
1860
1860
  data-machine-id=${e.id}
1861
1861
  @click=${()=>{this.select(e)}}
1862
1862
  @keydown=${r=>{this.handleMachineOptionKeydown(r)}}
1863
1863
  >
1864
1864
  <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
1865
- <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${an(i)}</small>
1865
+ <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${ln(i)}</small>
1866
1866
  </button>
1867
1867
  ${s?l`
1868
1868
  <div class="machine-option-actions">
@@ -1882,7 +1882,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1882
1882
  </div>
1883
1883
  `:null}
1884
1884
  </div>
1885
- `}renderActivity(e){const t=bs(e,this.statuses);if(t==="offline"||t==="error")return;const i=va(this.activities[e.id]);return wa(i,i==="terminal"?"Machine terminal active":"Machine active")}selectedMachine(){return this.selected??this.machines.find(e=>e.id==="local")??this.machines[0]}switcherButton(){return this.renderRoot.querySelector(".machine-switcher-button")}handleSwitcherButtonKeydown(e){if(e.key==="ArrowDown"||e.key==="ArrowUp"){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key==="Escape"&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key==="ArrowUp"){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key==="ArrowDown"){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key==="Home"){this.focusIndexedMachineOption(0,e);return}if(e.key==="End"){this.focusIndexedMachineOption(-1,e);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key==="ArrowLeft"||e.key==="Escape")&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=cn(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){const e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=cn(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){const e=this.renderRoot.querySelector(".machine-option.selected .machine-option-main"),t=this.machineOptionButtons()[0],i=e??t;return i===void 0?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}focusRelativeMachineOption(e,t,i){i.preventDefault(),i.stopPropagation();const s=this.machineOptionButtons();if(s.length===0||!(e instanceof HTMLElement))return;const o=s.indexOf(e);o<0||this.focusMachineOptionAt(o+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){const t=this.machineOptionButtons(),i=t[Math.min(Math.max(e,0),t.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(".machine-option-main"))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=ya(t,{constrainTo:"viewport"}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}};Y.styles=D`
1885
+ `}renderActivity(e){const t=ws(e,this.statuses);if(t==="offline"||t==="error")return;const i=ba(this.activities[e.id]);return ya(i,i==="terminal"?"Machine terminal active":"Machine active")}selectedMachine(){return this.selected??this.machines.find(e=>e.id==="local")??this.machines[0]}switcherButton(){return this.renderRoot.querySelector(".machine-switcher-button")}handleSwitcherButtonKeydown(e){if(e.key==="ArrowDown"||e.key==="ArrowUp"){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key==="Escape"&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key==="ArrowUp"){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key==="ArrowDown"){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key==="Home"){this.focusIndexedMachineOption(0,e);return}if(e.key==="End"){this.focusIndexedMachineOption(-1,e);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key==="ArrowLeft"||e.key==="Escape")&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=dn(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){const e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=dn(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){const e=this.renderRoot.querySelector(".machine-option.selected .machine-option-main"),t=this.machineOptionButtons()[0],i=e??t;return i===void 0?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}focusRelativeMachineOption(e,t,i){i.preventDefault(),i.stopPropagation();const s=this.machineOptionButtons();if(s.length===0||!(e instanceof HTMLElement))return;const o=s.indexOf(e);o<0||this.focusMachineOptionAt(o+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){const t=this.machineOptionButtons(),i=t[Math.min(Math.max(e,0),t.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(".machine-option-main"))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=Sa(t,{constrainTo:"viewport"}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}};Y.styles=D`
1886
1886
  :host { min-width: 0; display: block; }
1887
1887
  .machine-switcher { min-width: 0; }
1888
1888
  .machine-switcher-button { box-sizing: border-box; width: 100%; min-width: 0; display: flex; align-items: center; gap: 6px; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 8px; cursor: pointer; text-align: left; }
@@ -1915,10 +1915,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1915
1915
  .machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
1916
1916
  .machine-option-actions-panel button.danger:hover, .machine-option-actions-panel button.danger:focus-visible { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
1917
1917
  @keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
1918
- `;pe([d({attribute:!1})],Y.prototype,"machines",2);pe([d({attribute:!1})],Y.prototype,"selected",2);pe([d({attribute:!1})],Y.prototype,"statuses",2);pe([d({attribute:!1})],Y.prototype,"activities",2);pe([d({attribute:!1})],Y.prototype,"onSelect",2);pe([d({attribute:!1})],Y.prototype,"onRemove",2);pe([d({attribute:!1})],Y.prototype,"onFocusNextSection",2);pe([d({attribute:!1})],Y.prototype,"onCancelKeyboardNavigation",2);pe([k()],Y.prototype,"open",2);pe([k()],Y.prototype,"menuStyle",2);pe([k()],Y.prototype,"openActionsMachineId",2);pe([k()],Y.prototype,"actionMenuStyle",2);Y=pe([W("machine-switcher")],Y);function bs(e,t){return t[e.id]?.status??e.status??"unknown"}function an(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function ln(e){return e.baseUrl??e.name}function cn(e){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const t=e.getBoundingClientRect(),i=8,s=Math.min(280,Math.max(0,window.innerWidth-i*2)),o=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),r=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${ti(t.bottom)};`,`left: ${ti(o)};`,`width: ${ti(s)};`,`max-height: ${ti(r)};`].join(" ")}function ti(e){return`${String(Math.round(e))}px`}var Sw=Object.defineProperty,xw=Object.getOwnPropertyDescriptor,x=(e,t,i,s)=>{for(var o=s>1?void 0:s?xw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Sw(t,i,o),o};let S=class extends C{constructor(){super(...arguments),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions."}async focusSection(e){switch(await this.updateComplete,e){case"machines":return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case"projects":return await this.focusNavigableSection(this.projectList);case"workspaces":return await this.focusNavigableSection(this.workspaceList);case"sessions":return await this.focusNavigableSection(this.sessionList)}}render(){return l`
1918
+ `;pe([d({attribute:!1})],Y.prototype,"machines",2);pe([d({attribute:!1})],Y.prototype,"selected",2);pe([d({attribute:!1})],Y.prototype,"statuses",2);pe([d({attribute:!1})],Y.prototype,"activities",2);pe([d({attribute:!1})],Y.prototype,"onSelect",2);pe([d({attribute:!1})],Y.prototype,"onRemove",2);pe([d({attribute:!1})],Y.prototype,"onFocusNextSection",2);pe([d({attribute:!1})],Y.prototype,"onCancelKeyboardNavigation",2);pe([k()],Y.prototype,"open",2);pe([k()],Y.prototype,"menuStyle",2);pe([k()],Y.prototype,"openActionsMachineId",2);pe([k()],Y.prototype,"actionMenuStyle",2);Y=pe([W("machine-switcher")],Y);function ws(e,t){return t[e.id]?.status??e.status??"unknown"}function ln(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function cn(e){return e.baseUrl??e.name}function dn(e){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const t=e.getBoundingClientRect(),i=8,s=Math.min(280,Math.max(0,window.innerWidth-i*2)),o=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),r=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${ii(t.bottom)};`,`left: ${ii(o)};`,`width: ${ii(s)};`,`max-height: ${ii(r)};`].join(" ")}function ii(e){return`${String(Math.round(e))}px`}var xw=Object.defineProperty,kw=Object.getOwnPropertyDescriptor,x=(e,t,i,s)=>{for(var o=s>1?void 0:s?kw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&xw(t,i,o),o};let y=class extends C{constructor(){super(...arguments),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions."}async focusSection(e){switch(await this.updateComplete,e){case"machines":return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case"projects":return await this.focusNavigableSection(this.projectList);case"workspaces":return await this.focusNavigableSection(this.workspaceList);case"sessions":return await this.focusNavigableSection(this.sessionList)}}render(){return l`
1919
1919
  <header>
1920
1920
  <strong>PI WEB</strong>
1921
- ${Mi(this.machines)?l`
1921
+ ${Ei(this.machines)?l`
1922
1922
  <machine-switcher
1923
1923
  .machines=${this.machines}
1924
1924
  .selected=${this.selectedMachine}
@@ -1935,7 +1935,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1935
1935
  <button title="显示操作" aria-label="显示操作" @click=${()=>{this.onShowActions?.()}}>操作</button>
1936
1936
  </div>
1937
1937
  </header>
1938
- ${this.compact&&Mi(this.machines)?l`
1938
+ ${this.compact&&Ei(this.machines)?l`
1939
1939
  <machine-list
1940
1940
  .machines=${this.machines}
1941
1941
  .selected=${this.selectedMachine}
@@ -2008,7 +2008,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2008
2008
  .onFocusNextSection=${()=>{this.focusNextFrom("sessions")}}
2009
2009
  .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2010
2010
  ></session-list>
2011
- `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=kw(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.($w(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};S.styles=D`
2011
+ `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=$w(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Pw(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};y.styles=D`
2012
2012
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
2013
2013
  :host([compact]) { flex: 1 1 auto; }
2014
2014
  header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
@@ -2031,7 +2031,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2031
2031
  :host([compact]) workspace-list[collapsed],
2032
2032
  :host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
2033
2033
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2034
- `;x([d({attribute:!1})],S.prototype,"machines",2);x([d({attribute:!1})],S.prototype,"selectedMachine",2);x([d({attribute:!1})],S.prototype,"machineStatuses",2);x([d({attribute:!1})],S.prototype,"machineActivities",2);x([d({attribute:!1})],S.prototype,"projects",2);x([d({attribute:!1})],S.prototype,"selectedProject",2);x([d({attribute:!1})],S.prototype,"workspaces",2);x([d({attribute:!1})],S.prototype,"selectedWorkspace",2);x([d({attribute:!1})],S.prototype,"sessions",2);x([d({attribute:!1})],S.prototype,"selectedSession",2);x([d({attribute:!1})],S.prototype,"workspaceActivities",2);x([d({attribute:!1})],S.prototype,"sessionActivities",2);x([d({attribute:!1})],S.prototype,"sessionStatuses",2);x([d({attribute:!1})],S.prototype,"sendingPrompts",2);x([d({attribute:!1})],S.prototype,"workspacesByProjectId",2);x([d({attribute:!1})],S.prototype,"deletingWorkspaceIds",2);x([d({attribute:!1})],S.prototype,"workspaceLabelItems",2);x([d({attribute:!1})],S.prototype,"refreshControl",2);x([d({type:Boolean,reflect:!0})],S.prototype,"collapsible",2);x([d({type:Boolean,reflect:!0})],S.prototype,"compact",2);x([d({type:Boolean})],S.prototype,"machinesCollapsed",2);x([d({type:Boolean})],S.prototype,"projectsCollapsed",2);x([d({type:Boolean})],S.prototype,"workspacesCollapsed",2);x([d({type:Boolean})],S.prototype,"sessionsCollapsed",2);x([d({type:Boolean})],S.prototype,"canStartSession",2);x([d({type:Boolean})],S.prototype,"canDeleteArchivedSessions",2);x([d({type:Boolean})],S.prototype,"canReloadSessions",2);x([d({type:String})],S.prototype,"archivedDeleteUnavailableMessage",2);x([d({attribute:!1})],S.prototype,"onShowActions",2);x([d({attribute:!1})],S.prototype,"onToggleMachines",2);x([d({attribute:!1})],S.prototype,"onToggleProjects",2);x([d({attribute:!1})],S.prototype,"onToggleWorkspaces",2);x([d({attribute:!1})],S.prototype,"onToggleSessions",2);x([d({attribute:!1})],S.prototype,"onSelectProject",2);x([d({attribute:!1})],S.prototype,"onCloseProject",2);x([d({attribute:!1})],S.prototype,"onSelectWorkspace",2);x([d({attribute:!1})],S.prototype,"onDeleteWorkspace",2);x([d({attribute:!1})],S.prototype,"onStartSession",2);x([d({attribute:!1})],S.prototype,"onSelectSession",2);x([d({attribute:!1})],S.prototype,"onArchiveSession",2);x([d({attribute:!1})],S.prototype,"onArchiveSessionWithDescendants",2);x([d({attribute:!1})],S.prototype,"onArchiveSessions",2);x([d({attribute:!1})],S.prototype,"onRestoreSession",2);x([d({attribute:!1})],S.prototype,"onDeleteCachedNewSession",2);x([d({attribute:!1})],S.prototype,"onDeleteArchivedSession",2);x([d({attribute:!1})],S.prototype,"onDeleteArchivedSessions",2);x([d({attribute:!1})],S.prototype,"onDetachParentSession",2);x([d({attribute:!1})],S.prototype,"onReloadSession",2);x([d({attribute:!1})],S.prototype,"onArchivedCollapsed",2);x([d({attribute:!1})],S.prototype,"onSelectMachine",2);x([d({attribute:!1})],S.prototype,"onRemoveMachine",2);x([d({attribute:!1})],S.prototype,"onFocusNavigationTarget",2);x([d({attribute:!1})],S.prototype,"onCancelKeyboardNavigation",2);x([B("machine-list")],S.prototype,"machineList",2);x([B("machine-switcher")],S.prototype,"machineSwitcher",2);x([B("project-list")],S.prototype,"projectList",2);x([B("workspace-list")],S.prototype,"workspaceList",2);x([B("session-list")],S.prototype,"sessionList",2);S=x([W("app-navigation-panel")],S);function Mi(e){return e.length>1}function kw(e,t){const i=Ja(t);return i[i.indexOf(e)-1]}function $w(e,t){const i=Ja(t);return i[i.indexOf(e)+1]??"chat"}function Ja(e){return $i.filter(t=>t!=="machines"||Mi(e))}var Pw=Object.defineProperty,Rw=Object.getOwnPropertyDescriptor,Q=(e,t,i,s)=>{for(var o=s>1?void 0:s?Rw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Pw(t,i,o),o};const Iw=new Set(["ArrowLeft","ArrowRight","Home","End"]),Cw=420,Tw=4;let q=class extends C{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.resizable=!1,this.controls="",this.resizeLabel="调整面板宽度",this.expandLabel="展开面板",this.collapseLabel="折叠面板",this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
2034
+ `;x([d({attribute:!1})],y.prototype,"machines",2);x([d({attribute:!1})],y.prototype,"selectedMachine",2);x([d({attribute:!1})],y.prototype,"machineStatuses",2);x([d({attribute:!1})],y.prototype,"machineActivities",2);x([d({attribute:!1})],y.prototype,"projects",2);x([d({attribute:!1})],y.prototype,"selectedProject",2);x([d({attribute:!1})],y.prototype,"workspaces",2);x([d({attribute:!1})],y.prototype,"selectedWorkspace",2);x([d({attribute:!1})],y.prototype,"sessions",2);x([d({attribute:!1})],y.prototype,"selectedSession",2);x([d({attribute:!1})],y.prototype,"workspaceActivities",2);x([d({attribute:!1})],y.prototype,"sessionActivities",2);x([d({attribute:!1})],y.prototype,"sessionStatuses",2);x([d({attribute:!1})],y.prototype,"sendingPrompts",2);x([d({attribute:!1})],y.prototype,"workspacesByProjectId",2);x([d({attribute:!1})],y.prototype,"deletingWorkspaceIds",2);x([d({attribute:!1})],y.prototype,"workspaceLabelItems",2);x([d({attribute:!1})],y.prototype,"refreshControl",2);x([d({type:Boolean,reflect:!0})],y.prototype,"collapsible",2);x([d({type:Boolean,reflect:!0})],y.prototype,"compact",2);x([d({type:Boolean})],y.prototype,"machinesCollapsed",2);x([d({type:Boolean})],y.prototype,"projectsCollapsed",2);x([d({type:Boolean})],y.prototype,"workspacesCollapsed",2);x([d({type:Boolean})],y.prototype,"sessionsCollapsed",2);x([d({type:Boolean})],y.prototype,"canStartSession",2);x([d({type:Boolean})],y.prototype,"canDeleteArchivedSessions",2);x([d({type:Boolean})],y.prototype,"canReloadSessions",2);x([d({type:String})],y.prototype,"archivedDeleteUnavailableMessage",2);x([d({attribute:!1})],y.prototype,"onShowActions",2);x([d({attribute:!1})],y.prototype,"onToggleMachines",2);x([d({attribute:!1})],y.prototype,"onToggleProjects",2);x([d({attribute:!1})],y.prototype,"onToggleWorkspaces",2);x([d({attribute:!1})],y.prototype,"onToggleSessions",2);x([d({attribute:!1})],y.prototype,"onSelectProject",2);x([d({attribute:!1})],y.prototype,"onCloseProject",2);x([d({attribute:!1})],y.prototype,"onSelectWorkspace",2);x([d({attribute:!1})],y.prototype,"onDeleteWorkspace",2);x([d({attribute:!1})],y.prototype,"onStartSession",2);x([d({attribute:!1})],y.prototype,"onSelectSession",2);x([d({attribute:!1})],y.prototype,"onArchiveSession",2);x([d({attribute:!1})],y.prototype,"onArchiveSessionWithDescendants",2);x([d({attribute:!1})],y.prototype,"onArchiveSessions",2);x([d({attribute:!1})],y.prototype,"onRestoreSession",2);x([d({attribute:!1})],y.prototype,"onDeleteCachedNewSession",2);x([d({attribute:!1})],y.prototype,"onDeleteArchivedSession",2);x([d({attribute:!1})],y.prototype,"onDeleteArchivedSessions",2);x([d({attribute:!1})],y.prototype,"onDetachParentSession",2);x([d({attribute:!1})],y.prototype,"onReloadSession",2);x([d({attribute:!1})],y.prototype,"onArchivedCollapsed",2);x([d({attribute:!1})],y.prototype,"onSelectMachine",2);x([d({attribute:!1})],y.prototype,"onRemoveMachine",2);x([d({attribute:!1})],y.prototype,"onFocusNavigationTarget",2);x([d({attribute:!1})],y.prototype,"onCancelKeyboardNavigation",2);x([B("machine-list")],y.prototype,"machineList",2);x([B("machine-switcher")],y.prototype,"machineSwitcher",2);x([B("project-list")],y.prototype,"projectList",2);x([B("workspace-list")],y.prototype,"workspaceList",2);x([B("session-list")],y.prototype,"sessionList",2);y=x([W("app-navigation-panel")],y);function Ei(e){return e.length>1}function $w(e,t){const i=Qa(t);return i[i.indexOf(e)-1]}function Pw(e,t){const i=Qa(t);return i[i.indexOf(e)+1]??"chat"}function Qa(e){return Pi.filter(t=>t!=="machines"||Ei(e))}var Rw=Object.defineProperty,Iw=Object.getOwnPropertyDescriptor,Q=(e,t,i,s)=>{for(var o=s>1?void 0:s?Iw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Rw(t,i,o),o};const Cw=new Set(["ArrowLeft","ArrowRight","Home","End"]),Tw=420,Aw=4;let q=class extends C{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.resizable=!1,this.controls="",this.resizeLabel="调整面板宽度",this.expandLabel="展开面板",this.collapseLabel="折叠面板",this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
2035
2035
  ${this.renderResizeHandle()}
2036
2036
  <button
2037
2037
  type="button"
@@ -2061,7 +2061,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2061
2061
  @dblclick=${t=>{this.onResizeDoubleClick(t)}}
2062
2062
  @keydown=${t=>{this.onResizeKeyDown(t)}}
2063
2063
  ></div>
2064
- `}resizeAriaValueNow(){return this.panelWidth===void 0?F:String(Math.round(this.panelWidth))}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return l`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${t}/></svg>`}iconDirection(){return this.side==="navigation"?this.collapsed?"right":"left":this.collapsed?"left":"right"}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=this.resizeStartWidth();i!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:i,handle:t,moved:!1},this.toggleAttribute("resizing",!0))}onResizePointerMove(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=Tw)&&(t.moved=!0,this.commitPanelWidth(Kf(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!Iw.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=Vf(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});i!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(i),this.onResizeEnd?.())}registerTapForReset(){const e=Date.now();if(e-this.lastTapAt<=Cw){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){const e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return ue(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(ue(this.side,e,this.resizeConstraints()))}finishActiveResize(){const e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute("resizing",!1),this.onResizeEnd?.()}}resizeConstraints(){const e=Ht(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};q.styles=D`
2064
+ `}resizeAriaValueNow(){return this.panelWidth===void 0?F:String(Math.round(this.panelWidth))}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return l`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${t}/></svg>`}iconDirection(){return this.side==="navigation"?this.collapsed?"right":"left":this.collapsed?"left":"right"}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=this.resizeStartWidth();i!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:i,handle:t,moved:!1},this.toggleAttribute("resizing",!0))}onResizePointerMove(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=Aw)&&(t.moved=!0,this.commitPanelWidth(Vf(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!Cw.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=Gf(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});i!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(i),this.onResizeEnd?.())}registerTapForReset(){const e=Date.now();if(e-this.lastTapAt<=Tw){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){const e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return ue(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(ue(this.side,e,this.resizeConstraints()))}finishActiveResize(){const e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute("resizing",!1),this.onResizeEnd?.()}}resizeConstraints(){const e=qt(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};q.styles=D`
2065
2065
  :host { position: relative; min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
2066
2066
  :host([side="navigation"]) { grid-column: 2; }
2067
2067
  :host([side="workspace"]) { grid-column: 4; }
@@ -2080,7 +2080,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2080
2080
  @media (max-width: 760px) {
2081
2081
  :host([side="navigation"]) { display: none; }
2082
2082
  }
2083
- `;Q([d({reflect:!0})],q.prototype,"side",2);Q([d({type:Boolean,reflect:!0})],q.prototype,"collapsed",2);Q([d({type:Boolean})],q.prototype,"resizable",2);Q([d({type:Number})],q.prototype,"panelWidth",2);Q([d({type:Number})],q.prototype,"minWidth",2);Q([d({type:Number})],q.prototype,"maxWidth",2);Q([d()],q.prototype,"controls",2);Q([d()],q.prototype,"resizeLabel",2);Q([d()],q.prototype,"expandLabel",2);Q([d()],q.prototype,"collapseLabel",2);Q([d({attribute:!1})],q.prototype,"onToggle",2);Q([d({attribute:!1})],q.prototype,"onResizeStart",2);Q([d({attribute:!1})],q.prototype,"onResize",2);Q([d({attribute:!1})],q.prototype,"onResizeEnd",2);Q([d({attribute:!1})],q.prototype,"onReset",2);q=Q([W("app-panel-edge-control")],q);var Aw=Object.defineProperty,Mw=Object.getOwnPropertyDescriptor,Qa=(e,t,i,s)=>{for(var o=s>1?void 0:s?Mw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Aw(t,i,o),o};let Ei=class extends C{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="完整重载页面";return l`
2083
+ `;Q([d({reflect:!0})],q.prototype,"side",2);Q([d({type:Boolean,reflect:!0})],q.prototype,"collapsed",2);Q([d({type:Boolean})],q.prototype,"resizable",2);Q([d({type:Number})],q.prototype,"panelWidth",2);Q([d({type:Number})],q.prototype,"minWidth",2);Q([d({type:Number})],q.prototype,"maxWidth",2);Q([d()],q.prototype,"controls",2);Q([d()],q.prototype,"resizeLabel",2);Q([d()],q.prototype,"expandLabel",2);Q([d()],q.prototype,"collapseLabel",2);Q([d({attribute:!1})],q.prototype,"onToggle",2);Q([d({attribute:!1})],q.prototype,"onResizeStart",2);Q([d({attribute:!1})],q.prototype,"onResize",2);Q([d({attribute:!1})],q.prototype,"onResizeEnd",2);Q([d({attribute:!1})],q.prototype,"onReset",2);q=Q([W("app-panel-edge-control")],q);var Mw=Object.defineProperty,Ew=Object.getOwnPropertyDescriptor,Za=(e,t,i,s)=>{for(var o=s>1?void 0:s?Ew(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Mw(t,i,o),o};let Di=class extends C{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="完整重载页面";return l`
2084
2084
  <button
2085
2085
  class="app-refresh-button"
2086
2086
  title=${e}
@@ -2094,12 +2094,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2094
2094
  <path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
2095
2095
  <path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
2096
2096
  </svg>
2097
- `}};Ei.styles=D`
2097
+ `}};Di.styles=D`
2098
2098
  :host { position: relative; z-index: 1; display: flex; align-items: center; pointer-events: auto; -webkit-touch-callout: none; -webkit-user-select: none; user-select: none; }
2099
2099
  :host, :host * { -webkit-user-select: none; user-select: none; }
2100
2100
  .app-refresh-button { box-sizing: border-box; width: 36px; height: 36px; display: grid; place-items: center; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 0; line-height: 1; cursor: pointer; touch-action: manipulation; -webkit-touch-callout: none; }
2101
2101
  .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
2102
- `;Qa([d({attribute:!1})],Ei.prototype,"onReload",2);Ei=Qa([W("app-refresh-control")],Ei);var Ew=Object.defineProperty,Dw=Object.getOwnPropertyDescriptor,Te=(e,t,i,s)=>{for(var o=s>1?void 0:s?Dw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ew(t,i,o),o};const Ww=D`
2102
+ `;Za([d({attribute:!1})],Di.prototype,"onReload",2);Di=Za([W("app-refresh-control")],Di);var Dw=Object.defineProperty,Ww=Object.getOwnPropertyDescriptor,Te=(e,t,i,s)=>{for(var o=s>1?void 0:s?Ww(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Dw(t,i,o),o};const Ow=D`
2103
2103
  /* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
2104
2104
  :host { --pi-app-safe-area-bottom: 0px; position: fixed; top: 0; right: 0; left: 0; display: block; height: 100dvh; box-sizing: border-box; overflow: hidden; padding: env(safe-area-inset-top) env(safe-area-inset-right) var(--pi-app-safe-area-bottom) env(safe-area-inset-left); color: var(--pi-text); background: var(--pi-bg); font: 14px system-ui, sans-serif; }
2105
2105
  :host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
@@ -2198,7 +2198,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2198
2198
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2199
2199
  .empty { margin: auto; color: var(--pi-muted); }
2200
2200
  .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
2201
- `,Ow=900*1e3,_w=750,Us=[1e3,3e3,8e3,15e3,3e4],dn={capture:!0},ws="auto:on",pn="auto:off",ii="theme:",ys=Ft("core:workspace.files"),Ss=Ft("core:workspace.git"),si=Ft("core:workspace.terminal"),Lw=320,jw=2,Fw="(min-width: 1181px)";let ce=class extends C{constructor(){super(...arguments),this.state=Sd(),this.sessions=new gh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new ch),this.activity=new xd(()=>this.state,e=>{this.setState(e)}),this.auth=new Pd(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Th(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Ih),this.projects=new _d(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Od(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new Td(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Wd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Bh,this.realtime=new pr,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Dh,this.terminalSelection=new Nh,this.appShell=new Tf(this),this.panelCollapse=new Bf(this),this.panelResize=new Hf(this),this.navigationSections=new Ff(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=Nw(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=su()??eu,this.activeThemeId=po,this.isRefreshingApp=!1,this.settingsSection=Ar(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.previousStackedWorkspaceLayout=this.appShell.isStackedWorkspaceLayout,this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode),this.normalizeMainViewForLayoutChange()}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,dn),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},Ow),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()})}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,dn),this.systemLightThemeMedia?.removeEventListener("change",this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!Uw(this.state,e))return;const t=this.state;this.state={...this.state,...e},this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),zw(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=Tr();await this.machines.loadMachines(e.machineId);const t=this.routeForSelectedMachine(e),i=this.state.machineStatuses[t.machineId??"local"];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,i)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}schedulePiWebStatusRefresh(e=_w){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.refreshPiWebStatus()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshPiWebStatus(){const e=f(this.state);try{const t=await Wn.piWebStatus(e);f(this.state)===e&&this.setState({piWebStatus:t})}catch(t){f(this.state)===e&&this.setState({piWebStatus:void 0}),console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}async refreshWorkspaceActivity(e=f(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){const e=this.state.machines.length===0?[f(this.state)]:this.state.machines.filter(t=>Za(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await fi.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(Tr(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=f(this.state),r=e.projectId===void 0||e.projectId===""?fn():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=r.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(n))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:this.appShell.normalizedMainView(s??e.view,e.sessionId!==void 0),selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const c=this.state.projects.find(p=>p.id===e.projectId);if(!c){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(c,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),f(this.state)!==o&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?fn():{selectedFilePath:es(ys,"file"),selectedDiffPath:es(Ss,"diff"),selectedTerminalId:es(si,"terminal")}}routeForSelectedMachine(e){const t=this.state.selectedMachine?.id??"local";return(e.machineId??"local")===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){as(e,{replace:!0}),ae(ys,"file",void 0,{replace:!0}),ae(Ss,"diff",void 0,{replace:!0}),ae(si,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.kind!=="remote"||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===""?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=qw(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;const e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{const t=e.machineId??"local",i=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==""){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=Us.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",r=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),n=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${n}${r===void 0?"":` ${r}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(o=>o.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e){this.chatView?.saveScrollPosition(),await e(),await this.updateComplete,await this.chatView?.updateComplete,await xs(),this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}normalizeMainViewForLayoutChange(){const e=this.previousStackedWorkspaceLayout,t=this.appShell.isStackedWorkspaceLayout;if(this.previousStackedWorkspaceLayout=t,e||!t)return;const i=this.appShell.normalizedMainView(this.state.mainView,this.state.selectedSession!==void 0);i!==this.state.mainView&&(this.setState({mainView:i}),this.updateUrl({replace:!0}))}updateUrl(e){this.rememberCurrentMachineNavigation(),as({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView==="navigation"?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(fr(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(fr(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){as(gr(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){ae(ys,"file",e.selectedFilePath,{replace:!0}),ae(Ss,"diff",e.selectedDiffPath,{replace:!0}),ae(si,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??Wh(e.id);if(await this.restoreRouteFor(gr(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==""}openWorkspaceTool(e){e==="core:workspace.terminal"&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool("core:workspace.terminal")}terminalCommandRunsForOrigin(e,t=f(this.state)){const i=gn(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=ag(e,{api:{runTerminalCommand:(r,n)=>dt.runTerminalCommand(r,n,t),listCommandRuns:r=>dt.listCommandRuns(r,t),getCommandRun:r=>dt.getCommandRun(r,t)},openTerminal:(r,n)=>{this.openRuntimeTerminal(t,r,n)}});return this.terminalCommandRunRuntimes.set(i,o),o}async openRuntimeTerminal(e,t,i){if((f(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:"core:workspace.terminal",view:"core:workspace.terminal"},!1,{selectedTerminalId:i?.terminalId},"core:workspace.terminal"),f(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){ae(si,"terminal",e,t)}terminalWorkspaceKey(e){return`${f(this.state)}:${e.path}`}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e="general"){this.settingsSection=e,ls(e)}closeSettings(){this.settingsSection=void 0,ls(void 0)}navigateSettings(e){this.settingsSection=e,ls(e)}restoreSettingsRoute(){this.settingsSection=Ar()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();const i=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:i}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(i,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}connectRealtime(){this.realtime.connect(e=>{this.handleRealtimeEvent(e)},()=>{const e=this.state.selectedWorkspace;e!==void 0&&this.refreshActiveTerminals(e),this.refreshWorkspaceActivity()},f(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new pr;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=f(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>Bw(t,this.state.machineStatuses[t.id])).map(t=>t.id))}handleMachineActivityEvent(e,t){t.type==="workspace.activity"&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e){e.type==="workspace.activity"?this.activity.applyWorkspaceActivity(e.activity):Hw(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const t=this.state.selectedWorkspace;t===void 0||(e.type==="terminal.closed"?e.cwd:e.terminal.cwd)!==t.path||(e.type==="terminal.created"&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type==="terminal.closed"?e.terminalId:e.terminal.id),e.type==="terminal.closed"&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){const t=f(this.state);try{const i=await dt.terminals(e.projectId,e.id,t);if(f(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=un(e),s=un(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return l`
2201
+ `,_w=900*1e3,Lw=750,Hs=[1e3,3e3,8e3,15e3,3e4],pn={capture:!0},ys="auto:on",hn="auto:off",si="theme:",Ss=Nt("core:workspace.files"),xs=Nt("core:workspace.git"),oi=Nt("core:workspace.terminal"),jw=320,Fw=2,Nw="(min-width: 1181px)";let ce=class extends C{constructor(){super(...arguments),this.state=xd(),this.sessions=new mh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new dh),this.activity=new kd(()=>this.state,e=>{this.setState(e)}),this.auth=new Rd(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Ah(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Ch),this.projects=new Ld(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new _d(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new Ad(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Od(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Uh,this.realtime=new hr,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Wh,this.terminalSelection=new zh,this.appShell=new Af(this),this.panelCollapse=new Uf(this),this.panelResize=new qf(this),this.navigationSections=new Nf(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=zw(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=ou()??tu,this.activeThemeId=ho,this.isRefreshingApp=!1,this.settingsSection=Mr(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.previousStackedWorkspaceLayout=this.appShell.isStackedWorkspaceLayout,this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode),this.normalizeMainViewForLayoutChange()}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,pn),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},_w),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()})}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,pn),this.systemLightThemeMedia?.removeEventListener("change",this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!Hw(this.state,e))return;const t=this.state;this.state={...this.state,...e},this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),Bw(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=Ar();await this.machines.loadMachines(e.machineId);const t=this.routeForSelectedMachine(e),i=this.state.machineStatuses[t.machineId??"local"];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,i)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}schedulePiWebStatusRefresh(e=Lw){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.refreshPiWebStatus()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshPiWebStatus(){const e=f(this.state);try{const t=await On.piWebStatus(e);f(this.state)===e&&this.setState({piWebStatus:t})}catch(t){f(this.state)===e&&this.setState({piWebStatus:void 0}),console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}async refreshWorkspaceActivity(e=f(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){const e=this.state.machines.length===0?[f(this.state)]:this.state.machines.filter(t=>Xa(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await gi.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(Ar(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=f(this.state),r=e.projectId===void 0||e.projectId===""?gn():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=r.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(n))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:this.appShell.normalizedMainView(s??e.view,e.sessionId!==void 0),selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const c=this.state.projects.find(p=>p.id===e.projectId);if(!c){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(c,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),f(this.state)!==o&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?gn():{selectedFilePath:ts(Ss,"file"),selectedDiffPath:ts(xs,"diff"),selectedTerminalId:ts(oi,"terminal")}}routeForSelectedMachine(e){const t=this.state.selectedMachine?.id??"local";return(e.machineId??"local")===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){ls(e,{replace:!0}),ae(Ss,"file",void 0,{replace:!0}),ae(xs,"diff",void 0,{replace:!0}),ae(oi,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.kind!=="remote"||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===""?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=Kw(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;const e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{const t=e.machineId??"local",i=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==""){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=Hs.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",r=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),n=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${n}${r===void 0?"":` ${r}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(o=>o.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e){this.chatView?.saveScrollPosition(),await e(),await this.updateComplete,await this.chatView?.updateComplete,await ks(),this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}normalizeMainViewForLayoutChange(){const e=this.previousStackedWorkspaceLayout,t=this.appShell.isStackedWorkspaceLayout;if(this.previousStackedWorkspaceLayout=t,e||!t)return;const i=this.appShell.normalizedMainView(this.state.mainView,this.state.selectedSession!==void 0);i!==this.state.mainView&&(this.setState({mainView:i}),this.updateUrl({replace:!0}))}updateUrl(e){this.rememberCurrentMachineNavigation(),ls({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView==="navigation"?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(gr(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(gr(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){ls(mr(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){ae(Ss,"file",e.selectedFilePath,{replace:!0}),ae(xs,"diff",e.selectedDiffPath,{replace:!0}),ae(oi,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??Oh(e.id);if(await this.restoreRouteFor(mr(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==""}openWorkspaceTool(e){e==="core:workspace.terminal"&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool("core:workspace.terminal")}terminalCommandRunsForOrigin(e,t=f(this.state)){const i=mn(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=lg(e,{api:{runTerminalCommand:(r,n)=>pt.runTerminalCommand(r,n,t),listCommandRuns:r=>pt.listCommandRuns(r,t),getCommandRun:r=>pt.getCommandRun(r,t)},openTerminal:(r,n)=>{this.openRuntimeTerminal(t,r,n)}});return this.terminalCommandRunRuntimes.set(i,o),o}async openRuntimeTerminal(e,t,i){if((f(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:"core:workspace.terminal",view:"core:workspace.terminal"},!1,{selectedTerminalId:i?.terminalId},"core:workspace.terminal"),f(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){ae(oi,"terminal",e,t)}terminalWorkspaceKey(e){return`${f(this.state)}:${e.path}`}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e="general"){this.settingsSection=e,cs(e)}closeSettings(){this.settingsSection=void 0,cs(void 0)}navigateSettings(e){this.settingsSection=e,cs(e)}restoreSettingsRoute(){this.settingsSection=Mr()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();const i=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:i}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(i,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}connectRealtime(){this.realtime.connect(e=>{this.handleRealtimeEvent(e)},()=>{const e=this.state.selectedWorkspace;e!==void 0&&this.refreshActiveTerminals(e),this.refreshWorkspaceActivity()},f(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new hr;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=f(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>Uw(t,this.state.machineStatuses[t.id])).map(t=>t.id))}handleMachineActivityEvent(e,t){t.type==="workspace.activity"&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e){e.type==="workspace.activity"?this.activity.applyWorkspaceActivity(e.activity):qw(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const t=this.state.selectedWorkspace;t===void 0||(e.type==="terminal.closed"?e.cwd:e.terminal.cwd)!==t.path||(e.type==="terminal.created"&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type==="terminal.closed"?e.terminalId:e.terminal.id),e.type==="terminal.closed"&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){const t=f(this.state);try{const i=await pt.terminals(e.projectId,e.id,t);if(f(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=fn(e),s=fn(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return l`
2202
2202
  <workspace-panel
2203
2203
  id="workspace-panel"
2204
2204
  .workspace=${e}
@@ -2244,7 +2244,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2244
2244
  .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
2245
2245
  .onReset=${()=>{this.resetResizablePanel("workspace")}}
2246
2246
  ></app-panel-edge-control>
2247
- `}startPanelResize(e){return e==="navigation"?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){const t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){const i=this.getBoundingClientRect().width||(typeof window>"u"?0:window.innerWidth);if(i<=0)return t.maxWidth;const s=this.oppositeResizablePanelWidth(e),o=Math.floor(i-s-jw-Lw);return Math.max(t.minWidth,Math.min(t.maxWidth,o))}oppositeResizablePanelWidth(e){const t=e==="navigation"?"workspace":"navigation";return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e==="navigation"?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>"u"||!("matchMedia"in window)?!0:window.matchMedia(Fw).matches}measuredPanelWidth(e){const i=(e==="navigation"?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return i===void 0||i<=0?void 0:i}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&_t(e,ht.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&_t(e,ht.sessionsReload)}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??"this machine"} to delete archived sessions.`}selectedMachineRuntime(){return this.state.machineRuntimes[f(this.state)]}renderNavigationPanel(){return l`
2247
+ `}startPanelResize(e){return e==="navigation"?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){const t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){const i=this.getBoundingClientRect().width||(typeof window>"u"?0:window.innerWidth);if(i<=0)return t.maxWidth;const s=this.oppositeResizablePanelWidth(e),o=Math.floor(i-s-Fw-jw);return Math.max(t.minWidth,Math.min(t.maxWidth,o))}oppositeResizablePanelWidth(e){const t=e==="navigation"?"workspace":"navigation";return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e==="navigation"?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>"u"||!("matchMedia"in window)?!0:window.matchMedia(Nw).matches}measuredPanelWidth(e){const i=(e==="navigation"?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return i===void 0||i<=0?void 0:i}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&Lt(e,ut.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&Lt(e,ut.sessionsReload)}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??"this machine"} to delete archived sessions.`}selectedMachineRuntime(){return this.state.machineRuntimes[f(this.state)]}renderNavigationPanel(){return l`
2248
2248
  <app-navigation-panel
2249
2249
  .machines=${this.state.machines}
2250
2250
  .selectedMachine=${this.state.selectedMachine}
@@ -2260,7 +2260,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2260
2260
  .workspacesByProjectId=${this.state.workspacesByProjectId}
2261
2261
  .workspaces=${this.state.workspaces}
2262
2262
  .selectedWorkspace=${this.state.selectedWorkspace}
2263
- .deletingWorkspaceIds=${Su(this.state.workspaceDeletionRuns)}
2263
+ .deletingWorkspaceIds=${xu(this.state.workspaceDeletionRuns)}
2264
2264
  .sessions=${this.state.sessions}
2265
2265
  .sessionStatuses=${this.state.sessionStatuses}
2266
2266
  .sessionActivities=${this.state.sessionActivities}
@@ -2300,14 +2300,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2300
2300
  .onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
2301
2301
  .onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
2302
2302
  ></app-navigation-panel>
2303
- `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()}),await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!Mi(this.state.machines)){await this.focusNavigationSection("projects");return}this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView("navigation"),this.navigationSections.expand(e),await this.updateComplete,await xs(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await xs(),this.promptEditor?.focusInput()}visibleWorkspacePanels(){const e=this.state.selectedWorkspace;if(e===void 0)return[];const t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(i=>i.visible?.(t)??!0)}workspacePanelEmptyState(){const e=this.state.selectedProject;return this.state.isLoadingProjects?{title:"正在加载项目…",body:"正在查找你已添加到 PI WEB 的项目。"}:e===void 0?this.state.projects.length===0?{title:"还没有项目",body:"使用“操作 → 添加项目”添加文件夹。选择工作区后,工作区工具会显示在这里。"}:{title:"选择项目",body:"从侧边栏选择一个项目,然后选择工作区来查看文件、Git 或终端。"}:this.state.isLoadingWorkspaces?{title:"正在加载工作区…",body:`正在为 ${e.name} 准备工作区工具。`}:this.state.workspaces.length===0?{title:"未找到工作区",body:`${e.name} 没有可用工作区。请尝试重新选择该项目,或重新添加它。`}:{title:"选择工作区",body:`选择 ${e.name} 中的工作区,以查看文件、Git 或终端。`}}sessionEmptyMessage(){return this.state.isLoadingProjects?"正在加载项目…":this.state.selectedWorkspace!==void 0?"选择或启动会话。":this.state.selectedProject!==void 0?"选择工作区以启动会话。":this.state.projects.length===0?"添加项目以启动会话。":"选择项目和工作区以开始会话。"}mobilePanelBadge(e){const t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case"core:workspace.files":return"files";case"core:workspace.git":return"git";case"core:workspace.terminal":return"terminal";default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){const t=hn(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:i=>Is.workspaceFile(e.projectId,e.id,i,t)}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=hn(this.state),i=t.id,s=o=>{const r=this.terminalCommandRunsForOrigin(o,i);return mf({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>r.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:r},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,onRefreshFiles:()=>{this.files.refreshFiles()},onUploadFiles:n=>{this.files.uploadFiles(n)},onCreateFile:n=>{this.files.createFile(n)},onCreateDirectory:n=>{this.files.createDirectory(n)},onMoveSelectedPath:n=>{this.files.moveSelectedPath(n)},onDeleteSelectedPath:()=>{this.files.deleteSelectedPath()},onDownloadSelectedFile:()=>{this.files.downloadSelectedFile()},onExpandDir:n=>{this.files.expandDir(n)},onSelectDirectory:n=>{this.files.selectDirectory(n)},onSelectFile:n=>{this.files.selectFile(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return rg(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.navigationFocusActions(),...this.panelLayoutActions()]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"重置导航面板宽度",description:"将导航面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"重置工作区面板宽度",description:"将工作区面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"重置面板宽度",description:"将所有侧边面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"聚焦机器",description:"将键盘焦点移到机器选择器",shortcut:"mod+g m",group:"导航",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"聚焦项目",description:"将键盘焦点移到项目列表",shortcut:"mod+g p",group:"导航",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"聚焦工作区",description:"将键盘焦点移到工作区列表",shortcut:"mod+g w",group:"导航",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"聚焦会话",description:"将键盘焦点移到会话列表",shortcut:"mod+g s",group:"导航",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>Pr())}async loadPluginsForSelectedMachine(){const e=this.state.selectedMachine;e?.kind==="remote"&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!=="remote"||this.loadedMachinePluginIds.has(e.id))return;const t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;const i=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>Pr(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:s=>this.plugins.shouldLoadRemotePlugin(s.id,s.machineSpecific)})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(o){console.warn(`Failed to register PI WEB plugin ${s.id}`,o)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPluginRuntimeContext(){const e=t=>gf({state:this.state,piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Ah(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(aa(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
2303
+ `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()}),await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!Ei(this.state.machines)){await this.focusNavigationSection("projects");return}this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView("navigation"),this.navigationSections.expand(e),await this.updateComplete,await ks(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await ks(),this.promptEditor?.focusInput()}visibleWorkspacePanels(){const e=this.state.selectedWorkspace;if(e===void 0)return[];const t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(i=>i.visible?.(t)??!0)}workspacePanelEmptyState(){const e=this.state.selectedProject;return this.state.isLoadingProjects?{title:"正在加载项目…",body:"正在查找你已添加到 PI WEB 的项目。"}:e===void 0?this.state.projects.length===0?{title:"还没有项目",body:"使用“操作 → 添加项目”添加文件夹。选择工作区后,工作区工具会显示在这里。"}:{title:"选择项目",body:"从侧边栏选择一个项目,然后选择工作区来查看文件、Git 或终端。"}:this.state.isLoadingWorkspaces?{title:"正在加载工作区…",body:`正在为 ${e.name} 准备工作区工具。`}:this.state.workspaces.length===0?{title:"未找到工作区",body:`${e.name} 没有可用工作区。请尝试重新选择该项目,或重新添加它。`}:{title:"选择工作区",body:`选择 ${e.name} 中的工作区,以查看文件、Git 或终端。`}}sessionEmptyMessage(){return this.state.isLoadingProjects?"正在加载项目…":this.state.selectedWorkspace!==void 0?"选择或启动会话。":this.state.selectedProject!==void 0?"选择工作区以启动会话。":this.state.projects.length===0?"添加项目以启动会话。":"选择项目和工作区以开始会话。"}mobilePanelBadge(e){const t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case"core:workspace.files":return"files";case"core:workspace.git":return"git";case"core:workspace.terminal":return"terminal";default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){const t=un(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:i=>Cs.workspaceFile(e.projectId,e.id,i,t)}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=un(this.state),i=t.id,s=o=>{const r=this.terminalCommandRunsForOrigin(o,i);return vf({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>r.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:r},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,onRefreshFiles:()=>{this.files.refreshFiles()},onUploadFiles:n=>{this.files.uploadFiles(n)},onCreateFile:n=>{this.files.createFile(n)},onCreateDirectory:n=>{this.files.createDirectory(n)},onMoveSelectedPath:n=>{this.files.moveSelectedPath(n)},onDeleteSelectedPath:()=>{this.files.deleteSelectedPath()},onDownloadSelectedFile:()=>{this.files.downloadSelectedFile()},onExpandDir:n=>{this.files.expandDir(n)},onSelectDirectory:n=>{this.files.selectDirectory(n)},onSelectFile:n=>{this.files.selectFile(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return ng(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.navigationFocusActions(),...this.panelLayoutActions()]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"重置导航面板宽度",description:"将导航面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"重置工作区面板宽度",description:"将工作区面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"重置面板宽度",description:"将所有侧边面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"聚焦机器",description:"将键盘焦点移到机器选择器",shortcut:"mod+g m",group:"导航",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"聚焦项目",description:"将键盘焦点移到项目列表",shortcut:"mod+g p",group:"导航",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"聚焦工作区",description:"将键盘焦点移到工作区列表",shortcut:"mod+g w",group:"导航",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"聚焦会话",description:"将键盘焦点移到会话列表",shortcut:"mod+g s",group:"导航",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>Rr())}async loadPluginsForSelectedMachine(){const e=this.state.selectedMachine;e?.kind==="remote"&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!=="remote"||this.loadedMachinePluginIds.has(e.id))return;const t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;const i=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>Rr(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:s=>this.plugins.shouldLoadRemotePlugin(s.id,s.machineSpecific)})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(o){console.warn(`Failed to register PI WEB plugin ${s.id}`,o)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPluginRuntimeContext(){const e=t=>mf({state:this.state,piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Mh(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(la(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
2304
2304
 
2305
2305
  This will run git worktree remove and delete:
2306
2306
  ${e.path}
2307
2307
 
2308
- The Git branch will not be deleted.`))return;const s=f(this.state);try{const o=await Is.deleteWorkspace(e.projectId,e.id,s);if(f(this.state)!==s)return;this.recordWorkspaceDeletionRun(o,s);const r=await this.workspaceForCommandRun(o);if(f(this.state)!==s)return;r!==void 0&&this.openRuntimeTerminal(s,r,{terminalId:o.terminalId})}catch(o){f(this.state)===s&&this.setState({error:`启动工作区删除失败:${Kw(o)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(i=>i.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(f(this.state)!==t)return;const i=Ws(e);i!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[i]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;const e=f(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{const i=await this.terminalCommandRunsForOrigin("core",e).listCommandRuns(wu(t.id));if(f(this.state)!==e)return;const s=yu(i);this.setState({workspaceDeletionRuns:s});for(const o of Object.values(s))xi(o)||await this.handleCompletedWorkspaceDeletionRun(o,e)}catch(i){console.warn("Failed to refresh workspace deletion runs",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(xi);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=f(this.state)){if(f(this.state)!==t)return;const i=gn(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Ws(e);if(s!==void 0){if(this.handledWorkspaceDeletionRunIds.add(i),e.status==="succeeded"){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,s),f(this.state)!==t)return;this.setState({workspaceDeletionRuns:Vw(this.state.workspaceDeletionRuns,s)}),this.updateWorkspaceDeletionPolling();return}e.status==="failed"&&(this.setState({error:"工作区删除失败。请查看终端输出。"}),this.updateWorkspaceDeletionPolling())}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:""})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind==="local"||!window.confirm(`移除 ${e.name}?
2308
+ The Git branch will not be deleted.`))return;const s=f(this.state);try{const o=await Cs.deleteWorkspace(e.projectId,e.id,s);if(f(this.state)!==s)return;this.recordWorkspaceDeletionRun(o,s);const r=await this.workspaceForCommandRun(o);if(f(this.state)!==s)return;r!==void 0&&this.openRuntimeTerminal(s,r,{terminalId:o.terminalId})}catch(o){f(this.state)===s&&this.setState({error:`启动工作区删除失败:${Vw(o)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(i=>i.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(f(this.state)!==t)return;const i=Os(e);i!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[i]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;const e=f(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{const i=await this.terminalCommandRunsForOrigin("core",e).listCommandRuns(yu(t.id));if(f(this.state)!==e)return;const s=Su(i);this.setState({workspaceDeletionRuns:s});for(const o of Object.values(s))ki(o)||await this.handleCompletedWorkspaceDeletionRun(o,e)}catch(i){console.warn("Failed to refresh workspace deletion runs",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(ki);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=f(this.state)){if(f(this.state)!==t)return;const i=mn(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Os(e);if(s!==void 0){if(this.handledWorkspaceDeletionRunIds.add(i),e.status==="succeeded"){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,s),f(this.state)!==t)return;this.setState({workspaceDeletionRuns:Gw(this.state.workspaceDeletionRuns,s)}),this.updateWorkspaceDeletionPolling();return}e.status==="failed"&&(this.setState({error:"工作区删除失败。请查看终端输出。"}),this.updateWorkspaceDeletionPolling())}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:""})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind==="local"||!window.confirm(`移除 ${e.name}?
2309
2309
 
2310
- 这只会从当前 PI WEB 网关移除它。`))return;const t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();const i=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(s=>s.id===e.id)||this.machineNavigation.forget(e.id),t&&i!==void 0&&await this.selectMachineWithMemory(i,{rememberCurrent:!1})}openSelectedMachine(){const e=this.state.selectedMachine;e?.kind!=="remote"||e.baseUrl===void 0||window.open(e.baseUrl,"_blank","noopener,noreferrer")}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{const i=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`操作失败:${i}`})})}async openModelDialog(){const e=await this.sessions.listModels(),t=this.state.status?.model?.provider,i=this.state.status?.model?.id;this.setState({modelDialog:{title:"选择模型",...t!==void 0&&i!==void 0?{selectedValue:`${t}/${i}`}:{},options:e.map(s=>{const o=s.provider??"",r=s.id??"",n=o===t&&r===i;return{value:`${o}/${r}`,label:`${r}${n?" ✓ 当前":""}`,description:o}})}})}async pickModel(e){this.setState({modelDialog:void 0});const t=e.indexOf("/");t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){const e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?pn:ws;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${ii}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开启":"关闭"}`,description:this.autoThemeDescription(t)},...e.map(o=>({value:`${ii}${o.id}`,label:this.themeOptionLabel(o,i),description:this.themeOptionDescription(o)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===ws||e===pn){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===ws},this.applyPreferredTheme(!0);return}if(!e.startsWith(ii))return;const t=e.slice(ii.length),i=this.plugins.getThemes().find(s=>s.id===t);i!==void 0&&(this.themePreference={themeId:i.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){const t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,ru(t),e&&ou(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return nu({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return na(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?"当所选主题有配对主题时,跟随系统明暗偏好。":e.selectedThemePair===void 0?"已开启,但所选主题没有明暗配对,因此会保持当前主题。":`已开启 · ${e.selectedThemePair.name} 跟随系统${this.systemPrefersLight()?"浅色":"深色"}偏好。`}themeOptionLabel(e,t){const i=[...e.id===t?["已选择"]:[],...e.id===this.activeThemeId&&e.id!==t?["生效中"]:[]];return i.length===0?e.name:`${e.name} ✓ ${i.join(" · ")}`}themeOptionDescription(e){const t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push("自动配对"),e.description!==void 0&&t.push(e.description),t.join(" · ")}async openThinkingDialog(){const e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??"off";this.setState({thinkingDialog:{title:"选择思考级别",selectedValue:t,options:e.map(i=>{const s=Gw(i);return{value:i,label:`${i}${i===t?" ✓ 当前":""}`,...s===void 0?{}:{description:s}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==""&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t,i,s){!(i!==void 0&&i.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,i,s)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
2310
+ 这只会从当前 PI WEB 网关移除它。`))return;const t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();const i=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(s=>s.id===e.id)||this.machineNavigation.forget(e.id),t&&i!==void 0&&await this.selectMachineWithMemory(i,{rememberCurrent:!1})}openSelectedMachine(){const e=this.state.selectedMachine;e?.kind!=="remote"||e.baseUrl===void 0||window.open(e.baseUrl,"_blank","noopener,noreferrer")}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{const i=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`操作失败:${i}`})})}async openModelDialog(){const e=await this.sessions.listModels(),t=this.state.status?.model?.provider,i=this.state.status?.model?.id;this.setState({modelDialog:{title:"选择模型",...t!==void 0&&i!==void 0?{selectedValue:`${t}/${i}`}:{},options:e.map(s=>{const o=s.provider??"",r=s.id??"",n=o===t&&r===i;return{value:`${o}/${r}`,label:`${r}${n?" ✓ 当前":""}`,description:o}})}})}async pickModel(e){this.setState({modelDialog:void 0});const t=e.indexOf("/");t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){const e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?hn:ys;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${si}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开启":"关闭"}`,description:this.autoThemeDescription(t)},...e.map(o=>({value:`${si}${o.id}`,label:this.themeOptionLabel(o,i),description:this.themeOptionDescription(o)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===ys||e===hn){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===ys},this.applyPreferredTheme(!0);return}if(!e.startsWith(si))return;const t=e.slice(si.length),i=this.plugins.getThemes().find(s=>s.id===t);i!==void 0&&(this.themePreference={themeId:i.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){const t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,nu(t),e&&ru(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return au({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return aa(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?"当所选主题有配对主题时,跟随系统明暗偏好。":e.selectedThemePair===void 0?"已开启,但所选主题没有明暗配对,因此会保持当前主题。":`已开启 · ${e.selectedThemePair.name} 跟随系统${this.systemPrefersLight()?"浅色":"深色"}偏好。`}themeOptionLabel(e,t){const i=[...e.id===t?["已选择"]:[],...e.id===this.activeThemeId&&e.id!==t?["生效中"]:[]];return i.length===0?e.name:`${e.name} ✓ ${i.join(" · ")}`}themeOptionDescription(e){const t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push("自动配对"),e.description!==void 0&&t.push(e.description),t.join(" · ")}async openThinkingDialog(){const e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??"off";this.setState({thinkingDialog:{title:"选择思考级别",selectedValue:t,options:e.map(i=>{const s=Jw(i);return{value:i,label:`${i}${i===t?" ✓ 当前":""}`,...s===void 0?{}:{description:s}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==""&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t,i,s){!(i!==void 0&&i.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,i,s)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
2311
2311
  <app-context-bar
2312
2312
  .machines=${this.state.machines}
2313
2313
  .machine=${this.state.selectedMachine}
@@ -2328,7 +2328,7 @@ The Git branch will not be deleted.`))return;const s=f(this.state);try{const o=a
2328
2328
  <div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints("navigation"),workspace:this.resizablePanelConstraints("workspace")})}>
2329
2329
  <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
2330
2330
  ${this.renderNavigationPanelEdgeControl()}
2331
- <main class=${fa(e.mainView)}>
2331
+ <main class=${ga(e.mainView)}>
2332
2332
  ${this.renderContextBar()}
2333
2333
  ${this.renderMobileMainTabs()}
2334
2334
  ${e.error?l`<div class="error">${e.error}</div>`:null}
@@ -2351,4 +2351,4 @@ The Git branch will not be deleted.`))return;const s=f(this.state);try{const o=a
2351
2351
  ${e.themeDialog!==void 0?l`<command-picker title=${e.themeDialog.title} .options=${e.themeDialog.options} .selectedValue=${e.themeDialog.selectedValue} .onPick=${t=>{this.pickTheme(t)}} .onCancel=${()=>{this.setState({themeDialog:void 0})}}></command-picker>`:null}
2352
2352
  ${this.settingsSection!==void 0?l`<settings-dialog .section=${this.settingsSection} .actions=${this.getDefaultActions()} .onNavigate=${t=>{this.navigateSettings(t)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${t=>{this.applyClientConfig(t)}}></settings-dialog>`:null}
2353
2353
  </div>
2354
- `}};ce.styles=Ww;Te([k()],ce.prototype,"state",2);Te([B("chat-view")],ce.prototype,"chatView",2);Te([B("prompt-editor")],ce.prototype,"promptEditor",2);Te([B("app-navigation-panel")],ce.prototype,"navigationPanel",2);Te([B("#navigation-panel")],ce.prototype,"navigationPanelFrame",2);Te([B("#workspace-panel")],ce.prototype,"workspacePanelFrame",2);Te([k()],ce.prototype,"activeThemeId",2);Te([k()],ce.prototype,"isRefreshingApp",2);Te([k()],ce.prototype,"settingsSection",2);Te([k()],ce.prototype,"shortcutConfig",2);ce=Te([W("pi-web-app")],ce);function Nw(){const e=new uf;return e.register({id:"core",plugin:Ju}),e.register({id:"themes",plugin:Yu}),e}function hn(e){const t=e.selectedMachine;return t!==void 0?{id:t.id,name:t.name,kind:t.kind}:{id:"local",name:"local",kind:"local"}}function zw(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function Bw(e,t){return Za(e,t)}function Za(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function Uw(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function un(e){return Xe(e.status,e.activity)}function Hw(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function fn(){return{}}function gn(e,t){return JSON.stringify([e,t])}function qw(e){const t=Math.min(e,Us.length-1);return Us[t]??3e4}function Kw(e){return e instanceof Error?e.message:String(e)}function Vw(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function xs(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function Gw(e){switch(e){case"off":return"不使用推理";case"minimal":return"极简推理(约 1k tokens)";case"low":return"轻量推理(约 2k tokens)";case"medium":return"中等推理(约 8k tokens)";case"high":return"深度推理(约 16k tokens)";case"xhigh":return"最大推理(约 32k tokens)";default:return}}export{D as a,l as b,dt as c,ay as d,B as e,ry as f,C as i,d as n,k as r,ny as s,W as t};
2354
+ `}};ce.styles=Ow;Te([k()],ce.prototype,"state",2);Te([B("chat-view")],ce.prototype,"chatView",2);Te([B("prompt-editor")],ce.prototype,"promptEditor",2);Te([B("app-navigation-panel")],ce.prototype,"navigationPanel",2);Te([B("#navigation-panel")],ce.prototype,"navigationPanelFrame",2);Te([B("#workspace-panel")],ce.prototype,"workspacePanelFrame",2);Te([k()],ce.prototype,"activeThemeId",2);Te([k()],ce.prototype,"isRefreshingApp",2);Te([k()],ce.prototype,"settingsSection",2);Te([k()],ce.prototype,"shortcutConfig",2);ce=Te([W("pi-web-app")],ce);function zw(){const e=new ff;return e.register({id:"core",plugin:Qu}),e.register({id:"themes",plugin:ef}),e}function un(e){const t=e.selectedMachine;return t!==void 0?{id:t.id,name:t.name,kind:t.kind}:{id:"local",name:"local",kind:"local"}}function Bw(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function Uw(e,t){return Xa(e,t)}function Xa(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function Hw(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function fn(e){return Ye(e.status,e.activity)}function qw(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function gn(){return{}}function mn(e,t){return JSON.stringify([e,t])}function Kw(e){const t=Math.min(e,Hs.length-1);return Hs[t]??3e4}function Vw(e){return e instanceof Error?e.message:String(e)}function Gw(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function ks(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function Jw(e){switch(e){case"off":return"不使用推理";case"minimal":return"极简推理(约 1k tokens)";case"low":return"轻量推理(约 2k tokens)";case"medium":return"中等推理(约 8k tokens)";case"high":return"深度推理(约 16k tokens)";case"xhigh":return"最大推理(约 32k tokens)";default:return}}export{D as a,l as b,pt as c,ly as d,B as e,ny as f,C as i,d as n,k as r,ay as s,W as t};