@chainingintention/pi-web-cn 1.202607.3-beta.0 → 1.202607.3

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,29 +1,29 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-B9FasHbW.js","assets/vendor-editor-core-C7aWiQy0.js","assets/vendor-editor-languages-EW34FfVy.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/UnifiedDiffViewer-ChTX4eDR.js","assets/TerminalPanel-BSE17h19.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
- import{Q as ro,v as it,J as us,R as cc,S as dc,G as pc,U as hc,V as uc,W as fc,A as gc,X as mc,Y as vc,Z as oo,w as no,_ as bc}from"./vendor-editor-core-C7aWiQy0.js";import{m as wc,d as yc,i as xc}from"./vendor-editor-languages-EW34FfVy.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const n of o.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=i(r);fetch(r.href,o)}})();const fi=globalThis,dr=fi.ShadowRoot&&(fi.ShadyCSS===void 0||fi.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,pr=Symbol(),ao=new WeakMap;let fa=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==pr)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(dr&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=ao.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&ao.set(i,t))}return t}toString(){return this.cssText}};const Sc=e=>new fa(typeof e=="string"?e:e+"",void 0,pr),E=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,r,o)=>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.")})(r)+e[o+1],e[0]);return new fa(i,e,pr)},kc=(e,t)=>{if(dr)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),r=fi.litNonce;r!==void 0&&s.setAttribute("nonce",r),s.textContent=i.cssText,e.appendChild(s)}},lo=dr?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return Sc(i)})(e):e;const{is:$c,defineProperty:Pc,getOwnPropertyDescriptor:Cc,getOwnPropertyNames:Ic,getOwnPropertySymbols:Rc,getPrototypeOf:Ac}=Object,Vi=globalThis,co=Vi.trustedTypes,Tc=co?co.emptyScript:"",Mc=Vi.reactiveElementPolyfillSupport,Bt=(e,t)=>e,$i={toAttribute(e,t){switch(t){case Boolean:e=e?Tc: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}},hr=(e,t)=>!$c(e,t),po={attribute:!0,type:String,converter:$i,reflect:!1,useDefault:!1,hasChanged:hr};Symbol.metadata??=Symbol("metadata"),Vi.litPropertyMetadata??=new WeakMap;let bt=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=po){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(),r=this.getPropertyDescriptor(t,s,i);r!==void 0&&Pc(this.prototype,t,r)}}static getPropertyDescriptor(t,i,s){const{get:r,set:o}=Cc(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:r,set(n){const a=r?.call(this);o?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??po}static _$Ei(){if(this.hasOwnProperty(Bt("elementProperties")))return;const t=Ac(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Bt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Bt("properties"))){const i=this.properties,s=[...Ic(i),...Rc(i)];for(const r of s)this.createProperty(r,i[r])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,r]of i)this.elementProperties.set(s,r)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const r=this._$Eu(i,s);r!==void 0&&this._$Eh.set(r,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 r of s)i.unshift(lo(r))}else t!==void 0&&i.push(lo(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 kc(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),r=this.constructor._$Eu(t,s);if(r!==void 0&&s.reflect===!0){const o=(s.converter?.toAttribute!==void 0?s.converter:$i).toAttribute(i,s.type);this._$Em=t,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(t,i){const s=this.constructor,r=s._$Eh.get(t);if(r!==void 0&&this._$Em!==r){const o=s.getPropertyOptions(r),n=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:$i;this._$Em=r;const a=n.fromAttribute(i,o.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(t,i,s,r=!1,o){if(t!==void 0){const n=this.constructor;if(r===!1&&(o=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??hr)(o,i)||s.useDefault&&s.reflect&&o===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:r,wrapped:o},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),o!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),r===!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[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,o]of s){const{wrapped:n}=o,a=this[r];n!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,o,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){}};bt.elementStyles=[],bt.shadowRootOptions={mode:"open"},bt[Bt("elementProperties")]=new Map,bt[Bt("finalized")]=new Map,Mc?.({ReactiveElement:bt}),(Vi.reactiveElementVersions??=[]).push("2.1.2");const ur=globalThis,ho=e=>e,Pi=ur.trustedTypes,uo=Pi?Pi.createPolicy("lit-html",{createHTML:e=>e}):void 0,ga="$lit$",Ze=`lit$${Math.random().toFixed(9).slice(2)}$`,ma="?"+Ze,Ec=`<${ma}>`,ct=document,qt=()=>ct.createComment(""),Ht=e=>e===null||typeof e!="object"&&typeof e!="function",fr=Array.isArray,Dc=e=>fr(e)||typeof e?.[Symbol.iterator]=="function",fs=`[
3
- \f\r]`,Tt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,fo=/-->/g,go=/>/g,st=RegExp(`>|${fs}(?:([^\\s"'>=/]+)(${fs}*=${fs}*(?:[^
4
- \f\r"'\`<>=]|("|')|))|$)`,"g"),mo=/'/g,vo=/"/g,va=/^(?:script|style|textarea|title)$/i,ba=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=ba(1),be=ba(2),Xe=Symbol.for("lit-noChange"),z=Symbol.for("lit-nothing"),bo=new WeakMap,at=ct.createTreeWalker(ct,129);function wa(e,t){if(!fr(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return uo!==void 0?uo.createHTML(t):t}const Wc=(e,t)=>{const i=e.length-1,s=[];let r,o=t===2?"<svg>":t===3?"<math>":"",n=Tt;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===Tt?u[1]==="!--"?n=fo:u[1]!==void 0?n=go:u[2]!==void 0?(va.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=st):u[3]!==void 0&&(n=st):n===st?u[0]===">"?(n=r??Tt,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?st:u[3]==='"'?vo:mo):n===vo||n===mo?n=st:n===fo||n===go?n=Tt:(n=st,r=void 0);const w=n===st&&e[a+1].startsWith("/>")?" ":"";o+=n===Tt?c+Ec:h>=0?(s.push(p),c.slice(0,h)+ga+c.slice(h)+Ze+w):c+Ze+(h===-2?a:w)}return[wa(e,o+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Kt{constructor({strings:t,_$litType$:i},s){let r;this.parts=[];let o=0,n=0;const a=t.length-1,c=this.parts,[p,u]=Wc(t,i);if(this.el=Kt.createElement(p,s),at.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(r=at.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const h of r.getAttributeNames())if(h.endsWith(ga)){const g=u[n++],w=r.getAttribute(h).split(Ze),P=/([.?@])?(.*)/.exec(g);c.push({type:1,index:o,name:P[2],strings:w,ctor:P[1]==="."?_c:P[1]==="?"?Lc:P[1]==="@"?jc:Gi}),r.removeAttribute(h)}else h.startsWith(Ze)&&(c.push({type:6,index:o}),r.removeAttribute(h));if(va.test(r.tagName)){const h=r.textContent.split(Ze),g=h.length-1;if(g>0){r.textContent=Pi?Pi.emptyScript:"";for(let w=0;w<g;w++)r.append(h[w],qt()),at.nextNode(),c.push({type:2,index:++o});r.append(h[g],qt())}}}else if(r.nodeType===8)if(r.data===ma)c.push({type:2,index:o});else{let h=-1;for(;(h=r.data.indexOf(Ze,h+1))!==-1;)c.push({type:7,index:o}),h+=Ze.length-1}o++}}static createElement(t,i){const s=ct.createElement("template");return s.innerHTML=t,s}}function St(e,t,i=e,s){if(t===Xe)return t;let r=s!==void 0?i._$Co?.[s]:i._$Cl;const o=Ht(t)?void 0:t._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(e),r._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=r:i._$Cl=r),r!==void 0&&(t=St(e,r._$AS(e,t.values),r,s)),t}class Oc{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,r=(t?.creationScope??ct).importNode(i,!0);at.currentNode=r;let o=at.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new Ct(o,o.nextSibling,this,t):c.type===1?p=new c.ctor(o,c.name,c.strings,this,t):c.type===6&&(p=new Fc(o,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(o=at.nextNode(),n++)}return at.currentNode=ct,r}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 Ct{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,r){this.type=2,this._$AH=z,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=r,this._$Cv=r?.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=St(this,t,i),Ht(t)?t===z||t==null||t===""?(this._$AH!==z&&this._$AR(),this._$AH=z):t!==this._$AH&&t!==Xe&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Dc(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!==z&&Ht(this._$AH)?this._$AA.nextSibling.data=t:this.T(ct.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,r=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Kt.createElement(wa(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(i);else{const o=new Oc(r,this),n=o.u(this.options);o.p(i),this.T(n),this._$AH=o}}_$AC(t){let i=bo.get(t.strings);return i===void 0&&bo.set(t.strings,i=new Kt(t)),i}k(t){fr(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,r=0;for(const o of t)r===i.length?i.push(s=new Ct(this.O(qt()),this.O(qt()),this,this.options)):s=i[r],s._$AI(o),r++;r<i.length&&(this._$AR(s&&s._$AB.nextSibling,r),i.length=r)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=ho(t).nextSibling;ho(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Gi=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,r,o){this.type=1,this._$AH=z,this._$AN=void 0,this.element=t,this.name=i,this._$AM=r,this.options=o,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=z}_$AI(t,i=this,s,r){const o=this.strings;let n=!1;if(o===void 0)t=St(this,t,i,0),n=!Ht(t)||t!==this._$AH&&t!==Xe,n&&(this._$AH=t);else{const a=t;let c,p;for(t=o[0],c=0;c<o.length-1;c++)p=St(this,a[s+c],i,c),p===Xe&&(p=this._$AH[c]),n||=!Ht(p)||p!==this._$AH[c],p===z?t=z:t!==z&&(t+=(p??"")+o[c+1]),this._$AH[c]=p}n&&!r&&this.j(t)}j(t){t===z?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},_c=class extends Gi{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===z?void 0:t}},Lc=class extends Gi{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==z)}},jc=class extends Gi{constructor(t,i,s,r,o){super(t,i,s,r,o),this.type=5}_$AI(t,i=this){if((t=St(this,t,i,0)??z)===Xe)return;const s=this._$AH,r=t===z&&s!==z||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,o=t!==z&&(s===z||r);r&&this.element.removeEventListener(this.name,this,s),o&&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)}},Fc=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){St(this,t)}};const Uc={I:Ct},zc=ur.litHtmlPolyfillSupport;zc?.(Kt,Ct),(ur.litHtmlVersions??=[]).push("3.3.3");const Bc=(e,t,i)=>{const s=i?.renderBefore??t;let r=s._$litPart$;if(r===void 0){const o=i?.renderBefore??null;s._$litPart$=r=new Ct(t.insertBefore(qt(),o),o,void 0,i??{})}return r._$AI(e),r};const gr=globalThis;let A=class extends bt{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=Bc(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Xe}};A._$litElement$=!0,A.finalized=!0,gr.litElementHydrateSupport?.({LitElement:A});const Nc=gr.litElementPolyfillSupport;Nc?.({LitElement:A});(gr.litElementVersions??=[]).push("4.2.2");const W=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const qc={attribute:!0,type:String,converter:$i,reflect:!1,hasChanged:hr},Hc=(e=qc,t,i)=>{const{kind:s,metadata:r}=i;let o=globalThis.litPropertyMetadata.get(r);if(o===void 0&&globalThis.litPropertyMetadata.set(r,o=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),o.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"?Hc(e,t,i):((s,r,o)=>{const n=r.hasOwnProperty(o);return r.constructor.createProperty(o,s),n?Object.getOwnPropertyDescriptor(r,o):void 0})(e,t,i)}function x(e){return d({...e,state:!0,attribute:!1})}const Kc=(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,r)=>{const o=n=>n.renderRoot?.querySelector(e)??null;return Kc(i,s,{get(){return o(this)}})}}function mr(e=br()){return vr(e)===void 0?"normal":"management"}function Ji(e,t=br(),i="management"){if(i==="normal"||t===void 0)return e;const s=vr(t);if(s===void 0)return e;const r=new URL(e,t.origin);return r.searchParams.set("embed",s.embed),r.searchParams.set("token",s.token),`${r.pathname}${r.search}${r.hash}`}function ya(e,t=br(),i="management"){if(i==="normal"||t===void 0)return e;const s=vr(t);if(s===void 0)return e;const r=new URL(e,t.origin);return r.searchParams.set("embed",s.embed),r.searchParams.set("token",s.token),`${r.pathname}${r.search}`}function vr(e){if(e===void 0)return;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 br(){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}`)}let xa=mr();function Vc(e){xa=e}function wr(e){return Ji(e,void 0,xa)}async function v(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&!s.has("content-type")&&s.set("content-type","application/json");const r=await fetch(wr(e),{...i,headers:s});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(Sa(n)??r.statusText)}const o=await r.json();return t(o)}async function Gc(e,t){const i=await fetch(wr(e));if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Sa(s)??i.statusText)}return t(await i.json())}}function Sa(e){if(Jc(e))return typeof e.error=="string"?e.error:void 0}function Jc(e){return typeof e=="object"&&e!==null}function Ne(e){return typeof e=="object"&&e!==null}function y(e){if(!Ne(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 H(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function ne(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 D(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function j(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function et(e,t){if(y(e)[t]!==!0)throw new Error(`Expected ${t} response`);return!0}function b(e,t){return t===void 0?{}:{[e]:t}}const Oe={sessionsDeleteArchived:"sessions.deleteArchived",sessionsBulkMutations:"sessions.bulkMutations",sessionsCleanup:"sessions.cleanup",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments",workspaceFileSuggestions:"workspace.fileSuggestions"},Qc=Object.values(Oe),Zc=new Set(Qc);function Xc(e){return typeof e=="string"&&Zc.has(e)}function Be(e,t){return e?.capabilities?.includes(t)===!0}function wo(e){const t=y(e);return{path:m(t,"path"),exists:D(t,"exists"),config:yo(t.config),effectiveConfig:yo(t.effectiveConfig),envOverrides:od(t.envOverrides)}}function yo(e){const t=y(e);return{...b("host",$(t,"host")),...b("port",ne(t,"port")),...b("allowedHosts",Yc(t.allowedHosts)),...b("shortcuts",sd(t.shortcuts)),...b("plugins",rd(t.plugins)),...b("pathAccess",ed(t.pathAccess)),...b("uploads",id(t.uploads)),...b("maxUploadBytes",ne(t,"maxUploadBytes")),...b("spawnSessions",So(t,"spawnSessions")),...b("subsessions",So(t,"subsessions"))}}function Yc(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 ed(e){if(e===void 0)return;if(!Ne(e)||Array.isArray(e))throw new Error("Invalid PI WEB pathAccess field");const t=e.allowedPaths;return{...b("allowedPaths",td(t,"pathAccess.allowedPaths"))}}function td(e,t){if(e!==void 0){if(Array.isArray(e)&&e.every(i=>typeof i=="string"&&i!==""))return e;throw new Error(`Invalid PI WEB ${t} field`)}}function id(e){if(e!==void 0){if(!Ne(e)||Array.isArray(e))throw new Error("Invalid PI WEB uploads field");return{...b("defaultFolder",$(e,"defaultFolder"))}}}function sd(e){if(e!==void 0){if(!Ne(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 rd(e){if(e!==void 0){if(!Ne(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!Ne(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 r=i.settings;if(r!==void 0&&(!Ne(r)||Array.isArray(r)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function od(e){const t=y(e);return{host:D(t,"host"),port:D(t,"port"),allowedHosts:D(t,"allowedHosts"),spawnSessions:D(t,"spawnSessions"),subsessions:D(t,"subsessions")}}function nd(e){const t=y(e);return{plugins:j(ad)(t.plugins)}}function ad(e){const t=y(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:ld(t.scope),machineSpecific:vd(t.machineSpecific,"machineSpecific")??!1,enabled:D(t,"enabled")}}function ld(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function cd(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:pd(t.components),release:ud(t.release),commands:fd(t.commands),messages:j(gd)(t.messages)}}function dd(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:ka(t.components),capabilities:yr(t.capabilities)}}function pd(e){const t=y(e);return{web:Ci(t.web),sessiond:Ci(t.sessiond)}}function ka(e){const t=y(e);return{web:xo(t.web),sessiond:xo(t.sessiond)}}function xo(e){const t=y(e);return{component:$a(t.component),label:m(t,"label"),...b("runtimeVersion",$(t,"runtimeVersion")),available:D(t,"available"),capabilities:yr(t.capabilities),...b("error",$(t,"error"))}}function Ci(e){const t=y(e);return{component:$a(t.component),label:m(t,"label"),...b("runtimeVersion",$(t,"runtimeVersion")),...b("installedVersion",$(t,"installedVersion")),stale:D(t,"stale"),available:D(t,"available"),...b("installation",hd(t.installation)),...b("error",$(t,"error"))}}function hd(e){if(e===void 0)return;const t=y(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,...b("path",$(t,"path")),...b("source",$(t,"source")),...s===void 0?{}:{scope:s},...b("npmRoot",$(t,"npmRoot"))}}function ud(e){const t=y(e);return{packageName:m(t,"packageName"),...b("latestVersion",$(t,"latestVersion")),updateAvailable:D(t,"updateAvailable"),...b("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...b("error",$(t,"error"))}}function fd(e){const t=y(e);return{...b("update",$(t,"update")),...b("restart",$(t,"restart")),...b("restartWeb",$(t,"restartWeb")),...b("restartSessiond",$(t,"restartSessiond")),...b("status",$(t,"status"))}}function gd(e){const t=y(e);return{id:m(t,"id"),severity:md(t.severity),title:m(t,"title"),body:m(t,"body"),...b("command",$(t,"command"))}}function $a(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function yr(e){if(!Array.isArray(e)||!e.every(Xc))throw new Error("Invalid PI WEB capabilities");return e}function md(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function vd(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function So(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 bd(e){const t=y(e);return j(Pa)(t.machines)}function Pa(e){const t=y(e),i=xd(t,"kind"),s=$(t,"baseUrl"),r=Ca(t,"status"),o=$(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"),...r===void 0?{}:{status:r},...o===void 0?{}:{statusMessage:o}}}function wd(e){const t=y(e),i=Ca(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:D(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:Ci(t.web)},...t.sessiond===void 0?{}:{sessiond:Ci(t.sessiond)},...s===void 0?{}:{error:s}}}function yd(e){const t=y(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:D(t,"ok"),checkedAt:m(t,"checkedAt"),...b("packageName",$(t,"packageName")),...b("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:ka(t.components)},...t.capabilities===void 0?{}:{capabilities:yr(t.capabilities)},...i===void 0?{}:{error:i}}}function xd(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function Ca(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 Sd(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function kt(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function kd(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=y(e);return{messages:Sd(t.messages),start:H(t,"start"),total:H(t,"total")}}function ko(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function $d(e){const t=y(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:D(t,"isMain"),isGitRepo:D(t,"isGitRepo"),isGitWorktree:D(t,"isGitWorktree"),...b("effectiveConfig",Pd(t.effectiveConfig))}}function Pd(e){if(e!==void 0){if(!Ne(e)||Array.isArray(e))throw new Error("Invalid workspace effectiveConfig field");return{...b("uploads",pp(e.uploads))}}}function Bs(e){const t=y(e);return{path:m(t,"path"),size:H(t,"size"),modifiedAt:m(t,"modifiedAt")}}function $o(e){const t=y(e);return{path:m(t,"path")}}function Cd(e){const t=y(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function Ns(e){const t=y(e),i=$(t,"name"),s=$(t,"parentSessionPath"),r=$(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:H(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...r===void 0?{}:{archivedAt:r}}}function Mt(e){const t=y(e);return{sessionId:m(t,"sessionId"),isStreaming:D(t,"isStreaming"),isCompacting:D(t,"isCompacting"),isBashRunning:D(t,"isBashRunning"),pendingMessageCount:H(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:j(Dd)(t.queuedMessages),...b("messageCount",ne(t,"messageCount")),tokens:Wd(t.tokens),cost:H(t,"cost"),...Ld(t.model),...Qd(t.contextUsage),...b("thinkingLevel",$(t,"thinkingLevel"))}}function Ia(e){const t=y(e),i=t.skippedBusySessionIds===void 0?void 0:kt(t.skippedBusySessionIds,"skippedBusySessionIds");return{generatedAt:m(t,"generatedAt"),thresholds:Td(t.thresholds),projects:j(Md)(t.projects),totals:Ed(t.totals),...i===void 0?{}:{skippedBusySessionIds:i}}}function Id(e){const t=y(e);return{...Ia(t),archivedSessionIds:kt(t.archivedSessionIds,"archivedSessionIds"),deletedSessionIds:kt(t.deletedSessionIds,"deletedSessionIds")}}function Rd(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected bulk archived response");return{archived:!0,archivedSessionIds:kt(t.archivedSessionIds,"archivedSessionIds"),failures:j(Ra)(t.failures),generatedAt:m(t,"generatedAt")}}function Ad(e){const t=y(e);if(t.deleted!==!0)throw new Error("Expected bulk deleted response");return{deleted:!0,deletedSessionIds:kt(t.deletedSessionIds,"deletedSessionIds"),failures:j(Ra)(t.failures),generatedAt:m(t,"generatedAt")}}function Ra(e){const t=y(e);return{sessionId:m(t,"sessionId"),error:m(t,"error")}}function Td(e){const t=y(e);return{...b("archiveIdleDays",ne(t,"archiveIdleDays")),...b("deleteArchivedDays",ne(t,"deleteArchivedDays"))}}function Md(e){const t=y(e);return{cwd:m(t,"cwd"),archiveCount:H(t,"archiveCount"),deleteCount:H(t,"deleteCount")}}function Ed(e){const t=y(e);return{archiveCount:H(t,"archiveCount"),deleteCount:H(t,"deleteCount")}}function Dd(e){const t=y(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text"),...b("imageCount",ne(t,"imageCount"))}}function Wd(e){const t=y(e);return{input:H(t,"input"),output:H(t,"output"),cacheRead:H(t,"cacheRead"),cacheWrite:H(t,"cacheWrite"),total:H(t,"total")}}function Aa(e){const t=y(e);return{...b("provider",$(t,"provider")),...b("id",$(t,"id")),...b("name",$(t,"name")),...b("contextWindow",ne(t,"contextWindow")),...b("reasoning",t.reasoning),...b("input",Od(t.input))}}function Od(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Invalid model input");return e.map(_d)}}function _d(e){if(e==="text"||e==="image")return e;throw new Error("Invalid model input")}function Ld(e){return e===void 0?{}:{model:Aa(e)}}function jd(e){const t=y(e);return{models:j(Aa)(t.models)}}function Fd(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function Ud(e){const t=y(e);return{levels:j(Fd)(t.levels)}}function zd(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Bd(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 Nd(e){const t=y(e),i=t.source===void 0?void 0:Bd(t.source);return{configured:D(t,"configured"),...b("source",i),...b("label",$(t,"label"))}}function qd(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),authType:zd(t.authType),status:Nd(t.status)}}function Hd(e){const t=y(e);return{providers:j(qd)(t.providers)}}function ii(e){const t=y(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:Kd(t.status),progress:j(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...b("error",$(t,"error")),...b("auth",Vd(t.auth)),...b("prompt",Gd(t.prompt)),...b("select",Jd(t.select))}}function Kd(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Vd(e){if(e===void 0)return;const t=y(e);return{url:m(t,"url"),...b("instructions",$(t,"instructions"))}}function Gd(e){if(e===void 0)return;const t=y(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,...b("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function Jd(e){if(e===void 0)return;const t=y(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:j(Ma)(t.options)}}function Qd(e){if(e===void 0)return{};const t=y(e);return{contextUsage:{tokens:Ro(t,"tokens"),contextWindow:H(t,"contextWindow"),percent:Ro(t,"percent")}}}function Zd(e){const t=y(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,...b("description",$(t,"description"))}}function qs(e){const t=y(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 Xd(e){const t=y(e);return{path:m(t,"path"),entries:j(Yd)(t.entries),scannedAt:m(t,"scannedAt"),truncated:D(t,"truncated")}}function Yd(e){const t=y(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,...b("size",ne(t,"size")),...b("modifiedAt",$(t,"modifiedAt"))}}function ep(e){const t=y(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...b("language",$(t,"language")),...b("mediaType",sp(t.mediaType)),...b("mimeType",$(t,"mimeType")),encoding:i,size:H(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:D(t,"truncated"),binary:D(t,"binary")}}function Ta(e){const t=y(e);return{path:m(t,"path"),size:H(t,"size"),modifiedAt:m(t,"modifiedAt"),created:D(t,"created")}}function tp(e){const t=y(e);return{path:m(t,"path"),existed:D(t,"existed")}}function ip(e){const t=y(e);return{fromPath:m(t,"fromPath"),toPath:m(t,"toPath"),size:H(t,"size"),modifiedAt:m(t,"modifiedAt")}}function sp(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function rp(e){const t=y(e);return{isGitRepo:D(t,"isGitRepo"),hash:m(t,"hash"),...b("branch",$(t,"branch")),...b("upstream",$(t,"upstream")),...b("ahead",ne(t,"ahead")),...b("behind",ne(t,"behind")),files:j(op)(t.files)}}function op(e){const t=y(e);return{path:m(t,"path"),...b("oldPath",$(t,"oldPath")),index:Po(t.index),workingTree:Po(t.workingTree)}}function Po(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 np(e){const t=y(e);return{...b("path",$(t,"path")),staged:D(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:D(t,"truncated")}}function gs(e){const t=y(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:D(t,"exited"),...b("exitCode",ne(t,"exitCode")),...b("commandRunId",$(t,"commandRunId"))}}function Nt(e){const t=y(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:ap(t.status),...b("exitCode",ne(t,"exitCode")),createdAt:m(t,"createdAt"),...b("startedAt",$(t,"startedAt")),...b("completedAt",$(t,"completedAt")),metadata:lp(t.metadata,"metadata")}}function ap(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function lp(e,t){const i=y(e);return Object.fromEntries(Object.entries(i).map(([s,r])=>{if(typeof r!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,r]}))}function cp(e){const t=y(e);return{cwd:m(t,"cwd"),hasSessionActivity:D(t,"hasSessionActivity"),hasTerminalActivity:D(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function dp(e){const t=y(e);return{workspaces:j(cp)(t.workspaces),generatedAt:m(t,"generatedAt")}}function pp(e){if(e!==void 0){if(!Ne(e)||Array.isArray(e))throw new Error("Invalid uploads field");return{...b("defaultFolder",$(e,"defaultFolder"))}}}function Co(e){const t=y(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:j(Ma)(t.options)};if(i==="done")return{type:i,...b("message",$(t,"message")),...hp(t.session),...b("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function Ma(e){const t=y(e);return{value:m(t,"value"),label:m(t,"label"),...b("description",$(t,"description"))}}function hp(e){return e===void 0?{}:{session:Ns(e)}}function si(e){return{accepted:et(e,"accepted")}}function up(e){const t=y(e);return j(fp)(t.attachments)}function fp(e){const t=y(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:H(t,"size")}}function Hs(e){return{closed:et(e,"closed")}}function gp(e){return{aborted:et(e,"aborted")}}function mp(e){return{stopped:et(e,"stopped")}}function Io(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:kt(t.sessionIds,"sessionIds"),s=ne(t,"archivedCount"),r=ne(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...r===void 0?{}:{skippedAlreadyArchivedCount:r}}}function vp(e){return{restored:et(e,"restored")}}function bp(e){return{deleted:et(e,"deleted")}}function wp(e){return{detached:et(e,"detached")}}function yp(e){return{reloaded:et(e,"reloaded")}}function Ro(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 xp(e){return typeof e=="string"?e:e.id}function Sp(e){return typeof e=="string"?void 0:e.cwd}function kp(e,t,i,s){const r=new URLSearchParams;s?.path!==void 0&&r.set("path",s.path),s?.staged===!0&&r.set("staged","true");const o=r.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${o?`?${o}`:""}`}function $p(e,t,i="local"){const s=new URLSearchParams,r=Sp(e);r!==void 0&&r!==""&&s.set("cwd",r),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const o=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(xp(e))}/messages${o===""?"":`?${o}`}`}function Pp(e,t,i,s){const r=new URLSearchParams({path:i});s?.createDirs===!1&&r.set("createDirs","false"),s?.overwrite===!1&&r.set("overwrite","false");const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Ji(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`)}function Cp(e,t,i,s){const r=new URLSearchParams;r.set("path",i),s?.modifiedAt!==void 0&&r.set("v",s.modifiedAt);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Ji(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${r.toString()}`)}function Ea(e,t,i,s){const r=new URLSearchParams;r.set("path",i);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Ji(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${r.toString()}`)}const C=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function Da(e){return typeof e=="string"?e:e.id}function xr(e){return typeof e=="string"?void 0:e.cwd}function Wa(e,t="local"){return`${C(t)}/sessions/${encodeURIComponent(Da(e))}`}function G(e,t,i="local"){return`${Wa(e,i)}/${t}`}function ri(e,t,i="local"){return`${G(e,t,i)}${Oa(e)}`}function Ip(e,t="local"){return`${Wa(e,t)}${Oa(e)}`}function Oa(e){const t=xr(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function Q(e,t={}){const i=xr(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}function Ao(e){return JSON.stringify({sessions:e.map(Rp)})}function Rp(e){const t=Da(e),i=xr(e);return i===void 0||i===""?{id:t}:{id:t,cwd:i}}const _a={piWebStatus:(e="local")=>v(e==="local"?"/api/pi-web/status":`${C(e)}/pi-web/status`,cd),piWebRuntime:()=>v("/api/pi-web/runtime",dd)},Ap={machines:()=>v("/api/machines",bd),addMachine:e=>v("/api/machines",Pa,{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`,wd),runtime:e=>v(`/api/machines/${encodeURIComponent(e)}/runtime`,yd)},Ii={config:()=>v("/api/config",wo),saveConfig:e=>v("/api/config",wo,{method:"PUT",body:JSON.stringify({config:e})})},Ks={plugins:()=>v("/api/plugins",nd)},La={workspaceActivity:(e="local")=>v(`${C(e)}/activity`,dp)},Tp={projects:(e="local")=>v(`${C(e)}/projects`,j(ko)),addProject:(e,t,i,s="local")=>v(`${C(s)}/projects`,ko,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>v(`${C(t)}/projects/${encodeURIComponent(e)}`,Hs,{method:"DELETE"}),projectDirectories:(e,t="local")=>v(`${C(t)}/project-directories?q=${encodeURIComponent(e)}`,j(qs))},wt={workspaces:(e,t="local")=>v(`${C(t)}/projects/${e}/workspaces`,j($d)),deleteWorkspace:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Nt,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Xd),workspaceFile:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,ep),uploadWorkspaceFile:async(e,t,i,s,r="local")=>r==="local"?Op(e,t,i,s):v(`${C(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Bs,{method:"POST",body:JSON.stringify({path:i,contentBase64:await Dp(s)})}),createWorkspaceFile:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Bs,{method:"POST",body:JSON.stringify({path:i,contentBase64:""})}),writeWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({path:i});r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!1&&n.set("overwrite","false");const a=s instanceof Uint8Array,c=a?new Uint8Array(s):new TextEncoder().encode(s);return v(`${C(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${n.toString()}`,Ta,{method:"PUT",body:c,headers:{"Content-Type":a?"application/octet-stream":"text/plain"}})},deleteWorkspaceFile:(e,t,i,s="local")=>{const r=new URLSearchParams({path:i});return v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`,tp,{method:"DELETE"})},moveWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({fromPath:i,toPath:s});return r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!0&&n.set("overwrite","true"),v(`${C(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${n.toString()}`,ip,{method:"POST"})},createWorkspaceDirectory:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,$o,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,r="local")=>v(`${C(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,$o,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,Cd,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>Ea(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>_p(e,t,i,s)},Vs={sessions:(e,t="local")=>v(`${C(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(Ns)),startSession:(e,t="local")=>v(`${C(t)}/sessions`,Ns,{method:"POST",body:JSON.stringify({cwd:e})}),cleanupPreview:(e,t="local")=>v(`${C(t)}/sessions/cleanup/preview`,Ia,{method:"POST",body:JSON.stringify(e)}),cleanup:(e,t="local")=>v(`${C(t)}/sessions/cleanup`,Id,{method:"POST",body:JSON.stringify(e)}),archiveMany:(e,t="local")=>v(`${C(t)}/sessions/bulk/archive`,Rd,{method:"POST",body:Ao(e)}),deleteArchivedMany:(e,t="local")=>v(`${C(t)}/sessions/bulk/delete-archived`,Ad,{method:"POST",body:Ao(e)}),messages:(e,t,i="local")=>v($p(e,t,i),kd),status:(e,t="local")=>v(ri(e,"status",t),Mt),models:(e,t="local")=>v(ri(e,"models",t),jd),setModel:(e,t,i,s="local")=>v(G(e,"model",s),Mt,{method:"POST",body:Q(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>v(G(e,"model/cycle",i),Mt,{method:"POST",body:Q(e,{direction:t})}),thinkingLevels:(e,t="local")=>v(ri(e,"thinking-levels",t),Ud),setThinkingLevel:(e,t,i="local")=>v(G(e,"thinking-level",i),Mt,{method:"POST",body:Q(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>v(G(e,"thinking-level/cycle",t),Mt,{method:"POST",body:Q(e)}),commands:(e,t="local")=>v(ri(e,"commands",t),j(Zd)),prompt:(e,t,i,s="local",r)=>v(G(e,"prompt",s),si,{method:"POST",body:Q(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...r!==void 0&&r.length>0?{attachments:r}:{}})}),saveAttachments:(e,t,i="local",s)=>v(G(e,"attachments",i),up,{method:"POST",body:Q(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>v(G(e,"shell",i),si,{method:"POST",body:Q(e,{text:t})}),runCommand:(e,t,i="local")=>v(G(e,"commands/run",i),Co,{method:"POST",body:Q(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>v(G(e,"commands/respond",s),Co,{method:"POST",body:Q(e,{requestId:t,value:i})}),abort:(e,t="local")=>v(G(e,"abort",t),gp,{method:"POST",body:Q(e)}),stop:(e,t="local")=>v(G(e,"stop",t),mp,{method:"POST",body:Q(e)}),archive:(e,t="local")=>v(G(e,"archive",t),Io,{method:"POST",body:Q(e)}),archiveWithDescendants:(e,t="local")=>v(G(e,"archive-tree",t),Io,{method:"POST",body:Q(e)}),restore:(e,t="local")=>v(G(e,"restore",t),vp,{method:"POST",body:Q(e)}),deleteArchived:(e,t="local")=>v(Ip(e,t),bp,{method:"DELETE"}),detachParent:(e,t="local")=>v(G(e,"detach-parent",t),wp,{method:"POST",body:Q(e)}),reloadSession:(e,t="local")=>v(G(e,"reload",t),yp,{method:"POST",body:Q(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(`${C(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Hd)},saveApiKey:(e,t,i="local")=>v(`${C(i)}/auth/api-key`,si,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>v(`${C(t)}/auth/logout`,si,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>v(`${C(t)}/auth/oauth`,ii,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>v(`${C(t)}/auth/oauth/${encodeURIComponent(e)}`,ii),respondOAuthFlow:(e,t,i,s="local")=>v(`${C(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,ii,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>v(`${C(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,ii,{method:"POST"})},yt={terminals:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(gs)),startTerminal:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,gs,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Hs,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,Hs,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,gs,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Nt,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>v(`${C(t)}/terminal-command-runs${Ep(e)}`,j(Nt)),getCommandRun:(e,t="local")=>Mp(e,t),cancelCommandRun:(e,t="local")=>v(`${C(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Nt,{method:"POST"})};async function Mp(e,t){return Gc(`${C(t)}/terminal-command-runs/${encodeURIComponent(e)}`,Nt)}function Ep(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 ja(e){if(!Lp(e))return;const t=e.error;return typeof t=="string"?t:void 0}async function Dp(e){return Wp(await e.arrayBuffer())}function Wp(e){const t=new Uint8Array(e);let i="";for(const s of t)i+=String.fromCharCode(s);return btoa(i)}async function Op(e,t,i,s){const r=new FormData;r.set("path",i),r.set("file",s,s.name);const o=await fetch(wr(`${C("local")}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`),{method:"POST",body:r});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(ja(n)??o.statusText)}return Bs(await o.json())}async function _p(e,t,i,s){const r=await fetch(Ea(e,t,i,{machineId:s}));if(!r.ok){const p=await r.json().catch(()=>({}));throw new Error(ja(p)??r.statusText)}const o=await r.blob(),n=URL.createObjectURL(o),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 Lp(e){return typeof e=="object"&&e!==null}const jp={files:(e,t,i={})=>{const s=new URLSearchParams({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),i.workspaceScoped===!0&&i.projectId!==void 0&&i.workspaceId!==void 0?v(`${C(i.machineId)}/projects/${encodeURIComponent(i.projectId)}/workspaces/${encodeURIComponent(i.workspaceId)}/files?${s.toString()}`,j(qs)):(s.set("cwd",e),v(`${C(i.machineId)}/files?${s.toString()}`,j(qs)))}},Fp={gitStatus:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,rp),gitDiff:(e,t,i,s="local")=>v(kp(s,e,t,i),np)},N={..._a,...Ap,...Ii,...Ks,...La,...Tp,...wt,...Vs,...yt,...jp,...Fp};function Up(e,t="local",i=mr()){const s=typeof e=="string"?void 0:e.cwd,r=s===void 0||s===""?"":`?${new URLSearchParams({cwd:s}).toString()}`,o=typeof e=="string"?e:e.id,n=ya(`${Sr(t)}/sessions/${encodeURIComponent(o)}/events${r}`,void 0,i);return new WebSocket(`${kr()}${n}`)}function fx(e,t,i,s,r="local"){const o=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${kr()}${Sr(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${o}`)}function zp(e="local",t=mr()){const i=ya(`${Sr(e)}/events`,void 0,t);return new WebSocket(`${kr()}${i}`)}function Sr(e){return`/api/machines/${encodeURIComponent(e)}`}function kr(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}const Fa=".pi-web/uploads";class Qi extends Error{constructor(t="Workspace upload cancelled"){super(t),this.name="WorkspaceUploadCancelledError"}}class Ua extends Error{constructor(t,i){super(Jp(t)),this.name="WorkspaceUploadBatchError",this.failures=t.map(s=>({...s})),this.responses=i.map(s=>({...s}))}}function To(e){return e?.uploads?.defaultFolder??Fa}function Bp(e,t){return e?.uploads?.defaultFolder??t}function $r(e,t){const i=Mo(e,"upload destination",{allowEmpty:!0}),s=Mo(t,"upload file name",{allowEmpty:!1});return i===""?s:`${i}/${s}`}function Np(e,t,i,s={}){const r=s.xhrFactory?.()??new XMLHttpRequest;let o=!1,n=!1;return{promise:new Promise((c,p)=>{const u=g=>{o||(o=!0,p(g))},h=g=>{o||(o=!0,c(g))};r.open("PUT",Pp(e,t,i.path,Kp(s)),!0),r.responseType="json",r.setRequestHeader("Content-Type",(i.contentType??i.file.type)||"application/octet-stream"),r.upload.onprogress=g=>{s.onProgress?.(Vp(g,i.file.size))},r.onload=()=>{if(r.status>=200&&r.status<300){try{s.onProgress?.({loaded:i.file.size,total:i.file.size,percent:1,lengthComputable:!0}),h(Ta(za(r)))}catch(g){u(g instanceof Error?g:new Error(String(g)))}return}u(new Error(Yp(r)))},r.onerror=()=>{u(new Error("Workspace upload failed"))},r.onabort=()=>{u(new Qi(n?void 0:"Workspace upload aborted"))},r.send(i.file)}),cancel:()=>{o||(n=!0,r.abort())}}}function qp(e,t,i,s={}){const r=s.destinationFolder??Fa,o=i.map((h,g)=>({index:g,name:h.name,path:$r(r,h.name),loaded:0,total:h.size,percent:Pr(0,h.size),lengthComputable:!0,done:!1}));let n,a=0;const c={requested:!1},p=()=>{s.onProgress?.(Gp(o,a,o.every(h=>h.done)))};return{promise:(async()=>{const h=[],g=[];for(let w=0;w<i.length;w+=1){if(c.requested)throw new Qi;a=w;const P=i[w],I=o[w];if(!(P===void 0||I===void 0)){n=Np(e,t,{path:I.path,file:P},{...Hp(s),onProgress:V=>{I.total=V.total,I.loaded=Math.min(V.loaded,I.total),I.percent=V.percent,I.lengthComputable=V.lengthComputable,p()}});try{const V=await n.promise;I.loaded=I.total,I.percent=1,I.lengthComputable=!0,I.done=!0,h.push(V),p()}catch(V){if(Zp(V,c))throw V;const Je=Qp(V);I.loaded=I.total,I.percent=1,I.lengthComputable=!0,I.done=!0,I.error=Je,g.push({index:w,name:P.name,path:I.path,error:Je}),p()}finally{n=void 0}}}if(g.length>0)throw new Ua(g,h);return h})(),cancel:()=>{c.requested=!0,n?.cancel()}}}function Hp(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function Kp(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Vp(e,t){const i=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:i,percent:Pr(e.loaded,i),lengthComputable:e.lengthComputable}}function Gp(e,t,i){const s=e.reduce((o,n)=>o+n.total,0),r=e.reduce((o,n)=>o+n.loaded,0);return{currentFileIndex:t,files:e.map(o=>({...o})),loaded:r,total:s,percent:Pr(r,s),done:i}}function Pr(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Jp(e){return e.length===1?e[0]?.error??"Workspace upload failed":`${String(e.length)} files failed to upload`}function Qp(e){return e instanceof Error?e.message:String(e)}function Zp(e,t){return t.requested||e instanceof Qi}function Mo(e,t,i){const s=e.trim();if(s===""){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(Xp(s))throw new Error(`${t} must be workspace-relative`);const r=s.split(/[\\/]+/u).filter(o=>o!==""&&o!==".");if(r.length===0){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(r.some(o=>o===".."))throw new Error(`${t} must not contain path traversal`);return r.join("/")}function Xp(e){const t=e.replace(/\\/g,"/");return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}function za(e){return e.response!==void 0&&e.response!==null&&e.response!==""?e.response:e.responseText===""?{}:JSON.parse(e.responseText)}function Yp(e){const t=eh(e);return th(t)&&typeof t.error=="string"?t.error:e.statusText||`HTTP ${String(e.status)}`}function eh(e){try{return za(e)}catch{return}}function th(e){return typeof e=="object"&&e!==null}function gi(){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 ih(){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,workspaceUploadBatches:{},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 Ba(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const Na="local";function ms(e,t){return`${e}:${t}`}function qa(e,t){return`${e}:${t}`}function f(e){return e.selectedMachine?.id??Na}class sh{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??La}async refresh(t=f(this.getState())){this.applyMachineActivitySnapshot(t,rh(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=f(this.getState())){const s=this.getState(),r=f(s)===i,o=s.machineActivities[i]??(r?s.workspaceActivities:{}),n=oh(o,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...r?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...f(s)===t?{workspaceActivities:i}:{}})}}function rh(e){const t={};for(const i of e.workspaces)Ba(i)&&(t[i.cwd]=i);return t}function oh(e,t){const i={...e};return Ba(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class nh{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=r.api??N,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=ah(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 r=s.providers.find(o=>o.id===t&&(i===void 0||o.authType===i));r!==void 0&&(r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,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(r){this.setState({authDialog:{...t,saving:!1,error:String(r)}})}}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(r=>r.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(r=>r.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(r){this.setState({error:String(r)})}}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 r=t??i.inputValue??"",o={...i};delete o.error,this.setState({authDialog:{...o,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,r,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(o=>o.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 r=s[0];if(r===void 0)return;r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,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 r=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${r}.`}),!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??"":"",r=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,o=t.prompt?.requestId??t.select?.requestId,n=r!==void 0&&r===o,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 ah(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 r=i[2];return r===void 0||r===""?{command:s}:{command:s,providerId:r}}function Jt(e){return e.replaceAll(":",".")}function lh(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[r,o]of t.entries()){if(!r.startsWith(i))continue;const n=r.slice(i.length),a=s[n];a===void 0?s[n]=o:Array.isArray(a)?a.push(o):s[n]=[a,o]}return s}function vs(e,t){const i=lh(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function he(e,t,i,s){const r=new URL(window.location.href),o=`${e}--${t}`;if(r.searchParams.delete(o),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)r.searchParams.append(o,String(n));else r.searchParams.set(o,String(i));ch(r,s)}function ch(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))}function dh(e){const t=e.files.map((s,r)=>{const o=s.size;return{index:r,name:s.name,path:$r(e.destinationFolder,s.name),size:s.size,loaded:0,total:o,percent:Do(0,o),lengthComputable:!0,status:r===0?"uploading":"pending"}}),i=t.reduce((s,r)=>s+r.total,0);return{id:e.id,projectId:e.projectId,workspaceId:e.workspaceId,machineId:e.machineId,destinationFolder:e.destinationFolder,overwrite:e.overwrite,createDirs:e.createDirs,files:t,currentFileIndex:t.length===0?-1:0,loaded:0,total:i,percent:Do(0,i),status:"uploading",startedAt:e.startedAt}}function ph(e,t){const i=new Map(t.files.map(r=>[r.index,r])),s=e.files.map(r=>{const o=i.get(r.index);if(o===void 0)return r;const n={...r,path:o.path,loaded:o.loaded,total:o.total,percent:o.percent,lengthComputable:o.lengthComputable,status:o.error!==void 0?"error":o.done?"completed":t.currentFileIndex===r.index?"uploading":r.status};return o.error===void 0?delete n.error:n.error=o.error,n});return{...e,files:s,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function hh(e,t,i){const s=e.files.map((o,n)=>{const a=t[n];return{...o,...a===void 0?{}:{path:a.path,response:a},loaded:o.total,percent:1,lengthComputable:!0,status:"completed"}}),r=Cr(s);return{...e,files:s,currentFileIndex:s.length===0?-1:s.length-1,...r,status:"completed",completedAt:i}}function uh(e,t,i){const s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:r.status==="uploading"||r.index===e.currentFileIndex?{...r,status:"error",error:t}:{...r,status:"cancelled",error:"Not uploaded because an earlier file failed."});return{...e,files:s,...Cr(s),status:"error",error:t,completedAt:i}}function Eo(e,t){const i="Upload cancelled",s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:{...r,status:"cancelled",error:i});return{...e,files:s,...Cr(s),status:"cancelled",error:i,completedAt:t}}function Cr(e){const t=e.reduce((i,s)=>i+s.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function Do(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}const oi=Jt("core:workspace.files");class fh{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??N,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??qp,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=f(this.getState()),r=await this.api.workspaceTree(t.id,i.id,"",s),o=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(Wo(c))return;throw c}})),n=Object.fromEntries(o.filter(a=>a!==void 0));this.setState({fileTree:r.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:Oo(this.getState().expandedDirs,t)});return}try{const r=await this.api.workspaceTree(i.id,s.id,t,f(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:r.entries},error:""})}catch(r){this.setState({error:String(r)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),he(oi,"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"}),he(oi,"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 r=await this.api.workspaceFile(i.id,s.id,t,f(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:r,error:""})}catch(r){if(this.getState().selectedFilePath!==t)return;if(Wo(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),he(oi,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}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(r){this.setState({error:String(r)})}}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(r){this.setState({error:String(r)})}}async moveSelectedPath(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace,r=this.getState().selectedFilePath;if(!(i===void 0||s===void 0||r===void 0||r===""||t===""))try{const o=f(this.getState());bs(this.getState())==="directory"?(await this.api.moveWorkspaceDirectory(i.id,s.id,r,t,o),await this.refreshFiles(),this.selectDirectory(t)):(await this.api.moveWorkspaceFile(i.id,s.id,r,t,void 0,o),await this.refreshFiles(),await this.selectFile(t)),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}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 r=f(this.getState());bs(this.getState())==="directory"?await this.api.deleteWorkspaceDirectory(t.id,i.id,s,r):await this.api.deleteWorkspaceFile(t.id,i.id,s,r),await this.refreshFiles(),this.clearSelection(),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}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===""||bs(this.getState())==="directory"))try{await this.api.downloadWorkspaceFile(t.id,i.id,s,f(this.getState())),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),he(oi,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}startWorkspaceUpload(t,i){const s=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(s===void 0||r===void 0){this.setState({error:"Select a workspace before uploading files."});return}if(t.length===0)return;const o=f(this.getState()),n=i.overwrite??!1,a=i.createDirs??!0;let c;try{c=dh({id:this.createUploadBatchId(),projectId:s.id,workspaceId:r.id,machineId:o,destinationFolder:i.destinationFolder,overwrite:n,createDirs:a,files:t,startedAt:this.now()})}catch(h){this.setState({error:String(h)});return}this.setUploadBatch(c);let p;try{p=this.uploadWorkspaceFiles(s.id,r.id,t,{destinationFolder:i.destinationFolder,machineId:o,overwrite:n,createDirs:a,onProgress:h=>{this.updateUploadProgress(c.id,h)}})}catch(h){return this.failUploadBatch(c.id,h),{batchId:c.id,done:Promise.resolve()}}this.uploadTasks.set(c.id,p);const u=p.promise.then(async h=>{await this.completeUploadBatch(c.id,h,i)}).catch(async h=>{await this.handleUploadFailure(c.id,h,i)}).finally(()=>{this.uploadTasks.delete(c.id)});return{batchId:c.id,done:u}}cancelWorkspaceUpload(t){const i=this.getUploadBatch(t);i?.status==="uploading"&&(this.setUploadBatch(Eo(i,this.now())),this.uploadTasks.get(t)?.cancel())}clearWorkspaceUpload(t){this.uploadTasks.get(t)?.cancel(),this.uploadTasks.delete(t),this.setState({workspaceUploadBatches:Oo(this.getState().workspaceUploadBatches,t)})}updateUploadProgress(t,i){const s=this.getUploadBatch(t);s?.status==="uploading"&&this.setUploadBatch(ph(s,i))}async completeUploadBatch(t,i,s){const r=this.getUploadBatch(t);if(r?.status!=="uploading"||(this.setUploadBatch(hh(r,i,this.now()),{error:""}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();const o=i[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}async handleUploadFailure(t,i,s){const r=this.failUploadBatch(t,i);if(!(i instanceof Ua)||i.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshFiles();const o=i.responses[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}failUploadBatch(t,i){const s=this.getUploadBatch(t);if(s?.status!=="uploading")return;if(gh(i)){const n=Eo(s,this.now());return this.setUploadBatch(n),n}const r=mh(i),o=uh(s,r,this.now());return this.setUploadBatch(o,{error:r}),o}getUploadBatch(t){return this.getState().workspaceUploadBatches[t]}setUploadBatch(t,i={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[t.id]:t},...i})}isCurrentWorkspaceBatch(t){const i=this.getState();return i.selectedProject?.id===t.projectId&&i.selectedWorkspace?.id===t.workspaceId&&f(i)===t.machineId}}function Wo(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function gh(e){return e instanceof Qi}function mh(e){return e instanceof Error?e.message:String(e)}function Oo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function bs(e){const t=e.selectedFilePath;return t===void 0?"file":vh(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function vh(e,t,i){const s=e.find(r=>r.path===i);if(s!==void 0)return s;for(const r of Object.values(t)){const o=r.find(n=>n.path===i);if(o!==void 0)return o}}const _o=Jt("core:workspace.git");class bh{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 N.gitStatus(t.id,i.id,f(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const r=this.getState().selectedDiffPath;r!==void 0&&(s.files.some(o=>o.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),he(_o,"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"}),he(_o,"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[r,o]=await Promise.all([N.gitDiff(i.id,s.id,{path:t},f(this.getState())),N.gitDiff(i.id,s.id,{path:t,staged:!0},f(this.getState()))]);this.setState({selectedDiff:r,selectedStagedDiff:o,error:""})}catch(r){this.setState({error:String(r)})}}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 wh{constructor(t,i,s,r){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=r}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await N.machines(),s=await this.selectInitialMachine(i,t),r=new Set(i.map(o=>o.id));this.setState({machines:i,selectedMachine:s,machineActivities:Lo(this.getState().machineActivities,r),machineRuntimes:Lo(this.getState().machineRuntimes,r)}),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,...gi()}),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 N.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 N.deleteMachine(t.id);const r=this.getState().machines.filter(n=>n.id!==t.id),o=r.find(n=>n.id==="local")??r[0];return this.setState({machines:r,machineStatuses:ws(this.getState().machineStatuses,t.id),machineRuntimes:ws(this.getState().machineRuntimes,t.id),machineActivities:ws(this.getState().machineActivities,t.id)}),s&&o!==void 0?(i.selectFallback===!1||await this.selectMachine(o),o):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await N.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 N.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(o=>o.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const r=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await N.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(r=>N.health(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(r=>N.runtime(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function ws(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Lo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class yh{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 N.projects(t);if(f(this.getState())!==t)return;const s=new Set(i.map(o=>o.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([o])=>s.has(o)));this.setState({projects:i,workspacesByProjectId:r})}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 N.addProject(t.trim(),void 0,i,f(this.getState())),r=this.getState().projects;this.setState({projects:[...r.filter(o=>o.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await N.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 Gs="pi-web:cached-new-sessions:v1",xh="browserCachedNew",It="local";function Qt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function jo(e,t=It,i=Qt()){if(e.messageCount!==0||e.archived===!0)return;const s=Ir(i).filter(r=>r.id!==e.id||r.machineId!==t);Rr([Js(e,t),...s],i)}function Js(e,t=It){return{...e,browserCachedNew:!0,machineId:t}}function Fo(e,t=It,i=Qt()){const s=Ir(i).filter(r=>r.id!==e||r.machineId!==t);Rr(s,i)}function Ha(e,t,i=It,s=Qt()){const r=new Set(t.map(c=>c.id)),o=Ir(s),n=o.filter(c=>c.machineId!==i||!r.has(c.id));return n.length!==o.length&&Rr(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function Z(e){return e===void 0?!1:$h(e)&&e.browserCachedNew===!0}function Sh(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:It},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Ir(e=Qt()){try{const t=e?.getItem(Gs);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>kh(s)):[]}catch{return[]}}function Rr(e,t=Qt()){try{e.length===0?t?.removeItem(Gs):t?.setItem(Gs,JSON.stringify(e))}catch{}}function kh(e){if(!Ph(e))return[];const t=gt(e,"id"),i=gt(e,"path"),s=gt(e,"cwd"),r=gt(e,"created"),o=gt(e,"modified"),n=gt(e,"firstMessage"),a=Ch(e,"messageCount");if(t===void 0||i===void 0||s===void 0||r===void 0||o===void 0||n===void 0||a!==0)return[];const c=ys(e,"name"),p=ys(e,"parentSessionPath"),u=ys(e,"machineId")??It;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:r,modified:o,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function $h(e){return xh in e}function Ph(e){return typeof e=="object"&&e!==null}function gt(e,t){const i=e[t];return typeof i=="string"?i:void 0}function ys(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Ch(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Ih(e){return Nh(e.flatMap(Ar)).filter(t=>t.parts.length>0)}function _e(e,t){return{role:e,parts:[{type:"text",text:t}]}}function Et(e,t){const i=Oh(t);return i===void 0?e:{...e,meta:i}}function Rh(e,t,i){if(i==="")return e;const s=e.at(-1),r=s?.parts.at(-1);return s?.role===t&&r?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...r,text:r.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,_e(t,i)]}function Ah(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 Ar(e){if(Mh(e))return[e];if(_(e,"role")==="bashExecution")return[Et(jh(e),e)];const t=Fh(_(e,"role")),i=Uh(ye(e,"content"),e),s=t==="user"?Eh(i):void 0;if(s!==void 0)return s.map(p=>Et(p,e));const r=Wh(e);if(t==="tool")return[Et({role:t,parts:i,...r===void 0?{}:{source:r}},e)];const o=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&o.length>0&&o.every(p=>p.type==="skillRead")?"skill":t,a=o.length>0?[Et({role:n,parts:o,...r===void 0?{}:{source:r}},e)]:[],c=Th(e);return c===void 0?a:[...a,Et(c,e)]}function Th(e){if(_(e,"role")!=="assistant"||_(e,"stopReason")!=="error")return;const t=_(e,"errorMessage")?.trim();return _e("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function Mh(e){const t=_(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(ye(e,"parts"))}function Eh(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Dh(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 Dh(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 Wh(e){const t=_(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Oh(e){const t=_h(ye(e,"timestamp")),i=Lh(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function _h(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 Lh(e){if(_(e,"role")!=="assistant")return;const t=_(e,"provider"),i=_(e,"model"),s=_(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 jh(e){const t=_(e,"command")??"",i=mi(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=ye(e,"output");s!=null&&i.push("",Ai(s));const r=ye(e,"exitCode");r!=null&&i.push("",`exit ${Ai(r)}`),mi(e,"cancelled")===!0&&i.push("","cancelled"),mi(e,"truncated")===!0&&i.push("","output truncated");const o=_(e,"fullOutputPath");return o!==void 0&&o!==""&&i.push("",`full output: ${o}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
- `)}]}}function Fh(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function Uh(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=_(i,"type"),r=_(i,"text");if(s==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(s==="thinking"){const o=_(i,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}if(s==="toolCall"){const o=_(i,"name")??"tool",n=ye(i,"arguments"),a=_(i,"id"),c=o==="read"?Bh(_(n,"path")):void 0;return c!==void 0?[{type:"skillRead",...c,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:o,summary:Zt(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const o=_(i,"data"),n=_(i,"mimeType");return o!==void 0&&o!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:o}]:[{type:"text",text:"[image]"}]}return Uo(i)}).map(i=>i.type==="text"&&_(t,"role")==="toolResult"?zh(i.text,t):i):Uo(e)}function zh(e,t){const i=_(t,"toolCallId"),s=ye(t,"content"),r=ye(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:_(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...r===void 0?{}:{details:r},isError:mi(t,"isError")===!0}}function Bh(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 Nh(e){const t=[],i=new Map;for(const s of e){let r=[];const o={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{r.length!==0&&(t.push({role:s.role,parts:r,...o}),r=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=qh(a),p=t.length;t.push({role:"tool",parts:[c],...o}),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&&Hh(t,c,a)){i.delete(a.toolCallId??"");continue}}r.push(a)}n()}return t}function qh(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 Hh(e,t,i){const s=e[t.lineIndex],r=s?.parts[t.partIndex];if(s===void 0||r?.type!=="toolExecution")return!1;const o=Ri(i.details)??r.preview,n={...r,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...o===void 0?{}:{preview:o}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function Ri(e){const t=ye(e,"preview");if(!Tr(t))return;const i=_(t,"diff"),s=_(t,"error"),r=Vh(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&r===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...r===void 0?{}:{firstChangedLine:r}}}function Uo(e){return e==null?[]:typeof e=="object"?[{type:"text",text:Zt(e)}]:[{type:"text",text:Ai(e)}]}function Zt(e){if(!Tr(e))return Ai(e);const t=_(e,"command");if(t!==void 0)return t;const i=_(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(([,o])=>o!=null).slice(0,3).map(([o,n])=>`${o}: ${Kh(n)}`).join(" · ")}function Kh(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 Tr(e){return typeof e=="object"&&e!==null}function ye(e,t){return Tr(e)?e[t]:void 0}function _(e,t){const i=ye(e,t);return typeof i=="string"?i:void 0}function mi(e,t){const i=ye(e,t);return typeof i=="boolean"?i:void 0}function Vh(e,t){const i=ye(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function Ai(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const Gh="pi-web:prompt-draft:";function Ti(e){return`${Gh}${e}`}function Zi(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Ka(e,t=Zi()){try{return t?.getItem(Ti(e))??""}catch{return""}}function Mi(e,t,i=Zi()){try{t?i?.setItem(Ti(e),t):i?.removeItem(Ti(e))}catch{}}function Mr(e,t=Zi()){try{t?.removeItem(Ti(e))}catch{}}function Jh(e,t,i=Zi()){const s=Ka(e,i);s!==""&&(Mi(t,s,i),Mr(e,i))}function Qh(e,t){return _e("bash",`${t===!0?`不加入上下文
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-CGV4uBeZ.js","assets/vendor-editor-core-C7aWiQy0.js","assets/vendor-editor-languages-EW34FfVy.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/UnifiedDiffViewer-BSzsWx-m.js","assets/TerminalPanel-CeJN9p9P.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
+ import{Q as lo,v as rt,J as vs,R as uc,S as fc,G as gc,U as mc,V as vc,W as bc,A as wc,X as yc,Y as xc,Z as co,w as po,_ as Sc}from"./vendor-editor-core-C7aWiQy0.js";import{m as kc,d as $c,i as Pc}from"./vendor-editor-languages-EW34FfVy.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const n of o.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=i(r);fetch(r.href,o)}})();const bi=globalThis,fr=bi.ShadowRoot&&(bi.ShadyCSS===void 0||bi.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,gr=Symbol(),ho=new WeakMap;let ba=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==gr)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(fr&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=ho.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&ho.set(i,t))}return t}toString(){return this.cssText}};const Cc=e=>new ba(typeof e=="string"?e:e+"",void 0,gr),D=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,r,o)=>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.")})(r)+e[o+1],e[0]);return new ba(i,e,gr)},Ic=(e,t)=>{if(fr)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),r=bi.litNonce;r!==void 0&&s.setAttribute("nonce",r),s.textContent=i.cssText,e.appendChild(s)}},uo=fr?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return Cc(i)})(e):e;const{is:Rc,defineProperty:Ac,getOwnPropertyDescriptor:Tc,getOwnPropertyNames:Mc,getOwnPropertySymbols:Ec,getPrototypeOf:Dc}=Object,Zi=globalThis,fo=Zi.trustedTypes,Wc=fo?fo.emptyScript:"",Oc=Zi.reactiveElementPolyfillSupport,Vt=(e,t)=>e,Ri={toAttribute(e,t){switch(t){case Boolean:e=e?Wc: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}},mr=(e,t)=>!Rc(e,t),go={attribute:!0,type:String,converter:Ri,reflect:!1,useDefault:!1,hasChanged:mr};Symbol.metadata??=Symbol("metadata"),Zi.litPropertyMetadata??=new WeakMap;let xt=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=go){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(),r=this.getPropertyDescriptor(t,s,i);r!==void 0&&Ac(this.prototype,t,r)}}static getPropertyDescriptor(t,i,s){const{get:r,set:o}=Tc(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:r,set(n){const a=r?.call(this);o?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??go}static _$Ei(){if(this.hasOwnProperty(Vt("elementProperties")))return;const t=Dc(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Vt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Vt("properties"))){const i=this.properties,s=[...Mc(i),...Ec(i)];for(const r of s)this.createProperty(r,i[r])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,r]of i)this.elementProperties.set(s,r)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const r=this._$Eu(i,s);r!==void 0&&this._$Eh.set(r,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 r of s)i.unshift(uo(r))}else t!==void 0&&i.push(uo(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 Ic(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),r=this.constructor._$Eu(t,s);if(r!==void 0&&s.reflect===!0){const o=(s.converter?.toAttribute!==void 0?s.converter:Ri).toAttribute(i,s.type);this._$Em=t,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(t,i){const s=this.constructor,r=s._$Eh.get(t);if(r!==void 0&&this._$Em!==r){const o=s.getPropertyOptions(r),n=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:Ri;this._$Em=r;const a=n.fromAttribute(i,o.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(t,i,s,r=!1,o){if(t!==void 0){const n=this.constructor;if(r===!1&&(o=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??mr)(o,i)||s.useDefault&&s.reflect&&o===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:r,wrapped:o},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),o!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),r===!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[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,o]of s){const{wrapped:n}=o,a=this[r];n!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,o,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){}};xt.elementStyles=[],xt.shadowRootOptions={mode:"open"},xt[Vt("elementProperties")]=new Map,xt[Vt("finalized")]=new Map,Oc?.({ReactiveElement:xt}),(Zi.reactiveElementVersions??=[]).push("2.1.2");const vr=globalThis,mo=e=>e,Ai=vr.trustedTypes,vo=Ai?Ai.createPolicy("lit-html",{createHTML:e=>e}):void 0,wa="$lit$",Ye=`lit$${Math.random().toFixed(9).slice(2)}$`,ya="?"+Ye,_c=`<${ya}>`,ht=document,Jt=()=>ht.createComment(""),Qt=e=>e===null||typeof e!="object"&&typeof e!="function",br=Array.isArray,Lc=e=>br(e)||typeof e?.[Symbol.iterator]=="function",bs=`[
3
+ \f\r]`,Wt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,bo=/-->/g,wo=/>/g,ot=RegExp(`>|${bs}(?:([^\\s"'>=/]+)(${bs}*=${bs}*(?:[^
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),yo=/'/g,xo=/"/g,xa=/^(?:script|style|textarea|title)$/i,Sa=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=Sa(1),be=Sa(2),et=Symbol.for("lit-noChange"),U=Symbol.for("lit-nothing"),So=new WeakMap,ct=ht.createTreeWalker(ht,129);function ka(e,t){if(!br(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return vo!==void 0?vo.createHTML(t):t}const jc=(e,t)=>{const i=e.length-1,s=[];let r,o=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=bo:u[1]!==void 0?n=wo:u[2]!==void 0?(xa.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=ot):u[3]!==void 0&&(n=ot):n===ot?u[0]===">"?(n=r??Wt,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?ot:u[3]==='"'?xo:yo):n===xo||n===yo?n=ot:n===bo||n===wo?n=Wt:(n=ot,r=void 0);const y=n===ot&&e[a+1].startsWith("/>")?" ":"";o+=n===Wt?c+_c:h>=0?(s.push(p),c.slice(0,h)+wa+c.slice(h)+Ye+y):c+Ye+(h===-2?a:y)}return[ka(e,o+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Zt{constructor({strings:t,_$litType$:i},s){let r;this.parts=[];let o=0,n=0;const a=t.length-1,c=this.parts,[p,u]=jc(t,i);if(this.el=Zt.createElement(p,s),ct.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(r=ct.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const h of r.getAttributeNames())if(h.endsWith(wa)){const g=u[n++],y=r.getAttribute(h).split(Ye),P=/([.?@])?(.*)/.exec(g);c.push({type:1,index:o,name:P[2],strings:y,ctor:P[1]==="."?zc:P[1]==="?"?Uc:P[1]==="@"?Bc:Xi}),r.removeAttribute(h)}else h.startsWith(Ye)&&(c.push({type:6,index:o}),r.removeAttribute(h));if(xa.test(r.tagName)){const h=r.textContent.split(Ye),g=h.length-1;if(g>0){r.textContent=Ai?Ai.emptyScript:"";for(let y=0;y<g;y++)r.append(h[y],Jt()),ct.nextNode(),c.push({type:2,index:++o});r.append(h[g],Jt())}}}else if(r.nodeType===8)if(r.data===ya)c.push({type:2,index:o});else{let h=-1;for(;(h=r.data.indexOf(Ye,h+1))!==-1;)c.push({type:7,index:o}),h+=Ye.length-1}o++}}static createElement(t,i){const s=ht.createElement("template");return s.innerHTML=t,s}}function Ct(e,t,i=e,s){if(t===et)return t;let r=s!==void 0?i._$Co?.[s]:i._$Cl;const o=Qt(t)?void 0:t._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(e),r._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=r:i._$Cl=r),r!==void 0&&(t=Ct(e,r._$AS(e,t.values),r,s)),t}class Fc{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,r=(t?.creationScope??ht).importNode(i,!0);ct.currentNode=r;let o=ct.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new Tt(o,o.nextSibling,this,t):c.type===1?p=new c.ctor(o,c.name,c.strings,this,t):c.type===6&&(p=new Nc(o,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(o=ct.nextNode(),n++)}return ct.currentNode=ht,r}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 Tt{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,r){this.type=2,this._$AH=U,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=r,this._$Cv=r?.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=Ct(this,t,i),Qt(t)?t===U||t==null||t===""?(this._$AH!==U&&this._$AR(),this._$AH=U):t!==this._$AH&&t!==et&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Lc(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!==U&&Qt(this._$AH)?this._$AA.nextSibling.data=t:this.T(ht.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,r=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Zt.createElement(ka(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(i);else{const o=new Fc(r,this),n=o.u(this.options);o.p(i),this.T(n),this._$AH=o}}_$AC(t){let i=So.get(t.strings);return i===void 0&&So.set(t.strings,i=new Zt(t)),i}k(t){br(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,r=0;for(const o of t)r===i.length?i.push(s=new Tt(this.O(Jt()),this.O(Jt()),this,this.options)):s=i[r],s._$AI(o),r++;r<i.length&&(this._$AR(s&&s._$AB.nextSibling,r),i.length=r)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=mo(t).nextSibling;mo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Xi=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,r,o){this.type=1,this._$AH=U,this._$AN=void 0,this.element=t,this.name=i,this._$AM=r,this.options=o,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=U}_$AI(t,i=this,s,r){const o=this.strings;let n=!1;if(o===void 0)t=Ct(this,t,i,0),n=!Qt(t)||t!==this._$AH&&t!==et,n&&(this._$AH=t);else{const a=t;let c,p;for(t=o[0],c=0;c<o.length-1;c++)p=Ct(this,a[s+c],i,c),p===et&&(p=this._$AH[c]),n||=!Qt(p)||p!==this._$AH[c],p===U?t=U:t!==U&&(t+=(p??"")+o[c+1]),this._$AH[c]=p}n&&!r&&this.j(t)}j(t){t===U?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},zc=class extends Xi{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===U?void 0:t}},Uc=class extends Xi{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==U)}},Bc=class extends Xi{constructor(t,i,s,r,o){super(t,i,s,r,o),this.type=5}_$AI(t,i=this){if((t=Ct(this,t,i,0)??U)===et)return;const s=this._$AH,r=t===U&&s!==U||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,o=t!==U&&(s===U||r);r&&this.element.removeEventListener(this.name,this,s),o&&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)}},Nc=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){Ct(this,t)}};const Hc={I:Tt},qc=vr.litHtmlPolyfillSupport;qc?.(Zt,Tt),(vr.litHtmlVersions??=[]).push("3.3.3");const Kc=(e,t,i)=>{const s=i?.renderBefore??t;let r=s._$litPart$;if(r===void 0){const o=i?.renderBefore??null;s._$litPart$=r=new Tt(t.insertBefore(Jt(),o),o,void 0,i??{})}return r._$AI(e),r};const wr=globalThis;let R=class extends xt{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=Kc(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return et}};R._$litElement$=!0,R.finalized=!0,wr.litElementHydrateSupport?.({LitElement:R});const Vc=wr.litElementPolyfillSupport;Vc?.({LitElement:R});(wr.litElementVersions??=[]).push("4.2.2");const W=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const Gc={attribute:!0,type:String,converter:Ri,reflect:!1,hasChanged:mr},Jc=(e=Gc,t,i)=>{const{kind:s,metadata:r}=i;let o=globalThis.litPropertyMetadata.get(r);if(o===void 0&&globalThis.litPropertyMetadata.set(r,o=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),o.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"?Jc(e,t,i):((s,r,o)=>{const n=r.hasOwnProperty(o);return r.constructor.createProperty(o,s),n?Object.getOwnPropertyDescriptor(r,o):void 0})(e,t,i)}function w(e){return d({...e,state:!0,attribute:!1})}const Qc=(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,r)=>{const o=n=>n.renderRoot?.querySelector(e)??null;return Qc(i,s,{get(){return o(this)}})}}function yr(e=Sr()){return xr(e)===void 0?"normal":"management"}function Yi(e,t=Sr(),i="management"){if(i==="normal"||t===void 0)return e;const s=xr(t);if(s===void 0)return e;const r=new URL(e,t.origin);return r.searchParams.set("embed",s.embed),r.searchParams.set("token",s.token),`${r.pathname}${r.search}${r.hash}`}function $a(e,t=Sr(),i="management"){if(i==="normal"||t===void 0)return e;const s=xr(t);if(s===void 0)return e;const r=new URL(e,t.origin);return r.searchParams.set("embed",s.embed),r.searchParams.set("token",s.token),`${r.pathname}${r.search}`}function xr(e){if(e===void 0)return;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 Sr(){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}`)}let Pa=yr();function Zc(e){Pa=e}function kr(e){return Yi(e,void 0,Pa)}async function v(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&!s.has("content-type")&&s.set("content-type","application/json");const r=await fetch(kr(e),{...i,headers:s});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(Ca(n)??r.statusText)}const o=await r.json();return t(o)}async function Xc(e,t){const i=await fetch(kr(e));if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Ca(s)??i.statusText)}return t(await i.json())}}function Ca(e){if(Yc(e))return typeof e.error=="string"?e.error:void 0}function Yc(e){return typeof e=="object"&&e!==null}function je(e){return typeof e=="object"&&e!==null}function x(e){if(!je(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 q(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function ae(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 j(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function it(e,t){if(x(e)[t]!==!0)throw new Error(`Expected ${t} response`);return!0}function b(e,t){return t===void 0?{}:{[e]:t}}const _e={sessionsDeleteArchived:"sessions.deleteArchived",sessionsBulkMutations:"sessions.bulkMutations",sessionsCleanup:"sessions.cleanup",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments",workspaceFileSuggestions:"workspace.fileSuggestions"},ed=Object.values(_e),td=new Set(ed);function id(e){return typeof e=="string"&&td.has(e)}function qe(e,t){return e?.capabilities?.includes(t)===!0}function ko(e){const t=x(e);return{path:m(t,"path"),exists:E(t,"exists"),config:$o(t.config),effectiveConfig:$o(t.effectiveConfig),envOverrides:dd(t.envOverrides)}}function $o(e){const t=x(e);return{...b("host",$(t,"host")),...b("port",ae(t,"port")),...b("allowedHosts",rd(t.allowedHosts)),...b("shortcuts",ld(t.shortcuts)),...b("plugins",cd(t.plugins)),...b("normalAuth",sd(t.normalAuth)),...b("pathAccess",od(t.pathAccess)),...b("uploads",ad(t.uploads)),...b("maxUploadBytes",ae(t,"maxUploadBytes")),...b("spawnSessions",Co(t,"spawnSessions")),...b("subsessions",Co(t,"subsessions"))}}function sd(e){if(e!==void 0){if(!je(e)||Array.isArray(e))throw new Error("Invalid PI WEB normalAuth field");return{...b("passwordHash",$(e,"passwordHash"))}}}function rd(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 od(e){if(e===void 0)return;if(!je(e)||Array.isArray(e))throw new Error("Invalid PI WEB pathAccess field");const t=e.allowedPaths;return{...b("allowedPaths",nd(t,"pathAccess.allowedPaths"))}}function nd(e,t){if(e!==void 0){if(Array.isArray(e)&&e.every(i=>typeof i=="string"&&i!==""))return e;throw new Error(`Invalid PI WEB ${t} field`)}}function ad(e){if(e!==void 0){if(!je(e)||Array.isArray(e))throw new Error("Invalid PI WEB uploads field");return{...b("defaultFolder",$(e,"defaultFolder"))}}}function ld(e){if(e!==void 0){if(!je(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 cd(e){if(e!==void 0){if(!je(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!je(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 r=i.settings;if(r!==void 0&&(!je(r)||Array.isArray(r)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function dd(e){const t=x(e);return{host:E(t,"host"),port:E(t,"port"),allowedHosts:E(t,"allowedHosts"),spawnSessions:E(t,"spawnSessions"),subsessions:E(t,"subsessions")}}function pd(e){const t=x(e);return{plugins:j(hd)(t.plugins)}}function hd(e){const t=x(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:ud(t.scope),machineSpecific:Sd(t.machineSpecific,"machineSpecific")??!1,enabled:E(t,"enabled")}}function ud(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function fd(e){const t=x(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:md(t.components),release:bd(t.release),commands:wd(t.commands),messages:j(yd)(t.messages)}}function gd(e){const t=x(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:Ia(t.components),capabilities:$r(t.capabilities)}}function md(e){const t=x(e);return{web:Ti(t.web),sessiond:Ti(t.sessiond)}}function Ia(e){const t=x(e);return{web:Po(t.web),sessiond:Po(t.sessiond)}}function Po(e){const t=x(e);return{component:Ra(t.component),label:m(t,"label"),...b("runtimeVersion",$(t,"runtimeVersion")),available:E(t,"available"),capabilities:$r(t.capabilities),...b("error",$(t,"error"))}}function Ti(e){const t=x(e);return{component:Ra(t.component),label:m(t,"label"),...b("runtimeVersion",$(t,"runtimeVersion")),...b("installedVersion",$(t,"installedVersion")),stale:E(t,"stale"),available:E(t,"available"),...b("installation",vd(t.installation)),...b("error",$(t,"error"))}}function vd(e){if(e===void 0)return;const t=x(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,...b("path",$(t,"path")),...b("source",$(t,"source")),...s===void 0?{}:{scope:s},...b("npmRoot",$(t,"npmRoot"))}}function bd(e){const t=x(e);return{packageName:m(t,"packageName"),...b("latestVersion",$(t,"latestVersion")),updateAvailable:E(t,"updateAvailable"),...b("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...b("error",$(t,"error"))}}function wd(e){const t=x(e);return{...b("update",$(t,"update")),...b("restart",$(t,"restart")),...b("restartWeb",$(t,"restartWeb")),...b("restartSessiond",$(t,"restartSessiond")),...b("status",$(t,"status"))}}function yd(e){const t=x(e);return{id:m(t,"id"),severity:xd(t.severity),title:m(t,"title"),body:m(t,"body"),...b("command",$(t,"command"))}}function Ra(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function $r(e){if(!Array.isArray(e)||!e.every(id))throw new Error("Invalid PI WEB capabilities");return e}function xd(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Sd(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function Co(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 kd(e){const t=x(e);return j(Aa)(t.machines)}function Aa(e){const t=x(e),i=Cd(t,"kind"),s=$(t,"baseUrl"),r=Ta(t,"status"),o=$(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"),...r===void 0?{}:{status:r},...o===void 0?{}:{statusMessage:o}}}function $d(e){const t=x(e),i=Ta(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:Ti(t.web)},...t.sessiond===void 0?{}:{sessiond:Ti(t.sessiond)},...s===void 0?{}:{error:s}}}function Pd(e){const t=x(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...b("packageName",$(t,"packageName")),...b("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:Ia(t.components)},...t.capabilities===void 0?{}:{capabilities:$r(t.capabilities)},...i===void 0?{}:{error:i}}}function Cd(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function Ta(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 Id(e){const t=x(e);return{configured:E(t,"configured"),authenticated:E(t,"authenticated")}}function Rd(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function It(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function Ad(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=x(e);return{messages:Rd(t.messages),start:q(t,"start"),total:q(t,"total")}}function Io(e){const t=x(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function Td(e){const t=x(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"),...b("effectiveConfig",Md(t.effectiveConfig))}}function Md(e){if(e!==void 0){if(!je(e)||Array.isArray(e))throw new Error("Invalid workspace effectiveConfig field");return{...b("uploads",vp(e.uploads))}}}function Ks(e){const t=x(e);return{path:m(t,"path"),size:q(t,"size"),modifiedAt:m(t,"modifiedAt")}}function Ro(e){const t=x(e);return{path:m(t,"path")}}function Ed(e){const t=x(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function Vs(e){const t=x(e),i=$(t,"name"),s=$(t,"parentSessionPath"),r=$(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:q(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...r===void 0?{}:{archivedAt:r}}}function Ot(e){const t=x(e);return{sessionId:m(t,"sessionId"),isStreaming:E(t,"isStreaming"),isCompacting:E(t,"isCompacting"),isBashRunning:E(t,"isBashRunning"),pendingMessageCount:q(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:j(Fd)(t.queuedMessages),...b("messageCount",ae(t,"messageCount")),tokens:zd(t.tokens),cost:q(t,"cost"),...Nd(t.model),...ip(t.contextUsage),...b("thinkingLevel",$(t,"thinkingLevel"))}}function Ma(e){const t=x(e),i=t.skippedBusySessionIds===void 0?void 0:It(t.skippedBusySessionIds,"skippedBusySessionIds");return{generatedAt:m(t,"generatedAt"),thresholds:_d(t.thresholds),projects:j(Ld)(t.projects),totals:jd(t.totals),...i===void 0?{}:{skippedBusySessionIds:i}}}function Dd(e){const t=x(e);return{...Ma(t),archivedSessionIds:It(t.archivedSessionIds,"archivedSessionIds"),deletedSessionIds:It(t.deletedSessionIds,"deletedSessionIds")}}function Wd(e){const t=x(e);if(t.archived!==!0)throw new Error("Expected bulk archived response");return{archived:!0,archivedSessionIds:It(t.archivedSessionIds,"archivedSessionIds"),failures:j(Ea)(t.failures),generatedAt:m(t,"generatedAt")}}function Od(e){const t=x(e);if(t.deleted!==!0)throw new Error("Expected bulk deleted response");return{deleted:!0,deletedSessionIds:It(t.deletedSessionIds,"deletedSessionIds"),failures:j(Ea)(t.failures),generatedAt:m(t,"generatedAt")}}function Ea(e){const t=x(e);return{sessionId:m(t,"sessionId"),error:m(t,"error")}}function _d(e){const t=x(e);return{...b("archiveIdleDays",ae(t,"archiveIdleDays")),...b("deleteArchivedDays",ae(t,"deleteArchivedDays"))}}function Ld(e){const t=x(e);return{cwd:m(t,"cwd"),archiveCount:q(t,"archiveCount"),deleteCount:q(t,"deleteCount")}}function jd(e){const t=x(e);return{archiveCount:q(t,"archiveCount"),deleteCount:q(t,"deleteCount")}}function Fd(e){const t=x(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text"),...b("imageCount",ae(t,"imageCount"))}}function zd(e){const t=x(e);return{input:q(t,"input"),output:q(t,"output"),cacheRead:q(t,"cacheRead"),cacheWrite:q(t,"cacheWrite"),total:q(t,"total")}}function Da(e){const t=x(e);return{...b("provider",$(t,"provider")),...b("id",$(t,"id")),...b("name",$(t,"name")),...b("contextWindow",ae(t,"contextWindow")),...b("reasoning",t.reasoning),...b("input",Ud(t.input))}}function Ud(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Invalid model input");return e.map(Bd)}}function Bd(e){if(e==="text"||e==="image")return e;throw new Error("Invalid model input")}function Nd(e){return e===void 0?{}:{model:Da(e)}}function Hd(e){const t=x(e);return{models:j(Da)(t.models)}}function qd(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function Kd(e){const t=x(e);return{levels:j(qd)(t.levels)}}function Vd(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Gd(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 Jd(e){const t=x(e),i=t.source===void 0?void 0:Gd(t.source);return{configured:E(t,"configured"),...b("source",i),...b("label",$(t,"label"))}}function Qd(e){const t=x(e);return{id:m(t,"id"),name:m(t,"name"),authType:Vd(t.authType),status:Jd(t.status)}}function Zd(e){const t=x(e);return{providers:j(Qd)(t.providers)}}function ai(e){const t=x(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:Xd(t.status),progress:j(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...b("error",$(t,"error")),...b("auth",Yd(t.auth)),...b("prompt",ep(t.prompt)),...b("select",tp(t.select))}}function Xd(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Yd(e){if(e===void 0)return;const t=x(e);return{url:m(t,"url"),...b("instructions",$(t,"instructions"))}}function ep(e){if(e===void 0)return;const t=x(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,...b("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function tp(e){if(e===void 0)return;const t=x(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:j(Oa)(t.options)}}function ip(e){if(e===void 0)return{};const t=x(e);return{contextUsage:{tokens:Eo(t,"tokens"),contextWindow:q(t,"contextWindow"),percent:Eo(t,"percent")}}}function sp(e){const t=x(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,...b("description",$(t,"description"))}}function Gs(e){const t=x(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 rp(e){const t=x(e);return{path:m(t,"path"),entries:j(op)(t.entries),scannedAt:m(t,"scannedAt"),truncated:E(t,"truncated")}}function op(e){const t=x(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,...b("size",ae(t,"size")),...b("modifiedAt",$(t,"modifiedAt"))}}function np(e){const t=x(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...b("language",$(t,"language")),...b("mediaType",cp(t.mediaType)),...b("mimeType",$(t,"mimeType")),encoding:i,size:q(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:E(t,"truncated"),binary:E(t,"binary")}}function Wa(e){const t=x(e);return{path:m(t,"path"),size:q(t,"size"),modifiedAt:m(t,"modifiedAt"),created:E(t,"created")}}function ap(e){const t=x(e);return{path:m(t,"path"),existed:E(t,"existed")}}function lp(e){const t=x(e);return{fromPath:m(t,"fromPath"),toPath:m(t,"toPath"),size:q(t,"size"),modifiedAt:m(t,"modifiedAt")}}function cp(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function dp(e){const t=x(e);return{isGitRepo:E(t,"isGitRepo"),hash:m(t,"hash"),...b("branch",$(t,"branch")),...b("upstream",$(t,"upstream")),...b("ahead",ae(t,"ahead")),...b("behind",ae(t,"behind")),files:j(pp)(t.files)}}function pp(e){const t=x(e);return{path:m(t,"path"),...b("oldPath",$(t,"oldPath")),index:Ao(t.index),workingTree:Ao(t.workingTree)}}function Ao(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 hp(e){const t=x(e);return{...b("path",$(t,"path")),staged:E(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:E(t,"truncated")}}function ws(e){const t=x(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:E(t,"exited"),...b("exitCode",ae(t,"exitCode")),...b("commandRunId",$(t,"commandRunId"))}}function Gt(e){const t=x(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:up(t.status),...b("exitCode",ae(t,"exitCode")),createdAt:m(t,"createdAt"),...b("startedAt",$(t,"startedAt")),...b("completedAt",$(t,"completedAt")),metadata:fp(t.metadata,"metadata")}}function up(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function fp(e,t){const i=x(e);return Object.fromEntries(Object.entries(i).map(([s,r])=>{if(typeof r!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,r]}))}function gp(e){const t=x(e);return{cwd:m(t,"cwd"),hasSessionActivity:E(t,"hasSessionActivity"),hasTerminalActivity:E(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function mp(e){const t=x(e);return{workspaces:j(gp)(t.workspaces),generatedAt:m(t,"generatedAt")}}function vp(e){if(e!==void 0){if(!je(e)||Array.isArray(e))throw new Error("Invalid uploads field");return{...b("defaultFolder",$(e,"defaultFolder"))}}}function To(e){const t=x(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:j(Oa)(t.options)};if(i==="done")return{type:i,...b("message",$(t,"message")),...bp(t.session),...b("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function Oa(e){const t=x(e);return{value:m(t,"value"),label:m(t,"label"),...b("description",$(t,"description"))}}function bp(e){return e===void 0?{}:{session:Vs(e)}}function dt(e){return{accepted:it(e,"accepted")}}function wp(e){const t=x(e);return j(yp)(t.attachments)}function yp(e){const t=x(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:q(t,"size")}}function Js(e){return{closed:it(e,"closed")}}function xp(e){return{aborted:it(e,"aborted")}}function Sp(e){return{stopped:it(e,"stopped")}}function Mo(e){const t=x(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:It(t.sessionIds,"sessionIds"),s=ae(t,"archivedCount"),r=ae(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...r===void 0?{}:{skippedAlreadyArchivedCount:r}}}function kp(e){return{restored:it(e,"restored")}}function $p(e){return{deleted:it(e,"deleted")}}function Pp(e){return{detached:it(e,"detached")}}function Cp(e){return{reloaded:it(e,"reloaded")}}function Eo(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 Ip(e){return typeof e=="string"?e:e.id}function Rp(e){return typeof e=="string"?void 0:e.cwd}function Ap(e,t,i,s){const r=new URLSearchParams;s?.path!==void 0&&r.set("path",s.path),s?.staged===!0&&r.set("staged","true");const o=r.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${o?`?${o}`:""}`}function Tp(e,t,i="local"){const s=new URLSearchParams,r=Rp(e);r!==void 0&&r!==""&&s.set("cwd",r),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const o=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(Ip(e))}/messages${o===""?"":`?${o}`}`}function Mp(e,t,i,s){const r=new URLSearchParams({path:i});s?.createDirs===!1&&r.set("createDirs","false"),s?.overwrite===!1&&r.set("overwrite","false");const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Yi(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`)}function Ep(e,t,i,s){const r=new URLSearchParams;r.set("path",i),s?.modifiedAt!==void 0&&r.set("v",s.modifiedAt);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Yi(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${r.toString()}`)}function _a(e,t,i,s){const r=new URLSearchParams;r.set("path",i);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Yi(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${r.toString()}`)}const C=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function La(e){return typeof e=="string"?e:e.id}function Pr(e){return typeof e=="string"?void 0:e.cwd}function ja(e,t="local"){return`${C(t)}/sessions/${encodeURIComponent(La(e))}`}function J(e,t,i="local"){return`${ja(e,i)}/${t}`}function li(e,t,i="local"){return`${J(e,t,i)}${Fa(e)}`}function Dp(e,t="local"){return`${ja(e,t)}${Fa(e)}`}function Fa(e){const t=Pr(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function X(e,t={}){const i=Pr(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}function Do(e){return JSON.stringify({sessions:e.map(Wp)})}function Wp(e){const t=La(e),i=Pr(e);return i===void 0||i===""?{id:t}:{id:t,cwd:i}}const za={piWebStatus:(e="local")=>v(e==="local"?"/api/pi-web/status":`${C(e)}/pi-web/status`,fd),piWebRuntime:()=>v("/api/pi-web/runtime",gd)},Op={machines:()=>v("/api/machines",kd),addMachine:e=>v("/api/machines",Aa,{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`,$d),runtime:e=>v(`/api/machines/${encodeURIComponent(e)}/runtime`,Pd)},Mi={config:()=>v("/api/config",ko),saveConfig:e=>v("/api/config",ko,{method:"PUT",body:JSON.stringify({config:e})})},St={status:()=>v("/api/normal-auth/status",Id),setup:e=>v("/api/normal-auth/setup",dt,{method:"POST",body:JSON.stringify({password:e})}),login:e=>v("/api/normal-auth/login",dt,{method:"POST",body:JSON.stringify({password:e})}),changePassword:(e,t)=>v("/api/normal-auth/change-password",dt,{method:"POST",body:JSON.stringify({currentPassword:e,newPassword:t})})},Qs={plugins:()=>v("/api/plugins",pd)},Ua={workspaceActivity:(e="local")=>v(`${C(e)}/activity`,mp)},_p={projects:(e="local")=>v(`${C(e)}/projects`,j(Io)),addProject:(e,t,i,s="local")=>v(`${C(s)}/projects`,Io,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>v(`${C(t)}/projects/${encodeURIComponent(e)}`,Js,{method:"DELETE"}),projectDirectories:(e,t="local")=>v(`${C(t)}/project-directories?q=${encodeURIComponent(e)}`,j(Gs))},kt={workspaces:(e,t="local")=>v(`${C(t)}/projects/${e}/workspaces`,j(Td)),deleteWorkspace:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Gt,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,rp),workspaceFile:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,np),uploadWorkspaceFile:async(e,t,i,s,r="local")=>r==="local"?Up(e,t,i,s):v(`${C(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Ks,{method:"POST",body:JSON.stringify({path:i,contentBase64:await Fp(s)})}),createWorkspaceFile:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Ks,{method:"POST",body:JSON.stringify({path:i,contentBase64:""})}),writeWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({path:i});r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!1&&n.set("overwrite","false");const a=s instanceof Uint8Array,c=a?new Uint8Array(s):new TextEncoder().encode(s);return v(`${C(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${n.toString()}`,Wa,{method:"PUT",body:c,headers:{"Content-Type":a?"application/octet-stream":"text/plain"}})},deleteWorkspaceFile:(e,t,i,s="local")=>{const r=new URLSearchParams({path:i});return v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`,ap,{method:"DELETE"})},moveWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({fromPath:i,toPath:s});return r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!0&&n.set("overwrite","true"),v(`${C(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${n.toString()}`,lp,{method:"POST"})},createWorkspaceDirectory:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Ro,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,r="local")=>v(`${C(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Ro,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,Ed,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>_a(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>Bp(e,t,i,s)},Zs={sessions:(e,t="local")=>v(`${C(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(Vs)),startSession:(e,t="local")=>v(`${C(t)}/sessions`,Vs,{method:"POST",body:JSON.stringify({cwd:e})}),cleanupPreview:(e,t="local")=>v(`${C(t)}/sessions/cleanup/preview`,Ma,{method:"POST",body:JSON.stringify(e)}),cleanup:(e,t="local")=>v(`${C(t)}/sessions/cleanup`,Dd,{method:"POST",body:JSON.stringify(e)}),archiveMany:(e,t="local")=>v(`${C(t)}/sessions/bulk/archive`,Wd,{method:"POST",body:Do(e)}),deleteArchivedMany:(e,t="local")=>v(`${C(t)}/sessions/bulk/delete-archived`,Od,{method:"POST",body:Do(e)}),messages:(e,t,i="local")=>v(Tp(e,t,i),Ad),status:(e,t="local")=>v(li(e,"status",t),Ot),models:(e,t="local")=>v(li(e,"models",t),Hd),setModel:(e,t,i,s="local")=>v(J(e,"model",s),Ot,{method:"POST",body:X(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>v(J(e,"model/cycle",i),Ot,{method:"POST",body:X(e,{direction:t})}),thinkingLevels:(e,t="local")=>v(li(e,"thinking-levels",t),Kd),setThinkingLevel:(e,t,i="local")=>v(J(e,"thinking-level",i),Ot,{method:"POST",body:X(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>v(J(e,"thinking-level/cycle",t),Ot,{method:"POST",body:X(e)}),commands:(e,t="local")=>v(li(e,"commands",t),j(sp)),prompt:(e,t,i,s="local",r)=>v(J(e,"prompt",s),dt,{method:"POST",body:X(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...r!==void 0&&r.length>0?{attachments:r}:{}})}),saveAttachments:(e,t,i="local",s)=>v(J(e,"attachments",i),wp,{method:"POST",body:X(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>v(J(e,"shell",i),dt,{method:"POST",body:X(e,{text:t})}),runCommand:(e,t,i="local")=>v(J(e,"commands/run",i),To,{method:"POST",body:X(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>v(J(e,"commands/respond",s),To,{method:"POST",body:X(e,{requestId:t,value:i})}),abort:(e,t="local")=>v(J(e,"abort",t),xp,{method:"POST",body:X(e)}),stop:(e,t="local")=>v(J(e,"stop",t),Sp,{method:"POST",body:X(e)}),archive:(e,t="local")=>v(J(e,"archive",t),Mo,{method:"POST",body:X(e)}),archiveWithDescendants:(e,t="local")=>v(J(e,"archive-tree",t),Mo,{method:"POST",body:X(e)}),restore:(e,t="local")=>v(J(e,"restore",t),kp,{method:"POST",body:X(e)}),deleteArchived:(e,t="local")=>v(Dp(e,t),$p,{method:"DELETE"}),detachParent:(e,t="local")=>v(J(e,"detach-parent",t),Pp,{method:"POST",body:X(e)}),reloadSession:(e,t="local")=>v(J(e,"reload",t),Cp,{method:"POST",body:X(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(`${C(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Zd)},saveApiKey:(e,t,i="local")=>v(`${C(i)}/auth/api-key`,dt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>v(`${C(t)}/auth/logout`,dt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>v(`${C(t)}/auth/oauth`,ai,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>v(`${C(t)}/auth/oauth/${encodeURIComponent(e)}`,ai),respondOAuthFlow:(e,t,i,s="local")=>v(`${C(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,ai,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>v(`${C(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,ai,{method:"POST"})},$t={terminals:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(ws)),startTerminal:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ws,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Js,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,Js,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,ws,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Gt,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>v(`${C(t)}/terminal-command-runs${jp(e)}`,j(Gt)),getCommandRun:(e,t="local")=>Lp(e,t),cancelCommandRun:(e,t="local")=>v(`${C(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Gt,{method:"POST"})};async function Lp(e,t){return Xc(`${C(t)}/terminal-command-runs/${encodeURIComponent(e)}`,Gt)}function jp(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 Ba(e){if(!Np(e))return;const t=e.error;return typeof t=="string"?t:void 0}async function Fp(e){return zp(await e.arrayBuffer())}function zp(e){const t=new Uint8Array(e);let i="";for(const s of t)i+=String.fromCharCode(s);return btoa(i)}async function Up(e,t,i,s){const r=new FormData;r.set("path",i),r.set("file",s,s.name);const o=await fetch(kr(`${C("local")}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`),{method:"POST",body:r});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(Ba(n)??o.statusText)}return Ks(await o.json())}async function Bp(e,t,i,s){const r=await fetch(_a(e,t,i,{machineId:s}));if(!r.ok){const p=await r.json().catch(()=>({}));throw new Error(Ba(p)??r.statusText)}const o=await r.blob(),n=URL.createObjectURL(o),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 Np(e){return typeof e=="object"&&e!==null}const Hp={files:(e,t,i={})=>{const s=new URLSearchParams({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),i.workspaceScoped===!0&&i.projectId!==void 0&&i.workspaceId!==void 0?v(`${C(i.machineId)}/projects/${encodeURIComponent(i.projectId)}/workspaces/${encodeURIComponent(i.workspaceId)}/files?${s.toString()}`,j(Gs)):(s.set("cwd",e),v(`${C(i.machineId)}/files?${s.toString()}`,j(Gs)))}},qp={gitStatus:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,dp),gitDiff:(e,t,i,s="local")=>v(Ap(s,e,t,i),hp)},N={...za,...Op,...Mi,...St,...Qs,...Ua,..._p,...kt,...Zs,...$t,...Hp,...qp};function Kp(e,t="local",i=yr()){const s=typeof e=="string"?void 0:e.cwd,r=s===void 0||s===""?"":`?${new URLSearchParams({cwd:s}).toString()}`,o=typeof e=="string"?e:e.id,n=$a(`${Cr(t)}/sessions/${encodeURIComponent(o)}/events${r}`,void 0,i);return new WebSocket(`${Ir()}${n}`)}function kx(e,t,i,s,r="local"){const o=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Ir()}${Cr(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${o}`)}function Vp(e="local",t=yr()){const i=$a(`${Cr(e)}/events`,void 0,t);return new WebSocket(`${Ir()}${i}`)}function Cr(e){return`/api/machines/${encodeURIComponent(e)}`}function Ir(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}const Na=".pi-web/uploads";class es extends Error{constructor(t="Workspace upload cancelled"){super(t),this.name="WorkspaceUploadCancelledError"}}class Ha extends Error{constructor(t,i){super(th(t)),this.name="WorkspaceUploadBatchError",this.failures=t.map(s=>({...s})),this.responses=i.map(s=>({...s}))}}function Wo(e){return e?.uploads?.defaultFolder??Na}function Gp(e,t){return e?.uploads?.defaultFolder??t}function Rr(e,t){const i=Oo(e,"upload destination",{allowEmpty:!0}),s=Oo(t,"upload file name",{allowEmpty:!1});return i===""?s:`${i}/${s}`}function Jp(e,t,i,s={}){const r=s.xhrFactory?.()??new XMLHttpRequest;let o=!1,n=!1;return{promise:new Promise((c,p)=>{const u=g=>{o||(o=!0,p(g))},h=g=>{o||(o=!0,c(g))};r.open("PUT",Mp(e,t,i.path,Xp(s)),!0),r.responseType="json",r.setRequestHeader("Content-Type",(i.contentType??i.file.type)||"application/octet-stream"),r.upload.onprogress=g=>{s.onProgress?.(Yp(g,i.file.size))},r.onload=()=>{if(r.status>=200&&r.status<300){try{s.onProgress?.({loaded:i.file.size,total:i.file.size,percent:1,lengthComputable:!0}),h(Wa(qa(r)))}catch(g){u(g instanceof Error?g:new Error(String(g)))}return}u(new Error(oh(r)))},r.onerror=()=>{u(new Error("Workspace upload failed"))},r.onabort=()=>{u(new es(n?void 0:"Workspace upload aborted"))},r.send(i.file)}),cancel:()=>{o||(n=!0,r.abort())}}}function Qp(e,t,i,s={}){const r=s.destinationFolder??Na,o=i.map((h,g)=>({index:g,name:h.name,path:Rr(r,h.name),loaded:0,total:h.size,percent:Ar(0,h.size),lengthComputable:!0,done:!1}));let n,a=0;const c={requested:!1},p=()=>{s.onProgress?.(eh(o,a,o.every(h=>h.done)))};return{promise:(async()=>{const h=[],g=[];for(let y=0;y<i.length;y+=1){if(c.requested)throw new es;a=y;const P=i[y],I=o[y];if(!(P===void 0||I===void 0)){n=Jp(e,t,{path:I.path,file:P},{...Zp(s),onProgress:G=>{I.total=G.total,I.loaded=Math.min(G.loaded,I.total),I.percent=G.percent,I.lengthComputable=G.lengthComputable,p()}});try{const G=await n.promise;I.loaded=I.total,I.percent=1,I.lengthComputable=!0,I.done=!0,h.push(G),p()}catch(G){if(sh(G,c))throw G;const Ze=ih(G);I.loaded=I.total,I.percent=1,I.lengthComputable=!0,I.done=!0,I.error=Ze,g.push({index:y,name:P.name,path:I.path,error:Ze}),p()}finally{n=void 0}}}if(g.length>0)throw new Ha(g,h);return h})(),cancel:()=>{c.requested=!0,n?.cancel()}}}function Zp(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function Xp(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Yp(e,t){const i=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:i,percent:Ar(e.loaded,i),lengthComputable:e.lengthComputable}}function eh(e,t,i){const s=e.reduce((o,n)=>o+n.total,0),r=e.reduce((o,n)=>o+n.loaded,0);return{currentFileIndex:t,files:e.map(o=>({...o})),loaded:r,total:s,percent:Ar(r,s),done:i}}function Ar(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function th(e){return e.length===1?e[0]?.error??"Workspace upload failed":`${String(e.length)} files failed to upload`}function ih(e){return e instanceof Error?e.message:String(e)}function sh(e,t){return t.requested||e instanceof es}function Oo(e,t,i){const s=e.trim();if(s===""){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(rh(s))throw new Error(`${t} must be workspace-relative`);const r=s.split(/[\\/]+/u).filter(o=>o!==""&&o!==".");if(r.length===0){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(r.some(o=>o===".."))throw new Error(`${t} must not contain path traversal`);return r.join("/")}function rh(e){const t=e.replace(/\\/g,"/");return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}function qa(e){return e.response!==void 0&&e.response!==null&&e.response!==""?e.response:e.responseText===""?{}:JSON.parse(e.responseText)}function oh(e){const t=nh(e);return ah(t)&&typeof t.error=="string"?t.error:e.statusText||`HTTP ${String(e.status)}`}function nh(e){try{return qa(e)}catch{return}}function ah(e){return typeof e=="object"&&e!==null}function wi(){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 lh(){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,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function tt(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Ka(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const Va="local";function ys(e,t){return`${e}:${t}`}function Ga(e,t){return`${e}:${t}`}function f(e){return e.selectedMachine?.id??Va}class ch{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??Ua}async refresh(t=f(this.getState())){this.applyMachineActivitySnapshot(t,dh(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=f(this.getState())){const s=this.getState(),r=f(s)===i,o=s.machineActivities[i]??(r?s.workspaceActivities:{}),n=ph(o,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...r?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...f(s)===t?{workspaceActivities:i}:{}})}}function dh(e){const t={};for(const i of e.workspaces)Ka(i)&&(t[i.cwd]=i);return t}function ph(e,t){const i={...e};return Ka(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class hh{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=r.api??N,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=uh(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 r=s.providers.find(o=>o.id===t&&(i===void 0||o.authType===i));r!==void 0&&(r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,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(r){this.setState({authDialog:{...t,saving:!1,error:String(r)}})}}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(r=>r.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(r=>r.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(r){this.setState({error:String(r)})}}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 r=t??i.inputValue??"",o={...i};delete o.error,this.setState({authDialog:{...o,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,r,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(o=>o.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 r=s[0];if(r===void 0)return;r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,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 r=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${r}.`}),!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??"":"",r=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,o=t.prompt?.requestId??t.select?.requestId,n=r!==void 0&&r===o,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 uh(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 r=i[2];return r===void 0||r===""?{command:s}:{command:s,providerId:r}}function ei(e){return e.replaceAll(":",".")}function fh(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[r,o]of t.entries()){if(!r.startsWith(i))continue;const n=r.slice(i.length),a=s[n];a===void 0?s[n]=o:Array.isArray(a)?a.push(o):s[n]=[a,o]}return s}function xs(e,t){const i=fh(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function ue(e,t,i,s){const r=new URL(window.location.href),o=`${e}--${t}`;if(r.searchParams.delete(o),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)r.searchParams.append(o,String(n));else r.searchParams.set(o,String(i));gh(r,s)}function gh(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))}function mh(e){const t=e.files.map((s,r)=>{const o=s.size;return{index:r,name:s.name,path:Rr(e.destinationFolder,s.name),size:s.size,loaded:0,total:o,percent:Lo(0,o),lengthComputable:!0,status:r===0?"uploading":"pending"}}),i=t.reduce((s,r)=>s+r.total,0);return{id:e.id,projectId:e.projectId,workspaceId:e.workspaceId,machineId:e.machineId,destinationFolder:e.destinationFolder,overwrite:e.overwrite,createDirs:e.createDirs,files:t,currentFileIndex:t.length===0?-1:0,loaded:0,total:i,percent:Lo(0,i),status:"uploading",startedAt:e.startedAt}}function vh(e,t){const i=new Map(t.files.map(r=>[r.index,r])),s=e.files.map(r=>{const o=i.get(r.index);if(o===void 0)return r;const n={...r,path:o.path,loaded:o.loaded,total:o.total,percent:o.percent,lengthComputable:o.lengthComputable,status:o.error!==void 0?"error":o.done?"completed":t.currentFileIndex===r.index?"uploading":r.status};return o.error===void 0?delete n.error:n.error=o.error,n});return{...e,files:s,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function bh(e,t,i){const s=e.files.map((o,n)=>{const a=t[n];return{...o,...a===void 0?{}:{path:a.path,response:a},loaded:o.total,percent:1,lengthComputable:!0,status:"completed"}}),r=Tr(s);return{...e,files:s,currentFileIndex:s.length===0?-1:s.length-1,...r,status:"completed",completedAt:i}}function wh(e,t,i){const s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:r.status==="uploading"||r.index===e.currentFileIndex?{...r,status:"error",error:t}:{...r,status:"cancelled",error:"Not uploaded because an earlier file failed."});return{...e,files:s,...Tr(s),status:"error",error:t,completedAt:i}}function _o(e,t){const i="Upload cancelled",s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:{...r,status:"cancelled",error:i});return{...e,files:s,...Tr(s),status:"cancelled",error:i,completedAt:t}}function Tr(e){const t=e.reduce((i,s)=>i+s.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function Lo(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}const ci=ei("core:workspace.files");class yh{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??N,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??Qp,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=f(this.getState()),r=await this.api.workspaceTree(t.id,i.id,"",s),o=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(jo(c))return;throw c}})),n=Object.fromEntries(o.filter(a=>a!==void 0));this.setState({fileTree:r.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:Fo(this.getState().expandedDirs,t)});return}try{const r=await this.api.workspaceTree(i.id,s.id,t,f(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:r.entries},error:""})}catch(r){this.setState({error:String(r)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),ue(ci,"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"}),ue(ci,"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 r=await this.api.workspaceFile(i.id,s.id,t,f(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:r,error:""})}catch(r){if(this.getState().selectedFilePath!==t)return;if(jo(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),ue(ci,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}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(r){this.setState({error:String(r)})}}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(r){this.setState({error:String(r)})}}async moveSelectedPath(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace,r=this.getState().selectedFilePath;if(!(i===void 0||s===void 0||r===void 0||r===""||t===""))try{const o=f(this.getState());Ss(this.getState())==="directory"?(await this.api.moveWorkspaceDirectory(i.id,s.id,r,t,o),await this.refreshFiles(),this.selectDirectory(t)):(await this.api.moveWorkspaceFile(i.id,s.id,r,t,void 0,o),await this.refreshFiles(),await this.selectFile(t)),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}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 r=f(this.getState());Ss(this.getState())==="directory"?await this.api.deleteWorkspaceDirectory(t.id,i.id,s,r):await this.api.deleteWorkspaceFile(t.id,i.id,s,r),await this.refreshFiles(),this.clearSelection(),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}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===""||Ss(this.getState())==="directory"))try{await this.api.downloadWorkspaceFile(t.id,i.id,s,f(this.getState())),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),ue(ci,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}startWorkspaceUpload(t,i){const s=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(s===void 0||r===void 0){this.setState({error:"Select a workspace before uploading files."});return}if(t.length===0)return;const o=f(this.getState()),n=i.overwrite??!1,a=i.createDirs??!0;let c;try{c=mh({id:this.createUploadBatchId(),projectId:s.id,workspaceId:r.id,machineId:o,destinationFolder:i.destinationFolder,overwrite:n,createDirs:a,files:t,startedAt:this.now()})}catch(h){this.setState({error:String(h)});return}this.setUploadBatch(c);let p;try{p=this.uploadWorkspaceFiles(s.id,r.id,t,{destinationFolder:i.destinationFolder,machineId:o,overwrite:n,createDirs:a,onProgress:h=>{this.updateUploadProgress(c.id,h)}})}catch(h){return this.failUploadBatch(c.id,h),{batchId:c.id,done:Promise.resolve()}}this.uploadTasks.set(c.id,p);const u=p.promise.then(async h=>{await this.completeUploadBatch(c.id,h,i)}).catch(async h=>{await this.handleUploadFailure(c.id,h,i)}).finally(()=>{this.uploadTasks.delete(c.id)});return{batchId:c.id,done:u}}cancelWorkspaceUpload(t){const i=this.getUploadBatch(t);i?.status==="uploading"&&(this.setUploadBatch(_o(i,this.now())),this.uploadTasks.get(t)?.cancel())}clearWorkspaceUpload(t){this.uploadTasks.get(t)?.cancel(),this.uploadTasks.delete(t),this.setState({workspaceUploadBatches:Fo(this.getState().workspaceUploadBatches,t)})}updateUploadProgress(t,i){const s=this.getUploadBatch(t);s?.status==="uploading"&&this.setUploadBatch(vh(s,i))}async completeUploadBatch(t,i,s){const r=this.getUploadBatch(t);if(r?.status!=="uploading"||(this.setUploadBatch(bh(r,i,this.now()),{error:""}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();const o=i[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}async handleUploadFailure(t,i,s){const r=this.failUploadBatch(t,i);if(!(i instanceof Ha)||i.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshFiles();const o=i.responses[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}failUploadBatch(t,i){const s=this.getUploadBatch(t);if(s?.status!=="uploading")return;if(xh(i)){const n=_o(s,this.now());return this.setUploadBatch(n),n}const r=Sh(i),o=wh(s,r,this.now());return this.setUploadBatch(o,{error:r}),o}getUploadBatch(t){return this.getState().workspaceUploadBatches[t]}setUploadBatch(t,i={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[t.id]:t},...i})}isCurrentWorkspaceBatch(t){const i=this.getState();return i.selectedProject?.id===t.projectId&&i.selectedWorkspace?.id===t.workspaceId&&f(i)===t.machineId}}function jo(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function xh(e){return e instanceof es}function Sh(e){return e instanceof Error?e.message:String(e)}function Fo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Ss(e){const t=e.selectedFilePath;return t===void 0?"file":kh(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function kh(e,t,i){const s=e.find(r=>r.path===i);if(s!==void 0)return s;for(const r of Object.values(t)){const o=r.find(n=>n.path===i);if(o!==void 0)return o}}const zo=ei("core:workspace.git");class $h{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 N.gitStatus(t.id,i.id,f(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const r=this.getState().selectedDiffPath;r!==void 0&&(s.files.some(o=>o.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),ue(zo,"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"}),ue(zo,"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[r,o]=await Promise.all([N.gitDiff(i.id,s.id,{path:t},f(this.getState())),N.gitDiff(i.id,s.id,{path:t,staged:!0},f(this.getState()))]);this.setState({selectedDiff:r,selectedStagedDiff:o,error:""})}catch(r){this.setState({error:String(r)})}}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 Ph{constructor(t,i,s,r){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=r}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await N.machines(),s=await this.selectInitialMachine(i,t),r=new Set(i.map(o=>o.id));this.setState({machines:i,selectedMachine:s,machineActivities:Uo(this.getState().machineActivities,r),machineRuntimes:Uo(this.getState().machineRuntimes,r)}),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,...wi()}),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 N.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 N.deleteMachine(t.id);const r=this.getState().machines.filter(n=>n.id!==t.id),o=r.find(n=>n.id==="local")??r[0];return this.setState({machines:r,machineStatuses:ks(this.getState().machineStatuses,t.id),machineRuntimes:ks(this.getState().machineRuntimes,t.id),machineActivities:ks(this.getState().machineActivities,t.id)}),s&&o!==void 0?(i.selectFallback===!1||await this.selectMachine(o),o):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await N.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 N.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(o=>o.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const r=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await N.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(r=>N.health(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(r=>N.runtime(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function ks(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Uo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class Ch{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 N.projects(t);if(f(this.getState())!==t)return;const s=new Set(i.map(o=>o.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([o])=>s.has(o)));this.setState({projects:i,workspacesByProjectId:r})}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 N.addProject(t.trim(),void 0,i,f(this.getState())),r=this.getState().projects;this.setState({projects:[...r.filter(o=>o.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await N.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 Xs="pi-web:cached-new-sessions:v1",Ih="browserCachedNew",Mt="local";function ti(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Bo(e,t=Mt,i=ti()){if(e.messageCount!==0||e.archived===!0)return;const s=Mr(i).filter(r=>r.id!==e.id||r.machineId!==t);Er([Ys(e,t),...s],i)}function Ys(e,t=Mt){return{...e,browserCachedNew:!0,machineId:t}}function No(e,t=Mt,i=ti()){const s=Mr(i).filter(r=>r.id!==e||r.machineId!==t);Er(s,i)}function Ja(e,t,i=Mt,s=ti()){const r=new Set(t.map(c=>c.id)),o=Mr(s),n=o.filter(c=>c.machineId!==i||!r.has(c.id));return n.length!==o.length&&Er(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function Y(e){return e===void 0?!1:Th(e)&&e.browserCachedNew===!0}function Rh(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 Mr(e=ti()){try{const t=e?.getItem(Xs);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>Ah(s)):[]}catch{return[]}}function Er(e,t=ti()){try{e.length===0?t?.removeItem(Xs):t?.setItem(Xs,JSON.stringify(e))}catch{}}function Ah(e){if(!Mh(e))return[];const t=bt(e,"id"),i=bt(e,"path"),s=bt(e,"cwd"),r=bt(e,"created"),o=bt(e,"modified"),n=bt(e,"firstMessage"),a=Eh(e,"messageCount");if(t===void 0||i===void 0||s===void 0||r===void 0||o===void 0||n===void 0||a!==0)return[];const c=$s(e,"name"),p=$s(e,"parentSessionPath"),u=$s(e,"machineId")??Mt;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:r,modified:o,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function Th(e){return Ih in e}function Mh(e){return typeof e=="object"&&e!==null}function bt(e,t){const i=e[t];return typeof i=="string"?i:void 0}function $s(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Eh(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Dh(e){return Jh(e.flatMap(Dr)).filter(t=>t.parts.length>0)}function Le(e,t){return{role:e,parts:[{type:"text",text:t}]}}function _t(e,t){const i=Uh(t);return i===void 0?e:{...e,meta:i}}function Wh(e,t,i){if(i==="")return e;const s=e.at(-1),r=s?.parts.at(-1);return s?.role===t&&r?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...r,text:r.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,Le(t,i)]}function Oh(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 Dr(e){if(Lh(e))return[e];if(_(e,"role")==="bashExecution")return[_t(Hh(e),e)];const t=qh(_(e,"role")),i=Kh(ye(e,"content"),e),s=t==="user"?jh(i):void 0;if(s!==void 0)return s.map(p=>_t(p,e));const r=zh(e);if(t==="tool")return[_t({role:t,parts:i,...r===void 0?{}:{source:r}},e)];const o=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&o.length>0&&o.every(p=>p.type==="skillRead")?"skill":t,a=o.length>0?[_t({role:n,parts:o,...r===void 0?{}:{source:r}},e)]:[],c=_h(e);return c===void 0?a:[...a,_t(c,e)]}function _h(e){if(_(e,"role")!=="assistant"||_(e,"stopReason")!=="error")return;const t=_(e,"errorMessage")?.trim();return Le("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function Lh(e){const t=_(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(ye(e,"parts"))}function jh(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Fh(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 Fh(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 zh(e){const t=_(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Uh(e){const t=Bh(ye(e,"timestamp")),i=Nh(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Bh(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 Nh(e){if(_(e,"role")!=="assistant")return;const t=_(e,"provider"),i=_(e,"model"),s=_(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 Hh(e){const t=_(e,"command")??"",i=yi(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=ye(e,"output");s!=null&&i.push("",Di(s));const r=ye(e,"exitCode");r!=null&&i.push("",`exit ${Di(r)}`),yi(e,"cancelled")===!0&&i.push("","cancelled"),yi(e,"truncated")===!0&&i.push("","output truncated");const o=_(e,"fullOutputPath");return o!==void 0&&o!==""&&i.push("",`full output: ${o}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
+ `)}]}}function qh(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function Kh(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=_(i,"type"),r=_(i,"text");if(s==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(s==="thinking"){const o=_(i,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}if(s==="toolCall"){const o=_(i,"name")??"tool",n=ye(i,"arguments"),a=_(i,"id"),c=o==="read"?Gh(_(n,"path")):void 0;return c!==void 0?[{type:"skillRead",...c,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:o,summary:ii(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const o=_(i,"data"),n=_(i,"mimeType");return o!==void 0&&o!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:o}]:[{type:"text",text:"[image]"}]}return Ho(i)}).map(i=>i.type==="text"&&_(t,"role")==="toolResult"?Vh(i.text,t):i):Ho(e)}function Vh(e,t){const i=_(t,"toolCallId"),s=ye(t,"content"),r=ye(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:_(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...r===void 0?{}:{details:r},isError:yi(t,"isError")===!0}}function Gh(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 Jh(e){const t=[],i=new Map;for(const s of e){let r=[];const o={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{r.length!==0&&(t.push({role:s.role,parts:r,...o}),r=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=Qh(a),p=t.length;t.push({role:"tool",parts:[c],...o}),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&&Zh(t,c,a)){i.delete(a.toolCallId??"");continue}}r.push(a)}n()}return t}function Qh(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 Zh(e,t,i){const s=e[t.lineIndex],r=s?.parts[t.partIndex];if(s===void 0||r?.type!=="toolExecution")return!1;const o=Ei(i.details)??r.preview,n={...r,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...o===void 0?{}:{preview:o}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function Ei(e){const t=ye(e,"preview");if(!Wr(t))return;const i=_(t,"diff"),s=_(t,"error"),r=Yh(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&r===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...r===void 0?{}:{firstChangedLine:r}}}function Ho(e){return e==null?[]:typeof e=="object"?[{type:"text",text:ii(e)}]:[{type:"text",text:Di(e)}]}function ii(e){if(!Wr(e))return Di(e);const t=_(e,"command");if(t!==void 0)return t;const i=_(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(([,o])=>o!=null).slice(0,3).map(([o,n])=>`${o}: ${Xh(n)}`).join(" · ")}function Xh(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 Wr(e){return typeof e=="object"&&e!==null}function ye(e,t){return Wr(e)?e[t]:void 0}function _(e,t){const i=ye(e,t);return typeof i=="string"?i:void 0}function yi(e,t){const i=ye(e,t);return typeof i=="boolean"?i:void 0}function Yh(e,t){const i=ye(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function Di(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const eu="pi-web:prompt-draft:";function Wi(e){return`${eu}${e}`}function ts(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Qa(e,t=ts()){try{return t?.getItem(Wi(e))??""}catch{return""}}function Oi(e,t,i=ts()){try{t?i?.setItem(Wi(e),t):i?.removeItem(Wi(e))}catch{}}function Or(e,t=ts()){try{t?.removeItem(Wi(e))}catch{}}function tu(e,t,i=ts()){const s=Qa(e,i);s!==""&&(Oi(t,s,i),Or(e,i))}function iu(e,t){return Le("bash",`${t===!0?`不加入上下文
6
6
 
7
- `:""}$ ${e}`)}function Zh(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,_e("bash",t)];const r=Yh(s.text)?"":`
7
+ `:""}$ ${e}`)}function su(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Le("bash",t)];const r=ou(s.text)?"":`
8
8
 
9
- `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+r+t}]}]}function Xh(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const r=[];return!s.text.includes(`
9
+ `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+r+t}]}]}function ru(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const r=[];return!s.text.includes(`
10
10
 
11
11
  `)&&(t.output===void 0||t.output==="")&&r.push("(no output)"),t.isError===!0&&r.push(t.output??"Bash 命令失败"),t.exitCode!=null&&r.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&r.push("cancelled"),t.truncated===!0&&r.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&r.push(`完整输出:${t.fullOutputPath}`),r.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
12
12
 
13
13
  ${r.join(`
14
- `)}`}]}]}function Yh(e){const t=e.lastIndexOf(`
14
+ `)}`}]}]}function ou(e){const t=e.lastIndexOf(`
15
15
 
16
- `),i=e.lastIndexOf("$ ");return t>i}function eu(e,t){if(t.type==="message.append")return fu(e,t.message);if(t.type==="assistant.delta")return Rh(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return Ah(e,t.text);if(t.type==="tool.start")return ou(e,t);if(t.type==="tool.update")return Ga(e,t.toolCallId,i=>nu(i,t));if(t.type==="tool.end")return Va(e,t.toolCallId,t.toolName,Zt(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,Qh(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return Zh(e,t.chunk);if(t.type==="shell.end")return Xh(e,t);if(t.type==="command.output")return[...e,_e(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,_e("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:tu(e,t.message)}function tu(e,t){const i=au(t);if(i!==void 0)return Va(e,i.toolCallId,i.toolName,Zt(i.content),i.text,i.isError,i.content,i.details);const s=Ar(t);if(s.length===0)return;const r=s.map(o=>o.role==="assistant"?su(o):o).filter(o=>o.parts.length>0);return r.length===0?e:r.reduce((o,n)=>iu(o,n),e)}function iu(e,t){const i=lu(e,t);if(i.length>0)return cu(e,i,t);const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||uu(s,t)?[...e.slice(0,-1),t]:[...e,t]}function su(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function ru(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 ou(e,t){const i=t.toolName==="read"?ru(lt(t.args,"path")):void 0;if(i!==void 0)return gu(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 nu(e,t){const i=Ri(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 Va(e,t,i,s,r,o,n,a){const c=Ga(e,t,h=>{const g=Ri(a)??h.preview;return{...h,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...g===void 0?{}:{preview:g}}});if(c!==e)return c;const p=Ri(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function Ga(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const r=e[s];if(r===void 0)continue;const o=r.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(o<0)continue;const n=r.parts[o];if(n?.type!=="toolExecution")continue;const a={...r,parts:[...r.parts.slice(0,o),i(n),...r.parts.slice(o+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function au(e){if(lt(e,"role")!=="toolResult")return;const t=lt(e,"toolCallId"),i=Di(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:lt(e,"toolName")??"tool",text:Ja(i),isError:wu(e,"isError")===!0,content:i,details:Di(e,"details")}}function Ja(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Ja).filter(t=>t!=="").join(`
17
- `);if(typeof e=="object"&&e!==null){const t=lt(e,"text")??lt(e,"content")??lt(e,"output");if(t!==void 0)return t}return""}function lu(e,t){const i=Ei(t);if(i.length===0)return[];const s=[];let r=i.length;const o=Za(e)+1;for(let n=e.length-1;n>=o;n--){const a=Ei(e[n]);if(a.length===0)continue;const c=r-a.length;if(!(c<0)&&hu(a,i.slice(c,r))&&(s.unshift(n),r=c,r===0))return s}return[]}function cu(e,t,i){const s=du(e,t,i),r=s[0];if(r===void 0)return e;const o=new Set(s),n=[];for(let a=0;a<e.length;a++){a===r&&n.push(i);const c=e[a];c!==void 0&&!o.has(a)&&n.push(c)}return n}function du(e,t,i){const s=t[0];if(i.role!=="assistant"||s===void 0)return t;const r=s-1;return pu(e[r])?[r,...t]:t}function pu(e){return e?.role==="assistant"&&e.parts.length>0&&e.parts.every(t=>t.type==="text"||t.type==="thinking")}function Ei(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function hu(e,t){return e.length===t.length&&e.every((i,s)=>Qa(i,t[s]))}function Qa(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:zo(e.path)===zo(t.path)||e.name===t.name}function zo(e){return e.replace(/\\/g,"/")}function uu(e,t){return Bo(e)===Bo(t)}function Bo(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
16
+ `),i=e.lastIndexOf("$ ");return t>i}function nu(e,t){if(t.type==="message.append")return yu(e,t.message);if(t.type==="assistant.delta")return Wh(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return Oh(e,t.text);if(t.type==="tool.start")return pu(e,t);if(t.type==="tool.update")return Xa(e,t.toolCallId,i=>hu(i,t));if(t.type==="tool.end")return Za(e,t.toolCallId,t.toolName,ii(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,iu(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return su(e,t.chunk);if(t.type==="shell.end")return ru(e,t);if(t.type==="command.output")return[...e,Le(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,Le("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:au(e,t.message)}function au(e,t){const i=uu(t);if(i!==void 0)return Za(e,i.toolCallId,i.toolName,ii(i.content),i.text,i.isError,i.content,i.details);const s=Dr(t);if(s.length===0)return;const r=s.map(o=>o.role==="assistant"?cu(o):o).filter(o=>o.parts.length>0);return r.length===0?e:r.reduce((o,n)=>lu(o,n),e)}function lu(e,t){const i=fu(e,t);if(i.length>0)return gu(e,i,t);const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||wu(s,t)?[...e.slice(0,-1),t]:[...e,t]}function cu(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function du(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 pu(e,t){const i=t.toolName==="read"?du(pt(t.args,"path")):void 0;if(i!==void 0)return xu(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||ii(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function hu(e,t){const i=Ei(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 Za(e,t,i,s,r,o,n,a){const c=Xa(e,t,h=>{const g=Ei(a)??h.preview;return{...h,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...g===void 0?{}:{preview:g}}});if(c!==e)return c;const p=Ei(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function Xa(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const r=e[s];if(r===void 0)continue;const o=r.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(o<0)continue;const n=r.parts[o];if(n?.type!=="toolExecution")continue;const a={...r,parts:[...r.parts.slice(0,o),i(n),...r.parts.slice(o+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function uu(e){if(pt(e,"role")!=="toolResult")return;const t=pt(e,"toolCallId"),i=Li(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:pt(e,"toolName")??"tool",text:Ya(i),isError:Pu(e,"isError")===!0,content:i,details:Li(e,"details")}}function Ya(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Ya).filter(t=>t!=="").join(`
17
+ `);if(typeof e=="object"&&e!==null){const t=pt(e,"text")??pt(e,"content")??pt(e,"output");if(t!==void 0)return t}return""}function fu(e,t){const i=_i(t);if(i.length===0)return[];const s=[];let r=i.length;const o=tl(e)+1;for(let n=e.length-1;n>=o;n--){const a=_i(e[n]);if(a.length===0)continue;const c=r-a.length;if(!(c<0)&&bu(a,i.slice(c,r))&&(s.unshift(n),r=c,r===0))return s}return[]}function gu(e,t,i){const s=mu(e,t,i),r=s[0];if(r===void 0)return e;const o=new Set(s),n=[];for(let a=0;a<e.length;a++){a===r&&n.push(i);const c=e[a];c!==void 0&&!o.has(a)&&n.push(c)}return n}function mu(e,t,i){const s=t[0];if(i.role!=="assistant"||s===void 0)return t;const r=s-1;return vu(e[r])?[r,...t]:t}function vu(e){return e?.role==="assistant"&&e.parts.length>0&&e.parts.every(t=>t.type==="text"||t.type==="thinking")}function _i(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function bu(e,t){return e.length===t.length&&e.every((i,s)=>el(i,t[s]))}function el(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:qo(e.path)===qo(t.path)||e.name===t.name}function qo(e){return e.replace(/\\/g,"/")}function wu(e,t){return Ko(e)===Ko(t)}function Ko(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
18
18
 
19
- `)}function fu(e,t){const i=Ar(t);return i.length===0?e:[...e,...i]}function gu(e,t){const i=e.at(-1);return mu(e,t)?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function mu(e,t){const i=Ei(t);if(t.role!=="skill"||i.length===0)return!1;const s=Za(e)+1;return i.every(r=>vu(e,r,s))}function vu(e,t,i){for(let s=e.length-1;s>=i;s--)if(Ei(e[s]).some(r=>Qa(r,t)))return!0;return!1}function Za(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="user")return t;return-1}function bu(e){return typeof e=="object"&&e!==null}function Di(e,t){return bu(e)?e[t]:void 0}function lt(e,t){const i=Di(e,t);return typeof i=="string"?i:void 0}function wu(e,t){const i=Di(e,t);return typeof i=="boolean"?i:void 0}const yu="pi-web:chat-history:v2:",xu=1800*1e3;function Su(e){try{const t=sessionStorage.getItem(Wi(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!Ru(i))return;if(Date.now()-i.savedAt>xu){sessionStorage.removeItem(Wi(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function ku(e,t){try{sessionStorage.setItem(Wi(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function $u(e){try{sessionStorage.removeItem(Wi(e))}catch{}}function Pu(e,t){if(e===void 0||!Qs(e))return t;if(!Qs(t))return e;if(Cu(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),r=new Array(s-i);return No(r,i,e),No(r,i,t),Iu(r)?t:{start:i,total:Math.max(e.total,t.total),messages:r}}function Cu(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Iu(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function No(e,t,i){i.messages.forEach((s,r)=>{e[i.start-t+r]=s})}function Wi(e){return`${yu}${e}`}function Ru(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:r}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof r=="number"&&Qs({messages:t,start:i,total:s})}function Qs(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(Au)}function Au(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 Tu={read:Su,write:ku,remove:$u};class Mu{constructor(t=Tu){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return qo(this.rawHistoryPage(t))}mergeHistory(t,i){const s=Pu(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),qo(s)}applyLiveEvent(t,i){return eu(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 qo(e){const t=e?.start??0;return{messages:Ih(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Xa(e,t=e.length){const i=e.slice(0,t),s=Eu(i,t);if(s!==void 0)return s;const r=Du(i,t);if(r!==void 0)return r;const o=Math.max(i.lastIndexOf(" "),i.lastIndexOf(`
20
- `))+1,n=i.slice(o);if(i.slice(0,o).endsWith("@ "))return{kind:"file",query:n,from:o-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&o===0)return{kind:"command",query:n.slice(1),from:o,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:o,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:o,to:t,fileScope:"tracked"}}function Ya(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Eu(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 Du(e,t){const i=e.lastIndexOf(`
21
- `)+1,s=e.slice(i),r=Ho(s,"@ "),o=Ho(s,"!@"),n=Math.max(r,o);if(n===-1)return;const a=n===o?"!@":"@ ",c=i+n,p=c+a.length;return{kind:"file",query:e.slice(p),from:c,to:t,fileScope:"all",allPrefix:a}}function Ho(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||Wu(e[i-1]))return i;return-1}function Wu(e){return e===" "||e===" "}function Oi(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Lu(e).startsWith("/")?{kind:"command"}:Xa(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function Ou(e){return Oi(e).kind==="shell"}function _u(e,t){return e.kind!==t.kind?!1:e.kind==="shell"&&t.kind==="shell"?e.excludeFromContext===t.excludeFromContext:!0}function Lu(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
- `))+1;return e.slice(t)}class el{constructor(t="normal"){this.scope=t,this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,r="local"){this.close(),this.machineId=r,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),il(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=Up(this.session,this.machineId,this.scope);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 tl(t);ju(i)&&this.onEvent?.(i)}}class Ko{constructor(t="normal"){this.scope=t,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),il(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=zp(this.machineId,this.scope);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 tl(t);Uu(i)&&this.onEvent?.(i)}}function ju(e){const t=Er(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 Fu(e){const t=Er(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function Uu(e){const t=Er(e);return Fu(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function Er(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function tl(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 il(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 Xt(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class Xi{constructor(t,i,s=Xt()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[r,o]of zu(t,i,s))this.values.set(r,o)}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 Dr(e){return typeof e=="string"&&e!==""?e:void 0}function zu(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const r=JSON.parse(s);if(!Bu(r))return[];const o=[];for(const n of r.entries){const a=n[0],c=t(n[1]);c!==void 0&&o.push([a,c])}return o}catch{return[]}}function Bu(e){return!Nu(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 Nu(e){return typeof e=="object"&&e!==null}class qu{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 Hu="pi-web:session-selection:v1";class Ku{constructor(t=Xt()){this.sessionIdsByCwd=new Xi(Hu,Dr,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function Vu(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return Ju(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>r.archived!==!0):e.find(r=>r.archived!==!0)}function Gu(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function Ju(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function Qu(e,t,i){return vi(e,[t],i)}function vi(e,t,i){const s=new Set(t);return e.map(r=>s.has(r.id)?{...r,archived:!0,archivedAt:i}:r)}function Zu(e,t,i){return bi(e,t,[i])}function bi(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),r=e.find(o=>!s.has(o.id)&&o.archived!==!0);return r===void 0?{type:"clear"}:{type:"select",session:r}}const Dt=100,Vo=4;class Xu{constructor(t,i,s,r=new qu,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.socket=o.socket??new el,this.api=o.api??N,this.transcripts=o.transcripts??new Mu}applyGlobalEvent(t){t.type==="status.update"?this.queueStatusUpdate(t.status):t.type==="activity.update"?this.queueActivityUpdate(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingUpdates()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates(),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();Gu(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);jo(s,i);const r=Js(s,i);this.setState({sessions:[r,...this.getState().sessions.filter(o=>o.id!==r.id)]}),await this.selectSession(r)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return Vu(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.clearPendingUpdates();const r=this.sessionCacheKey(t.id),o=this.transcripts.cachedView(r);this.setState({selectedSession:t,...o,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:Dt},f(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(r,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:Dt},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(r,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)&&nf(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:Dt},f(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(r)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i,s,r="inline"){const o=t.trim(),n=s!==void 0&&s.length>0;if(!n&&o.startsWith("/"))return this.runCommand(t);if(!n&&Ou(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&&r==="folder"){const h=(await this.api.saveAttachments(a,s,p)).map(w=>Ya(w.path,!1)).join(" "),g=t===""?h:`${t}
19
+ `)}function yu(e,t){const i=Dr(t);return i.length===0?e:[...e,...i]}function xu(e,t){const i=e.at(-1);return Su(e,t)?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Su(e,t){const i=_i(t);if(t.role!=="skill"||i.length===0)return!1;const s=tl(e)+1;return i.every(r=>ku(e,r,s))}function ku(e,t,i){for(let s=e.length-1;s>=i;s--)if(_i(e[s]).some(r=>el(r,t)))return!0;return!1}function tl(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="user")return t;return-1}function $u(e){return typeof e=="object"&&e!==null}function Li(e,t){return $u(e)?e[t]:void 0}function pt(e,t){const i=Li(e,t);return typeof i=="string"?i:void 0}function Pu(e,t){const i=Li(e,t);return typeof i=="boolean"?i:void 0}const Cu="pi-web:chat-history:v2:",Iu=1800*1e3;function Ru(e){try{const t=sessionStorage.getItem(ji(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!Wu(i))return;if(Date.now()-i.savedAt>Iu){sessionStorage.removeItem(ji(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function Au(e,t){try{sessionStorage.setItem(ji(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Tu(e){try{sessionStorage.removeItem(ji(e))}catch{}}function Mu(e,t){if(e===void 0||!er(e))return t;if(!er(t))return e;if(Eu(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),r=new Array(s-i);return Vo(r,i,e),Vo(r,i,t),Du(r)?t:{start:i,total:Math.max(e.total,t.total),messages:r}}function Eu(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Du(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function Vo(e,t,i){i.messages.forEach((s,r)=>{e[i.start-t+r]=s})}function ji(e){return`${Cu}${e}`}function Wu(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:r}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof r=="number"&&er({messages:t,start:i,total:s})}function er(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(Ou)}function Ou(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 _u={read:Ru,write:Au,remove:Tu};class Lu{constructor(t=_u){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return Go(this.rawHistoryPage(t))}mergeHistory(t,i){const s=Mu(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),Go(s)}applyLiveEvent(t,i){return nu(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 Go(e){const t=e?.start??0;return{messages:Dh(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function il(e,t=e.length){const i=e.slice(0,t),s=ju(i,t);if(s!==void 0)return s;const r=Fu(i,t);if(r!==void 0)return r;const o=Math.max(i.lastIndexOf(" "),i.lastIndexOf(`
20
+ `))+1,n=i.slice(o);if(i.slice(0,o).endsWith("@ "))return{kind:"file",query:n,from:o-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&o===0)return{kind:"command",query:n.slice(1),from:o,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:o,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:o,to:t,fileScope:"tracked"}}function sl(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function ju(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 Fu(e,t){const i=e.lastIndexOf(`
21
+ `)+1,s=e.slice(i),r=Jo(s,"@ "),o=Jo(s,"!@"),n=Math.max(r,o);if(n===-1)return;const a=n===o?"!@":"@ ",c=i+n,p=c+a.length;return{kind:"file",query:e.slice(p),from:c,to:t,fileScope:"all",allPrefix:a}}function Jo(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||zu(e[i-1]))return i;return-1}function zu(e){return e===" "||e===" "}function Fi(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Nu(e).startsWith("/")?{kind:"command"}:il(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function Uu(e){return Fi(e).kind==="shell"}function Bu(e,t){return e.kind!==t.kind?!1:e.kind==="shell"&&t.kind==="shell"?e.excludeFromContext===t.excludeFromContext:!0}function Nu(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
+ `))+1;return e.slice(t)}class rl{constructor(t="normal"){this.scope=t,this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,r="local"){this.close(),this.machineId=r,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),nl(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=Kp(this.session,this.machineId,this.scope);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 ol(t);Hu(i)&&this.onEvent?.(i)}}class Qo{constructor(t="normal"){this.scope=t,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),nl(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Vp(this.machineId,this.scope);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 ol(t);Ku(i)&&this.onEvent?.(i)}}function Hu(e){const t=_r(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 qu(e){const t=_r(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function Ku(e){const t=_r(e);return qu(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function _r(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function ol(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 nl(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 si(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class is{constructor(t,i,s=si()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[r,o]of Vu(t,i,s))this.values.set(r,o)}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 Lr(e){return typeof e=="string"&&e!==""?e:void 0}function Vu(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const r=JSON.parse(s);if(!Gu(r))return[];const o=[];for(const n of r.entries){const a=n[0],c=t(n[1]);c!==void 0&&o.push([a,c])}return o}catch{return[]}}function Gu(e){return!Ju(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 Ju(e){return typeof e=="object"&&e!==null}class Qu{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 Zu="pi-web:session-selection:v1";class Xu{constructor(t=si()){this.sessionIdsByCwd=new is(Zu,Lr,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function Yu(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return tf(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>r.archived!==!0):e.find(r=>r.archived!==!0)}function ef(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function tf(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function sf(e,t,i){return xi(e,[t],i)}function xi(e,t,i){const s=new Set(t);return e.map(r=>s.has(r.id)?{...r,archived:!0,archivedAt:i}:r)}function rf(e,t,i){return Si(e,t,[i])}function Si(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),r=e.find(o=>!s.has(o.id)&&o.archived!==!0);return r===void 0?{type:"clear"}:{type:"select",session:r}}const Lt=100,Zo=4;class of{constructor(t,i,s,r=new Qu,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.socket=o.socket??new rl,this.api=o.api??N,this.transcripts=o.transcripts??new Lu}applyGlobalEvent(t){t.type==="status.update"?this.queueStatusUpdate(t.status):t.type==="activity.update"?this.queueActivityUpdate(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingUpdates()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates(),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();ef(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);Bo(s,i);const r=Ys(s,i);this.setState({sessions:[r,...this.getState().sessions.filter(o=>o.id!==r.id)]}),await this.selectSession(r)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return Yu(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.clearPendingUpdates();const r=this.sessionCacheKey(t.id),o=this.transcripts.cachedView(r);this.setState({selectedSession:t,...o,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:Lt},f(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(r,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:Lt},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(r,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(Y(t)&&hf(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:Lt},f(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(r)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i,s,r="inline"){const o=t.trim(),n=s!==void 0&&s.length>0;if(!n&&o.startsWith("/"))return this.runCommand(t);if(!n&&Uu(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&&r==="folder"){const h=(await this.api.saveAttachments(a,s,p)).map(y=>sl(y.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:sl(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,_e("user",t)]});try{await this.api.shell(i,t,f(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,_e("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(r){this.setState({messages:[...this.getState().messages,_e("system",String(r))],error:String(r)})}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(r){this.setState({error:String(r)})}}}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=Qu(i.sessions,t.id,new Date().toISOString()),r=Zu(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),r.type==="select"?await this.selectSession(r.session):r.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],r=this.getState(),o=vi(r.sessions,s,new Date().toISOString()),n=bi(o,r.selectedSession?.id,s);this.setState({sessions:o}),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=Jo(t).filter(s=>s.archived!==!0&&!Z(s));if(i.length!==0)try{const s=f(this.getState()),{succeededIds:r,failures:o,generatedAt:n}=await this.archiveSessionBatch(i,s);if(r.length>0){const a=this.getState(),c=vi(a.sessions,r,n??new Date().toISOString()),p=bi(c,a.selectedSession?.id,r);this.setState({sessions:c}),p.type==="select"?await this.selectSession(p.session):p.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures("Archive",o)}catch(s){this.setState({error:`Archive failed: ${Zs(s)}`})}}async deleteArchivedSessions(t){const i=Jo(t).filter(o=>o.archived===!0);if(i.length===0)return;const s=f(this.getState()),r=this.getState().machineRuntimes[s];if(r?.ok!==!0||!Be(r,Oe.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}try{const{succeededIds:o,failures:n}=await this.deleteArchivedSessionBatch(i,s);if(o.length>0){const a=new Set(o),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.applyBulkSessionFailures("Delete",n)}catch(o){this.setState({error:`Delete failed: ${Zs(o)}`})}}async archiveSessionBatch(t,i){const s=this.getState().machineRuntimes[i];if(s?.ok===!0&&Be(s,Oe.sessionsBulkMutations)){const o=await this.api.archiveMany(t,i);return{succeededIds:o.archivedSessionIds,failures:Zo(o.failures),generatedAt:o.generatedAt}}const r=await Yo(t,Vo,async o=>(await this.api.archive(o,i),o.id));return{succeededIds:Qo(r),failures:Xo(t,r)}}async deleteArchivedSessionBatch(t,i){const s=this.getState().machineRuntimes[i];if(s?.ok===!0&&Be(s,Oe.sessionsBulkMutations)){const o=await this.api.deleteArchivedMany(t,i);return{succeededIds:o.deletedSessionIds,failures:Zo(o.failures)}}const r=await Yo(t,Vo,async o=>(await this.api.deleteArchived(o,i),o.id));return{succeededIds:Qo(r),failures:Xo(t,r)}}async applySessionCleanupResult(t,i=f(this.getState())){if(f(this.getState())!==i)return;const s=t.archivedSessionIds,r=t.deletedSessionIds;if(s.length>0||r.length>0){const o=this.getState(),n=new Set(r),a=[...s,...r],c=vi(o.sessions,s,t.generatedAt).filter(u=>!n.has(u.id)),p=o.selectedSession!==void 0&&a.includes(o.selectedSession.id);if(this.setState({sessions:c,sessionStatuses:Go(o.sessionStatuses,a),sessionActivities:Go(o.sessionActivities,a),...p?{status:void 0,activity:void 0}:{}}),o.selectedSession!==void 0&&n.has(o.selectedSession.id)){const u=c.find(h=>h.archived!==!0)??c[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}else{const u=bi(c,o.selectedSession?.id,s);u.type==="select"?await this.selectSession(u.session):u.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(i)}async refreshCurrentWorkspaceSessions(t=f(this.getState())){const i=this.getState().selectedWorkspace;if(i!==void 0)try{const s=Ha(i.path,await this.api.sessions(i.path,t),t);if(f(this.getState())!==t||this.getState().selectedWorkspace?.id!==i.id)return;const r=this.getState().selectedSession;if(this.setState({sessions:s}),r===void 0)return;const o=s.find(a=>a.id===r.id);if(o!==void 0){o!==r&&this.setState({selectedSession:o});return}const n=s.find(a=>a.archived!==!0)??s[0];n!==void 0?await this.selectSession(n):this.deselectSession({forgetRememberedSelection:!0})}catch(s){f(this.getState())===t&&this.getState().selectedWorkspace?.id===i.id&&this.setState({error:String(s)})}}async deleteCachedNewSession(t=this.getState().selectedSession){if(!Z(t))return;this.api.stop(t,f(this.getState())).catch(()=>{}),Fo(t.id,f(this.getState())),Mr(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(r=>r.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(r=>r.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||!Be(s,Oe.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(r){this.setState({error:String(r)})}}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(r){this.setState({error:String(r)})}}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.flushPendingUpdates();const[s,r]=await Promise.all([this.api.messages(i,{limit:Dt},f(this.getState())),this.api.status(i,f(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...o,status:r,activity:this.getState().sessionActivities[t],...this.setStreamCatchup(r.isStreaming?t:void 0)}),this.applyStatus(r)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionFailures(t,i){i.length!==0&&this.setState({error:`${t} failed for ${String(i.length)} session${i.length===1?"":"s"}: ${i.join("; ")}`})}sessionCacheKey(t){return qa(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()),r=await this.api.startSession(t.cwd,s);jo(r,s),Jh(this.sessionCacheKey(t.id),this.sessionCacheKey(r.id)),Fo(t.id,s);const o=Js(r,s);this.setState({sessions:[o,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(o,{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(Sh(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,_e(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&Mi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,r=[t.session,...this.getState().sessions.filter(o=>o.id!==t.session?.id)];this.setState({sessions:r,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},...sf(i,t.sessionId,t.messageCount),...s?{sessionActivities:Yu(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=o=>{if(o.id!==t)return o;const n={...o};return i===void 0||i===""?delete n.name:n.name=i,n},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:r===void 0?void 0:s(r)})}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(rf(t))return}if(t.type==="status.update"){this.queueStatusUpdate(t.status);return}if(t.type==="activity.update"){this.queueActivityUpdate(t.activity);return}if(of(t)){this.queueTranscriptEvent(t);return}this.flushPendingUpdates();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.schedulePendingFlush()}queueStatusUpdate(t){this.pendingStatusBySession.set(t.sessionId,t),this.schedulePendingFlush()}queueActivityUpdate(t){this.pendingActivityBySession.set(t.sessionId,t),this.schedulePendingFlush()}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){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})}if(this.pendingActivityBySession.size>0){const t=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(const i of t)this.applyActivity(i)}if(this.pendingStatusBySession.size>0){const t=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(const i of t)this.applyStatus(i)}}clearPendingUpdates(){this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=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:Dt},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 Yu(e,t){return sl(e,t)}function sl(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Go(e,t){if(t.length===0)return e;const i=new Set(t);return Object.fromEntries(Object.entries(e).filter(([s])=>!i.has(s)))}function Jo(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 Qo(e){return e.filter(ef).map(t=>t.value)}function Zo(e){return e.map(t=>`${t.sessionId}: ${t.error}`)}function Xo(e,t){return t.flatMap((i,s)=>tf(i)?[`${e[s]?.id??"unknown"}: ${Zs(i.reason)}`]:[])}async function Yo(e,t,i){const s=e.map((c,p)=>({item:c,index:p})),r=[];let o=0;async function n(){for(;o<s.length;){const c=s[o];if(c===void 0)return;o+=1;try{r[c.index]={status:"fulfilled",value:await i(c.item)}}catch(p){r[c.index]={status:"rejected",reason:p}}}}const a=Math.min(Math.max(1,t),s.length);return await Promise.all(Array.from({length:a},()=>n())),r}function ef(e){return e.status==="fulfilled"}function tf(e){return e.status==="rejected"}function Zs(e){return e instanceof Error?e.message:String(e)}function sf(e,t,i){if(i===void 0)return{};const r=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,o=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...o!==e.selectedSession?{selectedSession:o}:{}}}function rf(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 of(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function nf(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("session not found")||t.includes("未找到会话")}class af{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 lf="pi-web:workspace-selection:v1";class cf{constructor(t=Xt()){this.workspaceIdsByProject=new Xi(lf,Dr,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function df(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e[0]:e[0]}class pf{constructor(t,i,s,r,o=new af,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=r,this.workspaceSelection=o,this.api=n.api??N}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...gi()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(ms(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,...gi()});try{const r=await this.api.workspaces(t.id,s);if(f(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:r,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:r},isLoadingWorkspaces:!1});const o=df(r,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(ms(s,t.id))});o?await this.selectWorkspace(o,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){f(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(r),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=f(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:ms(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...gi()});try{const r=Ha(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:r});const o=this.sessions.preferredSession(t.path,r,i?.sessionId);o?await this.sessions.selectSession(o,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){f(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(r)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(r=>r.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),r=this.getState();if(r.selectedProject?.id!==t||r.selectedWorkspace?.id!==i)return;const o=uf(s);o!==void 0?await this.selectWorkspace(o):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),r={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:r}):this.setState({workspacesByProjectId:r})}}function hf(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function uf(e){return e.find(t=>t.isMain)??e[0]}const ff="pi-web:machine-navigation:v1";class gf{constructor(t=Xt()){this.snapshotsByMachine=new Xi(ff,vf,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?sn(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,sn(t))}forget(t){this.snapshotsByMachine.delete(t)}}function mf(e){return{machineId:e,surface:{}}}function en(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??Na,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 tn(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 sn(e){return{...e,surface:{...e.surface}}}function vf(e){if(!ol(e))return;const t=ze(e,"machineId");if(t===void 0)return;const i=rl(ze(e,"tool")),s=wf(ze(e,"view"));return{machineId:t,projectId:ze(e,"projectId"),workspaceId:ze(e,"workspaceId"),sessionId:ze(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:bf(e.surface)}}function bf(e){return ol(e)?{selectedFilePath:ze(e,"selectedFilePath"),selectedDiffPath:ze(e,"selectedDiffPath"),selectedTerminalId:ze(e,"selectedTerminalId")}:{}}function wf(e){return e==="navigation"||e==="chat"?e:rl(e)}function rl(e){return yf(e)?e:void 0}function yf(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function ze(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function ol(e){return typeof e=="object"&&e!==null}const xf="pi-web:terminal-selection:v1";class Sf{constructor(t=Xt()){this.terminalIdsByCwd=new Xi(xf,Dr,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 gx(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>!r.exited)??e[0]:e.find(r=>!r.exited)??e[0]}function mx(e){return e.find(t=>!t.exited)??e[0]}const nl=1200,kf=["mod","alt","shift"];class $f{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const r=ll(t);if(r===void 0)return!1;const o=Wr(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,r],o))return!0;if(this.clearPending(),!Vt(r))return!1}else if(!Vt(r))return!1;return this.handleSequence([r],o)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(o=>Wf(o.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(o=>Or(o.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},nl)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Wr(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Pf(p,t,u);return h===void 0?[]:[h]}),r=new Map;for(const p of s)r.set(p.key,[...r.get(p.key)??[],p]);const o=new Map;for(const p of r.values()){const u=[...p].sort(Xs)[0];u!==void 0&&o.set(u.key,u)}const n=[...o.values()].sort(Rf),a=new Map,c=new Map;for(const p of s){const u=o.get(p.key);if(u===void 0)continue;const h=Af(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:rn(u),w=h?[...a.get(p)??[]].sort(Xs).map(rn):[];return{...p,active:h,shadows:w,...g===void 0?{}:{shadowedBy:g}}}).sort((p,u)=>p.order-u.order)}function xs(e){return cl(e,{requireFirstChordActivator:!0})}function al(e){const t=cl(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function wi(e){return al(e).map(t=>t.split("+").map(pl).join("+")).join(" ")}function ll(e){if(e.isComposing)return;const t=Ef(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 Vt(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Pf(e,t,i){const s=Cf(e.id,t);if(s===null)return;const r=s??e.shortcut;if(r===void 0||r==="")return;const o=al(r),n=o[0];if(!(n===void 0||!Vt(n)))return{action:e,shortcut:o.join(" "),source:s===void 0?"default":"custom",tokens:o,key:If(o),order:i}}function Cf(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function If(e){return e.join("\0")}function rn(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Xs(e,t){return on(e.source)-on(t.source)||nn(e.action.id,t.action.id)||nn(e.action.title,t.action.title)||e.order-t.order}function Rf(e,t){return e.tokens.length-t.tokens.length||Xs(e,t)}function Af(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&Or(e.tokens,i.tokens))}function on(e){switch(e){case"custom":return 0;case"default":return 1}}function nn(e,t){return e<t?-1:e>t?1:0}function cl(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"请输入快捷键,选择无,或重置为默认值。"};const s=[],r=i.split(/\s+/u).filter(o=>o!=="");for(const[o,n]of r.entries()){const a=Tf(n);if(!a.ok)return a;if(o===0&&t.requireFirstChordActivator&&!Vt(a.token))return{ok:!1,message:"快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。"};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Tf(e){const t=e.split("+").filter(o=>o!=="");if(t.length===0)return{ok:!1,message:"快捷键组合必须包含一个按键。"};const i=new Set;let s;for(const o of t){const n=Mf(o);if(n!==void 0){if(i.has(n))return{ok:!1,message:`快捷键包含重复的 ${pl(n)} 修饰键。`};i.add(n);continue}const a=dl(o);if(a===void 0)return{ok:!1,message:`不支持的快捷键按键:${o}`};if(s!==void 0)return{ok:!1,message:"每个快捷键组合只能包含一个非修饰键。"};s=a}return s===void 0?{ok:!1,message:"快捷键组合必须包含一个按键。"}:{ok:!0,token:[...kf.filter(o=>i.has(o)),s].join("+")}}function Mf(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 dl(e){const t=Df(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 Ef(e){if(e===" ")return"space";const t=e.toLowerCase();return dl(t)}function Df(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 pl(e){return e==="mod"?an()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?an()?"⌥":"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 Wf(e,t){return e.length===t.length&&Or(e,t)}function Or(e,t){return t.every((i,s)=>e[s]===i)}function an(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const Of={archiveIdleEnabled:!0,archiveIdleDays:"30",deleteArchivedEnabled:!1,deleteArchivedDays:"90"};function Ut(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:"请至少启用一项清理操作。"};const t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){const i=dn(e.archiveIdleDays,"归档空闲会话天数");if(typeof i=="string")return{ok:!1,error:i};t.archiveIdleDays=i}if(e.deleteArchivedEnabled){const i=dn(e.deleteArchivedDays,"删除已归档会话天数");if(typeof i=="string")return{ok:!1,error:i};t.deleteArchivedDays=i}return{ok:!0,request:t}}function $t(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function ln(e){if(!e.canCleanup||e.loading===!0||e.running===!0||e.preview===void 0)return!1;const t=Ut(e.draft);return!t.ok||$t(t.request)!==$t(e.previewRequest)?!1:yi(e.preview)}function yi(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function hl(e,t){const i=e.projects.map(r=>r.cwd);if(t===void 0)return i;const s=new Set(t);return i.filter(r=>s.has(r))}function cn(e,t){const i=new Set(hl(e,t)),s=e.projects.filter(r=>i.has(r.cwd));return{...e,projects:s,totals:s.reduce((r,o)=>({archiveCount:r.archiveCount+o.archiveCount,deleteCount:r.deleteCount+o.deleteCount}),{archiveCount:0,deleteCount:0})}}function _f(e,t){return t(Lf(e))}function Lf(e){const t=e.totals.archiveCount,i=e.totals.deleteCount,s=[];return t>0&&s.push(`归档 ${String(t)} 个空闲会话`),i>0&&s.push(`永久删除 ${String(i)} 个已归档会话`),`运行清理并${s.length===0?"执行清理":s.join("并")}?
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:al(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Le("user",t)]});try{await this.api.shell(i,t,f(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Le("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(r){this.setState({messages:[...this.getState().messages,Le("system",String(r))],error:String(r)})}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(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(Y(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,f(this.getState()));const i=this.getState(),s=sf(i.sessions,t.id,new Date().toISOString()),r=rf(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),r.type==="select"?await this.selectSession(r.session):r.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||Y(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],r=this.getState(),o=xi(r.sessions,s,new Date().toISOString()),n=Si(o,r.selectedSession?.id,s);this.setState({sessions:o}),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=Yo(t).filter(s=>s.archived!==!0&&!Y(s));if(i.length!==0)try{const s=f(this.getState()),{succeededIds:r,failures:o,generatedAt:n}=await this.archiveSessionBatch(i,s);if(r.length>0){const a=this.getState(),c=xi(a.sessions,r,n??new Date().toISOString()),p=Si(c,a.selectedSession?.id,r);this.setState({sessions:c}),p.type==="select"?await this.selectSession(p.session):p.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures("Archive",o)}catch(s){this.setState({error:`Archive failed: ${tr(s)}`})}}async deleteArchivedSessions(t){const i=Yo(t).filter(o=>o.archived===!0);if(i.length===0)return;const s=f(this.getState()),r=this.getState().machineRuntimes[s];if(r?.ok!==!0||!qe(r,_e.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}try{const{succeededIds:o,failures:n}=await this.deleteArchivedSessionBatch(i,s);if(o.length>0){const a=new Set(o),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.applyBulkSessionFailures("Delete",n)}catch(o){this.setState({error:`Delete failed: ${tr(o)}`})}}async archiveSessionBatch(t,i){const s=this.getState().machineRuntimes[i];if(s?.ok===!0&&qe(s,_e.sessionsBulkMutations)){const o=await this.api.archiveMany(t,i);return{succeededIds:o.archivedSessionIds,failures:tn(o.failures),generatedAt:o.generatedAt}}const r=await rn(t,Zo,async o=>(await this.api.archive(o,i),o.id));return{succeededIds:en(r),failures:sn(t,r)}}async deleteArchivedSessionBatch(t,i){const s=this.getState().machineRuntimes[i];if(s?.ok===!0&&qe(s,_e.sessionsBulkMutations)){const o=await this.api.deleteArchivedMany(t,i);return{succeededIds:o.deletedSessionIds,failures:tn(o.failures)}}const r=await rn(t,Zo,async o=>(await this.api.deleteArchived(o,i),o.id));return{succeededIds:en(r),failures:sn(t,r)}}async applySessionCleanupResult(t,i=f(this.getState())){if(f(this.getState())!==i)return;const s=t.archivedSessionIds,r=t.deletedSessionIds;if(s.length>0||r.length>0){const o=this.getState(),n=new Set(r),a=[...s,...r],c=xi(o.sessions,s,t.generatedAt).filter(u=>!n.has(u.id)),p=o.selectedSession!==void 0&&a.includes(o.selectedSession.id);if(this.setState({sessions:c,sessionStatuses:Xo(o.sessionStatuses,a),sessionActivities:Xo(o.sessionActivities,a),...p?{status:void 0,activity:void 0}:{}}),o.selectedSession!==void 0&&n.has(o.selectedSession.id)){const u=c.find(h=>h.archived!==!0)??c[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}else{const u=Si(c,o.selectedSession?.id,s);u.type==="select"?await this.selectSession(u.session):u.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(i)}async refreshCurrentWorkspaceSessions(t=f(this.getState())){const i=this.getState().selectedWorkspace;if(i!==void 0)try{const s=Ja(i.path,await this.api.sessions(i.path,t),t);if(f(this.getState())!==t||this.getState().selectedWorkspace?.id!==i.id)return;const r=this.getState().selectedSession;if(this.setState({sessions:s}),r===void 0)return;const o=s.find(a=>a.id===r.id);if(o!==void 0){o!==r&&this.setState({selectedSession:o});return}const n=s.find(a=>a.archived!==!0)??s[0];n!==void 0?await this.selectSession(n):this.deselectSession({forgetRememberedSelection:!0})}catch(s){f(this.getState())===t&&this.getState().selectedWorkspace?.id===i.id&&this.setState({error:String(s)})}}async deleteCachedNewSession(t=this.getState().selectedSession){if(!Y(t))return;this.api.stop(t,f(this.getState())).catch(()=>{}),No(t.id,f(this.getState())),Or(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(r=>r.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(r=>r.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||Y(t)||t.archived===!0)return;const i=f(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!qe(s,_e.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(r){this.setState({error:String(r)})}}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(r){this.setState({error:String(r)})}}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.flushPendingUpdates();const[s,r]=await Promise.all([this.api.messages(i,{limit:Lt},f(this.getState())),this.api.status(i,f(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...o,status:r,activity:this.getState().sessionActivities[t],...this.setStreamCatchup(r.isStreaming?t:void 0)}),this.applyStatus(r)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionFailures(t,i){i.length!==0&&this.setState({error:`${t} failed for ${String(i.length)} session${i.length===1?"":"s"}: ${i.join("; ")}`})}sessionCacheKey(t){return Ga(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()),r=await this.api.startSession(t.cwd,s);Bo(r,s),tu(this.sessionCacheKey(t.id),this.sessionCacheKey(r.id)),No(t.id,s);const o=Ys(r,s);this.setState({sessions:[o,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(o,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!Y(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Rh(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,Le(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&Oi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,r=[t.session,...this.getState().sessions.filter(o=>o.id!==t.session?.id)];this.setState({sessions:r,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"&&!tt(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...cf(i,t.sessionId,t.messageCount),...s?{sessionActivities:nf(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=o=>{if(o.id!==t)return o;const n={...o};return i===void 0||i===""?delete n.name:n.name=i,n},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:r===void 0?void 0:s(r)})}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(df(t))return}if(t.type==="status.update"){this.queueStatusUpdate(t.status);return}if(t.type==="activity.update"){this.queueActivityUpdate(t.activity);return}if(pf(t)){this.queueTranscriptEvent(t);return}this.flushPendingUpdates();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.schedulePendingFlush()}queueStatusUpdate(t){this.pendingStatusBySession.set(t.sessionId,t),this.schedulePendingFlush()}queueActivityUpdate(t){this.pendingActivityBySession.set(t.sessionId,t),this.schedulePendingFlush()}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){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})}if(this.pendingActivityBySession.size>0){const t=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(const i of t)this.applyActivity(i)}if(this.pendingStatusBySession.size>0){const t=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(const i of t)this.applyStatus(i)}}clearPendingUpdates(){this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=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:Lt},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 nf(e,t){return al(e,t)}function al(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Xo(e,t){if(t.length===0)return e;const i=new Set(t);return Object.fromEntries(Object.entries(e).filter(([s])=>!i.has(s)))}function Yo(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 en(e){return e.filter(af).map(t=>t.value)}function tn(e){return e.map(t=>`${t.sessionId}: ${t.error}`)}function sn(e,t){return t.flatMap((i,s)=>lf(i)?[`${e[s]?.id??"unknown"}: ${tr(i.reason)}`]:[])}async function rn(e,t,i){const s=e.map((c,p)=>({item:c,index:p})),r=[];let o=0;async function n(){for(;o<s.length;){const c=s[o];if(c===void 0)return;o+=1;try{r[c.index]={status:"fulfilled",value:await i(c.item)}}catch(p){r[c.index]={status:"rejected",reason:p}}}}const a=Math.min(Math.max(1,t),s.length);return await Promise.all(Array.from({length:a},()=>n())),r}function af(e){return e.status==="fulfilled"}function lf(e){return e.status==="rejected"}function tr(e){return e instanceof Error?e.message:String(e)}function cf(e,t,i){if(i===void 0)return{};const r=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,o=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...o!==e.selectedSession?{selectedSession:o}:{}}}function df(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 pf(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function hf(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("session not found")||t.includes("未找到会话")}class uf{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 ff="pi-web:workspace-selection:v1";class gf{constructor(t=si()){this.workspaceIdsByProject=new is(ff,Lr,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function mf(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e[0]:e[0]}class vf{constructor(t,i,s,r,o=new uf,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=r,this.workspaceSelection=o,this.api=n.api??N}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...wi()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(ys(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,...wi()});try{const r=await this.api.workspaces(t.id,s);if(f(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:r,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:r},isLoadingWorkspaces:!1});const o=mf(r,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(ys(s,t.id))});o?await this.selectWorkspace(o,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){f(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(r),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=f(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:ys(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...wi()});try{const r=Ja(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:r});const o=this.sessions.preferredSession(t.path,r,i?.sessionId);o?await this.sessions.selectSession(o,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){f(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(r)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(r=>r.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),r=this.getState();if(r.selectedProject?.id!==t||r.selectedWorkspace?.id!==i)return;const o=wf(s);o!==void 0?await this.selectWorkspace(o):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),r={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:r}):this.setState({workspacesByProjectId:r})}}function bf(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function wf(e){return e.find(t=>t.isMain)??e[0]}const yf="pi-web:machine-navigation:v1";class xf{constructor(t=si()){this.snapshotsByMachine=new is(yf,kf,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?an(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,an(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Sf(e){return{machineId:e,surface:{}}}function on(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??Va,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 nn(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 an(e){return{...e,surface:{...e.surface}}}function kf(e){if(!cl(e))return;const t=He(e,"machineId");if(t===void 0)return;const i=ll(He(e,"tool")),s=Pf(He(e,"view"));return{machineId:t,projectId:He(e,"projectId"),workspaceId:He(e,"workspaceId"),sessionId:He(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:$f(e.surface)}}function $f(e){return cl(e)?{selectedFilePath:He(e,"selectedFilePath"),selectedDiffPath:He(e,"selectedDiffPath"),selectedTerminalId:He(e,"selectedTerminalId")}:{}}function Pf(e){return e==="navigation"||e==="chat"?e:ll(e)}function ll(e){return Cf(e)?e:void 0}function Cf(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function He(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function cl(e){return typeof e=="object"&&e!==null}const If="pi-web:terminal-selection:v1";class Rf{constructor(t=si()){this.terminalIdsByCwd=new is(If,Lr,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 $x(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>!r.exited)??e[0]:e.find(r=>!r.exited)??e[0]}function Px(e){return e.find(t=>!t.exited)??e[0]}const dl=1200,Af=["mod","alt","shift"];class Tf{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const r=hl(t);if(r===void 0)return!1;const o=jr(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,r],o))return!0;if(this.clearPending(),!Xt(r))return!1}else if(!Xt(r))return!1;return this.handleSequence([r],o)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(o=>zf(o.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(o=>Fr(o.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},dl)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function jr(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Mf(p,t,u);return h===void 0?[]:[h]}),r=new Map;for(const p of s)r.set(p.key,[...r.get(p.key)??[],p]);const o=new Map;for(const p of r.values()){const u=[...p].sort(ir)[0];u!==void 0&&o.set(u.key,u)}const n=[...o.values()].sort(Wf),a=new Map,c=new Map;for(const p of s){const u=o.get(p.key);if(u===void 0)continue;const h=Of(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:ln(u),y=h?[...a.get(p)??[]].sort(ir).map(ln):[];return{...p,active:h,shadows:y,...g===void 0?{}:{shadowedBy:g}}}).sort((p,u)=>p.order-u.order)}function Ps(e){return ul(e,{requireFirstChordActivator:!0})}function pl(e){const t=ul(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function ki(e){return pl(e).map(t=>t.split("+").map(gl).join("+")).join(" ")}function hl(e){if(e.isComposing)return;const t=jf(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 Xt(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Mf(e,t,i){const s=Ef(e.id,t);if(s===null)return;const r=s??e.shortcut;if(r===void 0||r==="")return;const o=pl(r),n=o[0];if(!(n===void 0||!Xt(n)))return{action:e,shortcut:o.join(" "),source:s===void 0?"default":"custom",tokens:o,key:Df(o),order:i}}function Ef(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Df(e){return e.join("\0")}function ln(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function ir(e,t){return cn(e.source)-cn(t.source)||dn(e.action.id,t.action.id)||dn(e.action.title,t.action.title)||e.order-t.order}function Wf(e,t){return e.tokens.length-t.tokens.length||ir(e,t)}function Of(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&Fr(e.tokens,i.tokens))}function cn(e){switch(e){case"custom":return 0;case"default":return 1}}function dn(e,t){return e<t?-1:e>t?1:0}function ul(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"请输入快捷键,选择无,或重置为默认值。"};const s=[],r=i.split(/\s+/u).filter(o=>o!=="");for(const[o,n]of r.entries()){const a=_f(n);if(!a.ok)return a;if(o===0&&t.requireFirstChordActivator&&!Xt(a.token))return{ok:!1,message:"快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。"};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function _f(e){const t=e.split("+").filter(o=>o!=="");if(t.length===0)return{ok:!1,message:"快捷键组合必须包含一个按键。"};const i=new Set;let s;for(const o of t){const n=Lf(o);if(n!==void 0){if(i.has(n))return{ok:!1,message:`快捷键包含重复的 ${gl(n)} 修饰键。`};i.add(n);continue}const a=fl(o);if(a===void 0)return{ok:!1,message:`不支持的快捷键按键:${o}`};if(s!==void 0)return{ok:!1,message:"每个快捷键组合只能包含一个非修饰键。"};s=a}return s===void 0?{ok:!1,message:"快捷键组合必须包含一个按键。"}:{ok:!0,token:[...Af.filter(o=>i.has(o)),s].join("+")}}function Lf(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 fl(e){const t=Ff(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 jf(e){if(e===" ")return"space";const t=e.toLowerCase();return fl(t)}function Ff(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 gl(e){return e==="mod"?pn()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?pn()?"⌥":"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 zf(e,t){return e.length===t.length&&Fr(e,t)}function Fr(e,t){return t.every((i,s)=>e[s]===i)}function pn(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const Uf={archiveIdleEnabled:!0,archiveIdleDays:"30",deleteArchivedEnabled:!1,deleteArchivedDays:"90"};function qt(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:"请至少启用一项清理操作。"};const t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){const i=fn(e.archiveIdleDays,"归档空闲会话天数");if(typeof i=="string")return{ok:!1,error:i};t.archiveIdleDays=i}if(e.deleteArchivedEnabled){const i=fn(e.deleteArchivedDays,"删除已归档会话天数");if(typeof i=="string")return{ok:!1,error:i};t.deleteArchivedDays=i}return{ok:!0,request:t}}function Rt(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function hn(e){if(!e.canCleanup||e.loading===!0||e.running===!0||e.preview===void 0)return!1;const t=qt(e.draft);return!t.ok||Rt(t.request)!==Rt(e.previewRequest)?!1:$i(e.preview)}function $i(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function ml(e,t){const i=e.projects.map(r=>r.cwd);if(t===void 0)return i;const s=new Set(t);return i.filter(r=>s.has(r))}function un(e,t){const i=new Set(ml(e,t)),s=e.projects.filter(r=>i.has(r.cwd));return{...e,projects:s,totals:s.reduce((r,o)=>({archiveCount:r.archiveCount+o.archiveCount,deleteCount:r.deleteCount+o.deleteCount}),{archiveCount:0,deleteCount:0})}}function Bf(e,t){return t(Nf(e))}function Nf(e){const t=e.totals.archiveCount,i=e.totals.deleteCount,s=[];return t>0&&s.push(`归档 ${String(t)} 个空闲会话`),i>0&&s.push(`永久删除 ${String(i)} 个已归档会话`),`运行清理并${s.length===0?"执行清理":s.join("并")}?
25
25
 
26
- 永久删除只适用于已归档会话,且无法撤销。`}function jf(e){return`请更新并重启 ${e??"此机器"} 上的 Pi-Web 后再清理会话。`}function dn(e,t){const i=e.trim();if(i==="")return`${t}必须设置。`;const s=Number(i);return!Number.isInteger(s)||s<0?`${t}必须是非负整数天数。`:s}const Ff="management";function ul(e){return Uf(zf())===Ff}function Uf(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function zf(){return typeof window>"u"?void 0:window.location.search}const _r="themes:classic",Bf="themes:pi-web-dark",Nf={themeId:Bf,auto:!0},fl="pi-web-app-theme",qf=["--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"],Hf=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Kf(){try{const e=window.localStorage.getItem(fl);return e===null?void 0:Zf(e)}catch{return}}function Vf(e){try{window.localStorage.setItem(fl,JSON.stringify(e))}catch{}}function Gf(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of qf){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function Jf(e){const t=Qf(e.themes,e.fallbackThemeId??_r),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=gl(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const r=e.prefersLight?s.light:s.dark,o=e.themes.find(n=>n.id===r)??i;return{selectedTheme:i,activeTheme:o,selectedThemePair:s,fallbackTheme:t}}function Qf(e,t=_r){return e.find(i=>i.id===t)??e[0]}function gl(e,t){return e.find(i=>i.light===t||i.dark===t)}function Zf(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return Xf(i)?i:void 0}catch{return}}function Xf(e){if(!Yf(e))return!1;const t=e.themeId,i=e.auto;return eg(t)&&typeof i=="boolean"}function Yf(e){return typeof e=="object"&&e!==null}function eg(e){return typeof e=="string"&&Hf.test(e)}const tg="workspace.delete",ig="pi.operation",sg="target.workspaceId";function rg(e){return{...e===void 0?{}:{projectId:e},metadata:{[ig]:tg}}}function og(e){const t={};for(const i of e){const s=Ys(i);if(s===void 0)continue;const r=t[s];(r===void 0||i.createdAt.localeCompare(r.createdAt)>=0)&&(t[s]=i)}return t}function ng(e){return Object.entries(e).filter(([,t])=>_i(t)).map(([t])=>t)}function ml(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&_i(i)}function Ys(e){return e.metadata[sg]}function _i(e){return e.status==="queued"||e.status==="running"}function pn(){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:Wt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:hn,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:Wt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:Wt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:hn,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:Wt,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:ag,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:Wt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:lg,run:e=>e.archiveSession()},{id:"session.reload",title:"重新加载会话",description:"从磁盘重新读取所选会话,以获取其他进程写入的条目",group:"会话",enabled:dg,disabledReason:vl,run:e=>e.reloadSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:cg,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 Wt(e){return e.state.selectedWorkspace!==void 0}function hn(e){return e.state.selectedWorkspace?.isGitRepo===!0}function ag(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!ml(e.state,t)}function lg(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!Z(t)}function cg(e){return Z(e.state.selectedSession)}function dg(e){const t=e.state.selectedSession;return t===void 0||t.archived===!0||Z(t)||vl(e)!==void 0?!1:!Ye(e.state.status,e.state.activity)}function vl(e){const t=e.state.selectedSession;if(!(t===void 0||t.archived===!0||Z(t))&&!Ye(e.state.status,e.state.activity))return pg(e.state,Oe.sessionsReload,"reload sessions")}function pg(e,t,i){const s=e.machineRuntimes[f(e)];if(!(s?.ok===!0&&Be(s,t)))return`Update and restart Pi-Web on ${e.selectedMachine?.name??"this machine"} to ${i}.`}const hg="modulepreload",ug=function(e){return"/"+e},un={},Lr=function(t,i,s){let r=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");r=c(i.map(p=>{if(p=ug(p),p in un)return;un[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":hg,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 o(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return r.then(n=>{for(const a of n||[])a.status==="rejected"&&o(a.reason);return t().catch(o)})};function fg(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:xi(e)}function xi(e){switch(e){case"navigation":return be`
26
+ 永久删除只适用于已归档会话,且无法撤销。`}function Hf(e){return`请更新并重启 ${e??"此机器"} 上的 Pi-Web 后再清理会话。`}function fn(e,t){const i=e.trim();if(i==="")return`${t}必须设置。`;const s=Number(i);return!Number.isInteger(s)||s<0?`${t}必须是非负整数天数。`:s}const qf="management";function vl(e){return Kf(Vf())===qf}function Kf(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function Vf(){return typeof window>"u"?void 0:window.location.search}const zr="themes:classic",Gf="themes:pi-web-dark",Jf={themeId:Gf,auto:!0},bl="pi-web-app-theme",Qf=["--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"],Zf=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Xf(){try{const e=window.localStorage.getItem(bl);return e===null?void 0:sg(e)}catch{return}}function Yf(e){try{window.localStorage.setItem(bl,JSON.stringify(e))}catch{}}function eg(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of Qf){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function tg(e){const t=ig(e.themes,e.fallbackThemeId??zr),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=wl(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const r=e.prefersLight?s.light:s.dark,o=e.themes.find(n=>n.id===r)??i;return{selectedTheme:i,activeTheme:o,selectedThemePair:s,fallbackTheme:t}}function ig(e,t=zr){return e.find(i=>i.id===t)??e[0]}function wl(e,t){return e.find(i=>i.light===t||i.dark===t)}function sg(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return rg(i)?i:void 0}catch{return}}function rg(e){if(!og(e))return!1;const t=e.themeId,i=e.auto;return ng(t)&&typeof i=="boolean"}function og(e){return typeof e=="object"&&e!==null}function ng(e){return typeof e=="string"&&Zf.test(e)}const ag="workspace.delete",lg="pi.operation",cg="target.workspaceId";function dg(e){return{...e===void 0?{}:{projectId:e},metadata:{[lg]:ag}}}function pg(e){const t={};for(const i of e){const s=sr(i);if(s===void 0)continue;const r=t[s];(r===void 0||i.createdAt.localeCompare(r.createdAt)>=0)&&(t[s]=i)}return t}function hg(e){return Object.entries(e).filter(([,t])=>zi(t)).map(([t])=>t)}function yl(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&zi(i)}function sr(e){return e.metadata[cg]}function zi(e){return e.status==="queued"||e.status==="running"}function gn(){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:jt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:mn,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:jt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:jt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:mn,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:jt,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:ug,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:jt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:fg,run:e=>e.archiveSession()},{id:"session.reload",title:"重新加载会话",description:"从磁盘重新读取所选会话,以获取其他进程写入的条目",group:"会话",enabled:mg,disabledReason:xl,run:e=>e.reloadSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:gg,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&tt(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function jt(e){return e.state.selectedWorkspace!==void 0}function mn(e){return e.state.selectedWorkspace?.isGitRepo===!0}function ug(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!yl(e.state,t)}function fg(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!Y(t)}function gg(e){return Y(e.state.selectedSession)}function mg(e){const t=e.state.selectedSession;return t===void 0||t.archived===!0||Y(t)||xl(e)!==void 0?!1:!tt(e.state.status,e.state.activity)}function xl(e){const t=e.state.selectedSession;if(!(t===void 0||t.archived===!0||Y(t))&&!tt(e.state.status,e.state.activity))return vg(e.state,_e.sessionsReload,"reload sessions")}function vg(e,t,i){const s=e.machineRuntimes[f(e)];if(!(s?.ok===!0&&qe(s,t)))return`Update and restart Pi-Web on ${e.selectedMachine?.name??"this machine"} to ${i}.`}const bg="modulepreload",wg=function(e){return"/"+e},vn={},Ur=function(t,i,s){let r=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");r=c(i.map(p=>{if(p=wg(p),p in vn)return;vn[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":bg,u||(g.as="script"),g.crossOrigin="",g.href=p,a&&g.setAttribute("nonce",a),document.head.appendChild(g),u)return new Promise((y,P)=>{g.addEventListener("load",y),g.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function o(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return r.then(n=>{for(const a of n||[])a.status==="rejected"&&o(a.reason);return t().catch(o)})};function yg(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:Pi(e)}function Pi(e){switch(e){case"navigation":return be`
27
27
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
28
28
  <circle cx="6" cy="7" r="1.5"></circle>
29
29
  <path d="M10 7h8"></path>
@@ -57,7 +57,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
57
57
  <path d="m7 10 3 3-3 3"></path>
58
58
  <path d="M12 16h5"></path>
59
59
  </svg>
60
- `}}const gg=10*1024*1024,mg="10 MB",vg=E`
60
+ `}}const xg=10*1024*1024,Sg="10 MB",kg=D`
61
61
  :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; }
62
62
  header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
63
63
  .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
@@ -112,7 +112,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
112
112
  .image-preview img { display: block; max-width: 100%; max-height: 100%; object-fit: contain; border: 1px solid var(--pi-border-muted); border-radius: 8px; background-color: var(--pi-surface); background-image: linear-gradient(45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(-45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%), linear-gradient(-45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%); background-position: 0 0, 0 8px, 8px -8px, -8px 0; background-size: 16px 16px; box-shadow: 0 8px 24px var(--pi-shadow-soft); }
113
113
  pre { margin: 0; padding: 10px; overflow: auto; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; }
114
114
  p { margin: 10px; }
115
- `,bg=E`
115
+ `,$g=D`
116
116
  :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
117
117
  footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
118
118
  footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
@@ -163,7 +163,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
163
163
  button { padding: 5px 7px; }
164
164
  .icon-button { width: 34px; height: 34px; }
165
165
  }
166
- `;var wg=Object.defineProperty,yg=Object.getOwnPropertyDescriptor,Ke=(e,t,i,s)=>{for(var r=s>1?void 0:s?yg(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&wg(t,i,r),r};let Te=class extends A{constructor(){super(...arguments),this.destinationFolder="",this.overwrite=!1,this.createDirs=!0,this.formError="",this.dragActive=!1,this.dragDepth=0,this.openFilePicker=()=>{this.uploadInput?.click()},this.handleFileInputChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0,i=wn(t?.files);t!==void 0&&(t.value=""),i.length>0&&this.openUploadReview(i)},this.handleDragEnter=e=>{ni(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{ni(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect="copy"),this.dragActive=!0)},this.handleDragLeave=e=>{ni(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!ni(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;const t=wn(e.dataTransfer?.files),i=this.context;t.length>0&&i!==void 0&&Pg(i,t)},this.handleDestinationInput=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.destinationFolder=t?.value??"",this.formError=""},this.handleCreateDirsChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.createDirs=t?.checked??!0},this.handleOverwriteChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.overwrite=t?.checked??!1},this.handleDialogKeyDown=e=>{e.key==="Escape"&&(e.preventDefault(),this.closeUploadDialog())}}willUpdate(e){if(!e.has("context"))return;const t=e.get("context");t!==void 0&&this.context!==void 0&&mn(t)!==mn(this.context)&&this.resetPendingUpload()}render(){const e=this.context;if(e===void 0)return l`<p class="muted">文件不可用。</p>`;const t=e.selectedFilePath,i=fn(e.fileTree,e.expandedDirs,t),s=$g(t,i),r=t!==void 0&&t!=="";return l`
166
+ `;var Pg=Object.defineProperty,Cg=Object.getOwnPropertyDescriptor,Ge=(e,t,i,s)=>{for(var r=s>1?void 0:s?Cg(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Pg(t,i,r),r};let Me=class extends R{constructor(){super(...arguments),this.destinationFolder="",this.overwrite=!1,this.createDirs=!0,this.formError="",this.dragActive=!1,this.dragDepth=0,this.openFilePicker=()=>{this.uploadInput?.click()},this.handleFileInputChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0,i=kn(t?.files);t!==void 0&&(t.value=""),i.length>0&&this.openUploadReview(i)},this.handleDragEnter=e=>{di(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{di(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect="copy"),this.dragActive=!0)},this.handleDragLeave=e=>{di(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!di(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;const t=kn(e.dataTransfer?.files),i=this.context;t.length>0&&i!==void 0&&Mg(i,t)},this.handleDestinationInput=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.destinationFolder=t?.value??"",this.formError=""},this.handleCreateDirsChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.createDirs=t?.checked??!0},this.handleOverwriteChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.overwrite=t?.checked??!1},this.handleDialogKeyDown=e=>{e.key==="Escape"&&(e.preventDefault(),this.closeUploadDialog())}}willUpdate(e){if(!e.has("context"))return;const t=e.get("context");t!==void 0&&this.context!==void 0&&yn(t)!==yn(this.context)&&this.resetPendingUpload()}render(){const e=this.context;if(e===void 0)return l`<p class="muted">文件不可用。</p>`;const t=e.selectedFilePath,i=bn(e.fileTree,e.expandedDirs,t),s=Tg(t,i),r=t!==void 0&&t!=="";return l`
167
167
  <section
168
168
  class=${this.dragActive?"files-panel dragging":"files-panel"}
169
169
  @dragenter=${this.handleDragEnter}
@@ -207,22 +207,22 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
207
207
  <span>${t.name}</span>
208
208
  </button>
209
209
  ${r?s.map(n=>this.renderTreeEntry(e,n,i+1)):null}
210
- `}selectTreeEntry(e,t){if(t.type==="directory"){e.onSelectDirectory(t.path),e.onExpandDir(t.path);return}e.onSelectFile(t.path)}renderFileViewer(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">请选择文件。</p>`:fn(e.fileTree,e.expandedDirs,e.selectedFilePath)==="directory"?l`<p class="muted">已选择文件夹:${e.selectedFilePath}</p>`:t===void 0?l`<p class="muted">正在加载 ${e.selectedFilePath}…</p>`:t.mediaType==="image"?this.renderImageViewer(e,t):t.binary?l`<p class="muted">二进制文件:${t.path} · ${xt(t.size)}</p>`:(Wg(),l`
210
+ `}selectTreeEntry(e,t){if(t.type==="directory"){e.onSelectDirectory(t.path),e.onExpandDir(t.path);return}e.onSelectFile(t.path)}renderFileViewer(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">请选择文件。</p>`:bn(e.fileTree,e.expandedDirs,e.selectedFilePath)==="directory"?l`<p class="muted">已选择文件夹:${e.selectedFilePath}</p>`:t===void 0?l`<p class="muted">正在加载 ${e.selectedFilePath}…</p>`:t.mediaType==="image"?this.renderImageViewer(e,t):t.binary?l`<p class="muted">二进制文件:${t.path} · ${Pt(t.size)}</p>`:(zg(),l`
211
211
  <div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"文本"}${t.truncated?" · 已截断":""}</small></div>
212
212
  <code-viewer .content=${t.content} .language=${t.language}></code-viewer>
213
- `)}renderImageViewer(e,t){const i=`${t.mimeType??"image"} · ${xt(t.size)}`;if(t.size>gg)return l`
213
+ `)}renderImageViewer(e,t){const i=`${t.mimeType??"image"} · ${Pt(t.size)}`;if(t.size>xg)return l`
214
214
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
215
- <p class="muted">图片过大,无法预览:${xt(t.size)} · 限制 ${mg}</p>
216
- `;const s=Cp(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
215
+ <p class="muted">图片过大,无法预览:${Pt(t.size)} · 限制 ${Sg}</p>
216
+ `;const s=Ep(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
217
217
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
218
218
  <div class="image-preview">
219
219
  <img src=${s} alt=${t.path} decoding="async" />
220
220
  </div>
221
- `}renderUploadProgress(e){const t=xg(e.state.workspaceUploadBatches,{projectId:e.workspace.projectId,workspaceId:e.workspace.id,machineId:e.machine.id});return t.length===0?null:l`
221
+ `}renderUploadProgress(e){const t=Ig(e.state.workspaceUploadBatches,{projectId:e.workspace.projectId,workspaceId:e.workspace.id,machineId:e.machine.id});return t.length===0?null:l`
222
222
  <section class="upload-progress" aria-label="工作区上传">
223
223
  <div class="upload-progress-header">
224
224
  <strong>上传</strong>
225
- <small>${Rg(t)}</small>
225
+ <small>${Wg(t)}</small>
226
226
  </div>
227
227
  ${t.map(i=>this.renderUploadBatch(e,i))}
228
228
  </section>
@@ -230,12 +230,12 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
230
230
  <article class=${`upload-batch ${t.status}`}>
231
231
  <div class="upload-batch-heading">
232
232
  <div>
233
- <strong>${Ag(t)}</strong>
233
+ <strong>${Og(t)}</strong>
234
234
  <small>${t.destinationFolder===""?"工作区根目录":t.destinationFolder}</small>
235
235
  </div>
236
- <span>${Tg(t)}</span>
236
+ <span>${_g(t)}</span>
237
237
  </div>
238
- <progress max="1" .value=${Mg(t)}></progress>
238
+ <progress max="1" .value=${Lg(t)}></progress>
239
239
  <div class="upload-file-list">
240
240
  ${t.files.map(i=>this.renderUploadFile(i))}
241
241
  </div>
@@ -243,13 +243,13 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
243
243
  ${t.status==="uploading"?l`<button @click=${()=>{e.onCancelWorkspaceUpload(t.id)}}>取消</button>`:l`<button @click=${()=>{e.onClearWorkspaceUpload(t.id)}}>关闭</button>`}
244
244
  </div>
245
245
  </article>
246
- `}renderUploadFile(e){const t=Dg(e);return l`
246
+ `}renderUploadFile(e){const t=Fg(e);return l`
247
247
  <div class=${`upload-file ${e.status}`}>
248
248
  <div class="upload-file-main">
249
249
  <span>${e.name}</span>
250
250
  <small>${t}</small>
251
251
  </div>
252
- <span class="upload-file-status">${Eg(e)}</span>
252
+ <span class="upload-file-status">${jg(e)}</span>
253
253
  </div>
254
254
  `}renderUploadDialog(e,t){const i=t.files.length;return l`
255
255
  <div class="dialog-backdrop" @mousedown=${()=>{this.closeUploadDialog()}}>
@@ -282,7 +282,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
282
282
  ${t.files.map(s=>l`
283
283
  <div class="review-file">
284
284
  <span>${s.name}</span>
285
- <small>${xt(s.size)}</small>
285
+ <small>${Pt(s.size)}</small>
286
286
  </div>
287
287
  `)}
288
288
  </section>
@@ -294,7 +294,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
294
294
  </form>
295
295
  </section>
296
296
  </div>
297
- `}promptCreateFile(e,t){const i=vn("新建文件路径",gn(e.selectedFilePath,t,"new-file.txt"));i!==void 0&&e.onCreateFile(i)}promptCreateDirectory(e,t){const i=vn("新建文件夹路径",gn(e.selectedFilePath,t,"new-folder"));i!==void 0&&e.onCreateDirectory(i)}confirmDeleteSelectedPath(e){const t=e.selectedFilePath;t===void 0||t===""||window.confirm(`删除 ${t}?此操作无法撤销。`)&&e.onDeleteSelectedPath()}openUploadReview(e){const t=this.context,i=kg(t?.workspaceUploadDefaultFolder??"");this.pendingUpload={files:e},this.destinationFolder=i.destinationFolder,this.overwrite=i.overwrite,this.createDirs=i.createDirs,this.formError=""}submitUploadReview(e,t,i){e.preventDefault();const s=Sg(i.files,this.destinationFolder);if(s!==void 0){this.formError=s;return}t.onStartWorkspaceUpload(i.files,{destinationFolder:this.destinationFolder,createDirs:this.createDirs,overwrite:this.overwrite,selectUploadedFile:!0})!==void 0&&this.closeUploadDialog()}closeUploadDialog(){this.pendingUpload=void 0,this.formError=""}resetPendingUpload(){this.closeUploadDialog(),this.dragDepth=0,this.dragActive=!1}};Te.styles=[vg,E`
297
+ `}promptCreateFile(e,t){const i=xn("新建文件路径",wn(e.selectedFilePath,t,"new-file.txt"));i!==void 0&&e.onCreateFile(i)}promptCreateDirectory(e,t){const i=xn("新建文件夹路径",wn(e.selectedFilePath,t,"new-folder"));i!==void 0&&e.onCreateDirectory(i)}confirmDeleteSelectedPath(e){const t=e.selectedFilePath;t===void 0||t===""||window.confirm(`删除 ${t}?此操作无法撤销。`)&&e.onDeleteSelectedPath()}openUploadReview(e){const t=this.context,i=Ag(t?.workspaceUploadDefaultFolder??"");this.pendingUpload={files:e},this.destinationFolder=i.destinationFolder,this.overwrite=i.overwrite,this.createDirs=i.createDirs,this.formError=""}submitUploadReview(e,t,i){e.preventDefault();const s=Rg(i.files,this.destinationFolder);if(s!==void 0){this.formError=s;return}t.onStartWorkspaceUpload(i.files,{destinationFolder:this.destinationFolder,createDirs:this.createDirs,overwrite:this.overwrite,selectUploadedFile:!0})!==void 0&&this.closeUploadDialog()}closeUploadDialog(){this.pendingUpload=void 0,this.formError=""}resetPendingUpload(){this.closeUploadDialog(),this.dragDepth=0,this.dragActive=!1}};Me.styles=[kg,D`
298
298
  :host { flex: 1 1 auto; }
299
299
  .files-panel { position: relative; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
300
300
  .toolbar-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
@@ -342,7 +342,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
342
342
  .review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
343
343
  .dialog-error { border: 1px solid var(--pi-danger); border-radius: 8px; background: color-mix(in srgb, var(--pi-danger) 10%, transparent); color: var(--pi-danger); padding: 9px; line-height: 1.35; overflow-wrap: anywhere; }
344
344
  footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
345
- `];Ke([d({attribute:!1})],Te.prototype,"context",2);Ke([B("#workspace-upload-input")],Te.prototype,"uploadInput",2);Ke([x()],Te.prototype,"pendingUpload",2);Ke([x()],Te.prototype,"destinationFolder",2);Ke([x()],Te.prototype,"overwrite",2);Ke([x()],Te.prototype,"createDirs",2);Ke([x()],Te.prototype,"formError",2);Ke([x()],Te.prototype,"dragActive",2);Te=Ke([W("workspace-files-panel")],Te);function xg(e,t){return Object.values(e).filter(i=>i.projectId===t.projectId&&i.workspaceId===t.workspaceId&&i.machineId===t.machineId).sort((i,s)=>s.startedAt.localeCompare(i.startedAt))}function Sg(e,t){if(e.length===0)return"请至少选择一个要上传的文件。";for(const i of e)try{$r(t,i.name)}catch(s){return s instanceof Error?s.message:String(s)}}function kg(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function fn(e,t,i){if(i!==void 0)return Cg(e,t,i)?.type}function $g(e,t){return e!==void 0&&e!==""&&t==="file"}function gn(e,t,i){if(e===void 0||e==="")return i;if(t==="directory")return bn(e,i);const s=Ig(e);return s===""?i:bn(s,i)}function Pg(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function mn(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function vn(e,t){const i=window.prompt(e,t);if(i===null)return;const s=i.trim();return s===""?void 0:s}function Cg(e,t,i){const s=e.find(r=>r.path===i);if(s!==void 0)return s;for(const r of Object.values(t)){const o=r.find(n=>n.path===i);if(o!==void 0)return o}}function Ig(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function bn(e,t){return e===""?t:`${e.replace(/\/+$/u,"")}/${t.replace(/^\/+/u,"")}`}function wn(e){return e==null?[]:Array.from(e)}function ni(e){return Array.from(e.dataTransfer?.types??[]).includes("Files")}function Rg(e){const t=e.filter(i=>i.status==="uploading").length;return t===0?`${String(e.length)} 个最近`:`${String(t)} 个上传中`}function Ag(e){const t=String(e.files.length);switch(e.status){case"completed":return`已上传 ${t} 个文件`;case"error":return`${t} 个文件上传失败`;case"cancelled":return`已取消 ${t} 个文件的上传`;case"uploading":return`正在上传 ${t} 个文件`}}function Tg(e){switch(e.status){case"completed":return"完成";case"error":return"失败";case"cancelled":return"已取消";case"uploading":return bl(e.percent)}}function Mg(e){return e.status==="uploading"?e.percent:1}function Eg(e){switch(e.status){case"pending":return"待处理";case"uploading":return bl(e.percent);case"completed":return"完成";case"error":return"错误";case"cancelled":return"已取消"}}function Dg(e){return e.error!==void 0?e.error:e.response!==void 0?`已写入 ${e.response.path}`:`${e.path} · ${xt(e.loaded)} / ${xt(e.total)}`}function bl(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function Wg(){Lr(()=>import("./CodeViewer-B9FasHbW.js"),__vite__mapDeps([0,1,2,3]))}function xt(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`${Ss(t)} KB`;const i=t/1024;return i<1024?`${Ss(i)} MB`:`${Ss(i/1024)} GB`}function Ss(e){return e>=10?String(Math.round(e)):e.toFixed(1)}function yn(){return[{id:"workspace.files",title:"文件",icon:xi("files"),order:10,render:Og},{id:"workspace.git",title:"Git",icon:xi("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:Lg},{id:"workspace.terminal",title:"终端",icon:xi("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:_g}]}function Og(e){return l`<workspace-files-panel .context=${e}></workspace-files-panel>`}function _g(e){return zg(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Lg(e){const t=e.gitStatus;return l`
345
+ `];Ge([d({attribute:!1})],Me.prototype,"context",2);Ge([B("#workspace-upload-input")],Me.prototype,"uploadInput",2);Ge([w()],Me.prototype,"pendingUpload",2);Ge([w()],Me.prototype,"destinationFolder",2);Ge([w()],Me.prototype,"overwrite",2);Ge([w()],Me.prototype,"createDirs",2);Ge([w()],Me.prototype,"formError",2);Ge([w()],Me.prototype,"dragActive",2);Me=Ge([W("workspace-files-panel")],Me);function Ig(e,t){return Object.values(e).filter(i=>i.projectId===t.projectId&&i.workspaceId===t.workspaceId&&i.machineId===t.machineId).sort((i,s)=>s.startedAt.localeCompare(i.startedAt))}function Rg(e,t){if(e.length===0)return"请至少选择一个要上传的文件。";for(const i of e)try{Rr(t,i.name)}catch(s){return s instanceof Error?s.message:String(s)}}function Ag(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function bn(e,t,i){if(i!==void 0)return Eg(e,t,i)?.type}function Tg(e,t){return e!==void 0&&e!==""&&t==="file"}function wn(e,t,i){if(e===void 0||e==="")return i;if(t==="directory")return Sn(e,i);const s=Dg(e);return s===""?i:Sn(s,i)}function Mg(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function yn(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function xn(e,t){const i=window.prompt(e,t);if(i===null)return;const s=i.trim();return s===""?void 0:s}function Eg(e,t,i){const s=e.find(r=>r.path===i);if(s!==void 0)return s;for(const r of Object.values(t)){const o=r.find(n=>n.path===i);if(o!==void 0)return o}}function Dg(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function Sn(e,t){return e===""?t:`${e.replace(/\/+$/u,"")}/${t.replace(/^\/+/u,"")}`}function kn(e){return e==null?[]:Array.from(e)}function di(e){return Array.from(e.dataTransfer?.types??[]).includes("Files")}function Wg(e){const t=e.filter(i=>i.status==="uploading").length;return t===0?`${String(e.length)} 个最近`:`${String(t)} 个上传中`}function Og(e){const t=String(e.files.length);switch(e.status){case"completed":return`已上传 ${t} 个文件`;case"error":return`${t} 个文件上传失败`;case"cancelled":return`已取消 ${t} 个文件的上传`;case"uploading":return`正在上传 ${t} 个文件`}}function _g(e){switch(e.status){case"completed":return"完成";case"error":return"失败";case"cancelled":return"已取消";case"uploading":return Sl(e.percent)}}function Lg(e){return e.status==="uploading"?e.percent:1}function jg(e){switch(e.status){case"pending":return"待处理";case"uploading":return Sl(e.percent);case"completed":return"完成";case"error":return"错误";case"cancelled":return"已取消"}}function Fg(e){return e.error!==void 0?e.error:e.response!==void 0?`已写入 ${e.response.path}`:`${e.path} · ${Pt(e.loaded)} / ${Pt(e.total)}`}function Sl(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function zg(){Ur(()=>import("./CodeViewer-CGV4uBeZ.js"),__vite__mapDeps([0,1,2,3]))}function Pt(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`${Cs(t)} KB`;const i=t/1024;return i<1024?`${Cs(i)} MB`:`${Cs(i/1024)} GB`}function Cs(e){return e>=10?String(Math.round(e)):e.toFixed(1)}function $n(){return[{id:"workspace.files",title:"文件",icon:Pi("files"),order:10,render:Ug},{id:"workspace.git",title:"Git",icon:Pi("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:Ng},{id:"workspace.terminal",title:"终端",icon:Pi("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Bg}]}function Ug(e){return l`<workspace-files-panel .context=${e}></workspace-files-panel>`}function Bg(e){return Vg(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Ng(e){const t=e.gitStatus;return l`
346
346
  <section class="toolbar">
347
347
  <strong>Git</strong>
348
348
  ${e.gitStale?l`<span class="stale">过期</span>`:null}
@@ -351,29 +351,29 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
351
351
  <section class="split">
352
352
  <div class="list">
353
353
  ${t===void 0?l`<p class="muted">尚未加载状态。</p>`:t.isGitRepo?l`
354
- <p class="summary">${Bg(t)}</p>
354
+ <p class="summary">${Gg(t)}</p>
355
355
  ${t.files.length===0?l`<p class="muted">没有变更。</p>`:t.files.map(i=>l`
356
356
  <button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
357
- <span>${Ng(i.index,i.workingTree)}</span>
357
+ <span>${Jg(i.index,i.workingTree)}</span>
358
358
  <span>${i.path}</span>
359
359
  </button>
360
360
  `)}
361
361
  `:l`<p class="muted">不是 Git 仓库。</p>`}
362
362
  </div>
363
363
  <div class="viewer">
364
- ${jg(e)}
364
+ ${Hg(e)}
365
365
  </div>
366
366
  </section>
367
- `}function jg(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(r=>r.diff!=="");return s.length===0?l`<p class="muted">没有 staged 或 unstaged diff。</p>`:l`
367
+ `}function Hg(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(r=>r.diff!=="");return s.length===0?l`<p class="muted">没有 staged 或 unstaged diff。</p>`:l`
368
368
  <div class=${s.length===1?"diffs single":"diffs"}>
369
- ${s.map(r=>Fg(r))}
369
+ ${s.map(r=>qg(r))}
370
370
  </div>
371
- `}function Fg(e){return Ug(),l`
371
+ `}function qg(e){return Kg(),l`
372
372
  <section class="diff-section">
373
373
  <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"已暂存":"未暂存"}${e.truncated?" · 已截断":""}</small></div>
374
374
  <unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
375
375
  </section>
376
- `}function Ug(){Lr(()=>import("./UnifiedDiffViewer-ChTX4eDR.js"),__vite__mapDeps([4,1,2]))}function zg(){Lr(()=>import("./TerminalPanel-BSE17h19.js"),__vite__mapDeps([5,6,7,1,2]))}function Bg(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 Ng(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}const qg={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!ul();return{contributions:{actions:e?pn():pn().filter(t=>t.id!=="view.terminal"),workspacePanels:e?yn():yn().filter(t=>t.id!=="workspace.terminal")}}}},Hg={"--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"},Kg={"--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"},Vg={"--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"},Gg={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:Kg},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Vg},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Hg}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},Jg=/^[a-z][a-z0-9.-]*$/u;function Qg(e){return Jg.test(e)}const Zg="machine.";function Xg(e,t){if(e==="")throw new Error("Machine id is required");if(!Qg(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Zg}${Yg(e)}.${t}`}function Yg(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function xn(e="/pi-web-plugins/manifest.json",t={}){const i=await em(e);if(i===void 0)return[];const s=[];for(const r of i.plugins)if(t.shouldLoadPlugin?.(r)!==!1)try{const o=new URL(r.module,new URL(e,window.location.href)).toString(),n=await import(o),a=sm(n,o);s.push({id:t.machineId===void 0?r.id:Xg(t.machineId,r.id),plugin:a,machineSpecific:r.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:r.id}})}catch(o){console.warn(`Failed to load PI WEB plugin ${r.module}`,o)}return s}async function em(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 tm(await t.json())}}function tm(e){if(!Li(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!Li(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:im(t.machineSpecific)}})}}function im(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function sm(e,t){if(!Li(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!rm(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function rm(e){return Li(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function Li(e){return typeof e=="object"&&e!==null}const om=/^[a-z][a-z0-9.-]*$/u,nm=/^[a-z][a-z0-9.-]*$/u,wl=new WeakMap,yl=new WeakMap;class am{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 r=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,r))return;this.pluginIds.add(i);const o=s.apiVersion;if(o!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(o)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:be}).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),r&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&r&&pm(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=um(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const r=lm(t,s.pluginId),o=s.enabled?.(r),n=o===!1?s.disabledReason?.(r):void 0,a={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(r)};return s.description!==void 0&&(a.description=s.description),s.shortcut!==void 0&&(a.shortcut=s.shortcut),s.group!==void 0&&(a.group=s.group),o!==void 0&&(a.enabled=o),n!==void 0&&n!==""&&(a.disabledReason=n),a})}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,r){const o=this.qualify(t,i.id);return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(t,i,s,r){const o=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,r)&&(a?.(ks(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,r)?n(ks(c,t)):void 0},render:c=>i.render(ks(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,r){const o=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,r)&&(n?.(c)??!0),items:c=>this.isContributionActive(t,s,c.machine.id,r)?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,r){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(r,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(!om.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!nm.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}: ${hm(i)}`);return i}}function lm(e,t){return wl.get(e)?.(t)??e}function ks(e,t){return yl.get(e)?.(t)??e}function cm(e,t){return wl.set(e,t),e}function dm(e,t){return yl.set(e,t),e}function pm(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function hm(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 um(e){return e.state.selectedMachine?.id??"local"}const fm=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function gm(){return typeof window>"u"||!("matchMedia"in window)?[]:fm.map(e=>window.matchMedia(e))}function Sn(e,t=mm()){return e.some(i=>i.matches)||vm(t)}function mm(){return typeof navigator>"u"?void 0:navigator}function vm(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const bm=250;class wm{constructor(t=ym()){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()},bm)}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 ym(){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 xm="(max-width: 760px)",Sm="(max-width: 1180px)";class km{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=Sn(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??$m(),this.stackedWorkspaceMedia=i.stackedWorkspaceMedia??Pm(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??gm(),this.viewportPositionRepairer=i.viewportPositionRepairer??new wm,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=Sn(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 Cm(t,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:i})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function $m(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(xm)}function Pm(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Sm)}function Cm(e,t){const i=e??(t.isMobileNavigationLayout?"navigation":"chat");return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||i==="navigation"||i==="chat"?i:"chat"}const ji=["machines","projects","workspaces","sessions"];function Im(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function jr(e,t){if(e!=="none")return e??Im(t)}function Rm(e,t){return t.isMobileLayout?jr(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Am(e,t,i){return jr(e,i.state)===t?"none":t}function Tm(e,t,i){return i?t:e}function Mm(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Wm(i)}function Em(e){return ji[ji.indexOf(e)+1]}class Dm{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return jr(this.expanded,this.getState())}isCollapsed(t){return Rm(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Am(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Mm(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(Tm(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=Em(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){Om(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Wm(e){const t=new Set(e);return ji.filter(i=>t.has(i))}function Om(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class _m{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",xl(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function xl(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const er="pi-web:panel-sizes:v1",Lm={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class jm{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??Fr(),this.panelSizes=Bm(this.storage)}hostConnected(){}constraints(t){return Yt(t)}panelWidth(t,i){return we(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const r=we(t,i);this.storedPanelWidth(t)!==r&&(this.panelSizes=Hm(this.panelSizes,t,r),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Km(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(){Nm(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${$n(we("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${$n(we("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Yt(e){return Lm[e]}function Fm(e,t,i){return e==="navigation"?i-t:t-i}function Um(e,t,i,s,r=Yt(e)){return we(e,t+Fm(e,i,s),r)}function zm(e,t,i,s={}){const r=s.constraints??Yt(e);if(i==="Home")return r.minWidth;if(i==="End")return r.maxWidth;const o=s.largeStep===!0?r.largeKeyboardStep:r.keyboardStep,n=Vm(e,i,o);if(n!==void 0)return we(e,t+n,r)}function we(e,t,i=Yt(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Bm(e=Fr()){try{const t=e?.getItem(er);if(t==null||t==="")return{};const i=JSON.parse(t);return qm(i)}catch{return{}}}function Nm(e,t=Fr()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(er);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=we("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=we("workspace",e.workspacePanelWidth)),t.setItem(er,JSON.stringify(i))}catch{}}function qm(e){if(!Gm(e)||e.version!==1)return{};const t={},i=kn(e.navigationPanelWidth),s=kn(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=we("navigation",i)),s!==void 0&&(t.workspacePanelWidth=we("workspace",s)),t}function kn(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Hm(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Km(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Vm(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 $n(e){return`${String(Math.round(e))}px`}function Fr(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Gm(e){return typeof e=="object"&&e!==null}function Pn(){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:Jm(e.get("tool")),view:Qm(e.get("view"))}}function $s(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}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function Jm(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Sl(e)?e:void 0}function Qm(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Sl(e)?e:void 0}function Sl(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Cn(){return Zm(new URLSearchParams(window.location.search).get("settings"))}function Ps(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}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&window.history.pushState({},"",i)}function Zm(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 Xm(e,t){return t===void 0?e:e.map(i=>ev(i,t))}function Ym(e,t){const i=new Set(Wr(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return Xm(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?kl(s):s)}function ev(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?kl(e):{...e,shortcut:i}}function kl(e){const t={...e};return delete t.shortcut,t}function tv(e,t){const i=t.api??yt,s=t.pollIntervalMs??1e3,r=t.setTimeout??sv(),o=t.clearTimeout??rv();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:iv(a,i,s,r,o)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function iv(e,t,i,s,r){return In(e)?Promise.resolve(e):new Promise((o,n)=>{let a,c=!1;const p=g=>{c||(c=!0,a!==void 0&&r(a),o(g))},u=g=>{c||(c=!0,a!==void 0&&r(a),n(g instanceof Error?g:new Error(String(g))))},h=()=>{t.getCommandRun(e.id).then(g=>{if(g!==void 0&&In(g)){p(g);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function In(e){return e.status==="succeeded"||e.status==="failed"}function sv(){return(e,t)=>globalThis.setTimeout(e,t)}function rv(){return e=>{globalThis.clearTimeout(e)}}function ov(e,t){return t[e.path]}function nv(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function av(e,t,i){return Pl(lv(e,t,i))}function $l(e){return Pl(Object.values(e??{}))}function Pl(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function lv(e,t,i){const s=new Set(t.filter(o=>o.projectId===e.id).map(o=>o.path)),r=new Map;for(const o of s){const n=i[o];n!==void 0&&r.set(n.cwd,n)}for(const o of Object.values(i))(o.cwd===e.path||o.cwd.startsWith(`${e.path}/`))&&r.set(o.cwd,o);return[...r.values()]}function Cl(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Yi(e,t="活跃"){const i=Cl(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const ai=0,cv=120;function Il(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?Rl():dv(e),r=window.innerWidth,o=window.innerHeight,n=Math.max(0,s.left),a=Math.min(r,s.right),c=Math.max(0,s.top),p=Math.min(o,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-ai,g=i.top-c-ai;return[...h<cv&&g>h?[`bottom: ${mt(o-i.top+ai)};`,`max-height: ${mt(Math.max(0,g))};`]:[`top: ${mt(i.bottom+ai)};`,`max-height: ${mt(Math.max(0,h))};`],`right: ${mt(Math.max(0,r-u))};`,`max-width: ${mt(Math.max(0,u-n))};`].join(" ")}function dv(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Rl()}function Rl(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function mt(e){return`${String(Math.round(e))}px`}class es{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=Il(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 pv=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Al(e){return e.composedPath().some(t=>hv(t,pv))}function hv(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 ts(e,t){Al(e)||t()}function is(e,t){return Al(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?rt(e,()=>{Rn(e.currentTarget,-1)}):e.key==="ArrowDown"?rt(e,()=>{Rn(e.currentTarget,1)}):e.key==="Home"?rt(e,()=>{An(e.currentTarget,0)}):e.key==="End"?rt(e,()=>{An(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?rt(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?rt(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?rt(e,t.cancel):!1}function ss(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 rt(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function Rn(e,t){const i=Ml(e),s=El(e);if(s===void 0||i.length===0)return;const r=i.indexOf(s);r<0||Tl(i,r+t)}function An(e,t){const i=Ml(e);i.length!==0&&Tl(i,t<0?i.length-1:t)}function Tl(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function Ml(e){const t=El(e)?.getRootNode();return t===void 0||!uv(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function uv(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function El(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const rs=E`
376
+ `}function Kg(){Ur(()=>import("./UnifiedDiffViewer-BSzsWx-m.js"),__vite__mapDeps([4,1,2]))}function Vg(){Ur(()=>import("./TerminalPanel-CeJN9p9P.js"),__vite__mapDeps([5,6,7,1,2]))}function Gg(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 Jg(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}const Qg={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!vl();return{contributions:{actions:e?gn():gn().filter(t=>t.id!=="view.terminal"),workspacePanels:e?$n():$n().filter(t=>t.id!=="workspace.terminal")}}}},Zg={"--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"},Xg={"--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"},Yg={"--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"},em={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:Xg},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Yg},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Zg}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},tm=/^[a-z][a-z0-9.-]*$/u;function im(e){return tm.test(e)}const sm="machine.";function rm(e,t){if(e==="")throw new Error("Machine id is required");if(!im(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${sm}${om(e)}.${t}`}function om(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function Pn(e="/pi-web-plugins/manifest.json",t={}){const i=await nm(e);if(i===void 0)return[];const s=[];for(const r of i.plugins)if(t.shouldLoadPlugin?.(r)!==!1)try{const o=new URL(r.module,new URL(e,window.location.href)).toString(),n=await import(o),a=cm(n,o);s.push({id:t.machineId===void 0?r.id:rm(t.machineId,r.id),plugin:a,machineSpecific:r.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:r.id}})}catch(o){console.warn(`Failed to load PI WEB plugin ${r.module}`,o)}return s}async function nm(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 am(await t.json())}}function am(e){if(!Ui(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!Ui(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:lm(t.machineSpecific)}})}}function lm(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function cm(e,t){if(!Ui(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!dm(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function dm(e){return Ui(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function Ui(e){return typeof e=="object"&&e!==null}const pm=/^[a-z][a-z0-9.-]*$/u,hm=/^[a-z][a-z0-9.-]*$/u,kl=new WeakMap,$l=new WeakMap;class um{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 r=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,r))return;this.pluginIds.add(i);const o=s.apiVersion;if(o!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(o)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:be}).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),r&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&r&&vm(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=wm(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const r=fm(t,s.pluginId),o=s.enabled?.(r),n=o===!1?s.disabledReason?.(r):void 0,a={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(r)};return s.description!==void 0&&(a.description=s.description),s.shortcut!==void 0&&(a.shortcut=s.shortcut),s.group!==void 0&&(a.group=s.group),o!==void 0&&(a.enabled=o),n!==void 0&&n!==""&&(a.disabledReason=n),a})}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,r){const o=this.qualify(t,i.id);return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(t,i,s,r){const o=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,r)&&(a?.(Is(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,r)?n(Is(c,t)):void 0},render:c=>i.render(Is(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,r){const o=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,r)&&(n?.(c)??!0),items:c=>this.isContributionActive(t,s,c.machine.id,r)?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,r){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(r,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(!pm.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!hm.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}: ${bm(i)}`);return i}}function fm(e,t){return kl.get(e)?.(t)??e}function Is(e,t){return $l.get(e)?.(t)??e}function gm(e,t){return kl.set(e,t),e}function mm(e,t){return $l.set(e,t),e}function vm(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function bm(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 wm(e){return e.state.selectedMachine?.id??"local"}const ym=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function xm(){return typeof window>"u"||!("matchMedia"in window)?[]:ym.map(e=>window.matchMedia(e))}function Cn(e,t=Sm()){return e.some(i=>i.matches)||km(t)}function Sm(){return typeof navigator>"u"?void 0:navigator}function km(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const $m=250;class Pm{constructor(t=Cm()){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()},$m)}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 Cm(){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 Im="(max-width: 760px)",Rm="(max-width: 1180px)";class Am{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=Cn(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Tm(),this.stackedWorkspaceMedia=i.stackedWorkspaceMedia??Mm(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??xm(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Pm,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=Cn(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 Em(t,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:i})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Tm(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Im)}function Mm(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Rm)}function Em(e,t){const i=e??(t.isMobileNavigationLayout?"navigation":"chat");return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||i==="navigation"||i==="chat"?i:"chat"}const Bi=["machines","projects","workspaces","sessions"];function Dm(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function Br(e,t){if(e!=="none")return e??Dm(t)}function Wm(e,t){return t.isMobileLayout?Br(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Om(e,t,i){return Br(e,i.state)===t?"none":t}function _m(e,t,i){return i?t:e}function Lm(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),zm(i)}function jm(e){return Bi[Bi.indexOf(e)+1]}class Fm{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return Br(this.expanded,this.getState())}isCollapsed(t){return Wm(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Om(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Lm(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(_m(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=jm(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){Um(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function zm(e){const t=new Set(e);return Bi.filter(i=>t.has(i))}function Um(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class Bm{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",Pl(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Pl(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const rr="pi-web:panel-sizes:v1",Nm={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Hm{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??Nr(),this.panelSizes=Gm(this.storage)}hostConnected(){}constraints(t){return ri(t)}panelWidth(t,i){return we(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const r=we(t,i);this.storedPanelWidth(t)!==r&&(this.panelSizes=Zm(this.panelSizes,t,r),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Xm(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(){Jm(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${Rn(we("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${Rn(we("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function ri(e){return Nm[e]}function qm(e,t,i){return e==="navigation"?i-t:t-i}function Km(e,t,i,s,r=ri(e)){return we(e,t+qm(e,i,s),r)}function Vm(e,t,i,s={}){const r=s.constraints??ri(e);if(i==="Home")return r.minWidth;if(i==="End")return r.maxWidth;const o=s.largeStep===!0?r.largeKeyboardStep:r.keyboardStep,n=Ym(e,i,o);if(n!==void 0)return we(e,t+n,r)}function we(e,t,i=ri(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Gm(e=Nr()){try{const t=e?.getItem(rr);if(t==null||t==="")return{};const i=JSON.parse(t);return Qm(i)}catch{return{}}}function Jm(e,t=Nr()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(rr);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=we("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=we("workspace",e.workspacePanelWidth)),t.setItem(rr,JSON.stringify(i))}catch{}}function Qm(e){if(!ev(e)||e.version!==1)return{};const t={},i=In(e.navigationPanelWidth),s=In(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=we("navigation",i)),s!==void 0&&(t.workspacePanelWidth=we("workspace",s)),t}function In(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Zm(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Xm(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Ym(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 Rn(e){return`${String(Math.round(e))}px`}function Nr(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ev(e){return typeof e=="object"&&e!==null}function An(){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:tv(e.get("tool")),view:iv(e.get("view"))}}function Rs(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}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function tv(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Cl(e)?e:void 0}function iv(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Cl(e)?e:void 0}function Cl(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Tn(){return sv(new URLSearchParams(window.location.search).get("settings"))}function As(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}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&window.history.pushState({},"",i)}function sv(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 rv(e,t){return t===void 0?e:e.map(i=>nv(i,t))}function ov(e,t){const i=new Set(jr(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return rv(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?Il(s):s)}function nv(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?Il(e):{...e,shortcut:i}}function Il(e){const t={...e};return delete t.shortcut,t}function av(e,t){const i=t.api??$t,s=t.pollIntervalMs??1e3,r=t.setTimeout??cv(),o=t.clearTimeout??dv();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:lv(a,i,s,r,o)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function lv(e,t,i,s,r){return Mn(e)?Promise.resolve(e):new Promise((o,n)=>{let a,c=!1;const p=g=>{c||(c=!0,a!==void 0&&r(a),o(g))},u=g=>{c||(c=!0,a!==void 0&&r(a),n(g instanceof Error?g:new Error(String(g))))},h=()=>{t.getCommandRun(e.id).then(g=>{if(g!==void 0&&Mn(g)){p(g);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function Mn(e){return e.status==="succeeded"||e.status==="failed"}function cv(){return(e,t)=>globalThis.setTimeout(e,t)}function dv(){return e=>{globalThis.clearTimeout(e)}}function pv(e,t){return t[e.path]}function hv(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function uv(e,t,i){return Al(fv(e,t,i))}function Rl(e){return Al(Object.values(e??{}))}function Al(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function fv(e,t,i){const s=new Set(t.filter(o=>o.projectId===e.id).map(o=>o.path)),r=new Map;for(const o of s){const n=i[o];n!==void 0&&r.set(n.cwd,n)}for(const o of Object.values(i))(o.cwd===e.path||o.cwd.startsWith(`${e.path}/`))&&r.set(o.cwd,o);return[...r.values()]}function Tl(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function ss(e,t="活跃"){const i=Tl(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const pi=0,gv=120;function Ml(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?El():mv(e),r=window.innerWidth,o=window.innerHeight,n=Math.max(0,s.left),a=Math.min(r,s.right),c=Math.max(0,s.top),p=Math.min(o,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-pi,g=i.top-c-pi;return[...h<gv&&g>h?[`bottom: ${wt(o-i.top+pi)};`,`max-height: ${wt(Math.max(0,g))};`]:[`top: ${wt(i.bottom+pi)};`,`max-height: ${wt(Math.max(0,h))};`],`right: ${wt(Math.max(0,r-u))};`,`max-width: ${wt(Math.max(0,u-n))};`].join(" ")}function mv(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():El()}function El(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function wt(e){return`${String(Math.round(e))}px`}class rs{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=Ml(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 vv=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Dl(e){return e.composedPath().some(t=>bv(t,vv))}function bv(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 os(e,t){Dl(e)||t()}function ns(e,t){return Dl(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?nt(e,()=>{En(e.currentTarget,-1)}):e.key==="ArrowDown"?nt(e,()=>{En(e.currentTarget,1)}):e.key==="Home"?nt(e,()=>{Dn(e.currentTarget,0)}):e.key==="End"?nt(e,()=>{Dn(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?nt(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?nt(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?nt(e,t.cancel):!1}function as(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 nt(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function En(e,t){const i=Ol(e),s=_l(e);if(s===void 0||i.length===0)return;const r=i.indexOf(s);r<0||Wl(i,r+t)}function Dn(e,t){const i=Ol(e);i.length!==0&&Wl(i,t<0?i.length-1:t)}function Wl(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function Ol(e){const t=_l(e)?.getRootNode();return t===void 0||!wv(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function wv(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function _l(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const ls=D`
377
377
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
378
378
  :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
379
379
  section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
@@ -434,7 +434,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
434
434
  .workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
435
435
  .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; }
436
436
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
437
- `;var fv=Object.defineProperty,gv=Object.getOwnPropertyDescriptor,$e=(e,t,i,s)=>{for(var r=s>1?void 0:s?gv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&fv(t,i,r),r};let ae=class extends A{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menu=new es(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,ss(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
437
+ `;var yv=Object.defineProperty,xv=Object.getOwnPropertyDescriptor,Pe=(e,t,i,s)=>{for(var r=s>1?void 0:s?xv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&yv(t,i,r),r};let le=class extends R{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menu=new rs(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,as(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
438
438
  <section>
439
439
  <h2>${this.renderHeading()}</h2>
440
440
  ${this.collapsed?null:l`
@@ -443,12 +443,12 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
443
443
  </div>
444
444
  `}
445
445
  </section>
446
- `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=Dl(e)&&this.onRemove!==void 0;return l`
446
+ `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=Ll(e)&&this.onRemove!==void 0;return l`
447
447
  <div
448
448
  class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
449
449
  tabindex="0"
450
450
  title=${e.baseUrl??e.name}
451
- @click=${r=>{ts(r,()=>this.onSelect?.(e))}}
451
+ @click=${r=>{os(r,()=>this.onSelect?.(e))}}
452
452
  @keydown=${r=>{this.handleMachineKeydown(r,e)}}
453
453
  >
454
454
  <div class="action-main">
@@ -456,7 +456,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
456
456
  </div>
457
457
  ${s?this.renderMachineMenu(e):null}
458
458
  </div>
459
- `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=$l(this.activities[e.id]);return Yi(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.menu.isOpen(e.id),i=mv(e.id);return l`
459
+ `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=Rl(this.activities[e.id]);return ss(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.menu.isOpen(e.id),i=Sv(e.id);return l`
460
460
  <div class="action-menu">
461
461
  <button
462
462
  class="action-menu-toggle"
@@ -472,13 +472,13 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
472
472
  </div>
473
473
  `:null}
474
474
  </div>
475
- `}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)||is(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};ae.styles=[rs,E`
475
+ `}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)||ns(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};le.styles=[ls,D`
476
476
  .machine-row.no-actions .action-main { border-radius: 8px; }
477
477
  .machine-primary { display: flex; align-items: baseline; gap: 6px; }
478
478
  .machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
479
479
  .machine-menu-panel button.danger { color: var(--pi-danger); }
480
480
  .machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
481
- `];$e([d({attribute:!1})],ae.prototype,"machines",2);$e([d({attribute:!1})],ae.prototype,"selected",2);$e([d({attribute:!1})],ae.prototype,"statuses",2);$e([d({attribute:!1})],ae.prototype,"activities",2);$e([d({type:Boolean,reflect:!0})],ae.prototype,"collapsible",2);$e([d({type:Boolean,reflect:!0})],ae.prototype,"collapsed",2);$e([d({attribute:!1})],ae.prototype,"onSelect",2);$e([d({attribute:!1})],ae.prototype,"onRemove",2);$e([d({attribute:!1})],ae.prototype,"onToggleCollapsed",2);$e([d({attribute:!1})],ae.prototype,"onFocusNextSection",2);$e([d({attribute:!1})],ae.prototype,"onCancelKeyboardNavigation",2);ae=$e([W("machine-list")],ae);function Dl(e){return e.kind==="remote"}function mv(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var vv=Object.defineProperty,bv=Object.getOwnPropertyDescriptor,fe=(e,t,i,s)=>{for(var r=s>1?void 0:s?bv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&vv(t,i,r),r};let te=class extends A{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menu=new es(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,ss(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
481
+ `];Pe([d({attribute:!1})],le.prototype,"machines",2);Pe([d({attribute:!1})],le.prototype,"selected",2);Pe([d({attribute:!1})],le.prototype,"statuses",2);Pe([d({attribute:!1})],le.prototype,"activities",2);Pe([d({type:Boolean,reflect:!0})],le.prototype,"collapsible",2);Pe([d({type:Boolean,reflect:!0})],le.prototype,"collapsed",2);Pe([d({attribute:!1})],le.prototype,"onSelect",2);Pe([d({attribute:!1})],le.prototype,"onRemove",2);Pe([d({attribute:!1})],le.prototype,"onToggleCollapsed",2);Pe([d({attribute:!1})],le.prototype,"onFocusNextSection",2);Pe([d({attribute:!1})],le.prototype,"onCancelKeyboardNavigation",2);le=Pe([W("machine-list")],le);function Ll(e){return e.kind==="remote"}function Sv(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var kv=Object.defineProperty,$v=Object.getOwnPropertyDescriptor,ge=(e,t,i,s)=>{for(var r=s>1?void 0:s?$v(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&kv(t,i,r),r};let se=class extends R{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menu=new rs(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,as(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
482
482
  <section>
483
483
  <h2>${this.renderHeading()}</h2>
484
484
  ${this.collapsed?null:l`
@@ -493,7 +493,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
493
493
  class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
494
494
  tabindex="0"
495
495
  title=${e.path}
496
- @click=${t=>{ts(t,()=>this.onSelect?.(e))}}
496
+ @click=${t=>{os(t,()=>this.onSelect?.(e))}}
497
497
  @keydown=${t=>{this.handleProjectKeydown(t,e)}}
498
498
  >
499
499
  <div class="action-main">
@@ -513,19 +513,19 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
513
513
  </div>
514
514
  `}
515
515
  </section>
516
- `}handleProjectKeydown(e,t){is(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=av(e,this.workspacesByProjectId[e.id]??[],this.activities);return Yi(t,t==="terminal"?"项目终端活跃":"项目活跃")}close(e){this.menu.close(),confirm(`关闭 ${e.name}?
516
+ `}handleProjectKeydown(e,t){ns(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=uv(e,this.workspacesByProjectId[e.id]??[],this.activities);return ss(t,t==="terminal"?"项目终端活跃":"项目活跃")}close(e){this.menu.close(),confirm(`关闭 ${e.name}?
517
517
 
518
- 这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};te.styles=rs;fe([d({attribute:!1})],te.prototype,"projects",2);fe([d({attribute:!1})],te.prototype,"selected",2);fe([d({attribute:!1})],te.prototype,"activities",2);fe([d({attribute:!1})],te.prototype,"workspacesByProjectId",2);fe([d({type:Boolean,reflect:!0})],te.prototype,"collapsible",2);fe([d({type:Boolean,reflect:!0})],te.prototype,"collapsed",2);fe([d({attribute:!1})],te.prototype,"onSelect",2);fe([d({attribute:!1})],te.prototype,"onClose",2);fe([d({attribute:!1})],te.prototype,"onToggleCollapsed",2);fe([d({attribute:!1})],te.prototype,"onFocusPreviousSection",2);fe([d({attribute:!1})],te.prototype,"onFocusNextSection",2);fe([d({attribute:!1})],te.prototype,"onCancelKeyboardNavigation",2);te=fe([W("project-list")],te);function Tn(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${wv(t)}`)}function wv(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&yv(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 yv(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var xv=Object.defineProperty,Sv=Object.getOwnPropertyDescriptor,pe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Sv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&xv(t,i,r),r};let Y=class extends A{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menu=new es(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,ss(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
518
+ 这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};se.styles=ls;ge([d({attribute:!1})],se.prototype,"projects",2);ge([d({attribute:!1})],se.prototype,"selected",2);ge([d({attribute:!1})],se.prototype,"activities",2);ge([d({attribute:!1})],se.prototype,"workspacesByProjectId",2);ge([d({type:Boolean,reflect:!0})],se.prototype,"collapsible",2);ge([d({type:Boolean,reflect:!0})],se.prototype,"collapsed",2);ge([d({attribute:!1})],se.prototype,"onSelect",2);ge([d({attribute:!1})],se.prototype,"onClose",2);ge([d({attribute:!1})],se.prototype,"onToggleCollapsed",2);ge([d({attribute:!1})],se.prototype,"onFocusPreviousSection",2);ge([d({attribute:!1})],se.prototype,"onFocusNextSection",2);ge([d({attribute:!1})],se.prototype,"onCancelKeyboardNavigation",2);se=ge([W("project-list")],se);function Wn(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Pv(t)}`)}function Pv(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&Cv(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 Cv(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var Iv=Object.defineProperty,Rv=Object.getOwnPropertyDescriptor,he=(e,t,i,s)=>{for(var r=s>1?void 0:s?Rv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Iv(t,i,r),r};let te=class extends R{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menu=new rs(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,as(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
519
519
  <section>
520
520
  <h2>${this.renderHeading()}</h2>
521
521
  ${this.collapsed?null:l`
522
522
  <div class="list-body">
523
- ${this.workspaces.map(e=>{const t=kv(e),i=this.workspaceLabelItems(e);return l`
523
+ ${this.workspaces.map(e=>{const t=Av(e),i=this.workspaceLabelItems(e);return l`
524
524
  <div
525
525
  class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
526
526
  tabindex="0"
527
527
  title=${t}
528
- @click=${s=>{ts(s,()=>this.onSelect?.(e))}}
528
+ @click=${s=>{os(s,()=>this.onSelect?.(e))}}
529
529
  @keydown=${s=>{this.handleWorkspaceKeydown(s,e)}}
530
530
  >
531
531
  <div class="action-main">
@@ -537,18 +537,18 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
537
537
  </div>
538
538
  `}
539
539
  </section>
540
- `}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=nv(ov(e,this.activities));return Yi(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return l`
540
+ `}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=hv(pv(e,this.activities));return ss(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return l`
541
541
  <span class="workspace-primary">
542
542
  <span class="workspace-primary-label">${e}</span>
543
543
  ${this.isDeleting(i)?l`<span class="workspace-status">正在删除…</span>`:null}
544
544
  </span>
545
545
  ${t.length===0?null:l`
546
546
  <small class="workspace-secondary">
547
- <span class="workspace-label">${Tn(t)}</span>
547
+ <span class="workspace-label">${Wn(t)}</span>
548
548
  </small>
549
549
  `}
550
550
  ${this.renderActivity(i)}
551
- `}renderWorkspaceMenu(e,t,i){const s=this.menu.isOpen(i.id),r=Pv(i.id);return l`
551
+ `}renderWorkspaceMenu(e,t,i){const s=this.menu.isOpen(i.id),r=Mv(i.id);return l`
552
552
  <div class="action-menu">
553
553
  <button
554
554
  class="action-menu-toggle"
@@ -565,7 +565,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
565
565
  </div>
566
566
  `:null}
567
567
  </div>
568
- `}renderWorkspaceActions(e){if(!$v(e))return;const t=this.isDeleting(e);return l`
568
+ `}renderWorkspaceActions(e){if(!Tv(e))return;const t=this.isDeleting(e);return l`
569
569
  <div class="workspace-menu-actions">
570
570
  <button class="danger" title=${t?"正在删除工作区":"删除工作区"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"正在删除…":"删除工作区"}</button>
571
571
  </div>
@@ -582,11 +582,11 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
582
582
  ${t.length===0?null:l`
583
583
  <div class="workspace-detail-row">
584
584
  <dt>详情</dt>
585
- <dd><span class="workspace-label">${Tn(t)}</span></dd>
585
+ <dd><span class="workspace-label">${Wn(t)}</span></dd>
586
586
  </div>
587
587
  `}
588
588
  </dl>
589
- `}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)||is(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"})}};Y.styles=rs;pe([d({attribute:!1})],Y.prototype,"workspaces",2);pe([d({attribute:!1})],Y.prototype,"selected",2);pe([d({type:Boolean,reflect:!0})],Y.prototype,"collapsible",2);pe([d({type:Boolean,reflect:!0})],Y.prototype,"collapsed",2);pe([d({attribute:!1})],Y.prototype,"workspaceLabelItems",2);pe([d({attribute:!1})],Y.prototype,"activities",2);pe([d({attribute:!1})],Y.prototype,"deletingWorkspaceIds",2);pe([d({attribute:!1})],Y.prototype,"onSelect",2);pe([d({attribute:!1})],Y.prototype,"onDelete",2);pe([d({attribute:!1})],Y.prototype,"onToggleCollapsed",2);pe([d({attribute:!1})],Y.prototype,"onFocusPreviousSection",2);pe([d({attribute:!1})],Y.prototype,"onFocusNextSection",2);pe([d({attribute:!1})],Y.prototype,"onCancelKeyboardNavigation",2);Y=pe([W("workspace-list")],Y);function kv(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function $v(e){return e.isGitWorktree&&!e.isMain}function Pv(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Cv=Object.defineProperty,Iv=Object.getOwnPropertyDescriptor,M=(e,t,i,s)=>{for(var r=s>1?void 0:s?Iv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Cv(t,i,r),r};function Ot(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let R=class extends A{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.cleanupUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。",this.collapsible=!1,this.collapsed=!1,this.menu=new es(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,ss(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=Tv(this.sessions),t=new Set(e.map(o=>o.session.id)),i=e.map(o=>o.session).filter(o=>_t(o)==="current"),s=Wl(this.sessions.filter(o=>o.archived===!0&&!t.has(o.id))),r=Rv(this.sessions);return l`
589
+ `}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)||ns(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"})}};te.styles=ls;he([d({attribute:!1})],te.prototype,"workspaces",2);he([d({attribute:!1})],te.prototype,"selected",2);he([d({type:Boolean,reflect:!0})],te.prototype,"collapsible",2);he([d({type:Boolean,reflect:!0})],te.prototype,"collapsed",2);he([d({attribute:!1})],te.prototype,"workspaceLabelItems",2);he([d({attribute:!1})],te.prototype,"activities",2);he([d({attribute:!1})],te.prototype,"deletingWorkspaceIds",2);he([d({attribute:!1})],te.prototype,"onSelect",2);he([d({attribute:!1})],te.prototype,"onDelete",2);he([d({attribute:!1})],te.prototype,"onToggleCollapsed",2);he([d({attribute:!1})],te.prototype,"onFocusPreviousSection",2);he([d({attribute:!1})],te.prototype,"onFocusNextSection",2);he([d({attribute:!1})],te.prototype,"onCancelKeyboardNavigation",2);te=he([W("workspace-list")],te);function Av(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function Tv(e){return e.isGitWorktree&&!e.isMain}function Mv(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Ev=Object.defineProperty,Dv=Object.getOwnPropertyDescriptor,M=(e,t,i,s)=>{for(var r=s>1?void 0:s?Dv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ev(t,i,r),r};function Ft(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let A=class extends R{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.cleanupUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。",this.collapsible=!1,this.collapsed=!1,this.menu=new rs(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,as(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=_v(this.sessions),t=new Set(e.map(o=>o.session.id)),i=e.map(o=>o.session).filter(o=>zt(o)==="current"),s=jl(this.sessions.filter(o=>o.archived===!0&&!t.has(o.id))),r=Wv(this.sessions);return l`
590
590
  <section>
591
591
  ${this.renderHeading(e.length+s.length,i)}
592
592
  ${this.collapsed?null:l`
@@ -610,7 +610,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
610
610
  ${this.renderCleanupButton()}
611
611
  <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button>
612
612
  </h2>
613
- `;const i=this.selected===void 0?"未选择会话":Ot(this.selected),s=this.selected?.path??i;return l`
613
+ `;const i=this.selected===void 0?"未选择会话":Ft(this.selected),s=this.selected?.path??i;return l`
614
614
  <h2>
615
615
  <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" dir="auto" title=${s}>${i}</small>`:null}</span></button>
616
616
  ${this.renderCurrentSelectionButton(t)}
@@ -624,7 +624,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
624
624
  ${this.archivedExpanded?l`<button class="bulk-select-entry ${t?"selected":""}" title=${t?"关闭已归档会话选择":"选择已归档会话"} aria-label=${t?"关闭已归档会话选择":"选择已归档会话"} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${()=>{this.toggleSelection("archived",e)}}>☑</button>`:null}
625
625
  <small class="section-count">${e.length}</small>
626
626
  </h2>
627
- `}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("current"))return null;const t=this.selectedSessions("current"),i=t.filter(o=>!Z(o)),s=e.length>0&&e.every(o=>this.selectedSessionIds.has(o.id)),r=e.filter(o=>this.selectedSessionIds.has(o.id)).length;return l`
627
+ `}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("current"))return null;const t=this.selectedSessions("current"),i=t.filter(o=>!Y(o)),s=e.length>0&&e.every(o=>this.selectedSessionIds.has(o.id)),r=e.filter(o=>this.selectedSessionIds.has(o.id)).length;return l`
628
628
  <div class="bulk-row selecting">
629
629
  <button ?disabled=${e.length===0} @click=${()=>{this.toggleVisibleSelection(e,!s)}}>${s?"清除可见":"选择可见"}</button>
630
630
  <small>${t.length} 已选${r!==t.length?l` · ${r} 可见`:null}</small>
@@ -641,29 +641,29 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
641
641
  <button @click=${()=>{this.closeSelection("archived")}}>完成</button>
642
642
  ${this.canDeleteArchived?null:l`<small class="capability-hint">${this.archivedDeleteUnavailableMessage}</small>`}
643
643
  </div>
644
- `}renderSession(e,t,i){const{session:s}=e,r=Math.min(e.depth,2),o=_t(s)===i,n=this.selectionScopes.has(i),a=n&&o,c=a&&this.selectedSessionIds.has(s.id);return l`
644
+ `}renderSession(e,t,i){const{session:s}=e,r=Math.min(e.depth,2),o=zt(s)===i,n=this.selectionScopes.has(i),a=n&&o,c=a&&this.selectedSessionIds.has(s.id);return l`
645
645
  <div
646
646
  class="action-row ${this.selected?.id===s.id?"selected":""} ${c?"bulk-selected":""} ${s.archived===!0?"archived":""} ${n?"selecting":""}"
647
647
  style=${`--depth:${String(r)}`}
648
648
  tabindex="0"
649
649
  title=${s.path}
650
- @click=${p=>{ts(p,()=>{this.activateSessionRow(s,i)})}}
650
+ @click=${p=>{os(p,()=>{this.activateSessionRow(s,i)})}}
651
651
  @keydown=${p=>{this.handleSessionKeydown(p,s,i)}}
652
652
  >
653
653
  <div class="action-main ${n?"selecting":""}">
654
- ${a?l`<input class="session-checkbox" type="checkbox" aria-label=${`选择 ${Ot(s)}`} .checked=${c} @click=${p=>{p.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
655
- <span class="action-name" dir="auto">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${Ot(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>
654
+ ${a?l`<input class="session-checkbox" type="checkbox" aria-label=${`选择 ${Ft(s)}`} .checked=${c} @click=${p=>{p.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
655
+ <span class="action-name" dir="auto">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${Ft(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>
656
656
  ${this.renderActivity(s)}
657
657
  </div>
658
658
  <div class="action-menu">
659
659
  <button class="action-menu-toggle" title="会话操作" @click=${p=>{p.stopPropagation(),this.menu.toggle(s.id,p.currentTarget)}}>⋯</button>
660
660
  ${this.menu.isOpen(s.id)?l`
661
661
  <div class="action-menu-panel" style=${this.menu.menuStyle}>
662
- ${Z(s)?l`<button title="删除浏览器缓存的新会话" @click=${()=>{this.menu.close(),this.onDelete?.(s)}}>删除</button>`:s.archived===!0?l`
662
+ ${Y(s)?l`<button title="删除浏览器缓存的新会话" @click=${()=>{this.menu.close(),this.onDelete?.(s)}}>删除</button>`:s.archived===!0?l`
663
663
  <button title="恢复会话" @click=${()=>{this.menu.close(),this.onRestore?.(s)}}>恢复</button>
664
664
  <button class="danger" title=${this.canDeleteArchived?"永久删除已归档会话":this.archivedDeleteUnavailableMessage} ?disabled=${!this.canDeleteArchived} @click=${()=>{this.menu.close(),this.confirmDeleteArchived(s)}}>删除已归档会话</button>
665
665
  `:l`
666
- ${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}
666
+ ${this.canReload?l`<button title=${tt(this.statuses[s.id],this.activities[s.id])?"当前会话活动结束后才能重新加载":"从磁盘重新加载会话"} ?disabled=${tt(this.statuses[s.id],this.activities[s.id])} @click=${()=>{this.menu.close(),this.onReload?.(s)}}>重新加载</button>`:null}
667
667
  ${s.parentSessionPath!==void 0?l`<button title="从父会话分离" @click=${()=>{this.menu.close(),this.onDetachParent?.(s)}}>从父会话分离</button>`:null}
668
668
  <button title="归档会话" @click=${()=>{this.menu.close(),this.onArchive?.(s)}}>归档</button>
669
669
  ${t>0?l`<button title="归档此会话及其后代会话" @click=${()=>{this.menu.close(),this.confirmArchiveWithDescendants(s,t)}}>连同后代归档(${t})</button>`:null}
@@ -672,7 +672,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
672
672
  `:null}
673
673
  </div>
674
674
  </div>
675
- `}handleSessionKeydown(e,t,i){is(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)&&_t(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){confirm(`归档“${Ot(e)}”及其 ${String(t)} 个后代会话?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`永久删除已归档会话“${Ot(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=>_t(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)&&_t(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=Av(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return Yi(t,t==="sending"?"正在发送消息":"会话活跃")}};R.styles=[rs,E`
675
+ `}handleSessionKeydown(e,t,i){ns(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)&&zt(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){confirm(`归档“${Ft(e)}”及其 ${String(t)} 个后代会话?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`永久删除已归档会话“${Ft(e)}”?此操作无法撤销。`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");e.length!==0&&confirm(`永久删除 ${String(e.length)} 个所选已归档会话?此操作无法撤销。`)&&(this.selectedSessionIds=Ts(this.selectedSessionIds,e.map(t=>t.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>!Y(t));this.selectedSessionIds=Ts(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=>zt(i)===e).map(i=>i.id);this.selectedSessionIds=Ts(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)&&zt(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 Y(e)?"新建 · ":e.archived===!0?"只读 · ":""}renderActivity(e){const t=Ov(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return ss(t,t==="sending"?"正在发送消息":"会话活跃")}};A.styles=[ls,D`
676
676
  h2 { min-height: 30px; }
677
677
  h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
678
678
  .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; }
@@ -688,7 +688,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
688
688
  .action-row.bulk-selected .action-main { border-color: var(--pi-accent); box-shadow: inset 3px 0 0 var(--pi-accent); }
689
689
  .action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
690
690
  .session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
691
- `];M([d({attribute:!1})],R.prototype,"sessions",2);M([d({attribute:!1})],R.prototype,"statuses",2);M([d({attribute:!1})],R.prototype,"activities",2);M([d({attribute:!1})],R.prototype,"sending",2);M([d({attribute:!1})],R.prototype,"selected",2);M([d({type:Boolean})],R.prototype,"canStart",2);M([d({type:Boolean})],R.prototype,"canDeleteArchived",2);M([d({type:Boolean})],R.prototype,"canReload",2);M([d({type:Boolean})],R.prototype,"canCleanup",2);M([d({type:String})],R.prototype,"archivedDeleteUnavailableMessage",2);M([d({type:String})],R.prototype,"cleanupUnavailableMessage",2);M([d({type:Boolean,reflect:!0})],R.prototype,"collapsible",2);M([d({type:Boolean,reflect:!0})],R.prototype,"collapsed",2);M([d({attribute:!1})],R.prototype,"onSelect",2);M([d({attribute:!1})],R.prototype,"onStart",2);M([d({attribute:!1})],R.prototype,"onToggleCollapsed",2);M([d({attribute:!1})],R.prototype,"onArchivedCollapsed",2);M([d({attribute:!1})],R.prototype,"onFocusPreviousSection",2);M([d({attribute:!1})],R.prototype,"onFocusNextSection",2);M([d({attribute:!1})],R.prototype,"onCancelKeyboardNavigation",2);M([d({attribute:!1})],R.prototype,"onArchive",2);M([d({attribute:!1})],R.prototype,"onArchiveWithDescendants",2);M([d({attribute:!1})],R.prototype,"onArchiveMany",2);M([d({attribute:!1})],R.prototype,"onRestore",2);M([d({attribute:!1})],R.prototype,"onDelete",2);M([d({attribute:!1})],R.prototype,"onDeleteArchived",2);M([d({attribute:!1})],R.prototype,"onDeleteArchivedMany",2);M([d({attribute:!1})],R.prototype,"onDetachParent",2);M([d({attribute:!1})],R.prototype,"onReload",2);M([d({attribute:!1})],R.prototype,"onCleanup",2);M([x()],R.prototype,"archivedExpanded",2);M([x()],R.prototype,"selectionScopes",2);M([x()],R.prototype,"selectedSessionIds",2);R=M([W("session-list")],R);function _t(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 Rv(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const r=t.get(s.parentSessionPath)??[];r.push(s),t.set(s.parentSessionPath,r)}const i=(s,r)=>{if(r.has(s.path))return 0;const o=new Set(r);o.add(s.path);let n=0;for(const a of t.get(s.path)??[])o.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,o));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function Av(e,t,i,s){if(!(Z(e)||e.archived===!0))return s?"sending":Ye(t,i)?"session":void 0}function Tv(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 r=s.parentSessionPath;const o=new Set([s.path]);for(;r!==void 0&&!o.has(r);){o.add(r);const n=t.get(r);if(n===void 0)break;i.add(n.id),r=n.parentSessionPath}}return Wl(e.filter(s=>i.has(s.id)))}function Wl(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 r=[],o=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;r.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)??[])o(h,a+1,u)};for(const n of s)o(n,0,new Set);return r}var Mv=Object.defineProperty,Ev=Object.getOwnPropertyDescriptor,oe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ev(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Mv(t,i,r),r};let J=class extends A{constructor(){super(...arguments),this.canCleanup=!0,this.unavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。",this.loading=!1,this.running=!1,this.error="",this.draft={...Of},this.formError=""}willUpdate(e){e.has("preview")&&(this.selectedProjectCwds=this.preview?.projects.map(t=>t.cwd))}render(){const e=Ut(this.draft),t=this.selectedPreview(),i=ln({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),s=i?"运行清理":t!==void 0&&!yi(t)?"至少选择一个项目才能运行清理":"运行清理前请先预览";return l`
691
+ `];M([d({attribute:!1})],A.prototype,"sessions",2);M([d({attribute:!1})],A.prototype,"statuses",2);M([d({attribute:!1})],A.prototype,"activities",2);M([d({attribute:!1})],A.prototype,"sending",2);M([d({attribute:!1})],A.prototype,"selected",2);M([d({type:Boolean})],A.prototype,"canStart",2);M([d({type:Boolean})],A.prototype,"canDeleteArchived",2);M([d({type:Boolean})],A.prototype,"canReload",2);M([d({type:Boolean})],A.prototype,"canCleanup",2);M([d({type:String})],A.prototype,"archivedDeleteUnavailableMessage",2);M([d({type:String})],A.prototype,"cleanupUnavailableMessage",2);M([d({type:Boolean,reflect:!0})],A.prototype,"collapsible",2);M([d({type:Boolean,reflect:!0})],A.prototype,"collapsed",2);M([d({attribute:!1})],A.prototype,"onSelect",2);M([d({attribute:!1})],A.prototype,"onStart",2);M([d({attribute:!1})],A.prototype,"onToggleCollapsed",2);M([d({attribute:!1})],A.prototype,"onArchivedCollapsed",2);M([d({attribute:!1})],A.prototype,"onFocusPreviousSection",2);M([d({attribute:!1})],A.prototype,"onFocusNextSection",2);M([d({attribute:!1})],A.prototype,"onCancelKeyboardNavigation",2);M([d({attribute:!1})],A.prototype,"onArchive",2);M([d({attribute:!1})],A.prototype,"onArchiveWithDescendants",2);M([d({attribute:!1})],A.prototype,"onArchiveMany",2);M([d({attribute:!1})],A.prototype,"onRestore",2);M([d({attribute:!1})],A.prototype,"onDelete",2);M([d({attribute:!1})],A.prototype,"onDeleteArchived",2);M([d({attribute:!1})],A.prototype,"onDeleteArchivedMany",2);M([d({attribute:!1})],A.prototype,"onDetachParent",2);M([d({attribute:!1})],A.prototype,"onReload",2);M([d({attribute:!1})],A.prototype,"onCleanup",2);M([w()],A.prototype,"archivedExpanded",2);M([w()],A.prototype,"selectionScopes",2);M([w()],A.prototype,"selectedSessionIds",2);A=M([W("session-list")],A);function zt(e){return e.archived===!0?"archived":"current"}function Ts(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function Wv(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const r=t.get(s.parentSessionPath)??[];r.push(s),t.set(s.parentSessionPath,r)}const i=(s,r)=>{if(r.has(s.path))return 0;const o=new Set(r);o.add(s.path);let n=0;for(const a of t.get(s.path)??[])o.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,o));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function Ov(e,t,i,s){if(!(Y(e)||e.archived===!0))return s?"sending":tt(t,i)?"session":void 0}function _v(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 r=s.parentSessionPath;const o=new Set([s.path]);for(;r!==void 0&&!o.has(r);){o.add(r);const n=t.get(r);if(n===void 0)break;i.add(n.id),r=n.parentSessionPath}}return jl(e.filter(s=>i.has(s.id)))}function jl(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 r=[],o=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;r.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)??[])o(h,a+1,u)};for(const n of s)o(n,0,new Set);return r}var Lv=Object.defineProperty,jv=Object.getOwnPropertyDescriptor,ne=(e,t,i,s)=>{for(var r=s>1?void 0:s?jv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Lv(t,i,r),r};let Q=class extends R{constructor(){super(...arguments),this.canCleanup=!0,this.unavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。",this.loading=!1,this.running=!1,this.error="",this.draft={...Uf},this.formError=""}willUpdate(e){e.has("preview")&&(this.selectedProjectCwds=this.preview?.projects.map(t=>t.cwd))}render(){const e=qt(this.draft),t=this.selectedPreview(),i=hn({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),s=i?"运行清理":t!==void 0&&!$i(t)?"至少选择一个项目才能运行清理":"运行清理前请先预览";return l`
692
692
  <div class="backdrop" @mousedown=${()=>{this.onClose?.()}}>
693
693
  <section role="dialog" aria-modal="true" aria-label="清理会话" @mousedown=${r=>{r.stopPropagation()}} @keydown=${r=>{this.handleKeyDown(r)}}>
694
694
  <header>
@@ -712,25 +712,25 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
712
712
  </footer>
713
713
  </section>
714
714
  </div>
715
- `}renderForm(e){const t=this.loading||this.running,i=Ut(this.draft),s=this.preview!==void 0&&i.ok&&$t(i.request)!==$t(this.previewRequest)&&yi(this.preview);return l`
715
+ `}renderForm(e){const t=this.loading||this.running,i=qt(this.draft),s=this.preview!==void 0&&i.ok&&Rt(i.request)!==Rt(this.previewRequest)&&$i(this.preview);return l`
716
716
  <fieldset ?disabled=${t}>
717
717
  <label class="toggle-row">
718
- <input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${r=>{this.updateDraft({archiveIdleEnabled:Is(r)})}}>
718
+ <input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${r=>{this.updateDraft({archiveIdleEnabled:Ms(r)})}}>
719
719
  <span>归档空闲超过</span>
720
- <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${r=>{this.updateDraft({archiveIdleDays:Mn(r)})}}>
720
+ <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${r=>{this.updateDraft({archiveIdleDays:On(r)})}}>
721
721
  <span>天的未归档会话</span>
722
722
  </label>
723
723
  <label class="toggle-row delete-row">
724
- <input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${r=>{this.updateDraft({deleteArchivedEnabled:Is(r)})}}>
724
+ <input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${r=>{this.updateDraft({deleteArchivedEnabled:Ms(r)})}}>
725
725
  <span>删除已归档超过</span>
726
- <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${r=>{this.updateDraft({deleteArchivedDays:Mn(r)})}}>
726
+ <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${r=>{this.updateDraft({deleteArchivedDays:On(r)})}}>
727
727
  <span>天的已归档会话</span>
728
728
  </label>
729
729
  </fieldset>
730
730
  <p class="warning"><strong>删除是永久操作。</strong>清理只会删除已经归档的会话。</p>
731
731
  ${e===""?null:l`<div class="dialog-error" role="alert">${e}</div>`}
732
732
  ${s?l`<div class="hint" role="status">阈值已更改。运行清理前请重新预览。</div>`:null}
733
- `}renderUnavailable(){return l`<div class="unavailable" role="status">${this.unavailableMessage}</div>`}renderMessage(){const e=this.formError||this.error;return e===""?null:l`<div class="dialog-error" role="alert">${e}</div>`}renderPreview(e){const t=this.selectedProjectCwdsForPreview(),i=new Set(t),s=cn(e,t);return l`
733
+ `}renderUnavailable(){return l`<div class="unavailable" role="status">${this.unavailableMessage}</div>`}renderMessage(){const e=this.formError||this.error;return e===""?null:l`<div class="dialog-error" role="alert">${e}</div>`}renderPreview(e){const t=this.selectedProjectCwdsForPreview(),i=new Set(t),s=un(e,t);return l`
734
734
  <section class="preview" aria-label="清理预览">
735
735
  <h2>预览</h2>
736
736
  ${e.projects.length===0?l`<p class="empty">没有会话匹配这些阈值。</p>`:l`
@@ -760,7 +760,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
760
760
  ${t.length===0?l`<p class="hint" role="status">至少选择一个项目才能运行清理。</p>`:null}
761
761
  `}renderProjectRow(e,t){return l`
762
762
  <tr class=${t?"":"unselected"}>
763
- <td class="select-cell"><input type="checkbox" aria-label=${`清理 ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${i=>{this.setProjectSelected(e.cwd,Is(i))}}></td>
763
+ <td class="select-cell"><input type="checkbox" aria-label=${`清理 ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${i=>{this.setProjectSelected(e.cwd,Ms(i))}}></td>
764
764
  <th title=${e.cwd} dir="auto">${e.cwd}</th>
765
765
  <td>${e.archiveCount}</td>
766
766
  <td>${e.deleteCount}</td>
@@ -770,7 +770,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
770
770
  <h2>清理完成</h2>
771
771
  <p>已归档 ${e.archivedSessionIds.length} 个会话;已永久删除 ${e.deletedSessionIds.length} 个已归档会话。</p>
772
772
  </section>
773
- `}updateDraft(e){this.draft={...this.draft,...e},this.formError=""}selectedPreview(){return this.preview===void 0?void 0:cn(this.preview,this.selectedProjectCwdsForPreview())}selectedProjectCwdsForPreview(){return this.preview===void 0?[]:hl(this.preview,this.selectedProjectCwds)}selectAllProjects(){this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd)??[],this.formError=""}deselectAllProjects(){this.selectedProjectCwds=[],this.formError=""}setProjectSelected(e,t){const i=this.preview;if(i===void 0)return;const s=new Set(this.selectedProjectCwdsForPreview());t?s.add(e):s.delete(e),this.selectedProjectCwds=i.projects.map(r=>r.cwd).filter(r=>s.has(r)),this.formError=""}previewCleanup(){const e=Ut(this.draft);if(!e.ok){this.formError=e.error;return}this.formError="",this.onPreview?.(e.request)}runCleanup(){const e=Ut(this.draft);if(!e.ok){this.formError=e.error;return}const t=this.selectedPreview(),i=this.selectedProjectCwdsForPreview();if(!ln({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest})){this.formError=t!==void 0&&!yi(t)?"至少选择一个项目才能运行清理。":"运行清理前请先预览。";return}t===void 0||!_f(t,s=>confirm(s))||(this.formError="",this.onRun?.({...e.request,projectCwds:i}))}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};J.styles=E`
773
+ `}updateDraft(e){this.draft={...this.draft,...e},this.formError=""}selectedPreview(){return this.preview===void 0?void 0:un(this.preview,this.selectedProjectCwdsForPreview())}selectedProjectCwdsForPreview(){return this.preview===void 0?[]:ml(this.preview,this.selectedProjectCwds)}selectAllProjects(){this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd)??[],this.formError=""}deselectAllProjects(){this.selectedProjectCwds=[],this.formError=""}setProjectSelected(e,t){const i=this.preview;if(i===void 0)return;const s=new Set(this.selectedProjectCwdsForPreview());t?s.add(e):s.delete(e),this.selectedProjectCwds=i.projects.map(r=>r.cwd).filter(r=>s.has(r)),this.formError=""}previewCleanup(){const e=qt(this.draft);if(!e.ok){this.formError=e.error;return}this.formError="",this.onPreview?.(e.request)}runCleanup(){const e=qt(this.draft);if(!e.ok){this.formError=e.error;return}const t=this.selectedPreview(),i=this.selectedProjectCwdsForPreview();if(!hn({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest})){this.formError=t!==void 0&&!$i(t)?"至少选择一个项目才能运行清理。":"运行清理前请先预览。";return}t===void 0||!Bf(t,s=>confirm(s))||(this.formError="",this.onRun?.({...e.request,projectCwds:i}))}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};Q.styles=D`
774
774
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
775
775
  .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; }
776
776
  section[role="dialog"] { width: min(760px, 100%); max-height: min(760px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr) auto; border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -820,7 +820,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
820
820
  table { min-width: 560px; }
821
821
  thead th:first-child, td.select-cell { width: 58px; }
822
822
  }
823
- `;oe([d({type:Boolean})],J.prototype,"canCleanup",2);oe([d({type:String})],J.prototype,"unavailableMessage",2);oe([d({attribute:!1})],J.prototype,"preview",2);oe([d({attribute:!1})],J.prototype,"previewRequest",2);oe([d({attribute:!1})],J.prototype,"result",2);oe([d({type:Boolean})],J.prototype,"loading",2);oe([d({type:Boolean})],J.prototype,"running",2);oe([d({type:String})],J.prototype,"error",2);oe([d({attribute:!1})],J.prototype,"onPreview",2);oe([d({attribute:!1})],J.prototype,"onRun",2);oe([d({attribute:!1})],J.prototype,"onClose",2);oe([x()],J.prototype,"draft",2);oe([x()],J.prototype,"formError",2);oe([x()],J.prototype,"selectedProjectCwds",2);J=oe([W("session-cleanup-dialog")],J);function Is(e){return e.target instanceof HTMLInputElement?e.target.checked:!1}function Mn(e){return e.target instanceof HTMLInputElement?e.target.value:""}const Ur={CHILD:2,ELEMENT:6},zr=e=>(...t)=>({_$litDirective$:e,values:t});let Br=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:Dv}=Uc,En=e=>e,Dn=()=>document.createComment(""),Lt=(e,t,i)=>{const s=e._$AA.parentNode,r=t===void 0?e._$AB:t._$AA;if(i===void 0){const o=s.insertBefore(Dn(),r),n=s.insertBefore(Dn(),r);i=new Dv(o,n,e,e.options)}else{const o=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(o!==r||a){let c=i._$AA;for(;c!==o;){const p=En(c).nextSibling;En(s).insertBefore(c,r),c=p}}}return i},ot=(e,t,i=e)=>(e._$AI(t,i),e),Wv={},Ov=(e,t=Wv)=>e._$AH=t,_v=e=>e._$AH,Rs=e=>{e._$AR(),e._$AA.remove()};const Wn=(e,t,i)=>{const s=new Map;for(let r=t;r<=i;r++)s.set(e[r],r);return s},Lv=zr(class extends Br{constructor(e){if(super(e),e.type!==Ur.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 r=[],o=[];let n=0;for(const a of e)r[n]=s?s(a,n):n,o[n]=i(a,n),n++;return{values:o,keys:r}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const r=_v(e),{values:o,keys:n}=this.dt(t,i,s);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],c=[];let p,u,h=0,g=r.length-1,w=0,P=o.length-1;for(;h<=g&&w<=P;)if(r[h]===null)h++;else if(r[g]===null)g--;else if(a[h]===n[w])c[w]=ot(r[h],o[w]),h++,w++;else if(a[g]===n[P])c[P]=ot(r[g],o[P]),g--,P--;else if(a[h]===n[P])c[P]=ot(r[h],o[P]),Lt(e,c[P+1],r[h]),h++,P--;else if(a[g]===n[w])c[w]=ot(r[g],o[w]),Lt(e,r[h],r[g]),g--,w++;else if(p===void 0&&(p=Wn(n,w,P),u=Wn(a,h,g)),p.has(a[h]))if(p.has(a[g])){const I=u.get(n[w]),V=I!==void 0?r[I]:null;if(V===null){const Je=Lt(e,r[h]);ot(Je,o[w]),c[w]=Je}else c[w]=ot(V,o[w]),Lt(e,r[h],V),r[I]=null;w++}else Rs(r[g]),g--;else Rs(r[h]),h++;for(;w<=P;){const I=Lt(e,c[P+1]);ot(I,o[w]),c[w++]=I}for(;h<=g;){const I=r[h++];I!==null&&Rs(I)}return this.ut=n,Ov(e,c),Xe}}),jv="pi-web:chat-groups:",Fv={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(On(e));return t===null||t===""?void 0:zv(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(On(e),JSON.stringify(t))}catch{}}};class Uv{constructor(t=Fv){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 r=this.isOpen(t,s),o=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(o.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?o.add(t):o.delete(t)),(s?!n.has(t):o.has(t))===r&&_n(o,this.openGroupKeys)&&_n(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=o,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 On(e){return`${jv}${e}`}function zv(e){if(Array.isArray(e))return{open:As(e),closedDefaultOpen:[]};if(Bv(e))return{open:Array.isArray(e.open)?As(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?As(e.closedDefaultOpen):[]}}function As(e){return e.filter(t=>typeof t=="string")}function _n(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Bv(e){return typeof e=="object"&&e!==null}function Nv(e,t=0){const i=[];let s=[],r=0;const o=(a,c)=>{s.length||(r=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:r,endIndex:r+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(w=>Ln(a,w)),u=a.parts.filter(w=>!Ln(a,w)),h=t+c,g={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&o({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 qv(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,r)=>(s[r.role]=(s[r.role]??0)+1,s),{}),i=Object.entries(t).map(([s,r])=>`${String(r)} ${Hv(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Hv(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Ln(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 Kv=30;function Vv(e,t){const i=Jv(Xv(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Gv(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Qv(s,t.markerOffset);return}e.scrollTop=Zv(e.scrollHeight,t.distanceFromBottom)}function Jv(e){let t,i=Number.NEGATIVE_INFINITY,s,r=Number.POSITIVE_INFINITY;for(const o of e)o.offset<=0&&o.offset>=i?(t=o,i=o.offset):o.offset>0&&o.offset<r&&(s=o,r=o.offset);return t??s}function Qv(e,t){return e-t}function Zv(e,t){return Math.max(0,e-t)}function Xv(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const r=s.dataset.markerId;return r===void 0?[]:[{id:r,offset:s.getBoundingClientRect().top-i}]})}const Yv=600,eb=1;function tb(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:ib(e)||sb(e)}function ib(e){return e.scrollTop<(e.topThreshold??Math.max(Yv,e.clientHeight))}function sb(e){return e.scrollHeight<=e.clientHeight+eb}const rb="pi-web:chat-scroll:",ob=180,nb=48,ab=2,lb={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)}},cb={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class db{constructor(t=lb,i=cb){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=ob){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,r=ab){if(t===""||i===void 0||!Ms(i))return"skipped";try{if(_l(i,r)){const a={mode:"bottom"};return this.storage.setItem(Ts(t),JSON.stringify(a)),"saved"}const o=ub(i,s);if(o===void 0)return"skipped";const n=hb(i,o);return this.storage.setItem(Ts(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,r){const o=this.readPosition(t);return o===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(o,i,s,r)}restoreExplicitPosition(t,i,s,r){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!Ms(i))return{status:"skipped"};const o=fb(s,t.anchorId);if(o===void 0)return r?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=o.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(Ts(t));if(i===null||i==="")return;const s=JSON.parse(i);return pb(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!Ms(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function Ts(e){return`${rb}${e}`}function pb(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 Ms(e){return e.clientHeight>0&&e.scrollHeight>0}function Ol(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function _l(e,t=nb){return Ol(e)<t}function hb(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:Nr(t)??"",offset:t.getBoundingClientRect().top-i}}function ub(e,t){const i=e.getBoundingClientRect();let s,r=Number.NEGATIVE_INFINITY,o,n=Number.POSITIVE_INFINITY;for(const a of t){if(Nr(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>=r?(s=a,r=p):p>0&&p<n&&(o=a,n=p)}return s??o}function jn(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const r=s.getBoundingClientRect();return r.bottom>=i.top&&r.top<=i.bottom})}function fb(e,t){return e.find(i=>Nr(i)===t)}function Nr(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}async function qr(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}const gb=E`
823
+ `;ne([d({type:Boolean})],Q.prototype,"canCleanup",2);ne([d({type:String})],Q.prototype,"unavailableMessage",2);ne([d({attribute:!1})],Q.prototype,"preview",2);ne([d({attribute:!1})],Q.prototype,"previewRequest",2);ne([d({attribute:!1})],Q.prototype,"result",2);ne([d({type:Boolean})],Q.prototype,"loading",2);ne([d({type:Boolean})],Q.prototype,"running",2);ne([d({type:String})],Q.prototype,"error",2);ne([d({attribute:!1})],Q.prototype,"onPreview",2);ne([d({attribute:!1})],Q.prototype,"onRun",2);ne([d({attribute:!1})],Q.prototype,"onClose",2);ne([w()],Q.prototype,"draft",2);ne([w()],Q.prototype,"formError",2);ne([w()],Q.prototype,"selectedProjectCwds",2);Q=ne([W("session-cleanup-dialog")],Q);function Ms(e){return e.target instanceof HTMLInputElement?e.target.checked:!1}function On(e){return e.target instanceof HTMLInputElement?e.target.value:""}const Hr={CHILD:2,ELEMENT:6},qr=e=>(...t)=>({_$litDirective$:e,values:t});let Kr=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:Fv}=Hc,_n=e=>e,Ln=()=>document.createComment(""),Ut=(e,t,i)=>{const s=e._$AA.parentNode,r=t===void 0?e._$AB:t._$AA;if(i===void 0){const o=s.insertBefore(Ln(),r),n=s.insertBefore(Ln(),r);i=new Fv(o,n,e,e.options)}else{const o=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(o!==r||a){let c=i._$AA;for(;c!==o;){const p=_n(c).nextSibling;_n(s).insertBefore(c,r),c=p}}}return i},at=(e,t,i=e)=>(e._$AI(t,i),e),zv={},Uv=(e,t=zv)=>e._$AH=t,Bv=e=>e._$AH,Es=e=>{e._$AR(),e._$AA.remove()};const jn=(e,t,i)=>{const s=new Map;for(let r=t;r<=i;r++)s.set(e[r],r);return s},Nv=qr(class extends Kr{constructor(e){if(super(e),e.type!==Hr.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 r=[],o=[];let n=0;for(const a of e)r[n]=s?s(a,n):n,o[n]=i(a,n),n++;return{values:o,keys:r}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const r=Bv(e),{values:o,keys:n}=this.dt(t,i,s);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],c=[];let p,u,h=0,g=r.length-1,y=0,P=o.length-1;for(;h<=g&&y<=P;)if(r[h]===null)h++;else if(r[g]===null)g--;else if(a[h]===n[y])c[y]=at(r[h],o[y]),h++,y++;else if(a[g]===n[P])c[P]=at(r[g],o[P]),g--,P--;else if(a[h]===n[P])c[P]=at(r[h],o[P]),Ut(e,c[P+1],r[h]),h++,P--;else if(a[g]===n[y])c[y]=at(r[g],o[y]),Ut(e,r[h],r[g]),g--,y++;else if(p===void 0&&(p=jn(n,y,P),u=jn(a,h,g)),p.has(a[h]))if(p.has(a[g])){const I=u.get(n[y]),G=I!==void 0?r[I]:null;if(G===null){const Ze=Ut(e,r[h]);at(Ze,o[y]),c[y]=Ze}else c[y]=at(G,o[y]),Ut(e,r[h],G),r[I]=null;y++}else Es(r[g]),g--;else Es(r[h]),h++;for(;y<=P;){const I=Ut(e,c[P+1]);at(I,o[y]),c[y++]=I}for(;h<=g;){const I=r[h++];I!==null&&Es(I)}return this.ut=n,Uv(e,c),et}}),Hv="pi-web:chat-groups:",qv={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(Fn(e));return t===null||t===""?void 0:Vv(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(Fn(e),JSON.stringify(t))}catch{}}};class Kv{constructor(t=qv){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 r=this.isOpen(t,s),o=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(o.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?o.add(t):o.delete(t)),(s?!n.has(t):o.has(t))===r&&zn(o,this.openGroupKeys)&&zn(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=o,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 Fn(e){return`${Hv}${e}`}function Vv(e){if(Array.isArray(e))return{open:Ds(e),closedDefaultOpen:[]};if(Gv(e))return{open:Array.isArray(e.open)?Ds(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Ds(e.closedDefaultOpen):[]}}function Ds(e){return e.filter(t=>typeof t=="string")}function zn(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Gv(e){return typeof e=="object"&&e!==null}function Jv(e,t=0){const i=[];let s=[],r=0;const o=(a,c)=>{s.length||(r=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:r,endIndex:r+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(y=>Un(a,y)),u=a.parts.filter(y=>!Un(a,y)),h=t+c,g={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&o({role:a.role,parts:u,...g},h),p.length){n();const y=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:y,parts:p,...g},index:h})}}),n(),i}function Qv(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,r)=>(s[r.role]=(s[r.role]??0)+1,s),{}),i=Object.entries(t).map(([s,r])=>`${String(r)} ${Zv(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Zv(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Un(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 Xv=30;function Yv(e,t){const i=tb(rb(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function eb(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=ib(s,t.markerOffset);return}e.scrollTop=sb(e.scrollHeight,t.distanceFromBottom)}function tb(e){let t,i=Number.NEGATIVE_INFINITY,s,r=Number.POSITIVE_INFINITY;for(const o of e)o.offset<=0&&o.offset>=i?(t=o,i=o.offset):o.offset>0&&o.offset<r&&(s=o,r=o.offset);return t??s}function ib(e,t){return e-t}function sb(e,t){return Math.max(0,e-t)}function rb(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const r=s.dataset.markerId;return r===void 0?[]:[{id:r,offset:s.getBoundingClientRect().top-i}]})}const ob=600,nb=1;function ab(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:lb(e)||cb(e)}function lb(e){return e.scrollTop<(e.topThreshold??Math.max(ob,e.clientHeight))}function cb(e){return e.scrollHeight<=e.clientHeight+nb}const db="pi-web:chat-scroll:",pb=180,hb=48,ub=2,fb={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)}},gb={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class mb{constructor(t=fb,i=gb){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=pb){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,r=ub){if(t===""||i===void 0||!Os(i))return"skipped";try{if(zl(i,r)){const a={mode:"bottom"};return this.storage.setItem(Ws(t),JSON.stringify(a)),"saved"}const o=wb(i,s);if(o===void 0)return"skipped";const n=bb(i,o);return this.storage.setItem(Ws(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,r){const o=this.readPosition(t);return o===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(o,i,s,r)}restoreExplicitPosition(t,i,s,r){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!Os(i))return{status:"skipped"};const o=yb(s,t.anchorId);if(o===void 0)return r?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=o.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(Ws(t));if(i===null||i==="")return;const s=JSON.parse(i);return vb(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!Os(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function Ws(e){return`${db}${e}`}function vb(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 Os(e){return e.clientHeight>0&&e.scrollHeight>0}function Fl(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function zl(e,t=hb){return Fl(e)<t}function bb(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:Vr(t)??"",offset:t.getBoundingClientRect().top-i}}function wb(e,t){const i=e.getBoundingClientRect();let s,r=Number.NEGATIVE_INFINITY,o,n=Number.POSITIVE_INFINITY;for(const a of t){if(Vr(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>=r?(s=a,r=p):p>0&&p<n&&(o=a,n=p)}return s??o}function Bn(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const r=s.getBoundingClientRect();return r.bottom>=i.top&&r.top<=i.bottom})}function yb(e,t){return e.find(i=>Vr(i)===t)}function Vr(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}async function Gr(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}const xb=D`
824
824
  :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; }
825
825
  .chat-wrap { position: relative; flex: 1 1 0; min-height: 0; max-height: 100%; overflow: hidden; }
826
826
  .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
@@ -909,7 +909,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
909
909
  pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
910
910
  .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
911
911
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
912
- `;var mb=Object.defineProperty,vb=Object.getOwnPropertyDescriptor,Hr=(e,t,i,s)=>{for(var r=s>1?void 0:s?vb(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&mb(t,i,r),r};let Gt=class extends A{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=Fn(this.positionPercent),t=Fn(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return l`
912
+ `;var Sb=Object.defineProperty,kb=Object.getOwnPropertyDescriptor,Jr=(e,t,i,s)=>{for(var r=s>1?void 0:s?kb(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Sb(t,i,r),r};let Yt=class extends R{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=Nn(this.positionPercent),t=Nn(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return l`
913
913
  <div
914
914
  class="meter"
915
915
  style=${`--position:${e.toFixed(2)}%;`}
@@ -925,45 +925,45 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
925
925
  <div class="marker"></div>
926
926
  </div>
927
927
  </div>
928
- `}};Gt.styles=E`
928
+ `}};Yt.styles=D`
929
929
  :host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
930
930
  :host(:hover), :host(:focus-within) { opacity: .92; }
931
931
  .meter { height: 100%; }
932
932
  .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); }
933
933
  .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)); }
934
934
  .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%); }
935
- `;Hr([d({type:Number})],Gt.prototype,"positionPercent",2);Hr([d({type:Number})],Gt.prototype,"loadedPercent",2);Gt=Hr([W("conversation-meter")],Gt);function Fn(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class tr extends Br{constructor(t){if(super(t),this.it=z,t.type!==Ur.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===z||t==null)return this._t=void 0,this.it=t;if(t===Xe)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:[]}}}tr.directiveName="unsafeHTML",tr.resultType=1;const bb=zr(tr);function Kr(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ht=Kr();function Ll(e){ht=e}var nt={exec:()=>null};function vt(e){let t=[];return i=>{let s=Math.max(0,Math.min(3,i-1)),r=t[s];return r||(r=e(s),t[s]=r),r}}function T(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(r,o)=>{let n=typeof o=="string"?o:o.source;return n=n.replace(X.caret,"$1"),i=i.replace(r,n),s},getRegex:()=>new RegExp(i,t)};return s}var wb=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),X={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:vt(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:vt(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:vt(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:vt(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:vt(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:vt(e=>new RegExp(`^ {0,${e}}>`))},yb=/^(?:[ \t]*(?:\n|$))+/,xb=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Sb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ei=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,kb=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Vr=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,jl=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Fl=T(jl).replace(/bull/g,Vr).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(),$b=T(jl).replace(/bull/g,Vr).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(),Gr=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Pb=/^[^\n]+/,Jr=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Cb=T(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Jr).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ib=T(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Vr).getRegex(),os="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",Qr=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Rb=T("^ {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",Qr).replace("tag",os).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ul=T(Gr).replace("hr",ei).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",os).getRegex(),Ab=T(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ul).getRegex(),Zr={blockquote:Ab,code:xb,def:Cb,fences:Sb,heading:kb,hr:ei,html:Rb,lheading:Fl,list:Ib,newline:yb,paragraph:Ul,table:nt,text:Pb},Un=T("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",ei).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",os).getRegex(),Tb={...Zr,lheading:$b,table:Un,paragraph:T(Gr).replace("hr",ei).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Un).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",os).getRegex()},Mb={...Zr,html:T(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Qr).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:nt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:T(Gr).replace("hr",ei).replace("heading",` *#{1,6} *[^
936
- ]`).replace("lheading",Fl).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Eb=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Db=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,zl=/^( {2,}|\\)\n(?!\s*$)/,Wb=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Rt=/[\p{P}\p{S}]/u,ns=/[\s\p{P}\p{S}]/u,Xr=/[^\s\p{P}\p{S}]/u,Ob=T(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ns).getRegex(),Bl=/(?!~)[\p{P}\p{S}]/u,_b=/(?!~)[\s\p{P}\p{S}]/u,Lb=/(?:[^\s\p{P}\p{S}]|~)/u,jb=T(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",wb?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Nl=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Fb=T(Nl,"u").replace(/punct/g,Rt).getRegex(),Ub=T(Nl,"u").replace(/punct/g,Bl).getRegex(),ql="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",zb=T(ql,"gu").replace(/notPunctSpace/g,Xr).replace(/punctSpace/g,ns).replace(/punct/g,Rt).getRegex(),Bb=T(ql,"gu").replace(/notPunctSpace/g,Lb).replace(/punctSpace/g,_b).replace(/punct/g,Bl).getRegex(),Nb=T("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Xr).replace(/punctSpace/g,ns).replace(/punct/g,Rt).getRegex(),qb=T(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Rt).getRegex(),Hb="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Kb=T(Hb,"gu").replace(/notPunctSpace/g,Xr).replace(/punctSpace/g,ns).replace(/punct/g,Rt).getRegex(),Vb=T(/\\(punct)/,"gu").replace(/punct/g,Rt).getRegex(),Gb=T(/^<(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(),Jb=T(Qr).replace("(?:-->|$)","-->").getRegex(),Qb=T("^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",Jb).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Fi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Zb=T(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Fi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Hl=T(/^!?\[(label)\]\[(ref)\]/).replace("label",Fi).replace("ref",Jr).getRegex(),Kl=T(/^!?\[(ref)\](?:\[\])?/).replace("ref",Jr).getRegex(),Xb=T("reflink|nolink(?!\\()","g").replace("reflink",Hl).replace("nolink",Kl).getRegex(),zn=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Yr={_backpedal:nt,anyPunctuation:Vb,autolink:Gb,blockSkip:jb,br:zl,code:Db,del:nt,delLDelim:nt,delRDelim:nt,emStrongLDelim:Fb,emStrongRDelimAst:zb,emStrongRDelimUnd:Nb,escape:Eb,link:Zb,nolink:Kl,punctuation:Ob,reflink:Hl,reflinkSearch:Xb,tag:Qb,text:Wb,url:nt},Yb={...Yr,link:T(/^!?\[(label)\]\((.*?)\)/).replace("label",Fi).getRegex(),reflink:T(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Fi).getRegex()},ir={...Yr,emStrongRDelimAst:Bb,emStrongLDelim:Ub,delLDelim:qb,delRDelim:Kb,url:T(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",zn).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:T(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",zn).getRegex()},ew={...ir,br:T(zl).replace("{2,}","*").getRegex(),text:T(ir.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},li={normal:Zr,gfm:Tb,pedantic:Mb},jt={normal:Yr,gfm:ir,breaks:ew,pedantic:Yb},tw={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Bn=e=>tw[e];function We(e,t){if(t){if(X.escapeTest.test(e))return e.replace(X.escapeReplace,Bn)}else if(X.escapeTestNoEncode.test(e))return e.replace(X.escapeReplaceNoEncode,Bn);return e}function Nn(e){try{e=encodeURI(e).replace(X.percentDecode,"%")}catch{return null}return e}function qn(e,t){let i=e.replace(X.findPipe,(o,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(X.splitPipe),r=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(;r<s.length;r++)s[r]=s[r].trim().replace(X.slashPipe,"|");return s}function Qe(e,t,i){let s=e.length;if(s===0)return"";let r=0;for(;r<s&&e.charAt(s-r-1)===t;)r++;return e.slice(0,s-r)}function Hn(e){let t=e.split(`
937
- `),i=t.length-1;for(;i>=0&&X.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
938
- `)}function iw(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 sw(e,t=0){let i=t,s="";for(let r of e)if(r===" "){let o=4-i%4;s+=" ".repeat(o),i+=o}else s+=r,i++;return s}function Kn(e,t,i,s,r){let o=t.href,n=t.title||null,a=e[1].replace(r.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:o,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function rw(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(`
935
+ `;Jr([d({type:Number})],Yt.prototype,"positionPercent",2);Jr([d({type:Number})],Yt.prototype,"loadedPercent",2);Yt=Jr([W("conversation-meter")],Yt);function Nn(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class or extends Kr{constructor(t){if(super(t),this.it=U,t.type!==Hr.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===U||t==null)return this._t=void 0,this.it=t;if(t===et)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:[]}}}or.directiveName="unsafeHTML",or.resultType=1;const $b=qr(or);function Qr(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var gt=Qr();function Ul(e){gt=e}var lt={exec:()=>null};function yt(e){let t=[];return i=>{let s=Math.max(0,Math.min(3,i-1)),r=t[s];return r||(r=e(s),t[s]=r),r}}function T(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(r,o)=>{let n=typeof o=="string"?o:o.source;return n=n.replace(ee.caret,"$1"),i=i.replace(r,n),s},getRegex:()=>new RegExp(i,t)};return s}var Pb=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),ee={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:yt(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:yt(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:yt(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:yt(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:yt(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:yt(e=>new RegExp(`^ {0,${e}}>`))},Cb=/^(?:[ \t]*(?:\n|$))+/,Ib=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Rb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,oi=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ab=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Zr=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Bl=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Nl=T(Bl).replace(/bull/g,Zr).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(),Tb=T(Bl).replace(/bull/g,Zr).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(),Xr=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Mb=/^[^\n]+/,Yr=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Eb=T(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Yr).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Db=T(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Zr).getRegex(),cs="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",eo=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Wb=T("^ {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",eo).replace("tag",cs).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Hl=T(Xr).replace("hr",oi).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",cs).getRegex(),Ob=T(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Hl).getRegex(),to={blockquote:Ob,code:Ib,def:Eb,fences:Rb,heading:Ab,hr:oi,html:Wb,lheading:Nl,list:Db,newline:Cb,paragraph:Hl,table:lt,text:Mb},Hn=T("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",oi).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",cs).getRegex(),_b={...to,lheading:Tb,table:Hn,paragraph:T(Xr).replace("hr",oi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Hn).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",cs).getRegex()},Lb={...to,html:T(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",eo).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:lt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:T(Xr).replace("hr",oi).replace("heading",` *#{1,6} *[^
936
+ ]`).replace("lheading",Nl).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},jb=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Fb=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ql=/^( {2,}|\\)\n(?!\s*$)/,zb=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Et=/[\p{P}\p{S}]/u,ds=/[\s\p{P}\p{S}]/u,io=/[^\s\p{P}\p{S}]/u,Ub=T(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ds).getRegex(),Kl=/(?!~)[\p{P}\p{S}]/u,Bb=/(?!~)[\s\p{P}\p{S}]/u,Nb=/(?:[^\s\p{P}\p{S}]|~)/u,Hb=T(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Pb?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Vl=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,qb=T(Vl,"u").replace(/punct/g,Et).getRegex(),Kb=T(Vl,"u").replace(/punct/g,Kl).getRegex(),Gl="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Vb=T(Gl,"gu").replace(/notPunctSpace/g,io).replace(/punctSpace/g,ds).replace(/punct/g,Et).getRegex(),Gb=T(Gl,"gu").replace(/notPunctSpace/g,Nb).replace(/punctSpace/g,Bb).replace(/punct/g,Kl).getRegex(),Jb=T("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,io).replace(/punctSpace/g,ds).replace(/punct/g,Et).getRegex(),Qb=T(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Et).getRegex(),Zb="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Xb=T(Zb,"gu").replace(/notPunctSpace/g,io).replace(/punctSpace/g,ds).replace(/punct/g,Et).getRegex(),Yb=T(/\\(punct)/,"gu").replace(/punct/g,Et).getRegex(),ew=T(/^<(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(),tw=T(eo).replace("(?:-->|$)","-->").getRegex(),iw=T("^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",tw).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ni=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,sw=T(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Ni).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Jl=T(/^!?\[(label)\]\[(ref)\]/).replace("label",Ni).replace("ref",Yr).getRegex(),Ql=T(/^!?\[(ref)\](?:\[\])?/).replace("ref",Yr).getRegex(),rw=T("reflink|nolink(?!\\()","g").replace("reflink",Jl).replace("nolink",Ql).getRegex(),qn=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,so={_backpedal:lt,anyPunctuation:Yb,autolink:ew,blockSkip:Hb,br:ql,code:Fb,del:lt,delLDelim:lt,delRDelim:lt,emStrongLDelim:qb,emStrongRDelimAst:Vb,emStrongRDelimUnd:Jb,escape:jb,link:sw,nolink:Ql,punctuation:Ub,reflink:Jl,reflinkSearch:rw,tag:iw,text:zb,url:lt},ow={...so,link:T(/^!?\[(label)\]\((.*?)\)/).replace("label",Ni).getRegex(),reflink:T(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Ni).getRegex()},nr={...so,emStrongRDelimAst:Gb,emStrongLDelim:Kb,delLDelim:Qb,delRDelim:Xb,url:T(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",qn).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:T(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",qn).getRegex()},nw={...nr,br:T(ql).replace("{2,}","*").getRegex(),text:T(nr.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},hi={normal:to,gfm:_b,pedantic:Lb},Bt={normal:so,gfm:nr,breaks:nw,pedantic:ow},aw={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Kn=e=>aw[e];function Oe(e,t){if(t){if(ee.escapeTest.test(e))return e.replace(ee.escapeReplace,Kn)}else if(ee.escapeTestNoEncode.test(e))return e.replace(ee.escapeReplaceNoEncode,Kn);return e}function Vn(e){try{e=encodeURI(e).replace(ee.percentDecode,"%")}catch{return null}return e}function Gn(e,t){let i=e.replace(ee.findPipe,(o,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(ee.splitPipe),r=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(;r<s.length;r++)s[r]=s[r].trim().replace(ee.slashPipe,"|");return s}function Xe(e,t,i){let s=e.length;if(s===0)return"";let r=0;for(;r<s&&e.charAt(s-r-1)===t;)r++;return e.slice(0,s-r)}function Jn(e){let t=e.split(`
937
+ `),i=t.length-1;for(;i>=0&&ee.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
938
+ `)}function lw(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 cw(e,t=0){let i=t,s="";for(let r of e)if(r===" "){let o=4-i%4;s+=" ".repeat(o),i+=o}else s+=r,i++;return s}function Qn(e,t,i,s,r){let o=t.href,n=t.title||null,a=e[1].replace(r.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:o,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function dw(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(`
939
939
  `).map(o=>{let n=o.match(i.other.beginningSpace);if(n===null)return o;let[a]=n;return a.length>=r.length?o.slice(r.length):o}).join(`
940
- `)}var Ui=class{options;rules;lexer;constructor(e){this.options=e||ht}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]:Hn(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=rw(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=Qe(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Qe(t[0],`
941
- `),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:Qe(t[0],`
942
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Qe(t[0],`
940
+ `)}var Hi=class{options;rules;lexer;constructor(e){this.options=e||gt}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]:Jn(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=dw(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=Xe(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Xe(t[0],`
941
+ `),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:Xe(t[0],`
942
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Xe(t[0],`
943
943
  `).split(`
944
944
  `),s="",r="",o=[];for(;i.length>0;){let n=!1,a=[],c;for(c=0;c<i.length;c++)if(this.rules.other.blockquoteStart.test(i[c]))a.push(i[c]),n=!0;else if(!n)a.push(i[c]);else break;i=i.slice(c);let p=a.join(`
945
945
  `),u=p.replace(this.rules.other.blockquoteSetextReplace,`
946
946
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
947
947
  ${p}`:p,r=r?`${r}
948
- ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,o,!0),this.lexer.state.top=h,i.length===0)break;let g=o.at(-1);if(g?.type==="code")break;if(g?.type==="blockquote"){let w=g,P=w.raw+`
948
+ ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,o,!0),this.lexer.state.top=h,i.length===0)break;let g=o.at(-1);if(g?.type==="code")break;if(g?.type==="blockquote"){let y=g,P=y.raw+`
949
949
  `+i.join(`
950
- `),I=this.blockquote(P);o[o.length-1]=I,s=s.substring(0,s.length-w.raw.length)+I.raw,r=r.substring(0,r.length-w.text.length)+I.text;break}else if(g?.type==="list"){let w=g,P=w.raw+`
950
+ `),I=this.blockquote(P);o[o.length-1]=I,s=s.substring(0,s.length-y.raw.length)+I.raw,r=r.substring(0,r.length-y.text.length)+I.text;break}else if(g?.type==="list"){let y=g,P=y.raw+`
951
951
  `+i.join(`
952
- `),I=this.list(P);o[o.length-1]=I,s=s.substring(0,s.length-g.raw.length)+I.raw,r=r.substring(0,r.length-w.raw.length)+I.raw,i=P.substring(o.at(-1).raw.length).split(`
953
- `);continue}}return{type:"blockquote",raw:s,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,r={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 o=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=sw(t[2].split(`
952
+ `),I=this.list(P);o[o.length-1]=I,s=s.substring(0,s.length-g.raw.length)+I.raw,r=r.substring(0,r.length-y.raw.length)+I.raw,i=P.substring(o.at(-1).raw.length).split(`
953
+ `);continue}}return{type:"blockquote",raw:s,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,r={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 o=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=cw(t[2].split(`
954
954
  `,1)[0],t[1].length),g=e.split(`
955
- `,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+`
956
- `,e=e.substring(g.length+1),c=!0),!c){let I=this.rules.other.nextBulletRegex(P),V=this.rules.other.hrRegex(P),Je=this.rules.other.fencesBeginRegex(P),so=this.rules.other.headingBeginRegex(P),ac=this.rules.other.htmlBeginRegex(P),lc=this.rules.other.blockquoteBeginRegex(P);for(;e;){let hs=e.split(`
957
- `,1)[0],At;if(g=hs,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),At=g):At=g.replace(this.rules.other.tabCharGlobal," "),Je.test(g)||so.test(g)||ac.test(g)||lc.test(g)||I.test(g)||V.test(g))break;if(At.search(this.rules.other.nonSpaceChar)>=P||!g.trim())u+=`
958
- `+At.slice(P);else{if(w||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||Je.test(h)||so.test(h)||V.test(h))break;u+=`
959
- `+g}w=!g.trim(),p+=hs+`
960
- `,e=e.substring(hs.length+1),h=At.slice(P)}}r.loose||(n?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),r.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),r.raw+=p}let a=r.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let c of r.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,r.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(!r.loose){let u=c.tokens.filter(g=>g.type==="space"),h=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));r.loose=h}}if(r.loose)for(let c of r.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Hn(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"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:Qe(t[0],`
961
- `),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=qn(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
962
- `):[],o={type:"table",raw:Qe(t[0],`
963
- `),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?o.align.push("right"):this.rules.other.tableAlignCenter.test(n)?o.align.push("center"):this.rules.other.tableAlignLeft.test(n)?o.align.push("left"):o.align.push(null);for(let n=0;n<i.length;n++)o.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:o.align[n]});for(let n of r)o.rows.push(qn(n,o.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:Qe(t[0],`
955
+ `,1)[0],y=!h.trim(),P=0;if(this.options.pedantic?(P=2,u=h.trimStart()):y?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),y&&this.rules.other.blankLine.test(g)&&(p+=g+`
956
+ `,e=e.substring(g.length+1),c=!0),!c){let I=this.rules.other.nextBulletRegex(P),G=this.rules.other.hrRegex(P),Ze=this.rules.other.fencesBeginRegex(P),ao=this.rules.other.headingBeginRegex(P),pc=this.rules.other.htmlBeginRegex(P),hc=this.rules.other.blockquoteBeginRegex(P);for(;e;){let ms=e.split(`
957
+ `,1)[0],Dt;if(g=ms,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),Dt=g):Dt=g.replace(this.rules.other.tabCharGlobal," "),Ze.test(g)||ao.test(g)||pc.test(g)||hc.test(g)||I.test(g)||G.test(g))break;if(Dt.search(this.rules.other.nonSpaceChar)>=P||!g.trim())u+=`
958
+ `+Dt.slice(P);else{if(y||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||Ze.test(h)||ao.test(h)||G.test(h))break;u+=`
959
+ `+g}y=!g.trim(),p+=ms+`
960
+ `,e=e.substring(ms.length+1),h=Dt.slice(P)}}r.loose||(n?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),r.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),r.raw+=p}let a=r.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let c of r.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,r.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(!r.loose){let u=c.tokens.filter(g=>g.type==="space"),h=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));r.loose=h}}if(r.loose)for(let c of r.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Jn(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"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:Xe(t[0],`
961
+ `),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Gn(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
962
+ `):[],o={type:"table",raw:Xe(t[0],`
963
+ `),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?o.align.push("right"):this.rules.other.tableAlignCenter.test(n)?o.align.push("center"):this.rules.other.tableAlignLeft.test(n)?o.align.push("left"):o.align.push(null);for(let n=0;n<i.length;n++)o.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:o.align[n]});for(let n of r)o.rows.push(Gn(n,o.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:Xe(t[0],`
964
964
  `),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)===`
965
- `?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 o=Qe(i.slice(0,-1),"\\");if((i.length-o.length)%2===0)return}else{let o=iw(t[2],"()");if(o===-2)return;if(o>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],r="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(s);o&&(s=o[1],r=o[3])}else r=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)),Kn(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.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," "),r=t[s.toLowerCase()];if(!r){let o=i[0].charAt(0);return{type:"text",raw:o,text:o}}return Kn(i,r,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 r=[...s[0]].length-1,o,n,a=r,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+r);(s=p.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(n=[...o].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&r%3&&!((r+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,r+s.index+u+n);if(Math.min(r,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),r=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&r&&(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 r=[...s[0]].length-1,o,n,a=r,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+r);(s=c.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(n=[...o].length,n!==r))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,r+s.index+p+n),h=u.slice(r,-r);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 r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==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}}}},Re=class sr{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||ht,this.options.tokenizer=this.options.tokenizer||new Ui,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:X,block:li.normal,inline:jt.normal};this.options.pedantic?(i.block=li.pedantic,i.inline=jt.pedantic):this.options.gfm&&(i.block=li.gfm,this.options.breaks?i.inline=jt.breaks:i.inline=jt.gfm),this.tokenizer.rules=i}static get rules(){return{block:li,inline:jt}}static lex(t,i){return new sr(i).lex(t)}static lexInline(t,i){return new sr(i).inlineTokens(t)}lex(t){t=t.replace(X.carriageReturn,`
966
- `),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(X.tabCharGlobal," ").replace(X.spaceLine,""));let r=1/0;for(;t;){if(t.length<r)r=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},t,i))?(t=t.substring(o.raw.length),i.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let a=i.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
965
+ `?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 o=Xe(i.slice(0,-1),"\\");if((i.length-o.length)%2===0)return}else{let o=lw(t[2],"()");if(o===-2)return;if(o>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],r="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(s);o&&(s=o[1],r=o[3])}else r=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)),Qn(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.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," "),r=t[s.toLowerCase()];if(!r){let o=i[0].charAt(0);return{type:"text",raw:o,text:o}}return Qn(i,r,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 r=[...s[0]].length-1,o,n,a=r,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+r);(s=p.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(n=[...o].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&r%3&&!((r+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,r+s.index+u+n);if(Math.min(r,n)%2){let y=h.slice(1,-1);return{type:"em",raw:h,text:y,tokens:this.lexer.inlineTokens(y)}}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),r=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&r&&(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 r=[...s[0]].length-1,o,n,a=r,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+r);(s=c.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(n=[...o].length,n!==r))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,r+s.index+p+n),h=u.slice(r,-r);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 r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==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}}}},Ae=class ar{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||gt,this.options.tokenizer=this.options.tokenizer||new Hi,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:ee,block:hi.normal,inline:Bt.normal};this.options.pedantic?(i.block=hi.pedantic,i.inline=Bt.pedantic):this.options.gfm&&(i.block=hi.gfm,this.options.breaks?i.inline=Bt.breaks:i.inline=Bt.gfm),this.tokenizer.rules=i}static get rules(){return{block:hi,inline:Bt}}static lex(t,i){return new ar(i).lex(t)}static lexInline(t,i){return new ar(i).inlineTokens(t)}lex(t){t=t.replace(ee.carriageReturn,`
966
+ `),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(ee.tabCharGlobal," ").replace(ee.spaceLine,""));let r=1/0;for(;t;){if(t.length<r)r=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},t,i))?(t=t.substring(o.raw.length),i.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let a=i.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
967
967
  `:i.push(o);continue}if(o=this.tokenizer.code(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
968
968
  `)?"":`
969
969
  `)+o.raw,a.text+=`
@@ -976,9 +976,9 @@ ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
976
976
  `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o),s=n.length!==t.length,t=t.substring(o.raw.length);continue}if(o=this.tokenizer.text(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
977
977
  `)?"":`
978
978
  `)+o.raw,a.text+=`
979
- `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o);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,r=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)o=r[2]?r[2].length:0,s=s.slice(0,r.index+o)+"["+"a".repeat(r[0].length-o-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)}},zi=class{options;parser;constructor(e){this.options=e||ht}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(X.notSpaceStart)?.[0],r=e.replace(X.endingNewline,"")+`
980
- `;return s?'<pre><code class="language-'+We(s)+'">'+(i?r:We(r,!0))+`</code></pre>
981
- `:"<pre><code>"+(i?r:We(r,!0))+`</code></pre>
979
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o);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,r=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)o=r[2]?r[2].length:0,s=s.slice(0,r.index+o)+"["+"a".repeat(r[0].length-o-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),y;this.options.extensions.startInline.forEach(P=>{y=P.call({lexer:this},g),typeof y=="number"&&y>=0&&(h=Math.min(h,y))}),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)}},qi=class{options;parser;constructor(e){this.options=e||gt}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(ee.notSpaceStart)?.[0],r=e.replace(ee.endingNewline,"")+`
980
+ `;return s?'<pre><code class="language-'+Oe(s)+'">'+(i?r:Oe(r,!0))+`</code></pre>
981
+ `:"<pre><code>"+(i?r:Oe(r,!0))+`</code></pre>
982
982
  `}blockquote({tokens:e}){return`<blockquote>
983
983
  ${this.parser.parse(e)}</blockquote>
984
984
  `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
@@ -994,8 +994,8 @@ ${this.parser.parse(e)}</blockquote>
994
994
  `}tablerow({text:e}){return`<tr>
995
995
  ${e}</tr>
996
996
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
997
- `}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>${We(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),r=Nn(e);if(r===null)return s;e=r;let o='<a href="'+e+'"';return t&&(o+=' title="'+We(t)+'"'),o+=">"+s+"</a>",o}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let r=Nn(e);if(r===null)return We(i);e=r;let o=`<img src="${e}" alt="${We(i)}"`;return t&&(o+=` title="${We(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:We(e.text)}},eo=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}},Ae=class rr{options;renderer;textRenderer;constructor(t){this.options=t||ht,this.options.renderer=this.options.renderer||new zi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new eo}static parse(t,i){return new rr(i).parse(t)}static parseInline(t,i){return new rr(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let r=t[s];if(this.options.extensions?.renderers?.[r.type]){let n=r,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 o=r;switch(o.type){case"space":{i+=this.renderer.space(o);break}case"hr":{i+=this.renderer.hr(o);break}case"heading":{i+=this.renderer.heading(o);break}case"code":{i+=this.renderer.code(o);break}case"table":{i+=this.renderer.table(o);break}case"blockquote":{i+=this.renderer.blockquote(o);break}case"list":{i+=this.renderer.list(o);break}case"checkbox":{i+=this.renderer.checkbox(o);break}case"html":{i+=this.renderer.html(o);break}case"def":{i+=this.renderer.def(o);break}case"paragraph":{i+=this.renderer.paragraph(o);break}case"text":{i+=this.renderer.text(o);break}default:{let n='Token with "'+o.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 r=0;r<t.length;r++){let o=t[r];if(this.options.extensions?.renderers?.[o.type]){let a=this.options.extensions.renderers[o.type].call({parser:this},o);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){s+=a||"";continue}}let n=o;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}},zt=class{options;block;constructor(e){this.options=e||ht}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?Re.lex:Re.lexInline}provideParser(e=this.block){return e?Ae.parse:Ae.parseInline}},ow=class{defaults=Kr();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ae;Renderer=zi;TextRenderer=eo;Lexer=Re;Tokenizer=Ui;Hooks=zt;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 r=s;for(let o of r.header)i=i.concat(this.walkTokens(o.tokens,t));for(let o of r.rows)for(let n of o)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let r=s;i=i.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let n=r[o].flat(1/0);i=i.concat(this.walkTokens(n,t))}):r.tokens&&(i=i.concat(this.walkTokens(r.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(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...n){let a=r.renderer.apply(this,n);return a===!1&&(a=o.apply(this,n)),a}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),i.renderer){let r=this.defaults.renderer||new zi(this.defaults);for(let o in i.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let n=o,a=i.renderer[n],c=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u||""}}s.renderer=r}if(i.tokenizer){let r=this.defaults.tokenizer||new Ui(this.defaults);for(let o in i.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let n=o,a=i.tokenizer[n],c=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u}}s.tokenizer=r}if(i.hooks){let r=this.defaults.hooks||new zt;for(let o in i.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let n=o,a=i.hooks[n],c=r[n];zt.passThroughHooks.has(o)?r[n]=p=>{if(this.defaults.async&&zt.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await a.call(r,p);return c.call(r,h)})();let u=a.call(r,p);return c.call(r,u)}:r[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(r,p);return h===!1&&(h=await c.apply(r,p)),h})();let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u}}s.hooks=r}if(i.walkTokens){let r=this.defaults.walkTokens,o=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(o.call(this,n)),r&&(a=a.concat(r.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Re.lex(e,t??this.defaults)}parser(e,t){return Ae.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},r={...this.defaults,...s},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.async===!1)return o(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 o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let n=r.hooks?await r.hooks.preprocess(t):t,a=await(r.hooks?await r.hooks.provideLexer(e):e?Re.lex:Re.lexInline)(n,r),c=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(c,r.walkTokens));let p=await(r.hooks?await r.hooks.provideParser(e):e?Ae.parse:Ae.parseInline)(c,r);return r.hooks?await r.hooks.postprocess(p):p})().catch(o);try{r.hooks&&(t=r.hooks.preprocess(t));let n=(r.hooks?r.hooks.provideLexer(e):e?Re.lex:Re.lexInline)(t,r);r.hooks&&(n=r.hooks.processAllTokens(n)),r.walkTokens&&this.walkTokens(n,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(e):e?Ae.parse:Ae.parseInline)(n,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(n){return o(n)}}}onError(e,t){return i=>{if(i.message+=`
998
- Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+We(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},dt=new ow;function O(e,t){return dt.parse(e,t)}O.options=O.setOptions=function(e){return dt.setOptions(e),O.defaults=dt.defaults,Ll(O.defaults),O};O.getDefaults=Kr;O.defaults=ht;O.use=function(...e){return dt.use(...e),O.defaults=dt.defaults,Ll(O.defaults),O};O.walkTokens=function(e,t){return dt.walkTokens(e,t)};O.parseInline=dt.parseInline;O.Parser=Ae;O.parser=Ae.parse;O.Renderer=zi;O.TextRenderer=eo;O.Lexer=Re;O.lexer=Re.lex;O.Tokenizer=Ui;O.Hooks=zt;O.parse=O;O.options;O.setOptions;O.use;O.walkTokens;O.parseInline;Ae.parse;Re.lex;const Vl=new O.Renderer;Vl.html=({text:e})=>lw(e);const nw=300,Ft=new Map;function aw(e){const t=Ft.get(e);if(t!==void 0)return t;const i=O.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:Vl}),s=cw(i);if(Ft.set(e,s),Ft.size>nw){const r=Ft.keys().next().value;r!==void 0&&Ft.delete(r)}return s}function lw(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function cw(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 r=s.name.toLowerCase();r.startsWith("on")&&i.removeAttribute(s.name),(r==="href"||r==="src")&&!dw(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function dw(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var pw=Object.defineProperty,hw=Object.getOwnPropertyDescriptor,Gl=(e,t,i,s)=>{for(var r=s>1?void 0:s?hw(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&pw(t,i,r),r};const uw=E`
997
+ `}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>${Oe(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),r=Vn(e);if(r===null)return s;e=r;let o='<a href="'+e+'"';return t&&(o+=' title="'+Oe(t)+'"'),o+=">"+s+"</a>",o}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let r=Vn(e);if(r===null)return Oe(i);e=r;let o=`<img src="${e}" alt="${Oe(i)}"`;return t&&(o+=` title="${Oe(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Oe(e.text)}},ro=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}},Te=class lr{options;renderer;textRenderer;constructor(t){this.options=t||gt,this.options.renderer=this.options.renderer||new qi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new ro}static parse(t,i){return new lr(i).parse(t)}static parseInline(t,i){return new lr(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let r=t[s];if(this.options.extensions?.renderers?.[r.type]){let n=r,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 o=r;switch(o.type){case"space":{i+=this.renderer.space(o);break}case"hr":{i+=this.renderer.hr(o);break}case"heading":{i+=this.renderer.heading(o);break}case"code":{i+=this.renderer.code(o);break}case"table":{i+=this.renderer.table(o);break}case"blockquote":{i+=this.renderer.blockquote(o);break}case"list":{i+=this.renderer.list(o);break}case"checkbox":{i+=this.renderer.checkbox(o);break}case"html":{i+=this.renderer.html(o);break}case"def":{i+=this.renderer.def(o);break}case"paragraph":{i+=this.renderer.paragraph(o);break}case"text":{i+=this.renderer.text(o);break}default:{let n='Token with "'+o.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 r=0;r<t.length;r++){let o=t[r];if(this.options.extensions?.renderers?.[o.type]){let a=this.options.extensions.renderers[o.type].call({parser:this},o);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){s+=a||"";continue}}let n=o;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}},Kt=class{options;block;constructor(e){this.options=e||gt}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?Ae.lex:Ae.lexInline}provideParser(e=this.block){return e?Te.parse:Te.parseInline}},pw=class{defaults=Qr();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Te;Renderer=qi;TextRenderer=ro;Lexer=Ae;Tokenizer=Hi;Hooks=Kt;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 r=s;for(let o of r.header)i=i.concat(this.walkTokens(o.tokens,t));for(let o of r.rows)for(let n of o)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let r=s;i=i.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let n=r[o].flat(1/0);i=i.concat(this.walkTokens(n,t))}):r.tokens&&(i=i.concat(this.walkTokens(r.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(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...n){let a=r.renderer.apply(this,n);return a===!1&&(a=o.apply(this,n)),a}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),i.renderer){let r=this.defaults.renderer||new qi(this.defaults);for(let o in i.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let n=o,a=i.renderer[n],c=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u||""}}s.renderer=r}if(i.tokenizer){let r=this.defaults.tokenizer||new Hi(this.defaults);for(let o in i.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let n=o,a=i.tokenizer[n],c=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u}}s.tokenizer=r}if(i.hooks){let r=this.defaults.hooks||new Kt;for(let o in i.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let n=o,a=i.hooks[n],c=r[n];Kt.passThroughHooks.has(o)?r[n]=p=>{if(this.defaults.async&&Kt.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await a.call(r,p);return c.call(r,h)})();let u=a.call(r,p);return c.call(r,u)}:r[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(r,p);return h===!1&&(h=await c.apply(r,p)),h})();let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u}}s.hooks=r}if(i.walkTokens){let r=this.defaults.walkTokens,o=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(o.call(this,n)),r&&(a=a.concat(r.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ae.lex(e,t??this.defaults)}parser(e,t){return Te.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},r={...this.defaults,...s},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.async===!1)return o(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 o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let n=r.hooks?await r.hooks.preprocess(t):t,a=await(r.hooks?await r.hooks.provideLexer(e):e?Ae.lex:Ae.lexInline)(n,r),c=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(c,r.walkTokens));let p=await(r.hooks?await r.hooks.provideParser(e):e?Te.parse:Te.parseInline)(c,r);return r.hooks?await r.hooks.postprocess(p):p})().catch(o);try{r.hooks&&(t=r.hooks.preprocess(t));let n=(r.hooks?r.hooks.provideLexer(e):e?Ae.lex:Ae.lexInline)(t,r);r.hooks&&(n=r.hooks.processAllTokens(n)),r.walkTokens&&this.walkTokens(n,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(e):e?Te.parse:Te.parseInline)(n,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(n){return o(n)}}}onError(e,t){return i=>{if(i.message+=`
998
+ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Oe(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},ut=new pw;function O(e,t){return ut.parse(e,t)}O.options=O.setOptions=function(e){return ut.setOptions(e),O.defaults=ut.defaults,Ul(O.defaults),O};O.getDefaults=Qr;O.defaults=gt;O.use=function(...e){return ut.use(...e),O.defaults=ut.defaults,Ul(O.defaults),O};O.walkTokens=function(e,t){return ut.walkTokens(e,t)};O.parseInline=ut.parseInline;O.Parser=Te;O.parser=Te.parse;O.Renderer=qi;O.TextRenderer=ro;O.Lexer=Ae;O.lexer=Ae.lex;O.Tokenizer=Hi;O.Hooks=Kt;O.parse=O;O.options;O.setOptions;O.use;O.walkTokens;O.parseInline;Te.parse;Ae.lex;const Zl=new O.Renderer;Zl.html=({text:e})=>fw(e);const hw=300,Nt=new Map;function uw(e){const t=Nt.get(e);if(t!==void 0)return t;const i=O.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:Zl}),s=gw(i);if(Nt.set(e,s),Nt.size>hw){const r=Nt.keys().next().value;r!==void 0&&Nt.delete(r)}return s}function fw(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function gw(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 r=s.name.toLowerCase();r.startsWith("on")&&i.removeAttribute(s.name),(r==="href"||r==="src")&&!mw(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function mw(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var vw=Object.defineProperty,bw=Object.getOwnPropertyDescriptor,Xl=(e,t,i,s)=>{for(var r=s>1?void 0:s?bw(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&vw(t,i,r),r};const ww=D`
999
999
  :host { display: block; }
1000
1000
  .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
1001
1001
  p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
@@ -1020,18 +1020,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1020
1020
  table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
1021
1021
  th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
1022
1022
  th { background: var(--pi-surface); }
1023
- `;let Bi=class extends A{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" dir="auto" @click=${this.onFormattedClick}>${bb(aw(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 r=document.createElement("span");r.setAttribute("aria-hidden","true"),r.textContent="⧉",s.append(r),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await qr(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)}};Bi.styles=uw;Gl([d()],Bi.prototype,"text",2);Bi=Gl([W("formatted-text")],Bi);var fw=Object.defineProperty,gw=Object.getOwnPropertyDescriptor,ti=(e,t,i,s)=>{for(var r=s>1?void 0:s?gw(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&fw(t,i,r),r};const Vn=180;let pt=class extends A{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=mw(e.args),s=vw(e.details),r=e.preview,o=s??r?.diff,n=o===void 0?void 0:bw(o),a=s!==void 0&&r?.diff!==void 0&&s!==r.diff,c=e.status==="error"?e.resultText:r?.error,p=o===void 0?e.resultText:void 0;return l`
1023
+ `;let Ki=class extends R{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" dir="auto" @click=${this.onFormattedClick}>${$b(uw(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 r=document.createElement("span");r.setAttribute("aria-hidden","true"),r.textContent="⧉",s.append(r),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await Gr(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)}};Ki.styles=ww;Xl([d()],Ki.prototype,"text",2);Ki=Xl([W("formatted-text")],Ki);var yw=Object.defineProperty,xw=Object.getOwnPropertyDescriptor,ni=(e,t,i,s)=>{for(var r=s>1?void 0:s?xw(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&yw(t,i,r),r};const Zn=180;let ft=class extends R{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=Sw(e.args),s=kw(e.details),r=e.preview,o=s??r?.diff,n=o===void 0?void 0:$w(o),a=s!==void 0&&r?.diff!==void 0&&s!==r.diff,c=e.status==="error"?e.resultText:r?.error,p=o===void 0?e.resultText:void 0;return l`
1024
1024
  <section class=${`tool-card ${e.status}`}>
1025
1025
  <div class="tool-header">
1026
1026
  <div class="tool-title">
1027
- <span class="status-icon" aria-hidden="true">${yw(e.status)}</span>
1027
+ <span class="status-icon" aria-hidden="true">${Cw(e.status)}</span>
1028
1028
  <strong>${e.toolName}</strong>
1029
1029
  ${i===void 0?l`<span class="summary">${e.summary}</span>`:l`<span class="path">${i}</span>`}
1030
1030
  </div>
1031
1031
  <div class="tool-meta">
1032
- ${Gn(e)===void 0?null:l`<span>${Gn(e)}</span>`}
1032
+ ${Xn(e)===void 0?null:l`<span>${Xn(e)}</span>`}
1033
1033
  ${n===void 0?null:l`<span class="diff-stats"><b class="added">+${n.added}</b><span>/</span><b class="removed">-${n.removed}</b></span>`}
1034
- <span class="status-label">${xw(e.status)}</span>
1034
+ <span class="status-label">${Iw(e.status)}</span>
1035
1035
  </div>
1036
1036
  </div>
1037
1037
 
@@ -1046,7 +1046,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1046
1046
  <pre>${e}</pre>
1047
1047
  </details>
1048
1048
  `}renderDiffBody(e,t){const i=e.split(`
1049
- `),s=!this.showFullDiff&&i.length>Vn,r=s?i.slice(0,Vn):i;return l`
1049
+ `),s=!this.showFullDiff&&i.length>Zn,r=s?i.slice(0,Zn):i;return l`
1050
1050
  <details class="diff-details" ?open=${this.diffOpen} @toggle=${o=>{this.onDiffToggle(o)}}>
1051
1051
  <summary>
1052
1052
  <span>${t}</span>
@@ -1056,14 +1056,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1056
1056
  <span>${s?`显示 ${String(r.length)} / ${String(i.length)} 行`:"完整 diff"}</span>
1057
1057
  <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"已复制":"复制 diff"}</button>
1058
1058
  </div>
1059
- <pre class="diff" aria-label=${t}><code class="diff-content">${r.map(o=>l`<span class=${ww(o)}>${o}</span>`)}</code></pre>
1059
+ <pre class="diff" aria-label=${t}><code class="diff-content">${r.map(o=>l`<span class=${Pw(o)}>${o}</span>`)}</code></pre>
1060
1060
  ${s?l`
1061
1061
  <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
1062
1062
  显示全部 ${String(i.length)} 行 diff
1063
1063
  </button>
1064
1064
  `:null}
1065
1065
  </details>
1066
- `}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){const t=await qr(e);this.copied=t,t&&window.setTimeout(()=>{this.copied=!1},1200)}};pt.styles=E`
1066
+ `}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){const t=await Gr(e);this.copied=t,t&&window.setTimeout(()=>{this.copied=!1},1200)}};ft.styles=D`
1067
1067
  :host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
1068
1068
  .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); }
1069
1069
  .tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
@@ -1103,19 +1103,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1103
1103
  .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
1104
1104
  .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
1105
1105
  .show-more { justify-self: start; }
1106
- `;ti([d({attribute:!1})],pt.prototype,"execution",2);ti([x()],pt.prototype,"showFullDiff",2);ti([x()],pt.prototype,"copied",2);ti([x()],pt.prototype,"diffOpen",2);pt=ti([W("tool-execution-view")],pt);function mw(e){return or(e,"path")??or(e,"file_path")}function Gn(e){if(e.toolName!=="edit")return;const t=Si(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof Si(e.args,"oldText")=="string"&&typeof Si(e.args,"newText")=="string")return"1 处编辑"}function vw(e){return or(e,"diff")}function bw(e){let t=0,i=0;for(const s of e.split(`
1107
- `))Jl(s)?t++:Ql(s)&&i++;return{added:t,removed:i}}function ww(e){return Jl(e)?"added":Ql(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function Jl(e){return e.startsWith("+")&&!e.startsWith("+++")}function Ql(e){return e.startsWith("-")&&!e.startsWith("---")}function yw(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function xw(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function Sw(e){return typeof e=="object"&&e!==null}function Si(e,t){return Sw(e)?e[t]:void 0}function or(e,t){const i=Si(e,t);return typeof i=="string"?i:void 0}var kw=Object.defineProperty,$w=Object.getOwnPropertyDescriptor,q=(e,t,i,s)=>{for(var r=s>1?void 0:s?$w(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&kw(t,i,r),r};const Pw=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Cw=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),Es=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"],Iw={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 Jn(){return Es[Math.floor(Math.random()*Es.length)]??Es[0]}function Qn(e){return ki(e,0,100)}function ki(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let U=class extends A{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 Uv,this.scrollController=new db,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`
1106
+ `;ni([d({attribute:!1})],ft.prototype,"execution",2);ni([w()],ft.prototype,"showFullDiff",2);ni([w()],ft.prototype,"copied",2);ni([w()],ft.prototype,"diffOpen",2);ft=ni([W("tool-execution-view")],ft);function Sw(e){return cr(e,"path")??cr(e,"file_path")}function Xn(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 kw(e){return cr(e,"diff")}function $w(e){let t=0,i=0;for(const s of e.split(`
1107
+ `))Yl(s)?t++:ec(s)&&i++;return{added:t,removed:i}}function Pw(e){return Yl(e)?"added":ec(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function Yl(e){return e.startsWith("+")&&!e.startsWith("+++")}function ec(e){return e.startsWith("-")&&!e.startsWith("---")}function Cw(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function Iw(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function Rw(e){return typeof e=="object"&&e!==null}function Ci(e,t){return Rw(e)?e[t]:void 0}function cr(e,t){const i=Ci(e,t);return typeof i=="string"?i:void 0}var Aw=Object.defineProperty,Tw=Object.getOwnPropertyDescriptor,H=(e,t,i,s)=>{for(var r=s>1?void 0:s?Tw(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Aw(t,i,r),r};const Mw=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Ew=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),_s=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"],Dw={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 Yn(){return _s[Math.floor(Math.random()*_s.length)]??_s[0]}function ea(e){return Ii(e,0,100)}function Ii(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let z=class extends R{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 Kv,this.scrollController=new mb,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`
1108
1108
  <div class="chat-wrap">
1109
1109
  ${this.renderConversationRail()}
1110
1110
  <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
1111
1111
  ${this.renderHistoryBoundary()}
1112
- ${Lv(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)))}
1112
+ ${Nv(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)))}
1113
1113
  ${this.renderQueuedMessages()}
1114
1114
  ${this.renderSessionActivity()}
1115
1115
  </div>
1116
1116
  ${this.renderActivityDock()}
1117
1117
  </div>
1118
- `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Nv(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`
1118
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Jv(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`
1119
1119
  <div class="activity-dock active" aria-live="polite">
1120
1120
  <span class="dot"></span>
1121
1121
  <span class="activity-text">正在发送你的消息…</span>
@@ -1150,7 +1150,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1150
1150
  <span>助手正在总结早前上下文。压缩完成前,新提示会排队等待。</span>
1151
1151
  ${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} 条消息已排队</small>`:null}
1152
1152
  </aside>
1153
- `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Jn():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Jn(),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 Ds(e);const i=Ds(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?Qn(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=ki(this.currentConversationIndex??t,0,e-1);return Qn(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?l`
1153
+ `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Yn():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Yn(),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 Ls(e);const i=Ls(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?ea(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=Ii(this.currentConversationIndex??t,0,e-1);return ea(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?l`
1154
1154
  <div class="history-boundary">
1155
1155
  <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>加载更早的消息</button>
1156
1156
  <span>向上滚动加载更早的消息</span>
@@ -1167,7 +1167,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1167
1167
  <details class=${s?"msg event-group live":"msg event-group"} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${o} @toggle=${n=>{this.onGroupToggle(r,n,s)}}>
1168
1168
  <summary>
1169
1169
  <b class="label">${s?"实时事件":"事件"}</b>
1170
- <span>${qv(e)}</span>
1170
+ <span>${Qv(e)}</span>
1171
1171
  </summary>
1172
1172
  <div class="group-body">
1173
1173
  ${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
@@ -1180,7 +1180,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1180
1180
  </details>
1181
1181
  `}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`
1182
1182
  <div class="msg-header">
1183
- <b class="label">${Zn(e.role)}</b>
1183
+ <b class="label">${ta(e.role)}</b>
1184
1184
  <div class="msg-header-trailing">
1185
1185
  ${this.renderMessageActions(e,t)}
1186
1186
  <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=${r=>{this.onMetaKeydown(r,t,s)}}>${i.short}</span>
@@ -1188,13 +1188,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1188
1188
  </div>
1189
1189
  `}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return l`
1190
1190
  <div class="msg-actions" aria-label="消息操作">
1191
- <button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${Zn(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
1191
+ <button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${ta(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
1192
1192
  <span aria-hidden="true">${i?"✓":"⧉"}</span>
1193
1193
  </button>
1194
1194
  </div>
1195
1195
  `}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(`
1196
1196
 
1197
- `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await qr(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}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 r=i===void 0?void 0:this.formatTimestamp(i),o=[r?.short,s].filter(c=>c!==void 0&&c!==""),n=[r?.full,s===void 0?void 0:`模型:${s}`].filter(c=>c!==void 0&&c!==""),a={short:o.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:Pw.format(t),full:Cw.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`
1197
+ `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await Gr(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}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 r=i===void 0?void 0:this.formatTimestamp(i),o=[r?.short,s].filter(c=>c!==void 0&&c!==""),n=[r?.full,s===void 0?void 0:`模型:${s}`].filter(c=>c!==void 0&&c!==""),a={short:o.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:Mw.format(t),full:Ew.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`
1198
1198
  <details class="part skill-invocation">
1199
1199
  <summary><b>[技能]</b> ${e.name}</summary>
1200
1200
  <small>${e.location}</small>
@@ -1210,31 +1210,31 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1210
1210
  <summary>${e.isError?"✖":"✓"} ${e.toolName} 结果</summary>
1211
1211
  <formatted-text .text=${e.text}></formatted-text>
1212
1212
  </details>
1213
- `: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&&tb({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?_l(e):!0}isAtBottom(){const e=this.chat;return e?Ol(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 Vv(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 r=this.chat;if(!(!r||t!==this.prependRestoreToken)){if(Gv(r,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=r.scrollTop,i+=1,i<Kv){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=ki(i,0,Math.max(0,e-1));return}this.currentConversationIndex=ki(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 jn(e,t)??jn(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)}`}};U.styles=gb;q([d({attribute:!1})],U.prototype,"messages",2);q([d()],U.prototype,"sessionId",2);q([d({type:Number})],U.prototype,"messageStart",2);q([d({type:Number})],U.prototype,"messageEnd",2);q([d({type:Number})],U.prototype,"messageTotal",2);q([d({type:Boolean})],U.prototype,"hasMore",2);q([d({type:Boolean})],U.prototype,"loadingMore",2);q([d({type:Boolean})],U.prototype,"isReceivingPartialStream",2);q([d({type:Boolean})],U.prototype,"isSendingPrompt",2);q([d({type:Boolean})],U.prototype,"isCompacting",2);q([d({type:Number})],U.prototype,"pendingMessageCount",2);q([d({attribute:!1})],U.prototype,"status",2);q([d({attribute:!1})],U.prototype,"activity",2);q([d({attribute:!1})],U.prototype,"onLoadMore",2);q([B(".chat")],U.prototype,"chat",2);q([x()],U.prototype,"pinnedToBottom",2);q([x()],U.prototype,"expandedMetaKey",2);q([x()],U.prototype,"copiedMessageKey",2);q([x()],U.prototype,"currentConversationIndex",2);q([x()],U.prototype,"loadMoreRequested",2);U=q([W("chat-view")],U);function Zn(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Ds(e){return e==="bash"?"Shell 运行中":e==="running"?"运行中":Iw[e]??e}const Rw=["image/jpeg","image/png","image/gif","image/webp"],Aw=new Set(Rw);function to(e){return typeof e=="string"&&Aw.has(e)}function Tw(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 Mw="application/octet-stream",Ew="读取附件失败。";async function Dw(e,t){const i=[];let s;for(const r of e)try{const o=await t(r);i.push(Ow(r,o))}catch{s=Ew}return{attachments:i,...s===void 0?{}:{error:s}}}function nr(e){return e.kind==="image"&&to(e.mimeType)}function ar(e){return e.every(t=>nr(t))}function Ww(e,t){return ar(t)?e:"folder"}function Ow(e,t){return to(e.type)?{kind:"image",name:Xn(e),mimeType:e.type,data:t,size:e.size}:{kind:"file",name:Xn(e),mimeType:_w(e),data:t,size:e.size}}function _w(e){const t=e.type.trim();return t===""?Mw:t}function Xn(e){return e.name!==""?e.name:to(e.type)?`pasted-image.${Tw(e.type)}`:"pasted-file.bin"}const Zl="pi-web:attachment-delivery";function Xl(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Lw(e=Xl()){try{return e?.getItem(Zl)==="folder"?"folder":"inline"}catch{return"inline"}}function jw(e,t=Xl()){try{t?.setItem(Zl,e)}catch{}}const Fw="(pointer: coarse), (max-width: 760px)",Yl="pi-web.promptEnterPreference";function as(){return typeof window<"u"&&"matchMedia"in window?window.matchMedia(Fw):void 0}function Uw(e){return e==="send"||e==="newline"?e:"auto"}function ls(e=ec()){if(e===void 0)return"auto";try{return Uw(e.getItem(Yl))}catch{return"auto"}}function zw(e,t=ec()){if(t!==void 0)try{t.setItem(Yl,e)}catch{}}function Bw(e=as(),t=ls()){return t==="send"?!0:t==="newline"?!1:e?.matches!==!0}function Nw(e,t,i=as()){return e?i?.matches===!0?t:!0:!1}function qw(e,t=as(),i=ls()){const s=Bw(t,i);return e?!s:s}function ec(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function Hw(){return be`
1213
+ `: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&&ab({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?zl(e):!0}isAtBottom(){const e=this.chat;return e?Fl(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 Yv(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 r=this.chat;if(!(!r||t!==this.prependRestoreToken)){if(eb(r,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=r.scrollTop,i+=1,i<Xv){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=Ii(i,0,Math.max(0,e-1));return}this.currentConversationIndex=Ii(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 Bn(e,t)??Bn(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)}`}};z.styles=xb;H([d({attribute:!1})],z.prototype,"messages",2);H([d()],z.prototype,"sessionId",2);H([d({type:Number})],z.prototype,"messageStart",2);H([d({type:Number})],z.prototype,"messageEnd",2);H([d({type:Number})],z.prototype,"messageTotal",2);H([d({type:Boolean})],z.prototype,"hasMore",2);H([d({type:Boolean})],z.prototype,"loadingMore",2);H([d({type:Boolean})],z.prototype,"isReceivingPartialStream",2);H([d({type:Boolean})],z.prototype,"isSendingPrompt",2);H([d({type:Boolean})],z.prototype,"isCompacting",2);H([d({type:Number})],z.prototype,"pendingMessageCount",2);H([d({attribute:!1})],z.prototype,"status",2);H([d({attribute:!1})],z.prototype,"activity",2);H([d({attribute:!1})],z.prototype,"onLoadMore",2);H([B(".chat")],z.prototype,"chat",2);H([w()],z.prototype,"pinnedToBottom",2);H([w()],z.prototype,"expandedMetaKey",2);H([w()],z.prototype,"copiedMessageKey",2);H([w()],z.prototype,"currentConversationIndex",2);H([w()],z.prototype,"loadMoreRequested",2);z=H([W("chat-view")],z);function ta(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Ls(e){return e==="bash"?"Shell 运行中":e==="running"?"运行中":Dw[e]??e}const Ww=["image/jpeg","image/png","image/gif","image/webp"],Ow=new Set(Ww);function oo(e){return typeof e=="string"&&Ow.has(e)}function _w(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 Lw="application/octet-stream",jw="读取附件失败。";async function Fw(e,t){const i=[];let s;for(const r of e)try{const o=await t(r);i.push(Uw(r,o))}catch{s=jw}return{attachments:i,...s===void 0?{}:{error:s}}}function dr(e){return e.kind==="image"&&oo(e.mimeType)}function pr(e){return e.every(t=>dr(t))}function zw(e,t){return pr(t)?e:"folder"}function Uw(e,t){return oo(e.type)?{kind:"image",name:ia(e),mimeType:e.type,data:t,size:e.size}:{kind:"file",name:ia(e),mimeType:Bw(e),data:t,size:e.size}}function Bw(e){const t=e.type.trim();return t===""?Lw:t}function ia(e){return e.name!==""?e.name:oo(e.type)?`pasted-image.${_w(e.type)}`:"pasted-file.bin"}const tc="pi-web:attachment-delivery";function ic(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Nw(e=ic()){try{return e?.getItem(tc)==="folder"?"folder":"inline"}catch{return"inline"}}function Hw(e,t=ic()){try{t?.setItem(tc,e)}catch{}}const qw="(pointer: coarse), (max-width: 760px)",sc="pi-web.promptEnterPreference";function ps(){return typeof window<"u"&&"matchMedia"in window?window.matchMedia(qw):void 0}function Kw(e){return e==="send"||e==="newline"?e:"auto"}function hs(e=rc()){if(e===void 0)return"auto";try{return Kw(e.getItem(sc))}catch{return"auto"}}function Vw(e,t=rc()){if(t!==void 0)try{t.setItem(sc,e)}catch{}}function Gw(e=ps(),t=hs()){return t==="send"?!0:t==="newline"?!1:e?.matches!==!0}function Jw(e,t,i=ps()){return e?i?.matches===!0?t:!0:!1}function Qw(e,t=ps(),i=hs()){const s=Gw(t,i);return e?!s:s}function rc(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function Zw(){return be`
1214
1214
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1215
1215
  <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>
1216
1216
  </svg>
1217
- `}function tc(){return be`
1217
+ `}function oc(){return be`
1218
1218
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1219
1219
  <path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
1220
1220
  <path d="M21 3 11.5 12.5"></path>
1221
1221
  </svg>
1222
- `}function Kw(){return be`
1222
+ `}function Xw(){return be`
1223
1223
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1224
1224
  <path d="M4 7h11"></path>
1225
1225
  <path d="M4 12h7"></path>
1226
1226
  <path d="M4 17h7"></path>
1227
1227
  <path d="m15 14 5 3-5 3z"></path>
1228
1228
  </svg>
1229
- `}function Vw(){return tc()}function Gw(){return be`
1229
+ `}function Yw(){return oc()}function ey(){return be`
1230
1230
  <svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1231
1231
  <rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
1232
1232
  </svg>
1233
- `}function Jw(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 be`<rect class=${w?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${g} width=${n} height=${h} rx="1"></rect>`});return be`
1233
+ `}function ty(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,y=p<e.filled;return be`<rect class=${y?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${g} width=${n} height=${h} rx="1"></rect>`});return be`
1234
1234
  <svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1235
1235
  ${a}
1236
1236
  </svg>
1237
- `}const Qw=["off","minimal","low","medium","high","xhigh"];function lr(e){return e===void 0||e===""?"off":e}function Zw(e,t){const i=t.length>=2?t:Qw,s=i.length-1,r=lr(e),o=i.indexOf(r),n=o<=0?0:Math.min(o,s);return{total:s,filled:n}}class Xw extends Br{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===Ur.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 r="element"in t?t.element:void 0;requestAnimationFrame(()=>{r instanceof HTMLElement&&r.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const io=zr(Xw);var Yw=Object.defineProperty,ey=Object.getOwnPropertyDescriptor,cs=(e,t,i,s)=>{for(var r=s>1?void 0:s?ey(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Yw(t,i,r),r};const ty=E`
1237
+ `}const iy=["off","minimal","low","medium","high","xhigh"];function hr(e){return e===void 0||e===""?"off":e}function sy(e,t){const i=t.length>=2?t:iy,s=i.length-1,r=hr(e),o=i.indexOf(r),n=o<=0?0:Math.min(o,s);return{total:s,filled:n}}class ry extends Kr{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===Hr.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 r="element"in t?t.element:void 0;requestAnimationFrame(()=>{r instanceof HTMLElement&&r.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const no=qr(ry);var oy=Object.defineProperty,ny=Object.getOwnPropertyDescriptor,us=(e,t,i,s)=>{for(var r=s>1?void 0:s?ny(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&oy(t,i,r),r};const ay=D`
1238
1238
  :host { display: block; }
1239
1239
  .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); }
1240
1240
  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; }
@@ -1242,22 +1242,22 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1242
1242
  button.selected, button:hover { background: var(--pi-selection-bg); }
1243
1243
  span { color: var(--pi-muted); font-size: 12px; }
1244
1244
  small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1245
- `;let Pt=class extends A{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
1245
+ `;let At=class extends R{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
1246
1246
  <div class="menu">
1247
1247
  ${this.items.map((e,t)=>l`
1248
- <button class=${t===this.selectedIndex?"selected":""} ${io(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1248
+ <button class=${t===this.selectedIndex?"selected":""} ${no(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1249
1249
  <strong>${e.insertText}</strong>
1250
1250
  <span>${e.detail}</span>
1251
1251
  ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1252
1252
  </button>
1253
1253
  `)}
1254
1254
  </div>
1255
- `:null}};Pt.styles=ty;cs([d({attribute:!1})],Pt.prototype,"items",2);cs([d({type:Number})],Pt.prototype,"selectedIndex",2);cs([d({attribute:!1})],Pt.prototype,"onPick",2);Pt=cs([W("autocomplete-menu")],Pt);var iy=Object.defineProperty,sy=Object.getOwnPropertyDescriptor,F=(e,t,i,s)=>{for(var r=s>1?void 0:s?sy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&iy(t,i,r),r};let L=class extends A{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft="",this.currentInputMode={kind:"normal"},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=Lw(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new ro,this.readOnlyCompartment=new ro,this.mobilePromptEnterMedia=as(),this.explicitShiftKeyActive=!1}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=ci(i,t);s!==void 0&&Mi(s,this.draft);const r=ci(this.machineId,this.sessionId);this.draft=r!==void 0?Ka(r):"",this.currentInputMode=Oi(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has("status")&&e.size===1?!ry(e.get("status"),this.status):!0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=this.currentInputMode.kind==="shell"?this.currentInputMode:void 0,t=e!==void 0,i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return l`
1255
+ `:null}};At.styles=ay;us([d({attribute:!1})],At.prototype,"items",2);us([d({type:Number})],At.prototype,"selectedIndex",2);us([d({attribute:!1})],At.prototype,"onPick",2);At=us([W("autocomplete-menu")],At);var ly=Object.defineProperty,cy=Object.getOwnPropertyDescriptor,F=(e,t,i,s)=>{for(var r=s>1?void 0:s?cy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&ly(t,i,r),r};let L=class extends R{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft="",this.currentInputMode={kind:"normal"},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=Nw(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new lo,this.readOnlyCompartment=new lo,this.mobilePromptEnterMedia=ps(),this.explicitShiftKeyActive=!1}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=ui(i,t);s!==void 0&&Oi(s,this.draft);const r=ui(this.machineId,this.sessionId);this.draft=r!==void 0?Qa(r):"",this.currentInputMode=Fi(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has("status")&&e.size===1?!dy(e.get("status"),this.status):!0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=this.currentInputMode.kind==="shell"?this.currentInputMode:void 0,t=e!==void 0,i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return l`
1256
1256
  <footer class=${t?"shell-mode":""} @paste=${r=>{this.handlePaste(r)}} @dragover=${r=>{this.handleDragOver(r)}} @drop=${r=>{this.handleDrop(r)}}>
1257
1257
  <div class="editor-wrap">
1258
1258
  <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="给 pi 发送消息" aria-disabled=${this.disabled?"true":"false"}></div>
1259
1259
  <input class="attachment-input" type="file" multiple hidden @change=${r=>{this.handleFileInput(r)}} />
1260
- <button class="editor-attach icon-button" ?disabled=${s} title="附加文件" aria-label="附加文件" @click=${()=>{this.attachmentInput?.click()}}>${Hw()}</button>
1260
+ <button class="editor-attach icon-button" ?disabled=${s} title="附加文件" aria-label="附加文件" @click=${()=>{this.attachmentInput?.click()}}>${Zw()}</button>
1261
1261
  ${t?l`<div class="mode-hint">Shell 命令${e.excludeFromContext?" · 已排除上下文":""}</div>`:null}
1262
1262
  ${this.isCompacting&&!t?l`<div class="mode-hint">正在压缩历史 · 消息将排队发送</div>`:null}
1263
1263
  ${this.renderAttachments()}
@@ -1265,20 +1265,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1265
1265
  </div>
1266
1266
  <div class="actions">
1267
1267
  ${this.renderCompactStatus()}
1268
- <button class="icon-button send-button" ?disabled=${s} title=${i?"当前活动结束后排队发送":"发送"} aria-label=${i?"排队发送":"发送"} @click=${()=>{this.send("followUp")}}>${i?Kw():tc()}</button>
1269
- ${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send("steer")}}>${Vw()}</button>`:null}
1270
- <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} aria-label="停止" @click=${()=>this.onStop?.()}>${Gw()}</button>
1268
+ <button class="icon-button send-button" ?disabled=${s} title=${i?"当前活动结束后排队发送":"发送"} aria-label=${i?"排队发送":"发送"} @click=${()=>{this.send("followUp")}}>${i?Xw():oc()}</button>
1269
+ ${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send("steer")}}>${Yw()}</button>`:null}
1270
+ <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} aria-label="停止" @click=${()=>this.onStop?.()}>${ey()}</button>
1271
1271
  </div>
1272
1272
  </footer>
1273
1273
  `}focusInput(){this.editor?.focus()}get view(){return this.editor}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`
1274
1274
  <div class="compact-status" aria-label="会话状态">
1275
1275
  <button class="select-model" title="选择模型" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
1276
- <button class="select-thinking icon-button" title=${`思考级别:${lr(e.thinkingLevel)}`} aria-label=${`思考级别:${lr(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${Jw(Zw(e.thinkingLevel,this.availableThinkingLevels))}</button>
1276
+ <button class="select-thinking icon-button" title=${`思考级别:${hr(e.thinkingLevel)}`} aria-label=${`思考级别:${hr(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${ty(sy(e.thinkingLevel,this.availableThinkingLevels))}</button>
1277
1277
  </div>
1278
- `}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;const e=ar(this.attachments),t=this.effectiveAttachmentDelivery();return l`
1278
+ `}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;const e=pr(this.attachments),t=this.effectiveAttachmentDelivery();return l`
1279
1279
  <div class="attachments" aria-label="待发送附件">
1280
1280
  ${this.attachments.map(i=>l`
1281
- <div class=${`attachment-chip ${nr(i)?"attachment-chip-image":"attachment-chip-file"}`} title=${i.name}>
1281
+ <div class=${`attachment-chip ${dr(i)?"attachment-chip-image":"attachment-chip-file"}`} title=${i.name}>
1282
1282
  ${this.renderAttachmentPreview(i)}
1283
1283
  <button type="button" class="attachment-remove" title="移除附件" aria-label=${`移除 ${i.name}`} @click=${()=>{this.removeAttachment(i.id)}}>×</button>
1284
1284
  </div>
@@ -1293,10 +1293,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1293
1293
  `:null}
1294
1294
  ${this.attachmentError!==void 0?l`<div class="attachment-error">${this.attachmentError}</div>`:null}
1295
1295
  </div>
1296
- `}renderAttachmentPreview(e){return nr(e)?l`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:l`
1297
- <div class="attachment-file-preview" aria-hidden="true">${cy(e.name)}</div>
1296
+ `}renderAttachmentPreview(e){return dr(e)?l`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:l`
1297
+ <div class="attachment-file-preview" aria-hidden="true">${gy(e.name)}</div>
1298
1298
  <span class="attachment-file-name">${e.name}</span>
1299
- `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;const t=e.target.value==="folder"?"folder":"inline";if(t==="inline"&&!ar(this.attachments)){e.target.value="folder";return}this.attachmentDelivery=t,jw(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=Yn(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&ay(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){const t=Yn(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 Dw(e,dy);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=>ly(e))}effectiveAttachmentDelivery(){return Ww(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new it({parent:this.editorHost,state:us.create({doc:this.draft,extensions:[cc(),wc(),dc(),pc.of(" "),hc(uc,{fallback:!0}),it.lineWrapping,it.contentAttributes.of(e=>uy(e.state.sliceDoc(0,e.state.selection.main.head))),it.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),fc("给 pi 发送消息... 使用 / 输入命令,@ 输入已跟踪文件,@ 空格显示所有文件"),this.editableCompartment.of(it.editable.of(!this.disabled)),this.readOnlyCompartment.of(us.readOnly.of(this.disabled)),it.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),gc.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>oo.shift?.(e)??!1},{key:"Backspace",run:e=>yc(e)},...mc,...vc])]})}))}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:no.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(it.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(us.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=ci(this.machineId,this.sessionId);t!==void 0&&Mi(t,this.draft);const i=Oi(this.draft);_u(i,this.currentInputMode)||(this.currentInputMode=i),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 N.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(oy);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 N.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(ny);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const r=Ya(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:r,detail:s.kind,...s.path.endsWith("/")&&r.endsWith('"')?{cursorOffset:r.length-1}:{}}})}}currentTrigger(){return Xa(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}handleEditorKeyDown(e,t){if(e.key==="Shift")return this.explicitShiftKeyActive=!0,!1;if(e.key!=="Enter")return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;const i=Nw(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,i)}handleEditorKeyUp(e){return e.key==="Shift"&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(!t&&this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return qw(t,this.mobilePromptEnterMedia,ls())?(this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0):xc(e)||bc(e)}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):oo.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,r=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:r,insert:`${e.insertText}${i}`},selection:no.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,r=i.length>0?this.currentAttachments():void 0,o=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,s,r,r===void 0?void 0:o)}resetComposer(){this.draft="",this.currentInputMode={kind:"normal"};const e=ci(this.machineId,this.sessionId);e!==void 0&&Mr(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}};L.styles=bg;F([d({type:Boolean})],L.prototype,"disabled",2);F([d()],L.prototype,"sessionId",2);F([d()],L.prototype,"cwd",2);F([d()],L.prototype,"machineId",2);F([d()],L.prototype,"projectId",2);F([d()],L.prototype,"workspaceId",2);F([d({type:Boolean})],L.prototype,"workspaceScopedFileSuggestions",2);F([d({type:Boolean})],L.prototype,"canSteer",2);F([d({type:Boolean})],L.prototype,"isCompacting",2);F([d({type:Boolean})],L.prototype,"canStop",2);F([d({attribute:!1})],L.prototype,"status",2);F([d({type:Boolean})],L.prototype,"sending",2);F([d({attribute:!1})],L.prototype,"onSend",2);F([d({attribute:!1})],L.prototype,"onStop",2);F([d({attribute:!1})],L.prototype,"onSelectModel",2);F([d({attribute:!1})],L.prototype,"onSelectThinking",2);F([d({attribute:!1})],L.prototype,"availableThinkingLevels",2);F([B(".markdown-editor")],L.prototype,"editorHost",2);F([B(".attachment-input")],L.prototype,"attachmentInput",2);F([x()],L.prototype,"currentInputMode",2);F([x()],L.prototype,"completions",2);F([x()],L.prototype,"selectedIndex",2);F([x()],L.prototype,"attachments",2);F([x()],L.prototype,"attachmentDelivery",2);F([x()],L.prototype,"attachmentError",2);L=F([W("prompt-editor")],L);function ry(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel}function ci(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return qa(e,t)}function oy(){return[]}function ny(){return[]}function Yn(e){return e===null?[]:Array.from(e.files)}function ay(e){const t=Array.from(e.items);return t.length>0?t.some(i=>i.kind==="file"):Array.from(e.types).includes("Files")}function ly(e){return e.kind==="image"?{kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}:{kind:"file",mimeType:e.mimeType,data:e.data,name:e.name}}function cy(e){const t=e.trim(),i=t.lastIndexOf(".");return i>=0&&i<t.length-1?t.slice(i+1,i+5).toUpperCase():"FILE"}function dy(e){return new Promise((t,i)=>{const s=new FileReader;s.onerror=()=>{i(s.error??new Error("读取文件失败"))},s.onload=()=>{const r=s.result;if(typeof r!="string"){i(new Error("文件读取结果异常"));return}const o=r.indexOf(",");t(o===-1?r:r.slice(o+1))},s.readAsDataURL(e)})}const py={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true",dir:"auto"},hy={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",dir:"auto"};function uy(e){return Oi(e).kind==="normal"?py:hy}function di(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 fy(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var gy=Object.defineProperty,my=Object.getOwnPropertyDescriptor,ic=(e,t,i,s)=>{for(var r=s>1?void 0:s?my(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&gy(t,i,r),r};const vy=E`
1299
+ `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;const t=e.target.value==="folder"?"folder":"inline";if(t==="inline"&&!pr(this.attachments)){e.target.value="folder";return}this.attachmentDelivery=t,Hw(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=sa(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&uy(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){const t=sa(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 Fw(e,my);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=>fy(e))}effectiveAttachmentDelivery(){return zw(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new rt({parent:this.editorHost,state:vs.create({doc:this.draft,extensions:[uc(),kc(),fc(),gc.of(" "),mc(vc,{fallback:!0}),rt.lineWrapping,rt.contentAttributes.of(e=>wy(e.state.sliceDoc(0,e.state.selection.main.head))),rt.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),bc("给 pi 发送消息... 使用 / 输入命令,@ 输入已跟踪文件,@ 空格显示所有文件"),this.editableCompartment.of(rt.editable.of(!this.disabled)),this.readOnlyCompartment.of(vs.readOnly.of(this.disabled)),rt.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),wc.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>co.shift?.(e)??!1},{key:"Backspace",run:e=>$c(e)},...yc,...xc])]})}))}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:po.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(rt.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(vs.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=ui(this.machineId,this.sessionId);t!==void 0&&Oi(t,this.draft);const i=Fi(this.draft);Bu(i,this.currentInputMode)||(this.currentInputMode=i),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 N.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(py);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 N.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(hy);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const r=sl(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:r,detail:s.kind,...s.path.endsWith("/")&&r.endsWith('"')?{cursorOffset:r.length-1}:{}}})}}currentTrigger(){return il(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}handleEditorKeyDown(e,t){if(e.key==="Shift")return this.explicitShiftKeyActive=!0,!1;if(e.key!=="Enter")return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;const i=Jw(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,i)}handleEditorKeyUp(e){return e.key==="Shift"&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(!t&&this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return Qw(t,this.mobilePromptEnterMedia,hs())?(this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0):Pc(e)||Sc(e)}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):co.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,r=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:r,insert:`${e.insertText}${i}`},selection:po.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,r=i.length>0?this.currentAttachments():void 0,o=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,s,r,r===void 0?void 0:o)}resetComposer(){this.draft="",this.currentInputMode={kind:"normal"};const e=ui(this.machineId,this.sessionId);e!==void 0&&Or(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}};L.styles=$g;F([d({type:Boolean})],L.prototype,"disabled",2);F([d()],L.prototype,"sessionId",2);F([d()],L.prototype,"cwd",2);F([d()],L.prototype,"machineId",2);F([d()],L.prototype,"projectId",2);F([d()],L.prototype,"workspaceId",2);F([d({type:Boolean})],L.prototype,"workspaceScopedFileSuggestions",2);F([d({type:Boolean})],L.prototype,"canSteer",2);F([d({type:Boolean})],L.prototype,"isCompacting",2);F([d({type:Boolean})],L.prototype,"canStop",2);F([d({attribute:!1})],L.prototype,"status",2);F([d({type:Boolean})],L.prototype,"sending",2);F([d({attribute:!1})],L.prototype,"onSend",2);F([d({attribute:!1})],L.prototype,"onStop",2);F([d({attribute:!1})],L.prototype,"onSelectModel",2);F([d({attribute:!1})],L.prototype,"onSelectThinking",2);F([d({attribute:!1})],L.prototype,"availableThinkingLevels",2);F([B(".markdown-editor")],L.prototype,"editorHost",2);F([B(".attachment-input")],L.prototype,"attachmentInput",2);F([w()],L.prototype,"currentInputMode",2);F([w()],L.prototype,"completions",2);F([w()],L.prototype,"selectedIndex",2);F([w()],L.prototype,"attachments",2);F([w()],L.prototype,"attachmentDelivery",2);F([w()],L.prototype,"attachmentError",2);L=F([W("prompt-editor")],L);function dy(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel}function ui(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return Ga(e,t)}function py(){return[]}function hy(){return[]}function sa(e){return e===null?[]:Array.from(e.files)}function uy(e){const t=Array.from(e.items);return t.length>0?t.some(i=>i.kind==="file"):Array.from(e.types).includes("Files")}function fy(e){return e.kind==="image"?{kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}:{kind:"file",mimeType:e.mimeType,data:e.data,name:e.name}}function gy(e){const t=e.trim(),i=t.lastIndexOf(".");return i>=0&&i<t.length-1?t.slice(i+1,i+5).toUpperCase():"FILE"}function my(e){return new Promise((t,i)=>{const s=new FileReader;s.onerror=()=>{i(s.error??new Error("读取文件失败"))},s.onload=()=>{const r=s.result;if(typeof r!="string"){i(new Error("文件读取结果异常"));return}const o=r.indexOf(",");t(o===-1?r:r.slice(o+1))},s.readAsDataURL(e)})}const vy={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true",dir:"auto"},by={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",dir:"auto"};function wy(e){return Fi(e).kind==="normal"?vy:by}function fi(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 yy(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var xy=Object.defineProperty,Sy=Object.getOwnPropertyDescriptor,nc=(e,t,i,s)=>{for(var r=s>1?void 0:s?Sy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&xy(t,i,r),r};const ky=D`
1300
1300
  :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
1301
1301
  .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; }
1302
1302
  span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
@@ -1306,15 +1306,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1306
1306
  .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
1307
1307
  .muted { color: var(--pi-dim); }
1308
1308
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
1309
- `;let Ni=class extends A{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?`上下文 ${di(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${di(t.contextWindow)}`:"上下文未知",s=e.tokens;return l`
1309
+ `;let Vi=class extends R{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?`上下文 ${fi(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${fi(t.contextWindow)}`:"上下文未知",s=e.tokens;return l`
1310
1310
  <div class="bar">
1311
- <span>↑${di(s.input)}</span>
1312
- <span>↓${di(s.output)}</span>
1311
+ <span>↑${fi(s.input)}</span>
1312
+ <span>↓${fi(s.output)}</span>
1313
1313
  <span class="context">${i}</span>
1314
- <span>${fy(e.cost)}</span>
1314
+ <span>${yy(e.cost)}</span>
1315
1315
  ${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} 条排队</span>`:null}
1316
1316
  </div>
1317
- `}};Ni.styles=vy;ic([d({attribute:!1})],Ni.prototype,"status",2);Ni=ic([W("status-bar")],Ni);const sc=E`
1317
+ `}};Vi.styles=ky;nc([d({attribute:!1})],Vi.prototype,"status",2);Vi=nc([W("status-bar")],Vi);const ac=D`
1318
1318
  :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1319
1319
  .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
1320
1320
  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; }
@@ -1328,7 +1328,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1328
1328
  .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
1329
1329
  small { display: block; margin-top: 4px; color: var(--pi-muted); }
1330
1330
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
1331
- `;var by=Object.defineProperty,wy=Object.getOwnPropertyDescriptor,Ve=(e,t,i,s)=>{for(var r=s>1?void 0:s?wy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&by(t,i,r),r};let Me=class extends A{constructor(){super(...arguments),this.title="选择",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
1331
+ `;var $y=Object.defineProperty,Py=Object.getOwnPropertyDescriptor,Je=(e,t,i,s)=>{for(var r=s>1?void 0:s?Py(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&$y(t,i,r),r};let Ee=class extends R{constructor(){super(...arguments),this.title="选择",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
1332
1332
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1333
1333
  <section @mousedown=${t=>{t.stopPropagation()}}>
1334
1334
  <header>
@@ -1338,7 +1338,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1338
1338
  ${this.searchable?l`<input placeholder="搜索" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
1339
1339
  <div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
1340
1340
  ${e.map((t,i)=>l`
1341
- <button class=${i===this.selectedIndex?"selected":""} ${io(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1341
+ <button class=${i===this.selectedIndex?"selected":""} ${no(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1342
1342
  <span>${t.label}</span>
1343
1343
  ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1344
1344
  </button>
@@ -1347,7 +1347,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1347
1347
  </div>
1348
1348
  </section>
1349
1349
  </div>
1350
- `}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)}}};Me.styles=sc;Ve([d()],Me.prototype,"title",2);Ve([d({type:Boolean})],Me.prototype,"searchable",2);Ve([d({attribute:!1})],Me.prototype,"options",2);Ve([d({attribute:!1})],Me.prototype,"selectedValue",2);Ve([d({attribute:!1})],Me.prototype,"onPick",2);Ve([d({attribute:!1})],Me.prototype,"onCancel",2);Ve([x()],Me.prototype,"selectedIndex",2);Ve([x()],Me.prototype,"query",2);Me=Ve([W("command-picker")],Me);var yy=Object.defineProperty,xy=Object.getOwnPropertyDescriptor,ut=(e,t,i,s)=>{for(var r=s>1?void 0:s?xy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&yy(t,i,r),r};const Sy=E`
1350
+ `}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)}}};Ee.styles=ac;Je([d()],Ee.prototype,"title",2);Je([d({type:Boolean})],Ee.prototype,"searchable",2);Je([d({attribute:!1})],Ee.prototype,"options",2);Je([d({attribute:!1})],Ee.prototype,"selectedValue",2);Je([d({attribute:!1})],Ee.prototype,"onPick",2);Je([d({attribute:!1})],Ee.prototype,"onCancel",2);Je([w()],Ee.prototype,"selectedIndex",2);Je([w()],Ee.prototype,"query",2);Ee=Je([W("command-picker")],Ee);var Cy=Object.defineProperty,Iy=Object.getOwnPropertyDescriptor,mt=(e,t,i,s)=>{for(var r=s>1?void 0:s?Iy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Cy(t,i,r),r};const Ry=D`
1351
1351
  :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1352
1352
  .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; }
1353
1353
  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; }
@@ -1365,7 +1365,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1365
1365
  .group { grid-column: 1 / -1; font-size: 12px; }
1366
1366
  kbd { align-self: center; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 2px 6px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
1367
1367
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
1368
- `;let qe=class extends A{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
1368
+ `;let Ke=class extends R{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
1369
1369
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1370
1370
  <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1371
1371
  <header>
@@ -1378,20 +1378,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1378
1378
  </header>
1379
1379
  <div class="options">
1380
1380
  ${e.length===0?l`<div class="empty">未找到操作。</div>`:e.map((t,i)=>l`
1381
- <button class=${`${i===this.selectedIndex?"selected":""} ${t.enabled===!1?"disabled":""}`} ?disabled=${t.enabled===!1} title=${t.disabledReason??t.title} ${io(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1381
+ <button class=${`${i===this.selectedIndex?"selected":""} ${t.enabled===!1?"disabled":""}`} ?disabled=${t.enabled===!1} title=${t.disabledReason??t.title} ${no(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1382
1382
  <span class="main">
1383
1383
  <strong>${t.title}</strong>
1384
1384
  ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1385
1385
  ${t.enabled===!1&&t.disabledReason!==void 0?l`<small class="disabled-reason">${t.disabledReason}</small>`:null}
1386
1386
  </span>
1387
- ${t.shortcut!==void 0?l`<kbd>${wi(t.shortcut)}</kbd>`:null}
1387
+ ${t.shortcut!==void 0?l`<kbd>${ki(t.shortcut)}</kbd>`:null}
1388
1388
  ${t.group!==void 0&&t.group!==""?l`<small class="group">${t.group}</small>`:null}
1389
1389
  </button>
1390
1390
  `)}
1391
1391
  </div>
1392
1392
  </section>
1393
1393
  </div>
1394
- `}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(){return ky(this.actions,this.queryText)}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){e.enabled!==!1&&this.onRun?.(e)}};qe.styles=Sy;ut([d({attribute:!1})],qe.prototype,"actions",2);ut([d({attribute:!1})],qe.prototype,"onRun",2);ut([d({attribute:!1})],qe.prototype,"onCancel",2);ut([B("input")],qe.prototype,"input",2);ut([x()],qe.prototype,"queryText",2);ut([x()],qe.prototype,"selectedIndex",2);qe=ut([W("action-palette")],qe);function ky(e,t){const i=t.trim().toLowerCase();return e.filter(s=>s.enabled!==!1||s.disabledReason!==void 0).filter(s=>i===""?!0:[s.title,s.description??"",s.disabledReason??"",s.group??"",s.shortcut??""].join(" ").toLowerCase().includes(i))}var $y=Object.defineProperty,Py=Object.getOwnPropertyDescriptor,Pe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Py(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&$y(t,i,r),r};let le=class extends A{render(){const e=this.state;return e===void 0?null:l`
1394
+ `}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(){return Ay(this.actions,this.queryText)}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){e.enabled!==!1&&this.onRun?.(e)}};Ke.styles=Ry;mt([d({attribute:!1})],Ke.prototype,"actions",2);mt([d({attribute:!1})],Ke.prototype,"onRun",2);mt([d({attribute:!1})],Ke.prototype,"onCancel",2);mt([B("input")],Ke.prototype,"input",2);mt([w()],Ke.prototype,"queryText",2);mt([w()],Ke.prototype,"selectedIndex",2);Ke=mt([W("action-palette")],Ke);function Ay(e,t){const i=t.trim().toLowerCase();return e.filter(s=>s.enabled!==!1||s.disabledReason!==void 0).filter(s=>i===""?!0:[s.title,s.description??"",s.disabledReason??"",s.group??"",s.shortcut??""].join(" ").toLowerCase().includes(i))}var Ty=Object.defineProperty,My=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var r=s>1?void 0:s?My(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ty(t,i,r),r};let ce=class extends R{render(){const e=this.state;return e===void 0?null:l`
1395
1395
  <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
1396
1396
  <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1397
1397
  <header>
@@ -1414,11 +1414,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1414
1414
  <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>
1415
1415
  </div>
1416
1416
  `;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`
1417
- <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${ea(t.authType)}</small></button>
1417
+ <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${ra(t.authType)}</small></button>
1418
1418
  `)}</div>`}}renderProviderButton(e){return l`
1419
1419
  <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
1420
- <span>${e.name}${e.status.source!==void 0?l` <em>${Iy(e)}</em>`:null}</span>
1421
- <small>${e.id} · ${ea(e.authType)}</small>
1420
+ <span>${e.name}${e.status.source!==void 0?l` <em>${Dy(e)}</em>`:null}</span>
1421
+ <small>${e.id} · ${ra(e.authType)}</small>
1422
1422
  </button>
1423
1423
  `}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
1424
1424
  <div class="form">
@@ -1438,10 +1438,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1438
1438
  <div class="inline-options">${s.options.map(r=>l`<button @click=${()=>{this.onOAuthRespond?.(r.value)}}>${r.label}</button>`)}</div>
1439
1439
  `:null}
1440
1440
  ${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
1441
- ${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??Ry(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
1441
+ ${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??Wy(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
1442
1442
  ${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button></div>`:null}
1443
1443
  </div>
1444
- `}focusInputIfNeeded(){const e=Cy(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?.()}};le.styles=[sc,E`
1444
+ `}focusInputIfNeeded(){const e=Ey(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?.()}};ce.styles=[ac,D`
1445
1445
  .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
1446
1446
  .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
1447
1447
  .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
@@ -1456,7 +1456,60 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1456
1456
  .progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
1457
1457
  .inline-options { display: grid; gap: 8px; }
1458
1458
  em { color: var(--pi-success); font-style: normal; font-size: 12px; }
1459
- `];Pe([d({attribute:!1})],le.prototype,"state",2);Pe([d({attribute:!1})],le.prototype,"onChooseMethod",2);Pe([d({attribute:!1})],le.prototype,"onSelectProvider",2);Pe([d({attribute:!1})],le.prototype,"onApiKeyInput",2);Pe([d({attribute:!1})],le.prototype,"onSaveApiKey",2);Pe([d({attribute:!1})],le.prototype,"onLogoutProvider",2);Pe([d({attribute:!1})],le.prototype,"onOAuthInput",2);Pe([d({attribute:!1})],le.prototype,"onOAuthRespond",2);Pe([d({attribute:!1})],le.prototype,"onOAuthCancel",2);Pe([d({attribute:!1})],le.prototype,"onCancel",2);Pe([B("input")],le.prototype,"input",2);le=Pe([W("auth-dialog")],le);function ea(e){return e==="oauth"?"订阅":"API key"}function Cy(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 Iy(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 Ry(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var Ay=Object.defineProperty,Ty=Object.getOwnPropertyDescriptor,je=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ty(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ay(t,i,r),r};let xe=class extends A{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 N.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`
1459
+ `];Ce([d({attribute:!1})],ce.prototype,"state",2);Ce([d({attribute:!1})],ce.prototype,"onChooseMethod",2);Ce([d({attribute:!1})],ce.prototype,"onSelectProvider",2);Ce([d({attribute:!1})],ce.prototype,"onApiKeyInput",2);Ce([d({attribute:!1})],ce.prototype,"onSaveApiKey",2);Ce([d({attribute:!1})],ce.prototype,"onLogoutProvider",2);Ce([d({attribute:!1})],ce.prototype,"onOAuthInput",2);Ce([d({attribute:!1})],ce.prototype,"onOAuthRespond",2);Ce([d({attribute:!1})],ce.prototype,"onOAuthCancel",2);Ce([d({attribute:!1})],ce.prototype,"onCancel",2);Ce([B("input")],ce.prototype,"input",2);ce=Ce([W("auth-dialog")],ce);function ra(e){return e==="oauth"?"订阅":"API key"}function Ey(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 Dy(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 Wy(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var Oy=Object.defineProperty,_y=Object.getOwnPropertyDescriptor,ze=(e,t,i,s)=>{for(var r=s>1?void 0:s?_y(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Oy(t,i,r),r};let xe=class extends R{constructor(){super(...arguments),this.mode="login",this.loading=!1,this.error="",this.currentPassword="",this.password="",this.confirmPassword="",this.localError=""}render(){return l`
1460
+ <div class="backdrop">
1461
+ <section role="dialog" aria-modal="true" aria-label=${this.dialogTitle()} @keydown=${e=>{this.handleKeyDown(e)}}>
1462
+ <header>
1463
+ <div>
1464
+ <span class="eyebrow">普通模式</span>
1465
+ <h1>${this.dialogTitle()}</h1>
1466
+ </div>
1467
+ ${this.mode==="change"?l`<button class="close-button" title="关闭" aria-label="关闭" @click=${()=>this.onCancel?.()}>×</button>`:null}
1468
+ </header>
1469
+ <form @submit=${e=>{this.submit(e)}}>
1470
+ ${this.mode==="change"?l`
1471
+ <label>
1472
+ <span>当前密码</span>
1473
+ <input type="password" .value=${this.currentPassword} autocomplete="current-password" @input=${e=>{this.currentPassword=js(e),this.localError=""}}>
1474
+ </label>
1475
+ `:null}
1476
+ <label>
1477
+ <span>${this.mode==="login"?"密码":"新密码"}</span>
1478
+ <input type="password" .value=${this.password} autocomplete=${this.mode==="login"?"current-password":"new-password"} @input=${e=>{this.password=js(e),this.localError=""}}>
1479
+ </label>
1480
+ ${this.mode!=="login"?l`
1481
+ <label>
1482
+ <span>确认密码</span>
1483
+ <input type="password" .value=${this.confirmPassword} autocomplete="new-password" @input=${e=>{this.confirmPassword=js(e),this.localError=""}}>
1484
+ </label>
1485
+ `:null}
1486
+ ${this.message()===""?null:l`<p class="message">${this.message()}</p>`}
1487
+ <footer>
1488
+ ${this.mode==="change"?l`<button type="button" class="secondary" ?disabled=${this.loading} @click=${()=>this.onCancel?.()}>取消</button>`:null}
1489
+ <button class="primary" ?disabled=${this.loading}>${this.loading?"正在处理...":this.submitLabel()}</button>
1490
+ </footer>
1491
+ </form>
1492
+ </section>
1493
+ </div>
1494
+ `}dialogTitle(){return this.mode==="setup"?"设置进入密码":this.mode==="change"?"修改进入密码":"输入进入密码"}submitLabel(){return this.mode==="setup"?"设置并进入":this.mode==="change"?"保存密码":"进入"}message(){return this.localError||this.error}async submit(e){e.preventDefault();const t={currentPassword:this.currentPassword,password:this.password,confirmPassword:this.confirmPassword},i=Ly(this.mode,t);if(i!==void 0){this.localError=i;return}this.localError="",await this.onSubmit?.(t)}handleKeyDown(e){e.key!=="Escape"||this.mode!=="change"||(e.preventDefault(),e.stopPropagation(),this.onCancel?.())}};xe.styles=D`
1495
+ :host { position: fixed; inset: 0; z-index: 40; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1496
+ .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-bg); }
1497
+ section { width: min(420px, 100%); border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-surface); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
1498
+ header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 16px; border-bottom: 1px solid var(--pi-border); }
1499
+ .eyebrow { display: block; color: var(--pi-muted); font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
1500
+ h1 { margin: 0; font-size: 20px; line-height: 1.2; }
1501
+ form { display: grid; gap: 14px; padding: 16px; }
1502
+ label { display: grid; gap: 6px; }
1503
+ label span { color: var(--pi-muted); font-size: 12px; font-weight: 700; }
1504
+ input { 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: 10px; outline: none; font: var(--pi-control-font-size, 16px) var(--pi-control-font-family, system-ui, sans-serif); }
1505
+ input:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
1506
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 8px 10px; font: inherit; cursor: pointer; }
1507
+ button:disabled { opacity: .6; cursor: default; }
1508
+ .primary { border-color: var(--pi-accent); background: var(--pi-accent); color: var(--pi-accent-contrast); }
1509
+ .close-button { width: 34px; height: 34px; display: grid; place-items: center; border: 0; background: transparent; color: var(--pi-muted); padding: 0; font-size: 24px; }
1510
+ .message { margin: 0; border: 1px solid var(--pi-danger-border); border-radius: 8px; background: var(--pi-danger-surface); color: var(--pi-danger); padding: 10px; }
1511
+ footer { display: flex; justify-content: flex-end; gap: 8px; }
1512
+ `;ze([d()],xe.prototype,"mode",2);ze([d({type:Boolean})],xe.prototype,"loading",2);ze([d()],xe.prototype,"error",2);ze([d({attribute:!1})],xe.prototype,"onSubmit",2);ze([d({attribute:!1})],xe.prototype,"onCancel",2);ze([w()],xe.prototype,"currentPassword",2);ze([w()],xe.prototype,"password",2);ze([w()],xe.prototype,"confirmPassword",2);ze([w()],xe.prototype,"localError",2);xe=ze([W("normal-auth-dialog")],xe);function Ly(e,t){if(e==="change"&&(t.currentPassword??"")==="")return"请输入当前密码。";if(t.password==="")return"请输入密码。";if(e!=="login"&&t.password!==(t.confirmPassword??""))return"两次输入的密码不一致。"}function js(e){return e.target instanceof HTMLInputElement?e.target.value:""}var jy=Object.defineProperty,Fy=Object.getOwnPropertyDescriptor,Ue=(e,t,i,s)=>{for(var r=s>1?void 0:s?Fy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&jy(t,i,r),r};let Se=class extends R{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 N.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`
1460
1513
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1461
1514
  <section @click=${e=>{e.stopPropagation()}}>
1462
1515
  <header>
@@ -1488,7 +1541,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1488
1541
  </footer>
1489
1542
  </section>
1490
1543
  </div>
1491
- `}};xe.styles=E`
1544
+ `}};Se.styles=D`
1492
1545
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1493
1546
  .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1494
1547
  section { width: min(720px, calc(100vw - 40px)); max-height: min(700px, 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; }
@@ -1506,7 +1559,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1506
1559
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1507
1560
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1508
1561
  button:disabled { opacity: .5; cursor: not-allowed; }
1509
- `;je([d({attribute:!1})],xe.prototype,"onSubmit",2);je([d({attribute:!1})],xe.prototype,"onCancel",2);je([d()],xe.prototype,"machineId",2);je([x()],xe.prototype,"path",2);je([x()],xe.prototype,"createMissing",2);je([x()],xe.prototype,"suggestions",2);je([x()],xe.prototype,"selected",2);je([x()],xe.prototype,"loading",2);je([B("input")],xe.prototype,"pathInput",2);xe=je([W("project-dialog")],xe);var My=Object.defineProperty,Ey=Object.getOwnPropertyDescriptor,Fe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ey(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&My(t,i,r),r};let Se=class extends A{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=Dy(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"&&Ws(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===""||Ws(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?Ws(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1562
+ `;Ue([d({attribute:!1})],Se.prototype,"onSubmit",2);Ue([d({attribute:!1})],Se.prototype,"onCancel",2);Ue([d()],Se.prototype,"machineId",2);Ue([w()],Se.prototype,"path",2);Ue([w()],Se.prototype,"createMissing",2);Ue([w()],Se.prototype,"suggestions",2);Ue([w()],Se.prototype,"selected",2);Ue([w()],Se.prototype,"loading",2);Ue([B("input")],Se.prototype,"pathInput",2);Se=Ue([W("project-dialog")],Se);var zy=Object.defineProperty,Uy=Object.getOwnPropertyDescriptor,Be=(e,t,i,s)=>{for(var r=s>1?void 0:s?Uy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&zy(t,i,r),r};let ke=class extends R{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=By(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"&&Fs(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===""||Fs(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?Fs(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1510
1563
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1511
1564
  <section @click=${s=>{s.stopPropagation()}}>
1512
1565
  <form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
@@ -1541,7 +1594,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1541
1594
  </form>
1542
1595
  </section>
1543
1596
  </div>
1544
- `}};Se.styles=E`
1597
+ `}};ke.styles=D`
1545
1598
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1546
1599
  .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1547
1600
  section { width: min(560px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -1561,10 +1614,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1561
1614
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1562
1615
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1563
1616
  button:disabled { opacity: .5; cursor: not-allowed; }
1564
- `;Fe([d({attribute:!1})],Se.prototype,"onSubmit",2);Fe([d({attribute:!1})],Se.prototype,"onCancel",2);Fe([d()],Se.prototype,"error",2);Fe([x()],Se.prototype,"url",2);Fe([x()],Se.prototype,"name",2);Fe([x()],Se.prototype,"token",2);Fe([x()],Se.prototype,"submitting",2);Fe([B("input[name='baseUrl']")],Se.prototype,"urlInput",2);Fe([B("input[name='name']")],Se.prototype,"nameInput",2);Se=Fe([W("machine-dialog")],Se);function Dy(e){const t=e.trim();if(t==="")return"";const i=ta(t)??ta(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):Wy(t)}function Ws(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 ta(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function Wy(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 Oy(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:"",allowedPathsText:""}}function _y(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(`
1617
+ `;Be([d({attribute:!1})],ke.prototype,"onSubmit",2);Be([d({attribute:!1})],ke.prototype,"onCancel",2);Be([d()],ke.prototype,"error",2);Be([w()],ke.prototype,"url",2);Be([w()],ke.prototype,"name",2);Be([w()],ke.prototype,"token",2);Be([w()],ke.prototype,"submitting",2);Be([B("input[name='baseUrl']")],ke.prototype,"urlInput",2);Be([B("input[name='name']")],ke.prototype,"nameInput",2);ke=Be([W("machine-dialog")],ke);function By(e){const t=e.trim();if(t==="")return"";const i=oa(t)??oa(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):Ny(t)}function Fs(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 oa(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function Ny(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 Hy(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:"",allowedPathsText:""}}function qy(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(`
1565
1618
  `):"",allowedPathsText:e.pathAccess?.allowedPaths?.join(`
1566
- `)??""}}function Ly(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins},...t.uploads===void 0?{}:{uploads:t.uploads},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes},...t.spawnSessions===void 0?{}:{spawnSessions:t.spawnSessions},...t.subsessions===void 0?{}:{subsessions:t.subsessions}},s=e.host.trim(),r=e.port.trim();if(s!==""&&(i.host=s),r!==""){const n=Number(r);if(!Number.isInteger(n)||n<1||n>65535)throw new Error("端口必须是 1 到 65535 之间的整数。");i.port=n}i.allowedHosts=e.allowedHostsMode==="all"?!0:jy(e.allowedHostsText);const o=Fy(e.allowedPathsText);return o.length>0&&(i.pathAccess={allowedPaths:o}),i}function jy(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}function Fy(e){const t=e.split(`
1567
- `).map(s=>s.trim()).filter(s=>s!==""),i=t.find(s=>!Uy(s));if(i!==void 0)throw new Error(`Allowed external paths must be absolute paths or start with ~: ${i}`);return t}function Uy(e){return e==="~"||e.startsWith("~/")||e.startsWith("~\\")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:[\\/]/u.test(e)}function ds(e,t){return e!==""?l`<div class="message error-message">${e}</div>`:t!==""?l`<div class="message success-message">${t}</div>`:null}const ps=E`
1619
+ `)??""}}function Ky(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins},...t.normalAuth===void 0?{}:{normalAuth:t.normalAuth},...t.uploads===void 0?{}:{uploads:t.uploads},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes},...t.spawnSessions===void 0?{}:{spawnSessions:t.spawnSessions},...t.subsessions===void 0?{}:{subsessions:t.subsessions}},s=e.host.trim(),r=e.port.trim();if(s!==""&&(i.host=s),r!==""){const n=Number(r);if(!Number.isInteger(n)||n<1||n>65535)throw new Error("端口必须是 1 到 65535 之间的整数。");i.port=n}i.allowedHosts=e.allowedHostsMode==="all"?!0:Vy(e.allowedHostsText);const o=Gy(e.allowedPathsText);return o.length>0&&(i.pathAccess={allowedPaths:o}),i}function Vy(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}function Gy(e){const t=e.split(`
1620
+ `).map(s=>s.trim()).filter(s=>s!==""),i=t.find(s=>!Jy(s));if(i!==void 0)throw new Error(`Allowed external paths must be absolute paths or start with ~: ${i}`);return t}function Jy(e){return e==="~"||e.startsWith("~/")||e.startsWith("~\\")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:[\\/]/u.test(e)}function fs(e,t){return e!==""?l`<div class="message error-message">${e}</div>`:t!==""?l`<div class="message success-message">${t}</div>`:null}const gs=D`
1568
1621
  :host { display: block; }
1569
1622
  .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1570
1623
  .section-heading > div { display: grid; gap: 6px; min-width: 0; }
@@ -1600,7 +1653,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1600
1653
  .section-heading .secondary { justify-self: start; }
1601
1654
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1602
1655
  }
1603
- `;var zy=Object.defineProperty,By=Object.getOwnPropertyDescriptor,Ue=(e,t,i,s)=>{for(var r=s>1?void 0:s?By(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&zy(t,i,r),r};let ke=class extends A{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=Oy(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=_y(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
1656
+ `;var Qy=Object.defineProperty,Zy=Object.getOwnPropertyDescriptor,Ne=(e,t,i,s)=>{for(var r=s>1?void 0:s?Zy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Qy(t,i,r),r};let $e=class extends R{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=Hy(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=qy(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
1604
1657
  <div class="section-heading">
1605
1658
  <div>
1606
1659
  <h2>通用配置</h2>
@@ -1621,7 +1674,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1621
1674
  <span>Host</span>
1622
1675
  ${this.renderOverrideBadge("host")}
1623
1676
  </span>
1624
- <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:ia(t)})}}>
1677
+ <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:na(t)})}}>
1625
1678
  <small>Web 服务器应绑定的地址。留空则使用 PI WEB 默认值。</small>
1626
1679
  </label>
1627
1680
 
@@ -1630,7 +1683,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1630
1683
  <span>Port</span>
1631
1684
  ${this.renderOverrideBadge("port")}
1632
1685
  </span>
1633
- <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:ia(t)})}}>
1686
+ <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:na(t)})}}>
1634
1687
  <small>TCP 端口,范围 1 到 65535。留空则使用 PI WEB 默认值。</small>
1635
1688
  </label>
1636
1689
 
@@ -1639,11 +1692,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1639
1692
  <span>允许的 hosts</span>
1640
1693
  ${this.renderOverrideBadge("allowedHosts")}
1641
1694
  </span>
1642
- <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:Hy(t)==="all"?"all":"list"})}}>
1695
+ <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:e0(t)==="all"?"all":"list"})}}>
1643
1696
  <option value="list">仅允许列出的 hosts</option>
1644
1697
  <option value="all">允许所有 host</option>
1645
1698
  </select>
1646
- <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:sa(t)})}}></textarea>
1699
+ <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:aa(t)})}}></textarea>
1647
1700
  <small>每行输入一个 host,或选择“允许所有 host”写入 <code>true</code>。</small>
1648
1701
  </div>
1649
1702
 
@@ -1651,7 +1704,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1651
1704
  <span class="field-heading">
1652
1705
  <span>External filesystem roots</span>
1653
1706
  </span>
1654
- <textarea .value=${this.draft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${t=>{this.updateDraft({allowedPathsText:sa(t)})}}></textarea>
1707
+ <textarea .value=${this.draft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${t=>{this.updateDraft({allowedPathsText:aa(t)})}}></textarea>
1655
1708
  <small>Global allowlist for absolute <code>@</code> completions and file explorer reads outside a workspace. Enter one absolute path, Windows absolute path, or <code>~</code>-prefixed path per line. Leave empty to deny external paths by default.</small>
1656
1709
  </label>
1657
1710
 
@@ -1662,24 +1715,24 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1662
1715
  </footer>
1663
1716
  </form>
1664
1717
  `}
1665
- `}renderMessages(){const e=this.localError||this.error;return ds(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`
1718
+ `}renderMessages(){const e=this.localError||this.error;return fs(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`
1666
1719
  <section class="effective-card" aria-label="最终生效配置摘要">
1667
1720
  <h3>环境变量覆盖后的生效配置</h3>
1668
1721
  <dl>
1669
1722
  <div><dt>Host</dt><dd>${e.host??l`<span class="muted">默认 127.0.0.1</span>`}</dd></div>
1670
1723
  <div><dt>端口</dt><dd>${e.port??l`<span class="muted">默认 8504</span>`}</dd></div>
1671
- <div><dt>允许的 hosts</dt><dd>${Ny(e.allowedHosts)}</dd></div>
1672
- <div><dt>外部根目录</dt><dd>${qy(e.pathAccess?.allowedPaths)}</dd></div>
1724
+ <div><dt>允许的 hosts</dt><dd>${Xy(e.allowedHosts)}</dd></div>
1725
+ <div><dt>外部根目录</dt><dd>${Yy(e.pathAccess?.allowedPaths)}</dd></div>
1673
1726
  </dl>
1674
1727
  </section>
1675
- `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(Ly(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=Ky(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};ke.styles=[ps,E`
1728
+ `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(Ky(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=t0(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};$e.styles=[gs,D`
1676
1729
  .config-form { display: grid; gap: 14px; }
1677
1730
  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; font: var(--pi-control-font-size, 16px) var(--pi-control-font-family, system-ui, sans-serif); }
1678
1731
  input:focus, select:focus, textarea:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
1679
1732
  textarea { resize: vertical; min-height: 94px; font-family: var(--pi-control-monospace-font-family, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); }
1680
1733
  textarea:disabled { opacity: .55; }
1681
1734
  .form-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 2px; }
1682
- `];Ue([d({attribute:!1})],ke.prototype,"configResponse",2);Ue([d({type:Boolean})],ke.prototype,"loading",2);Ue([d({type:Boolean})],ke.prototype,"saving",2);Ue([d()],ke.prototype,"error",2);Ue([d()],ke.prototype,"savedMessage",2);Ue([d({attribute:!1})],ke.prototype,"onReload",2);Ue([d({attribute:!1})],ke.prototype,"onSave",2);Ue([x()],ke.prototype,"draft",2);Ue([x()],ke.prototype,"localError",2);ke=Ue([W("settings-general-panel")],ke);function Ny(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?l`<span class="muted">未列出</span>`:e.join(", "):l`<span class="muted">未设置</span>`}function qy(e){return e===void 0||e.length===0?l`<span class="muted">已禁止外部路径</span>`:e.join(", ")}function ia(e){return e.target instanceof HTMLInputElement?e.target.value:""}function Hy(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function sa(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function Ky(e){return e instanceof Error?e.message:String(e)}var Vy=Object.defineProperty,Gy=Object.getOwnPropertyDescriptor,tt=(e,t,i,s)=>{for(var r=s>1?void 0:s?Gy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Vy(t,i,r),r};let Le=class extends A{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,r=e?.effectiveConfig.subsessions===!0&&i;return l`
1735
+ `];Ne([d({attribute:!1})],$e.prototype,"configResponse",2);Ne([d({type:Boolean})],$e.prototype,"loading",2);Ne([d({type:Boolean})],$e.prototype,"saving",2);Ne([d()],$e.prototype,"error",2);Ne([d()],$e.prototype,"savedMessage",2);Ne([d({attribute:!1})],$e.prototype,"onReload",2);Ne([d({attribute:!1})],$e.prototype,"onSave",2);Ne([w()],$e.prototype,"draft",2);Ne([w()],$e.prototype,"localError",2);$e=Ne([W("settings-general-panel")],$e);function Xy(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?l`<span class="muted">未列出</span>`:e.join(", "):l`<span class="muted">未设置</span>`}function Yy(e){return e===void 0||e.length===0?l`<span class="muted">已禁止外部路径</span>`:e.join(", ")}function na(e){return e.target instanceof HTMLInputElement?e.target.value:""}function e0(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function aa(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function t0(e){return e instanceof Error?e.message:String(e)}var i0=Object.defineProperty,s0=Object.getOwnPropertyDescriptor,st=(e,t,i,s)=>{for(var r=s>1?void 0:s?s0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&i0(t,i,r),r};let Fe=class extends R{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,r=e?.effectiveConfig.subsessions===!0&&i;return l`
1683
1736
  <div class="section-heading">
1684
1737
  <div>
1685
1738
  <h2>会话守护进程</h2>
@@ -1735,7 +1788,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1735
1788
  </dl>
1736
1789
  </section>
1737
1790
  `}
1738
- `}renderMessages(){return ds(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})}};Le.styles=[ps,E`
1791
+ `}renderMessages(){return fs(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})}};Fe.styles=[gs,D`
1739
1792
  .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; }
1740
1793
  .field { margin-bottom: 14px; }
1741
1794
  .field small { line-height: 1.45; }
@@ -1743,7 +1796,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1743
1796
  .toggle input { width: 16px; height: 16px; }
1744
1797
  .toggle input:disabled { cursor: not-allowed; }
1745
1798
  .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; }
1746
- `];tt([d({attribute:!1})],Le.prototype,"configResponse",2);tt([d({type:Boolean})],Le.prototype,"loading",2);tt([d({type:Boolean})],Le.prototype,"saving",2);tt([d()],Le.prototype,"error",2);tt([d()],Le.prototype,"savedMessage",2);tt([d({attribute:!1})],Le.prototype,"onReload",2);tt([d({attribute:!1})],Le.prototype,"onSave",2);Le=tt([W("settings-sessiond-panel")],Le);var Jy=Object.defineProperty,Qy=Object.getOwnPropertyDescriptor,Ge=(e,t,i,s)=>{for(var r=s>1?void 0:s?Qy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Jy(t,i,r),r};let Ee=class extends A{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
1799
+ `];st([d({attribute:!1})],Fe.prototype,"configResponse",2);st([d({type:Boolean})],Fe.prototype,"loading",2);st([d({type:Boolean})],Fe.prototype,"saving",2);st([d()],Fe.prototype,"error",2);st([d()],Fe.prototype,"savedMessage",2);st([d({attribute:!1})],Fe.prototype,"onReload",2);st([d({attribute:!1})],Fe.prototype,"onSave",2);Fe=st([W("settings-sessiond-panel")],Fe);var r0=Object.defineProperty,o0=Object.getOwnPropertyDescriptor,Qe=(e,t,i,s)=>{for(var r=s>1?void 0:s?o0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&r0(t,i,r),r};let De=class extends R{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
1747
1800
  <div class="section-heading">
1748
1801
  <div>
1749
1802
  <h2>插件</h2>
@@ -1758,7 +1811,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1758
1811
  ${e.map(t=>this.renderPlugin(t))}
1759
1812
  </div>
1760
1813
  `}
1761
- `}renderMessages(){return ds(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`
1814
+ `}renderMessages(){return fs(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`
1762
1815
  <article class=${`plugin-card${e.enabled?"":" disabled"}`}>
1763
1816
  <div class="plugin-main">
1764
1817
  <strong>${e.id}</strong>
@@ -1770,7 +1823,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1770
1823
  <span>${e.enabled?"已启用":"已禁用"}</span>
1771
1824
  </label>
1772
1825
  </article>
1773
- `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};Ee.styles=[ps,E`
1826
+ `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};De.styles=[gs,D`
1774
1827
  .plugin-note, .plugin-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1775
1828
  .plugin-note { color: var(--pi-muted); }
1776
1829
  .plugin-note { margin-bottom: 14px; }
@@ -1787,7 +1840,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1787
1840
  .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
1788
1841
  .toggle { justify-self: start; }
1789
1842
  }
1790
- `];Ge([d({attribute:!1})],Ee.prototype,"pluginsResponse",2);Ge([d({attribute:!1})],Ee.prototype,"configResponse",2);Ge([d({type:Boolean})],Ee.prototype,"loading",2);Ge([d({type:Boolean})],Ee.prototype,"saving",2);Ge([d()],Ee.prototype,"error",2);Ge([d()],Ee.prototype,"savedMessage",2);Ge([d({attribute:!1})],Ee.prototype,"onReload",2);Ge([d({attribute:!1})],Ee.prototype,"onTogglePlugin",2);Ee=Ge([W("settings-plugins-panel")],Ee);var Zy=Object.defineProperty,Xy=Object.getOwnPropertyDescriptor,ge=(e,t,i,s)=>{for(var r=s>1?void 0:s?Xy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Zy(t,i,r),r};const ra={capture:!0},Yy=[{value:"auto",label:"Auto/default",description:"Desktop-like Enter sends; mobile, coarse pointer, or narrow screens insert a new line."},{value:"send",label:"Enter sends message",description:"Enter sends the chat message; Shift+Enter adds a new line when supported."},{value:"newline",label:"Enter inserts new line",description:"Enter adds a line break; Shift+Enter sends the chat message when supported."}];let ie=class extends A{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.promptEnterPreference=ls(),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=ll(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&&!Vt(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=s0(this.actions),t=this.shortcutResolutions();return l`
1843
+ `];Qe([d({attribute:!1})],De.prototype,"pluginsResponse",2);Qe([d({attribute:!1})],De.prototype,"configResponse",2);Qe([d({type:Boolean})],De.prototype,"loading",2);Qe([d({type:Boolean})],De.prototype,"saving",2);Qe([d()],De.prototype,"error",2);Qe([d()],De.prototype,"savedMessage",2);Qe([d({attribute:!1})],De.prototype,"onReload",2);Qe([d({attribute:!1})],De.prototype,"onTogglePlugin",2);De=Qe([W("settings-plugins-panel")],De);var n0=Object.defineProperty,a0=Object.getOwnPropertyDescriptor,me=(e,t,i,s)=>{for(var r=s>1?void 0:s?a0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&n0(t,i,r),r};const la={capture:!0},l0=[{value:"auto",label:"Auto/default",description:"Desktop-like Enter sends; mobile, coarse pointer, or narrow screens insert a new line."},{value:"send",label:"Enter sends message",description:"Enter sends the chat message; Shift+Enter adds a new line when supported."},{value:"newline",label:"Enter inserts new line",description:"Enter adds a line break; Shift+Enter sends the chat message when supported."}];let re=class extends R{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.promptEnterPreference=hs(),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=hl(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&&!Xt(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=h0(this.actions),t=this.shortcutResolutions();return l`
1791
1844
  <div class="section-heading">
1792
1845
  <div>
1793
1846
  <h2>键盘快捷键</h2>
@@ -1812,7 +1865,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1812
1865
  </section>
1813
1866
  `)}
1814
1867
  `}
1815
- `}renderMessages(){const e=this.localError||this.error;return ds(e,this.savedMessage)}renderPromptEnterPreferenceCard(){return l`
1868
+ `}renderMessages(){const e=this.localError||this.error;return fs(e,this.savedMessage)}renderPromptEnterPreferenceCard(){return l`
1816
1869
  <section class="prompt-enter-card" aria-labelledby="prompt-enter-preference-title">
1817
1870
  <div class="prompt-enter-copy">
1818
1871
  <span class="card-eyebrow">Chat composer</span>
@@ -1820,7 +1873,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1820
1873
  <p>Choose what Enter does in this browser. Shift+Enter does the opposite when supported; automatic touch-keyboard capitalization is ignored to avoid accidental sends.</p>
1821
1874
  </div>
1822
1875
  <div class="prompt-enter-options" role="radiogroup" aria-label="Enter and Shift Enter behavior in the chat composer">
1823
- ${Yy.map(e=>l`
1876
+ ${l0.map(e=>l`
1824
1877
  <label class="prompt-enter-option">
1825
1878
  <input
1826
1879
  type="radio"
@@ -1837,19 +1890,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1837
1890
  `)}
1838
1891
  </div>
1839
1892
  </section>
1840
- `}updatePromptEnterPreference(e){this.promptEnterPreference=e,zw(e)}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=qi(e.id,i),r=a0(e,i),o=this.shortcutInputText(e),n=o.trim()===""?void 0:xs(o),a=n?.ok===!0?n.shortcut:n0(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&o.trim()!==""?"custom":r,h=this.recordingHint(e.id),g=i0(t);return l`
1841
- <article class=${e0(t)}>
1893
+ `}updatePromptEnterPreference(e){this.promptEnterPreference=e,Vw(e)}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=Gi(e.id,i),r=m0(e,i),o=this.shortcutInputText(e),n=o.trim()===""?void 0:Ps(o),a=n?.ok===!0?n.shortcut:g0(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&o.trim()!==""?"custom":r,h=this.recordingHint(e.id),g=p0(t);return l`
1894
+ <article class=${c0(t)}>
1842
1895
  <div class="shortcut-main">
1843
1896
  <strong>${e.title}</strong>
1844
1897
  ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1845
1898
  <small class="shortcut-id">${e.id}</small>
1846
- <small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${wi(e.shortcut)}</kbd>`:"No default shortcut"}</small>
1899
+ <small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${ki(e.shortcut)}</kbd>`:"No default shortcut"}</small>
1847
1900
  </div>
1848
1901
  <div class="shortcut-editor">
1849
1902
  <div class="shortcut-status">
1850
- ${a!==void 0&&a!==""?l`<kbd>${wi(a)}</kbd>`:l`<span class="unassigned">${r==="disabled"?"已禁用":"未分配"}</span>`}
1851
- <small class=${u}>${l0(u)}${p?" · 未保存":""}</small>
1852
- ${g===void 0?null:l`<small class=${t0(t)}>${g}</small>`}
1903
+ ${a!==void 0&&a!==""?l`<kbd>${ki(a)}</kbd>`:l`<span class="unassigned">${r==="disabled"?"已禁用":"未分配"}</span>`}
1904
+ <small class=${u}>${v0(u)}${p?" · 未保存":""}</small>
1905
+ ${g===void 0?null:l`<small class=${d0(t)}>${g}</small>`}
1853
1906
  </div>
1854
1907
  <label class="shortcut-input-label">
1855
1908
  <span>快捷键</span>
@@ -1862,7 +1915,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1862
1915
  autocapitalize="off"
1863
1916
  spellcheck="false"
1864
1917
  ?disabled=${this.saving}
1865
- @input=${w=>{this.updateDraft(e.id,c0(w))}}
1918
+ @input=${y=>{this.updateDraft(e.id,b0(y))}}
1866
1919
  >
1867
1920
  </label>
1868
1921
  ${h!==""?l`<small class="recording-hint">${h}</small>`:null}
@@ -1874,7 +1927,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1874
1927
  </div>
1875
1928
  </div>
1876
1929
  </article>
1877
- `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=qi(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: ${wi(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=xs(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??{},r=t===void 0?o0(s,e):{...s,[e]:t};Object.keys(r).length===0?delete i.shortcuts:i.shortcuts=r,await this.onSave?.(i)}shortcutResolutions(){return new Map(Wr(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 r=xs(s);r.ok&&(e[t]=r.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()},nl)}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,ra),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,ra),this.recordingListenerActive=!1)}};ie.styles=[ps,E`
1930
+ `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=Gi(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: ${ki(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=Ps(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??{},r=t===void 0?f0(s,e):{...s,[e]:t};Object.keys(r).length===0?delete i.shortcuts:i.shortcuts=r,await this.onSave?.(i)}shortcutResolutions(){return new Map(jr(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 r=Ps(s);r.ok&&(e[t]=r.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()},dl)}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,la),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,la),this.recordingListenerActive=!1)}};re.styles=[gs,D`
1878
1931
  .prompt-enter-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; display: grid; grid-template-columns: minmax(0, .85fr) minmax(260px, 1fr); gap: 12px; align-items: start; margin-bottom: 14px; }
1879
1932
  .prompt-enter-copy { display: grid; gap: 5px; min-width: 0; }
1880
1933
  .prompt-enter-copy p, .prompt-enter-option small { font-size: 12px; }
@@ -1917,7 +1970,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1917
1970
  .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
1918
1971
  .shortcut-status, .shortcut-actions { justify-content: flex-start; }
1919
1972
  }
1920
- `];ge([d({attribute:!1})],ie.prototype,"actions",2);ge([d({attribute:!1})],ie.prototype,"configResponse",2);ge([d({type:Boolean})],ie.prototype,"loading",2);ge([d({type:Boolean})],ie.prototype,"saving",2);ge([d()],ie.prototype,"error",2);ge([d()],ie.prototype,"savedMessage",2);ge([d({attribute:!1})],ie.prototype,"onReload",2);ge([d({attribute:!1})],ie.prototype,"onSave",2);ge([x()],ie.prototype,"drafts",2);ge([x()],ie.prototype,"localError",2);ge([x()],ie.prototype,"promptEnterPreference",2);ge([x()],ie.prototype,"recording",2);ie=ge([W("settings-shortcuts-panel")],ie);function e0(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function t0(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function i0(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(r=>r.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function s0(e){const t=new Map;for(const i of[...e].sort(r0)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function r0(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function qi(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function o0(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function n0(e,t){const i=qi(e.id,t);if(i!==null)return i??e.shortcut}function a0(e,t){const i=qi(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function l0(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}function c0(e){return e.target instanceof HTMLInputElement?e.target.value:""}var d0=Object.defineProperty,p0=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var r=s>1?void 0:s?p0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&d0(t,i,r),r};let ce=class extends A{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`
1973
+ `];me([d({attribute:!1})],re.prototype,"actions",2);me([d({attribute:!1})],re.prototype,"configResponse",2);me([d({type:Boolean})],re.prototype,"loading",2);me([d({type:Boolean})],re.prototype,"saving",2);me([d()],re.prototype,"error",2);me([d()],re.prototype,"savedMessage",2);me([d({attribute:!1})],re.prototype,"onReload",2);me([d({attribute:!1})],re.prototype,"onSave",2);me([w()],re.prototype,"drafts",2);me([w()],re.prototype,"localError",2);me([w()],re.prototype,"promptEnterPreference",2);me([w()],re.prototype,"recording",2);re=me([W("settings-shortcuts-panel")],re);function c0(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function d0(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function p0(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(r=>r.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function h0(e){const t=new Map;for(const i of[...e].sort(u0)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function u0(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function Gi(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function f0(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function g0(e,t){const i=Gi(e.id,t);if(i!==null)return i??e.shortcut}function m0(e,t){const i=Gi(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function v0(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}function b0(e){return e.target instanceof HTMLInputElement?e.target.value:""}var w0=Object.defineProperty,y0=Object.getOwnPropertyDescriptor,Ie=(e,t,i,s)=>{for(var r=s>1?void 0:s?y0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&w0(t,i,r),r};let de=class extends R{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`
1921
1974
  <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
1922
1975
  <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB 设置" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
1923
1976
  <header class="settings-header">
@@ -1987,7 +2040,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1987
2040
  <strong>${t}</strong>
1988
2041
  <small>${i}</small>
1989
2042
  </button>
1990
- `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([Ii.config(),Ks.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`加载设置失败:${Os(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},r=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...r,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await Ii.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(t){this.error=`保存配置失败:${Os(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await Ks.plugins()}catch(e){this.error=`刷新插件失败:${Os(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?.())}};ce.styles=E`
2043
+ `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([Mi.config(),Qs.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`加载设置失败:${zs(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},r=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...r,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await Mi.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(t){this.error=`保存配置失败:${zs(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await Qs.plugins()}catch(e){this.error=`刷新插件失败:${zs(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?.())}};de.styles=D`
1991
2044
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1992
2045
  .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; }
1993
2046
  .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; }
@@ -2014,7 +2067,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2014
2067
  .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
2015
2068
  .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
2016
2069
  }
2017
- `;Ce([d({attribute:!1})],ce.prototype,"section",2);Ce([d({attribute:!1})],ce.prototype,"actions",2);Ce([d({attribute:!1})],ce.prototype,"onNavigate",2);Ce([d({attribute:!1})],ce.prototype,"onClose",2);Ce([d({attribute:!1})],ce.prototype,"onConfigSaved",2);Ce([x()],ce.prototype,"configResponse",2);Ce([x()],ce.prototype,"pluginsResponse",2);Ce([x()],ce.prototype,"loading",2);Ce([x()],ce.prototype,"saving",2);Ce([x()],ce.prototype,"error",2);Ce([x()],ce.prototype,"savedMessage",2);ce=Ce([W("settings-dialog")],ce);function Os(e){return e instanceof Error?e.message:String(e)}var h0=Object.defineProperty,u0=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var r=s>1?void 0:s?u0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&h0(t,i,r),r};const f0=E`
2070
+ `;Ie([d({attribute:!1})],de.prototype,"section",2);Ie([d({attribute:!1})],de.prototype,"actions",2);Ie([d({attribute:!1})],de.prototype,"onNavigate",2);Ie([d({attribute:!1})],de.prototype,"onClose",2);Ie([d({attribute:!1})],de.prototype,"onConfigSaved",2);Ie([w()],de.prototype,"configResponse",2);Ie([w()],de.prototype,"pluginsResponse",2);Ie([w()],de.prototype,"loading",2);Ie([w()],de.prototype,"saving",2);Ie([w()],de.prototype,"error",2);Ie([w()],de.prototype,"savedMessage",2);de=Ie([W("settings-dialog")],de);function zs(e){return e instanceof Error?e.message:String(e)}var x0=Object.defineProperty,S0=Object.getOwnPropertyDescriptor,We=(e,t,i,s)=>{for(var r=s>1?void 0:s?S0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&x0(t,i,r),r};const k0=D`
2018
2071
  :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; }
2019
2072
  header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
2020
2073
  .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
@@ -2073,7 +2126,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2073
2126
  .image-preview img { display: block; max-width: 100%; max-height: 100%; object-fit: contain; border: 1px solid var(--pi-border-muted); border-radius: 8px; background-color: var(--pi-surface); background-image: linear-gradient(45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(-45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%), linear-gradient(-45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%); background-position: 0 0, 0 8px, 8px -8px, -8px 0; background-size: 16px 16px; box-shadow: 0 8px 24px var(--pi-shadow-soft); }
2074
2127
  pre { margin: 0; padding: 10px; overflow: auto; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; }
2075
2128
  p { margin: 10px; }
2076
- `;let ue=class extends A{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>{},this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:"选择工作区",body:"选择工作区来查看文件、Git 或终端。"});const t=this.panelContext;if(t===void 0)return this.renderEmptyState({title:"工作区工具不可用",body:"请尝试重新选择工作区。"});const i=this.panels,s=i.find(r=>r.id===this.tool)??i[0];return l`
2129
+ `;let fe=class extends R{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>{},this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:"选择工作区",body:"选择工作区来查看文件、Git 或终端。"});const t=this.panelContext;if(t===void 0)return this.renderEmptyState({title:"工作区工具不可用",body:"请尝试重新选择工作区。"});const i=this.panels,s=i.find(r=>r.id===this.tool)??i[0];return l`
2077
2130
  ${this.hideToolTabs?null:l`
2078
2131
  <header>
2079
2132
  <div class=${this.workspaceHeaderFrameClass()}>
@@ -2103,32 +2156,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2103
2156
  <h2>${e.title}</h2>
2104
2157
  ${e.body===void 0?null:l`<p>${e.body}</p>`}
2105
2158
  </section>
2106
- `}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}};ue.styles=f0;De([d({attribute:!1})],ue.prototype,"workspace",2);De([d({attribute:!1})],ue.prototype,"panelContext",2);De([d({attribute:!1})],ue.prototype,"emptyState",2);De([d()],ue.prototype,"tool",2);De([d({attribute:!1})],ue.prototype,"panels",2);De([d({type:Boolean})],ue.prototype,"hideToolTabs",2);De([d({attribute:!1})],ue.prototype,"onSelectTool",2);De([B(".workspace-header-strip")],ue.prototype,"workspaceHeaderStrip",2);De([x()],ue.prototype,"workspaceHeaderCanScrollLeft",2);De([x()],ue.prototype,"workspaceHeaderCanScrollRight",2);ue=De([W("workspace-panel")],ue);var g0=Object.defineProperty,m0=Object.getOwnPropertyDescriptor,Ie=(e,t,i,s)=>{for(var r=s>1?void 0:s?m0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&g0(t,i,r),r};let de=class extends A{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=v0(this.machines),t=b0(this.machine),i=y0(this.project),s=S0(this.workspace),r=$0(this.session);return l`
2159
+ `}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}};fe.styles=k0;We([d({attribute:!1})],fe.prototype,"workspace",2);We([d({attribute:!1})],fe.prototype,"panelContext",2);We([d({attribute:!1})],fe.prototype,"emptyState",2);We([d()],fe.prototype,"tool",2);We([d({attribute:!1})],fe.prototype,"panels",2);We([d({type:Boolean})],fe.prototype,"hideToolTabs",2);We([d({attribute:!1})],fe.prototype,"onSelectTool",2);We([B(".workspace-header-strip")],fe.prototype,"workspaceHeaderStrip",2);We([w()],fe.prototype,"workspaceHeaderCanScrollLeft",2);We([w()],fe.prototype,"workspaceHeaderCanScrollRight",2);fe=We([W("workspace-panel")],fe);var $0=Object.defineProperty,P0=Object.getOwnPropertyDescriptor,Re=(e,t,i,s)=>{for(var r=s>1?void 0:s?P0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&$0(t,i,r),r};let pe=class extends R{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=C0(this.machines),t=I0(this.machine),i=A0(this.project),s=M0(this.workspace),r=D0(this.session);return l`
2107
2160
  <nav class=${this.contextBarClass()} aria-label="当前位置">
2108
2161
  <span class="context-bar-label">位置</span>
2109
2162
  <ol class="context-items" @scroll=${this.onContextScroll}>
2110
2163
  ${e?l`
2111
2164
  <li class="context-item">
2112
- <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${w0(this.machine)} aria-label=${`机器:${t}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
2165
+ <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${R0(this.machine)} aria-label=${`机器:${t}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
2113
2166
  <span class="context-kind">机器</span>
2114
2167
  <span class="context-value">${t}</span>
2115
2168
  </button>
2116
2169
  </li>
2117
2170
  `:null}
2118
2171
  <li class="context-item">
2119
- <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${x0(this.project)} aria-label=${`项目:${i}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
2172
+ <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${T0(this.project)} aria-label=${`项目:${i}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
2120
2173
  <span class="context-kind">项目</span>
2121
2174
  <span class="context-value">${i}</span>
2122
2175
  </button>
2123
2176
  </li>
2124
2177
  <li class="context-item">
2125
- <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${k0(this.workspace)} aria-label=${`工作区:${s}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
2178
+ <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${E0(this.workspace)} aria-label=${`工作区:${s}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
2126
2179
  <span class="context-kind">工作区</span>
2127
2180
  <span class="context-value">${s}</span>
2128
2181
  </button>
2129
2182
  </li>
2130
2183
  <li class="context-item">
2131
- <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${P0(this.session)} aria-label=${`会话:${r}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
2184
+ <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${W0(this.session)} aria-label=${`会话:${r}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
2132
2185
  <span class="context-kind">会话</span>
2133
2186
  <span class="context-value">${r}</span>
2134
2187
  </button>
@@ -2142,7 +2195,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2142
2195
  <path d="M13 2 4 14h7l-1 8 10-13h-7V2Z"></path>
2143
2196
  </svg>
2144
2197
  </button>
2145
- `}contextBarClass(){const e=["context-bar"];return this.hasContextActions()&&e.push("has-context-actions"),this.refreshControl!==void 0&&this.onShowActions!==void 0&&e.push("has-context-actions-double"),this.canScrollLeft&&e.push("can-scroll-left"),this.canScrollRight&&e.push("can-scroll-right"),e.join(" ")}hasContextActions(){return this.refreshControl!==void 0||this.onShowActions!==void 0}observeContextItems(){const e=this.contextItemsElement();this.observedContextItems!==e&&(this.contextItemsResizeObserver?.disconnect(),this.observedContextItems=e,this.contextItemsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.contextItemsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.contextItemsResizeObserver.observe(e)))}updateScrollState(){const e=this.contextItemsElement(),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)}contextItemsElement(){const e=this.contextItems;return e instanceof HTMLElement?e:void 0}};de.styles=E`
2198
+ `}contextBarClass(){const e=["context-bar"];return this.hasContextActions()&&e.push("has-context-actions"),this.refreshControl!==void 0&&this.onShowActions!==void 0&&e.push("has-context-actions-double"),this.canScrollLeft&&e.push("can-scroll-left"),this.canScrollRight&&e.push("can-scroll-right"),e.join(" ")}hasContextActions(){return this.refreshControl!==void 0||this.onShowActions!==void 0}observeContextItems(){const e=this.contextItemsElement();this.observedContextItems!==e&&(this.contextItemsResizeObserver?.disconnect(),this.observedContextItems=e,this.contextItemsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.contextItemsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.contextItemsResizeObserver.observe(e)))}updateScrollState(){const e=this.contextItemsElement(),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)}contextItemsElement(){const e=this.contextItems;return e instanceof HTMLElement?e:void 0}};pe.styles=D`
2146
2199
  /* Keep the refresh menu in this shadow tree above the following mobile tab strip. */
2147
2200
  :host { position: relative; z-index: 20; flex: 0 0 auto; min-width: 0; }
2148
2201
  .context-bar { position: relative; flex: 0 0 auto; min-width: 0; display: flex; align-items: center; gap: 0; padding: 6px 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
@@ -2168,7 +2221,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2168
2221
  .context-kind { display: none; }
2169
2222
  .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
2170
2223
  button { cursor: pointer; }
2171
- `;Ie([d({attribute:!1})],de.prototype,"machines",2);Ie([d({attribute:!1})],de.prototype,"machine",2);Ie([d({attribute:!1})],de.prototype,"project",2);Ie([d({attribute:!1})],de.prototype,"workspace",2);Ie([d({attribute:!1})],de.prototype,"session",2);Ie([d({attribute:!1})],de.prototype,"refreshControl",2);Ie([d({attribute:!1})],de.prototype,"onOpenSection",2);Ie([d({attribute:!1})],de.prototype,"onShowActions",2);Ie([B(".context-items")],de.prototype,"contextItems",2);Ie([x()],de.prototype,"canScrollLeft",2);Ie([x()],de.prototype,"canScrollRight",2);de=Ie([W("app-context-bar")],de);function v0(e){return e.length>1}function b0(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function w0(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function y0(e){return e?.name??"未选择项目"}function x0(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function S0(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function k0(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function $0(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 P0(e){return e===void 0?"未选择会话":e.path}var C0=Object.defineProperty,I0=Object.getOwnPropertyDescriptor,ft=(e,t,i,s)=>{for(var r=s>1?void 0:s?I0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&C0(t,i,r),r};let He=class extends A{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`
2224
+ `;Re([d({attribute:!1})],pe.prototype,"machines",2);Re([d({attribute:!1})],pe.prototype,"machine",2);Re([d({attribute:!1})],pe.prototype,"project",2);Re([d({attribute:!1})],pe.prototype,"workspace",2);Re([d({attribute:!1})],pe.prototype,"session",2);Re([d({attribute:!1})],pe.prototype,"refreshControl",2);Re([d({attribute:!1})],pe.prototype,"onOpenSection",2);Re([d({attribute:!1})],pe.prototype,"onShowActions",2);Re([B(".context-items")],pe.prototype,"contextItems",2);Re([w()],pe.prototype,"canScrollLeft",2);Re([w()],pe.prototype,"canScrollRight",2);pe=Re([W("app-context-bar")],pe);function C0(e){return e.length>1}function I0(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function R0(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function A0(e){return e?.name??"未选择项目"}function T0(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function M0(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function E0(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function D0(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 W0(e){return e===void 0?"未选择会话":e.path}var O0=Object.defineProperty,_0=Object.getOwnPropertyDescriptor,vt=(e,t,i,s)=>{for(var r=s>1?void 0:s?_0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&O0(t,i,r),r};let Ve=class extends R{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`
2172
2225
  <div class=${this.frameClass()}>
2173
2226
  <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
2174
2227
  ${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
@@ -2180,7 +2233,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2180
2233
  `})}
2181
2234
  </div>
2182
2235
  </div>
2183
- `}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>`:fg(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const r=this.initialsLabel(s.label);t.set(r,(t.get(r)??0)+1)}const i=new Map;for(const s of e){const r=this.initialsLabel(s.label);i.set(s.id,(t.get(r)??0)>1?this.fullFallbackLabel(s.label):r)}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}};He.styles=E`
2236
+ `}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>`:yg(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const r=this.initialsLabel(s.label);t.set(r,(t.get(r)??0)+1)}const i=new Map;for(const s of e){const r=this.initialsLabel(s.label);i.set(s.id,(t.get(r)??0)>1?this.fullFallbackLabel(s.label):r)}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}};Ve.styles=D`
2184
2237
  :host { flex: 0 0 auto; min-width: 0; }
2185
2238
  .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); }
2186
2239
  .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; }
@@ -2206,12 +2259,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2206
2259
  .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; }
2207
2260
  .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
2208
2261
  }
2209
- `;ft([d({attribute:!1})],He.prototype,"tabs",2);ft([d({attribute:!1})],He.prototype,"selectedView",2);ft([d({attribute:!1})],He.prototype,"onSelect",2);ft([B(".mobile-tabs")],He.prototype,"mobileTabs",2);ft([x()],He.prototype,"canScrollLeft",2);ft([x()],He.prototype,"canScrollRight",2);He=ft([W("app-mobile-main-tabs")],He);var R0=Object.defineProperty,A0=Object.getOwnPropertyDescriptor,me=(e,t,i,s)=>{for(var r=s>1?void 0:s?A0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&R0(t,i,r),r};let se=class extends A{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=_s(e,this.statuses),i=e.name;return l`
2262
+ `;vt([d({attribute:!1})],Ve.prototype,"tabs",2);vt([d({attribute:!1})],Ve.prototype,"selectedView",2);vt([d({attribute:!1})],Ve.prototype,"onSelect",2);vt([B(".mobile-tabs")],Ve.prototype,"mobileTabs",2);vt([w()],Ve.prototype,"canScrollLeft",2);vt([w()],Ve.prototype,"canScrollRight",2);Ve=vt([W("app-mobile-main-tabs")],Ve);var L0=Object.defineProperty,j0=Object.getOwnPropertyDescriptor,ve=(e,t,i,s)=>{for(var r=s>1?void 0:s?j0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&L0(t,i,r),r};let oe=class extends R{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=Us(e,this.statuses),i=e.name;return l`
2210
2263
  <div class="machine-switcher">
2211
2264
  <button
2212
2265
  type="button"
2213
2266
  class="machine-switcher-button"
2214
- title=${na(e)}
2267
+ title=${da(e)}
2215
2268
  aria-label=${`Machine: ${i}. Switch machine.`}
2216
2269
  aria-expanded=${String(this.open)}
2217
2270
  @click=${s=>{this.toggleMenu(s.currentTarget)}}
@@ -2222,7 +2275,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2222
2275
  <span class="machine-switcher-kicker">Machine</span>
2223
2276
  <span class="machine-switcher-label">${i}</span>
2224
2277
  </span>
2225
- <span class=${`machine-status ${t}`}>${oa(t)}</span>
2278
+ <span class=${`machine-status ${t}`}>${ca(t)}</span>
2226
2279
  <span class="machine-chevron" aria-hidden="true">▾</span>
2227
2280
  </button>
2228
2281
  ${this.open?l`
@@ -2231,18 +2284,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2231
2284
  </div>
2232
2285
  `:null}
2233
2286
  </div>
2234
- `}renderMachineOption(e){const t=this.selected?.id===e.id,i=_s(e,this.statuses),s=Dl(e)&&this.onRemove!==void 0,r=this.openActionsMachineId===e.id;return l`
2287
+ `}renderMachineOption(e){const t=this.selected?.id===e.id,i=Us(e,this.statuses),s=Ll(e)&&this.onRemove!==void 0,r=this.openActionsMachineId===e.id;return l`
2235
2288
  <div class=${`machine-option ${t?"selected":""} ${s?"":"no-actions"}`}>
2236
2289
  <button
2237
2290
  type="button"
2238
2291
  class="machine-option-main"
2239
- title=${na(e)}
2292
+ title=${da(e)}
2240
2293
  data-machine-id=${e.id}
2241
2294
  @click=${()=>{this.select(e)}}
2242
2295
  @keydown=${o=>{this.handleMachineOptionKeydown(o)}}
2243
2296
  >
2244
2297
  <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
2245
- <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${oa(i)}</small>
2298
+ <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${ca(i)}</small>
2246
2299
  </button>
2247
2300
  ${s?l`
2248
2301
  <div class="machine-option-actions">
@@ -2262,7 +2315,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2262
2315
  </div>
2263
2316
  `:null}
2264
2317
  </div>
2265
- `}renderActivity(e){const t=_s(e,this.statuses);if(t==="offline"||t==="error")return;const i=$l(this.activities[e.id]);return Cl(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=aa(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=aa(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 r=s.indexOf(e);r<0||this.focusMachineOptionAt(r+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=Il(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)}};se.styles=E`
2318
+ `}renderActivity(e){const t=Us(e,this.statuses);if(t==="offline"||t==="error")return;const i=Rl(this.activities[e.id]);return Tl(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=pa(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=pa(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 r=s.indexOf(e);r<0||this.focusMachineOptionAt(r+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=Ml(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)}};oe.styles=D`
2266
2319
  :host { min-width: 0; display: block; }
2267
2320
  .machine-switcher { min-width: 0; }
2268
2321
  .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; }
@@ -2295,10 +2348,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2295
2348
  .machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
2296
2349
  .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); }
2297
2350
  @keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
2298
- `;me([d({attribute:!1})],se.prototype,"machines",2);me([d({attribute:!1})],se.prototype,"selected",2);me([d({attribute:!1})],se.prototype,"statuses",2);me([d({attribute:!1})],se.prototype,"activities",2);me([d({attribute:!1})],se.prototype,"onSelect",2);me([d({attribute:!1})],se.prototype,"onRemove",2);me([d({attribute:!1})],se.prototype,"onFocusNextSection",2);me([d({attribute:!1})],se.prototype,"onCancelKeyboardNavigation",2);me([x()],se.prototype,"open",2);me([x()],se.prototype,"menuStyle",2);me([x()],se.prototype,"openActionsMachineId",2);me([x()],se.prototype,"actionMenuStyle",2);se=me([W("machine-switcher")],se);function _s(e,t){return t[e.id]?.status??e.status??"unknown"}function oa(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function na(e){return e.baseUrl??e.name}function aa(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)),r=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),o=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${pi(t.bottom)};`,`left: ${pi(r)};`,`width: ${pi(s)};`,`max-height: ${pi(o)};`].join(" ")}function pi(e){return`${String(Math.round(e))}px`}var T0=Object.defineProperty,M0=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var r=s>1?void 0:s?M0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&T0(t,i,r),r};let S=class extends A{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.canCleanupSessions=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.cleanupUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。"}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`
2351
+ `;ve([d({attribute:!1})],oe.prototype,"machines",2);ve([d({attribute:!1})],oe.prototype,"selected",2);ve([d({attribute:!1})],oe.prototype,"statuses",2);ve([d({attribute:!1})],oe.prototype,"activities",2);ve([d({attribute:!1})],oe.prototype,"onSelect",2);ve([d({attribute:!1})],oe.prototype,"onRemove",2);ve([d({attribute:!1})],oe.prototype,"onFocusNextSection",2);ve([d({attribute:!1})],oe.prototype,"onCancelKeyboardNavigation",2);ve([w()],oe.prototype,"open",2);ve([w()],oe.prototype,"menuStyle",2);ve([w()],oe.prototype,"openActionsMachineId",2);ve([w()],oe.prototype,"actionMenuStyle",2);oe=ve([W("machine-switcher")],oe);function Us(e,t){return t[e.id]?.status??e.status??"unknown"}function ca(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function da(e){return e.baseUrl??e.name}function pa(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)),r=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),o=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${gi(t.bottom)};`,`left: ${gi(r)};`,`width: ${gi(s)};`,`max-height: ${gi(o)};`].join(" ")}function gi(e){return`${String(Math.round(e))}px`}var F0=Object.defineProperty,z0=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var r=s>1?void 0:s?z0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&F0(t,i,r),r};let S=class extends R{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.canCleanupSessions=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.cleanupUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。"}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`
2299
2352
  <header>
2300
2353
  <strong>PI WEB</strong>
2301
- ${Hi(this.machines)?l`
2354
+ ${Ji(this.machines)?l`
2302
2355
  <machine-switcher
2303
2356
  .machines=${this.machines}
2304
2357
  .selected=${this.selectedMachine}
@@ -2315,7 +2368,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2315
2368
  <button title="显示操作" aria-label="显示操作" @click=${()=>{this.onShowActions?.()}}>操作</button>
2316
2369
  </div>
2317
2370
  </header>
2318
- ${this.compact&&Hi(this.machines)?l`
2371
+ ${this.compact&&Ji(this.machines)?l`
2319
2372
  <machine-list
2320
2373
  .machines=${this.machines}
2321
2374
  .selected=${this.selectedMachine}
@@ -2391,7 +2444,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2391
2444
  .onFocusNextSection=${()=>{this.focusNextFrom("sessions")}}
2392
2445
  .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2393
2446
  ></session-list>
2394
- `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=E0(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(D0(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};S.styles=E`
2447
+ `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=U0(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(B0(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};S.styles=D`
2395
2448
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
2396
2449
  :host([compact]) { flex: 1 1 auto; }
2397
2450
  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); }
@@ -2414,7 +2467,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2414
2467
  :host([compact]) workspace-list[collapsed],
2415
2468
  :host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
2416
2469
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2417
- `;k([d({attribute:!1})],S.prototype,"machines",2);k([d({attribute:!1})],S.prototype,"selectedMachine",2);k([d({attribute:!1})],S.prototype,"machineStatuses",2);k([d({attribute:!1})],S.prototype,"machineActivities",2);k([d({attribute:!1})],S.prototype,"projects",2);k([d({attribute:!1})],S.prototype,"selectedProject",2);k([d({attribute:!1})],S.prototype,"workspaces",2);k([d({attribute:!1})],S.prototype,"selectedWorkspace",2);k([d({attribute:!1})],S.prototype,"sessions",2);k([d({attribute:!1})],S.prototype,"selectedSession",2);k([d({attribute:!1})],S.prototype,"workspaceActivities",2);k([d({attribute:!1})],S.prototype,"sessionActivities",2);k([d({attribute:!1})],S.prototype,"sessionStatuses",2);k([d({attribute:!1})],S.prototype,"sendingPrompts",2);k([d({attribute:!1})],S.prototype,"workspacesByProjectId",2);k([d({attribute:!1})],S.prototype,"deletingWorkspaceIds",2);k([d({attribute:!1})],S.prototype,"workspaceLabelItems",2);k([d({attribute:!1})],S.prototype,"refreshControl",2);k([d({type:Boolean,reflect:!0})],S.prototype,"collapsible",2);k([d({type:Boolean,reflect:!0})],S.prototype,"compact",2);k([d({type:Boolean})],S.prototype,"machinesCollapsed",2);k([d({type:Boolean})],S.prototype,"projectsCollapsed",2);k([d({type:Boolean})],S.prototype,"workspacesCollapsed",2);k([d({type:Boolean})],S.prototype,"sessionsCollapsed",2);k([d({type:Boolean})],S.prototype,"canStartSession",2);k([d({type:Boolean})],S.prototype,"canDeleteArchivedSessions",2);k([d({type:Boolean})],S.prototype,"canReloadSessions",2);k([d({type:Boolean})],S.prototype,"canCleanupSessions",2);k([d({type:String})],S.prototype,"archivedDeleteUnavailableMessage",2);k([d({type:String})],S.prototype,"cleanupUnavailableMessage",2);k([d({attribute:!1})],S.prototype,"onShowActions",2);k([d({attribute:!1})],S.prototype,"onToggleMachines",2);k([d({attribute:!1})],S.prototype,"onToggleProjects",2);k([d({attribute:!1})],S.prototype,"onToggleWorkspaces",2);k([d({attribute:!1})],S.prototype,"onToggleSessions",2);k([d({attribute:!1})],S.prototype,"onSelectProject",2);k([d({attribute:!1})],S.prototype,"onCloseProject",2);k([d({attribute:!1})],S.prototype,"onSelectWorkspace",2);k([d({attribute:!1})],S.prototype,"onDeleteWorkspace",2);k([d({attribute:!1})],S.prototype,"onStartSession",2);k([d({attribute:!1})],S.prototype,"onSelectSession",2);k([d({attribute:!1})],S.prototype,"onArchiveSession",2);k([d({attribute:!1})],S.prototype,"onArchiveSessionWithDescendants",2);k([d({attribute:!1})],S.prototype,"onArchiveSessions",2);k([d({attribute:!1})],S.prototype,"onRestoreSession",2);k([d({attribute:!1})],S.prototype,"onDeleteCachedNewSession",2);k([d({attribute:!1})],S.prototype,"onDeleteArchivedSession",2);k([d({attribute:!1})],S.prototype,"onDeleteArchivedSessions",2);k([d({attribute:!1})],S.prototype,"onDetachParentSession",2);k([d({attribute:!1})],S.prototype,"onReloadSession",2);k([d({attribute:!1})],S.prototype,"onCleanupSessions",2);k([d({attribute:!1})],S.prototype,"onArchivedCollapsed",2);k([d({attribute:!1})],S.prototype,"onSelectMachine",2);k([d({attribute:!1})],S.prototype,"onRemoveMachine",2);k([d({attribute:!1})],S.prototype,"onFocusNavigationTarget",2);k([d({attribute:!1})],S.prototype,"onCancelKeyboardNavigation",2);k([B("machine-list")],S.prototype,"machineList",2);k([B("machine-switcher")],S.prototype,"machineSwitcher",2);k([B("project-list")],S.prototype,"projectList",2);k([B("workspace-list")],S.prototype,"workspaceList",2);k([B("session-list")],S.prototype,"sessionList",2);S=k([W("app-navigation-panel")],S);function Hi(e){return e.length>1}function E0(e,t){const i=rc(t);return i[i.indexOf(e)-1]}function D0(e,t){const i=rc(t);return i[i.indexOf(e)+1]??"chat"}function rc(e){return ji.filter(t=>t!=="machines"||Hi(e))}var W0=Object.defineProperty,O0=Object.getOwnPropertyDescriptor,ee=(e,t,i,s)=>{for(var r=s>1?void 0:s?O0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&W0(t,i,r),r};const _0=new Set(["ArrowLeft","ArrowRight","Home","End"]),L0=420,j0=4;let K=class extends A{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`
2470
+ `;k([d({attribute:!1})],S.prototype,"machines",2);k([d({attribute:!1})],S.prototype,"selectedMachine",2);k([d({attribute:!1})],S.prototype,"machineStatuses",2);k([d({attribute:!1})],S.prototype,"machineActivities",2);k([d({attribute:!1})],S.prototype,"projects",2);k([d({attribute:!1})],S.prototype,"selectedProject",2);k([d({attribute:!1})],S.prototype,"workspaces",2);k([d({attribute:!1})],S.prototype,"selectedWorkspace",2);k([d({attribute:!1})],S.prototype,"sessions",2);k([d({attribute:!1})],S.prototype,"selectedSession",2);k([d({attribute:!1})],S.prototype,"workspaceActivities",2);k([d({attribute:!1})],S.prototype,"sessionActivities",2);k([d({attribute:!1})],S.prototype,"sessionStatuses",2);k([d({attribute:!1})],S.prototype,"sendingPrompts",2);k([d({attribute:!1})],S.prototype,"workspacesByProjectId",2);k([d({attribute:!1})],S.prototype,"deletingWorkspaceIds",2);k([d({attribute:!1})],S.prototype,"workspaceLabelItems",2);k([d({attribute:!1})],S.prototype,"refreshControl",2);k([d({type:Boolean,reflect:!0})],S.prototype,"collapsible",2);k([d({type:Boolean,reflect:!0})],S.prototype,"compact",2);k([d({type:Boolean})],S.prototype,"machinesCollapsed",2);k([d({type:Boolean})],S.prototype,"projectsCollapsed",2);k([d({type:Boolean})],S.prototype,"workspacesCollapsed",2);k([d({type:Boolean})],S.prototype,"sessionsCollapsed",2);k([d({type:Boolean})],S.prototype,"canStartSession",2);k([d({type:Boolean})],S.prototype,"canDeleteArchivedSessions",2);k([d({type:Boolean})],S.prototype,"canReloadSessions",2);k([d({type:Boolean})],S.prototype,"canCleanupSessions",2);k([d({type:String})],S.prototype,"archivedDeleteUnavailableMessage",2);k([d({type:String})],S.prototype,"cleanupUnavailableMessage",2);k([d({attribute:!1})],S.prototype,"onShowActions",2);k([d({attribute:!1})],S.prototype,"onToggleMachines",2);k([d({attribute:!1})],S.prototype,"onToggleProjects",2);k([d({attribute:!1})],S.prototype,"onToggleWorkspaces",2);k([d({attribute:!1})],S.prototype,"onToggleSessions",2);k([d({attribute:!1})],S.prototype,"onSelectProject",2);k([d({attribute:!1})],S.prototype,"onCloseProject",2);k([d({attribute:!1})],S.prototype,"onSelectWorkspace",2);k([d({attribute:!1})],S.prototype,"onDeleteWorkspace",2);k([d({attribute:!1})],S.prototype,"onStartSession",2);k([d({attribute:!1})],S.prototype,"onSelectSession",2);k([d({attribute:!1})],S.prototype,"onArchiveSession",2);k([d({attribute:!1})],S.prototype,"onArchiveSessionWithDescendants",2);k([d({attribute:!1})],S.prototype,"onArchiveSessions",2);k([d({attribute:!1})],S.prototype,"onRestoreSession",2);k([d({attribute:!1})],S.prototype,"onDeleteCachedNewSession",2);k([d({attribute:!1})],S.prototype,"onDeleteArchivedSession",2);k([d({attribute:!1})],S.prototype,"onDeleteArchivedSessions",2);k([d({attribute:!1})],S.prototype,"onDetachParentSession",2);k([d({attribute:!1})],S.prototype,"onReloadSession",2);k([d({attribute:!1})],S.prototype,"onCleanupSessions",2);k([d({attribute:!1})],S.prototype,"onArchivedCollapsed",2);k([d({attribute:!1})],S.prototype,"onSelectMachine",2);k([d({attribute:!1})],S.prototype,"onRemoveMachine",2);k([d({attribute:!1})],S.prototype,"onFocusNavigationTarget",2);k([d({attribute:!1})],S.prototype,"onCancelKeyboardNavigation",2);k([B("machine-list")],S.prototype,"machineList",2);k([B("machine-switcher")],S.prototype,"machineSwitcher",2);k([B("project-list")],S.prototype,"projectList",2);k([B("workspace-list")],S.prototype,"workspaceList",2);k([B("session-list")],S.prototype,"sessionList",2);S=k([W("app-navigation-panel")],S);function Ji(e){return e.length>1}function U0(e,t){const i=lc(t);return i[i.indexOf(e)-1]}function B0(e,t){const i=lc(t);return i[i.indexOf(e)+1]??"chat"}function lc(e){return Bi.filter(t=>t!=="machines"||Ji(e))}var N0=Object.defineProperty,H0=Object.getOwnPropertyDescriptor,ie=(e,t,i,s)=>{for(var r=s>1?void 0:s?H0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&N0(t,i,r),r};const q0=new Set(["ArrowLeft","ArrowRight","Home","End"]),K0=420,V0=4;let V=class extends R{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`
2418
2471
  ${this.renderResizeHandle()}
2419
2472
  <button
2420
2473
  type="button"
@@ -2425,7 +2478,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2425
2478
  aria-expanded=${String(!this.collapsed)}
2426
2479
  @click=${()=>{this.onToggle?.()}}
2427
2480
  >${this.renderIcon()}</button>
2428
- `}renderResizeHandle(){if(!this.resizable)return z;const e=this.resizeConstraints();return l`
2481
+ `}renderResizeHandle(){if(!this.resizable)return U;const e=this.resizeConstraints();return l`
2429
2482
  <div
2430
2483
  class="resize-handle"
2431
2484
  role="separator"
@@ -2444,7 +2497,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2444
2497
  @dblclick=${t=>{this.onResizeDoubleClick(t)}}
2445
2498
  @keydown=${t=>{this.onResizeKeyDown(t)}}
2446
2499
  ></div>
2447
- `}resizeAriaValueNow(){return this.panelWidth===void 0?z: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)<=j0)&&(t.moved=!0,this.commitPanelWidth(Um(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||!_0.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=zm(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<=L0){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 we(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(we(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=Yt(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};K.styles=E`
2500
+ `}resizeAriaValueNow(){return this.panelWidth===void 0?U: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)<=V0)&&(t.moved=!0,this.commitPanelWidth(Km(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||!q0.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=Vm(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<=K0){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 we(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(we(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=ri(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};V.styles=D`
2448
2501
  :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; }
2449
2502
  :host([side="navigation"]) { grid-column: 2; }
2450
2503
  :host([side="workspace"]) { grid-column: 4; }
@@ -2463,7 +2516,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2463
2516
  @media (max-width: 760px) {
2464
2517
  :host([side="navigation"]) { display: none; }
2465
2518
  }
2466
- `;ee([d({reflect:!0})],K.prototype,"side",2);ee([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);ee([d({type:Boolean})],K.prototype,"resizable",2);ee([d({type:Number})],K.prototype,"panelWidth",2);ee([d({type:Number})],K.prototype,"minWidth",2);ee([d({type:Number})],K.prototype,"maxWidth",2);ee([d()],K.prototype,"controls",2);ee([d()],K.prototype,"resizeLabel",2);ee([d()],K.prototype,"expandLabel",2);ee([d()],K.prototype,"collapseLabel",2);ee([d({attribute:!1})],K.prototype,"onToggle",2);ee([d({attribute:!1})],K.prototype,"onResizeStart",2);ee([d({attribute:!1})],K.prototype,"onResize",2);ee([d({attribute:!1})],K.prototype,"onResizeEnd",2);ee([d({attribute:!1})],K.prototype,"onReset",2);K=ee([W("app-panel-edge-control")],K);var F0=Object.defineProperty,U0=Object.getOwnPropertyDescriptor,oc=(e,t,i,s)=>{for(var r=s>1?void 0:s?U0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&F0(t,i,r),r};let Ki=class extends A{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="完整重载页面";return l`
2519
+ `;ie([d({reflect:!0})],V.prototype,"side",2);ie([d({type:Boolean,reflect:!0})],V.prototype,"collapsed",2);ie([d({type:Boolean})],V.prototype,"resizable",2);ie([d({type:Number})],V.prototype,"panelWidth",2);ie([d({type:Number})],V.prototype,"minWidth",2);ie([d({type:Number})],V.prototype,"maxWidth",2);ie([d()],V.prototype,"controls",2);ie([d()],V.prototype,"resizeLabel",2);ie([d()],V.prototype,"expandLabel",2);ie([d()],V.prototype,"collapseLabel",2);ie([d({attribute:!1})],V.prototype,"onToggle",2);ie([d({attribute:!1})],V.prototype,"onResizeStart",2);ie([d({attribute:!1})],V.prototype,"onResize",2);ie([d({attribute:!1})],V.prototype,"onResizeEnd",2);ie([d({attribute:!1})],V.prototype,"onReset",2);V=ie([W("app-panel-edge-control")],V);var G0=Object.defineProperty,J0=Object.getOwnPropertyDescriptor,cc=(e,t,i,s)=>{for(var r=s>1?void 0:s?J0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&G0(t,i,r),r};let Qi=class extends R{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="完整重载页面";return l`
2467
2520
  <button
2468
2521
  class="app-refresh-button"
2469
2522
  title=${e}
@@ -2477,12 +2530,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2477
2530
  <path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
2478
2531
  <path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
2479
2532
  </svg>
2480
- `}};Ki.styles=E`
2533
+ `}};Qi.styles=D`
2481
2534
  :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; }
2482
2535
  :host, :host * { -webkit-user-select: none; user-select: none; }
2483
2536
  .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; }
2484
2537
  .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
2485
- `;oc([d({attribute:!1})],Ki.prototype,"onReload",2);Ki=oc([W("app-refresh-control")],Ki);var z0=Object.defineProperty,B0=Object.getOwnPropertyDescriptor,ve=(e,t,i,s)=>{for(var r=s>1?void 0:s?B0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&z0(t,i,r),r};const N0=E`
2538
+ `;cc([d({attribute:!1})],Qi.prototype,"onReload",2);Qi=cc([W("app-refresh-control")],Qi);var Q0=Object.defineProperty,Z0=Object.getOwnPropertyDescriptor,Z=(e,t,i,s)=>{for(var r=s>1?void 0:s?Z0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Q0(t,i,r),r};const X0=D`
2486
2539
  /* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
2487
2540
  :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; }
2488
2541
  :host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
@@ -2581,7 +2634,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2581
2634
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2582
2635
  .empty { margin: auto; color: var(--pi-muted); }
2583
2636
  .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
2584
- `,q0=900*1e3,H0=750,cr=[1e3,3e3,8e3,15e3,3e4],la={capture:!0},Ls="auto:on",ca="auto:off",hi="theme:",js=Jt("core:workspace.files"),Fs=Jt("core:workspace.git"),ui=Jt("core:workspace.terminal"),K0=320,V0=2,G0="(min-width: 1181px)";let re=class extends A{constructor(){super(...arguments),this.state=ih(),this.apiScope=Q0(),this.sessions=new Xu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Ku,{socket:new el(this.apiScope)}),this.activity=new sh(()=>this.state,e=>{this.setState(e)}),this.auth=new nh(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new pf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new cf),this.projects=new yh(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new wh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new fh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new bh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new $f,this.realtime=new Ko(this.apiScope),this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new gf,this.terminalSelection=new Sf,this.appShell=new km(this),this.panelCollapse=new _m(this),this.panelResize=new jm(this),this.navigationSections=new Dm(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.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=J0(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Kf()??Nf,this.activeThemeId=_r,this.isRefreshingApp=!1,this.settingsSection=Cn(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=To(void 0),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())},this.handleSendPrompt=(e,t,i,s)=>{this.sendPrompt(e,t,i,s)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}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,la),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},q0),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,la),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(!Y0(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),Z0(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=Pn();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=H0){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 _a.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=>nc(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 Ii.config()).effectiveConfig)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=To(e)}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(Pn(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const r=f(this.state),o=e.projectId===void 0||e.projectId===""?ha():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=o.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:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.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:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.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)!==r&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?ha():{selectedFilePath:vs(js,"file"),selectedDiffPath:vs(Fs,"diff"),selectedTerminalId:vs(ui,"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){$s(e,{replace:!0}),he(js,"file",void 0,{replace:!0}),he(Fs,"diff",void 0,{replace:!0}),he(ui,"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=tx(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>=cr.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",o=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}${o===void 0?"":` ${o}`}`})}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(r=>r.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,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await zs(),t()&&(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(),$s({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(en(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(en(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){$s(tn(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){he(js,"file",e.selectedFilePath,{replace:!0}),he(Fs,"diff",e.selectedDiffPath,{replace:!0}),he(ui,"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)??mf(e.id);if(await this.restoreRouteFor(tn(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=ua(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const r=tv(e,{api:{runTerminalCommand:(o,n)=>yt.runTerminalCommand(o,n,t),listCommandRuns:o=>yt.listCommandRuns(o,t),getCommandRun:o=>yt.getCommandRun(o,t)},openTerminal:(o,n)=>{this.openRuntimeTerminal(t,o,n)}});return this.terminalCommandRunRuntimes.set(i,r),r}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){he(ui,"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,Ps(e)}closeSettings(){this.settingsSection=void 0,Ps(void 0)}navigateSettings(e){this.settingsSection=e,Ps(e)}restoreSettingsRoute(){this.settingsSection=Cn()}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 Ko(this.apiScope);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=>X0(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):ex(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 yt.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=pa(e),s=pa(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.sessionCleanupDialog=void 0,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`
2637
+ `,Y0=900*1e3,ex=750,ur=[1e3,3e3,8e3,15e3,3e4],ha={capture:!0},Bs="auto:on",ua="auto:off",mi="theme:",Ns=ei("core:workspace.files"),Hs=ei("core:workspace.git"),vi=ei("core:workspace.terminal"),tx=320,ix=2,sx="(min-width: 1181px)";let K=class extends R{constructor(){super(...arguments),this.state=lh(),this.apiScope=ox(),this.sessions=new of(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Xu,{socket:new rl(this.apiScope)}),this.activity=new ch(()=>this.state,e=>{this.setState(e)}),this.auth=new hh(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new vf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new gf),this.projects=new Ch(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Ph(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new yh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new $h(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Tf,this.realtime=new Qo(this.apiScope),this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new xf,this.terminalSelection=new Rf,this.appShell=new Am(this),this.panelCollapse=new Bm(this),this.panelResize=new Hm(this),this.navigationSections=new Fm(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.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=rx(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Xf()??Jf,this.activeThemeId=zr,this.isRefreshingApp=!1,this.settingsSection=Tn(),this.normalAuthLoading=!0,this.normalAuthError="",this.shortcutConfig={},this.workspaceUploadDefaultFolder=Wo(void 0),this.appStartupStarted=!1,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())},this.handleSendPrompt=(e,t,i,s)=>{this.sendPrompt(e,t,i,s)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}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,ha),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.initializeNormalAuth()}startAuthenticatedApp(){this.appStartupStarted||(this.appStartupStarted=!0,this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},Y0),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()}))}async initializeNormalAuth(){if(this.apiScope==="management"){this.normalAuthStatus={configured:!0,authenticated:!0},this.normalAuthLoading=!1,this.startAuthenticatedApp();return}this.normalAuthLoading=!0,this.normalAuthError="";try{const e=await St.status();this.normalAuthStatus=e,e.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=`检查普通模式密码失败:${Ht(e)}`}finally{this.normalAuthLoading=!1}}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,ha),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(!lx(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),nx(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=An();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=ex){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 za.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=>dc(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 Mi.config()).effectiveConfig)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=Wo(e)}async submitNormalAuth(e){const t=this.normalAuthDialogMode??this.normalAuthGateMode();if(!(t===void 0||this.normalAuthLoading)){this.normalAuthLoading=!0,this.normalAuthError="";try{t==="setup"?await St.setup(e.password):t==="change"?await St.changePassword(e.currentPassword??"",e.password):await St.login(e.password);const i=await St.status();this.normalAuthStatus=i,this.normalAuthDialogMode=void 0,i.authenticated&&this.startAuthenticatedApp()}catch(i){this.normalAuthError=Ht(i)}finally{this.normalAuthLoading=!1}}}normalAuthGateMode(){if(this.apiScope!=="management"&&this.normalAuthStatus?.authenticated!==!0)return this.normalAuthStatus?.configured===!0?"login":"setup"}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(An(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const r=f(this.state),o=e.projectId===void 0||e.projectId===""?ma():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=o.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:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.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:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.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)!==r&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?ma():{selectedFilePath:xs(Ns,"file"),selectedDiffPath:xs(Hs,"diff"),selectedTerminalId:xs(vi,"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){Rs(e,{replace:!0}),ue(Ns,"file",void 0,{replace:!0}),ue(Hs,"diff",void 0,{replace:!0}),ue(vi,"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=dx(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>=ur.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",o=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}${o===void 0?"":` ${o}`}`})}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(r=>r.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,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await qs(),t()&&(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(),Rs({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(on(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(on(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Rs(nn(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){ue(Ns,"file",e.selectedFilePath,{replace:!0}),ue(Hs,"diff",e.selectedDiffPath,{replace:!0}),ue(vi,"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)??Sf(e.id);if(await this.restoreRouteFor(nn(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=va(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const r=av(e,{api:{runTerminalCommand:(o,n)=>$t.runTerminalCommand(o,n,t),listCommandRuns:o=>$t.listCommandRuns(o,t),getCommandRun:o=>$t.getCommandRun(o,t)},openTerminal:(o,n)=>{this.openRuntimeTerminal(t,o,n)}});return this.terminalCommandRunRuntimes.set(i,r),r}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){ue(vi,"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,As(e)}closeSettings(){this.settingsSection=void 0,As(void 0)}navigateSettings(e){this.settingsSection=e,As(e)}restoreSettingsRoute(){this.settingsSection=Tn()}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 Qo(this.apiScope);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=>ax(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):cx(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 $t.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=ga(e),s=ga(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.sessionCleanupDialog=void 0,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`
2585
2638
  <workspace-panel
2586
2639
  id="workspace-panel"
2587
2640
  .workspace=${e}
@@ -2627,7 +2680,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2627
2680
  .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
2628
2681
  .onReset=${()=>{this.resetResizablePanel("workspace")}}
2629
2682
  ></app-panel-edge-control>
2630
- `}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),r=Math.floor(i-s-V0-K0);return Math.max(t.minWidth,Math.min(t.maxWidth,r))}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(G0).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&&Be(e,Oe.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&Be(e,Oe.sessionsReload)}canCleanupSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&Be(e,Oe.sessionsCleanup)}supportsWorkspaceFileSuggestions(e=f(this.state)){if(e==="local")return!0;const t=this.state.machineRuntimes[e];return t?.ok===!0&&Be(t,Oe.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`请更新并重启 ${this.state.selectedMachine?.name??"此机器"} 上的 Pi-Web 后再删除已归档会话。`}sessionCleanupUnavailableMessage(){return jf(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[f(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:""}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}const t=f(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:"",preview:void 0,previewRequest:void 0,result:void 0};try{const i=await Vs.cleanupPreview(e,t);if(f(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:i,previewRequest:e,result:void 0,loading:!1,error:""}}catch(i){f(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`预览清理失败:${Us(i)}`})}}async runSessionCleanup(e){const t=this.sessionCleanupDialog;if(t?.preview===void 0||$t(t.previewRequest)!==$t(e)){this.sessionCleanupDialog={...t??{},error:"运行清理前请先预览。"};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}const i=f(this.state);this.sessionCleanupDialog={...t,running:!0,error:""};try{const s=await Vs.cleanup(e,i);if(f(this.state)!==i)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:s,previewRequest:e,result:s,running:!1,error:""},await this.sessions.applySessionCleanupResult(s,i)}catch(s){f(this.state)===i&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`运行清理失败:${Us(s)}`})}}renderNavigationPanel(){return l`
2683
+ `}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),r=Math.floor(i-s-ix-tx);return Math.max(t.minWidth,Math.min(t.maxWidth,r))}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(sx).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&&qe(e,_e.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&qe(e,_e.sessionsReload)}canCleanupSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&qe(e,_e.sessionsCleanup)}supportsWorkspaceFileSuggestions(e=f(this.state)){if(e==="local")return!0;const t=this.state.machineRuntimes[e];return t?.ok===!0&&qe(t,_e.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`请更新并重启 ${this.state.selectedMachine?.name??"此机器"} 上的 Pi-Web 后再删除已归档会话。`}sessionCleanupUnavailableMessage(){return Hf(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[f(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:""}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}const t=f(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:"",preview:void 0,previewRequest:void 0,result:void 0};try{const i=await Zs.cleanupPreview(e,t);if(f(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:i,previewRequest:e,result:void 0,loading:!1,error:""}}catch(i){f(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`预览清理失败:${Ht(i)}`})}}async runSessionCleanup(e){const t=this.sessionCleanupDialog;if(t?.preview===void 0||Rt(t.previewRequest)!==Rt(e)){this.sessionCleanupDialog={...t??{},error:"运行清理前请先预览。"};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}const i=f(this.state);this.sessionCleanupDialog={...t,running:!0,error:""};try{const s=await Zs.cleanup(e,i);if(f(this.state)!==i)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:s,previewRequest:e,result:s,running:!1,error:""},await this.sessions.applySessionCleanupResult(s,i)}catch(s){f(this.state)===i&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`运行清理失败:${Ht(s)}`})}}renderNavigationPanel(){return l`
2631
2684
  <app-navigation-panel
2632
2685
  .machines=${this.state.machines}
2633
2686
  .selectedMachine=${this.state.selectedMachine}
@@ -2643,7 +2696,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2643
2696
  .workspacesByProjectId=${this.state.workspacesByProjectId}
2644
2697
  .workspaces=${this.state.workspaces}
2645
2698
  .selectedWorkspace=${this.state.selectedWorkspace}
2646
- .deletingWorkspaceIds=${ng(this.state.workspaceDeletionRuns)}
2699
+ .deletingWorkspaceIds=${hg(this.state.workspaceDeletionRuns)}
2647
2700
  .sessions=${this.state.sessions}
2648
2701
  .sessionStatuses=${this.state.sessionStatuses}
2649
2702
  .sessionActivities=${this.state.sessionActivities}
@@ -2686,14 +2739,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2686
2739
  .onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
2687
2740
  .onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
2688
2741
  ></app-navigation-panel>
2689
- `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){const s=++this.navigationSelectionSeq,r=()=>s===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()},r),r()&&await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!Hi(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 zs(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await zs(),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=da(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=>wt.workspaceFile(e.projectId,e.id,i,t),writeFile:async(i,s,r)=>{const o=await wt.writeWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o},deleteFile:async i=>{const s=await wt.deleteWorkspaceFile(e.projectId,e.id,i,t);return this.files.refreshFiles(),s},moveFile:async(i,s,r)=>{const o=await wt.moveWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=da(this.state),i=t.id,s=r=>{const o=this.terminalCommandRunsForOrigin(r,i);return dm({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),prompt:this.createPromptEditor(),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>o.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:o},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,workspaceUploadDefaultFolder:Bp(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},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)},onStartWorkspaceUpload:(n,a)=>this.files.startWorkspaceUpload(n,a),onCancelWorkspaceUpload:n=>{this.files.cancelWorkspaceUpload(n)},onClearWorkspaceUpload:n=>{this.files.clearWorkspaceUpload(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return Ym(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}sessionActions(){return[{id:"app.sessions.cleanup",title:"清理会话",description:"预览并手动清理所选机器上的空闲或已归档会话",group:"Sessions",...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}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",()=>xn())}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}`,()=>xn(`/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(r){console.warn(`Failed to register PI WEB plugin ${s.id}`,r)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPromptEditor(){return{insertText:e=>{const t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();const i=t.state.selection.main;t.dispatch({changes:{from:i.from,to:i.to,insert:e},selection:{anchor:i.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??"",getSelection:()=>{const e=this.promptEditor?.view;if(!e)return null;const t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){const e=t=>cm({state:this.state,prompt:this.createPromptEditor(),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(!hf(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(ml(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
2742
+ `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){const s=++this.navigationSelectionSeq,r=()=>s===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()},r),r()&&await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!Ji(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 qs(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await qs(),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=fa(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=>kt.workspaceFile(e.projectId,e.id,i,t),writeFile:async(i,s,r)=>{const o=await kt.writeWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o},deleteFile:async i=>{const s=await kt.deleteWorkspaceFile(e.projectId,e.id,i,t);return this.files.refreshFiles(),s},moveFile:async(i,s,r)=>{const o=await kt.moveWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=fa(this.state),i=t.id,s=r=>{const o=this.terminalCommandRunsForOrigin(r,i);return mm({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),prompt:this.createPromptEditor(),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>o.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:o},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,workspaceUploadDefaultFolder:Gp(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},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)},onStartWorkspaceUpload:(n,a)=>this.files.startWorkspaceUpload(n,a),onCancelWorkspaceUpload:n=>{this.files.cancelWorkspaceUpload(n)},onClearWorkspaceUpload:n=>{this.files.clearWorkspaceUpload(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return ov(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.normalAuthActions(),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}normalAuthActions(){return this.apiScope==="management"?[]:[{id:"app.normal-auth.change-password",title:"修改普通模式密码",description:"更改进入普通模式所需的本地密码",group:"偏好设置",enabled:this.normalAuthStatus?.authenticated===!0,run:()=>{this.normalAuthDialogMode="change",this.normalAuthError=""}}]}sessionActions(){return[{id:"app.sessions.cleanup",title:"清理会话",description:"预览并手动清理所选机器上的空闲或已归档会话",group:"Sessions",...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}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",()=>Pn())}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}`,()=>Pn(`/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(r){console.warn(`Failed to register PI WEB plugin ${s.id}`,r)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPromptEditor(){return{insertText:e=>{const t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();const i=t.state.selection.main;t.dispatch({changes:{from:i.from,to:i.to,insert:e},selection:{anchor:i.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??"",getSelection:()=>{const e=this.promptEditor?.view;if(!e)return null;const t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){const e=t=>gm({state:this.state,prompt:this.createPromptEditor(),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(!bf(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(yl(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
2690
2743
 
2691
2744
  This will run git worktree remove and delete:
2692
2745
  ${e.path}
2693
2746
 
2694
- The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=await wt.deleteWorkspace(e.projectId,e.id,s);if(f(this.state)!==s)return;this.recordWorkspaceDeletionRun(r,s);const o=await this.workspaceForCommandRun(r);if(f(this.state)!==s)return;o!==void 0&&this.openRuntimeTerminal(s,o,{terminalId:r.terminalId})}catch(r){f(this.state)===s&&this.setState({error:`启动工作区删除失败:${Us(r)}`})}}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=Ys(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(rg(t.id));if(f(this.state)!==e)return;const s=og(i);this.setState({workspaceDeletionRuns:s});for(const r of Object.values(s))_i(r)||await this.handleCompletedWorkspaceDeletionRun(r,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(_i);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=ua(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Ys(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:ix(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}?
2747
+ The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=await kt.deleteWorkspace(e.projectId,e.id,s);if(f(this.state)!==s)return;this.recordWorkspaceDeletionRun(r,s);const o=await this.workspaceForCommandRun(r);if(f(this.state)!==s)return;o!==void 0&&this.openRuntimeTerminal(s,o,{terminalId:r.terminalId})}catch(r){f(this.state)===s&&this.setState({error:`启动工作区删除失败:${Ht(r)}`})}}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=sr(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(dg(t.id));if(f(this.state)!==e)return;const s=pg(i);this.setState({workspaceDeletionRuns:s});for(const r of Object.values(s))zi(r)||await this.handleCompletedWorkspaceDeletionRun(r,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(zi);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=va(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=sr(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:px(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}?
2695
2748
 
2696
- 这只会从当前 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 r=s.provider??"",o=s.id??"",n=r===t&&o===i;return{value:`${r}/${o}`,label:`${o}${n?" ✓ 当前":""}`,description:r}})}})}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?ca:Ls;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${hi}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开启":"关闭"}`,description:this.autoThemeDescription(t)},...e.map(r=>({value:`${hi}${r.id}`,label:this.themeOptionLabel(r,i),description:this.themeOptionDescription(r)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===Ls||e===ca){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===Ls},this.applyPreferredTheme(!0);return}if(!e.startsWith(hi))return;const t=e.slice(hi.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,Gf(t),e&&Vf(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Jf({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return gl(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=sx(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`
2749
+ 这只会从当前 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 r=s.provider??"",o=s.id??"",n=r===t&&o===i;return{value:`${r}/${o}`,label:`${o}${n?" ✓ 当前":""}`,description:r}})}})}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?ua:Bs;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${mi}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开启":"关闭"}`,description:this.autoThemeDescription(t)},...e.map(r=>({value:`${mi}${r.id}`,label:this.themeOptionLabel(r,i),description:this.themeOptionDescription(r)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===Bs||e===ua){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===Bs},this.applyPreferredTheme(!0);return}if(!e.startsWith(mi))return;const t=e.slice(mi.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,eg(t),e&&Yf(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return tg({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return wl(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=hx(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`
2697
2750
  <app-context-bar
2698
2751
  .machines=${this.state.machines}
2699
2752
  .machine=${this.state.selectedMachine}
@@ -2710,11 +2763,11 @@ The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=a
2710
2763
  .selectedView=${this.state.mainView}
2711
2764
  .onSelect=${e=>{this.selectMainView(e)}}
2712
2765
  ></app-mobile-main-tabs>
2713
- `}mobileMainTabs(){return[{id:"navigation",label:"会话",icon:"navigation",className:"navigation-tab"},{id:"chat",label:"聊天",icon:"chat"},...this.visibleWorkspacePanels().map(e=>{const t=e.icon??this.mobilePanelIcon(e);return{id:e.id,label:e.title,...t===void 0?{}:{icon:t},badge:this.mobilePanelBadge(e)}})]}renderAppRefresh(){return l`<app-refresh-control .onReload=${()=>{this.hardReloadApp()}}></app-refresh-control>`}render(){const e=this.state;return l`
2766
+ `}mobileMainTabs(){return[{id:"navigation",label:"会话",icon:"navigation",className:"navigation-tab"},{id:"chat",label:"聊天",icon:"chat"},...this.visibleWorkspacePanels().map(e=>{const t=e.icon??this.mobilePanelIcon(e);return{id:e.id,label:e.title,...t===void 0?{}:{icon:t},badge:this.mobilePanelBadge(e)}})]}renderAppRefresh(){return l`<app-refresh-control .onReload=${()=>{this.hardReloadApp()}}></app-refresh-control>`}render(){const e=this.state,t=this.normalAuthGateMode();return this.apiScope==="normal"&&(t!==void 0||this.normalAuthStatus===void 0)?this.renderNormalAuthDialog(t??"login"):l`
2714
2767
  <div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints("navigation"),workspace:this.resizablePanelConstraints("workspace")})}>
2715
2768
  <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
2716
2769
  ${this.renderNavigationPanelEdgeControl()}
2717
- <main class=${xl(e.mainView)}>
2770
+ <main class=${Pl(e.mainView)}>
2718
2771
  ${this.renderContextBar()}
2719
2772
  ${this.renderMobileMainTabs()}
2720
2773
  ${e.error?l`<div class="error">${e.error}</div>`:null}
@@ -2723,19 +2776,28 @@ The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=a
2723
2776
  <chat-view .sessionId=${e.selectedSession.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isReceivingPartialStream=${e.isReceivingPartialStream} .isSendingPrompt=${e.sendingPrompts[e.selectedSession.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .status=${e.status} .activity=${e.activity} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
2724
2777
  <prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${f(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${e.status} .availableThinkingLevels=${e.availableThinkingLevels} .sending=${e.sendingPrompts[e.selectedSession.id]===!0} .onSend=${this.handleSendPrompt} .onStop=${this.handleStopActiveWork} .onSelectModel=${this.handleSelectModel} .onSelectThinking=${this.handleSelectThinking}></prompt-editor>
2725
2778
  <status-bar .status=${e.status}></status-bar>
2726
- ${e.commandDialog!==void 0?l`<command-picker .title=${e.commandDialog.title} .options=${e.commandDialog.options} .onPick=${t=>this.sessions.respondToCommand(e.commandDialog?.requestId??"",t)} .onCancel=${()=>{this.sessions.cancelCommand()}}></command-picker>`:null}
2727
- ${e.modelDialog!==void 0?l`<command-picker title=${e.modelDialog.title} .searchable=${!0} .options=${e.modelDialog.options} .selectedValue=${e.modelDialog.selectedValue} .onPick=${t=>{this.pickModel(t)}} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></command-picker>`:null}
2728
- ${e.thinkingDialog!==void 0?l`<command-picker title=${e.thinkingDialog.title} .options=${e.thinkingDialog.options} .selectedValue=${e.thinkingDialog.selectedValue} .onPick=${t=>{this.pickThinking(t)}} .onCancel=${()=>{this.setState({thinkingDialog:void 0})}}></command-picker>`:null}
2729
- ${e.authDialog!==void 0?l`<auth-dialog .state=${e.authDialog} .onChooseMethod=${t=>{this.auth.chooseLoginMethod(t)}} .onSelectProvider=${(t,i)=>{this.auth.selectLoginProvider(t,i)}} .onApiKeyInput=${t=>{this.auth.updateApiKey(t)}} .onSaveApiKey=${()=>{this.auth.saveApiKey()}} .onLogoutProvider=${t=>{this.auth.logoutProvider(t)}} .onOAuthInput=${t=>{this.auth.updateOAuthInput(t)}} .onOAuthRespond=${t=>{this.auth.respondOAuth(t)}} .onOAuthCancel=${()=>{this.auth.cancelOAuth()}} .onCancel=${()=>{this.auth.closeDialog()}}></auth-dialog>`:null}
2779
+ ${e.commandDialog!==void 0?l`<command-picker .title=${e.commandDialog.title} .options=${e.commandDialog.options} .onPick=${i=>this.sessions.respondToCommand(e.commandDialog?.requestId??"",i)} .onCancel=${()=>{this.sessions.cancelCommand()}}></command-picker>`:null}
2780
+ ${e.modelDialog!==void 0?l`<command-picker title=${e.modelDialog.title} .searchable=${!0} .options=${e.modelDialog.options} .selectedValue=${e.modelDialog.selectedValue} .onPick=${i=>{this.pickModel(i)}} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></command-picker>`:null}
2781
+ ${e.thinkingDialog!==void 0?l`<command-picker title=${e.thinkingDialog.title} .options=${e.thinkingDialog.options} .selectedValue=${e.thinkingDialog.selectedValue} .onPick=${i=>{this.pickThinking(i)}} .onCancel=${()=>{this.setState({thinkingDialog:void 0})}}></command-picker>`:null}
2782
+ ${e.authDialog!==void 0?l`<auth-dialog .state=${e.authDialog} .onChooseMethod=${i=>{this.auth.chooseLoginMethod(i)}} .onSelectProvider=${(i,s)=>{this.auth.selectLoginProvider(i,s)}} .onApiKeyInput=${i=>{this.auth.updateApiKey(i)}} .onSaveApiKey=${()=>{this.auth.saveApiKey()}} .onLogoutProvider=${i=>{this.auth.logoutProvider(i)}} .onOAuthInput=${i=>{this.auth.updateOAuthInput(i)}} .onOAuthRespond=${i=>{this.auth.respondOAuth(i)}} .onOAuthCancel=${()=>{this.auth.cancelOAuth()}} .onCancel=${()=>{this.auth.closeDialog()}}></auth-dialog>`:null}
2730
2783
  `:l`<div class="empty">${this.sessionEmptyMessage()}</div>`}
2731
2784
  </main>
2732
2785
  ${this.renderWorkspacePanelEdgeControl()}
2733
2786
  ${this.renderWorkspacePanel()}
2734
- ${e.actionPaletteOpen?l`<action-palette .actions=${this.getActions()} .onRun=${t=>{this.setState({actionPaletteOpen:!1}),this.runAction(t)}} .onCancel=${()=>{this.setState({actionPaletteOpen:!1})}}></action-palette>`:null}
2735
- ${e.projectDialogOpen?l`<project-dialog .machineId=${f(e)} .onSubmit=${(t,i)=>this.projects.addProject(t,i)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
2736
- ${e.machineDialogOpen?l`<machine-dialog .error=${e.error} .onSubmit=${t=>this.submitMachineDialog(t)} .onCancel=${()=>{this.setState({machineDialogOpen:!1})}}></machine-dialog>`:null}
2737
- ${this.sessionCleanupDialog!==void 0?l`<session-cleanup-dialog .canCleanup=${this.canCleanupSessions()} .unavailableMessage=${this.sessionCleanupUnavailableMessage()} .preview=${this.sessionCleanupDialog.preview} .previewRequest=${this.sessionCleanupDialog.previewRequest} .result=${this.sessionCleanupDialog.result} .loading=${this.sessionCleanupDialog.loading===!0} .running=${this.sessionCleanupDialog.running===!0} .error=${this.sessionCleanupDialog.error??""} .onPreview=${t=>{this.previewSessionCleanup(t)}} .onRun=${t=>{this.runSessionCleanup(t)}} .onClose=${()=>{this.closeSessionCleanupDialog()}}></session-cleanup-dialog>`:null}
2738
- ${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}
2739
- ${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}
2787
+ ${e.actionPaletteOpen?l`<action-palette .actions=${this.getActions()} .onRun=${i=>{this.setState({actionPaletteOpen:!1}),this.runAction(i)}} .onCancel=${()=>{this.setState({actionPaletteOpen:!1})}}></action-palette>`:null}
2788
+ ${e.projectDialogOpen?l`<project-dialog .machineId=${f(e)} .onSubmit=${(i,s)=>this.projects.addProject(i,s)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
2789
+ ${e.machineDialogOpen?l`<machine-dialog .error=${e.error} .onSubmit=${i=>this.submitMachineDialog(i)} .onCancel=${()=>{this.setState({machineDialogOpen:!1})}}></machine-dialog>`:null}
2790
+ ${this.sessionCleanupDialog!==void 0?l`<session-cleanup-dialog .canCleanup=${this.canCleanupSessions()} .unavailableMessage=${this.sessionCleanupUnavailableMessage()} .preview=${this.sessionCleanupDialog.preview} .previewRequest=${this.sessionCleanupDialog.previewRequest} .result=${this.sessionCleanupDialog.result} .loading=${this.sessionCleanupDialog.loading===!0} .running=${this.sessionCleanupDialog.running===!0} .error=${this.sessionCleanupDialog.error??""} .onPreview=${i=>{this.previewSessionCleanup(i)}} .onRun=${i=>{this.runSessionCleanup(i)}} .onClose=${()=>{this.closeSessionCleanupDialog()}}></session-cleanup-dialog>`:null}
2791
+ ${e.themeDialog!==void 0?l`<command-picker title=${e.themeDialog.title} .options=${e.themeDialog.options} .selectedValue=${e.themeDialog.selectedValue} .onPick=${i=>{this.pickTheme(i)}} .onCancel=${()=>{this.setState({themeDialog:void 0})}}></command-picker>`:null}
2792
+ ${this.settingsSection!==void 0?l`<settings-dialog .section=${this.settingsSection} .actions=${this.getDefaultActions()} .onNavigate=${i=>{this.navigateSettings(i)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${i=>{this.applyClientConfig(i)}}></settings-dialog>`:null}
2793
+ ${this.normalAuthDialogMode==="change"?this.renderNormalAuthDialog("change"):null}
2740
2794
  </div>
2741
- `}};re.styles=N0;ve([x()],re.prototype,"state",2);ve([B("chat-view")],re.prototype,"chatView",2);ve([B("prompt-editor")],re.prototype,"promptEditor",2);ve([B("app-navigation-panel")],re.prototype,"navigationPanel",2);ve([B("#navigation-panel")],re.prototype,"navigationPanelFrame",2);ve([B("#workspace-panel")],re.prototype,"workspacePanelFrame",2);ve([x()],re.prototype,"activeThemeId",2);ve([x()],re.prototype,"isRefreshingApp",2);ve([x()],re.prototype,"sessionCleanupDialog",2);ve([x()],re.prototype,"settingsSection",2);ve([x()],re.prototype,"shortcutConfig",2);ve([x()],re.prototype,"workspaceUploadDefaultFolder",2);re=ve([W("pi-web-app")],re);function J0(){const e=new am;return e.register({id:"core",plugin:qg}),e.register({id:"themes",plugin:Gg}),e}function Q0(){const e=ul()?"management":"normal";return Vc(e),e}function da(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 Z0(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function X0(e,t){return nc(e,t)}function nc(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function Y0(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function pa(e){return Ye(e.status,e.activity)}function ex(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function ha(){return{}}function ua(e,t){return JSON.stringify([e,t])}function tx(e){const t=Math.min(e,cr.length-1);return cr[t]??3e4}function Us(e){return e instanceof Error?e.message:String(e)}function ix(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function zs(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function sx(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{E as a,l as b,yt as c,mx as d,fx as e,B as f,A as i,d as n,x as r,gx as s,W as t};
2795
+ `}renderNormalAuthDialog(e){return l`
2796
+ <normal-auth-dialog
2797
+ .mode=${e}
2798
+ .loading=${this.normalAuthLoading}
2799
+ .error=${this.normalAuthError}
2800
+ .onSubmit=${t=>{this.submitNormalAuth(t)}}
2801
+ .onCancel=${()=>{this.normalAuthDialogMode=void 0,this.normalAuthError=""}}
2802
+ ></normal-auth-dialog>
2803
+ `}};K.styles=X0;Z([w()],K.prototype,"state",2);Z([B("chat-view")],K.prototype,"chatView",2);Z([B("prompt-editor")],K.prototype,"promptEditor",2);Z([B("app-navigation-panel")],K.prototype,"navigationPanel",2);Z([B("#navigation-panel")],K.prototype,"navigationPanelFrame",2);Z([B("#workspace-panel")],K.prototype,"workspacePanelFrame",2);Z([w()],K.prototype,"activeThemeId",2);Z([w()],K.prototype,"isRefreshingApp",2);Z([w()],K.prototype,"sessionCleanupDialog",2);Z([w()],K.prototype,"settingsSection",2);Z([w()],K.prototype,"normalAuthStatus",2);Z([w()],K.prototype,"normalAuthLoading",2);Z([w()],K.prototype,"normalAuthError",2);Z([w()],K.prototype,"normalAuthDialogMode",2);Z([w()],K.prototype,"shortcutConfig",2);Z([w()],K.prototype,"workspaceUploadDefaultFolder",2);K=Z([W("pi-web-app")],K);function rx(){const e=new um;return e.register({id:"core",plugin:Qg}),e.register({id:"themes",plugin:em}),e}function ox(){const e=vl()?"management":"normal";return Zc(e),e}function fa(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 nx(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function ax(e,t){return dc(e,t)}function dc(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function lx(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function ga(e){return tt(e.status,e.activity)}function cx(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function ma(){return{}}function va(e,t){return JSON.stringify([e,t])}function dx(e){const t=Math.min(e,ur.length-1);return ur[t]??3e4}function Ht(e){return e instanceof Error?e.message:String(e)}function px(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function qs(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function hx(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,$t as c,Px as d,kx as e,B as f,R as i,d as n,w as r,$x as s,W as t};