@chainingintention/pi-web-cn 1.202606.14 → 1.202606.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,27 +1,27 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-D5OA_6r4.js","assets/vendor-editor-core-B4Sq6exx.js","assets/vendor-editor-languages-DznYbTkJ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-kfPHfhUe.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
- import{Q as Rr,w as ot,J as Ki,R as Ga,S as Ja,G as Qa,U as Za,V as Xa,A as Ya,W as ec,X as tc,Y as ic,Z as Ir,x as Cr,_ as sc}from"./vendor-editor-core-B4Sq6exx.js";import{m as rc,i as oc,d as nc}from"./vendor-editor-languages-DznYbTkJ.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 ri=globalThis,zs=ri.ShadowRoot&&(ri.ShadyCSS===void 0||ri.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Bs=Symbol(),Mr=new WeakMap;let hn=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==Bs)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(zs&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=Mr.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&Mr.set(i,t))}return t}toString(){return this.cssText}};const ac=e=>new hn(typeof e=="string"?e:e+"",void 0,Bs),_=(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 hn(i,e,Bs)},cc=(e,t)=>{if(zs)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),r=ri.litNonce;r!==void 0&&s.setAttribute("nonce",r),s.textContent=i.cssText,e.appendChild(s)}},Tr=zs?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return ac(i)})(e):e;const{is:lc,defineProperty:dc,getOwnPropertyDescriptor:pc,getOwnPropertyNames:hc,getOwnPropertySymbols:uc,getPrototypeOf:fc}=Object,Di=globalThis,Ar=Di.trustedTypes,gc=Ar?Ar.emptyScript:"",mc=Di.reactiveElementPolyfillSupport,Mt=(e,t)=>e,pi={toAttribute(e,t){switch(t){case Boolean:e=e?gc: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}},Us=(e,t)=>!lc(e,t),Er={attribute:!0,type:String,converter:pi,reflect:!1,useDefault:!1,hasChanged:Us};Symbol.metadata??=Symbol("metadata"),Di.litPropertyMetadata??=new WeakMap;let ct=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=Er){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&&dc(this.prototype,t,r)}}static getPropertyDescriptor(t,i,s){const{get:r,set:o}=pc(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)??Er}static _$Ei(){if(this.hasOwnProperty(Mt("elementProperties")))return;const t=fc(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Mt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Mt("properties"))){const i=this.properties,s=[...hc(i),...uc(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(Tr(r))}else t!==void 0&&i.push(Tr(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 cc(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:pi).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:pi;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??Us)(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){}};ct.elementStyles=[],ct.shadowRootOptions={mode:"open"},ct[Mt("elementProperties")]=new Map,ct[Mt("finalized")]=new Map,mc?.({ReactiveElement:ct}),(Di.reactiveElementVersions??=[]).push("2.1.2");const Hs=globalThis,Dr=e=>e,hi=Hs.trustedTypes,Wr=hi?hi.createPolicy("lit-html",{createHTML:e=>e}):void 0,un="$lit$",Be=`lit$${Math.random().toFixed(9).slice(2)}$`,fn="?"+Be,vc=`<${fn}>`,Ze=document,Et=()=>Ze.createComment(""),Dt=e=>e===null||typeof e!="object"&&typeof e!="function",qs=Array.isArray,bc=e=>qs(e)||typeof e?.[Symbol.iterator]=="function",Vi=`[
3
- \f\r]`,bt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,_r=/-->/g,Or=/>/g,qe=RegExp(`>|${Vi}(?:([^\\s"'>=/]+)(${Vi}*=${Vi}*(?:[^
4
- \f\r"'\`<>=]|("|')|))|$)`,"g"),Lr=/'/g,jr=/"/g,gn=/^(?:script|style|textarea|title)$/i,mn=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),c=mn(1),ue=mn(2),Ue=Symbol.for("lit-noChange"),F=Symbol.for("lit-nothing"),Fr=new WeakMap,Je=Ze.createTreeWalker(Ze,129);function vn(e,t){if(!qs(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Wr!==void 0?Wr.createHTML(t):t}const wc=(e,t)=>{const i=e.length-1,s=[];let r,o=t===2?"<svg>":t===3?"<math>":"",n=bt;for(let a=0;a<i;a++){const l=e[a];let p,u,h=-1,g=0;for(;g<l.length&&(n.lastIndex=g,u=n.exec(l),u!==null);)g=n.lastIndex,n===bt?u[1]==="!--"?n=_r:u[1]!==void 0?n=Or:u[2]!==void 0?(gn.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=qe):u[3]!==void 0&&(n=qe):n===qe?u[0]===">"?(n=r??bt,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?qe:u[3]==='"'?jr:Lr):n===jr||n===Lr?n=qe:n===_r||n===Or?n=bt:(n=qe,r=void 0);const w=n===qe&&e[a+1].startsWith("/>")?" ":"";o+=n===bt?l+vc:h>=0?(s.push(p),l.slice(0,h)+un+l.slice(h)+Be+w):l+Be+(h===-2?a:w)}return[vn(e,o+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Wt{constructor({strings:t,_$litType$:i},s){let r;this.parts=[];let o=0,n=0;const a=t.length-1,l=this.parts,[p,u]=wc(t,i);if(this.el=Wt.createElement(p,s),Je.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(r=Je.nextNode())!==null&&l.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const h of r.getAttributeNames())if(h.endsWith(un)){const g=u[n++],w=r.getAttribute(h).split(Be),P=/([.?@])?(.*)/.exec(g);l.push({type:1,index:o,name:P[2],strings:w,ctor:P[1]==="."?Sc:P[1]==="?"?xc:P[1]==="@"?kc:Wi}),r.removeAttribute(h)}else h.startsWith(Be)&&(l.push({type:6,index:o}),r.removeAttribute(h));if(gn.test(r.tagName)){const h=r.textContent.split(Be),g=h.length-1;if(g>0){r.textContent=hi?hi.emptyScript:"";for(let w=0;w<g;w++)r.append(h[w],Et()),Je.nextNode(),l.push({type:2,index:++o});r.append(h[g],Et())}}}else if(r.nodeType===8)if(r.data===fn)l.push({type:2,index:o});else{let h=-1;for(;(h=r.data.indexOf(Be,h+1))!==-1;)l.push({type:7,index:o}),h+=Be.length-1}o++}}static createElement(t,i){const s=Ze.createElement("template");return s.innerHTML=t,s}}function dt(e,t,i=e,s){if(t===Ue)return t;let r=s!==void 0?i._$Co?.[s]:i._$Cl;const o=Dt(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=dt(e,r._$AS(e,t.values),r,s)),t}class yc{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??Ze).importNode(i,!0);Je.currentNode=r;let o=Je.nextNode(),n=0,a=0,l=s[0];for(;l!==void 0;){if(n===l.index){let p;l.type===2?p=new ut(o,o.nextSibling,this,t):l.type===1?p=new l.ctor(o,l.name,l.strings,this,t):l.type===6&&(p=new $c(o,this,t)),this._$AV.push(p),l=s[++a]}n!==l?.index&&(o=Je.nextNode(),n++)}return Je.currentNode=Ze,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 ut{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,r){this.type=2,this._$AH=F,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=dt(this,t,i),Dt(t)?t===F||t==null||t===""?(this._$AH!==F&&this._$AR(),this._$AH=F):t!==this._$AH&&t!==Ue&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):bc(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==F&&Dt(this._$AH)?this._$AA.nextSibling.data=t:this.T(Ze.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=Wt.createElement(vn(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(i);else{const o=new yc(r,this),n=o.u(this.options);o.p(i),this.T(n),this._$AH=o}}_$AC(t){let i=Fr.get(t.strings);return i===void 0&&Fr.set(t.strings,i=new Wt(t)),i}k(t){qs(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 ut(this.O(Et()),this.O(Et()),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=Dr(t).nextSibling;Dr(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Wi=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,r,o){this.type=1,this._$AH=F,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=F}_$AI(t,i=this,s,r){const o=this.strings;let n=!1;if(o===void 0)t=dt(this,t,i,0),n=!Dt(t)||t!==this._$AH&&t!==Ue,n&&(this._$AH=t);else{const a=t;let l,p;for(t=o[0],l=0;l<o.length-1;l++)p=dt(this,a[s+l],i,l),p===Ue&&(p=this._$AH[l]),n||=!Dt(p)||p!==this._$AH[l],p===F?t=F:t!==F&&(t+=(p??"")+o[l+1]),this._$AH[l]=p}n&&!r&&this.j(t)}j(t){t===F?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Sc=class extends Wi{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===F?void 0:t}},xc=class extends Wi{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==F)}},kc=class extends Wi{constructor(t,i,s,r,o){super(t,i,s,r,o),this.type=5}_$AI(t,i=this){if((t=dt(this,t,i,0)??F)===Ue)return;const s=this._$AH,r=t===F&&s!==F||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,o=t!==F&&(s===F||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)}};class $c{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){dt(this,t)}}const Pc={I:ut},Rc=Hs.litHtmlPolyfillSupport;Rc?.(Wt,ut),(Hs.litHtmlVersions??=[]).push("3.3.2");const Ic=(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 ut(t.insertBefore(Et(),o),o,void 0,i??{})}return r._$AI(e),r};const Ks=globalThis;let M=class extends ct{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=Ic(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ue}};M._$litElement$=!0,M.finalized=!0,Ks.litElementHydrateSupport?.({LitElement:M});const Cc=Ks.litElementPolyfillSupport;Cc?.({LitElement:M});(Ks.litElementVersions??=[]).push("4.2.2");const E=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const Mc={attribute:!0,type:String,converter:pi,reflect:!1,hasChanged:Us},Tc=(e=Mc,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 l=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,l,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 l=this[n];t.call(this,a),this.requestUpdate(n,l,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?Tc(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 y(e){return d({...e,state:!0,attribute:!1})}const Ac=(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 Ac(i,s,{get(){return o(this)}})}}function bn(e,t=Dc()){if(t===void 0)return e;const i=Ec(t);if(i===void 0)return e;const s=new URL(e,t.origin);return s.searchParams.set("embed",i.embed),s.searchParams.set("token",i.token),`${s.pathname}${s.search}${s.hash}`}function Ec(e){const t=e.searchParams.get("embed"),i=e.searchParams.get("token")?.trim();if(!(t!=="management"||i===void 0||i===""))return{embed:t,token:i}}function Dc(){if(typeof globalThis.location>"u")return;const e=globalThis.location;if(typeof e.href=="string"&&e.href!=="")return new URL(e.href);const t=typeof e.protocol=="string"&&e.protocol!==""?e.protocol:"http:",i=typeof e.host=="string"&&e.host!==""?e.host:"localhost",s=typeof e.search=="string"?e.search:"";return new URL(`${t}//${i}/${s}`)}async function v(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const r=await fetch(bn(e),{...i,headers:s});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(Wc(n)??r.statusText)}const o=await r.json();return t(o)}function Wc(e){if(_c(e))return typeof e.error=="string"?e.error:void 0}function _c(e){return typeof e=="object"&&e!==null}const pt={sessionsDeleteArchived:"sessions.deleteArchived",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments"},Oc=Object.values(pt),Lc=new Set(Oc);function jc(e){return typeof e=="string"&&Lc.has(e)}function _t(e,t){return e?.capabilities?.includes(t)===!0}function Tt(e){return typeof e=="object"&&e!==null}function b(e){if(!Tt(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 se(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function W(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function N(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function Fc(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function Nc(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function zc(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=b(e);return{messages:Fc(t.messages),start:se(t,"start"),total:se(t,"total")}}function Bc(e){const t=b(e);return N(wn)(t.machines)}function wn(e){const t=b(e),i=qc(t,"kind"),s=$(t,"baseUrl"),r=yn(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 Uc(e){const t=b(e),i=yn(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:W(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:ui(t.web)},...t.sessiond===void 0?{}:{sessiond:ui(t.sessiond)},...s===void 0?{}:{error:s}}}function Hc(e){const t=b(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:W(t,"ok"),checkedAt:m(t,"checkedAt"),...S("packageName",$(t,"packageName")),...S("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:kn(t.components)},...t.capabilities===void 0?{}:{capabilities:Vs(t.capabilities)},...i===void 0?{}:{error:i}}}function qc(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function yn(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 Nr(e){const t=b(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function Kc(e){const t=b(e),i=$(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:W(t,"isMain"),isGitRepo:W(t,"isGitRepo"),isGitWorktree:W(t,"isGitWorktree")}}function ys(e){const t=b(e);return{path:m(t,"path"),size:se(t,"size"),modifiedAt:m(t,"modifiedAt")}}function Gi(e){const t=b(e);return{path:m(t,"path")}}function zr(e){const t=b(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function Ss(e){const t=b(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:se(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...r===void 0?{}:{archivedAt:r}}}function wt(e){const t=b(e);return{sessionId:m(t,"sessionId"),isStreaming:W(t,"isStreaming"),isCompacting:W(t,"isCompacting"),isBashRunning:W(t,"isBashRunning"),pendingMessageCount:se(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:N(Vc)(t.queuedMessages),...S("messageCount",Pe(t,"messageCount")),tokens:Gc(t.tokens),cost:se(t,"cost"),...Zc(t.model),...dl(t.contextUsage),...S("thinkingLevel",$(t,"thinkingLevel"))}}function Vc(e){const t=b(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text"),...S("imageCount",Pe(t,"imageCount"))}}function Gc(e){const t=b(e);return{input:se(t,"input"),output:se(t,"output"),cacheRead:se(t,"cacheRead"),cacheWrite:se(t,"cacheWrite"),total:se(t,"total")}}function Sn(e){const t=b(e);return{...S("provider",$(t,"provider")),...S("id",$(t,"id")),...S("name",$(t,"name")),...S("contextWindow",Pe(t,"contextWindow")),...S("reasoning",t.reasoning),...S("input",Jc(t.input))}}function Jc(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Invalid model input");return e.map(Qc)}}function Qc(e){if(e==="text"||e==="image")return e;throw new Error("Invalid model input")}function Zc(e){return e===void 0?{}:{model:Sn(e)}}function Xc(e){const t=b(e);return{models:N(Sn)(t.models)}}function Yc(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function el(e){const t=b(e);return{levels:N(Yc)(t.levels)}}function tl(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function il(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 sl(e){const t=b(e),i=t.source===void 0?void 0:il(t.source);return{configured:W(t,"configured"),...S("source",i),...S("label",$(t,"label"))}}function rl(e){const t=b(e);return{id:m(t,"id"),name:m(t,"name"),authType:tl(t.authType),status:sl(t.status)}}function ol(e){const t=b(e);return{providers:N(rl)(t.providers)}}function Vt(e){const t=b(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:nl(t.status),progress:N(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...S("error",$(t,"error")),...S("auth",al(t.auth)),...S("prompt",cl(t.prompt)),...S("select",ll(t.select))}}function nl(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function al(e){if(e===void 0)return;const t=b(e);return{url:m(t,"url"),...S("instructions",$(t,"instructions"))}}function cl(e){if(e===void 0)return;const t=b(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...S("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function ll(e){if(e===void 0)return;const t=b(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:N(Pn)(t.options)}}function dl(e){if(e===void 0)return{};const t=b(e);return{contextUsage:{tokens:Gr(t,"tokens"),contextWindow:se(t,"contextWindow"),percent:Gr(t,"percent")}}}function pl(e){const t=b(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...S("description",$(t,"description"))}}function xn(e){const t=b(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function hl(e){const t=b(e);return{path:m(t,"path"),entries:N(ul)(t.entries),scannedAt:m(t,"scannedAt"),truncated:W(t,"truncated")}}function ul(e){const t=b(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...S("size",Pe(t,"size")),...S("modifiedAt",$(t,"modifiedAt"))}}function fl(e){const t=b(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...S("language",$(t,"language")),...S("mediaType",gl(t.mediaType)),...S("mimeType",$(t,"mimeType")),encoding:i,size:se(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:W(t,"truncated"),binary:W(t,"binary")}}function gl(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function ml(e){const t=b(e);return{isGitRepo:W(t,"isGitRepo"),hash:m(t,"hash"),...S("branch",$(t,"branch")),...S("upstream",$(t,"upstream")),...S("ahead",Pe(t,"ahead")),...S("behind",Pe(t,"behind")),files:N(vl)(t.files)}}function vl(e){const t=b(e);return{path:m(t,"path"),...S("oldPath",$(t,"oldPath")),index:Br(t.index),workingTree:Br(t.workingTree)}}function Br(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 bl(e){const t=b(e);return{...S("path",$(t,"path")),staged:W(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:W(t,"truncated")}}function Ji(e){const t=b(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:W(t,"exited"),...S("exitCode",Pe(t,"exitCode")),...S("commandRunId",$(t,"commandRunId"))}}function At(e){const t=b(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:wl(t.status),...S("exitCode",Pe(t,"exitCode")),createdAt:m(t,"createdAt"),...S("startedAt",$(t,"startedAt")),...S("completedAt",$(t,"completedAt")),metadata:yl(t.metadata,"metadata")}}function wl(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function yl(e,t){const i=b(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 Sl(e){const t=b(e);return{cwd:m(t,"cwd"),hasSessionActivity:W(t,"hasSessionActivity"),hasTerminalActivity:W(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function xl(e){const t=b(e);return{workspaces:N(Sl)(t.workspaces),generatedAt:m(t,"generatedAt")}}function Ur(e){const t=b(e);return{path:m(t,"path"),exists:W(t,"exists"),config:Hr(t.config),effectiveConfig:Hr(t.effectiveConfig),envOverrides:Rl(t.envOverrides)}}function Hr(e){const t=b(e);return{...S("host",$(t,"host")),...S("port",Pe(t,"port")),...S("allowedHosts",kl(t.allowedHosts)),...S("shortcuts",$l(t.shortcuts)),...S("plugins",Pl(t.plugins)),...S("spawnSessions",Gl(t,"spawnSessions"))}}function kl(e){if(e!==void 0){if(e===!0)return!0;if(Array.isArray(e)&&e.every(t=>typeof t=="string"))return e;throw new Error("Invalid PI WEB allowedHosts field")}}function $l(e){if(e!==void 0){if(!Tt(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 Pl(e){if(e!==void 0){if(!Tt(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!Tt(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&&(!Tt(r)||Array.isArray(r)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Rl(e){const t=b(e);return{host:W(t,"host"),port:W(t,"port"),allowedHosts:W(t,"allowedHosts"),spawnSessions:W(t,"spawnSessions")}}function Il(e){const t=b(e);return{plugins:N(Cl)(t.plugins)}}function Cl(e){const t=b(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:Ml(t.scope),machineSpecific:Tl(t.machineSpecific,"machineSpecific")??!1,enabled:W(t,"enabled")}}function Ml(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function Tl(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function Al(e){const t=b(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:Dl(t.components),release:_l(t.release),commands:Ol(t.commands),messages:N(Ll)(t.messages)}}function El(e){const t=b(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:kn(t.components),capabilities:Vs(t.capabilities)}}function Dl(e){const t=b(e);return{web:ui(t.web),sessiond:ui(t.sessiond)}}function kn(e){const t=b(e);return{web:qr(t.web),sessiond:qr(t.sessiond)}}function qr(e){const t=b(e);return{component:$n(t.component),label:m(t,"label"),...S("runtimeVersion",$(t,"runtimeVersion")),available:W(t,"available"),capabilities:Vs(t.capabilities),...S("error",$(t,"error"))}}function ui(e){const t=b(e);return{component:$n(t.component),label:m(t,"label"),...S("runtimeVersion",$(t,"runtimeVersion")),...S("installedVersion",$(t,"installedVersion")),stale:W(t,"stale"),available:W(t,"available"),...S("installation",Wl(t.installation)),...S("error",$(t,"error"))}}function Wl(e){if(e===void 0)return;const t=b(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");return{kind:i,...S("path",$(t,"path")),...S("source",$(t,"source")),...s===void 0?{}:{scope:s},...S("npmRoot",$(t,"npmRoot"))}}function _l(e){const t=b(e);return{packageName:m(t,"packageName"),...S("latestVersion",$(t,"latestVersion")),updateAvailable:W(t,"updateAvailable"),...S("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...S("error",$(t,"error"))}}function Ol(e){const t=b(e);return{...S("update",$(t,"update")),...S("restart",$(t,"restart")),...S("restartWeb",$(t,"restartWeb")),...S("restartSessiond",$(t,"restartSessiond")),...S("status",$(t,"status"))}}function Ll(e){const t=b(e);return{id:m(t,"id"),severity:jl(t.severity),title:m(t,"title"),body:m(t,"body"),...S("command",$(t,"command"))}}function $n(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Vs(e){if(!Array.isArray(e)||!e.every(jc))throw new Error("Invalid PI WEB capabilities");return e}function jl(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Kr(e){const t=b(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:N(Pn)(t.options)};if(i==="done")return{type:i,...S("message",$(t,"message")),...Fl(t.session),...S("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function Pn(e){const t=b(e);return{value:m(t,"value"),label:m(t,"label"),...S("description",$(t,"description"))}}function Fl(e){return e===void 0?{}:{session:Ss(e)}}function Gt(e){if(b(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function Nl(e){const t=b(e);return N(zl)(t.attachments)}function zl(e){const t=b(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:se(t,"size")}}function xs(e){if(b(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function Bl(e){if(b(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function Ul(e){if(b(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Vr(e){const t=b(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:Nc(t.sessionIds,"sessionIds"),s=Pe(t,"archivedCount"),r=Pe(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...r===void 0?{}:{skippedAlreadyArchivedCount:r}}}function Hl(e){if(b(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function ql(e){if(b(e).deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0}}function Kl(e){if(b(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Vl(e){if(b(e).reloaded!==!0)throw new Error("Expected reloaded response");return{reloaded:!0}}function Gl(e,t){const i=e[t];if(i!==void 0){if(typeof i!="boolean")throw new Error(`Invalid PI WEB ${t} field`);return i}}function Pe(e,t){const i=e[t];if(i!==void 0){if(typeof i!="number")throw new Error(`Expected optional number field: ${t}`);return i}}function Gr(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 S(e,t){return t===void 0?{}:{[e]:t}}function Jl(e){return typeof e=="string"?e:e.id}function Ql(e){return typeof e=="string"?void 0:e.cwd}function Zl(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 Xl(e,t,i="local"){const s=new URLSearchParams,r=Ql(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(Jl(e))}/messages${o===""?"":`?${o}`}`}function Yl(e,t,i,s){const r=new URLSearchParams;return r.set("path",i),s?.modifiedAt!==void 0&&r.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${r.toString()}`}function Rn(e,t,i,s){const r=new URLSearchParams;r.set("path",i);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return bn(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${r.toString()}`)}const R=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function ed(e){return typeof e=="string"?e:e.id}function In(e){return typeof e=="string"?void 0:e.cwd}function Cn(e,t="local"){return`${R(t)}/sessions/${encodeURIComponent(ed(e))}`}function V(e,t,i="local"){return`${Cn(e,i)}/${t}`}function Jt(e,t,i="local"){return`${V(e,t,i)}${Mn(e)}`}function td(e,t="local"){return`${Cn(e,t)}${Mn(e)}`}function Mn(e){const t=In(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function J(e,t={}){const i=In(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}const Tn={piWebStatus:(e="local")=>v(e==="local"?"/api/pi-web/status":`${R(e)}/pi-web/status`,Al),piWebRuntime:()=>v("/api/pi-web/runtime",El)},id={machines:()=>v("/api/machines",Bc),addMachine:e=>v("/api/machines",wn,{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`,Uc),runtime:e=>v(`/api/machines/${encodeURIComponent(e)}/runtime`,Hc)},fi={config:()=>v("/api/config",Ur),saveConfig:e=>v("/api/config",Ur,{method:"PUT",body:JSON.stringify({config:e})})},ks={plugins:()=>v("/api/plugins",Il)},An={workspaceActivity:(e="local")=>v(`${R(e)}/activity`,xl)},sd={projects:(e="local")=>v(`${R(e)}/projects`,N(Nr)),addProject:(e,t,i,s="local")=>v(`${R(s)}/projects`,Nr,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>v(`${R(t)}/projects/${encodeURIComponent(e)}`,xs,{method:"DELETE"}),projectDirectories:(e,t="local")=>v(`${R(t)}/project-directories?q=${encodeURIComponent(e)}`,N(xn))},$s={workspaces:(e,t="local")=>v(`${R(t)}/projects/${e}/workspaces`,N(Kc)),deleteWorkspace:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,At,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,hl),workspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,fl),uploadWorkspaceFile:async(e,t,i,s,r="local")=>r==="local"?ld(e,t,i,s):v(`${R(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,ys,{method:"POST",body:JSON.stringify({path:i,contentBase64:await ad(s)})}),createWorkspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,ys,{method:"POST",body:JSON.stringify({path:i,contentBase64:""})}),moveWorkspaceFile:(e,t,i,s,r="local")=>v(`${R(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Gi,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,zr,{method:"DELETE"}),createWorkspaceDirectory:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Gi,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,r="local")=>v(`${R(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Gi,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,zr,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>Rn(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>dd(e,t,i,s)},rd={sessions:(e,t="local")=>v(`${R(t)}/sessions?cwd=${encodeURIComponent(e)}`,N(Ss)),startSession:(e,t="local")=>v(`${R(t)}/sessions`,Ss,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>v(Xl(e,t,i),zc),status:(e,t="local")=>v(Jt(e,"status",t),wt),models:(e,t="local")=>v(Jt(e,"models",t),Xc),setModel:(e,t,i,s="local")=>v(V(e,"model",s),wt,{method:"POST",body:J(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>v(V(e,"model/cycle",i),wt,{method:"POST",body:J(e,{direction:t})}),thinkingLevels:(e,t="local")=>v(Jt(e,"thinking-levels",t),el),setThinkingLevel:(e,t,i="local")=>v(V(e,"thinking-level",i),wt,{method:"POST",body:J(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>v(V(e,"thinking-level/cycle",t),wt,{method:"POST",body:J(e)}),commands:(e,t="local")=>v(Jt(e,"commands",t),N(pl)),prompt:(e,t,i,s="local",r)=>v(V(e,"prompt",s),Gt,{method:"POST",body:J(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...r!==void 0&&r.length>0?{attachments:r}:{}})}),saveAttachments:(e,t,i="local",s)=>v(V(e,"attachments",i),Nl,{method:"POST",body:J(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>v(V(e,"shell",i),Gt,{method:"POST",body:J(e,{text:t})}),runCommand:(e,t,i="local")=>v(V(e,"commands/run",i),Kr,{method:"POST",body:J(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>v(V(e,"commands/respond",s),Kr,{method:"POST",body:J(e,{requestId:t,value:i})}),abort:(e,t="local")=>v(V(e,"abort",t),Bl,{method:"POST",body:J(e)}),stop:(e,t="local")=>v(V(e,"stop",t),Ul,{method:"POST",body:J(e)}),archive:(e,t="local")=>v(V(e,"archive",t),Vr,{method:"POST",body:J(e)}),archiveWithDescendants:(e,t="local")=>v(V(e,"archive-tree",t),Vr,{method:"POST",body:J(e)}),restore:(e,t="local")=>v(V(e,"restore",t),Hl,{method:"POST",body:J(e)}),deleteArchived:(e,t="local")=>v(td(e,t),ql,{method:"DELETE"}),detachParent:(e,t="local")=>v(V(e,"detach-parent",t),Kl,{method:"POST",body:J(e)}),reloadSession:(e,t="local")=>v(V(e,"reload",t),Vl,{method:"POST",body:J(e)}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return v(`${R(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,ol)},saveApiKey:(e,t,i="local")=>v(`${R(i)}/auth/api-key`,Gt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>v(`${R(t)}/auth/logout`,Gt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>v(`${R(t)}/auth/oauth`,Vt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>v(`${R(t)}/auth/oauth/${encodeURIComponent(e)}`,Vt),respondOAuthFlow:(e,t,i,s="local")=>v(`${R(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Vt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>v(`${R(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Vt,{method:"POST"})},lt={terminals:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,N(Ji)),startTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Ji,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,xs,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,xs,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Ji,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,At,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>v(`${R(t)}/terminal-command-runs${nd(e)}`,N(At)),getCommandRun:(e,t="local")=>od(e,t),cancelCommandRun:(e,t="local")=>v(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,At,{method:"POST"})};async function od(e,t){const i=await fetch(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Gs(s)??i.statusText)}return At(await i.json())}}function nd(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 Gs(e){if(!pd(e))return;const t=e.error;return typeof t=="string"?t:void 0}async function ad(e){return cd(await e.arrayBuffer())}function cd(e){const t=new Uint8Array(e);let i="";for(const s of t)i+=String.fromCharCode(s);return btoa(i)}async function ld(e,t,i,s){const r=new FormData;r.set("path",i),r.set("file",s,s.name);const o=await fetch(`${R("local")}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,{method:"POST",body:r});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(Gs(n)??o.statusText)}return ys(await o.json())}async function dd(e,t,i,s){const r=await fetch(Rn(e,t,i,{machineId:s}));if(!r.ok){const p=await r.json().catch(()=>({}));throw new Error(Gs(p)??r.statusText)}const o=await r.blob(),n=URL.createObjectURL(o),a=document.createElement("a");a.href=n;const l=i.split("/").pop();a.download=l===void 0||l===""?"download":l,document.body.append(a),a.click(),a.remove(),URL.revokeObjectURL(n)}function pd(e){return typeof e=="object"&&e!==null}const hd={files:(e,t,i={})=>{const s=new URLSearchParams({cwd:e,q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),v(`${R(i.machineId)}/files?${s.toString()}`,N(xn))}},ud={gitStatus:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,ml),gitDiff:(e,t,i,s="local")=>v(Zl(s,e,t,i),bl)},z={...Tn,...id,...fi,...ks,...An,...sd,...$s,...rd,...lt,...hd,...ud};function fd(e,t="local"){const i=typeof e=="string"?void 0:e.cwd,s=i===void 0||i===""?"":`?${new URLSearchParams({cwd:i}).toString()}`,r=typeof e=="string"?e:e.id;return new WebSocket(`${Qs()}${Js(t)}/sessions/${encodeURIComponent(r)}/events${s}`)}function qw(e,t,i,s,r="local"){const o=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Qs()}${Js(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${o}`)}function gd(e="local"){return new WebSocket(`${Qs()}${Js(e)}/events`)}function Js(e){return`/api/machines/${encodeURIComponent(e)}`}function Qs(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function oi(){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 md(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Xe(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function En(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const Dn="local";function Qi(e,t){return`${e}:${t}`}function Wn(e,t){return`${e}:${t}`}function f(e){return e.selectedMachine?.id??Dn}class vd{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??An}async refresh(t=f(this.getState())){this.applyMachineActivitySnapshot(t,bd(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=wd(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 bd(e){const t={};for(const i of e.workspaces)En(i)&&(t[i.cwd]=i);return t}function wd(e,t){const i={...e};return En(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class yd{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=r.api??z,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=Sd(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:"",l=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:l}})}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 Sd(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 xd(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 Zi(e,t){const i=xd(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function le(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));kd(r,s)}function kd(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}const Qt=jt("core:workspace.files");class $d{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.api=r.api??z}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=f(this.getState()),r=await this.api.workspaceTree(t.id,i.id,"",s),o=await Promise.all(Object.keys(this.getState().expandedDirs).map(async a=>{try{const l=await this.api.workspaceTree(t.id,i.id,a,s);return[a,l.entries]}catch(l){if(Jr(l))return;throw l}})),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:Pd(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"}),le(Qt,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}selectDirectory(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),le(Qt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}async restoreFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){this.setState({selectedFilePath:t,selectedFileContent:void 0});try{const 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(Jr(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),le(Qt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}async uploadFiles(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t.length===0))try{const r=f(this.getState()),o=Rd(this.getState()),n=[];for(const l of t){const p=Cd(o,Id(l));await this.api.uploadWorkspaceFile(i.id,s.id,p,l,r),n.push(p)}await this.refreshFiles();const a=n.at(-1);a!==void 0&&await this.selectFile(a),this.setState({error:""})}catch(r){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());Xi(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,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());Xi(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===""||Xi(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}),le(Qt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}}function Jr(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function Pd(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Rd(e){const t=e.selectedFilePath;if(t===void 0||t==="")return"";if(_n(e.fileTree,e.expandedDirs,t)?.type==="directory")return t;const s=t.lastIndexOf("/");return s===-1?"":t.slice(0,s)}function Xi(e){const t=e.selectedFilePath;return t===void 0?"file":_n(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function _n(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 Id(e){return e.name.split(/[\\/]+/u).filter(t=>t!=="").at(-1)??e.name}function Cd(e,t){return e===""?t:`${e}/${t}`}const Qr=jt("core:workspace.git");class Md{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await z.gitStatus(t.id,i.id,f(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const 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}),le(Qr,"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"}),le(Qr,"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([z.gitDiff(i.id,s.id,{path:t},f(this.getState())),z.gitDiff(i.id,s.id,{path:t,staged:!0},f(this.getState()))]);this.setState({selectedDiff: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 Td{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 z.machines(),s=await this.selectInitialMachine(i,t),r=new Set(i.map(o=>o.id));this.setState({machines:i,selectedMachine:s,machineActivities:Zr(this.getState().machineActivities,r),machineRuntimes:Zr(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,...oi()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await z.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await z.deleteMachine(t.id);const 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:Yi(this.getState().machineStatuses,t.id),machineRuntimes:Yi(this.getState().machineRuntimes,t.id),machineActivities:Yi(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 z.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await z.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(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 z.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(r=>z.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=>z.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 Yi(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Zr(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class Ad{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=f(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await z.projects(t);if(f(this.getState())!==t)return;const s=new Set(i.map(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 z.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 z.closeProject(t,f(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const Ps="pi-web:cached-new-sessions:v1",Ed="browserCachedNew",ft="local";function Ft(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Xr(e,t=ft,i=Ft()){if(e.messageCount!==0||e.archived===!0)return;const s=Zs(i).filter(r=>r.id!==e.id||r.machineId!==t);Xs([Rs(e,t),...s],i)}function Rs(e,t=ft){return{...e,browserCachedNew:!0,machineId:t}}function Yr(e,t=ft,i=Ft()){const s=Zs(i).filter(r=>r.id!==e||r.machineId!==t);Xs(s,i)}function Dd(e,t,i=ft,s=Ft()){const r=new Set(t.map(l=>l.id)),o=Zs(s),n=o.filter(l=>l.machineId!==i||!r.has(l.id));return n.length!==o.length&&Xs(n,s),[...n.filter(l=>l.machineId===i&&l.cwd===e),...t]}function ee(e){return e===void 0?!1:Od(e)&&e.browserCachedNew===!0}function Wd(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:ft},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Zs(e=Ft()){try{const t=e?.getItem(Ps);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>_d(s)):[]}catch{return[]}}function Xs(e,t=Ft()){try{e.length===0?t?.removeItem(Ps):t?.setItem(Ps,JSON.stringify(e))}catch{}}function _d(e){if(!Ld(e))return[];const t=nt(e,"id"),i=nt(e,"path"),s=nt(e,"cwd"),r=nt(e,"created"),o=nt(e,"modified"),n=nt(e,"firstMessage"),a=jd(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 l=es(e,"name"),p=es(e,"parentSessionPath"),u=es(e,"machineId")??ft;return[{id:t,path:i,cwd:s,...l===void 0?{}:{name:l},created:r,modified:o,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function Od(e){return Ed in e}function Ld(e){return typeof e=="object"&&e!==null}function nt(e,t){const i=e[t];return typeof i=="string"?i:void 0}function es(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function jd(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Fd(e){return tp(e.flatMap(Ys)).filter(t=>t.parts.length>0)}function Ae(e,t){return{role:e,parts:[{type:"text",text:t}]}}function yt(e,t){const i=Vd(t);return i===void 0?e:{...e,meta:i}}function Nd(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,Ae(t,i)]}function zd(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 Ys(e){if(Ud(e))return[e];if(D(e,"role")==="bashExecution")return[yt(Qd(e),e)];const t=Zd(D(e,"role")),i=Xd(ge(e,"content"),e),s=t==="user"?Hd(i):void 0;if(s!==void 0)return s.map(p=>yt(p,e));const r=Kd(e);if(t==="tool")return[yt({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?[yt({role:n,parts:o,...r===void 0?{}:{source:r}},e)]:[],l=Bd(e);return l===void 0?a:[...a,yt(l,e)]}function Bd(e){if(D(e,"role")!=="assistant"||D(e,"stopReason")!=="error")return;const t=D(e,"errorMessage")?.trim();return Ae("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function Ud(e){const t=D(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(ge(e,"parts"))}function Hd(e){if(e.length!==1||e[0]?.type!=="text")return;const t=qd(e[0].text);if(t!==void 0)return[{role:"user",parts:[{type:"skillInvocation",name:t.name,location:t.location,content:t.content}]},...t.userMessage===void 0?[]:[{role:"user",parts:[{type:"text",text:t.userMessage}]}]]}function qd(e){const t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;const i=t[4]?.trim();return{name:t[1]??"skill",location:t[2]??"",content:t[3]??"",...i===void 0||i===""?{}:{userMessage:i}}}function Kd(e){const t=D(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Vd(e){const t=Gd(ge(e,"timestamp")),i=Jd(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Gd(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 Jd(e){if(D(e,"role")!=="assistant")return;const t=D(e,"provider"),i=D(e,"model"),s=D(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 Qd(e){const t=D(e,"command")??"",i=ni(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=ge(e,"output");s!=null&&i.push("",mi(s));const r=ge(e,"exitCode");r!=null&&i.push("",`exit ${mi(r)}`),ni(e,"cancelled")===!0&&i.push("","cancelled"),ni(e,"truncated")===!0&&i.push("","output truncated");const o=D(e,"fullOutputPath");return o!==void 0&&o!==""&&i.push("",`full output: ${o}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
- `)}]}}function Zd(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function Xd(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=D(i,"type"),r=D(i,"text");if(s==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(s==="thinking"){const o=D(i,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}if(s==="toolCall"){const o=D(i,"name")??"tool",n=ge(i,"arguments"),a=o==="read"?ep(D(n,"path")):void 0;if(a!==void 0)return[{type:"skillRead",...a}];const l=D(i,"id");return[{type:"toolCall",...l===void 0?{}:{toolCallId:l},toolName:o,summary:Nt(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const o=D(i,"data"),n=D(i,"mimeType");return o!==void 0&&o!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:o}]:[{type:"text",text:"[image]"}]}return eo(i)}).map(i=>i.type==="text"&&D(t,"role")==="toolResult"?Yd(i.text,t):i):eo(e)}function Yd(e,t){const i=D(t,"toolCallId"),s=ge(t,"content"),r=ge(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:D(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...r===void 0?{}:{details:r},isError:ni(t,"isError")===!0}}function ep(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 tp(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 l=ip(a),p=t.length;t.push({role:"tool",parts:[l],...o}),l.toolCallId!==void 0&&i.set(l.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const l=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(l!==void 0&&sp(t,l,a)){i.delete(a.toolCallId??"");continue}}r.push(a)}n()}return t}function ip(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 sp(e,t,i){const s=e[t.lineIndex],r=s?.parts[t.partIndex];if(s===void 0||r?.type!=="toolExecution")return!1;const o=gi(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 gi(e){const t=ge(e,"preview");if(!er(t))return;const i=D(t,"diff"),s=D(t,"error"),r=op(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 eo(e){return e==null?[]:typeof e=="object"?[{type:"text",text:Nt(e)}]:[{type:"text",text:mi(e)}]}function Nt(e){if(!er(e))return mi(e);const t=D(e,"command");if(t!==void 0)return t;const i=D(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}: ${rp(n)}`).join(" · ")}function rp(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 er(e){return typeof e=="object"&&e!==null}function ge(e,t){return er(e)?e[t]:void 0}function D(e,t){const i=ge(e,t);return typeof i=="string"?i:void 0}function ni(e,t){const i=ge(e,t);return typeof i=="boolean"?i:void 0}function op(e,t){const i=ge(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function mi(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const np="pi-web:prompt-draft:";function vi(e){return`${np}${e}`}function _i(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function On(e,t=_i()){try{return t?.getItem(vi(e))??""}catch{return""}}function bi(e,t,i=_i()){try{t?i?.setItem(vi(e),t):i?.removeItem(vi(e))}catch{}}function tr(e,t=_i()){try{t?.removeItem(vi(e))}catch{}}function ap(e,t,i=_i()){const s=On(e,i);s!==""&&(bi(t,s,i),tr(e,i))}function cp(e,t){return Ae("bash",`${t===!0?`不加入上下文
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-rwuQkhmb.js","assets/vendor-editor-core-Bc1A7SO7.js","assets/vendor-editor-languages-D0CnB2js.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-BTDv_JgG.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
+ import{Q as Co,w as rt,J as Vi,R as Za,S as Xa,G as Ya,U as ec,V as tc,A as ic,W as sc,X as oc,Y as rc,Z as Mo,x as To,_ as nc}from"./vendor-editor-core-Bc1A7SO7.js";import{m as ac,i as cc,d as lc}from"./vendor-editor-languages-D0CnB2js.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const n of r.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(o){if(o.ep)return;o.ep=!0;const r=i(o);fetch(o.href,r)}})();const ri=globalThis,Bs=ri.ShadowRoot&&(ri.ShadyCSS===void 0||ri.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Us=Symbol(),Ao=new WeakMap;let fn=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==Us)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(Bs&&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 dc=e=>new fn(typeof e=="string"?e:e+"",void 0,Us),_=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,o,r)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+e[r+1],e[0]);return new fn(i,e,Us)},pc=(e,t)=>{if(Bs)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),o=ri.litNonce;o!==void 0&&s.setAttribute("nonce",o),s.textContent=i.cssText,e.appendChild(s)}},Eo=Bs?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return dc(i)})(e):e;const{is:hc,defineProperty:uc,getOwnPropertyDescriptor:fc,getOwnPropertyNames:gc,getOwnPropertySymbols:mc,getPrototypeOf:vc}=Object,Wi=globalThis,Do=Wi.trustedTypes,bc=Do?Do.emptyScript:"",wc=Wi.reactiveElementPolyfillSupport,Tt=(e,t)=>e,hi={toAttribute(e,t){switch(t){case Boolean:e=e?bc: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}},Hs=(e,t)=>!hc(e,t),Wo={attribute:!0,type:String,converter:hi,reflect:!1,useDefault:!1,hasChanged:Hs};Symbol.metadata??=Symbol("metadata"),Wi.litPropertyMetadata??=new WeakMap;let lt=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=Wo){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const s=Symbol(),o=this.getPropertyDescriptor(t,s,i);o!==void 0&&uc(this.prototype,t,o)}}static getPropertyDescriptor(t,i,s){const{get:o,set:r}=fc(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:o,set(n){const a=o?.call(this);r?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Wo}static _$Ei(){if(this.hasOwnProperty(Tt("elementProperties")))return;const t=vc(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Tt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Tt("properties"))){const i=this.properties,s=[...gc(i),...mc(i)];for(const o of s)this.createProperty(o,i[o])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,o]of i)this.elementProperties.set(s,o)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const o=this._$Eu(i,s);o!==void 0&&this._$Eh.set(o,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const i=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const o of s)i.unshift(Eo(o))}else t!==void 0&&i.push(Eo(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 pc(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$ET(t,i){const s=this.constructor.elementProperties.get(t),o=this.constructor._$Eu(t,s);if(o!==void 0&&s.reflect===!0){const r=(s.converter?.toAttribute!==void 0?s.converter:hi).toAttribute(i,s.type);this._$Em=t,r==null?this.removeAttribute(o):this.setAttribute(o,r),this._$Em=null}}_$AK(t,i){const s=this.constructor,o=s._$Eh.get(t);if(o!==void 0&&this._$Em!==o){const r=s.getPropertyOptions(o),n=typeof r.converter=="function"?{fromAttribute:r.converter}:r.converter?.fromAttribute!==void 0?r.converter:hi;this._$Em=o;const a=n.fromAttribute(i,r.type);this[o]=a??this._$Ej?.get(o)??a,this._$Em=null}}requestUpdate(t,i,s,o=!1,r){if(t!==void 0){const n=this.constructor;if(o===!1&&(r=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??Hs)(r,i)||s.useDefault&&s.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:o,wrapped:r},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),r!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),o===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[o,r]of this._$Ep)this[o]=r;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,r]of s){const{wrapped:n}=r,a=this[o];n!==!0||this._$AL.has(o)||a===void 0||this.C(o,void 0,r,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};lt.elementStyles=[],lt.shadowRootOptions={mode:"open"},lt[Tt("elementProperties")]=new Map,lt[Tt("finalized")]=new Map,wc?.({ReactiveElement:lt}),(Wi.reactiveElementVersions??=[]).push("2.1.2");const qs=globalThis,_o=e=>e,ui=qs.trustedTypes,Lo=ui?ui.createPolicy("lit-html",{createHTML:e=>e}):void 0,gn="$lit$",Be=`lit$${Math.random().toFixed(9).slice(2)}$`,mn="?"+Be,yc=`<${mn}>`,Ze=document,Dt=()=>Ze.createComment(""),Wt=e=>e===null||typeof e!="object"&&typeof e!="function",Ks=Array.isArray,Sc=e=>Ks(e)||typeof e?.[Symbol.iterator]=="function",Gi=`[
3
+ \f\r]`,wt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Oo=/-->/g,jo=/>/g,qe=RegExp(`>|${Gi}(?:([^\\s"'>=/]+)(${Gi}*=${Gi}*(?:[^
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Fo=/'/g,zo=/"/g,vn=/^(?:script|style|textarea|title)$/i,bn=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),c=bn(1),ue=bn(2),Ue=Symbol.for("lit-noChange"),F=Symbol.for("lit-nothing"),No=new WeakMap,Je=Ze.createTreeWalker(Ze,129);function wn(e,t){if(!Ks(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Lo!==void 0?Lo.createHTML(t):t}const xc=(e,t)=>{const i=e.length-1,s=[];let o,r=t===2?"<svg>":t===3?"<math>":"",n=wt;for(let a=0;a<i;a++){const l=e[a];let p,u,h=-1,g=0;for(;g<l.length&&(n.lastIndex=g,u=n.exec(l),u!==null);)g=n.lastIndex,n===wt?u[1]==="!--"?n=Oo:u[1]!==void 0?n=jo:u[2]!==void 0?(vn.test(u[2])&&(o=RegExp("</"+u[2],"g")),n=qe):u[3]!==void 0&&(n=qe):n===qe?u[0]===">"?(n=o??wt,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?qe:u[3]==='"'?zo:Fo):n===zo||n===Fo?n=qe:n===Oo||n===jo?n=wt:(n=qe,o=void 0);const w=n===qe&&e[a+1].startsWith("/>")?" ":"";r+=n===wt?l+yc:h>=0?(s.push(p),l.slice(0,h)+gn+l.slice(h)+Be+w):l+Be+(h===-2?a:w)}return[wn(e,r+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class _t{constructor({strings:t,_$litType$:i},s){let o;this.parts=[];let r=0,n=0;const a=t.length-1,l=this.parts,[p,u]=xc(t,i);if(this.el=_t.createElement(p,s),Je.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(o=Je.nextNode())!==null&&l.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const h of o.getAttributeNames())if(h.endsWith(gn)){const g=u[n++],w=o.getAttribute(h).split(Be),P=/([.?@])?(.*)/.exec(g);l.push({type:1,index:r,name:P[2],strings:w,ctor:P[1]==="."?$c:P[1]==="?"?Pc:P[1]==="@"?Rc:_i}),o.removeAttribute(h)}else h.startsWith(Be)&&(l.push({type:6,index:r}),o.removeAttribute(h));if(vn.test(o.tagName)){const h=o.textContent.split(Be),g=h.length-1;if(g>0){o.textContent=ui?ui.emptyScript:"";for(let w=0;w<g;w++)o.append(h[w],Dt()),Je.nextNode(),l.push({type:2,index:++r});o.append(h[g],Dt())}}}else if(o.nodeType===8)if(o.data===mn)l.push({type:2,index:r});else{let h=-1;for(;(h=o.data.indexOf(Be,h+1))!==-1;)l.push({type:7,index:r}),h+=Be.length-1}r++}}static createElement(t,i){const s=Ze.createElement("template");return s.innerHTML=t,s}}function pt(e,t,i=e,s){if(t===Ue)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const r=Wt(t)?void 0:t._$litDirective$;return o?.constructor!==r&&(o?._$AO?.(!1),r===void 0?o=void 0:(o=new r(e),o._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=o:i._$Cl=o),o!==void 0&&(t=pt(e,o._$AS(e,t.values),o,s)),t}class kc{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,o=(t?.creationScope??Ze).importNode(i,!0);Je.currentNode=o;let r=Je.nextNode(),n=0,a=0,l=s[0];for(;l!==void 0;){if(n===l.index){let p;l.type===2?p=new ft(r,r.nextSibling,this,t):l.type===1?p=new l.ctor(r,l.name,l.strings,this,t):l.type===6&&(p=new Ic(r,this,t)),this._$AV.push(p),l=s[++a]}n!==l?.index&&(r=Je.nextNode(),n++)}return Je.currentNode=Ze,o}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class ft{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=F,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=o,this._$Cv=o?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=pt(this,t,i),Wt(t)?t===F||t==null||t===""?(this._$AH!==F&&this._$AR(),this._$AH=F):t!==this._$AH&&t!==Ue&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Sc(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==F&&Wt(this._$AH)?this._$AA.nextSibling.data=t:this.T(Ze.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,o=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=_t.createElement(wn(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const r=new kc(o,this),n=r.u(this.options);r.p(i),this.T(n),this._$AH=r}}_$AC(t){let i=No.get(t.strings);return i===void 0&&No.set(t.strings,i=new _t(t)),i}k(t){Ks(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,o=0;for(const r of t)o===i.length?i.push(s=new ft(this.O(Dt()),this.O(Dt()),this,this.options)):s=i[o],s._$AI(r),o++;o<i.length&&(this._$AR(s&&s._$AB.nextSibling,o),i.length=o)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=_o(t).nextSibling;_o(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let _i=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,r){this.type=1,this._$AH=F,this._$AN=void 0,this.element=t,this.name=i,this._$AM=o,this.options=r,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=F}_$AI(t,i=this,s,o){const r=this.strings;let n=!1;if(r===void 0)t=pt(this,t,i,0),n=!Wt(t)||t!==this._$AH&&t!==Ue,n&&(this._$AH=t);else{const a=t;let l,p;for(t=r[0],l=0;l<r.length-1;l++)p=pt(this,a[s+l],i,l),p===Ue&&(p=this._$AH[l]),n||=!Wt(p)||p!==this._$AH[l],p===F?t=F:t!==F&&(t+=(p??"")+r[l+1]),this._$AH[l]=p}n&&!o&&this.j(t)}j(t){t===F?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},$c=class extends _i{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===F?void 0:t}},Pc=class extends _i{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==F)}},Rc=class extends _i{constructor(t,i,s,o,r){super(t,i,s,o,r),this.type=5}_$AI(t,i=this){if((t=pt(this,t,i,0)??F)===Ue)return;const s=this._$AH,o=t===F&&s!==F||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==F&&(s===F||o);o&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Ic=class{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){pt(this,t)}};const Cc={I:ft},Mc=qs.litHtmlPolyfillSupport;Mc?.(_t,ft),(qs.litHtmlVersions??=[]).push("3.3.3");const Tc=(e,t,i)=>{const s=i?.renderBefore??t;let o=s._$litPart$;if(o===void 0){const r=i?.renderBefore??null;s._$litPart$=o=new ft(t.insertBefore(Dt(),r),r,void 0,i??{})}return o._$AI(e),o};const Vs=globalThis;let M=class extends lt{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=Tc(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ue}};M._$litElement$=!0,M.finalized=!0,Vs.litElementHydrateSupport?.({LitElement:M});const Ac=Vs.litElementPolyfillSupport;Ac?.({LitElement:M});(Vs.litElementVersions??=[]).push("4.2.2");const D=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const Ec={attribute:!0,type:String,converter:hi,reflect:!1,hasChanged:Hs},Dc=(e=Ec,t,i)=>{const{kind:s,metadata:o}=i;let r=globalThis.litPropertyMetadata.get(o);if(r===void 0&&globalThis.litPropertyMetadata.set(o,r=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const l=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,l,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 l=this[n];t.call(this,a),this.requestUpdate(n,l,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?Dc(e,t,i):((s,o,r)=>{const n=o.hasOwnProperty(r);return o.constructor.createProperty(r,s),n?Object.getOwnPropertyDescriptor(o,r):void 0})(e,t,i)}function S(e){return d({...e,state:!0,attribute:!1})}const Wc=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function B(e,t){return(i,s,o)=>{const r=n=>n.renderRoot?.querySelector(e)??null;return Wc(i,s,{get(){return r(this)}})}}function yn(e,t=Lc()){if(t===void 0)return e;const i=_c(t);if(i===void 0)return e;const s=new URL(e,t.origin);return s.searchParams.set("embed",i.embed),s.searchParams.set("token",i.token),`${s.pathname}${s.search}${s.hash}`}function _c(e){const t=e.searchParams.get("embed"),i=e.searchParams.get("token")?.trim();if(!(t!=="management"||i===void 0||i===""))return{embed:t,token:i}}function Lc(){if(typeof globalThis.location>"u")return;const e=globalThis.location;if(typeof e.href=="string"&&e.href!=="")return new URL(e.href);const t=typeof e.protocol=="string"&&e.protocol!==""?e.protocol:"http:",i=typeof e.host=="string"&&e.host!==""?e.host:"localhost",s=typeof e.search=="string"?e.search:"";return new URL(`${t}//${i}/${s}`)}async function v(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const o=await fetch(yn(e),{...i,headers:s});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(Oc(n)??o.statusText)}const r=await o.json();return t(r)}function Oc(e){if(jc(e))return typeof e.error=="string"?e.error:void 0}function jc(e){return typeof e=="object"&&e!==null}const ht={sessionsDeleteArchived:"sessions.deleteArchived",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments"},Fc=Object.values(ht),zc=new Set(Fc);function Nc(e){return typeof e=="string"&&zc.has(e)}function Lt(e,t){return e?.capabilities?.includes(t)===!0}function At(e){return typeof e=="object"&&e!==null}function b(e){if(!At(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 se(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function E(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function z(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function Bc(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function Uc(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function Hc(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=b(e);return{messages:Bc(t.messages),start:se(t,"start"),total:se(t,"total")}}function qc(e){const t=b(e);return z(Sn)(t.machines)}function Sn(e){const t=b(e),i=Gc(t,"kind"),s=$(t,"baseUrl"),o=xn(t,"status"),r=$(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...o===void 0?{}:{status:o},...r===void 0?{}:{statusMessage:r}}}function Kc(e){const t=b(e),i=xn(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:fi(t.web)},...t.sessiond===void 0?{}:{sessiond:fi(t.sessiond)},...s===void 0?{}:{error:s}}}function Vc(e){const t=b(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...y("packageName",$(t,"packageName")),...y("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:Pn(t.components)},...t.capabilities===void 0?{}:{capabilities:Gs(t.capabilities)},...i===void 0?{}:{error:i}}}function Gc(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function xn(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 Bo(e){const t=b(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function Jc(e){const t=b(e),i=$(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:E(t,"isMain"),isGitRepo:E(t,"isGitRepo"),isGitWorktree:E(t,"isGitWorktree")}}function Ss(e){const t=b(e);return{path:m(t,"path"),size:se(t,"size"),modifiedAt:m(t,"modifiedAt")}}function Ji(e){const t=b(e);return{path:m(t,"path")}}function Uo(e){const t=b(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function xs(e){const t=b(e),i=$(t,"name"),s=$(t,"parentSessionPath"),o=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:se(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function yt(e){const t=b(e);return{sessionId:m(t,"sessionId"),isStreaming:E(t,"isStreaming"),isCompacting:E(t,"isCompacting"),isBashRunning:E(t,"isBashRunning"),pendingMessageCount:se(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:z(Qc)(t.queuedMessages),...y("messageCount",Pe(t,"messageCount")),tokens:Zc(t.tokens),cost:se(t,"cost"),...el(t.model),...ul(t.contextUsage),...y("thinkingLevel",$(t,"thinkingLevel"))}}function Qc(e){const t=b(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text"),...y("imageCount",Pe(t,"imageCount"))}}function Zc(e){const t=b(e);return{input:se(t,"input"),output:se(t,"output"),cacheRead:se(t,"cacheRead"),cacheWrite:se(t,"cacheWrite"),total:se(t,"total")}}function kn(e){const t=b(e);return{...y("provider",$(t,"provider")),...y("id",$(t,"id")),...y("name",$(t,"name")),...y("contextWindow",Pe(t,"contextWindow")),...y("reasoning",t.reasoning),...y("input",Xc(t.input))}}function Xc(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Invalid model input");return e.map(Yc)}}function Yc(e){if(e==="text"||e==="image")return e;throw new Error("Invalid model input")}function el(e){return e===void 0?{}:{model:kn(e)}}function tl(e){const t=b(e);return{models:z(kn)(t.models)}}function il(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function sl(e){const t=b(e);return{levels:z(il)(t.levels)}}function ol(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function rl(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 nl(e){const t=b(e),i=t.source===void 0?void 0:rl(t.source);return{configured:E(t,"configured"),...y("source",i),...y("label",$(t,"label"))}}function al(e){const t=b(e);return{id:m(t,"id"),name:m(t,"name"),authType:ol(t.authType),status:nl(t.status)}}function cl(e){const t=b(e);return{providers:z(al)(t.providers)}}function Gt(e){const t=b(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:ll(t.status),progress:z(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...y("error",$(t,"error")),...y("auth",dl(t.auth)),...y("prompt",pl(t.prompt)),...y("select",hl(t.select))}}function ll(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function dl(e){if(e===void 0)return;const t=b(e);return{url:m(t,"url"),...y("instructions",$(t,"instructions"))}}function pl(e){if(e===void 0)return;const t=b(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...y("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function hl(e){if(e===void 0)return;const t=b(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:z(In)(t.options)}}function ul(e){if(e===void 0)return{};const t=b(e);return{contextUsage:{tokens:Zo(t,"tokens"),contextWindow:se(t,"contextWindow"),percent:Zo(t,"percent")}}}function fl(e){const t=b(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...y("description",$(t,"description"))}}function $n(e){const t=b(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function gl(e){const t=b(e);return{path:m(t,"path"),entries:z(ml)(t.entries),scannedAt:m(t,"scannedAt"),truncated:E(t,"truncated")}}function ml(e){const t=b(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...y("size",Pe(t,"size")),...y("modifiedAt",$(t,"modifiedAt"))}}function vl(e){const t=b(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...y("language",$(t,"language")),...y("mediaType",bl(t.mediaType)),...y("mimeType",$(t,"mimeType")),encoding:i,size:se(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:E(t,"truncated"),binary:E(t,"binary")}}function bl(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function wl(e){const t=b(e);return{isGitRepo:E(t,"isGitRepo"),hash:m(t,"hash"),...y("branch",$(t,"branch")),...y("upstream",$(t,"upstream")),...y("ahead",Pe(t,"ahead")),...y("behind",Pe(t,"behind")),files:z(yl)(t.files)}}function yl(e){const t=b(e);return{path:m(t,"path"),...y("oldPath",$(t,"oldPath")),index:Ho(t.index),workingTree:Ho(t.workingTree)}}function Ho(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 Sl(e){const t=b(e);return{...y("path",$(t,"path")),staged:E(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:E(t,"truncated")}}function Qi(e){const t=b(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:E(t,"exited"),...y("exitCode",Pe(t,"exitCode")),...y("commandRunId",$(t,"commandRunId"))}}function Et(e){const t=b(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:xl(t.status),...y("exitCode",Pe(t,"exitCode")),createdAt:m(t,"createdAt"),...y("startedAt",$(t,"startedAt")),...y("completedAt",$(t,"completedAt")),metadata:kl(t.metadata,"metadata")}}function xl(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function kl(e,t){const i=b(e);return Object.fromEntries(Object.entries(i).map(([s,o])=>{if(typeof o!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,o]}))}function $l(e){const t=b(e);return{cwd:m(t,"cwd"),hasSessionActivity:E(t,"hasSessionActivity"),hasTerminalActivity:E(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function Pl(e){const t=b(e);return{workspaces:z($l)(t.workspaces),generatedAt:m(t,"generatedAt")}}function qo(e){const t=b(e);return{path:m(t,"path"),exists:E(t,"exists"),config:Ko(t.config),effectiveConfig:Ko(t.effectiveConfig),envOverrides:Ml(t.envOverrides)}}function Ko(e){const t=b(e);return{...y("host",$(t,"host")),...y("port",Pe(t,"port")),...y("allowedHosts",Rl(t.allowedHosts)),...y("shortcuts",Il(t.shortcuts)),...y("plugins",Cl(t.plugins)),...y("spawnSessions",Qo(t,"spawnSessions")),...y("subsessions",Qo(t,"subsessions"))}}function Rl(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 Il(e){if(e!==void 0){if(!At(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 Cl(e){if(e!==void 0){if(!At(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!At(i)||Array.isArray(i))throw new Error("Invalid PI WEB plugin config field");const s=i.enabled;if(s!==void 0&&typeof s!="boolean")throw new Error("Invalid PI WEB plugin enabled field");const o=i.settings;if(o!==void 0&&(!At(o)||Array.isArray(o)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Ml(e){const t=b(e);return{host:E(t,"host"),port:E(t,"port"),allowedHosts:E(t,"allowedHosts"),spawnSessions:E(t,"spawnSessions"),subsessions:E(t,"subsessions")}}function Tl(e){const t=b(e);return{plugins:z(Al)(t.plugins)}}function Al(e){const t=b(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:El(t.scope),machineSpecific:Dl(t.machineSpecific,"machineSpecific")??!1,enabled:E(t,"enabled")}}function El(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function Dl(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function Wl(e){const t=b(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:Ll(t.components),release:jl(t.release),commands:Fl(t.commands),messages:z(zl)(t.messages)}}function _l(e){const t=b(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:Pn(t.components),capabilities:Gs(t.capabilities)}}function Ll(e){const t=b(e);return{web:fi(t.web),sessiond:fi(t.sessiond)}}function Pn(e){const t=b(e);return{web:Vo(t.web),sessiond:Vo(t.sessiond)}}function Vo(e){const t=b(e);return{component:Rn(t.component),label:m(t,"label"),...y("runtimeVersion",$(t,"runtimeVersion")),available:E(t,"available"),capabilities:Gs(t.capabilities),...y("error",$(t,"error"))}}function fi(e){const t=b(e);return{component:Rn(t.component),label:m(t,"label"),...y("runtimeVersion",$(t,"runtimeVersion")),...y("installedVersion",$(t,"installedVersion")),stale:E(t,"stale"),available:E(t,"available"),...y("installation",Ol(t.installation)),...y("error",$(t,"error"))}}function Ol(e){if(e===void 0)return;const t=b(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");return{kind:i,...y("path",$(t,"path")),...y("source",$(t,"source")),...s===void 0?{}:{scope:s},...y("npmRoot",$(t,"npmRoot"))}}function jl(e){const t=b(e);return{packageName:m(t,"packageName"),...y("latestVersion",$(t,"latestVersion")),updateAvailable:E(t,"updateAvailable"),...y("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...y("error",$(t,"error"))}}function Fl(e){const t=b(e);return{...y("update",$(t,"update")),...y("restart",$(t,"restart")),...y("restartWeb",$(t,"restartWeb")),...y("restartSessiond",$(t,"restartSessiond")),...y("status",$(t,"status"))}}function zl(e){const t=b(e);return{id:m(t,"id"),severity:Nl(t.severity),title:m(t,"title"),body:m(t,"body"),...y("command",$(t,"command"))}}function Rn(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Gs(e){if(!Array.isArray(e)||!e.every(Nc))throw new Error("Invalid PI WEB capabilities");return e}function Nl(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Go(e){const t=b(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:z(In)(t.options)};if(i==="done")return{type:i,...y("message",$(t,"message")),...Bl(t.session),...y("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function In(e){const t=b(e);return{value:m(t,"value"),label:m(t,"label"),...y("description",$(t,"description"))}}function Bl(e){return e===void 0?{}:{session:xs(e)}}function Jt(e){if(b(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function Ul(e){const t=b(e);return z(Hl)(t.attachments)}function Hl(e){const t=b(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:se(t,"size")}}function ks(e){if(b(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function ql(e){if(b(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function Kl(e){if(b(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Jo(e){const t=b(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:Uc(t.sessionIds,"sessionIds"),s=Pe(t,"archivedCount"),o=Pe(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...o===void 0?{}:{skippedAlreadyArchivedCount:o}}}function Vl(e){if(b(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function Gl(e){if(b(e).deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0}}function Jl(e){if(b(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Ql(e){if(b(e).reloaded!==!0)throw new Error("Expected reloaded response");return{reloaded:!0}}function Qo(e,t){const i=e[t];if(i!==void 0){if(typeof i!="boolean")throw new Error(`Invalid PI WEB ${t} field`);return i}}function Pe(e,t){const i=e[t];if(i!==void 0){if(typeof i!="number")throw new Error(`Expected optional number field: ${t}`);return i}}function Zo(e,t){const i=e[t];if(i===null)return null;if(typeof i!="number")throw new Error(`Expected number|null field: ${t}`);return i}function y(e,t){return t===void 0?{}:{[e]:t}}function Zl(e){return typeof e=="string"?e:e.id}function Xl(e){return typeof e=="string"?void 0:e.cwd}function Yl(e,t,i,s){const o=new URLSearchParams;s?.path!==void 0&&o.set("path",s.path),s?.staged===!0&&o.set("staged","true");const r=o.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${r?`?${r}`:""}`}function ed(e,t,i="local"){const s=new URLSearchParams,o=Xl(e);o!==void 0&&o!==""&&s.set("cwd",o),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const r=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(Zl(e))}/messages${r===""?"":`?${r}`}`}function td(e,t,i,s){const o=new URLSearchParams;return o.set("path",i),s?.modifiedAt!==void 0&&o.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${o.toString()}`}function Cn(e,t,i,s){const o=new URLSearchParams;o.set("path",i);const r=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return yn(`${r}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${o.toString()}`)}const R=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function id(e){return typeof e=="string"?e:e.id}function Mn(e){return typeof e=="string"?void 0:e.cwd}function Tn(e,t="local"){return`${R(t)}/sessions/${encodeURIComponent(id(e))}`}function V(e,t,i="local"){return`${Tn(e,i)}/${t}`}function Qt(e,t,i="local"){return`${V(e,t,i)}${An(e)}`}function sd(e,t="local"){return`${Tn(e,t)}${An(e)}`}function An(e){const t=Mn(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function J(e,t={}){const i=Mn(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}const En={piWebStatus:(e="local")=>v(e==="local"?"/api/pi-web/status":`${R(e)}/pi-web/status`,Wl),piWebRuntime:()=>v("/api/pi-web/runtime",_l)},od={machines:()=>v("/api/machines",qc),addMachine:e=>v("/api/machines",Sn,{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`,Kc),runtime:e=>v(`/api/machines/${encodeURIComponent(e)}/runtime`,Vc)},gi={config:()=>v("/api/config",qo),saveConfig:e=>v("/api/config",qo,{method:"PUT",body:JSON.stringify({config:e})})},$s={plugins:()=>v("/api/plugins",Tl)},Dn={workspaceActivity:(e="local")=>v(`${R(e)}/activity`,Pl)},rd={projects:(e="local")=>v(`${R(e)}/projects`,z(Bo)),addProject:(e,t,i,s="local")=>v(`${R(s)}/projects`,Bo,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>v(`${R(t)}/projects/${encodeURIComponent(e)}`,ks,{method:"DELETE"}),projectDirectories:(e,t="local")=>v(`${R(t)}/project-directories?q=${encodeURIComponent(e)}`,z($n))},Ps={workspaces:(e,t="local")=>v(`${R(t)}/projects/${e}/workspaces`,z(Jc)),deleteWorkspace:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Et,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,gl),workspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,vl),uploadWorkspaceFile:async(e,t,i,s,o="local")=>o==="local"?pd(e,t,i,s):v(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Ss,{method:"POST",body:JSON.stringify({path:i,contentBase64:await ld(s)})}),createWorkspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Ss,{method:"POST",body:JSON.stringify({path:i,contentBase64:""})}),moveWorkspaceFile:(e,t,i,s,o="local")=>v(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Ji,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceFile:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Uo,{method:"DELETE"}),createWorkspaceDirectory:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Ji,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,o="local")=>v(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Ji,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,Uo,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>Cn(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>hd(e,t,i,s)},nd={sessions:(e,t="local")=>v(`${R(t)}/sessions?cwd=${encodeURIComponent(e)}`,z(xs)),startSession:(e,t="local")=>v(`${R(t)}/sessions`,xs,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>v(ed(e,t,i),Hc),status:(e,t="local")=>v(Qt(e,"status",t),yt),models:(e,t="local")=>v(Qt(e,"models",t),tl),setModel:(e,t,i,s="local")=>v(V(e,"model",s),yt,{method:"POST",body:J(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>v(V(e,"model/cycle",i),yt,{method:"POST",body:J(e,{direction:t})}),thinkingLevels:(e,t="local")=>v(Qt(e,"thinking-levels",t),sl),setThinkingLevel:(e,t,i="local")=>v(V(e,"thinking-level",i),yt,{method:"POST",body:J(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>v(V(e,"thinking-level/cycle",t),yt,{method:"POST",body:J(e)}),commands:(e,t="local")=>v(Qt(e,"commands",t),z(fl)),prompt:(e,t,i,s="local",o)=>v(V(e,"prompt",s),Jt,{method:"POST",body:J(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...o!==void 0&&o.length>0?{attachments:o}:{}})}),saveAttachments:(e,t,i="local",s)=>v(V(e,"attachments",i),Ul,{method:"POST",body:J(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>v(V(e,"shell",i),Jt,{method:"POST",body:J(e,{text:t})}),runCommand:(e,t,i="local")=>v(V(e,"commands/run",i),Go,{method:"POST",body:J(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>v(V(e,"commands/respond",s),Go,{method:"POST",body:J(e,{requestId:t,value:i})}),abort:(e,t="local")=>v(V(e,"abort",t),ql,{method:"POST",body:J(e)}),stop:(e,t="local")=>v(V(e,"stop",t),Kl,{method:"POST",body:J(e)}),archive:(e,t="local")=>v(V(e,"archive",t),Jo,{method:"POST",body:J(e)}),archiveWithDescendants:(e,t="local")=>v(V(e,"archive-tree",t),Jo,{method:"POST",body:J(e)}),restore:(e,t="local")=>v(V(e,"restore",t),Vl,{method:"POST",body:J(e)}),deleteArchived:(e,t="local")=>v(sd(e,t),Gl,{method:"DELETE"}),detachParent:(e,t="local")=>v(V(e,"detach-parent",t),Jl,{method:"POST",body:J(e)}),reloadSession:(e,t="local")=>v(V(e,"reload",t),Ql,{method:"POST",body:J(e)}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return v(`${R(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,cl)},saveApiKey:(e,t,i="local")=>v(`${R(i)}/auth/api-key`,Jt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>v(`${R(t)}/auth/logout`,Jt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>v(`${R(t)}/auth/oauth`,Gt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>v(`${R(t)}/auth/oauth/${encodeURIComponent(e)}`,Gt),respondOAuthFlow:(e,t,i,s="local")=>v(`${R(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Gt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>v(`${R(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Gt,{method:"POST"})},dt={terminals:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,z(Qi)),startTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Qi,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ks,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,ks,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>v(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Qi,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Et,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>v(`${R(t)}/terminal-command-runs${cd(e)}`,z(Et)),getCommandRun:(e,t="local")=>ad(e,t),cancelCommandRun:(e,t="local")=>v(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Et,{method:"POST"})};async function ad(e,t){const i=await fetch(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Js(s)??i.statusText)}return Et(await i.json())}}function cd(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 Js(e){if(!ud(e))return;const t=e.error;return typeof t=="string"?t:void 0}async function ld(e){return dd(await e.arrayBuffer())}function dd(e){const t=new Uint8Array(e);let i="";for(const s of t)i+=String.fromCharCode(s);return btoa(i)}async function pd(e,t,i,s){const o=new FormData;o.set("path",i),o.set("file",s,s.name);const r=await fetch(`${R("local")}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,{method:"POST",body:o});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(Js(n)??r.statusText)}return Ss(await r.json())}async function hd(e,t,i,s){const o=await fetch(Cn(e,t,i,{machineId:s}));if(!o.ok){const p=await o.json().catch(()=>({}));throw new Error(Js(p)??o.statusText)}const r=await o.blob(),n=URL.createObjectURL(r),a=document.createElement("a");a.href=n;const l=i.split("/").pop();a.download=l===void 0||l===""?"download":l,document.body.append(a),a.click(),a.remove(),URL.revokeObjectURL(n)}function ud(e){return typeof e=="object"&&e!==null}const fd={files:(e,t,i={})=>{const s=new URLSearchParams({cwd:e,q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),v(`${R(i.machineId)}/files?${s.toString()}`,z($n))}},gd={gitStatus:(e,t,i="local")=>v(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,wl),gitDiff:(e,t,i,s="local")=>v(Yl(s,e,t,i),Sl)},N={...En,...od,...gi,...$s,...Dn,...rd,...Ps,...nd,...dt,...fd,...gd};function md(e,t="local"){const i=typeof e=="string"?void 0:e.cwd,s=i===void 0||i===""?"":`?${new URLSearchParams({cwd:i}).toString()}`,o=typeof e=="string"?e:e.id;return new WebSocket(`${Zs()}${Qs(t)}/sessions/${encodeURIComponent(o)}/events${s}`)}function iy(e,t,i,s,o="local"){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Zs()}${Qs(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`)}function vd(e="local"){return new WebSocket(`${Zs()}${Qs(e)}/events`)}function Qs(e){return`/api/machines/${encodeURIComponent(e)}`}function Zs(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function ni(){return{sessions:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:""}}function bd(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Xe(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Wn(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const _n="local";function Zi(e,t){return`${e}:${t}`}function Ln(e,t){return`${e}:${t}`}function f(e){return e.selectedMachine?.id??_n}class wd{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??Dn}async refresh(t=f(this.getState())){this.applyMachineActivitySnapshot(t,yd(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=f(this.getState())){const s=this.getState(),o=f(s)===i,r=s.machineActivities[i]??(o?s.workspaceActivities:{}),n=Sd(r,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...o?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...f(s)===t?{workspaceActivities:i}:{}})}}function yd(e){const t={};for(const i of e.workspaces)Wn(i)&&(t[i.cwd]=i);return t}function Sd(e,t){const i={...e};return Wn(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class xd{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??N,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=kd(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:f(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const o=s.providers.find(r=>r.id===t&&(i===void 0||r.authType===i));o!==void 0&&(o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({authDialog:{...t,saving:!1,error:String(o)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:f(this.getState())});if(t!==void 0&&t!==""){const s=i.find(o=>o.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(o=>o.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({error:String(o)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const o=t??i.inputValue??"",r={...i};delete r.error,this.setState({authDialog:{...r,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,o,f(this.getState()));this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...i,responding:!1,error:String(n)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,f(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:f(this.getState())}),s=i.filter(r=>r.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const o=s[0];if(o===void 0)return;o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,f(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const o=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${o}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",o=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,r=t.prompt?.requestId??t.select?.requestId,n=o!==void 0&&o===r,a=n?s:"",l=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:l}})}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 kd(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const o=i[2];return o===void 0||o===""?{command:s}:{command:s,providerId:o}}function Ft(e){return e.replaceAll(":",".")}function $d(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[o,r]of t.entries()){if(!o.startsWith(i))continue;const n=o.slice(i.length),a=s[n];a===void 0?s[n]=r:Array.isArray(a)?a.push(r):s[n]=[a,r]}return s}function Xi(e,t){const i=$d(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function le(e,t,i,s){const o=new URL(window.location.href),r=`${e}--${t}`;if(o.searchParams.delete(r),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)o.searchParams.append(r,String(n));else o.searchParams.set(r,String(i));Pd(o,s)}function Pd(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}const Zt=Ft("core:workspace.files");class Rd{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.api=o.api??N}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=f(this.getState()),o=await this.api.workspaceTree(t.id,i.id,"",s),r=await Promise.all(Object.keys(this.getState().expandedDirs).map(async a=>{try{const l=await this.api.workspaceTree(t.id,i.id,a,s);return[a,l.entries]}catch(l){if(Xo(l))return;throw l}})),n=Object.fromEntries(r.filter(a=>a!==void 0));this.setState({fileTree:o.entries,expandedDirs:n,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:Id(this.getState().expandedDirs,t)});return}try{const o=await this.api.workspaceTree(i.id,s.id,t,f(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:o.entries},error:""})}catch(o){this.setState({error:String(o)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),le(Zt,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}selectDirectory(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),le(Zt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}async restoreFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){this.setState({selectedFilePath:t,selectedFileContent:void 0});try{const o=await this.api.workspaceFile(i.id,s.id,t,f(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(Xo(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),le(Zt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}async uploadFiles(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t.length===0))try{const o=f(this.getState()),r=Cd(this.getState()),n=[];for(const l of t){const p=Td(r,Md(l));await this.api.uploadWorkspaceFile(i.id,s.id,p,l,o),n.push(p)}await this.refreshFiles();const a=n.at(-1);a!==void 0&&await this.selectFile(a),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async createFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceFile(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),await this.selectFile(t),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async createDirectory(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceDirectory(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),this.selectDirectory(t),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async moveSelectedPath(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace,o=this.getState().selectedFilePath;if(!(i===void 0||s===void 0||o===void 0||o===""||t===""))try{const r=f(this.getState());Yi(this.getState())==="directory"?(await this.api.moveWorkspaceDirectory(i.id,s.id,o,t,r),await this.refreshFiles(),this.selectDirectory(t)):(await this.api.moveWorkspaceFile(i.id,s.id,o,t,r),await this.refreshFiles(),await this.selectFile(t)),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async deleteSelectedPath(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""))try{const o=f(this.getState());Yi(this.getState())==="directory"?await this.api.deleteWorkspaceDirectory(t.id,i.id,s,o):await this.api.deleteWorkspaceFile(t.id,i.id,s,o),await this.refreshFiles(),this.clearSelection(),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async downloadSelectedFile(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""||Yi(this.getState())==="directory"))try{await this.api.downloadWorkspaceFile(t.id,i.id,s,f(this.getState())),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),le(Zt,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}}function Xo(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function Id(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Cd(e){const t=e.selectedFilePath;if(t===void 0||t==="")return"";if(On(e.fileTree,e.expandedDirs,t)?.type==="directory")return t;const s=t.lastIndexOf("/");return s===-1?"":t.slice(0,s)}function Yi(e){const t=e.selectedFilePath;return t===void 0?"file":On(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function On(e,t,i){const s=e.find(o=>o.path===i);if(s!==void 0)return s;for(const o of Object.values(t)){const r=o.find(n=>n.path===i);if(r!==void 0)return r}}function Md(e){return e.name.split(/[\\/]+/u).filter(t=>t!=="").at(-1)??e.name}function Td(e,t){return e===""?t:`${e}/${t}`}const Yo=Ft("core:workspace.git");class Ad{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 o=this.getState().selectedDiffPath;o!==void 0&&(s.files.some(r=>r.path===o)?await this.refreshDiff(o):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),le(Yo,"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"}),le(Yo,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[o,r]=await Promise.all([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:o,selectedStagedDiff:r,error:""})}catch(o){this.setState({error:String(o)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class Ed{constructor(t,i,s,o){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=o}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await N.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(r=>r.id));this.setState({machines:i,selectedMachine:s,machineActivities:er(this.getState().machineActivities,o),machineRuntimes:er(this.getState().machineRuntimes,o)}),this.refreshMachineHealthFor(i),this.refreshMachineRuntimeFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...ni()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await 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 o=this.getState().machines.filter(n=>n.id!==t.id),r=o.find(n=>n.id==="local")??o[0];return this.setState({machines:o,machineStatuses:es(this.getState().machineStatuses,t.id),machineRuntimes:es(this.getState().machineRuntimes,t.id),machineActivities:es(this.getState().machineActivities,t.id)}),s&&r!==void 0?(i.selectFallback===!1||await this.selectMachine(r),r):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await 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(r=>r.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const o=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[o.machineId]:o},...o.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await 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(o=>N.health(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(o=>N.runtime(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function es(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function er(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class Dd{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(r=>r.id)),o=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([r])=>s.has(r)));this.setState({projects:i,workspacesByProjectId:o})}catch(i){f(this.getState())===t&&this.setState({error:String(i)})}finally{f(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await N.addProject(t.trim(),void 0,i,f(this.getState())),o=this.getState().projects;this.setState({projects:[...o.filter(r=>r.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await 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 Rs="pi-web:cached-new-sessions:v1",Wd="browserCachedNew",gt="local";function zt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function tr(e,t=gt,i=zt()){if(e.messageCount!==0||e.archived===!0)return;const s=Xs(i).filter(o=>o.id!==e.id||o.machineId!==t);Ys([Is(e,t),...s],i)}function Is(e,t=gt){return{...e,browserCachedNew:!0,machineId:t}}function ir(e,t=gt,i=zt()){const s=Xs(i).filter(o=>o.id!==e||o.machineId!==t);Ys(s,i)}function _d(e,t,i=gt,s=zt()){const o=new Set(t.map(l=>l.id)),r=Xs(s),n=r.filter(l=>l.machineId!==i||!o.has(l.id));return n.length!==r.length&&Ys(n,s),[...n.filter(l=>l.machineId===i&&l.cwd===e),...t]}function ee(e){return e===void 0?!1:jd(e)&&e.browserCachedNew===!0}function Ld(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:gt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Xs(e=zt()){try{const t=e?.getItem(Rs);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>Od(s)):[]}catch{return[]}}function Ys(e,t=zt()){try{e.length===0?t?.removeItem(Rs):t?.setItem(Rs,JSON.stringify(e))}catch{}}function Od(e){if(!Fd(e))return[];const t=nt(e,"id"),i=nt(e,"path"),s=nt(e,"cwd"),o=nt(e,"created"),r=nt(e,"modified"),n=nt(e,"firstMessage"),a=zd(e,"messageCount");if(t===void 0||i===void 0||s===void 0||o===void 0||r===void 0||n===void 0||a!==0)return[];const l=ts(e,"name"),p=ts(e,"parentSessionPath"),u=ts(e,"machineId")??gt;return[{id:t,path:i,cwd:s,...l===void 0?{}:{name:l},created:o,modified:r,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function jd(e){return Wd in e}function Fd(e){return typeof e=="object"&&e!==null}function nt(e,t){const i=e[t];return typeof i=="string"?i:void 0}function ts(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function zd(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Nd(e){return sp(e.flatMap(eo)).filter(t=>t.parts.length>0)}function Ae(e,t){return{role:e,parts:[{type:"text",text:t}]}}function St(e,t){const i=Jd(t);return i===void 0?e:{...e,meta:i}}function Bd(e,t,i){if(i==="")return e;const s=e.at(-1),o=s?.parts.at(-1);return s?.role===t&&o?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...o,text:o.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,Ae(t,i)]}function Ud(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 eo(e){if(qd(e))return[e];if(W(e,"role")==="bashExecution")return[St(Xd(e),e)];const t=Yd(W(e,"role")),i=ep(ge(e,"content"),e),s=t==="user"?Kd(i):void 0;if(s!==void 0)return s.map(p=>St(p,e));const o=Gd(e);if(t==="tool")return[St({role:t,parts:i,...o===void 0?{}:{source:o}},e)];const r=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&r.length>0&&r.every(p=>p.type==="skillRead")?"skill":t,a=r.length>0?[St({role:n,parts:r,...o===void 0?{}:{source:o}},e)]:[],l=Hd(e);return l===void 0?a:[...a,St(l,e)]}function Hd(e){if(W(e,"role")!=="assistant"||W(e,"stopReason")!=="error")return;const t=W(e,"errorMessage")?.trim();return Ae("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function qd(e){const t=W(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(ge(e,"parts"))}function Kd(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Vd(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 Vd(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 Gd(e){const t=W(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Jd(e){const t=Qd(ge(e,"timestamp")),i=Zd(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Qd(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 Zd(e){if(W(e,"role")!=="assistant")return;const t=W(e,"provider"),i=W(e,"model"),s=W(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 Xd(e){const t=W(e,"command")??"",i=ai(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=ge(e,"output");s!=null&&i.push("",vi(s));const o=ge(e,"exitCode");o!=null&&i.push("",`exit ${vi(o)}`),ai(e,"cancelled")===!0&&i.push("","cancelled"),ai(e,"truncated")===!0&&i.push("","output truncated");const r=W(e,"fullOutputPath");return r!==void 0&&r!==""&&i.push("",`full output: ${r}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
+ `)}]}}function Yd(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function ep(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=W(i,"type"),o=W(i,"text");if(s==="text")return o!==void 0&&o!==""?[{type:"text",text:o}]:[];if(s==="thinking"){const r=W(i,"thinking")??o;return r!==void 0&&r!==""?[{type:"thinking",text:r}]:[]}if(s==="toolCall"){const r=W(i,"name")??"tool",n=ge(i,"arguments"),a=W(i,"id"),l=r==="read"?ip(W(n,"path")):void 0;return l!==void 0?[{type:"skillRead",...l,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:r,summary:Nt(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const r=W(i,"data"),n=W(i,"mimeType");return r!==void 0&&r!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:r}]:[{type:"text",text:"[image]"}]}return sr(i)}).map(i=>i.type==="text"&&W(t,"role")==="toolResult"?tp(i.text,t):i):sr(e)}function tp(e,t){const i=W(t,"toolCallId"),s=ge(t,"content"),o=ge(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:W(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...o===void 0?{}:{details:o},isError:ai(t,"isError")===!0}}function ip(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 sp(e){const t=[],i=new Map;for(const s of e){let o=[];const r={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{o.length!==0&&(t.push({role:s.role,parts:o,...r}),o=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const l=op(a),p=t.length;t.push({role:"tool",parts:[l],...r}),l.toolCallId!==void 0&&i.set(l.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const l=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(l!==void 0&&rp(t,l,a)){i.delete(a.toolCallId??"");continue}}o.push(a)}n()}return t}function op(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 rp(e,t,i){const s=e[t.lineIndex],o=s?.parts[t.partIndex];if(s===void 0||o?.type!=="toolExecution")return!1;const r=mi(i.details)??o.preview,n={...o,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...r===void 0?{}:{preview:r}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function mi(e){const t=ge(e,"preview");if(!to(t))return;const i=W(t,"diff"),s=W(t,"error"),o=ap(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&o===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...o===void 0?{}:{firstChangedLine:o}}}function sr(e){return e==null?[]:typeof e=="object"?[{type:"text",text:Nt(e)}]:[{type:"text",text:vi(e)}]}function Nt(e){if(!to(e))return vi(e);const t=W(e,"command");if(t!==void 0)return t;const i=W(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} edit${s.length===1?"":"s"}`:Object.entries(e).filter(([,r])=>r!=null).slice(0,3).map(([r,n])=>`${r}: ${np(n)}`).join(" · ")}function np(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 to(e){return typeof e=="object"&&e!==null}function ge(e,t){return to(e)?e[t]:void 0}function W(e,t){const i=ge(e,t);return typeof i=="string"?i:void 0}function ai(e,t){const i=ge(e,t);return typeof i=="boolean"?i:void 0}function ap(e,t){const i=ge(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function vi(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const cp="pi-web:prompt-draft:";function bi(e){return`${cp}${e}`}function Li(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function jn(e,t=Li()){try{return t?.getItem(bi(e))??""}catch{return""}}function wi(e,t,i=Li()){try{t?i?.setItem(bi(e),t):i?.removeItem(bi(e))}catch{}}function io(e,t=Li()){try{t?.removeItem(bi(e))}catch{}}function lp(e,t,i=Li()){const s=jn(e,i);s!==""&&(wi(t,s,i),io(e,i))}function dp(e,t){return Ae("bash",`${t===!0?`不加入上下文
6
6
 
7
- `:""}$ ${e}`)}function lp(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Ae("bash",t)];const r=pp(s.text)?"":`
7
+ `:""}$ ${e}`)}function pp(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Ae("bash",t)];const o=up(s.text)?"":`
8
8
 
9
- `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+r+t}]}]}function dp(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+o+t}]}]}function hp(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const o=[];return!s.text.includes(`
10
10
 
11
- `)&&(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}
11
+ `)&&(t.output===void 0||t.output==="")&&o.push("(no output)"),t.isError===!0&&o.push(t.output??"Bash 命令失败"),t.exitCode!=null&&o.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&o.push("cancelled"),t.truncated===!0&&o.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&o.push(`完整输出:${t.fullOutputPath}`),o.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
12
12
 
13
- ${r.join(`
14
- `)}`}]}]}function pp(e){const t=e.lastIndexOf(`
13
+ ${o.join(`
14
+ `)}`}]}]}function up(e){const t=e.lastIndexOf(`
15
15
 
16
- `),i=e.lastIndexOf("$ ");return t>i}function hp(e,t){if(t.type==="message.append")return kp(e,t.message);if(t.type==="assistant.delta")return Nd(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return zd(e,t.text);if(t.type==="tool.start")return vp(e,t);if(t.type==="tool.update")return jn(e,t.toolCallId,i=>bp(i,t));if(t.type==="tool.end")return Ln(e,t.toolCallId,t.toolName,Nt(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,cp(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return lp(e,t.chunk);if(t.type==="shell.end")return dp(e,t);if(t.type==="command.output")return[...e,Ae(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,Ae("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:up(e,t.message)}function up(e,t){const i=wp(t);if(i!==void 0)return Ln(e,i.toolCallId,i.toolName,Nt(i.content),i.text,i.isError,i.content,i.details);const s=Ys(t);if(s.length===0)return;const r=s.map(o=>o.role==="assistant"?gp(o):o).filter(o=>o.parts.length>0);return r.length===0?e:r.reduce((o,n)=>fp(o,n),e)}function fp(e,t){const i=yp(e,t);if(i>=0)return[...e.slice(0,i),t,...e.slice(i+1)];const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||xp(s,t)?[...e.slice(0,-1),t]:[...e,t]}function gp(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function mp(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 vp(e,t){const i=t.toolName==="read"?mp(Qe(t.args,"path")):void 0;if(i!==void 0)return $p(e,{role:"skill",parts:[{type:"skillRead",...i}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||Nt(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function bp(e,t){const i=gi(t.details)??e.preview;return{...e,status:e.status==="pending"?"running":e.status,...t.text===""?{}:{resultText:t.text},...t.content===void 0?{}:{content:t.content},...t.details===void 0?{}:{details:t.details},...i===void 0?{}:{preview:i}}}function Ln(e,t,i,s,r,o,n,a){const l=jn(e,t,h=>{const g=gi(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(l!==e)return l;const p=gi(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 jn(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(l=>l.type==="toolExecution"&&l.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 wp(e){if(Qe(e,"role")!=="toolResult")return;const t=Qe(e,"toolCallId"),i=yi(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:Qe(e,"toolName")??"tool",text:Fn(i),isError:Rp(e,"isError")===!0,content:i,details:yi(e,"details")}}function Fn(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Fn).filter(t=>t!=="").join(`
17
- `);if(typeof e=="object"&&e!==null){const t=Qe(e,"text")??Qe(e,"content")??Qe(e,"output");if(t!==void 0)return t}return""}function yp(e,t){const i=wi(t);if(i.length===0)return-1;for(let s=e.length-1;s>=0;s--){const r=e[s];if(r?.role!=="skill")continue;const o=wi(r);if(Nn(o,i))return s}return-1}function wi(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function Nn(e,t){return e.length===t.length&&e.every((i,s)=>Sp(i,t[s]))}function Sp(e,t){return t===void 0?!1:to(e.path)===to(t.path)||e.name===t.name}function to(e){return e.replace(/\\/g,"/")}function xp(e,t){return io(e)===io(t)}function io(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
16
+ `),i=e.lastIndexOf("$ ");return t>i}function fp(e,t){if(t.type==="message.append")return Cp(e,t.message);if(t.type==="assistant.delta")return Bd(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return Ud(e,t.text);if(t.type==="tool.start")return wp(e,t);if(t.type==="tool.update")return zn(e,t.toolCallId,i=>yp(i,t));if(t.type==="tool.end")return Fn(e,t.toolCallId,t.toolName,Nt(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,dp(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return pp(e,t.chunk);if(t.type==="shell.end")return hp(e,t);if(t.type==="command.output")return[...e,Ae(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,Ae("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:gp(e,t.message)}function gp(e,t){const i=Sp(t);if(i!==void 0)return Fn(e,i.toolCallId,i.toolName,Nt(i.content),i.text,i.isError,i.content,i.details);const s=eo(t);if(s.length===0)return;const o=s.map(r=>r.role==="assistant"?vp(r):r).filter(r=>r.parts.length>0);return o.length===0?e:o.reduce((r,n)=>mp(r,n),e)}function mp(e,t){const i=xp(e,t);if(i.length>0)return kp(e,i,t);const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||Ip(s,t)?[...e.slice(0,-1),t]:[...e,t]}function vp(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function bp(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 wp(e,t){const i=t.toolName==="read"?bp(Qe(t.args,"path")):void 0;if(i!==void 0)return Mp(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||Nt(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function yp(e,t){const i=mi(t.details)??e.preview;return{...e,status:e.status==="pending"?"running":e.status,...t.text===""?{}:{resultText:t.text},...t.content===void 0?{}:{content:t.content},...t.details===void 0?{}:{details:t.details},...i===void 0?{}:{preview:i}}}function Fn(e,t,i,s,o,r,n,a){const l=zn(e,t,h=>{const g=mi(a)??h.preview;return{...h,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...g===void 0?{}:{preview:g}}});if(l!==e)return l;const p=mi(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function zn(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const o=e[s];if(o===void 0)continue;const r=o.parts.findIndex(l=>l.type==="toolExecution"&&l.toolCallId===t);if(r<0)continue;const n=o.parts[r];if(n?.type!=="toolExecution")continue;const a={...o,parts:[...o.parts.slice(0,r),i(n),...o.parts.slice(r+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function Sp(e){if(Qe(e,"role")!=="toolResult")return;const t=Qe(e,"toolCallId"),i=Si(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:Qe(e,"toolName")??"tool",text:Nn(i),isError:Dp(e,"isError")===!0,content:i,details:Si(e,"details")}}function Nn(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Nn).filter(t=>t!=="").join(`
17
+ `);if(typeof e=="object"&&e!==null){const t=Qe(e,"text")??Qe(e,"content")??Qe(e,"output");if(t!==void 0)return t}return""}function xp(e,t){const i=yi(t);if(i.length===0)return[];const s=[];let o=i.length;const r=Un(e)+1;for(let n=e.length-1;n>=r;n--){const a=yi(e[n]);if(a.length===0)continue;const l=o-a.length;if(!(l<0)&&Rp(a,i.slice(l,o))&&(s.unshift(n),o=l,o===0))return s}return[]}function kp(e,t,i){const s=$p(e,t,i),o=s[0];if(o===void 0)return e;const r=new Set(s),n=[];for(let a=0;a<e.length;a++){a===o&&n.push(i);const l=e[a];l!==void 0&&!r.has(a)&&n.push(l)}return n}function $p(e,t,i){const s=t[0];if(i.role!=="assistant"||s===void 0)return t;const o=s-1;return Pp(e[o])?[o,...t]:t}function Pp(e){return e?.role==="assistant"&&e.parts.length>0&&e.parts.every(t=>t.type==="text"||t.type==="thinking")}function yi(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function Rp(e,t){return e.length===t.length&&e.every((i,s)=>Bn(i,t[s]))}function Bn(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:or(e.path)===or(t.path)||e.name===t.name}function or(e){return e.replace(/\\/g,"/")}function Ip(e,t){return rr(e)===rr(t)}function rr(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
18
18
 
19
- `)}function kp(e,t){const i=Ys(t);return i.length===0?e:[...e,...i]}function $p(e,t){const i=e.at(-1);return t.role==="skill"&&Nn(wi(i),wi(t))?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Pp(e){return typeof e=="object"&&e!==null}function yi(e,t){return Pp(e)?e[t]:void 0}function Qe(e,t){const i=yi(e,t);return typeof i=="string"?i:void 0}function Rp(e,t){const i=yi(e,t);return typeof i=="boolean"?i:void 0}const Ip="pi-web:chat-history:v2:",Cp=1800*1e3;function Mp(e){try{const t=sessionStorage.getItem(Si(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!_p(i))return;if(Date.now()-i.savedAt>Cp){sessionStorage.removeItem(Si(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function Tp(e,t){try{sessionStorage.setItem(Si(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Ap(e){try{sessionStorage.removeItem(Si(e))}catch{}}function Ep(e,t){if(e===void 0||!Is(e))return t;if(!Is(t))return e;if(Dp(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 so(r,i,e),so(r,i,t),Wp(r)?t:{start:i,total:Math.max(e.total,t.total),messages:r}}function Dp(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Wp(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function so(e,t,i){i.messages.forEach((s,r)=>{e[i.start-t+r]=s})}function Si(e){return`${Ip}${e}`}function _p(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"&&Is({messages:t,start:i,total:s})}function Is(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(Op)}function Op(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 Lp={read:Mp,write:Tp,remove:Ap};class jp{constructor(t=Lp){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return ro(this.rawHistoryPage(t))}mergeHistory(t,i){const s=Ep(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),ro(s)}applyLiveEvent(t,i){return hp(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 ro(e){const t=e?.start??0;return{messages:Fd(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function zn(e,t=e.length){const i=e.slice(0,t),s=Fp(i,t);if(s!==void 0)return s;const r=Np(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 Bn(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Fp(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 Np(e,t){const i=e.lastIndexOf(`
21
- `)+1,s=e.slice(i),r=oo(s,"@ "),o=oo(s,"!@"),n=Math.max(r,o);if(n===-1)return;const a=n===o?"!@":"@ ",l=i+n,p=l+a.length;return{kind:"file",query:e.slice(p),from:l,to:t,fileScope:"all",allPrefix:a}}function oo(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||zp(e[i-1]))return i;return-1}function zp(e){return e===" "||e===" "}function ir(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Up(e).startsWith("/")?{kind:"command"}:zn(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function Bp(e){return ir(e).kind==="shell"}function Up(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
- `))+1;return e.slice(t)}class Hp{constructor(){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),Hn(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=fd(this.session,this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Un(t);qp(i)&&this.onEvent?.(i)}}class no{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Hn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=gd(this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Un(t);Vp(i)&&this.onEvent?.(i)}}function qp(e){const t=sr(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 Kp(e){const t=sr(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function Vp(e){const t=sr(e);return Kp(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function sr(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Un(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 Hn(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 zt(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class Oi{constructor(t,i,s=zt()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[r,o]of Gp(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 rr(e){return typeof e=="string"&&e!==""?e:void 0}function Gp(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const r=JSON.parse(s);if(!Jp(r))return[];const o=[];for(const n of r.entries){const a=n[0],l=t(n[1]);l!==void 0&&o.push([a,l])}return o}catch{return[]}}function Jp(e){return!Qp(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 Qp(e){return typeof e=="object"&&e!==null}class Zp{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 Xp="pi-web:session-selection:v1";class Yp{constructor(t=zt()){this.sessionIdsByCwd=new Oi(Xp,rr,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function eh(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return ih(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 th(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function ih(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function sh(e,t,i){return Cs(e,[t],i)}function Cs(e,t,i){const s=new Set(t);return e.map(r=>s.has(r.id)?{...r,archived:!0,archivedAt:i}:r)}function rh(e,t,i){return Ms(e,t,[i])}function Ms(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 St=100;class oh{constructor(t,i,s,r=new Zp,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=o.socket??new Hp,this.api=o.api??z,this.transcripts=o.transcripts??new jp}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0,availableThinkingLevels:[]})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();th(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);Xr(s,i);const r=Rs(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 eh(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const 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:St},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,l]=await Promise.all([this.api.messages(t,{limit:St},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(l.isStreaming?t.id:void 0),status:l,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(l),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(ee(t)&&fh(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:St},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&&Bp(t))return this.runShell(t);const a=this.getState().selectedSession;if(!a||a.archived===!0)return;const l=a.id,p=f(this.getState());n&&this.markSendingPrompt(l,!0);try{if(n&&r==="folder"){const h=(await this.api.saveAttachments(a,s,p)).map(w=>Bn(w.path,!1)).join(" "),g=t===""?h:`${t}
19
+ `)}function Cp(e,t){const i=eo(t);return i.length===0?e:[...e,...i]}function Mp(e,t){const i=e.at(-1);return Tp(e,t)?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Tp(e,t){const i=yi(t);if(t.role!=="skill"||i.length===0)return!1;const s=Un(e)+1;return i.every(o=>Ap(e,o,s))}function Ap(e,t,i){for(let s=e.length-1;s>=i;s--)if(yi(e[s]).some(o=>Bn(o,t)))return!0;return!1}function Un(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="user")return t;return-1}function Ep(e){return typeof e=="object"&&e!==null}function Si(e,t){return Ep(e)?e[t]:void 0}function Qe(e,t){const i=Si(e,t);return typeof i=="string"?i:void 0}function Dp(e,t){const i=Si(e,t);return typeof i=="boolean"?i:void 0}const Wp="pi-web:chat-history:v2:",_p=1800*1e3;function Lp(e){try{const t=sessionStorage.getItem(xi(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!Bp(i))return;if(Date.now()-i.savedAt>_p){sessionStorage.removeItem(xi(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function Op(e,t){try{sessionStorage.setItem(xi(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function jp(e){try{sessionStorage.removeItem(xi(e))}catch{}}function Fp(e,t){if(e===void 0||!Cs(e))return t;if(!Cs(t))return e;if(zp(e,t))return t;const i=Math.min(e.start,t.start),s=Math.max(e.start+e.messages.length,t.start+t.messages.length),o=new Array(s-i);return nr(o,i,e),nr(o,i,t),Np(o)?t:{start:i,total:Math.max(e.total,t.total),messages:o}}function zp(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Np(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function nr(e,t,i){i.messages.forEach((s,o)=>{e[i.start-t+o]=s})}function xi(e){return`${Wp}${e}`}function Bp(e){if(typeof e!="object"||e===null||!("messages"in e)||!("start"in e)||!("total"in e)||!("savedAt"in e))return!1;const{messages:t,start:i,total:s,savedAt:o}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof o=="number"&&Cs({messages:t,start:i,total:s})}function Cs(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(Up)}function Up(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 Hp={read:Lp,write:Op,remove:jp};class qp{constructor(t=Hp){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return ar(this.rawHistoryPage(t))}mergeHistory(t,i){const s=Fp(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),ar(s)}applyLiveEvent(t,i){return fp(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 ar(e){const t=e?.start??0;return{messages:Nd(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Hn(e,t=e.length){const i=e.slice(0,t),s=Kp(i,t);if(s!==void 0)return s;const o=Vp(i,t);if(o!==void 0)return o;const r=Math.max(i.lastIndexOf(" "),i.lastIndexOf(`
20
+ `))+1,n=i.slice(r);if(i.slice(0,r).endsWith("@ "))return{kind:"file",query:n,from:r-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&r===0)return{kind:"command",query:n.slice(1),from:r,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:r,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:r,to:t,fileScope:"tracked"}}function qn(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Kp(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 Vp(e,t){const i=e.lastIndexOf(`
21
+ `)+1,s=e.slice(i),o=cr(s,"@ "),r=cr(s,"!@"),n=Math.max(o,r);if(n===-1)return;const a=n===r?"!@":"@ ",l=i+n,p=l+a.length;return{kind:"file",query:e.slice(p),from:l,to:t,fileScope:"all",allPrefix:a}}function cr(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||Gp(e[i-1]))return i;return-1}function Gp(e){return e===" "||e===" "}function so(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Qp(e).startsWith("/")?{kind:"command"}:Hn(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function Jp(e){return so(e).kind==="shell"}function Qp(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
+ `))+1;return e.slice(t)}class Zp{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,o="local"){this.close(),this.machineId=o,this.session=t,this.onEvent=i,this.onReconnect=s,this.shouldReconnect=!0,this.open()}setHandler(t){this.onEvent=t}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Vn(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=md(this.session,this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Kn(t);Xp(i)&&this.onEvent?.(i)}}class lr{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Vn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=vd(this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Kn(t);eh(i)&&this.onEvent?.(i)}}function Xp(e){const t=oo(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 Yp(e){const t=oo(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function eh(e){const t=oo(e);return Yp(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function oo(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Kn(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 Vn(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}function Bt(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class Oi{constructor(t,i,s=Bt()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[o,r]of th(t,i,s))this.values.set(o,r)}get(t){return this.values.get(t)}set(t,i){this.values.set(t,i),this.save()}delete(t){this.values.delete(t),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}const t={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(t))}catch{}}}function ro(e){return typeof e=="string"&&e!==""?e:void 0}function th(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const o=JSON.parse(s);if(!ih(o))return[];const r=[];for(const n of o.entries){const a=n[0],l=t(n[1]);l!==void 0&&r.push([a,l])}return r}catch{return[]}}function ih(e){return!sh(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 sh(e){return typeof e=="object"&&e!==null}class oh{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 rh="pi-web:session-selection:v1";class nh{constructor(t=Bt()){this.sessionIdsByCwd=new Oi(rh,ro,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function ah(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return lh(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>o.archived!==!0):e.find(o=>o.archived!==!0)}function ch(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function lh(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function dh(e,t,i){return Ms(e,[t],i)}function Ms(e,t,i){const s=new Set(t);return e.map(o=>s.has(o.id)?{...o,archived:!0,archivedAt:i}:o)}function ph(e,t,i){return Ts(e,t,[i])}function Ts(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),o=e.find(r=>!s.has(r.id)&&r.archived!==!0);return o===void 0?{type:"clear"}:{type:"select",session:o}}const xt=100;class hh{constructor(t,i,s,o=new oh,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=o,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=r.socket??new Zp,this.api=r.api??N,this.transcripts=r.transcripts??new qp}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0,availableThinkingLevels:[]})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();ch(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);tr(s,i);const o=Is(s,i);this.setState({sessions:[o,...this.getState().sessions.filter(r=>r.id!==o.id)]}),await this.selectSession(o)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return ah(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const o=this.sessionCacheKey(t.id),r=this.transcripts.cachedView(o);this.setState({selectedSession:t,...r,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const u=await this.api.messages(t,{limit:xt},f(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(o,u);this.setState({...h,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t,u=>n.push(u),()=>{this.refreshSelectedSession(t.id)},f(this.getState()));const[a,l]=await Promise.all([this.api.messages(t,{limit:xt},f(this.getState())),this.api.status(t,f(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(o,a);this.setState({...p,isLoadingEarlierMessages:!1,...this.setStreamCatchup(l.isStreaming?t.id:void 0),status:l,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(l),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(ee(t)&&Sh(n)){await this.recreateCachedNewSession(t,i);return}this.setState({error:String(n)})}}async loadEarlierMessages(){const t=this.getState(),i=t.selectedSession;if(!(!i||t.isLoadingEarlierMessages||t.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{const s=await this.api.messages(i,{before:t.messagePageStart,limit:xt},f(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(o)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i,s,o="inline"){const r=t.trim(),n=s!==void 0&&s.length>0;if(!n&&r.startsWith("/"))return this.runCommand(t);if(!n&&Jp(t))return this.runShell(t);const a=this.getState().selectedSession;if(!a||a.archived===!0)return;const l=a.id,p=f(this.getState());n&&this.markSendingPrompt(l,!0);try{if(n&&o==="folder"){const h=(await this.api.saveAttachments(a,s,p)).map(w=>qn(w.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(l,!1)}}markSendingPrompt(t,i){const s=this.getState().sendingPrompts;i?s[t]!==!0&&this.setState({sendingPrompts:{...s,[t]:!0}}):t in s&&this.setState({sendingPrompts:qn(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Ae("user",t)]});try{await this.api.shell(i,t,f(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Ae("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,Ae("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(ee(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,f(this.getState()));const i=this.getState(),s=sh(i.sessions,t.id,new Date().toISOString()),r=rh(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||ee(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=Cs(r.sessions,s,new Date().toISOString()),n=Ms(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=ao(t).filter(n=>n.archived!==!0&&!ee(n));if(i.length===0)return;const s=f(this.getState()),r=await Promise.allSettled(i.map(async n=>(await this.api.archive(n,s),n.id))),o=co(r);if(o.length>0){const n=this.getState(),a=Cs(n.sessions,o,new Date().toISOString()),l=Ms(a,n.selectedSession?.id,o);this.setState({sessions:a}),l.type==="select"?await this.selectSession(l.session):l.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionError("Archive",r)}async deleteArchivedSessions(t){const i=ao(t).filter(a=>a.archived===!0);if(i.length===0)return;const s=f(this.getState()),r=this.getState().machineRuntimes[s];if(r?.ok!==!0||!_t(r,pt.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}const o=await Promise.allSettled(i.map(async a=>(await this.api.deleteArchived(a,s),a.id))),n=co(o);if(n.length>0){const a=new Set(n),l=this.getState(),p=l.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),l.selectedSession!==void 0&&a.has(l.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionError("Delete",o)}async deleteCachedNewSession(t=this.getState().selectedSession){if(!ee(t))return;this.api.stop(t,f(this.getState())).catch(()=>{}),Yr(t.id,f(this.getState())),tr(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||ee(t)||t.archived===!0)return;const i=f(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!_t(s,pt.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.flushPendingTranscriptEvents();const[s,r]=await Promise.all([this.api.messages(i,{limit:St},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)})}}applyBulkSessionError(t,i){const s=ah(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return Wn(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);Xr(r,s),ap(this.sessionCacheKey(t.id),this.sessionCacheKey(r.id)),Yr(t.id,s);const o=Rs(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(!ee(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Wd(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,Ae(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&bi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,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"&&!Xe(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...ph(i,t.sessionId,t.messageCount),...s?{sessionActivities:nh(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(hh(t))return}if(uh(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}setStreamCatchup(t){return this.catchupStreamSessionId=t,{isReceivingPartialStream:t!==void 0}}finishStreamCatchup(t){const i=this.getState().selectedSession?.id===t;(this.catchupStreamSessionId===t||i&&this.getState().isReceivingPartialStream)&&(this.catchupStreamSessionId=void 0,i&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:St},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 nh(e,t){return qn(e,t)}function qn(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function ao(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 co(e){return e.filter(ch).map(t=>t.value)}function ah(e){return e.filter(lh).map(t=>dh(t.reason))}function ch(e){return e.status==="fulfilled"}function lh(e){return e.status==="rejected"}function dh(e){return e instanceof Error?e.message:String(e)}function ph(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 hh(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 uh(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function fh(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class gh{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 mh="pi-web:workspace-selection:v1";class vh{constructor(t=zt()){this.workspaceIdsByProject=new Oi(mh,rr,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function bh(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 wh{constructor(t,i,s,r,o=new gh,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=r,this.workspaceSelection=o,this.api=n.api??z}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...oi()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Qi(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,...oi()});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=bh(r,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Qi(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:Qi(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...oi()});try{const r=Dd(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=Sh(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 yh(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function Sh(e){return e.find(t=>t.isMain)??e[0]}const xh="pi-web:machine-navigation:v1";class kh{constructor(t=zt()){this.snapshotsByMachine=new Oi(xh,Ph,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?ho(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,ho(t))}forget(t){this.snapshotsByMachine.delete(t)}}function $h(e){return{machineId:e,surface:{}}}function lo(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??Dn,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 po(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 ho(e){return{...e,surface:{...e.surface}}}function Ph(e){if(!Vn(e))return;const t=Oe(e,"machineId");if(t===void 0)return;const i=Kn(Oe(e,"tool")),s=Ih(Oe(e,"view"));return{machineId:t,projectId:Oe(e,"projectId"),workspaceId:Oe(e,"workspaceId"),sessionId:Oe(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:Rh(e.surface)}}function Rh(e){return Vn(e)?{selectedFilePath:Oe(e,"selectedFilePath"),selectedDiffPath:Oe(e,"selectedDiffPath"),selectedTerminalId:Oe(e,"selectedTerminalId")}:{}}function Ih(e){return e==="navigation"||e==="chat"?e:Kn(e)}function Kn(e){return Ch(e)?e:void 0}function Ch(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Oe(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Vn(e){return typeof e=="object"&&e!==null}const Mh="pi-web:terminal-selection:v1";class Th{constructor(t=zt()){this.terminalIdsByCwd=new Oi(Mh,rr,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 Kw(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 Vw(e){return e.find(t=>!t.exited)??e[0]}const Gn=1200,Ah=["mod","alt","shift"];class Eh{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const r=Qn(t);if(r===void 0)return!1;const o=or(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(),!Ot(r))return!1}else if(!Ot(r))return!1;return this.handleSequence([r],o)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(o=>Bh(o.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(o=>nr(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},Gn)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function or(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Dh(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(Ts)[0];u!==void 0&&o.set(u.key,u)}const n=[...o.values()].sort(Oh),a=new Map,l=new Map;for(const p of s){const u=o.get(p.key);if(u===void 0)continue;const h=Lh(u,n)??u;l.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=l.get(p),h=u===p,g=u===void 0||h?void 0:uo(u),w=h?[...a.get(p)??[]].sort(Ts).map(uo):[];return{...p,active:h,shadows:w,...g===void 0?{}:{shadowedBy:g}}}).sort((p,u)=>p.order-u.order)}function ts(e){return Zn(e,{requireFirstChordActivator:!0})}function Jn(e){const t=Zn(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function ai(e){return Jn(e).map(t=>t.split("+").map(Yn).join("+")).join(" ")}function Qn(e){if(e.isComposing)return;const t=Nh(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 Ot(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Dh(e,t,i){const s=Wh(e.id,t);if(s===null)return;const r=s??e.shortcut;if(r===void 0||r==="")return;const o=Jn(r),n=o[0];if(!(n===void 0||!Ot(n)))return{action:e,shortcut:o.join(" "),source:s===void 0?"default":"custom",tokens:o,key:_h(o),order:i}}function Wh(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function _h(e){return e.join("\0")}function uo(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Ts(e,t){return fo(e.source)-fo(t.source)||go(e.action.id,t.action.id)||go(e.action.title,t.action.title)||e.order-t.order}function Oh(e,t){return e.tokens.length-t.tokens.length||Ts(e,t)}function Lh(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&nr(e.tokens,i.tokens))}function fo(e){switch(e){case"custom":return 0;case"default":return 1}}function go(e,t){return e<t?-1:e>t?1:0}function Zn(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=jh(n);if(!a.ok)return a;if(o===0&&t.requireFirstChordActivator&&!Ot(a.token))return{ok:!1,message:"快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。"};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function jh(e){const t=e.split("+").filter(o=>o!=="");if(t.length===0)return{ok:!1,message:"快捷键组合必须包含一个按键。"};const i=new Set;let s;for(const o of t){const n=Fh(o);if(n!==void 0){if(i.has(n))return{ok:!1,message:`快捷键包含重复的 ${Yn(n)} 修饰键。`};i.add(n);continue}const a=Xn(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:[...Ah.filter(o=>i.has(o)),s].join("+")}}function Fh(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 Xn(e){const t=zh(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function Nh(e){if(e===" ")return"space";const t=e.toLowerCase();return Xn(t)}function zh(e){switch(e){case" ":case"spacebar":case"space":return"space";case"esc":case"escape":return"escape";case"return":case"enter":return"enter";case"del":case"delete":return"delete";case"backspace":return"backspace";case"tab":return"tab";case"up":case"arrowup":return"arrowup";case"down":case"arrowdown":return"arrowdown";case"left":case"arrowleft":return"arrowleft";case"right":case"arrowright":return"arrowright";case"pageup":case"pagedown":case"home":case"end":return e;case"+":case"plus":return"plus";case"period":case"dot":return".";case"comma":return",";case"slash":return"/";case"backslash":return"\\";case"minus":return"-";default:return}}function Yn(e){return e==="mod"?mo()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?mo()?"⌥":"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 Bh(e,t){return e.length===t.length&&nr(e,t)}function nr(e,t){return t.every((i,s)=>e[s]===i)}function mo(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const ar="themes:classic",Uh="themes:pi-web-dark",Hh={themeId:Uh,auto:!0},ea="pi-web-app-theme",qh=["--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"],Kh=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Vh(){try{const e=window.localStorage.getItem(ea);return e===null?void 0:Xh(e)}catch{return}}function Gh(e){try{window.localStorage.setItem(ea,JSON.stringify(e))}catch{}}function Jh(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of qh){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function Qh(e){const t=Zh(e.themes,e.fallbackThemeId??ar),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=ta(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 Zh(e,t=ar){return e.find(i=>i.id===t)??e[0]}function ta(e,t){return e.find(i=>i.light===t||i.dark===t)}function Xh(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return Yh(i)?i:void 0}catch{return}}function Yh(e){if(!eu(e))return!1;const t=e.themeId,i=e.auto;return tu(t)&&typeof i=="boolean"}function eu(e){return typeof e=="object"&&e!==null}function tu(e){return typeof e=="string"&&Kh.test(e)}const iu="management";function su(e){return ru(ou())===iu}function ru(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function ou(){return typeof window>"u"?void 0:window.location.search}const nu="workspace.delete",au="pi.operation",cu="target.workspaceId";function lu(e){return{...e===void 0?{}:{projectId:e},metadata:{[au]:nu}}}function du(e){const t={};for(const i of e){const s=As(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 pu(e){return Object.entries(e).filter(([,t])=>xi(t)).map(([t])=>t)}function ia(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&xi(i)}function As(e){return e.metadata[cu]}function xi(e){return e.status==="queued"||e.status==="running"}function vo(){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:xt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:bo,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:xt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:xt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:bo,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:xt,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:hu,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:xt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:uu,run:e=>e.archiveSession()},{id:"session.reload",title:"重新加载会话",description:"从磁盘重新读取所选会话,以获取其他进程写入的条目",group:"会话",enabled:gu,run:e=>e.reloadSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:fu,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&Xe(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function xt(e){return e.state.selectedWorkspace!==void 0}function bo(e){return e.state.selectedWorkspace?.isGitRepo===!0}function hu(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!ia(e.state,t)}function uu(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!ee(t)}function fu(e){return ee(e.state.selectedSession)}function gu(e){const t=e.state.selectedSession;if(t===void 0||t.archived===!0||ee(t))return!1;const i=e.state.machineRuntimes[f(e.state)];return i?.ok!==!0||!_t(i,pt.sessionsReload)?!1:!Xe(e.state.status,e.state.activity)}const mu="modulepreload",vu=function(e){return"/"+e},wo={},sa=function(t,i,s){let r=Promise.resolve();if(i&&i.length>0){let l=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=l(i.map(p=>{if(p=vu(p),p in wo)return;wo[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":mu,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)})},bu=10*1024*1024,wu="10 MB";function yu(e){return typeof e!="string"?c`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:ci(e)}function ci(e){switch(e){case"navigation":return ue`
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(l,!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:Gn(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Ae("user",t)]});try{await this.api.shell(i,t,f(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Ae("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!i||i.archived===!0)return;const s=i.id;this.markSendingPrompt(s,!0);try{this.applyCommandResult(await this.api.runCommand(i,t,f(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(o){this.setState({messages:[...this.getState().messages,Ae("system",String(o))],error:String(o)})}finally{this.markSendingPrompt(s,!1)}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s,t,i,f(this.getState())))}catch(o){this.setState({error:String(o)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(ee(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,f(this.getState()));const i=this.getState(),s=dh(i.sessions,t.id,new Date().toISOString()),o=ph(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),o.type==="select"?await this.selectSession(o.session):o.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||ee(t)))try{const i=await this.api.archiveWithDescendants(t,f(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],o=this.getState(),r=Ms(o.sessions,s,new Date().toISOString()),n=Ts(r,o.selectedSession?.id,s);this.setState({sessions:r}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async archiveSessions(t){const i=dr(t).filter(n=>n.archived!==!0&&!ee(n));if(i.length===0)return;const s=f(this.getState()),o=await Promise.allSettled(i.map(async n=>(await this.api.archive(n,s),n.id))),r=pr(o);if(r.length>0){const n=this.getState(),a=Ms(n.sessions,r,new Date().toISOString()),l=Ts(a,n.selectedSession?.id,r);this.setState({sessions:a}),l.type==="select"?await this.selectSession(l.session):l.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionError("Archive",o)}async deleteArchivedSessions(t){const i=dr(t).filter(a=>a.archived===!0);if(i.length===0)return;const s=f(this.getState()),o=this.getState().machineRuntimes[s];if(o?.ok!==!0||!Lt(o,ht.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}const r=await Promise.allSettled(i.map(async a=>(await this.api.deleteArchived(a,s),a.id))),n=pr(r);if(n.length>0){const a=new Set(n),l=this.getState(),p=l.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),l.selectedSession!==void 0&&a.has(l.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionError("Delete",r)}async deleteCachedNewSession(t=this.getState().selectedSession){if(!ee(t))return;this.api.stop(t,f(this.getState())).catch(()=>{}),ir(t.id,f(this.getState())),io(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(o=>o.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(o=>o.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t,f(this.getState()));const i={...t};delete i.archived,delete i.archivedAt,this.replaceSession(i),this.getState().selectedSession?.id===i.id&&await this.selectSession(i)}catch(i){this.setState({error:String(i)})}}async reloadSession(t=this.getState().selectedSession){if(t===void 0||ee(t)||t.archived===!0)return;const i=f(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!Lt(s,ht.sessionsReload)){this.setState({error:"Reloading sessions requires an updated Pi-Web runtime on this machine."});return}try{await this.api.reloadSession(t.id,i),this.transcripts.discard(this.sessionCacheKey(t.id)),this.getState().selectedSession?.id===t.id&&await this.selectSession(t,{updateUrl:!1})}catch(o){this.setState({error:String(o)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t,f(this.getState()));const i={...t};delete i.parentSessionPath,this.replaceSession(i)}catch(i){this.setState({error:String(i)})}}async listModels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.models(t,f(this.getState()))).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s,t,i,f(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(o){this.setState({error:String(o)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,f(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(s){this.setState({error:String(s)})}}async listThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.thinkingLevels(t,f(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async refreshAvailableThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}const i=await this.listThinkingLevels();this.getState().selectedSession?.id===t.id&&this.setState({availableThinkingLevels:i})}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i,t,f(this.getState())))}catch(s){this.setState({error:String(s)})}}async cycleThinkingLevel(){const t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(t,f(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,f(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingTranscriptEvents();const[s,o]=await Promise.all([this.api.messages(i,{limit:xt},f(this.getState())),this.api.status(i,f(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...r,status:o,activity:this.getState().sessionActivities[t],...this.setStreamCatchup(o.isStreaming?t:void 0)}),this.applyStatus(o)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionError(t,i){const s=fh(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return Ln(f(this.getState()),t)}workspaceSelectionKey(t){return`${f(this.getState())}:${t}`}replaceSession(t){const i=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s=>s.id===t.id?t:s),selectedSession:i?.id===t.id?t:i})}async recreateCachedNewSession(t,i){try{const s=f(this.getState()),o=await this.api.startSession(t.cwd,s);tr(o,s),lp(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),ir(t.id,s);const r=Is(o,s);this.setState({sessions:[r,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(r,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!ee(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Ld(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,Ae(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&wi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,o=[t.session,...this.getState().sessions.filter(r=>r.id!==t.session?.id)];this.setState({sessions:o,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();i.selectedWorkspace?.path===t.cwd&&(i.sessions.some(s=>s.id===t.id)||this.setState({sessions:[t,...i.sessions]}))}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Xe(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...bh(i,t.sessionId,t.messageCount),...s?{sessionActivities:uh(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),t.isStreaming||this.finishStreamCatchup(t.sessionId)}applySessionName(t,i){const s=r=>{if(r.id!==t)return r;const n={...r};return i===void 0||i===""?delete n.name:n.name=i,n},o=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:o===void 0?void 0:s(o)})}applyEvent(t){const i=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===i){if(t.type==="message.end"||t.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(wh(t))return}if(yh(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}setStreamCatchup(t){return this.catchupStreamSessionId=t,{isReceivingPartialStream:t!==void 0}}finishStreamCatchup(t){const i=this.getState().selectedSession?.id===t;(this.catchupStreamSessionId===t||i&&this.getState().isReceivingPartialStream)&&(this.catchupStreamSessionId=void 0,i&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:xt},f(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),s))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function uh(e,t){return Gn(e,t)}function Gn(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function dr(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 pr(e){return e.filter(gh).map(t=>t.value)}function fh(e){return e.filter(mh).map(t=>vh(t.reason))}function gh(e){return e.status==="fulfilled"}function mh(e){return e.status==="rejected"}function vh(e){return e instanceof Error?e.message:String(e)}function bh(e,t,i){if(i===void 0)return{};const o=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,r=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...o===void 0?{}:{sessions:o},...r!==e.selectedSession?{selectedSession:r}:{}}}function wh(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 yh(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function Sh(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class xh{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 kh="pi-web:workspace-selection:v1";class $h{constructor(t=Bt()){this.workspaceIdsByProject=new Oi(kh,ro,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function Ph(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e[0]:e[0]}class Rh{constructor(t,i,s,o,r=new xh,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??N}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...ni()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(Zi(f(this.getState()),t));const i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([s])=>s!==t));this.setState({workspacesByProjectId:i})}async selectProject(t,i){const s=f(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...ni()});try{const o=await this.api.workspaces(t.id,s);if(f(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:o,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:o},isLoadingWorkspaces:!1});const r=Ph(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Zi(s,t.id))});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){f(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(o),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=f(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:Zi(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...ni()});try{const o=_d(t.path,await this.api.sessions(t.path,s),s);if(f(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:o});const r=this.sessions.preferredSession(t.path,o,i?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){f(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(o)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(o=>o.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,f(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),o=this.getState();if(o.selectedProject?.id!==t||o.selectedWorkspace?.id!==i)return;const r=Ch(s);r!==void 0?await this.selectWorkspace(r):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),o={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:o}):this.setState({workspacesByProjectId:o})}}function Ih(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function Ch(e){return e.find(t=>t.isMain)??e[0]}const Mh="pi-web:machine-navigation:v1";class Th{constructor(t=Bt()){this.snapshotsByMachine=new Oi(Mh,Eh,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?fr(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,fr(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Ah(e){return{machineId:e,surface:{}}}function hr(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??_n,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 ur(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 fr(e){return{...e,surface:{...e.surface}}}function Eh(e){if(!Qn(e))return;const t=Le(e,"machineId");if(t===void 0)return;const i=Jn(Le(e,"tool")),s=Wh(Le(e,"view"));return{machineId:t,projectId:Le(e,"projectId"),workspaceId:Le(e,"workspaceId"),sessionId:Le(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:Dh(e.surface)}}function Dh(e){return Qn(e)?{selectedFilePath:Le(e,"selectedFilePath"),selectedDiffPath:Le(e,"selectedDiffPath"),selectedTerminalId:Le(e,"selectedTerminalId")}:{}}function Wh(e){return e==="navigation"||e==="chat"?e:Jn(e)}function Jn(e){return _h(e)?e:void 0}function _h(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Le(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Qn(e){return typeof e=="object"&&e!==null}const Lh="pi-web:terminal-selection:v1";class Oh{constructor(t=Bt()){this.terminalIdsByCwd=new Oi(Lh,ro,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 sy(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>!o.exited)??e[0]:e.find(o=>!o.exited)??e[0]}function oy(e){return e.find(t=>!t.exited)??e[0]}const Zn=1200,jh=["mod","alt","shift"];class Fh{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=Yn(t);if(o===void 0)return!1;const r=no(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,o],r))return!0;if(this.clearPending(),!Ot(o))return!1}else if(!Ot(o))return!1;return this.handleSequence([o],r)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(r=>Jh(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>ao(r.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Zn)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function no(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=zh(p,t,u);return h===void 0?[]:[h]}),o=new Map;for(const p of s)o.set(p.key,[...o.get(p.key)??[],p]);const r=new Map;for(const p of o.values()){const u=[...p].sort(As)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort(Uh),a=new Map,l=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=Hh(u,n)??u;l.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=l.get(p),h=u===p,g=u===void 0||h?void 0:gr(u),w=h?[...a.get(p)??[]].sort(As).map(gr):[];return{...p,active:h,shadows:w,...g===void 0?{}:{shadowedBy:g}}}).sort((p,u)=>p.order-u.order)}function is(e){return ea(e,{requireFirstChordActivator:!0})}function Xn(e){const t=ea(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function ci(e){return Xn(e).map(t=>t.split("+").map(ia).join("+")).join(" ")}function Yn(e){if(e.isComposing)return;const t=Vh(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 Ot(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function zh(e,t,i){const s=Nh(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=Xn(o),n=r[0];if(!(n===void 0||!Ot(n)))return{action:e,shortcut:r.join(" "),source:s===void 0?"default":"custom",tokens:r,key:Bh(r),order:i}}function Nh(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Bh(e){return e.join("\0")}function gr(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function As(e,t){return mr(e.source)-mr(t.source)||vr(e.action.id,t.action.id)||vr(e.action.title,t.action.title)||e.order-t.order}function Uh(e,t){return e.tokens.length-t.tokens.length||As(e,t)}function Hh(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&ao(e.tokens,i.tokens))}function mr(e){switch(e){case"custom":return 0;case"default":return 1}}function vr(e,t){return e<t?-1:e>t?1:0}function ea(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"请输入快捷键,选择无,或重置为默认值。"};const s=[],o=i.split(/\s+/u).filter(r=>r!=="");for(const[r,n]of o.entries()){const a=qh(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!Ot(a.token))return{ok:!1,message:"快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。"};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function qh(e){const t=e.split("+").filter(r=>r!=="");if(t.length===0)return{ok:!1,message:"快捷键组合必须包含一个按键。"};const i=new Set;let s;for(const r of t){const n=Kh(r);if(n!==void 0){if(i.has(n))return{ok:!1,message:`快捷键包含重复的 ${ia(n)} 修饰键。`};i.add(n);continue}const a=ta(r);if(a===void 0)return{ok:!1,message:`不支持的快捷键按键:${r}`};if(s!==void 0)return{ok:!1,message:"每个快捷键组合只能包含一个非修饰键。"};s=a}return s===void 0?{ok:!1,message:"快捷键组合必须包含一个按键。"}:{ok:!0,token:[...jh.filter(r=>i.has(r)),s].join("+")}}function Kh(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 ta(e){const t=Gh(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 Vh(e){if(e===" ")return"space";const t=e.toLowerCase();return ta(t)}function Gh(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 ia(e){return e==="mod"?br()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?br()?"⌥":"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 Jh(e,t){return e.length===t.length&&ao(e,t)}function ao(e,t){return t.every((i,s)=>e[s]===i)}function br(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const co="themes:classic",Qh="themes:pi-web-dark",Zh={themeId:Qh,auto:!0},sa="pi-web-app-theme",Xh=["--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"],Yh=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function eu(){try{const e=window.localStorage.getItem(sa);return e===null?void 0:ru(e)}catch{return}}function tu(e){try{window.localStorage.setItem(sa,JSON.stringify(e))}catch{}}function iu(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of Xh){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function su(e){const t=ou(e.themes,e.fallbackThemeId??co),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=oa(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const o=e.prefersLight?s.light:s.dark,r=e.themes.find(n=>n.id===o)??i;return{selectedTheme:i,activeTheme:r,selectedThemePair:s,fallbackTheme:t}}function ou(e,t=co){return e.find(i=>i.id===t)??e[0]}function oa(e,t){return e.find(i=>i.light===t||i.dark===t)}function ru(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return nu(i)?i:void 0}catch{return}}function nu(e){if(!au(e))return!1;const t=e.themeId,i=e.auto;return cu(t)&&typeof i=="boolean"}function au(e){return typeof e=="object"&&e!==null}function cu(e){return typeof e=="string"&&Yh.test(e)}const lu="management";function du(e){return pu(hu())===lu}function pu(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function hu(){return typeof window>"u"?void 0:window.location.search}const uu="workspace.delete",fu="pi.operation",gu="target.workspaceId";function mu(e){return{...e===void 0?{}:{projectId:e},metadata:{[fu]:uu}}}function vu(e){const t={};for(const i of e){const s=Es(i);if(s===void 0)continue;const o=t[s];(o===void 0||i.createdAt.localeCompare(o.createdAt)>=0)&&(t[s]=i)}return t}function bu(e){return Object.entries(e).filter(([,t])=>ki(t)).map(([t])=>t)}function ra(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&ki(i)}function Es(e){return e.metadata[gu]}function ki(e){return e.status==="queued"||e.status==="running"}function wr(){return[{id:"actions.show",title:"显示操作",description:"打开命令面板",shortcut:"mod+k",group:"通用",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"聚焦提示词输入框",description:"将键盘焦点移动到消息编辑器",shortcut:"mod+g c",group:"通用",enabled:e=>e.state.selectedSession!==void 0,run:e=>{e.focusPrompt()}},{id:"machine.add",title:"添加机器",description:"注册另一个可从当前网关访问的 PI WEB 运行时",group:"机器",run:e=>e.addMachine()},{id:"machine.refresh",title:"刷新所选机器",description:"检查所选 PI WEB 运行时是否在线",group:"机器",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"打开所选机器的 PI WEB",description:"在新标签页中直接打开所选远程 PI WEB",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"移除所选机器",description:"从当前网关移除所选远程机器",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{id:"project.add",title:"添加项目",group:"项目",run:e=>e.addProject()},{id:"auth.login",title:"配置提供商认证",description:"运行 /login,但不将认证绑定到某个会话",group:"通用",run:e=>e.configureAuth()},{id:"auth.logout",title:"移除提供商认证",description:"针对已保存的 pi 凭据运行 /logout",group:"通用",run:e=>e.logoutAuth()},{id:"theme.select",title:"选择主题",description:"选择 PI WEB 颜色主题",group:"偏好设置",run:e=>{e.openThemePicker()}},{id:"settings.open",title:"打开设置",description:"管理 PI WEB 配置和键盘快捷键",shortcut:"mod+,",group:"偏好设置",run:e=>{e.piWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"完整重载页面",description:"重新加载 PI WEB 浏览器页面",group:"通用",run:e=>{e.reloadPage()}},{id:"view.chat",title:"转到聊天",shortcut:"mod+1",group:"导航",run:e=>{e.focusPrompt()}},{id:"view.files",title:"转到文件",shortcut:"mod+2",group:"导航",enabled:kt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:yr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:kt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:kt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:yr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:kt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"删除工作区",description:"移除所选 Git worktree",group:"工作区",enabled:wu,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:kt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:yu,run:e=>e.archiveSession()},{id:"session.reload",title:"重新加载会话",description:"从磁盘重新读取所选会话,以获取其他进程写入的条目",group:"会话",enabled:xu,run:e=>e.reloadSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:Su,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&Xe(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function kt(e){return e.state.selectedWorkspace!==void 0}function yr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function wu(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!ra(e.state,t)}function yu(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!ee(t)}function Su(e){return ee(e.state.selectedSession)}function xu(e){const t=e.state.selectedSession;if(t===void 0||t.archived===!0||ee(t))return!1;const i=e.state.machineRuntimes[f(e.state)];return i?.ok!==!0||!Lt(i,ht.sessionsReload)?!1:!Xe(e.state.status,e.state.activity)}const ku="modulepreload",$u=function(e){return"/"+e},Sr={},na=function(t,i,s){let o=Promise.resolve();if(i&&i.length>0){let l=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");o=l(i.map(p=>{if(p=$u(p),p in Sr)return;Sr[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":ku,u||(g.as="script"),g.crossOrigin="",g.href=p,a&&g.setAttribute("nonce",a),document.head.appendChild(g),u)return new Promise((w,P)=>{g.addEventListener("load",w),g.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function r(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return o.then(n=>{for(const a of n||[])a.status==="rejected"&&r(a.reason);return t().catch(r)})},Pu=10*1024*1024,Ru="10 MB";function Iu(e){return typeof e!="string"?c`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:li(e)}function li(e){switch(e){case"navigation":return ue`
25
25
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
26
26
  <circle cx="6" cy="7" r="1.5"></circle>
27
27
  <path d="M10 7h8"></path>
@@ -55,53 +55,53 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
55
55
  <path d="m7 10 3 3-3 3"></path>
56
56
  <path d="M12 16h5"></path>
57
57
  </svg>
58
- `}}function yo(){return[{id:"workspace.files",title:"文件",icon:ci("files"),order:10,render:Su},{id:"workspace.git",title:"Git",icon:ci("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:Du},{id:"workspace.terminal",title:"终端",icon:ci("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Eu}]}function Su(e){const t=e.machine.kind==="local";return c`
58
+ `}}function xr(){return[{id:"workspace.files",title:"文件",icon:li("files"),order:10,render:Cu},{id:"workspace.git",title:"Git",icon:li("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:zu},{id:"workspace.terminal",title:"终端",icon:li("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Fu}]}function Cu(e){const t=e.machine.kind==="local";return c`
59
59
  <section class="toolbar">
60
60
  <strong>文件</strong>
61
61
  ${e.fileTreeStale?c`<span class="stale">过期</span>`:null}
62
62
  <div class="toolbar-actions">
63
63
  <button @click=${e.onRefreshFiles}>刷新</button>
64
- <button @click=${()=>{$u(e)}}>新建文件</button>
65
- <button @click=${()=>{Pu(e)}}>新建目录</button>
64
+ <button @click=${()=>{Au(e)}}>新建文件</button>
65
+ <button @click=${()=>{Eu(e)}}>新建目录</button>
66
66
  ${e.selectedFilePath===void 0?null:c`
67
- ${Bt(e)==="file"?c`<button @click=${()=>{e.onDownloadSelectedFile()}}>下载</button>`:null}
68
- <button @click=${()=>{Ru(e)}}>移动</button>
69
- <button class="danger" @click=${()=>{Iu(e)}}>删除</button>
67
+ ${Ut(e)==="file"?c`<button @click=${()=>{e.onDownloadSelectedFile()}}>下载</button>`:null}
68
+ <button @click=${()=>{Du(e)}}>移动</button>
69
+ <button class="danger" @click=${()=>{Wu(e)}}>删除</button>
70
70
  `}
71
71
  ${t?c`
72
- <label class="file-upload-button" role="button" tabindex="0" aria-label="上传文件" @keydown=${xu}>
72
+ <label class="file-upload-button" role="button" tabindex="0" aria-label="上传文件" @keydown=${Mu}>
73
73
  上传
74
- <input type="file" multiple hidden @change=${i=>{ku(e,i)}} />
74
+ <input type="file" multiple hidden @change=${i=>{Tu(e,i)}} />
75
75
  </label>
76
76
  `:c`<span class="file-upload-button disabled" title="远端机器暂不支持上传" aria-disabled="true">上传</span>`}
77
77
  </div>
78
78
  </section>
79
79
  <section class="split">
80
80
  <div class="list tree">
81
- ${e.fileTree.length===0?c`<p class="muted">尚未加载文件。</p>`:e.fileTree.map(i=>ra(e,i,0))}
81
+ ${e.fileTree.length===0?c`<p class="muted">尚未加载文件。</p>`:e.fileTree.map(i=>aa(e,i,0))}
82
82
  </div>
83
83
  <div class="viewer">
84
- ${Tu(e)}
84
+ ${Ou(e)}
85
85
  </div>
86
86
  </section>
87
- `}function xu(e){if(e.key!=="Enter"&&e.key!==" ")return;e.preventDefault();const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=t.querySelector("input[type='file']");i instanceof HTMLInputElement&&i.click()}function ku(e,t){const i=t.currentTarget;!(i instanceof HTMLInputElement)||i.files===null||(e.onUploadFiles(Array.from(i.files)),i.value="")}function $u(e){const t=window.prompt("新建文件路径",oa(e,"new-file.txt"));t===null||t.trim()===""||e.onCreateFile(t.trim())}function Pu(e){const t=window.prompt("新建目录路径",oa(e,"new-folder"));t===null||t.trim()===""||e.onCreateDirectory(t.trim())}function Ru(e){const t=e.selectedFilePath;if(t===void 0||t==="")return;const i=window.prompt(Bt(e)==="directory"?"移动或重命名目录到":"移动或重命名文件到",t);i===null||i.trim()===""||i.trim()===t||e.onMoveSelectedPath(i.trim())}function Iu(e){const t=e.selectedFilePath;if(t===void 0||t==="")return;const i=Bt(e)==="directory"?"空目录":"文件";window.confirm(`删除${i} ${t}?`)&&e.onDeleteSelectedPath()}function ra(e,t,i){const s=e.expandedDirs[t.path],r=s!==void 0,o=e.selectedFilePath===t.path;return c`
88
- <button class=${o?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{Cu(e,t)}}>
89
- <span>${t.type==="directory"?r?"▾":"▸":"·"}</span>
87
+ `}function Mu(e){if(e.key!=="Enter"&&e.key!==" ")return;e.preventDefault();const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=t.querySelector("input[type='file']");i instanceof HTMLInputElement&&i.click()}function Tu(e,t){const i=t.currentTarget;!(i instanceof HTMLInputElement)||i.files===null||(e.onUploadFiles(Array.from(i.files)),i.value="")}function Au(e){const t=window.prompt("新建文件路径",ca(e,"new-file.txt"));t===null||t.trim()===""||e.onCreateFile(t.trim())}function Eu(e){const t=window.prompt("新建目录路径",ca(e,"new-folder"));t===null||t.trim()===""||e.onCreateDirectory(t.trim())}function Du(e){const t=e.selectedFilePath;if(t===void 0||t==="")return;const i=window.prompt(Ut(e)==="directory"?"移动或重命名目录到":"移动或重命名文件到",t);i===null||i.trim()===""||i.trim()===t||e.onMoveSelectedPath(i.trim())}function Wu(e){const t=e.selectedFilePath;if(t===void 0||t==="")return;const i=Ut(e)==="directory"?"空目录":"文件";window.confirm(`删除${i} ${t}?`)&&e.onDeleteSelectedPath()}function aa(e,t,i){const s=e.expandedDirs[t.path],o=s!==void 0,r=e.selectedFilePath===t.path;return c`
88
+ <button class=${r?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{_u(e,t)}}>
89
+ <span>${t.type==="directory"?o?"▾":"▸":"·"}</span>
90
90
  <span>${t.name}</span>
91
91
  </button>
92
- ${r?s.map(n=>ra(e,n,i+1)):null}
93
- `}function Cu(e,t){t.type==="directory"?(e.onSelectDirectory(t.path),e.onExpandDir(t.path)):e.onSelectFile(t.path)}function Bt(e){const t=e.selectedFilePath;return t===void 0?"file":Mu(e,t)?.type??"file"}function oa(e,t){const i=e.selectedFilePath;if(i===void 0||i==="")return t;if(Bt(e)==="directory")return`${i}/${t}`;const s=i.lastIndexOf("/");return s===-1?t:`${i.slice(0,s)}/${t}`}function Mu(e,t){const i=e.fileTree.find(s=>s.path===t);if(i!==void 0)return i;for(const s of Object.values(e.expandedDirs)){const r=s.find(o=>o.path===t);if(r!==void 0)return r}}function Tu(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?c`<p class="muted">请选择文件。</p>`:Bt(e)==="directory"?c`<p class="muted">已选择目录 ${e.selectedFilePath}。</p>`:t===void 0?c`<p class="muted">正在加载 ${e.selectedFilePath}…</p>`:t.mediaType==="image"?Au(e,t):t.binary?c`<p class="muted">二进制文件:${t.path} · ${Es(t.size)}</p>`:(na(),c`
92
+ ${o?s.map(n=>aa(e,n,i+1)):null}
93
+ `}function _u(e,t){t.type==="directory"?(e.onSelectDirectory(t.path),e.onExpandDir(t.path)):e.onSelectFile(t.path)}function Ut(e){const t=e.selectedFilePath;return t===void 0?"file":Lu(e,t)?.type??"file"}function ca(e,t){const i=e.selectedFilePath;if(i===void 0||i==="")return t;if(Ut(e)==="directory")return`${i}/${t}`;const s=i.lastIndexOf("/");return s===-1?t:`${i.slice(0,s)}/${t}`}function Lu(e,t){const i=e.fileTree.find(s=>s.path===t);if(i!==void 0)return i;for(const s of Object.values(e.expandedDirs)){const o=s.find(r=>r.path===t);if(o!==void 0)return o}}function Ou(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?c`<p class="muted">请选择文件。</p>`:Ut(e)==="directory"?c`<p class="muted">已选择目录 ${e.selectedFilePath}。</p>`:t===void 0?c`<p class="muted">正在加载 ${e.selectedFilePath}…</p>`:t.mediaType==="image"?ju(e,t):t.binary?c`<p class="muted">二进制文件:${t.path} · ${Ds(t.size)}</p>`:(la(),c`
94
94
  <div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"文本"}${t.truncated?" · 已截断":""}</small></div>
95
95
  <code-viewer .content=${t.content} .language=${t.language}></code-viewer>
96
- `)}function Au(e,t){const i=`${t.mimeType??"image"} · ${Es(t.size)}`;if(t.size>bu)return c`
96
+ `)}function ju(e,t){const i=`${t.mimeType??"image"} · ${Ds(t.size)}`;if(t.size>Pu)return c`
97
97
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
98
- <p class="muted">图片过大,无法预览:${Es(t.size)} · 限制 ${wu}</p>
99
- `;const s=Yl(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return c`
98
+ <p class="muted">图片过大,无法预览:${Ds(t.size)} · 限制 ${Ru}</p>
99
+ `;const s=td(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return c`
100
100
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
101
101
  <div class="image-preview">
102
102
  <img src=${s} alt=${t.path} decoding="async" />
103
103
  </div>
104
- `}function Eu(e){return Ou(),c`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Du(e){const t=e.gitStatus;return c`
104
+ `}function Fu(e){return Uu(),c`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function zu(e){const t=e.gitStatus;return c`
105
105
  <section class="toolbar">
106
106
  <strong>Git</strong>
107
107
  ${e.gitStale?c`<span class="stale">过期</span>`:null}
@@ -110,29 +110,29 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
110
110
  <section class="split">
111
111
  <div class="list">
112
112
  ${t===void 0?c`<p class="muted">尚未加载状态。</p>`:t.isGitRepo?c`
113
- <p class="summary">${Lu(t)}</p>
113
+ <p class="summary">${Hu(t)}</p>
114
114
  ${t.files.length===0?c`<p class="muted">没有变更。</p>`:t.files.map(i=>c`
115
115
  <button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
116
- <span>${ju(i.index,i.workingTree)}</span>
116
+ <span>${qu(i.index,i.workingTree)}</span>
117
117
  <span>${i.path}</span>
118
118
  </button>
119
119
  `)}
120
120
  `:c`<p class="muted">不是 Git 仓库。</p>`}
121
121
  </div>
122
122
  <div class="viewer">
123
- ${Wu(e)}
123
+ ${Nu(e)}
124
124
  </div>
125
125
  </section>
126
- `}function Wu(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return c`<p class="muted">请选择一个已变更文件。</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return c`<p class="muted">正在加载 diff…</p>`;const s=[i,t].filter(r=>r.diff!=="");return s.length===0?c`<p class="muted">没有 staged 或 unstaged diff。</p>`:c`
126
+ `}function Nu(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return c`<p class="muted">请选择一个已变更文件。</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return c`<p class="muted">正在加载 diff…</p>`;const s=[i,t].filter(o=>o.diff!=="");return s.length===0?c`<p class="muted">没有 staged 或 unstaged diff。</p>`:c`
127
127
  <div class=${s.length===1?"diffs single":"diffs"}>
128
- ${s.map(r=>_u(r))}
128
+ ${s.map(o=>Bu(o))}
129
129
  </div>
130
- `}function _u(e){return na(),c`
130
+ `}function Bu(e){return la(),c`
131
131
  <section class="diff-section">
132
132
  <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"已暂存":"未暂存"}${e.truncated?" · 已截断":""}</small></div>
133
133
  <code-viewer .content=${e.diff} .language=${"diff"}></code-viewer>
134
134
  </section>
135
- `}function na(){sa(()=>import("./CodeViewer-D5OA_6r4.js"),__vite__mapDeps([0,1,2,3]))}function Ou(){sa(()=>import("./TerminalPanel-kfPHfhUe.js"),__vite__mapDeps([4,5,6,1,2]))}function Lu(e){const t=e.branch??"分离 HEAD",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function ju(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function Es(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`${is(t)} KB`;const i=t/1024;return i<1024?`${is(i)} MB`:`${is(i/1024)} GB`}function is(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const Fu={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!su();return{contributions:{actions:e?vo():vo().filter(t=>t.id!=="view.terminal"),workspacePanels:e?yo():yo().filter(t=>t.id!=="workspace.terminal")}}}},Nu={"--pi-bg":"#0d1117","--pi-surface":"#161b22","--pi-surface-hover":"#21262d","--pi-terminal-bg":"#05070a","--pi-terminal-text":"#e6edf3","--pi-border":"#30363d","--pi-border-muted":"#21262d","--pi-text":"#e6edf3","--pi-text-secondary":"#c9d1d9","--pi-text-bright":"#f0f6fc","--pi-muted":"#8b949e","--pi-dim":"#6e7681","--pi-accent":"#58a6ff","--pi-accent-border":"#2f81f7","--pi-selection-bg":"#0d2847","--pi-success":"#3fb950","--pi-success-border":"#238636","--pi-success-bg":"#0f1b12","--pi-success-surface":"#0f2a16","--pi-success-ring":"#3fb95055","--pi-warning":"#d29922","--pi-warning-border":"#6e5200","--pi-warning-surface":"#1f1a10","--pi-danger":"#ff7b72","--pi-purple":"#d2a8ff","--pi-purple-border":"#a371f7","--pi-purple-surface":"#21132f","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#0d1117dd","--pi-bg-overlay":"#0d1117e6","--pi-success-bg-overlay":"#0f1b12ee","--pi-terminal-selection":"#264f78"},zu={"--pi-bg":"#070912","--pi-surface":"#101527","--pi-surface-hover":"#151b31","--pi-terminal-bg":"#050710","--pi-terminal-text":"#f7f4ff","--pi-border":"#26304f","--pi-border-muted":"#26304f","--pi-text":"#f7f4ff","--pi-text-secondary":"#aaa4bd","--pi-text-bright":"#ffffff","--pi-muted":"#aaa4bd","--pi-dim":"#817a99","--pi-accent":"#7c3cff","--pi-accent-border":"#5a47b0","--pi-selection-bg":"#1d2547","--pi-success":"#00f0d8","--pi-success-border":"#00f0d8","--pi-success-bg":"#071e22","--pi-success-surface":"#092d31","--pi-success-ring":"#00f0d855","--pi-warning":"#ffb000","--pi-warning-border":"#ffb000","--pi-warning-surface":"#16140d","--pi-danger":"#ff4f7b","--pi-purple":"#b7a2ff","--pi-purple-border":"#7c3cff","--pi-purple-surface":"#181026","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#070912dd","--pi-bg-overlay":"#070912e6","--pi-success-bg-overlay":"#071e22ee","--pi-terminal-selection":"#3d4a78"},Bu={"--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"},Uu={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:zu},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Bu},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Nu}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},Hu=/^[a-z][a-z0-9.-]*$/u;function qu(e){return Hu.test(e)}const Ku="machine.";function Vu(e,t){if(e==="")throw new Error("Machine id is required");if(!qu(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Ku}${Gu(e)}.${t}`}function Gu(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function So(e="/pi-web-plugins/manifest.json",t={}){const i=await Ju(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=Xu(n,o);s.push({id:t.machineId===void 0?r.id:Vu(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 Ju(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 Qu(await t.json())}}function Qu(e){if(!ki(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!ki(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module,machineSpecific:Zu(t.machineSpecific)}})}}function Zu(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function Xu(e,t){if(!ki(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!Yu(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function Yu(e){return ki(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function ki(e){return typeof e=="object"&&e!==null}const ef=/^[a-z][a-z0-9.-]*$/u,tf=/^[a-z][a-z0-9.-]*$/u,aa=new WeakMap,ca=new WeakMap;class sf{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:c,svg:ue}).contributions;for(const l of a.actions??[])this.actions.push(this.qualifyAction(i,l,t.machineId,t.sourcePluginId));for(const l of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,l,t.machineId,t.sourcePluginId));for(const l of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,l,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const l of a.themes??[])this.themes.push(this.qualifyTheme(i,l));for(const l of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,l));this.gatewayPluginIds.add(i),r&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&r&&af(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=lf(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const r=rf(t,s.pluginId),o=s.enabled?.(r),n={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&&(n.description=s.description),s.shortcut!==void 0&&(n.shortcut=s.shortcut),s.group!==void 0&&(n.group=s.group),o!==void 0&&(n.enabled=o),n})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,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:l=>this.isContributionActive(t,s,l.machine.id,r)&&(a?.(ss(l,t))??!0),...n===void 0?{}:{badge:l=>this.isContributionActive(t,s,l.machine.id,r)?n(ss(l,t)):void 0},render:l=>i.render(ss(l,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:l=>this.isContributionActive(t,s,l.machine.id,r)&&(n?.(l)??!0),items:l=>this.isContributionActive(t,s,l.machine.id,r)?a(l):[]}}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(!ef.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!tf.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}: ${cf(i)}`);return i}}function rf(e,t){return aa.get(e)?.(t)??e}function ss(e,t){return ca.get(e)?.(t)??e}function of(e,t){return aa.set(e,t),e}function nf(e,t){return ca.set(e,t),e}function af(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function cf(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 lf(e){return e.state.selectedMachine?.id??"local"}const df=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function pf(){return typeof window>"u"||!("matchMedia"in window)?[]:df.map(e=>window.matchMedia(e))}function xo(e,t=hf()){return e.some(i=>i.matches)||uf(t)}function hf(){return typeof navigator>"u"?void 0:navigator}function uf(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const ff=250;class gf{constructor(t=mf()){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()},ff)}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 mf(){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 vf="(max-width: 760px)";class bf{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=xo(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??wf(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??pf(),this.viewportPositionRepairer=i.viewportPositionRepairer??new gf,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=xo(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange);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.isMobileNavigationLayout?"navigation":"chat"}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function wf(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(vf)}const $i=["machines","projects","workspaces","sessions"];function yf(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function cr(e,t){if(e!=="none")return e??yf(t)}function Sf(e,t){return t.isMobileLayout?cr(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function xf(e,t,i){return cr(e,i.state)===t?"none":t}function kf(e,t,i){return i?t:e}function $f(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),If(i)}function Pf(e){return $i[$i.indexOf(e)+1]}class Rf{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return cr(this.expanded,this.getState())}isCollapsed(t){return Sf(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(xf(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections($f(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(kf(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=Pf(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){Cf(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function If(e){const t=new Set(e);return $i.filter(i=>t.has(i))}function Cf(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class Mf{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",la(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function la(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const Ds="pi-web:panel-sizes:v1",Tf={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Af{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??lr(),this.panelSizes=_f(this.storage)}hostConnected(){}constraints(t){return Ut(t)}panelWidth(t,i){return fe(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const r=fe(t,i);this.storedPanelWidth(t)!==r&&(this.panelSizes=jf(this.panelSizes,t,r),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Ff(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(){Of(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${$o(fe("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${$o(fe("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Ut(e){return Tf[e]}function Ef(e,t,i){return e==="navigation"?i-t:t-i}function Df(e,t,i,s,r=Ut(e)){return fe(e,t+Ef(e,i,s),r)}function Wf(e,t,i,s={}){const r=s.constraints??Ut(e);if(i==="Home")return r.minWidth;if(i==="End")return r.maxWidth;const o=s.largeStep===!0?r.largeKeyboardStep:r.keyboardStep,n=Nf(e,i,o);if(n!==void 0)return fe(e,t+n,r)}function fe(e,t,i=Ut(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function _f(e=lr()){try{const t=e?.getItem(Ds);if(t==null||t==="")return{};const i=JSON.parse(t);return Lf(i)}catch{return{}}}function Of(e,t=lr()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Ds);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=fe("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=fe("workspace",e.workspacePanelWidth)),t.setItem(Ds,JSON.stringify(i))}catch{}}function Lf(e){if(!zf(e)||e.version!==1)return{};const t={},i=ko(e.navigationPanelWidth),s=ko(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=fe("navigation",i)),s!==void 0&&(t.workspacePanelWidth=fe("workspace",s)),t}function ko(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function jf(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Ff(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Nf(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 $o(e){return`${String(Math.round(e))}px`}function lr(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function zf(e){return typeof e=="object"&&e!==null}function Po(){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:Bf(e.get("tool")),view:Uf(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 Bf(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":da(e)?e:void 0}function Uf(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":da(e)?e:void 0}function da(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Ro(){return Hf(new URLSearchParams(window.location.search).get("settings"))}function os(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 Hf(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 qf(e,t){return t===void 0?e:e.map(i=>Vf(i,t))}function Kf(e,t){const i=new Set(or(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return qf(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?pa(s):s)}function Vf(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?pa(e):{...e,shortcut:i}}function pa(e){const t={...e};return delete t.shortcut,t}function Gf(e,t){const i=t.api??lt,s=t.pollIntervalMs??1e3,r=t.setTimeout??Qf(),o=t.clearTimeout??Zf();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:Jf(a,i,s,r,o)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function Jf(e,t,i,s,r){return Io(e)?Promise.resolve(e):new Promise((o,n)=>{let a,l=!1;const p=g=>{l||(l=!0,a!==void 0&&r(a),o(g))},u=g=>{l||(l=!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&&Io(g)){p(g);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function Io(e){return e.status==="succeeded"||e.status==="failed"}function Qf(){return(e,t)=>globalThis.setTimeout(e,t)}function Zf(){return e=>{globalThis.clearTimeout(e)}}function Xf(e,t){return t[e.path]}function Yf(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function eg(e,t,i){return ua(tg(e,t,i))}function ha(e){return ua(Object.values(e??{}))}function ua(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function tg(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()]}const Zt=0,ig=120;function Ht(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?fa():sg(e),r=window.innerWidth,o=window.innerHeight,n=Math.max(0,s.left),a=Math.min(r,s.right),l=Math.max(0,s.top),p=Math.min(o,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Zt,g=i.top-l-Zt;return[...h<ig&&g>h?[`bottom: ${at(o-i.top+Zt)};`,`max-height: ${at(Math.max(0,g))};`]:[`top: ${at(i.bottom+Zt)};`,`max-height: ${at(Math.max(0,h))};`],`right: ${at(Math.max(0,r-u))};`,`max-width: ${at(Math.max(0,u-n))};`].join(" ")}function sg(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():fa()}function fa(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function at(e){return`${String(Math.round(e))}px`}function ga(e,t="活跃"){if(e!==void 0)return c`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Li(e,t="活跃"){const i=ga(e,t);if(i!==void 0)return c`<span class="action-activity">${i}</span>`}const rg=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function ma(e){return e.composedPath().some(t=>og(t,rg))}function og(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 ji(e,t){ma(e)||t()}function Fi(e,t){return ma(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?Ke(e,()=>{Co(e.currentTarget,-1)}):e.key==="ArrowDown"?Ke(e,()=>{Co(e.currentTarget,1)}):e.key==="Home"?Ke(e,()=>{Mo(e.currentTarget,0)}):e.key==="End"?Ke(e,()=>{Mo(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?Ke(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?Ke(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?Ke(e,t.cancel):!1}function Ni(e,t={}){const i=e.querySelector(".action-row.selected")??e.querySelector(".action-row")??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return i==null?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}function Ke(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function Co(e,t){const i=ba(e),s=wa(e);if(s===void 0||i.length===0)return;const r=i.indexOf(s);r<0||va(i,r+t)}function Mo(e,t){const i=ba(e);i.length!==0&&va(i,t<0?i.length-1:t)}function va(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function ba(e){const t=wa(e)?.getRootNode();return t===void 0||!ng(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function ng(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function wa(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const ag=_`
135
+ `}function la(){na(()=>import("./CodeViewer-rwuQkhmb.js"),__vite__mapDeps([0,1,2,3]))}function Uu(){na(()=>import("./TerminalPanel-BTDv_JgG.js"),__vite__mapDeps([4,5,6,1,2]))}function Hu(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 qu(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function Ds(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)}const Ku={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!du();return{contributions:{actions:e?wr():wr().filter(t=>t.id!=="view.terminal"),workspacePanels:e?xr():xr().filter(t=>t.id!=="workspace.terminal")}}}},Vu={"--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"},Gu={"--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"},Ju={"--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"},Qu={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:Gu},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Ju},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Vu}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},Zu=/^[a-z][a-z0-9.-]*$/u;function Xu(e){return Zu.test(e)}const Yu="machine.";function ef(e,t){if(e==="")throw new Error("Machine id is required");if(!Xu(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Yu}${tf(e)}.${t}`}function tf(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function kr(e="/pi-web-plugins/manifest.json",t={}){const i=await sf(e);if(i===void 0)return[];const s=[];for(const o of i.plugins)if(t.shouldLoadPlugin?.(o)!==!1)try{const r=new URL(o.module,new URL(e,window.location.href)).toString(),n=await import(r),a=nf(n,r);s.push({id:t.machineId===void 0?o.id:ef(t.machineId,o.id),plugin:a,machineSpecific:o.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:o.id}})}catch(r){console.warn(`Failed to load PI WEB plugin ${o.module}`,r)}return s}async function sf(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 of(await t.json())}}function of(e){if(!$i(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!$i(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module,machineSpecific:rf(t.machineSpecific)}})}}function rf(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function nf(e,t){if(!$i(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!af(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function af(e){return $i(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function $i(e){return typeof e=="object"&&e!==null}const cf=/^[a-z][a-z0-9.-]*$/u,lf=/^[a-z][a-z0-9.-]*$/u,da=new WeakMap,pa=new WeakMap;class df{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;this.validatePluginId(i);const o=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,o))return;this.pluginIds.add(i);const r=s.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(r)}`);const a=s.activate({apiVersion:1,pluginId:i,html:c,svg:ue}).contributions;for(const l of a.actions??[])this.actions.push(this.qualifyAction(i,l,t.machineId,t.sourcePluginId));for(const l of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,l,t.machineId,t.sourcePluginId));for(const l of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,l,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const l of a.themes??[])this.themes.push(this.qualifyTheme(i,l));for(const l of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,l));this.gatewayPluginIds.add(i),o&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&o&&ff(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=mf(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const o=pf(t,s.pluginId),r=s.enabled?.(o),n={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(o)};return s.description!==void 0&&(n.description=s.description),s.shortcut!==void 0&&(n.shortcut=s.shortcut),s.group!==void 0&&(n.group=s.group),r!==void 0&&(n.enabled=r),n})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,o){const r=this.qualify(t,i.id);return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...o===void 0?{}:{sourcePluginId:o}}}qualifyWorkspacePanel(t,i,s,o){const r=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:l=>this.isContributionActive(t,s,l.machine.id,o)&&(a?.(os(l,t))??!0),...n===void 0?{}:{badge:l=>this.isContributionActive(t,s,l.machine.id,o)?n(os(l,t)):void 0},render:l=>i.render(os(l,t))}}qualifyWorkspaceLabelContribution(t,i,s,o){const r=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:l=>this.isContributionActive(t,s,l.machine.id,o)&&(n?.(l)??!0),items:l=>this.isContributionActive(t,s,l.machine.id,o)?a(l):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}isContributionActive(t,i,s,o){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(o,i)}isRemoteDuplicateHiddenByGateway(t,i,s){return t!==void 0&&i!==void 0&&this.gatewayPluginIds.has(t)&&!this.gatewayMachineSpecificPluginIds.has(t)&&!s}isRemotePluginHiddenByGateway(t,i){return t===void 0||this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0?!1:this.gatewayPluginIds.has(t)}isGatewayPluginHiddenForMachine(t,i){return i!=="local"&&(this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0)}validatePluginId(t){if(!cf.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!lf.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}: ${gf(i)}`);return i}}function pf(e,t){return da.get(e)?.(t)??e}function os(e,t){return pa.get(e)?.(t)??e}function hf(e,t){return da.set(e,t),e}function uf(e,t){return pa.set(e,t),e}function ff(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function gf(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 mf(e){return e.state.selectedMachine?.id??"local"}const vf=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function bf(){return typeof window>"u"||!("matchMedia"in window)?[]:vf.map(e=>window.matchMedia(e))}function $r(e,t=wf()){return e.some(i=>i.matches)||yf(t)}function wf(){return typeof navigator>"u"?void 0:navigator}function yf(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const Sf=250;class xf{constructor(t=kf()){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()},Sf)}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 kf(){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 $f="(max-width: 760px)",Pf="(max-width: 1180px)";class Rf{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=$r(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??If(),this.stackedWorkspaceMedia=i.stackedWorkspaceMedia??Cf(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??bf(),this.viewportPositionRepairer=i.viewportPositionRepairer??new xf,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=$r(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 Mf(t,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:i})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function If(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia($f)}function Cf(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Pf)}function Mf(e,t){const i=e??(t.isMobileNavigationLayout?"navigation":"chat");return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||i==="navigation"||i==="chat"?i:"chat"}const Pi=["machines","projects","workspaces","sessions"];function Tf(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function lo(e,t){if(e!=="none")return e??Tf(t)}function Af(e,t){return t.isMobileLayout?lo(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Ef(e,t,i){return lo(e,i.state)===t?"none":t}function Df(e,t,i){return i?t:e}function Wf(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Of(i)}function _f(e){return Pi[Pi.indexOf(e)+1]}class Lf{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return lo(this.expanded,this.getState())}isCollapsed(t){return Af(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Ef(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Wf(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(Df(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=_f(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){jf(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Of(e){const t=new Set(e);return Pi.filter(i=>t.has(i))}function jf(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class Ff{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",ha(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function ha(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const Ws="pi-web:panel-sizes:v1",zf={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Nf{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??po(),this.panelSizes=qf(this.storage)}hostConnected(){}constraints(t){return Ht(t)}panelWidth(t,i){return fe(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const o=fe(t,i);this.storedPanelWidth(t)!==o&&(this.panelSizes=Gf(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Jf(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(){Kf(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${Rr(fe("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${Rr(fe("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Ht(e){return zf[e]}function Bf(e,t,i){return e==="navigation"?i-t:t-i}function Uf(e,t,i,s,o=Ht(e)){return fe(e,t+Bf(e,i,s),o)}function Hf(e,t,i,s={}){const o=s.constraints??Ht(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=Qf(e,i,r);if(n!==void 0)return fe(e,t+n,o)}function fe(e,t,i=Ht(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function qf(e=po()){try{const t=e?.getItem(Ws);if(t==null||t==="")return{};const i=JSON.parse(t);return Vf(i)}catch{return{}}}function Kf(e,t=po()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Ws);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=fe("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=fe("workspace",e.workspacePanelWidth)),t.setItem(Ws,JSON.stringify(i))}catch{}}function Vf(e){if(!Zf(e)||e.version!==1)return{};const t={},i=Pr(e.navigationPanelWidth),s=Pr(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=fe("navigation",i)),s!==void 0&&(t.workspacePanelWidth=fe("workspace",s)),t}function Pr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Gf(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Jf(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Qf(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 Rr(e){return`${String(Math.round(e))}px`}function po(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Zf(e){return typeof e=="object"&&e!==null}function Ir(){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:Xf(e.get("tool")),view:Yf(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}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function Xf(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":ua(e)?e:void 0}function Yf(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":ua(e)?e:void 0}function ua(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Cr(){return eg(new URLSearchParams(window.location.search).get("settings"))}function ns(e,t){const i=new URL(window.location.href);e===void 0?i.searchParams.delete("settings"):i.searchParams.set("settings",e);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&window.history.pushState({},"",i)}function eg(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 tg(e,t){return t===void 0?e:e.map(i=>sg(i,t))}function ig(e,t){const i=new Set(no(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return tg(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?fa(s):s)}function sg(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?fa(e):{...e,shortcut:i}}function fa(e){const t={...e};return delete t.shortcut,t}function og(e,t){const i=t.api??dt,s=t.pollIntervalMs??1e3,o=t.setTimeout??ng(),r=t.clearTimeout??ag();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:rg(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function rg(e,t,i,s,o){return Mr(e)?Promise.resolve(e):new Promise((r,n)=>{let a,l=!1;const p=g=>{l||(l=!0,a!==void 0&&o(a),r(g))},u=g=>{l||(l=!0,a!==void 0&&o(a),n(g instanceof Error?g:new Error(String(g))))},h=()=>{t.getCommandRun(e.id).then(g=>{if(g!==void 0&&Mr(g)){p(g);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function Mr(e){return e.status==="succeeded"||e.status==="failed"}function ng(){return(e,t)=>globalThis.setTimeout(e,t)}function ag(){return e=>{globalThis.clearTimeout(e)}}function cg(e,t){return t[e.path]}function lg(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function dg(e,t,i){return ma(pg(e,t,i))}function ga(e){return ma(Object.values(e??{}))}function ma(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function pg(e,t,i){const s=new Set(t.filter(r=>r.projectId===e.id).map(r=>r.path)),o=new Map;for(const r of s){const n=i[r];n!==void 0&&o.set(n.cwd,n)}for(const r of Object.values(i))(r.cwd===e.path||r.cwd.startsWith(`${e.path}/`))&&o.set(r.cwd,r);return[...o.values()]}const Xt=0,hg=120;function qt(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?va():ug(e),o=window.innerWidth,r=window.innerHeight,n=Math.max(0,s.left),a=Math.min(o,s.right),l=Math.max(0,s.top),p=Math.min(r,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Xt,g=i.top-l-Xt;return[...h<hg&&g>h?[`bottom: ${at(r-i.top+Xt)};`,`max-height: ${at(Math.max(0,g))};`]:[`top: ${at(i.bottom+Xt)};`,`max-height: ${at(Math.max(0,h))};`],`right: ${at(Math.max(0,o-u))};`,`max-width: ${at(Math.max(0,u-n))};`].join(" ")}function ug(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():va()}function va(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function at(e){return`${String(Math.round(e))}px`}function ba(e,t="活跃"){if(e!==void 0)return c`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function ji(e,t="活跃"){const i=ba(e,t);if(i!==void 0)return c`<span class="action-activity">${i}</span>`}const fg=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function wa(e){return e.composedPath().some(t=>gg(t,fg))}function gg(e,t){if(typeof Element<"u"&&e instanceof Element)return e.matches(t);if(!("matches"in e))return!1;const{matches:i}=e;return typeof i=="function"&&i.call(e,t)===!0}function Fi(e,t){wa(e)||t()}function zi(e,t){return wa(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?Ke(e,()=>{Tr(e.currentTarget,-1)}):e.key==="ArrowDown"?Ke(e,()=>{Tr(e.currentTarget,1)}):e.key==="Home"?Ke(e,()=>{Ar(e.currentTarget,0)}):e.key==="End"?Ke(e,()=>{Ar(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?Ke(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?Ke(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?Ke(e,t.cancel):!1}function Ni(e,t={}){const i=e.querySelector(".action-row.selected")??e.querySelector(".action-row")??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return i==null?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}function Ke(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function Tr(e,t){const i=Sa(e),s=xa(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||ya(i,o+t)}function Ar(e,t){const i=Sa(e);i.length!==0&&ya(i,t<0?i.length-1:t)}function ya(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function Sa(e){const t=xa(e)?.getRootNode();return t===void 0||!mg(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function mg(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function xa(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const vg=_`
136
136
  /* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
137
137
  :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; }
138
138
  :host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
@@ -230,7 +230,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
230
230
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
231
231
  .empty { margin: auto; color: var(--pi-muted); }
232
232
  .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
233
- `,cg=_`
233
+ `,bg=_`
234
234
  :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; }
235
235
  header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
236
236
  .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
@@ -289,7 +289,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
289
289
  .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); }
290
290
  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; }
291
291
  p { margin: 10px; }
292
- `,zi=_`
292
+ `,Bi=_`
293
293
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
294
294
  :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
295
295
  section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
@@ -350,7 +350,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
350
350
  .workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
351
351
  .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; }
352
352
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
353
- `,lg=_`
353
+ `,wg=_`
354
354
  :host { position: relative; z-index: 0; display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
355
355
  .chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
356
356
  .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
@@ -439,7 +439,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
439
439
  pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
440
440
  .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
441
441
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
442
- `,dg=_`
442
+ `,yg=_`
443
443
  :host { display: block; }
444
444
  .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
445
445
  p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
@@ -464,7 +464,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
464
464
  table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
465
465
  th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
466
466
  th { background: var(--pi-surface); }
467
- `,pg=_`
467
+ `,Sg=_`
468
468
  :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
469
469
  .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; }
470
470
  span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
@@ -474,7 +474,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
474
474
  .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
475
475
  .muted { color: var(--pi-dim); }
476
476
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
477
- `,hg=_`
477
+ `,xg=_`
478
478
  :host { display: block; }
479
479
  .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); }
480
480
  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; }
@@ -482,7 +482,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
482
482
  button.selected, button:hover { background: var(--pi-selection-bg); }
483
483
  span { color: var(--pi-muted); font-size: 12px; }
484
484
  small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
485
- `,ya=_`
485
+ `,ka=_`
486
486
  :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
487
487
  .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
488
488
  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; }
@@ -496,7 +496,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
496
496
  .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
497
497
  small { display: block; margin-top: 4px; color: var(--pi-muted); }
498
498
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
499
- `,ug=_`
499
+ `,kg=_`
500
500
  :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
501
501
  .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; }
502
502
  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; }
@@ -514,7 +514,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
514
514
  .group { grid-column: 1 / -1; font-size: 12px; }
515
515
  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; }
516
516
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
517
- `,fg=_`
517
+ `,$g=_`
518
518
  :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
519
519
  footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
520
520
  footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
@@ -562,7 +562,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
562
562
  button { padding: 5px 7px; }
563
563
  .icon-button { width: 34px; height: 34px; }
564
564
  }
565
- `;var gg=Object.defineProperty,mg=Object.getOwnPropertyDescriptor,ce=(e,t,i,s)=>{for(var r=s>1?void 0:s?mg(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&&gg(t,i,r),r};let Z=class extends M{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.openMenuMachineId!==void 0&&!this.machines.some(t=>t.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return c`
565
+ `;var Pg=Object.defineProperty,Rg=Object.getOwnPropertyDescriptor,ce=(e,t,i,s)=>{for(var o=s>1?void 0:s?Rg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Pg(t,i,o),o};let Z=class extends M{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.openMenuMachineId!==void 0&&!this.machines.some(t=>t.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return c`
566
566
  <section>
567
567
  <h2>${this.renderHeading()}</h2>
568
568
  ${this.collapsed?null:c`
@@ -571,20 +571,20 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
571
571
  </div>
572
572
  `}
573
573
  </section>
574
- `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=Sa(e)&&this.onRemove!==void 0;return c`
574
+ `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=$a(e)&&this.onRemove!==void 0;return c`
575
575
  <div
576
576
  class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
577
577
  tabindex="0"
578
578
  title=${e.baseUrl??e.name}
579
- @click=${r=>{ji(r,()=>this.onSelect?.(e))}}
580
- @keydown=${r=>{this.handleMachineKeydown(r,e)}}
579
+ @click=${o=>{Fi(o,()=>this.onSelect?.(e))}}
580
+ @keydown=${o=>{this.handleMachineKeydown(o,e)}}
581
581
  >
582
582
  <div class="action-main">
583
583
  <span class="action-name machine-primary">${this.renderActivity(e)}<span class="machine-primary-label">${e.name}</span></span><small>${e.kind==="local"?"本机 Pi Web":e.baseUrl??"远程 Pi Web"} · ${i}</small>
584
584
  </div>
585
585
  ${s?this.renderMachineMenu(e):null}
586
586
  </div>
587
- `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=ha(this.activities[e.id]);return Li(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.openMenuMachineId===e.id,i=vg(e.id);return c`
587
+ `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=ga(this.activities[e.id]);return ji(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.openMenuMachineId===e.id,i=Ig(e.id);return c`
588
588
  <div class="action-menu">
589
589
  <button
590
590
  class="action-menu-toggle"
@@ -600,13 +600,13 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
600
600
  </div>
601
601
  `:null}
602
602
  </div>
603
- `}renderHeading(){if(!this.collapsible)return"机器";const e=this.selected?.name??"未选择机器",t=this.selected?.baseUrl??e;return c`<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?c`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key==="Escape"&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}Fi(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};Z.styles=[zi,_`
603
+ `}renderHeading(){if(!this.collapsible)return"机器";const e=this.selected?.name??"未选择机器",t=this.selected?.baseUrl??e;return c`<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?c`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=qt(t,{constrainTo:"viewport"}),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key==="Escape"&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}zi(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};Z.styles=[Bi,_`
604
604
  .machine-row.no-actions .action-main { border-radius: 8px; }
605
605
  .machine-primary { display: flex; align-items: baseline; gap: 6px; }
606
606
  .machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
607
607
  .machine-menu-panel button.danger { color: var(--pi-danger); }
608
608
  .machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
609
- `];ce([d({attribute:!1})],Z.prototype,"machines",2);ce([d({attribute:!1})],Z.prototype,"selected",2);ce([d({attribute:!1})],Z.prototype,"statuses",2);ce([d({attribute:!1})],Z.prototype,"activities",2);ce([d({type:Boolean,reflect:!0})],Z.prototype,"collapsible",2);ce([d({type:Boolean,reflect:!0})],Z.prototype,"collapsed",2);ce([d({attribute:!1})],Z.prototype,"onSelect",2);ce([d({attribute:!1})],Z.prototype,"onRemove",2);ce([d({attribute:!1})],Z.prototype,"onToggleCollapsed",2);ce([d({attribute:!1})],Z.prototype,"onFocusNextSection",2);ce([d({attribute:!1})],Z.prototype,"onCancelKeyboardNavigation",2);ce([y()],Z.prototype,"openMenuMachineId",2);ce([y()],Z.prototype,"menuStyle",2);Z=ce([E("machine-list")],Z);function Sa(e){return e.kind==="remote"}function vg(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var bg=Object.defineProperty,wg=Object.getOwnPropertyDescriptor,ie=(e,t,i,s)=>{for(var r=s>1?void 0:s?wg(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&&bg(t,i,r),r};let G=class extends M{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("projects")&&this.openMenuProjectId!==void 0&&!this.projects.some(t=>t.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuProjectId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return c`
609
+ `];ce([d({attribute:!1})],Z.prototype,"machines",2);ce([d({attribute:!1})],Z.prototype,"selected",2);ce([d({attribute:!1})],Z.prototype,"statuses",2);ce([d({attribute:!1})],Z.prototype,"activities",2);ce([d({type:Boolean,reflect:!0})],Z.prototype,"collapsible",2);ce([d({type:Boolean,reflect:!0})],Z.prototype,"collapsed",2);ce([d({attribute:!1})],Z.prototype,"onSelect",2);ce([d({attribute:!1})],Z.prototype,"onRemove",2);ce([d({attribute:!1})],Z.prototype,"onToggleCollapsed",2);ce([d({attribute:!1})],Z.prototype,"onFocusNextSection",2);ce([d({attribute:!1})],Z.prototype,"onCancelKeyboardNavigation",2);ce([S()],Z.prototype,"openMenuMachineId",2);ce([S()],Z.prototype,"menuStyle",2);Z=ce([D("machine-list")],Z);function $a(e){return e.kind==="remote"}function Ig(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Cg=Object.defineProperty,Mg=Object.getOwnPropertyDescriptor,ie=(e,t,i,s)=>{for(var o=s>1?void 0:s?Mg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Cg(t,i,o),o};let G=class extends M{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("projects")&&this.openMenuProjectId!==void 0&&!this.projects.some(t=>t.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuProjectId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return c`
610
610
  <section>
611
611
  <h2>${this.renderHeading()}</h2>
612
612
  ${this.collapsed?null:c`
@@ -621,7 +621,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
621
621
  class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
622
622
  tabindex="0"
623
623
  title=${e.path}
624
- @click=${t=>{ji(t,()=>this.onSelect?.(e))}}
624
+ @click=${t=>{Fi(t,()=>this.onSelect?.(e))}}
625
625
  @keydown=${t=>{this.handleProjectKeydown(t,e)}}
626
626
  >
627
627
  <div class="action-main">
@@ -641,19 +641,19 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
641
641
  </div>
642
642
  `}
643
643
  </section>
644
- `}handleProjectKeydown(e,t){Fi(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 c`<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?c`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=eg(e,this.workspacesByProjectId[e.id]??[],this.activities);return Li(t,t==="terminal"?"项目终端活跃":"项目活跃")}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`关闭 ${e.name}?
644
+ `}handleProjectKeydown(e,t){zi(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return"项目";const e=this.selected?.name??"未选择项目",t=this.selected?.path??e;return c`<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?c`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=dg(e,this.workspacesByProjectId[e.id]??[],this.activities);return ji(t,t==="terminal"?"项目终端活跃":"项目活跃")}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=qt(t,{constrainTo:"viewport"}),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`关闭 ${e.name}?
645
645
 
646
- 这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};G.styles=zi;ie([d({attribute:!1})],G.prototype,"projects",2);ie([d({attribute:!1})],G.prototype,"selected",2);ie([d({attribute:!1})],G.prototype,"activities",2);ie([d({attribute:!1})],G.prototype,"workspacesByProjectId",2);ie([d({type:Boolean,reflect:!0})],G.prototype,"collapsible",2);ie([d({type:Boolean,reflect:!0})],G.prototype,"collapsed",2);ie([d({attribute:!1})],G.prototype,"onSelect",2);ie([d({attribute:!1})],G.prototype,"onClose",2);ie([d({attribute:!1})],G.prototype,"onToggleCollapsed",2);ie([d({attribute:!1})],G.prototype,"onFocusPreviousSection",2);ie([d({attribute:!1})],G.prototype,"onFocusNextSection",2);ie([d({attribute:!1})],G.prototype,"onCancelKeyboardNavigation",2);ie([y()],G.prototype,"openMenuProjectId",2);ie([y()],G.prototype,"menuStyle",2);G=ie([E("project-list")],G);function To(e=[]){return e.map((t,i)=>c`${i===0?null:c`<span class="workspace-label-separator">·</span>`}${yg(t)}`)}function yg(e){if(e.type==="render")return c`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&Sg(e.href)){const t=e.target??"_blank",i=t==="_blank"?"noopener noreferrer":void 0;return c`<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 c`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function Sg(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var xg=Object.defineProperty,kg=Object.getOwnPropertyDescriptor,X=(e,t,i,s)=>{for(var r=s>1?void 0:s?kg(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&&xg(t,i,r),r};let q=class extends M{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuWorkspaceId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("workspaces")&&this.openMenuWorkspaceId!==void 0&&!this.workspaces.some(t=>t.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuWorkspaceId=void 0),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return c`
646
+ 这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};G.styles=Bi;ie([d({attribute:!1})],G.prototype,"projects",2);ie([d({attribute:!1})],G.prototype,"selected",2);ie([d({attribute:!1})],G.prototype,"activities",2);ie([d({attribute:!1})],G.prototype,"workspacesByProjectId",2);ie([d({type:Boolean,reflect:!0})],G.prototype,"collapsible",2);ie([d({type:Boolean,reflect:!0})],G.prototype,"collapsed",2);ie([d({attribute:!1})],G.prototype,"onSelect",2);ie([d({attribute:!1})],G.prototype,"onClose",2);ie([d({attribute:!1})],G.prototype,"onToggleCollapsed",2);ie([d({attribute:!1})],G.prototype,"onFocusPreviousSection",2);ie([d({attribute:!1})],G.prototype,"onFocusNextSection",2);ie([d({attribute:!1})],G.prototype,"onCancelKeyboardNavigation",2);ie([S()],G.prototype,"openMenuProjectId",2);ie([S()],G.prototype,"menuStyle",2);G=ie([D("project-list")],G);function Er(e=[]){return e.map((t,i)=>c`${i===0?null:c`<span class="workspace-label-separator">·</span>`}${Tg(t)}`)}function Tg(e){if(e.type==="render")return c`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&Ag(e.href)){const t=e.target??"_blank",i=t==="_blank"?"noopener noreferrer":void 0;return c`<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 c`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function Ag(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var Eg=Object.defineProperty,Dg=Object.getOwnPropertyDescriptor,X=(e,t,i,s)=>{for(var o=s>1?void 0:s?Dg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Eg(t,i,o),o};let q=class extends M{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuWorkspaceId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("workspaces")&&this.openMenuWorkspaceId!==void 0&&!this.workspaces.some(t=>t.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuWorkspaceId=void 0),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Ni(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return c`
647
647
  <section>
648
648
  <h2>${this.renderHeading()}</h2>
649
649
  ${this.collapsed?null:c`
650
650
  <div class="list-body">
651
- ${this.workspaces.map(e=>{const t=$g(e),i=this.workspaceLabelItems(e);return c`
651
+ ${this.workspaces.map(e=>{const t=Wg(e),i=this.workspaceLabelItems(e);return c`
652
652
  <div
653
653
  class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
654
654
  tabindex="0"
655
655
  title=${t}
656
- @click=${s=>{ji(s,()=>this.onSelect?.(e))}}
656
+ @click=${s=>{Fi(s,()=>this.onSelect?.(e))}}
657
657
  @keydown=${s=>{this.handleWorkspaceKeydown(s,e)}}
658
658
  >
659
659
  <div class="action-main">
@@ -665,35 +665,35 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
665
665
  </div>
666
666
  `}
667
667
  </section>
668
- `}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 c`<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?c`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=Yf(Xf(e,this.activities));return Li(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return c`
668
+ `}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 c`<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?c`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=lg(cg(e,this.activities));return ji(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return c`
669
669
  <span class="workspace-primary">
670
670
  <span class="workspace-primary-label">${e}</span>
671
671
  ${this.isDeleting(i)?c`<span class="workspace-status">正在删除…</span>`:null}
672
672
  </span>
673
673
  ${t.length===0?null:c`
674
674
  <small class="workspace-secondary">
675
- <span class="workspace-label">${To(t)}</span>
675
+ <span class="workspace-label">${Er(t)}</span>
676
676
  </small>
677
677
  `}
678
678
  ${this.renderActivity(i)}
679
- `}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,r=Rg(i.id);return c`
679
+ `}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,o=Lg(i.id);return c`
680
680
  <div class="action-menu">
681
681
  <button
682
682
  class="action-menu-toggle"
683
683
  title="工作区操作和详情"
684
684
  aria-label=${`${e} 的操作和详情`}
685
685
  aria-expanded=${String(s)}
686
- aria-controls=${r}
687
- @click=${o=>{o.stopPropagation(),this.toggleMenu(i.id,o.currentTarget)}}
686
+ aria-controls=${o}
687
+ @click=${r=>{r.stopPropagation(),this.toggleMenu(i.id,r.currentTarget)}}
688
688
  >⋯</button>
689
689
  ${s?c`
690
- <div class="action-menu-panel workspace-menu-panel" id=${r} style=${this.menuStyle} @click=${o=>{o.stopPropagation()}}>
690
+ <div class="action-menu-panel workspace-menu-panel" id=${o} style=${this.menuStyle} @click=${r=>{r.stopPropagation()}}>
691
691
  ${this.renderWorkspaceActions(i)}
692
692
  ${this.renderWorkspaceDetails(e,t,i)}
693
693
  </div>
694
694
  `:null}
695
695
  </div>
696
- `}renderWorkspaceActions(e){if(!Pg(e))return;const t=this.isDeleting(e);return c`
696
+ `}renderWorkspaceActions(e){if(!_g(e))return;const t=this.isDeleting(e);return c`
697
697
  <div class="workspace-menu-actions">
698
698
  <button class="danger" title=${t?"正在删除工作区":"删除工作区"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"正在删除…":"删除工作区"}</button>
699
699
  </div>
@@ -710,22 +710,22 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
710
710
  ${t.length===0?null:c`
711
711
  <div class="workspace-detail-row">
712
712
  <dt>详情</dt>
713
- <dd><span class="workspace-label">${To(t)}</span></dd>
713
+ <dd><span class="workspace-label">${Er(t)}</span></dd>
714
714
  </div>
715
715
  `}
716
716
  </dl>
717
- `}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key==="Escape"&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}Fi(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"})}};q.styles=zi;X([d({attribute:!1})],q.prototype,"workspaces",2);X([d({attribute:!1})],q.prototype,"selected",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsible",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsed",2);X([d({attribute:!1})],q.prototype,"workspaceLabelItems",2);X([d({attribute:!1})],q.prototype,"activities",2);X([d({attribute:!1})],q.prototype,"deletingWorkspaceIds",2);X([d({attribute:!1})],q.prototype,"onSelect",2);X([d({attribute:!1})],q.prototype,"onDelete",2);X([d({attribute:!1})],q.prototype,"onToggleCollapsed",2);X([d({attribute:!1})],q.prototype,"onFocusPreviousSection",2);X([d({attribute:!1})],q.prototype,"onFocusNextSection",2);X([d({attribute:!1})],q.prototype,"onCancelKeyboardNavigation",2);X([y()],q.prototype,"openMenuWorkspaceId",2);X([y()],q.prototype,"menuStyle",2);q=X([E("workspace-list")],q);function $g(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function Pg(e){return e.isGitWorktree&&!e.isMain}function Rg(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Ig=Object.defineProperty,Cg=Object.getOwnPropertyDescriptor,T=(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&&Ig(t,i,r),r};function kt(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let I=class extends M{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("sessions")&&(this.openMenuSessionId!==void 0&&!this.sessions.some(i=>i.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.collapsed&&(this.openMenuSessionId=void 0);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,Ni(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=Ag(this.sessions),t=new Set(e.map(o=>o.session.id)),i=e.map(o=>o.session).filter(o=>$t(o)==="current"),s=xa(this.sessions.filter(o=>o.archived===!0&&!t.has(o.id))),r=Mg(this.sessions);return c`
717
+ `}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=qt(t,{constrainTo:"viewport"}),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key==="Escape"&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}zi(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};q.styles=Bi;X([d({attribute:!1})],q.prototype,"workspaces",2);X([d({attribute:!1})],q.prototype,"selected",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsible",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsed",2);X([d({attribute:!1})],q.prototype,"workspaceLabelItems",2);X([d({attribute:!1})],q.prototype,"activities",2);X([d({attribute:!1})],q.prototype,"deletingWorkspaceIds",2);X([d({attribute:!1})],q.prototype,"onSelect",2);X([d({attribute:!1})],q.prototype,"onDelete",2);X([d({attribute:!1})],q.prototype,"onToggleCollapsed",2);X([d({attribute:!1})],q.prototype,"onFocusPreviousSection",2);X([d({attribute:!1})],q.prototype,"onFocusNextSection",2);X([d({attribute:!1})],q.prototype,"onCancelKeyboardNavigation",2);X([S()],q.prototype,"openMenuWorkspaceId",2);X([S()],q.prototype,"menuStyle",2);q=X([D("workspace-list")],q);function Wg(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function _g(e){return e.isGitWorktree&&!e.isMain}function Lg(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Og=Object.defineProperty,jg=Object.getOwnPropertyDescriptor,T=(e,t,i,s)=>{for(var o=s>1?void 0:s?jg(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Og(t,i,o),o};function $t(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let I=class extends M{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("sessions")&&(this.openMenuSessionId!==void 0&&!this.sessions.some(i=>i.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.collapsed&&(this.openMenuSessionId=void 0);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,Ni(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=Ng(this.sessions),t=new Set(e.map(r=>r.session.id)),i=e.map(r=>r.session).filter(r=>Pt(r)==="current"),s=Pa(this.sessions.filter(r=>r.archived===!0&&!t.has(r.id))),o=Fg(this.sessions);return c`
718
718
  <section>
719
719
  ${this.renderHeading(e.length+s.length,i)}
720
720
  ${this.collapsed?null:c`
721
721
  <div class="list-body">
722
722
  ${this.renderCurrentSelectionToolbar(i)}
723
- ${e.map(o=>this.renderSession(o,r.get(o.session.id)??0,"current"))}
723
+ ${e.map(r=>this.renderSession(r,o.get(r.session.id)??0,"current"))}
724
724
  ${s.length>0?c`
725
- ${this.renderArchivedHeading(s.map(o=>o.session))}
725
+ ${this.renderArchivedHeading(s.map(r=>r.session))}
726
726
  ${this.archivedExpanded?c`
727
- ${this.renderArchivedSelectionToolbar(s.map(o=>o.session))}
728
- ${s.map(o=>this.renderSession(o,r.get(o.session.id)??0,"archived"))}
727
+ ${this.renderArchivedSelectionToolbar(s.map(r=>r.session))}
728
+ ${s.map(r=>this.renderSession(r,o.get(r.session.id)??0,"archived"))}
729
729
  `:null}
730
730
  `:null}
731
731
  </div>
@@ -737,12 +737,12 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
737
737
  ${this.renderCurrentSelectionButton(t)}
738
738
  <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button>
739
739
  </h2>
740
- `;const i=this.selected===void 0?"未选择会话":kt(this.selected),s=this.selected?.path??i;return c`
740
+ `;const i=this.selected===void 0?"未选择会话":$t(this.selected),s=this.selected?.path??i;return c`
741
741
  <h2>
742
742
  <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?c`<small class="section-selected" title=${s}>${i}</small>`:null}</span></button>
743
743
  ${this.renderCurrentSelectionButton(t)}
744
744
  <small class="section-count">${e}</small>
745
- <button ?disabled=${!this.canStart} @click=${r=>{r.stopPropagation(),this.onStart?.()}}>+</button>
745
+ <button ?disabled=${!this.canStart} @click=${o=>{o.stopPropagation(),this.onStart?.()}}>+</button>
746
746
  </h2>
747
747
  `}renderCurrentSelectionButton(e){if(this.collapsed||e.length===0)return null;const t=this.selectionScopes.has("current");return c`<button class="bulk-select-entry ${t?"selected":""}" title=${t?"关闭当前会话选择":"选择当前会话"} aria-label=${t?"关闭当前会话选择":"选择当前会话"} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${i=>{i.stopPropagation(),this.toggleSelection("current",e)}}>☑</button>`}renderArchivedHeading(e){const t=this.selectionScopes.has("archived");return c`
748
748
  <h2 class="subheading">
@@ -750,15 +750,15 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
750
750
  ${this.archivedExpanded?c`<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}
751
751
  <small class="section-count">${e.length}</small>
752
752
  </h2>
753
- `}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("current"))return null;const t=this.selectedSessions("current"),i=t.filter(o=>!ee(o)),s=e.length>0&&e.every(o=>this.selectedSessionIds.has(o.id)),r=e.filter(o=>this.selectedSessionIds.has(o.id)).length;return c`
753
+ `}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("current"))return null;const t=this.selectedSessions("current"),i=t.filter(r=>!ee(r)),s=e.length>0&&e.every(r=>this.selectedSessionIds.has(r.id)),o=e.filter(r=>this.selectedSessionIds.has(r.id)).length;return c`
754
754
  <div class="bulk-row selecting">
755
755
  <button ?disabled=${e.length===0} @click=${()=>{this.toggleVisibleSelection(e,!s)}}>${s?"清除可见":"选择可见"}</button>
756
- <small>${t.length} 已选${r!==t.length?c` · ${r} 可见`:null}</small>
756
+ <small>${t.length} 已选${o!==t.length?c` · ${o} 可见`:null}</small>
757
757
  <button ?disabled=${i.length===0} @click=${()=>{this.archiveSelectedCurrent()}}>归档所选</button>
758
758
  <button @click=${()=>{this.clearSelection("current")}}>清除</button>
759
759
  <button @click=${()=>{this.closeSelection("current")}}>完成</button>
760
760
  </div>
761
- `}renderArchivedSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("archived"))return null;const t=this.selectedSessions("archived"),i=e.length>0&&e.every(r=>this.selectedSessionIds.has(r.id)),s=e.filter(r=>this.selectedSessionIds.has(r.id)).length;return c`
761
+ `}renderArchivedSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("archived"))return null;const t=this.selectedSessions("archived"),i=e.length>0&&e.every(o=>this.selectedSessionIds.has(o.id)),s=e.filter(o=>this.selectedSessionIds.has(o.id)).length;return c`
762
762
  <div class="bulk-row selecting">
763
763
  <button ?disabled=${e.length===0} @click=${()=>{this.toggleVisibleSelection(e,!i)}}>${i?"清除可见":"选择可见"}</button>
764
764
  <small>${t.length} 已选${s!==t.length?c` · ${s} 可见`:null}</small>
@@ -767,18 +767,18 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
767
767
  <button @click=${()=>{this.closeSelection("archived")}}>完成</button>
768
768
  ${this.canDeleteArchived?null:c`<small class="capability-hint">${this.archivedDeleteUnavailableMessage}</small>`}
769
769
  </div>
770
- `}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,l=a&&this.selectedSessionIds.has(s.id);return c`
770
+ `}renderSession(e,t,i){const{session:s}=e,o=Math.min(e.depth,2),r=Pt(s)===i,n=this.selectionScopes.has(i),a=n&&r,l=a&&this.selectedSessionIds.has(s.id);return c`
771
771
  <div
772
772
  class="action-row ${this.selected?.id===s.id?"selected":""} ${l?"bulk-selected":""} ${s.archived===!0?"archived":""} ${n?"selecting":""}"
773
- style=${`--depth:${String(r)}`}
773
+ style=${`--depth:${String(o)}`}
774
774
  tabindex="0"
775
775
  title=${s.path}
776
- @click=${p=>{ji(p,()=>{this.activateSessionRow(s,i)})}}
776
+ @click=${p=>{Fi(p,()=>{this.activateSessionRow(s,i)})}}
777
777
  @keydown=${p=>{this.handleSessionKeydown(p,s,i)}}
778
778
  >
779
779
  <div class="action-main ${n?"selecting":""}">
780
- ${a?c`<input class="session-checkbox" type="checkbox" aria-label=${`选择 ${kt(s)}`} .checked=${l} @click=${p=>{p.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
781
- <span class="action-name">${e.depth>0?c`<span class="tree-marker">↳</span>`:null}${kt(s)}${e.depth>2?c` <span class="badge">深度 ${e.depth}</span>`:null}${e.hasMissingParent?c` <span class="badge">父会话不可用</span>`:null}</span><small>${this.renderSessionMetaPrefix(s)}${String(s.messageCount)} 条消息</small>
780
+ ${a?c`<input class="session-checkbox" type="checkbox" aria-label=${`选择 ${$t(s)}`} .checked=${l} @click=${p=>{p.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
781
+ <span class="action-name">${e.depth>0?c`<span class="tree-marker">↳</span>`:null}${$t(s)}${e.depth>2?c` <span class="badge">深度 ${e.depth}</span>`:null}${e.hasMissingParent?c` <span class="badge">父会话不可用</span>`:null}</span><small>${this.renderSessionMetaPrefix(s)}${String(s.messageCount)} 条消息</small>
782
782
  ${this.renderActivity(s)}
783
783
  </div>
784
784
  <div class="action-menu">
@@ -798,7 +798,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
798
798
  `:null}
799
799
  </div>
800
800
  </div>
801
- `}handleSessionKeydown(e,t,i){Fi(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(`归档“${kt(e)}”及其 ${String(t)} 个后代会话?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`永久删除已归档会话“${kt(e)}”?此操作无法撤销。`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");e.length!==0&&confirm(`永久删除 ${String(e.length)} 个所选已归档会话?此操作无法撤销。`)&&(this.selectedSessionIds=ns(this.selectedSessionIds,e.map(t=>t.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>!ee(t));this.selectedSessionIds=ns(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=ns(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")}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=Ht(t,{constrainTo:"viewport"}),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return ee(e)?"新建 · ":e.archived===!0?"只读 · ":""}renderActivity(e){const t=Tg(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return Li(t,t==="sending"?"正在发送消息":"会话活跃")}};I.styles=[zi,_`
801
+ `}handleSessionKeydown(e,t,i){zi(e,{activate:()=>{this.activateSessionRow(t,i)},previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}activateSessionRow(e,t){if(this.selectionScopes.has(t)&&Pt(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){confirm(`归档“${$t(e)}”及其 ${String(t)} 个后代会话?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`永久删除已归档会话“${$t(e)}”?此操作无法撤销。`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");e.length!==0&&confirm(`永久删除 ${String(e.length)} 个所选已归档会话?此操作无法撤销。`)&&(this.selectedSessionIds=as(this.selectedSessionIds,e.map(t=>t.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>!ee(t));this.selectedSessionIds=as(this.selectedSessionIds,e.map(t=>t.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){if(this.selectionScopes.has(e)){this.closeSelection(e);return}this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);const i=t.length===1?t[0]:void 0;i!==void 0&&(this.selectedSessionIds=new Set([...this.selectedSessionIds,i.id]))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){const t=this.sessions.filter(i=>Pt(i)===e).map(i=>i.id);this.selectedSessionIds=as(this.selectedSessionIds,t)}toggleSelected(e){const t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}toggleVisibleSelection(e,t){const i=new Set(this.selectedSessionIds);for(const s of e)t?i.add(s.id):i.delete(s.id);this.selectedSessionIds=i}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&Pt(t)===e)}pruneSelectedSessionIds(){const e=new Set(this.sessions.map(i=>i.id)),t=new Set([...this.selectedSessionIds].filter(i=>e.has(i)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has("archived")&&!this.sessions.some(i=>i.archived===!0)&&this.closeSelection("archived"),this.selectionScopes.has("current")&&!this.sessions.some(i=>i.archived!==!0)&&this.closeSelection("current")}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=qt(t,{constrainTo:"viewport"}),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return ee(e)?"新建 · ":e.archived===!0?"只读 · ":""}renderActivity(e){const t=zg(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return ji(t,t==="sending"?"正在发送消息":"会话活跃")}};I.styles=[Bi,_`
802
802
  h2 { min-height: 30px; }
803
803
  h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
804
804
  .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; }
@@ -812,7 +812,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
812
812
  .action-row.bulk-selected .action-main { border-color: var(--pi-accent); box-shadow: inset 3px 0 0 var(--pi-accent); }
813
813
  .action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
814
814
  .session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
815
- `];T([d({attribute:!1})],I.prototype,"sessions",2);T([d({attribute:!1})],I.prototype,"statuses",2);T([d({attribute:!1})],I.prototype,"activities",2);T([d({attribute:!1})],I.prototype,"sending",2);T([d({attribute:!1})],I.prototype,"selected",2);T([d({type:Boolean})],I.prototype,"canStart",2);T([d({type:Boolean})],I.prototype,"canDeleteArchived",2);T([d({type:Boolean})],I.prototype,"canReload",2);T([d({type:String})],I.prototype,"archivedDeleteUnavailableMessage",2);T([d({type:Boolean,reflect:!0})],I.prototype,"collapsible",2);T([d({type:Boolean,reflect:!0})],I.prototype,"collapsed",2);T([d({attribute:!1})],I.prototype,"onSelect",2);T([d({attribute:!1})],I.prototype,"onStart",2);T([d({attribute:!1})],I.prototype,"onToggleCollapsed",2);T([d({attribute:!1})],I.prototype,"onArchivedCollapsed",2);T([d({attribute:!1})],I.prototype,"onFocusPreviousSection",2);T([d({attribute:!1})],I.prototype,"onFocusNextSection",2);T([d({attribute:!1})],I.prototype,"onCancelKeyboardNavigation",2);T([d({attribute:!1})],I.prototype,"onArchive",2);T([d({attribute:!1})],I.prototype,"onArchiveWithDescendants",2);T([d({attribute:!1})],I.prototype,"onArchiveMany",2);T([d({attribute:!1})],I.prototype,"onRestore",2);T([d({attribute:!1})],I.prototype,"onDelete",2);T([d({attribute:!1})],I.prototype,"onDeleteArchived",2);T([d({attribute:!1})],I.prototype,"onDeleteArchivedMany",2);T([d({attribute:!1})],I.prototype,"onDetachParent",2);T([d({attribute:!1})],I.prototype,"onReload",2);T([y()],I.prototype,"openMenuSessionId",2);T([y()],I.prototype,"menuStyle",2);T([y()],I.prototype,"archivedExpanded",2);T([y()],I.prototype,"selectionScopes",2);T([y()],I.prototype,"selectedSessionIds",2);I=T([E("session-list")],I);function $t(e){return e.archived===!0?"archived":"current"}function ns(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function Mg(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 Tg(e,t,i,s){if(!(ee(e)||e.archived===!0))return s?"sending":Xe(t,i)?"session":void 0}function Ag(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 xa(e.filter(s=>i.has(s.id)))}function xa(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,l=a===void 0?void 0:t.get(a);if(l===void 0){s.push(n);continue}const p=i.get(l.path)??[];p.push(n),i.set(l.path,p)}const r=[],o=(n,a,l)=>{if(l.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(l);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}const dr={CHILD:2,ELEMENT:6},pr=e=>(...t)=>({_$litDirective$:e,values:t});let hr=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:Eg}=Pc,Ao=e=>e,Eo=()=>document.createComment(""),Pt=(e,t,i)=>{const s=e._$AA.parentNode,r=t===void 0?e._$AB:t._$AA;if(i===void 0){const o=s.insertBefore(Eo(),r),n=s.insertBefore(Eo(),r);i=new Eg(o,n,e,e.options)}else{const o=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let l;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(l=e._$AU)!==n._$AU&&i._$AP(l)}if(o!==r||a){let l=i._$AA;for(;l!==o;){const p=Ao(l).nextSibling;Ao(s).insertBefore(l,r),l=p}}}return i},Ve=(e,t,i=e)=>(e._$AI(t,i),e),Dg={},Wg=(e,t=Dg)=>e._$AH=t,_g=e=>e._$AH,as=e=>{e._$AR(),e._$AA.remove()};const Do=(e,t,i)=>{const s=new Map;for(let r=t;r<=i;r++)s.set(e[r],r);return s},Og=pr(class extends hr{constructor(e){if(super(e),e.type!==dr.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=_g(e),{values:o,keys:n}=this.dt(t,i,s);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],l=[];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])l[w]=Ve(r[h],o[w]),h++,w++;else if(a[g]===n[P])l[P]=Ve(r[g],o[P]),g--,P--;else if(a[h]===n[P])l[P]=Ve(r[h],o[P]),Pt(e,l[P+1],r[h]),h++,P--;else if(a[g]===n[w])l[w]=Ve(r[g],o[w]),Pt(e,r[h],r[g]),g--,w++;else if(p===void 0&&(p=Do(n,w,P),u=Do(a,h,g)),p.has(a[h]))if(p.has(a[g])){const H=u.get(n[w]),rt=H!==void 0?r[H]:null;if(rt===null){const mt=Pt(e,r[h]);Ve(mt,o[w]),l[w]=mt}else l[w]=Ve(rt,o[w]),Pt(e,r[h],rt),r[H]=null;w++}else as(r[g]),g--;else as(r[h]),h++;for(;w<=P;){const H=Pt(e,l[P+1]);Ve(H,o[w]),l[w++]=H}for(;h<=g;){const H=r[h++];H!==null&&as(H)}return this.ut=n,Wg(e,l),Ue}}),Lg="pi-web:chat-groups:",jg={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(Wo(e));return t===null||t===""?void 0:Ng(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(Wo(e),JSON.stringify(t))}catch{}}};class Fg{constructor(t=jg){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&&_o(o,this.openGroupKeys)&&_o(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 Wo(e){return`${Lg}${e}`}function Ng(e){if(Array.isArray(e))return{open:cs(e),closedDefaultOpen:[]};if(zg(e))return{open:Array.isArray(e.open)?cs(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?cs(e.closedDefaultOpen):[]}}function cs(e){return e.filter(t=>typeof t=="string")}function _o(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function zg(e){return typeof e=="object"&&e!==null}function Bg(e,t=0){const i=[];let s=[],r=0;const o=(a,l)=>{s.length||(r=l),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:r,endIndex:r+s.length-1}),s=[])};return e.forEach((a,l)=>{const p=a.parts.filter(w=>Oo(a,w)),u=a.parts.filter(w=>!Oo(a,w)),h=t+l,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 Ug(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)} ${Hg(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Hg(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Oo(e,t){return e.source==="compaction"||e.source==="branch_summary"?!1:t.type==="skillInvocation"||t.type==="skillRead"?!0:t.type==="text"&&(e.role==="user"||e.role==="assistant"||e.role==="system"||e.role==="bash")}const qg=30;function Kg(e,t){const i=Gg(Zg(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Vg(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Jg(s,t.markerOffset);return}e.scrollTop=Qg(e.scrollHeight,t.distanceFromBottom)}function Gg(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 Jg(e,t){return e-t}function Qg(e,t){return Math.max(0,e-t)}function Zg(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 Xg=600,Yg=1;function em(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:tm(e)||im(e)}function tm(e){return e.scrollTop<(e.topThreshold??Math.max(Xg,e.clientHeight))}function im(e){return e.scrollHeight<=e.clientHeight+Yg}const sm="pi-web:chat-scroll:",rm=180,om=48,nm=2,am={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)}},cm={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class lm{constructor(t=am,i=cm){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=rm){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,r=nm){if(t===""||i===void 0||!ds(i))return"skipped";try{if($a(i,r)){const a={mode:"bottom"};return this.storage.setItem(ls(t),JSON.stringify(a)),"saved"}const o=hm(i,s);if(o===void 0)return"skipped";const n=pm(i,o);return this.storage.setItem(ls(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||!ds(i))return{status:"skipped"};const o=um(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(ls(t));if(i===null||i==="")return;const s=JSON.parse(i);return dm(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!ds(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function ls(e){return`${sm}${e}`}function dm(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 ds(e){return e.clientHeight>0&&e.scrollHeight>0}function ka(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function $a(e,t=om){return ka(e)<t}function pm(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:ur(t)??"",offset:t.getBoundingClientRect().top-i}}function hm(e,t){const i=e.getBoundingClientRect();let s,r=Number.NEGATIVE_INFINITY,o,n=Number.POSITIVE_INFINITY;for(const a of t){if(ur(a)===void 0)continue;const l=a.getBoundingClientRect();if(l.bottom<=l.top||l.bottom<i.top||l.top>i.bottom)continue;const p=l.top-i.top;p<=0&&p>=r?(s=a,r=p):p>0&&p<n&&(o=a,n=p)}return s??o}function Lo(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const r=s.getBoundingClientRect();return r.bottom>=i.top&&r.top<=i.bottom})}function um(e,t){return e.find(i=>ur(i)===t)}function ur(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var fm=Object.defineProperty,gm=Object.getOwnPropertyDescriptor,fr=(e,t,i,s)=>{for(var r=s>1?void 0:s?gm(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&&fm(t,i,r),r};let Lt=class extends M{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=jo(this.positionPercent),t=jo(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return c`
815
+ `];T([d({attribute:!1})],I.prototype,"sessions",2);T([d({attribute:!1})],I.prototype,"statuses",2);T([d({attribute:!1})],I.prototype,"activities",2);T([d({attribute:!1})],I.prototype,"sending",2);T([d({attribute:!1})],I.prototype,"selected",2);T([d({type:Boolean})],I.prototype,"canStart",2);T([d({type:Boolean})],I.prototype,"canDeleteArchived",2);T([d({type:Boolean})],I.prototype,"canReload",2);T([d({type:String})],I.prototype,"archivedDeleteUnavailableMessage",2);T([d({type:Boolean,reflect:!0})],I.prototype,"collapsible",2);T([d({type:Boolean,reflect:!0})],I.prototype,"collapsed",2);T([d({attribute:!1})],I.prototype,"onSelect",2);T([d({attribute:!1})],I.prototype,"onStart",2);T([d({attribute:!1})],I.prototype,"onToggleCollapsed",2);T([d({attribute:!1})],I.prototype,"onArchivedCollapsed",2);T([d({attribute:!1})],I.prototype,"onFocusPreviousSection",2);T([d({attribute:!1})],I.prototype,"onFocusNextSection",2);T([d({attribute:!1})],I.prototype,"onCancelKeyboardNavigation",2);T([d({attribute:!1})],I.prototype,"onArchive",2);T([d({attribute:!1})],I.prototype,"onArchiveWithDescendants",2);T([d({attribute:!1})],I.prototype,"onArchiveMany",2);T([d({attribute:!1})],I.prototype,"onRestore",2);T([d({attribute:!1})],I.prototype,"onDelete",2);T([d({attribute:!1})],I.prototype,"onDeleteArchived",2);T([d({attribute:!1})],I.prototype,"onDeleteArchivedMany",2);T([d({attribute:!1})],I.prototype,"onDetachParent",2);T([d({attribute:!1})],I.prototype,"onReload",2);T([S()],I.prototype,"openMenuSessionId",2);T([S()],I.prototype,"menuStyle",2);T([S()],I.prototype,"archivedExpanded",2);T([S()],I.prototype,"selectionScopes",2);T([S()],I.prototype,"selectedSessionIds",2);I=T([D("session-list")],I);function Pt(e){return e.archived===!0?"archived":"current"}function as(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function Fg(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const o=t.get(s.parentSessionPath)??[];o.push(s),t.set(s.parentSessionPath,o)}const i=(s,o)=>{if(o.has(s.path))return 0;const r=new Set(o);r.add(s.path);let n=0;for(const a of t.get(s.path)??[])r.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,r));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function zg(e,t,i,s){if(!(ee(e)||e.archived===!0))return s?"sending":Xe(t,i)?"session":void 0}function Ng(e){const t=new Map(e.map(s=>[s.path,s])),i=new Set;for(const s of e){if(s.archived===!0)continue;i.add(s.id);let o=s.parentSessionPath;const r=new Set([s.path]);for(;o!==void 0&&!r.has(o);){r.add(o);const n=t.get(o);if(n===void 0)break;i.add(n.id),o=n.parentSessionPath}}return Pa(e.filter(s=>i.has(s.id)))}function Pa(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,l=a===void 0?void 0:t.get(a);if(l===void 0){s.push(n);continue}const p=i.get(l.path)??[];p.push(n),i.set(l.path,p)}const o=[],r=(n,a,l)=>{if(l.has(n.path))return;const p=n.parentSessionPath;o.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(l);u.add(n.path);for(const h of i.get(n.path)??[])r(h,a+1,u)};for(const n of s)r(n,0,new Set);return o}const ho={CHILD:2,ELEMENT:6},uo=e=>(...t)=>({_$litDirective$:e,values:t});let fo=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:Bg}=Cc,Dr=e=>e,Wr=()=>document.createComment(""),Rt=(e,t,i)=>{const s=e._$AA.parentNode,o=t===void 0?e._$AB:t._$AA;if(i===void 0){const r=s.insertBefore(Wr(),o),n=s.insertBefore(Wr(),o);i=new Bg(r,n,e,e.options)}else{const r=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let l;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(l=e._$AU)!==n._$AU&&i._$AP(l)}if(r!==o||a){let l=i._$AA;for(;l!==r;){const p=Dr(l).nextSibling;Dr(s).insertBefore(l,o),l=p}}}return i},Ve=(e,t,i=e)=>(e._$AI(t,i),e),Ug={},Hg=(e,t=Ug)=>e._$AH=t,qg=e=>e._$AH,cs=e=>{e._$AR(),e._$AA.remove()};const _r=(e,t,i)=>{const s=new Map;for(let o=t;o<=i;o++)s.set(e[o],o);return s},Kg=uo(class extends fo{constructor(e){if(super(e),e.type!==ho.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let s;i===void 0?i=t:t!==void 0&&(s=t);const o=[],r=[];let n=0;for(const a of e)o[n]=s?s(a,n):n,r[n]=i(a,n),n++;return{values:r,keys:o}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const o=qg(e),{values:r,keys:n}=this.dt(t,i,s);if(!Array.isArray(o))return this.ut=n,r;const a=this.ut??=[],l=[];let p,u,h=0,g=o.length-1,w=0,P=r.length-1;for(;h<=g&&w<=P;)if(o[h]===null)h++;else if(o[g]===null)g--;else if(a[h]===n[w])l[w]=Ve(o[h],r[w]),h++,w++;else if(a[g]===n[P])l[P]=Ve(o[g],r[P]),g--,P--;else if(a[h]===n[P])l[P]=Ve(o[h],r[P]),Rt(e,l[P+1],o[h]),h++,P--;else if(a[g]===n[w])l[w]=Ve(o[g],r[w]),Rt(e,o[h],o[g]),g--,w++;else if(p===void 0&&(p=_r(n,w,P),u=_r(a,h,g)),p.has(a[h]))if(p.has(a[g])){const H=u.get(n[w]),ot=H!==void 0?o[H]:null;if(ot===null){const vt=Rt(e,o[h]);Ve(vt,r[w]),l[w]=vt}else l[w]=Ve(ot,r[w]),Rt(e,o[h],ot),o[H]=null;w++}else cs(o[g]),g--;else cs(o[h]),h++;for(;w<=P;){const H=Rt(e,l[P+1]);Ve(H,r[w]),l[w++]=H}for(;h<=g;){const H=o[h++];H!==null&&cs(H)}return this.ut=n,Hg(e,l),Ue}}),Vg="pi-web:chat-groups:",Gg={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(Lr(e));return t===null||t===""?void 0:Qg(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(Lr(e),JSON.stringify(t))}catch{}}};class Jg{constructor(t=Gg){this.storage=t,this.sessionId="",this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(t){if(this.sessionId===t)return;this.sessionId=t;const i=t===""?void 0:this.storage.read(t);this.openGroupKeys=new Set(i?.open??[]),this.closedDefaultOpenGroupKeys=new Set(i?.closedDefaultOpen??[])}isOpen(t,i){return i?!this.closedDefaultOpenGroupKeys.has(t):this.openGroupKeys.has(t)}applyToggle(t,i,s){const o=this.isOpen(t,s),r=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(r.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?r.add(t):r.delete(t)),(s?!n.has(t):r.has(t))===o&&Or(r,this.openGroupKeys)&&Or(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=r,this.closedDefaultOpenGroupKeys=n,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==""&&this.storage.write(this.sessionId,this.snapshot())}}function Lr(e){return`${Vg}${e}`}function Qg(e){if(Array.isArray(e))return{open:ls(e),closedDefaultOpen:[]};if(Zg(e))return{open:Array.isArray(e.open)?ls(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?ls(e.closedDefaultOpen):[]}}function ls(e){return e.filter(t=>typeof t=="string")}function Or(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Zg(e){return typeof e=="object"&&e!==null}function Xg(e,t=0){const i=[];let s=[],o=0;const r=(a,l)=>{s.length||(o=l),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:o,endIndex:o+s.length-1}),s=[])};return e.forEach((a,l)=>{const p=a.parts.filter(w=>jr(a,w)),u=a.parts.filter(w=>!jr(a,w)),h=t+l,g={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&r({role:a.role,parts:u,...g},h),p.length){n();const w=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:w,parts:p,...g},index:h})}}),n(),i}function Yg(e){if(e.every(s=>s.source==="compaction"))return`${String(e.length)} 条历史压缩摘要`;if(e.every(s=>s.source==="branch_summary"))return`${String(e.length)} 条分支摘要`;const t=e.reduce((s,o)=>(s[o.role]=(s[o.role]??0)+1,s),{}),i=Object.entries(t).map(([s,o])=>`${String(o)} ${em(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function em(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function jr(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 tm=30;function im(e,t){const i=om(am(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function sm(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=rm(s,t.markerOffset);return}e.scrollTop=nm(e.scrollHeight,t.distanceFromBottom)}function om(e){let t,i=Number.NEGATIVE_INFINITY,s,o=Number.POSITIVE_INFINITY;for(const r of e)r.offset<=0&&r.offset>=i?(t=r,i=r.offset):r.offset>0&&r.offset<o&&(s=r,o=r.offset);return t??s}function rm(e,t){return e-t}function nm(e,t){return Math.max(0,e-t)}function am(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const o=s.dataset.markerId;return o===void 0?[]:[{id:o,offset:s.getBoundingClientRect().top-i}]})}const cm=600,lm=1;function dm(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:pm(e)||hm(e)}function pm(e){return e.scrollTop<(e.topThreshold??Math.max(cm,e.clientHeight))}function hm(e){return e.scrollHeight<=e.clientHeight+lm}const um="pi-web:chat-scroll:",fm=180,gm=48,mm=2,vm={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)}},bm={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class wm{constructor(t=vm,i=bm){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=fm){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,o=mm){if(t===""||i===void 0||!ps(i))return"skipped";try{if(Ia(i,o)){const a={mode:"bottom"};return this.storage.setItem(ds(t),JSON.stringify(a)),"saved"}const r=xm(i,s);if(r===void 0)return"skipped";const n=Sm(i,r);return this.storage.setItem(ds(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,o){const r=this.readPosition(t);return r===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(r,i,s,o)}restoreExplicitPosition(t,i,s,o){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!ps(i))return{status:"skipped"};const r=km(s,t.anchorId);if(r===void 0)return o?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=r.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(ds(t));if(i===null||i==="")return;const s=JSON.parse(i);return ym(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!ps(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function ds(e){return`${um}${e}`}function ym(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 ps(e){return e.clientHeight>0&&e.scrollHeight>0}function Ra(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function Ia(e,t=gm){return Ra(e)<t}function Sm(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:go(t)??"",offset:t.getBoundingClientRect().top-i}}function xm(e,t){const i=e.getBoundingClientRect();let s,o=Number.NEGATIVE_INFINITY,r,n=Number.POSITIVE_INFINITY;for(const a of t){if(go(a)===void 0)continue;const l=a.getBoundingClientRect();if(l.bottom<=l.top||l.bottom<i.top||l.top>i.bottom)continue;const p=l.top-i.top;p<=0&&p>=o?(s=a,o=p):p>0&&p<n&&(r=a,n=p)}return s??r}function Fr(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const o=s.getBoundingClientRect();return o.bottom>=i.top&&o.top<=i.bottom})}function km(e,t){return e.find(i=>go(i)===t)}function go(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var $m=Object.defineProperty,Pm=Object.getOwnPropertyDescriptor,mo=(e,t,i,s)=>{for(var o=s>1?void 0:s?Pm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&$m(t,i,o),o};let jt=class extends M{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=zr(this.positionPercent),t=zr(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return c`
816
816
  <div
817
817
  class="meter"
818
818
  style=${`--position:${e.toFixed(2)}%;`}
@@ -828,95 +828,95 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
828
828
  <div class="marker"></div>
829
829
  </div>
830
830
  </div>
831
- `}};Lt.styles=_`
831
+ `}};jt.styles=_`
832
832
  :host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
833
833
  :host(:hover), :host(:focus-within) { opacity: .92; }
834
834
  .meter { height: 100%; }
835
835
  .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); }
836
836
  .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)); }
837
837
  .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%); }
838
- `;fr([d({type:Number})],Lt.prototype,"positionPercent",2);fr([d({type:Number})],Lt.prototype,"loadedPercent",2);Lt=fr([E("conversation-meter")],Lt);function jo(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class Ws extends hr{constructor(t){if(super(t),this.it=F,t.type!==dr.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===F||t==null)return this._t=void 0,this.it=t;if(t===Ue)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const i=[t];return i.raw=i,this._t={_$litType$:this.constructor.resultType,strings:i,values:[]}}}Ws.directiveName="unsafeHTML",Ws.resultType=1;const mm=pr(Ws);function gr(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var tt=gr();function Pa(e){tt=e}var Ge={exec:()=>null};function C(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(Q.caret,"$1"),i=i.replace(r,n),s},getRegex:()=>new RegExp(i,t)};return s}var vm=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),Q={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:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},bm=/^(?:[ \t]*(?:\n|$))+/,wm=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ym=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,qt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Sm=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,mr=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ra=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ia=C(Ra).replace(/bull/g,mr).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(),xm=C(Ra).replace(/bull/g,mr).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(),vr=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,km=/^[^\n]+/,br=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,$m=C(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",br).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Pm=C(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,mr).getRegex(),Bi="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",wr=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Rm=C("^ {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",wr).replace("tag",Bi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ca=C(vr).replace("hr",qt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Bi).getRegex(),Im=C(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ca).getRegex(),yr={blockquote:Im,code:wm,def:$m,fences:ym,heading:Sm,hr:qt,html:Rm,lheading:Ia,list:Pm,newline:bm,paragraph:Ca,table:Ge,text:km},Fo=C("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",qt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Bi).getRegex(),Cm={...yr,lheading:xm,table:Fo,paragraph:C(vr).replace("hr",qt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Fo).replace("blockquote"," {0,3}>").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",Bi).getRegex()},Mm={...yr,html:C(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",wr).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ge,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:C(vr).replace("hr",qt).replace("heading",` *#{1,6} *[^
839
- ]`).replace("lheading",Ia).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Tm=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Am=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ma=/^( {2,}|\\)\n(?!\s*$)/,Em=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,gt=/[\p{P}\p{S}]/u,Ui=/[\s\p{P}\p{S}]/u,Sr=/[^\s\p{P}\p{S}]/u,Dm=C(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ui).getRegex(),Ta=/(?!~)[\p{P}\p{S}]/u,Wm=/(?!~)[\s\p{P}\p{S}]/u,_m=/(?:[^\s\p{P}\p{S}]|~)/u,Om=C(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",vm?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Aa=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Lm=C(Aa,"u").replace(/punct/g,gt).getRegex(),jm=C(Aa,"u").replace(/punct/g,Ta).getRegex(),Ea="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Fm=C(Ea,"gu").replace(/notPunctSpace/g,Sr).replace(/punctSpace/g,Ui).replace(/punct/g,gt).getRegex(),Nm=C(Ea,"gu").replace(/notPunctSpace/g,_m).replace(/punctSpace/g,Wm).replace(/punct/g,Ta).getRegex(),zm=C("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Sr).replace(/punctSpace/g,Ui).replace(/punct/g,gt).getRegex(),Bm=C(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,gt).getRegex(),Um="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Hm=C(Um,"gu").replace(/notPunctSpace/g,Sr).replace(/punctSpace/g,Ui).replace(/punct/g,gt).getRegex(),qm=C(/\\(punct)/,"gu").replace(/punct/g,gt).getRegex(),Km=C(/^<(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(),Vm=C(wr).replace("(?:-->|$)","-->").getRegex(),Gm=C("^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",Vm).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Pi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Jm=C(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Pi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Da=C(/^!?\[(label)\]\[(ref)\]/).replace("label",Pi).replace("ref",br).getRegex(),Wa=C(/^!?\[(ref)\](?:\[\])?/).replace("ref",br).getRegex(),Qm=C("reflink|nolink(?!\\()","g").replace("reflink",Da).replace("nolink",Wa).getRegex(),No=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,xr={_backpedal:Ge,anyPunctuation:qm,autolink:Km,blockSkip:Om,br:Ma,code:Am,del:Ge,delLDelim:Ge,delRDelim:Ge,emStrongLDelim:Lm,emStrongRDelimAst:Fm,emStrongRDelimUnd:zm,escape:Tm,link:Jm,nolink:Wa,punctuation:Dm,reflink:Da,reflinkSearch:Qm,tag:Gm,text:Em,url:Ge},Zm={...xr,link:C(/^!?\[(label)\]\((.*?)\)/).replace("label",Pi).getRegex(),reflink:C(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Pi).getRegex()},_s={...xr,emStrongRDelimAst:Nm,emStrongLDelim:jm,delLDelim:Bm,delRDelim:Hm,url:C(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",No).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:C(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",No).getRegex()},Xm={..._s,br:C(Ma).replace("{2,}","*").getRegex(),text:C(_s.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Xt={normal:yr,gfm:Cm,pedantic:Mm},Rt={normal:xr,gfm:_s,breaks:Xm,pedantic:Zm},Ym={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},zo=e=>Ym[e];function Te(e,t){if(t){if(Q.escapeTest.test(e))return e.replace(Q.escapeReplace,zo)}else if(Q.escapeTestNoEncode.test(e))return e.replace(Q.escapeReplaceNoEncode,zo);return e}function Bo(e){try{e=encodeURI(e).replace(Q.percentDecode,"%")}catch{return null}return e}function Uo(e,t){let i=e.replace(Q.findPipe,(o,n,a)=>{let l=!1,p=n;for(;--p>=0&&a[p]==="\\";)l=!l;return l?"|":" |"}),s=i.split(Q.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(Q.slashPipe,"|");return s}function ze(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 Ho(e){let t=e.split(`
838
+ `;mo([d({type:Number})],jt.prototype,"positionPercent",2);mo([d({type:Number})],jt.prototype,"loadedPercent",2);jt=mo([D("conversation-meter")],jt);function zr(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class _s extends fo{constructor(t){if(super(t),this.it=F,t.type!==ho.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===F||t==null)return this._t=void 0,this.it=t;if(t===Ue)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const i=[t];return i.raw=i,this._t={_$litType$:this.constructor.resultType,strings:i,values:[]}}}_s.directiveName="unsafeHTML",_s.resultType=1;const Rm=uo(_s);function vo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var tt=vo();function Ca(e){tt=e}var Ge={exec:()=>null};function ct(e){let t=[];return i=>{let s=Math.max(0,Math.min(3,i-1)),o=t[s];return o||(o=e(s),t[s]=o),o}}function C(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(o,r)=>{let n=typeof r=="string"?r:r.source;return n=n.replace(Q.caret,"$1"),i=i.replace(o,n),s},getRegex:()=>new RegExp(i,t)};return s}var Im=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),Q={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:ct(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:ct(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:ct(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:ct(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:ct(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:ct(e=>new RegExp(`^ {0,${e}}>`))},Cm=/^(?:[ \t]*(?:\n|$))+/,Mm=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Tm=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Kt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Am=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,bo=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Ma=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ta=C(Ma).replace(/bull/g,bo).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(),Em=C(Ma).replace(/bull/g,bo).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(),wo=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Dm=/^[^\n]+/,yo=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Wm=C(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",yo).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),_m=C(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,bo).getRegex(),Ui="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",So=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Lm=C("^ {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",So).replace("tag",Ui).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Aa=C(wo).replace("hr",Kt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ui).getRegex(),Om=C(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Aa).getRegex(),xo={blockquote:Om,code:Mm,def:Wm,fences:Tm,heading:Am,hr:Kt,html:Lm,lheading:Ta,list:_m,newline:Cm,paragraph:Aa,table:Ge,text:Dm},Nr=C("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Kt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ui).getRegex(),jm={...xo,lheading:Em,table:Nr,paragraph:C(wo).replace("hr",Kt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Nr).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Ui).getRegex()},Fm={...xo,html:C(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",So).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Ge,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:C(wo).replace("hr",Kt).replace("heading",` *#{1,6} *[^
839
+ ]`).replace("lheading",Ta).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},zm=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Nm=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ea=/^( {2,}|\\)\n(?!\s*$)/,Bm=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,mt=/[\p{P}\p{S}]/u,Hi=/[\s\p{P}\p{S}]/u,ko=/[^\s\p{P}\p{S}]/u,Um=C(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Hi).getRegex(),Da=/(?!~)[\p{P}\p{S}]/u,Hm=/(?!~)[\s\p{P}\p{S}]/u,qm=/(?:[^\s\p{P}\p{S}]|~)/u,Km=C(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Im?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Wa=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Vm=C(Wa,"u").replace(/punct/g,mt).getRegex(),Gm=C(Wa,"u").replace(/punct/g,Da).getRegex(),_a="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Jm=C(_a,"gu").replace(/notPunctSpace/g,ko).replace(/punctSpace/g,Hi).replace(/punct/g,mt).getRegex(),Qm=C(_a,"gu").replace(/notPunctSpace/g,qm).replace(/punctSpace/g,Hm).replace(/punct/g,Da).getRegex(),Zm=C("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ko).replace(/punctSpace/g,Hi).replace(/punct/g,mt).getRegex(),Xm=C(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,mt).getRegex(),Ym="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",ev=C(Ym,"gu").replace(/notPunctSpace/g,ko).replace(/punctSpace/g,Hi).replace(/punct/g,mt).getRegex(),tv=C(/\\(punct)/,"gu").replace(/punct/g,mt).getRegex(),iv=C(/^<(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(),sv=C(So).replace("(?:-->|$)","-->").getRegex(),ov=C("^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",sv).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ri=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,rv=C(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Ri).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),La=C(/^!?\[(label)\]\[(ref)\]/).replace("label",Ri).replace("ref",yo).getRegex(),Oa=C(/^!?\[(ref)\](?:\[\])?/).replace("ref",yo).getRegex(),nv=C("reflink|nolink(?!\\()","g").replace("reflink",La).replace("nolink",Oa).getRegex(),Br=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,$o={_backpedal:Ge,anyPunctuation:tv,autolink:iv,blockSkip:Km,br:Ea,code:Nm,del:Ge,delLDelim:Ge,delRDelim:Ge,emStrongLDelim:Vm,emStrongRDelimAst:Jm,emStrongRDelimUnd:Zm,escape:zm,link:rv,nolink:Oa,punctuation:Um,reflink:La,reflinkSearch:nv,tag:ov,text:Bm,url:Ge},av={...$o,link:C(/^!?\[(label)\]\((.*?)\)/).replace("label",Ri).getRegex(),reflink:C(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Ri).getRegex()},Ls={...$o,emStrongRDelimAst:Qm,emStrongLDelim:Gm,delLDelim:Xm,delRDelim:ev,url:C(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Br).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:C(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Br).getRegex()},cv={...Ls,br:C(Ea).replace("{2,}","*").getRegex(),text:C(Ls.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Yt={normal:xo,gfm:jm,pedantic:Fm},It={normal:$o,gfm:Ls,breaks:cv,pedantic:av},lv={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Ur=e=>lv[e];function Te(e,t){if(t){if(Q.escapeTest.test(e))return e.replace(Q.escapeReplace,Ur)}else if(Q.escapeTestNoEncode.test(e))return e.replace(Q.escapeReplaceNoEncode,Ur);return e}function Hr(e){try{e=encodeURI(e).replace(Q.percentDecode,"%")}catch{return null}return e}function qr(e,t){let i=e.replace(Q.findPipe,(r,n,a)=>{let l=!1,p=n;for(;--p>=0&&a[p]==="\\";)l=!l;return l?"|":" |"}),s=i.split(Q.splitPipe),o=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;o<s.length;o++)s[o]=s[o].trim().replace(Q.slashPipe,"|");return s}function Ne(e,t,i){let s=e.length;if(s===0)return"";let o=0;for(;o<s&&e.charAt(s-o-1)===t;)o++;return e.slice(0,s-o)}function Kr(e){let t=e.split(`
840
840
  `),i=t.length-1;for(;i>=0&&Q.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
841
- `)}function ev(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 tv(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 qo(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 l={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:o,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,l}function iv(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(`
842
- `).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(`
843
- `)}var Ri=class{options;rules;lexer;constructor(e){this.options=e||tt}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:Ho(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=iv(i,t[3]||"",this.rules);return{type:"code",raw:i,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let i=t[2].trim();if(this.rules.other.endingHash.test(i)){let s=ze(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:ze(t[0],`
844
- `),depth:t[1].length,text:i,tokens:this.lexer.inline(i)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:ze(t[0],`
845
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=ze(t[0],`
841
+ `)}function dv(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 pv(e,t=0){let i=t,s="";for(let o of e)if(o===" "){let r=4-i%4;s+=" ".repeat(r),i+=r}else s+=o,i++;return s}function Vr(e,t,i,s,o){let r=t.href,n=t.title||null,a=e[1].replace(o.other.outputLinkReplace,"$1");s.state.inLink=!0;let l={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:r,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,l}function hv(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let o=s[1];return t.split(`
842
+ `).map(r=>{let n=r.match(i.other.beginningSpace);if(n===null)return r;let[a]=n;return a.length>=o.length?r.slice(o.length):r}).join(`
843
+ `)}var Ii=class{options;rules;lexer;constructor(e){this.options=e||tt}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:Kr(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=hv(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=Ne(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Ne(t[0],`
844
+ `),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:Ne(t[0],`
845
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Ne(t[0],`
846
846
  `).split(`
847
- `),s="",r="",o=[];for(;i.length>0;){let n=!1,a=[],l;for(l=0;l<i.length;l++)if(this.rules.other.blockquoteStart.test(i[l]))a.push(i[l]),n=!0;else if(!n)a.push(i[l]);else break;i=i.slice(l);let p=a.join(`
847
+ `),s="",o="",r=[];for(;i.length>0;){let n=!1,a=[],l;for(l=0;l<i.length;l++)if(this.rules.other.blockquoteStart.test(i[l]))a.push(i[l]),n=!0;else if(!n)a.push(i[l]);else break;i=i.slice(l);let p=a.join(`
848
848
  `),u=p.replace(this.rules.other.blockquoteSetextReplace,`
849
849
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
850
- ${p}`:p,r=r?`${r}
851
- ${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+`
850
+ ${p}`:p,o=o?`${o}
851
+ ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,r,!0),this.lexer.state.top=h,i.length===0)break;let g=r.at(-1);if(g?.type==="code")break;if(g?.type==="blockquote"){let w=g,P=w.raw+`
852
852
  `+i.join(`
853
- `),H=this.blockquote(P);o[o.length-1]=H,s=s.substring(0,s.length-w.raw.length)+H.raw,r=r.substring(0,r.length-w.text.length)+H.text;break}else if(g?.type==="list"){let w=g,P=w.raw+`
853
+ `),H=this.blockquote(P);r[r.length-1]=H,s=s.substring(0,s.length-w.raw.length)+H.raw,o=o.substring(0,o.length-w.text.length)+H.text;break}else if(g?.type==="list"){let w=g,P=w.raw+`
854
854
  `+i.join(`
855
- `),H=this.list(P);o[o.length-1]=H,s=s.substring(0,s.length-g.raw.length)+H.raw,r=r.substring(0,r.length-w.raw.length)+H.raw,i=P.substring(o.at(-1).raw.length).split(`
856
- `);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 l=!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=tv(t[2].split(`
855
+ `),H=this.list(P);r[r.length-1]=H,s=s.substring(0,s.length-g.raw.length)+H.raw,o=o.substring(0,o.length-w.raw.length)+H.raw,i=P.substring(r.at(-1).raw.length).split(`
856
+ `);continue}}return{type:"blockquote",raw:s,tokens:r,text:o}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,o={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let r=this.rules.other.listItemRegex(i),n=!1;for(;e;){let l=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=pv(t[2].split(`
857
857
  `,1)[0],t[1].length),g=e.split(`
858
858
  `,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+`
859
- `,e=e.substring(g.length+1),l=!0),!l){let H=this.rules.other.nextBulletRegex(P),rt=this.rules.other.hrRegex(P),mt=this.rules.other.fencesBeginRegex(P),Pr=this.rules.other.headingBeginRegex(P),Ka=this.rules.other.htmlBeginRegex(P),Va=this.rules.other.blockquoteBeginRegex(P);for(;e;){let qi=e.split(`
860
- `,1)[0],vt;if(g=qi,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),vt=g):vt=g.replace(this.rules.other.tabCharGlobal," "),mt.test(g)||Pr.test(g)||Ka.test(g)||Va.test(g)||H.test(g)||rt.test(g))break;if(vt.search(this.rules.other.nonSpaceChar)>=P||!g.trim())u+=`
861
- `+vt.slice(P);else{if(w||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||mt.test(h)||Pr.test(h)||rt.test(h))break;u+=`
862
- `+g}w=!g.trim(),p+=qi+`
863
- `,e=e.substring(qi.length+1),h=vt.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 l of r.items){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);let p=l.tokens[0];if(l.task&&(p?.type==="text"||p?.type==="paragraph")){l.text=l.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(l.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=h.checked,r.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=h.raw+l.tokens[0].raw,l.tokens[0].text=h.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(h)):l.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):l.tokens.unshift(h)}}else l.task&&(l.task=!1);if(!r.loose){let u=l.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 l of r.items){l.loose=!0;for(let p of l.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Ho(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:ze(t[0],`
864
- `),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=Uo(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
865
- `):[],o={type:"table",raw:ze(t[0],`
866
- `),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(Uo(n,o.header.length).map((a,l)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[l]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:ze(t[0],`
859
+ `,e=e.substring(g.length+1),l=!0),!l){let H=this.rules.other.nextBulletRegex(P),ot=this.rules.other.hrRegex(P),vt=this.rules.other.fencesBeginRegex(P),Io=this.rules.other.headingBeginRegex(P),Ja=this.rules.other.htmlBeginRegex(P),Qa=this.rules.other.blockquoteBeginRegex(P);for(;e;){let Ki=e.split(`
860
+ `,1)[0],bt;if(g=Ki,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),bt=g):bt=g.replace(this.rules.other.tabCharGlobal," "),vt.test(g)||Io.test(g)||Ja.test(g)||Qa.test(g)||H.test(g)||ot.test(g))break;if(bt.search(this.rules.other.nonSpaceChar)>=P||!g.trim())u+=`
861
+ `+bt.slice(P);else{if(w||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||vt.test(h)||Io.test(h)||ot.test(h))break;u+=`
862
+ `+g}w=!g.trim(),p+=Ki+`
863
+ `,e=e.substring(Ki.length+1),h=bt.slice(P)}}o.loose||(n?o.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),o.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),o.raw+=p}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let l of o.items){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);let p=l.tokens[0];if(l.task&&(p?.type==="text"||p?.type==="paragraph")){l.text=l.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(l.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};l.checked=h.checked,o.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=h.raw+l.tokens[0].raw,l.tokens[0].text=h.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(h)):l.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):l.tokens.unshift(h)}}else l.task&&(l.task=!1);if(!o.loose){let u=l.tokens.filter(g=>g.type==="space"),h=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));o.loose=h}}if(o.loose)for(let l of o.items){l.loose=!0;for(let p of l.tokens)p.type==="text"&&(p.type="paragraph")}return o}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Kr(t[0]);return{type:"html",block:!0,raw:i,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:i}}}def(e){let t=this.rules.block.def.exec(e);if(t){let i=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:Ne(t[0],`
864
+ `),href:s,title:o}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=qr(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
865
+ `):[],r={type:"table",raw:Ne(t[0],`
866
+ `),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?r.align.push("right"):this.rules.other.tableAlignCenter.test(n)?r.align.push("center"):this.rules.other.tableAlignLeft.test(n)?r.align.push("left"):r.align.push(null);for(let n=0;n<i.length;n++)r.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:r.align[n]});for(let n of o)r.rows.push(qr(n,r.header.length).map((a,l)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[l]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:Ne(t[0],`
867
867
  `),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)===`
868
- `?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=ze(i.slice(0,-1),"\\");if((i.length-o.length)%2===0)return}else{let o=ev(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)),qo(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 qo(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,l=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)){l+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+l);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,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+r);(s=l.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}}}},ke=class Os{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||tt,this.options.tokenizer=this.options.tokenizer||new Ri,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let i={other:Q,block:Xt.normal,inline:Rt.normal};this.options.pedantic?(i.block=Xt.pedantic,i.inline=Rt.pedantic):this.options.gfm&&(i.block=Xt.gfm,this.options.breaks?i.inline=Rt.breaks:i.inline=Rt.gfm),this.tokenizer.rules=i}static get rules(){return{block:Xt,inline:Rt}}static lex(t,i){return new Os(i).lex(t)}static lexInline(t,i){return new Os(i).inlineTokens(t)}lex(t){t=t.replace(Q.carriageReturn,`
869
- `),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(Q.tabCharGlobal," ").replace(Q.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+=`
870
- `: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(`
868
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let r=Ne(i.slice(0,-1),"\\");if((i.length-r.length)%2===0)return}else{let r=dv(t[2],"()");if(r===-2)return;if(r>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+r;t[2]=t[2].substring(0,r),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],o="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],o=r[3])}else o=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(i)?s=s.slice(1):s=s.slice(1,-1)),Vr(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let s=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=t[s.toLowerCase()];if(!o){let r=i[0].charAt(0);return{type:"text",raw:r,text:r}}return Vr(i,o,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&i.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,l=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+o);(s=p.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(n=[...r].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&o%3&&!((o+n)%3)){l+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+l);let u=[...s[0]][0].length,h=e.slice(0,o+s.index+u+n);if(Math.min(o,n)%2){let w=h.slice(1,-1);return{type:"em",raw:h,text:w,tokens:this.lexer.inlineTokens(w)}}let g=h.slice(2,-2);return{type:"strong",raw:h,text:g,tokens:this.lexer.inlineTokens(g)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(i),o=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&o&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+o);(s=l.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r||(n=[...r].length,n!==o))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,u=e.slice(0,o+s.index+p+n),h=u.slice(o,-o);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,s;return t[2]==="@"?(i=t[1],s="mailto:"+i):(i=t[1],s=i),{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let o;do o=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(o!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:i}}}},ke=class Os{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||tt,this.options.tokenizer=this.options.tokenizer||new Ii,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let i={other:Q,block:Yt.normal,inline:It.normal};this.options.pedantic?(i.block=Yt.pedantic,i.inline=It.pedantic):this.options.gfm&&(i.block=Yt.gfm,this.options.breaks?i.inline=It.breaks:i.inline=It.gfm),this.tokenizer.rules=i}static get rules(){return{block:Yt,inline:It}}static lex(t,i){return new Os(i).lex(t)}static lexInline(t,i){return new Os(i).inlineTokens(t)}lex(t){t=t.replace(Q.carriageReturn,`
869
+ `),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(Q.tabCharGlobal," ").replace(Q.spaceLine,""));let o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(a=>(r=a.call({lexer:this},t,i))?(t=t.substring(r.raw.length),i.push(r),!0):!1))continue;if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length);let a=i.at(-1);r.raw.length===1&&a!==void 0?a.raw+=`
870
+ `:i.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
871
871
  `)?"":`
872
- `)+o.raw,a.text+=`
873
- `+o.text,this.inlineQueue.at(-1).src=a.text):i.push(o);continue}if(o=this.tokenizer.fences(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.heading(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.hr(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.blockquote(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.list(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.html(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.def(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
872
+ `)+r.raw,a.text+=`
873
+ `+r.text,this.inlineQueue.at(-1).src=a.text):i.push(r);continue}if(r=this.tokenizer.fences(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.heading(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.hr(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.blockquote(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.list(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.html(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.def(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
874
874
  `)?"":`
875
- `)+o.raw,a.text+=`
876
- `+o.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},i.push(o));continue}if(o=this.tokenizer.table(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.lheading(t)){t=t.substring(o.raw.length),i.push(o);continue}let n=t;if(this.options.extensions?.startBlock){let a=1/0,l=t.slice(1),p;this.options.extensions.startBlock.forEach(u=>{p=u.call({lexer:this},l),typeof p=="number"&&p>=0&&(a=Math.min(a,p))}),a<1/0&&a>=0&&(n=t.substring(0,a+1))}if(this.state.top&&(o=this.tokenizer.paragraph(n))){let a=i.at(-1);s&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
875
+ `)+r.raw,a.text+=`
876
+ `+r.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},i.push(r));continue}if(r=this.tokenizer.table(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.lheading(t)){t=t.substring(r.raw.length),i.push(r);continue}let n=t;if(this.options.extensions?.startBlock){let a=1/0,l=t.slice(1),p;this.options.extensions.startBlock.forEach(u=>{p=u.call({lexer:this},l),typeof p=="number"&&p>=0&&(a=Math.min(a,p))}),a<1/0&&a>=0&&(n=t.substring(0,a+1))}if(this.state.top&&(r=this.tokenizer.paragraph(n))){let a=i.at(-1);s&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
877
877
  `)?"":`
878
- `)+o.raw,a.text+=`
879
- `+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(`
878
+ `)+r.raw,a.text+=`
879
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r),s=n.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
880
880
  `)?"":`
881
- `)+o.raw,a.text+=`
882
- `+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="",l=1/0;for(;t;){if(t.length<l)l=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let u=t;if(this.options.extensions?.startInline){let h=1/0,g=t.slice(1),w;this.options.extensions.startInline.forEach(P=>{w=P.call({lexer:this},g),typeof w=="number"&&w>=0&&(h=Math.min(h,w))}),h<1/0&&h>=0&&(u=t.substring(0,h+1))}if(p=this.tokenizer.inlineText(u)){t=t.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),n=!0;let h=i.at(-1);h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},Ii=class{options;parser;constructor(e){this.options=e||tt}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(Q.notSpaceStart)?.[0],r=e.replace(Q.endingNewline,"")+`
883
- `;return s?'<pre><code class="language-'+Te(s)+'">'+(i?r:Te(r,!0))+`</code></pre>
884
- `:"<pre><code>"+(i?r:Te(r,!0))+`</code></pre>
881
+ `)+r.raw,a.text+=`
882
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,o=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,o.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)r=o[2]?o[2].length:0,s=s.slice(0,o.index+r)+"["+"a".repeat(o[0].length-r-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",l=1/0;for(;t;){if(t.length<l)l=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)}},Ci=class{options;parser;constructor(e){this.options=e||tt}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(Q.notSpaceStart)?.[0],o=e.replace(Q.endingNewline,"")+`
883
+ `;return s?'<pre><code class="language-'+Te(s)+'">'+(i?o:Te(o,!0))+`</code></pre>
884
+ `:"<pre><code>"+(i?o:Te(o,!0))+`</code></pre>
885
885
  `}blockquote({tokens:e}){return`<blockquote>
886
886
  ${this.parser.parse(e)}</blockquote>
887
887
  `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
888
888
  `}hr(e){return`<hr>
889
- `}list(e){let t=e.ordered,i=e.start,s="";for(let n=0;n<e.items.length;n++){let a=e.items[n];s+=this.listitem(a)}let r=t?"ol":"ul",o=t&&i!==1?' start="'+i+'"':"";return"<"+r+o+`>
890
- `+s+"</"+r+`>
889
+ `}list(e){let t=e.ordered,i=e.start,s="";for(let n=0;n<e.items.length;n++){let a=e.items[n];s+=this.listitem(a)}let o=t?"ol":"ul",r=t&&i!==1?' start="'+i+'"':"";return"<"+o+r+`>
890
+ `+s+"</"+o+`>
891
891
  `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
892
892
  `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
893
- `}table(e){let t="",i="";for(let r=0;r<e.header.length;r++)i+=this.tablecell(e.header[r]);t+=this.tablerow({text:i});let s="";for(let r=0;r<e.rows.length;r++){let o=e.rows[r];i="";for(let n=0;n<o.length;n++)i+=this.tablecell(o[n]);s+=this.tablerow({text:i})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
893
+ `}table(e){let t="",i="";for(let o=0;o<e.header.length;o++)i+=this.tablecell(e.header[o]);t+=this.tablerow({text:i});let s="";for(let o=0;o<e.rows.length;o++){let r=e.rows[o];i="";for(let n=0;n<r.length;n++)i+=this.tablecell(r[n]);s+=this.tablerow({text:i})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
894
894
  <thead>
895
895
  `+t+`</thead>
896
896
  `+s+`</table>
897
897
  `}tablerow({text:e}){return`<tr>
898
898
  ${e}</tr>
899
899
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
900
- `}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>${Te(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=Bo(e);if(r===null)return s;e=r;let o='<a href="'+e+'"';return t&&(o+=' title="'+Te(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=Bo(e);if(r===null)return Te(i);e=r;let o=`<img src="${e}" alt="${Te(i)}"`;return t&&(o+=` title="${Te(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Te(e.text)}},kr=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},$e=class Ls{options;renderer;textRenderer;constructor(t){this.options=t||tt,this.options.renderer=this.options.renderer||new Ii,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new kr}static parse(t,i){return new Ls(i).parse(t)}static parseInline(t,i){return new Ls(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}},Ct=class{options;block;constructor(e){this.options=e||tt}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?ke.lex:ke.lexInline}provideParser(e=this.block){return e?$e.parse:$e.parseInline}},sv=class{defaults=gr();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=$e;Renderer=Ii;TextRenderer=kr;Lexer=ke;Tokenizer=Ri;Hooks=Ct;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 Ii(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],l=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=l.apply(r,p)),u||""}}s.renderer=r}if(i.tokenizer){let r=this.defaults.tokenizer||new Ri(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],l=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=l.apply(r,p)),u}}s.tokenizer=r}if(i.hooks){let r=this.defaults.hooks||new Ct;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],l=r[n];Ct.passThroughHooks.has(o)?r[n]=p=>{if(this.defaults.async&&Ct.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await a.call(r,p);return l.call(r,h)})();let u=a.call(r,p);return l.call(r,u)}:r[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(r,p);return h===!1&&(h=await l.apply(r,p)),h})();let u=a.apply(r,p);return u===!1&&(u=l.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 ke.lex(e,t??this.defaults)}parser(e,t){return $e.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?ke.lex:ke.lexInline)(n,r),l=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(l,r.walkTokens));let p=await(r.hooks?await r.hooks.provideParser(e):e?$e.parse:$e.parseInline)(l,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?ke.lex:ke.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?$e.parse:$e.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+=`
901
- Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Te(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},Ye=new sv;function A(e,t){return Ye.parse(e,t)}A.options=A.setOptions=function(e){return Ye.setOptions(e),A.defaults=Ye.defaults,Pa(A.defaults),A};A.getDefaults=gr;A.defaults=tt;A.use=function(...e){return Ye.use(...e),A.defaults=Ye.defaults,Pa(A.defaults),A};A.walkTokens=function(e,t){return Ye.walkTokens(e,t)};A.parseInline=Ye.parseInline;A.Parser=$e;A.parser=$e.parse;A.Renderer=Ii;A.TextRenderer=kr;A.Lexer=ke;A.lexer=ke.lex;A.Tokenizer=Ri;A.Hooks=Ct;A.parse=A;A.options;A.setOptions;A.use;A.walkTokens;A.parseInline;$e.parse;ke.lex;const _a=new A.Renderer;_a.html=({text:e})=>nv(e);const rv=300,It=new Map;function ov(e){const t=It.get(e);if(t!==void 0)return t;const i=A.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:_a}),s=av(i);if(It.set(e,s),It.size>rv){const r=It.keys().next().value;r!==void 0&&It.delete(r)}return s}function nv(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function av(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")&&!cv(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function cv(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var lv=Object.defineProperty,dv=Object.getOwnPropertyDescriptor,Oa=(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&&lv(t,i,r),r};let Ci=class extends M{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 c`<div class="formatted" @click=${this.onFormattedClick}>${mm(ov(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 pv(e);this.setCopyButtonState(t,i?"copied":"failed"),window.setTimeout(()=>{this.setCopyButtonState(t,"idle")},1200)}setCopyButtonState(e,t){const i=e.querySelector("span");i!==null&&(i.textContent=t==="copied"?"✓":"⧉");const s=t==="copied"?"已复制代码块":t==="failed"?"复制代码块失败":"复制代码块";e.title=s,e.setAttribute("aria-label",s)}};Ci.styles=dg;Oa([d()],Ci.prototype,"text",2);Ci=Oa([E("formatted-text")],Ci);async function pv(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var hv=Object.defineProperty,uv=Object.getOwnPropertyDescriptor,Kt=(e,t,i,s)=>{for(var r=s>1?void 0:s?uv(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&&hv(t,i,r),r};const Ko=180;let et=class extends M{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=fv(e.args),s=gv(e.details),r=e.preview,o=s??r?.diff,n=o===void 0?void 0:mv(o),a=s!==void 0&&r?.diff!==void 0&&s!==r.diff,l=e.status==="error"?e.resultText:r?.error,p=o===void 0?e.resultText:void 0;return c`
900
+ `}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>${Te(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:i}){let s=this.parser.parseInline(i),o=Hr(e);if(o===null)return s;e=o;let r='<a href="'+e+'"';return t&&(r+=' title="'+Te(t)+'"'),r+=">"+s+"</a>",r}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let o=Hr(e);if(o===null)return Te(i);e=o;let r=`<img src="${e}" alt="${Te(i)}"`;return t&&(r+=` title="${Te(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Te(e.text)}},Po=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},$e=class js{options;renderer;textRenderer;constructor(t){this.options=t||tt,this.options.renderer=this.options.renderer||new Ci,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Po}static parse(t,i){return new js(i).parse(t)}static parseInline(t,i){return new js(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let o=t[s];if(this.options.extensions?.renderers?.[o.type]){let n=o,a=this.options.extensions.renderers[n.type].call({parser:this},n);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(n.type)){i+=a||"";continue}}let r=o;switch(r.type){case"space":{i+=this.renderer.space(r);break}case"hr":{i+=this.renderer.hr(r);break}case"heading":{i+=this.renderer.heading(r);break}case"code":{i+=this.renderer.code(r);break}case"table":{i+=this.renderer.table(r);break}case"blockquote":{i+=this.renderer.blockquote(r);break}case"list":{i+=this.renderer.list(r);break}case"checkbox":{i+=this.renderer.checkbox(r);break}case"html":{i+=this.renderer.html(r);break}case"def":{i+=this.renderer.def(r);break}case"paragraph":{i+=this.renderer.paragraph(r);break}case"text":{i+=this.renderer.text(r);break}default:{let n='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(n),"";throw new Error(n)}}}return i}parseInline(t,i=this.renderer){this.renderer.parser=this;let s="";for(let o=0;o<t.length;o++){let r=t[o];if(this.options.extensions?.renderers?.[r.type]){let a=this.options.extensions.renderers[r.type].call({parser:this},r);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){s+=a||"";continue}}let n=r;switch(n.type){case"escape":{s+=i.text(n);break}case"html":{s+=i.html(n);break}case"link":{s+=i.link(n);break}case"image":{s+=i.image(n);break}case"checkbox":{s+=i.checkbox(n);break}case"strong":{s+=i.strong(n);break}case"em":{s+=i.em(n);break}case"codespan":{s+=i.codespan(n);break}case"br":{s+=i.br(n);break}case"del":{s+=i.del(n);break}case"text":{s+=i.text(n);break}default:{let a='Token with "'+n.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return s}},Mt=class{options;block;constructor(e){this.options=e||tt}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?ke.lex:ke.lexInline}provideParser(e=this.block){return e?$e.parse:$e.parseInline}},uv=class{defaults=vo();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=$e;Renderer=Ci;TextRenderer=Po;Lexer=ke;Tokenizer=Ii;Hooks=Mt;constructor(...e){this.use(...e)}walkTokens(e,t){let i=[];for(let s of e)switch(i=i.concat(t.call(this,s)),s.type){case"table":{let o=s;for(let r of o.header)i=i.concat(this.walkTokens(r.tokens,t));for(let r of o.rows)for(let n of r)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let o=s;i=i.concat(this.walkTokens(o.items,t));break}default:{let o=s;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(r=>{let n=o[r].flat(1/0);i=i.concat(this.walkTokens(n,t))}):o.tokens&&(i=i.concat(this.walkTokens(o.tokens,t)))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let s={...i};if(s.async=this.defaults.async||s.async||!1,i.extensions&&(i.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let r=t.renderers[o.name];r?t.renderers[o.name]=function(...n){let a=o.renderer.apply(this,n);return a===!1&&(a=r.apply(this,n)),a}:t.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[o.level];r?r.unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),s.extensions=t),i.renderer){let o=this.defaults.renderer||new Ci(this.defaults);for(let r in i.renderer){if(!(r in o))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let n=r,a=i.renderer[n],l=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=l.apply(o,p)),u||""}}s.renderer=o}if(i.tokenizer){let o=this.defaults.tokenizer||new Ii(this.defaults);for(let r in i.tokenizer){if(!(r in o))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let n=r,a=i.tokenizer[n],l=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=l.apply(o,p)),u}}s.tokenizer=o}if(i.hooks){let o=this.defaults.hooks||new Mt;for(let r in i.hooks){if(!(r in o))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let n=r,a=i.hooks[n],l=o[n];Mt.passThroughHooks.has(r)?o[n]=p=>{if(this.defaults.async&&Mt.passThroughHooksRespectAsync.has(r))return(async()=>{let h=await a.call(o,p);return l.call(o,h)})();let u=a.call(o,p);return l.call(o,u)}:o[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(o,p);return h===!1&&(h=await l.apply(o,p)),h})();let u=a.apply(o,p);return u===!1&&(u=l.apply(o,p)),u}}s.hooks=o}if(i.walkTokens){let o=this.defaults.walkTokens,r=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(r.call(this,n)),o&&(a=a.concat(o.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ke.lex(e,t??this.defaults)}parser(e,t){return $e.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},o={...this.defaults,...s},r=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&s.async===!1)return r(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return r(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let n=o.hooks?await o.hooks.preprocess(t):t,a=await(o.hooks?await o.hooks.provideLexer(e):e?ke.lex:ke.lexInline)(n,o),l=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(l,o.walkTokens));let p=await(o.hooks?await o.hooks.provideParser(e):e?$e.parse:$e.parseInline)(l,o);return o.hooks?await o.hooks.postprocess(p):p})().catch(r);try{o.hooks&&(t=o.hooks.preprocess(t));let n=(o.hooks?o.hooks.provideLexer(e):e?ke.lex:ke.lexInline)(t,o);o.hooks&&(n=o.hooks.processAllTokens(n)),o.walkTokens&&this.walkTokens(n,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(e):e?$e.parse:$e.parseInline)(n,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(n){return r(n)}}}onError(e,t){return i=>{if(i.message+=`
901
+ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Te(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},Ye=new uv;function A(e,t){return Ye.parse(e,t)}A.options=A.setOptions=function(e){return Ye.setOptions(e),A.defaults=Ye.defaults,Ca(A.defaults),A};A.getDefaults=vo;A.defaults=tt;A.use=function(...e){return Ye.use(...e),A.defaults=Ye.defaults,Ca(A.defaults),A};A.walkTokens=function(e,t){return Ye.walkTokens(e,t)};A.parseInline=Ye.parseInline;A.Parser=$e;A.parser=$e.parse;A.Renderer=Ci;A.TextRenderer=Po;A.Lexer=ke;A.lexer=ke.lex;A.Tokenizer=Ii;A.Hooks=Mt;A.parse=A;A.options;A.setOptions;A.use;A.walkTokens;A.parseInline;$e.parse;ke.lex;const ja=new A.Renderer;ja.html=({text:e})=>mv(e);const fv=300,Ct=new Map;function gv(e){const t=Ct.get(e);if(t!==void 0)return t;const i=A.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:ja}),s=vv(i);if(Ct.set(e,s),Ct.size>fv){const o=Ct.keys().next().value;o!==void 0&&Ct.delete(o)}return s}function mv(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function vv(e){const t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("script, style, iframe, object, embed").forEach(i=>{i.remove()}),t.content.querySelectorAll("*").forEach(i=>{for(const s of[...i.attributes]){const o=s.name.toLowerCase();o.startsWith("on")&&i.removeAttribute(s.name),(o==="href"||o==="src")&&!bv(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function bv(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var wv=Object.defineProperty,yv=Object.getOwnPropertyDescriptor,Fa=(e,t,i,s)=>{for(var o=s>1?void 0:s?yv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&wv(t,i,o),o};let Mi=class extends M{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 c`<div class="formatted" @click=${this.onFormattedClick}>${Rm(gv(this.text))}</div>`}updated(){this.enhanceCodeBlocks()}enhanceCodeBlocks(){this.renderRoot.querySelectorAll("pre").forEach(e=>{if(!(e instanceof HTMLPreElement)||e.parentElement?.classList.contains("code-block-wrapper")===!0||!(e.querySelector("code")instanceof HTMLElement))return;const i=document.createElement("div");i.className="code-block-wrapper";const s=document.createElement("button");s.type="button",s.className="code-copy-button",s.title="复制代码块",s.setAttribute("aria-label","复制代码块");const o=document.createElement("span");o.setAttribute("aria-hidden","true"),o.textContent="⧉",s.append(o),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await Sv(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)}};Mi.styles=yg;Fa([d()],Mi.prototype,"text",2);Mi=Fa([D("formatted-text")],Mi);async function Sv(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var xv=Object.defineProperty,kv=Object.getOwnPropertyDescriptor,Vt=(e,t,i,s)=>{for(var o=s>1?void 0:s?kv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&xv(t,i,o),o};const Gr=180;let et=class extends M{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=$v(e.args),s=Pv(e.details),o=e.preview,r=s??o?.diff,n=r===void 0?void 0:Rv(r),a=s!==void 0&&o?.diff!==void 0&&s!==o.diff,l=e.status==="error"?e.resultText:o?.error,p=r===void 0?e.resultText:void 0;return c`
902
902
  <section class=${`tool-card ${e.status}`}>
903
903
  <div class="tool-header">
904
904
  <div class="tool-title">
905
- <span class="status-icon" aria-hidden="true">${bv(e.status)}</span>
905
+ <span class="status-icon" aria-hidden="true">${Cv(e.status)}</span>
906
906
  <strong>${e.toolName}</strong>
907
907
  ${i===void 0?c`<span class="summary">${e.summary}</span>`:c`<span class="path">${i}</span>`}
908
908
  </div>
909
909
  <div class="tool-meta">
910
- ${Vo(e)===void 0?null:c`<span>${Vo(e)}</span>`}
910
+ ${Jr(e)===void 0?null:c`<span>${Jr(e)}</span>`}
911
911
  ${n===void 0?null:c`<span class="diff-stats"><b class="added">+${n.added}</b><span>/</span><b class="removed">-${n.removed}</b></span>`}
912
- <span class="status-label">${wv(e.status)}</span>
912
+ <span class="status-label">${Mv(e.status)}</span>
913
913
  </div>
914
914
  </div>
915
915
 
916
916
  ${a?c`<p class="notice">实际应用的 diff 与预览不同。</p>`:null}
917
917
  ${l===void 0||l===""?null:c`<pre class="error-text">${l}</pre>`}
918
- ${o===void 0?this.renderTextBody(p,e.status==="error"):this.renderDiffBody(o,s===void 0?"预览 diff":"已应用 diff")}
919
- ${!t&&o===void 0&&(p===void 0||p==="")?c`<p class="muted">${e.summary}</p>`:null}
918
+ ${r===void 0?this.renderTextBody(p,e.status==="error"):this.renderDiffBody(r,s===void 0?"预览 diff":"已应用 diff")}
919
+ ${!t&&r===void 0&&(p===void 0||p==="")?c`<p class="muted">${e.summary}</p>`:null}
920
920
  </section>
921
921
  `}renderTextBody(e,t){return e===void 0||e===""?null:c`
922
922
  <details class="text-body" ?open=${t}>
@@ -924,17 +924,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
924
924
  <pre>${e}</pre>
925
925
  </details>
926
926
  `}renderDiffBody(e,t){const i=e.split(`
927
- `),s=!this.showFullDiff&&i.length>Ko,r=s?i.slice(0,Ko):i;return c`
928
- <details class="diff-details" ?open=${this.diffOpen} @toggle=${o=>{this.onDiffToggle(o)}}>
927
+ `),s=!this.showFullDiff&&i.length>Gr,o=s?i.slice(0,Gr):i;return c`
928
+ <details class="diff-details" ?open=${this.diffOpen} @toggle=${r=>{this.onDiffToggle(r)}}>
929
929
  <summary>
930
930
  <span>${t}</span>
931
931
  <small>${String(i.length)} 行</small>
932
932
  </summary>
933
933
  <div class="diff-toolbar">
934
- <span>${s?`显示 ${String(r.length)} / ${String(i.length)} 行`:"完整 diff"}</span>
934
+ <span>${s?`显示 ${String(o.length)} / ${String(i.length)} 行`:"完整 diff"}</span>
935
935
  <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"已复制":"复制 diff"}</button>
936
936
  </div>
937
- <pre class="diff" aria-label=${t}><code class="diff-content">${r.map(o=>c`<span class=${vv(o)}>${o}</span>`)}</code></pre>
937
+ <pre class="diff" aria-label=${t}><code class="diff-content">${o.map(r=>c`<span class=${Iv(r)}>${r}</span>`)}</code></pre>
938
938
  ${s?c`
939
939
  <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
940
940
  显示全部 ${String(i.length)} 行 diff
@@ -981,19 +981,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
981
981
  .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
982
982
  .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
983
983
  .show-more { justify-self: start; }
984
- `;Kt([d({attribute:!1})],et.prototype,"execution",2);Kt([y()],et.prototype,"showFullDiff",2);Kt([y()],et.prototype,"copied",2);Kt([y()],et.prototype,"diffOpen",2);et=Kt([E("tool-execution-view")],et);function fv(e){return js(e,"path")??js(e,"file_path")}function Vo(e){if(e.toolName!=="edit")return;const t=li(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof li(e.args,"oldText")=="string"&&typeof li(e.args,"newText")=="string")return"1 处编辑"}function gv(e){return js(e,"diff")}function mv(e){let t=0,i=0;for(const s of e.split(`
985
- `))La(s)?t++:ja(s)&&i++;return{added:t,removed:i}}function vv(e){return La(e)?"added":ja(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function La(e){return e.startsWith("+")&&!e.startsWith("+++")}function ja(e){return e.startsWith("-")&&!e.startsWith("---")}function bv(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function wv(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function yv(e){return typeof e=="object"&&e!==null}function li(e,t){return yv(e)?e[t]:void 0}function js(e,t){const i=li(e,t);return typeof i=="string"?i:void 0}var Sv=Object.defineProperty,xv=Object.getOwnPropertyDescriptor,U=(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&&Sv(t,i,r),r};const kv=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),$v=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),ps=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"],Pv={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 Go(){return ps[Math.floor(Math.random()*ps.length)]??ps[0]}function Jo(e){return di(e,0,100)}function di(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let L=class extends M{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 Fg,this.scrollController=new lm,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 c`
984
+ `;Vt([d({attribute:!1})],et.prototype,"execution",2);Vt([S()],et.prototype,"showFullDiff",2);Vt([S()],et.prototype,"copied",2);Vt([S()],et.prototype,"diffOpen",2);et=Vt([D("tool-execution-view")],et);function $v(e){return Fs(e,"path")??Fs(e,"file_path")}function Jr(e){if(e.toolName!=="edit")return;const t=di(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof di(e.args,"oldText")=="string"&&typeof di(e.args,"newText")=="string")return"1 处编辑"}function Pv(e){return Fs(e,"diff")}function Rv(e){let t=0,i=0;for(const s of e.split(`
985
+ `))za(s)?t++:Na(s)&&i++;return{added:t,removed:i}}function Iv(e){return za(e)?"added":Na(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function za(e){return e.startsWith("+")&&!e.startsWith("+++")}function Na(e){return e.startsWith("-")&&!e.startsWith("---")}function Cv(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function Mv(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function Tv(e){return typeof e=="object"&&e!==null}function di(e,t){return Tv(e)?e[t]:void 0}function Fs(e,t){const i=di(e,t);return typeof i=="string"?i:void 0}var Av=Object.defineProperty,Ev=Object.getOwnPropertyDescriptor,U=(e,t,i,s)=>{for(var o=s>1?void 0:s?Ev(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Av(t,i,o),o};const Dv=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Wv=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),hs=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"],_v={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 Qr(){return hs[Math.floor(Math.random()*hs.length)]??hs[0]}function Zr(e){return pi(e,0,100)}function pi(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let O=class extends M{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 Jg,this.scrollController=new wm,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 c`
986
986
  <div class="chat-wrap">
987
987
  ${this.renderConversationRail()}
988
988
  <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
989
989
  ${this.renderHistoryBoundary()}
990
- ${Og(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)))}
990
+ ${Kg(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)))}
991
991
  ${this.renderQueuedMessages()}
992
992
  ${this.renderSessionActivity()}
993
993
  </div>
994
994
  ${this.renderActivityDock()}
995
995
  </div>
996
- `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Bg(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 c`
996
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Xg(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 c`
997
997
  <div class="activity-dock active" aria-live="polite">
998
998
  <span class="dot"></span>
999
999
  <span class="activity-text">正在发送你的消息…</span>
@@ -1028,7 +1028,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1028
1028
  <span>助手正在总结早前上下文。压缩完成前,新提示会排队等待。</span>
1029
1029
  ${this.pendingMessageCount>0?c`<small>${this.pendingMessageCount} 条消息已排队</small>`:null}
1030
1030
  </aside>
1031
- `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Go():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Go(),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 hs(e);const i=hs(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?Jo(this.messages.length/e*100):100;return c`<conversation-meter .positionPercent=${t} .loadedPercent=${i}></conversation-meter>`}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;const t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,i=di(this.currentConversationIndex??t,0,e-1);return Jo(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?c`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?c`
1031
+ `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Qr():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Qr(),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 us(e);const i=us(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?Zr(this.messages.length/e*100):100;return c`<conversation-meter .positionPercent=${t} .loadedPercent=${i}></conversation-meter>`}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;const t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,i=pi(this.currentConversationIndex??t,0,e-1);return Zr(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?c`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?c`
1032
1032
  <div class="history-boundary">
1033
1033
  <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>加载更早的消息</button>
1034
1034
  <span>向上滚动加载更早的消息</span>
@@ -1040,12 +1040,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1040
1040
  ${i?null:this.renderMessageHeader(e,String(t))}
1041
1041
  ${e.parts.map(s=>this.renderPart(s,e))}
1042
1042
  </article>
1043
- `}isToolExecutionOnlyMessage(e){return e.role==="tool"&&e.parts.length>0&&e.parts.every(t=>t.type==="toolExecution")}renderMessageGroup(e,t,i,s){const r=this.groupDisclosureKey(t,i,s),o=this.disclosures.isOpen(r,s);return c`
1043
+ `}isToolExecutionOnlyMessage(e){return e.role==="tool"&&e.parts.length>0&&e.parts.every(t=>t.type==="toolExecution")}renderMessageGroup(e,t,i,s){const o=this.groupDisclosureKey(t,i,s),r=this.disclosures.isOpen(o,s);return c`
1044
1044
  ${this.renderScrollMarker(this.groupScrollMarkerId(i))}
1045
- <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)}}>
1045
+ <details class=${s?"msg event-group live":"msg event-group"} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${r} @toggle=${n=>{this.onGroupToggle(o,n,s)}}>
1046
1046
  <summary>
1047
1047
  <b class="label">${s?"实时事件":"事件"}</b>
1048
- <span>${Ug(e)}</span>
1048
+ <span>${Yg(e)}</span>
1049
1049
  </summary>
1050
1050
  <div class="group-body">
1051
1051
  ${e.map((n,a)=>{const l=this.isToolExecutionOnlyMessage(n);return c`
@@ -1058,21 +1058,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1058
1058
  </details>
1059
1059
  `}renderScrollMarker(e){return c`<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 c`
1060
1060
  <div class="msg-header">
1061
- <b class="label">${Qo(e.role)}</b>
1061
+ <b class="label">${Xr(e.role)}</b>
1062
1062
  <div class="msg-header-trailing">
1063
1063
  ${this.renderMessageActions(e,t)}
1064
- <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>
1064
+ <span class=${s?"msg-meta expanded":"msg-meta"} role="button" tabindex="0" title=${i.full} aria-label=${i.full} aria-expanded=${String(s)} @click=${()=>{this.expandedMetaKey=s?void 0:t}} @keydown=${o=>{this.onMetaKeydown(o,t,s)}}>${i.short}</span>
1065
1065
  </div>
1066
1066
  </div>
1067
1067
  `}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return c`
1068
1068
  <div class="msg-actions" aria-label="消息操作">
1069
- <button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${Qo(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
1069
+ <button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${Xr(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
1070
1070
  <span aria-hidden="true">${i?"✓":"⧉"}</span>
1071
1071
  </button>
1072
1072
  </div>
1073
1073
  `}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(`
1074
1074
 
1075
- `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await this.writeClipboard(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const l={short:"无信息",full:"没有可用的 Pi 消息元数据"};return this.messageMetaCache.set(e,l),l}const r=i===void 0?void 0:this.formatTimestamp(i),o=[r?.short,s].filter(l=>l!==void 0&&l!==""),n=[r?.full,s===void 0?void 0:`模型:${s}`].filter(l=>l!==void 0&&l!==""),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:kv.format(t),full:$v.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"?c`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?c`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="image"?c`<figure class="part chat-image"><img src=${`data:${e.mimeType};base64,${e.data}`} alt="用户上传的图片" loading="lazy"></figure>`:e.type==="thinking"?c`<details class="part"><summary>思考</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?c`
1075
+ `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await this.writeClipboard(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const l={short:"无信息",full:"没有可用的 Pi 消息元数据"};return this.messageMetaCache.set(e,l),l}const o=i===void 0?void 0:this.formatTimestamp(i),r=[o?.short,s].filter(l=>l!==void 0&&l!==""),n=[o?.full,s===void 0?void 0:`模型:${s}`].filter(l=>l!==void 0&&l!==""),a={short:r.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:Dv.format(t),full:Wv.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"?c`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?c`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="image"?c`<figure class="part chat-image"><img src=${`data:${e.mimeType};base64,${e.data}`} alt="用户上传的图片" loading="lazy"></figure>`:e.type==="thinking"?c`<details class="part"><summary>思考</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?c`
1076
1076
  <details class="part skill-invocation">
1077
1077
  <summary><b>[技能]</b> ${e.name}</summary>
1078
1078
  <small>${e.location}</small>
@@ -1088,62 +1088,62 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1088
1088
  <summary>${e.isError?"✖":"✓"} ${e.toolName} 结果</summary>
1089
1089
  <formatted-text .text=${e.text}></formatted-text>
1090
1090
  </details>
1091
- `: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&&em({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?$a(e):!0}isAtBottom(){const e=this.chat;return e?ka(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 Kg(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(Vg(r,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=r.scrollTop,i+=1,i<qg){requestAnimationFrame(s);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};s()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){const e=this.sessionId;this.scrollController.scheduleSave(e,t=>{this.sessionId===t&&this.saveScrollPosition(t)})}scheduleConversationRailUpdate(){this.conversationRailFrame===void 0&&(this.conversationRailFrame=requestAnimationFrame(()=>{this.conversationRailFrame=void 0,this.updateConversationRailPosition()}))}updateConversationRailPosition(){if(!this.messages.length||this.messageTotal<=0){this.currentConversationIndex=void 0;return}const e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),i=Number(t?.dataset.index);if(Number.isFinite(i)){this.currentConversationIndex=di(i,0,Math.max(0,e-1));return}this.currentConversationIndex=di(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(".scroll-marker"))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}firstVisibleArticle(){const e=this.chat;if(e===void 0)return;const t=Array.from(this.renderRoot.querySelectorAll("article.msg"));return Lo(e,t)??Lo(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll("[data-scroll-anchor-id]"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,i){return i?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return`m:${String(e)}`}groupRenderKey(e){return`g:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}eventAnchorKey(e){return`e:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}};L.styles=lg;U([d({attribute:!1})],L.prototype,"messages",2);U([d()],L.prototype,"sessionId",2);U([d({type:Number})],L.prototype,"messageStart",2);U([d({type:Number})],L.prototype,"messageEnd",2);U([d({type:Number})],L.prototype,"messageTotal",2);U([d({type:Boolean})],L.prototype,"hasMore",2);U([d({type:Boolean})],L.prototype,"loadingMore",2);U([d({type:Boolean})],L.prototype,"isReceivingPartialStream",2);U([d({type:Boolean})],L.prototype,"isSendingPrompt",2);U([d({type:Boolean})],L.prototype,"isCompacting",2);U([d({type:Number})],L.prototype,"pendingMessageCount",2);U([d({attribute:!1})],L.prototype,"status",2);U([d({attribute:!1})],L.prototype,"activity",2);U([d({attribute:!1})],L.prototype,"onLoadMore",2);U([B(".chat")],L.prototype,"chat",2);U([y()],L.prototype,"pinnedToBottom",2);U([y()],L.prototype,"expandedMetaKey",2);U([y()],L.prototype,"copiedMessageKey",2);U([y()],L.prototype,"currentConversationIndex",2);U([y()],L.prototype,"loadMoreRequested",2);L=U([E("chat-view")],L);function Qo(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function hs(e){return e==="bash"?"Shell 运行中":e==="running"?"运行中":Pv[e]??e}const Rv=["image/jpeg","image/png","image/gif","image/webp"],Iv=new Set(Rv);function Cv(e){return typeof e=="string"&&Iv.has(e)}function Mv(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 Tv="Only PNG, JPEG, GIF, and WebP images are supported.",Av="读取附件失败。";async function Ev(e,t){const i=[];let s;for(const r of e){if(!Cv(r.type)){s=Tv;continue}try{const o=await t(r);i.push({name:Dv(r),mimeType:r.type,data:o,size:r.size})}catch{s=Av}}return{attachments:i,...s===void 0?{}:{error:s}}}function Dv(e){return e.name!==""?e.name:`pasted-image.${Mv(e.type)}`}const Fa="pi-web:attachment-delivery";function Na(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Wv(e=Na()){try{return e?.getItem(Fa)==="folder"?"folder":"inline"}catch{return"inline"}}function _v(e,t=Na()){try{t?.setItem(Fa,e)}catch{}}function Ov(){return ue`
1091
+ `: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&&dm({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?Ia(e):!0}isAtBottom(){const e=this.chat;return e?Ra(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 im(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;const t=this.prependRestoreToken+1;this.prependRestoreToken=t;let i=0;const s=()=>{const o=this.chat;if(!(!o||t!==this.prependRestoreToken)){if(sm(o,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=o.scrollTop,i+=1,i<tm){requestAnimationFrame(s);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};s()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){const e=this.sessionId;this.scrollController.scheduleSave(e,t=>{this.sessionId===t&&this.saveScrollPosition(t)})}scheduleConversationRailUpdate(){this.conversationRailFrame===void 0&&(this.conversationRailFrame=requestAnimationFrame(()=>{this.conversationRailFrame=void 0,this.updateConversationRailPosition()}))}updateConversationRailPosition(){if(!this.messages.length||this.messageTotal<=0){this.currentConversationIndex=void 0;return}const e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),i=Number(t?.dataset.index);if(Number.isFinite(i)){this.currentConversationIndex=pi(i,0,Math.max(0,e-1));return}this.currentConversationIndex=pi(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(".scroll-marker"))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}firstVisibleArticle(){const e=this.chat;if(e===void 0)return;const t=Array.from(this.renderRoot.querySelectorAll("article.msg"));return Fr(e,t)??Fr(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)}`}};O.styles=wg;U([d({attribute:!1})],O.prototype,"messages",2);U([d()],O.prototype,"sessionId",2);U([d({type:Number})],O.prototype,"messageStart",2);U([d({type:Number})],O.prototype,"messageEnd",2);U([d({type:Number})],O.prototype,"messageTotal",2);U([d({type:Boolean})],O.prototype,"hasMore",2);U([d({type:Boolean})],O.prototype,"loadingMore",2);U([d({type:Boolean})],O.prototype,"isReceivingPartialStream",2);U([d({type:Boolean})],O.prototype,"isSendingPrompt",2);U([d({type:Boolean})],O.prototype,"isCompacting",2);U([d({type:Number})],O.prototype,"pendingMessageCount",2);U([d({attribute:!1})],O.prototype,"status",2);U([d({attribute:!1})],O.prototype,"activity",2);U([d({attribute:!1})],O.prototype,"onLoadMore",2);U([B(".chat")],O.prototype,"chat",2);U([S()],O.prototype,"pinnedToBottom",2);U([S()],O.prototype,"expandedMetaKey",2);U([S()],O.prototype,"copiedMessageKey",2);U([S()],O.prototype,"currentConversationIndex",2);U([S()],O.prototype,"loadMoreRequested",2);O=U([D("chat-view")],O);function Xr(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function us(e){return e==="bash"?"Shell 运行中":e==="running"?"运行中":_v[e]??e}const Lv=["image/jpeg","image/png","image/gif","image/webp"],Ov=new Set(Lv);function jv(e){return typeof e=="string"&&Ov.has(e)}function Fv(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 zv="Only PNG, JPEG, GIF, and WebP images are supported.",Nv="读取附件失败。";async function Bv(e,t){const i=[];let s;for(const o of e){if(!jv(o.type)){s=zv;continue}try{const r=await t(o);i.push({name:Uv(o),mimeType:o.type,data:r,size:o.size})}catch{s=Nv}}return{attachments:i,...s===void 0?{}:{error:s}}}function Uv(e){return e.name!==""?e.name:`pasted-image.${Fv(e.type)}`}const Ba="pi-web:attachment-delivery";function Ua(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Hv(e=Ua()){try{return e?.getItem(Ba)==="folder"?"folder":"inline"}catch{return"inline"}}function qv(e,t=Ua()){try{t?.setItem(Ba,e)}catch{}}function Kv(){return ue`
1092
1092
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1093
1093
  <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>
1094
1094
  </svg>
1095
- `}function za(){return ue`
1095
+ `}function Ha(){return ue`
1096
1096
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1097
1097
  <path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
1098
1098
  <path d="M21 3 11.5 12.5"></path>
1099
1099
  </svg>
1100
- `}function Lv(){return ue`
1100
+ `}function Vv(){return ue`
1101
1101
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1102
1102
  <path d="M4 7h11"></path>
1103
1103
  <path d="M4 12h7"></path>
1104
1104
  <path d="M4 17h7"></path>
1105
1105
  <path d="m15 14 5 3-5 3z"></path>
1106
1106
  </svg>
1107
- `}function jv(){return za()}function Fv(){return ue`
1107
+ `}function Gv(){return Ha()}function Jv(){return ue`
1108
1108
  <svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1109
1109
  <rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
1110
1110
  </svg>
1111
- `}function Nv(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},(l,p)=>{const u=s+p*(n+i),h=4+(p+1)/t*12,g=20-h,w=p<e.filled;return ue`<rect class=${w?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${g} width=${n} height=${h} rx="1"></rect>`});return ue`
1111
+ `}function Qv(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},(l,p)=>{const u=s+p*(n+i),h=4+(p+1)/t*12,g=20-h,w=p<e.filled;return ue`<rect class=${w?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${g} width=${n} height=${h} rx="1"></rect>`});return ue`
1112
1112
  <svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1113
1113
  ${a}
1114
1114
  </svg>
1115
- `}const zv=["off","minimal","low","medium","high","xhigh"];function Fs(e){return e===void 0||e===""?"off":e}function Bv(e,t){const i=t.length>=2?t:zv,s=i.length-1,r=Fs(e),o=i.indexOf(r),n=o<=0?0:Math.min(o,s);return{total:s,filled:n}}class Uv extends hr{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===dr.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 $r=pr(Uv);var Hv=Object.defineProperty,qv=Object.getOwnPropertyDescriptor,Hi=(e,t,i,s)=>{for(var r=s>1?void 0:s?qv(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&&Hv(t,i,r),r};let ht=class extends M{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?c`
1115
+ `}const Zv=["off","minimal","low","medium","high","xhigh"];function zs(e){return e===void 0||e===""?"off":e}function Xv(e,t){const i=t.length>=2?t:Zv,s=i.length-1,o=zs(e),r=i.indexOf(o),n=r<=0?0:Math.min(r,s);return{total:s,filled:n}}class Yv extends fo{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===ho.ELEMENT}update(t,[i,s]){if(!this.isElementPart)throw new Error("scrollWhenSelected must be used on an element");if(i&&(!this.wasSelected||s!==this.previousKey)){const o="element"in t?t.element:void 0;requestAnimationFrame(()=>{o instanceof HTMLElement&&o.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const Ro=uo(Yv);var eb=Object.defineProperty,tb=Object.getOwnPropertyDescriptor,qi=(e,t,i,s)=>{for(var o=s>1?void 0:s?tb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&eb(t,i,o),o};let ut=class extends M{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?c`
1116
1116
  <div class="menu">
1117
1117
  ${this.items.map((e,t)=>c`
1118
- <button class=${t===this.selectedIndex?"selected":""} ${$r(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1118
+ <button class=${t===this.selectedIndex?"selected":""} ${Ro(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1119
1119
  <strong>${e.insertText}</strong>
1120
1120
  <span>${e.detail}</span>
1121
1121
  ${e.description!==void 0&&e.description!==""?c`<small>${e.description}</small>`:null}
1122
1122
  </button>
1123
1123
  `)}
1124
1124
  </div>
1125
- `:null}};ht.styles=hg;Hi([d({attribute:!1})],ht.prototype,"items",2);Hi([d({type:Number})],ht.prototype,"selectedIndex",2);Hi([d({attribute:!1})],ht.prototype,"onPick",2);ht=Hi([E("autocomplete-menu")],ht);var Kv=Object.defineProperty,Vv=Object.getOwnPropertyDescriptor,j=(e,t,i,s)=>{for(var r=s>1?void 0:s?Vv(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 O=class extends M{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft="",this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=Wv(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new Rr,this.readOnlyCompartment=new Rr}willUpdate(e){if(!e.has("sessionId")&&!e.has("machineId"))return;const t=e.has("sessionId")?e.get("sessionId"):this.sessionId,i=e.has("machineId")?e.get("machineId"):this.machineId,s=Yt(i,t);s!==void 0&&bi(s,this.draft);const r=Yt(this.machineId,this.sessionId);this.draft=r!==void 0?On(r):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("draft")||e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=ir(this.draft),t=e.kind==="shell",i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return c`
1126
- <footer class=${t?"shell-mode":""} @paste=${r=>{this.handlePaste(r)}} @dragover=${r=>{this.handleDragOver(r)}} @drop=${r=>{this.handleDrop(r)}}>
1125
+ `:null}};ut.styles=xg;qi([d({attribute:!1})],ut.prototype,"items",2);qi([d({type:Number})],ut.prototype,"selectedIndex",2);qi([d({attribute:!1})],ut.prototype,"onPick",2);ut=qi([D("autocomplete-menu")],ut);var ib=Object.defineProperty,sb=Object.getOwnPropertyDescriptor,j=(e,t,i,s)=>{for(var o=s>1?void 0:s?sb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&ib(t,i,o),o};let L=class extends M{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft="",this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=Hv(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new Co,this.readOnlyCompartment=new Co}willUpdate(e){if(!e.has("sessionId")&&!e.has("machineId"))return;const t=e.has("sessionId")?e.get("sessionId"):this.sessionId,i=e.has("machineId")?e.get("machineId"):this.machineId,s=ei(i,t);s!==void 0&&wi(s,this.draft);const o=ei(this.machineId,this.sessionId);this.draft=o!==void 0?jn(o):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("draft")||e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=so(this.draft),t=e.kind==="shell",i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return c`
1126
+ <footer class=${t?"shell-mode":""} @paste=${o=>{this.handlePaste(o)}} @dragover=${o=>{this.handleDragOver(o)}} @drop=${o=>{this.handleDrop(o)}}>
1127
1127
  <div class="editor-wrap">
1128
1128
  <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="给 pi 发送消息" aria-disabled=${this.disabled?"true":"false"}></div>
1129
- <input class="attachment-input" type="file" accept="image/png,image/jpeg,image/gif,image/webp" multiple hidden @change=${r=>{this.handleFileInput(r)}} />
1130
- <button class="editor-attach icon-button" ?disabled=${s} title="附加图片" aria-label="附加图片" @click=${()=>{this.attachmentInput?.click()}}>${Ov()}</button>
1129
+ <input class="attachment-input" type="file" accept="image/png,image/jpeg,image/gif,image/webp" multiple hidden @change=${o=>{this.handleFileInput(o)}} />
1130
+ <button class="editor-attach icon-button" ?disabled=${s} title="附加图片" aria-label="附加图片" @click=${()=>{this.attachmentInput?.click()}}>${Kv()}</button>
1131
1131
  ${t?c`<div class="mode-hint">Shell 命令${e.excludeFromContext?" · 已排除上下文":""}</div>`:null}
1132
1132
  ${this.isCompacting&&!t?c`<div class="mode-hint">正在压缩历史 · 消息将排队发送</div>`:null}
1133
1133
  ${this.renderAttachments()}
1134
- <autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${r=>{this.pick(r)}}></autocomplete-menu>
1134
+ <autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${o=>{this.pick(o)}}></autocomplete-menu>
1135
1135
  </div>
1136
1136
  <div class="actions">
1137
1137
  ${this.renderCompactStatus()}
1138
- <button class="icon-button send-button" ?disabled=${s} title=${i?"当前活动结束后排队发送":"发送"} aria-label=${i?"排队发送":"发送"} @click=${()=>{this.send("followUp")}}>${i?Lv():za()}</button>
1139
- ${this.canSteer&&!this.isCompacting?c`<button class="icon-button steer-button" ?disabled=${s} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send("steer")}}>${jv()}</button>`:null}
1140
- <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} aria-label="停止" @click=${()=>this.onStop?.()}>${Fv()}</button>
1138
+ <button class="icon-button send-button" ?disabled=${s} title=${i?"当前活动结束后排队发送":"发送"} aria-label=${i?"排队发送":"发送"} @click=${()=>{this.send("followUp")}}>${i?Vv():Ha()}</button>
1139
+ ${this.canSteer&&!this.isCompacting?c`<button class="icon-button steer-button" ?disabled=${s} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send("steer")}}>${Gv()}</button>`:null}
1140
+ <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} aria-label="停止" @click=${()=>this.onStop?.()}>${Jv()}</button>
1141
1141
  </div>
1142
1142
  </footer>
1143
1143
  `}focusInput(){this.editor?.focus()}renderCompactStatus(){const e=this.status;if(e===void 0)return null;const t=e.model?.id??"无模型",i=e.model?.provider!==void 0&&e.model.provider!==""?`${e.model.provider}/`:"";return c`
1144
1144
  <div class="compact-status" aria-label="会话状态">
1145
1145
  <button class="select-model" title="选择模型" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
1146
- <button class="select-thinking icon-button" title=${`思考级别:${Fs(e.thinkingLevel)}`} aria-label=${`思考级别:${Fs(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${Nv(Bv(e.thinkingLevel,this.availableThinkingLevels))}</button>
1146
+ <button class="select-thinking icon-button" title=${`思考级别:${zs(e.thinkingLevel)}`} aria-label=${`思考级别:${zs(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${Qv(Xv(e.thinkingLevel,this.availableThinkingLevels))}</button>
1147
1147
  </div>
1148
1148
  `}renderAttachments(){return this.attachments.length===0&&this.attachmentError===void 0?null:c`
1149
1149
  <div class="attachments" aria-label="待发送附件">
@@ -1163,15 +1163,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1163
1163
  `:null}
1164
1164
  ${this.attachmentError!==void 0?c`<div class="attachment-error">${this.attachmentError}</div>`:null}
1165
1165
  </div>
1166
- `}changeDelivery(e){e.target instanceof HTMLSelectElement&&(this.attachmentDelivery=e.target.value==="folder"?"folder":"inline",_v(this.attachmentDelivery))}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=Zo(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&Array.from(e.dataTransfer.items).some(t=>t.kind==="file"&&t.type.startsWith("image/"))&&e.preventDefault()}async handleDrop(e){const t=Zo(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 Ev(e,Qv);t.length>0&&(this.attachments=[...this.attachments,...t.map(s=>({id:`attachment-${String(++this.attachmentSeq)}`,...s}))]),i!==void 0&&(this.attachmentError=i)}currentAttachments(){return this.attachments.map(e=>({kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}))}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new ot({parent:this.editorHost,state:Ki.create({doc:this.draft,extensions:[Ga(),rc(),Ja(),Qa.of(" "),Za(sc,{fallback:!0}),ot.lineWrapping,ot.contentAttributes.of(e=>Yv(e.state.sliceDoc(0,e.state.selection.main.head))),Xa("给 pi 发送消息... 使用 / 输入命令,@ 输入已跟踪文件,@ 空格显示所有文件"),this.editableCompartment.of(ot.editable.of(!this.disabled)),this.readOnlyCompartment.of(Ki.readOnly.of(this.disabled)),ot.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Ya.of([{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Enter",run:()=>this.handleEditorEnter()},{key:"Shift-Enter",run:e=>oc(e)||ic(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>Ir.shift?.(e)??!1},{key:"Backspace",run:e=>nc(e)},...ec,...tc])]})}))}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:Cr.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(ot.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(Ki.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Yt(this.machineId,this.sessionId);t!==void 0&&bi(t,this.draft),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""&&this.cwd!==void 0&&this.cwd!==""){const i=await z.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(Gv);if(t!==this.requestVersion)return;this.completions=i.filter(s=>s.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(s=>({kind:"command",replaceFrom:e.from,replaceTo:e.to,insertText:`/${s.name}`,detail:s.source,...s.description===void 0?{}:{description:s.description}}))}else if(e.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const i=await z.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId}).catch(Jv);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const r=Bn(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 zn(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorEnter(){if(this.completions.length){const e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):Ir.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:Cr.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.attachmentDelivery;this.resetComposer(),this.onSend?.(t,s,r,r===void 0?void 0:o)}resetComposer(){this.draft="";const e=Yt(this.machineId,this.sessionId);e!==void 0&&tr(e),this.completions=[],this.attachments=[],this.attachmentError=void 0}};O.styles=fg;j([d({type:Boolean})],O.prototype,"disabled",2);j([d()],O.prototype,"sessionId",2);j([d()],O.prototype,"cwd",2);j([d()],O.prototype,"machineId",2);j([d({type:Boolean})],O.prototype,"canSteer",2);j([d({type:Boolean})],O.prototype,"isCompacting",2);j([d({type:Boolean})],O.prototype,"canStop",2);j([d({attribute:!1})],O.prototype,"status",2);j([d({type:Boolean})],O.prototype,"sending",2);j([d({attribute:!1})],O.prototype,"onSend",2);j([d({attribute:!1})],O.prototype,"onStop",2);j([d({attribute:!1})],O.prototype,"onSelectModel",2);j([d({attribute:!1})],O.prototype,"onSelectThinking",2);j([d({attribute:!1})],O.prototype,"availableThinkingLevels",2);j([B(".markdown-editor")],O.prototype,"editorHost",2);j([B(".attachment-input")],O.prototype,"attachmentInput",2);j([y()],O.prototype,"draft",2);j([y()],O.prototype,"completions",2);j([y()],O.prototype,"selectedIndex",2);j([y()],O.prototype,"attachments",2);j([y()],O.prototype,"attachmentDelivery",2);j([y()],O.prototype,"attachmentError",2);O=j([E("prompt-editor")],O);function Yt(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return Wn(e,t)}function Gv(){return[]}function Jv(){return[]}function Zo(e){return e===null?[]:Array.from(e.files).filter(t=>t.type.startsWith("image/"))}function Qv(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 Zv={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},Xv={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function Yv(e){return ir(e).kind==="normal"?Zv:Xv}function ei(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:"0"}function eb(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var tb=Object.defineProperty,ib=Object.getOwnPropertyDescriptor,Ba=(e,t,i,s)=>{for(var r=s>1?void 0:s?ib(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&&tb(t,i,r),r};let Mi=class extends M{render(){const e=this.status;if(e===void 0)return c`<div class="bar muted">暂无会话状态</div>`;const t=e.contextUsage,i=t?t.percent==null?`上下文 ${ei(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${ei(t.contextWindow)}`:"上下文未知",s=e.tokens;return c`
1166
+ `}changeDelivery(e){e.target instanceof HTMLSelectElement&&(this.attachmentDelivery=e.target.value==="folder"?"folder":"inline",qv(this.attachmentDelivery))}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=Yr(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&Array.from(e.dataTransfer.items).some(t=>t.kind==="file"&&t.type.startsWith("image/"))&&e.preventDefault()}async handleDrop(e){const t=Yr(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 Bv(e,nb);t.length>0&&(this.attachments=[...this.attachments,...t.map(s=>({id:`attachment-${String(++this.attachmentSeq)}`,...s}))]),i!==void 0&&(this.attachmentError=i)}currentAttachments(){return this.attachments.map(e=>({kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}))}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new rt({parent:this.editorHost,state:Vi.create({doc:this.draft,extensions:[Za(),ac(),Xa(),Ya.of(" "),ec(nc,{fallback:!0}),rt.lineWrapping,rt.contentAttributes.of(e=>lb(e.state.sliceDoc(0,e.state.selection.main.head))),tc("给 pi 发送消息... 使用 / 输入命令,@ 输入已跟踪文件,@ 空格显示所有文件"),this.editableCompartment.of(rt.editable.of(!this.disabled)),this.readOnlyCompartment.of(Vi.readOnly.of(this.disabled)),rt.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),ic.of([{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Enter",run:()=>this.handleEditorEnter()},{key:"Shift-Enter",run:e=>cc(e)||rc(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>Mo.shift?.(e)??!1},{key:"Backspace",run:e=>lc(e)},...sc,...oc])]})}))}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:To.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(rt.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(Vi.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=ei(this.machineId,this.sessionId);t!==void 0&&wi(t,this.draft),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""&&this.cwd!==void 0&&this.cwd!==""){const i=await N.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(ob);if(t!==this.requestVersion)return;this.completions=i.filter(s=>s.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(s=>({kind:"command",replaceFrom:e.from,replaceTo:e.to,insertText:`/${s.name}`,detail:s.source,...s.description===void 0?{}:{description:s.description}}))}else if(e.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const i=await N.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId}).catch(rb);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const o=qn(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:o,detail:s.kind,...s.path.endsWith("/")&&o.endsWith('"')?{cursorOffset:o.length-1}:{}}})}}currentTrigger(){return Hn(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorEnter(){if(this.completions.length){const e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):Mo.run?.(e)??!1}pick(e){const t=this.editor;if(!t)return;const i=e.kind==="file"&&(e.insertText.endsWith("/")||e.cursorOffset!==void 0)?"":" ",s=e.replaceFrom+(e.cursorOffset??e.insertText.length)+i.length,o=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:o,insert:`${e.insertText}${i}`},selection:To.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;const t=this.draft.trim(),i=this.attachments;if(t===""&&i.length===0)return;const s=this.canSteer||this.isCompacting?e:void 0,o=i.length>0?this.currentAttachments():void 0,r=this.attachmentDelivery;this.resetComposer(),this.onSend?.(t,s,o,o===void 0?void 0:r)}resetComposer(){this.draft="";const e=ei(this.machineId,this.sessionId);e!==void 0&&io(e),this.completions=[],this.attachments=[],this.attachmentError=void 0}};L.styles=$g;j([d({type:Boolean})],L.prototype,"disabled",2);j([d()],L.prototype,"sessionId",2);j([d()],L.prototype,"cwd",2);j([d()],L.prototype,"machineId",2);j([d({type:Boolean})],L.prototype,"canSteer",2);j([d({type:Boolean})],L.prototype,"isCompacting",2);j([d({type:Boolean})],L.prototype,"canStop",2);j([d({attribute:!1})],L.prototype,"status",2);j([d({type:Boolean})],L.prototype,"sending",2);j([d({attribute:!1})],L.prototype,"onSend",2);j([d({attribute:!1})],L.prototype,"onStop",2);j([d({attribute:!1})],L.prototype,"onSelectModel",2);j([d({attribute:!1})],L.prototype,"onSelectThinking",2);j([d({attribute:!1})],L.prototype,"availableThinkingLevels",2);j([B(".markdown-editor")],L.prototype,"editorHost",2);j([B(".attachment-input")],L.prototype,"attachmentInput",2);j([S()],L.prototype,"draft",2);j([S()],L.prototype,"completions",2);j([S()],L.prototype,"selectedIndex",2);j([S()],L.prototype,"attachments",2);j([S()],L.prototype,"attachmentDelivery",2);j([S()],L.prototype,"attachmentError",2);L=j([D("prompt-editor")],L);function ei(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return Ln(e,t)}function ob(){return[]}function rb(){return[]}function Yr(e){return e===null?[]:Array.from(e.files).filter(t=>t.type.startsWith("image/"))}function nb(e){return new Promise((t,i)=>{const s=new FileReader;s.onerror=()=>{i(s.error??new Error("读取文件失败"))},s.onload=()=>{const o=s.result;if(typeof o!="string"){i(new Error("文件读取结果异常"));return}const r=o.indexOf(",");t(r===-1?o:o.slice(r+1))},s.readAsDataURL(e)})}const ab={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},cb={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function lb(e){return so(e).kind==="normal"?ab:cb}function ti(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:"0"}function db(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var pb=Object.defineProperty,hb=Object.getOwnPropertyDescriptor,qa=(e,t,i,s)=>{for(var o=s>1?void 0:s?hb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&pb(t,i,o),o};let Ti=class extends M{render(){const e=this.status;if(e===void 0)return c`<div class="bar muted">暂无会话状态</div>`;const t=e.contextUsage,i=t?t.percent==null?`上下文 ${ti(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${ti(t.contextWindow)}`:"上下文未知",s=e.tokens;return c`
1167
1167
  <div class="bar">
1168
- <span>↑${ei(s.input)}</span>
1169
- <span>↓${ei(s.output)}</span>
1168
+ <span>↑${ti(s.input)}</span>
1169
+ <span>↓${ti(s.output)}</span>
1170
1170
  <span class="context">${i}</span>
1171
- <span>${eb(e.cost)}</span>
1171
+ <span>${db(e.cost)}</span>
1172
1172
  ${e.pendingMessageCount>0?c`<span>${String(e.pendingMessageCount)} 条排队</span>`:null}
1173
1173
  </div>
1174
- `}};Mi.styles=pg;Ba([d({attribute:!1})],Mi.prototype,"status",2);Mi=Ba([E("status-bar")],Mi);var sb=Object.defineProperty,rb=Object.getOwnPropertyDescriptor,Fe=(e,t,i,s)=>{for(var r=s>1?void 0:s?rb(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 Re=class extends M{constructor(){super(...arguments),this.title="选择",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return c`
1174
+ `}};Ti.styles=Sg;qa([d({attribute:!1})],Ti.prototype,"status",2);Ti=qa([D("status-bar")],Ti);var ub=Object.defineProperty,fb=Object.getOwnPropertyDescriptor,Fe=(e,t,i,s)=>{for(var o=s>1?void 0:s?fb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&ub(t,i,o),o};let Re=class extends M{constructor(){super(...arguments),this.title="选择",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return c`
1175
1175
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1176
1176
  <section @mousedown=${t=>{t.stopPropagation()}}>
1177
1177
  <header>
@@ -1181,7 +1181,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1181
1181
  ${this.searchable?c`<input placeholder="搜索" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
1182
1182
  <div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
1183
1183
  ${e.map((t,i)=>c`
1184
- <button class=${i===this.selectedIndex?"selected":""} ${$r(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1184
+ <button class=${i===this.selectedIndex?"selected":""} ${Ro(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1185
1185
  <span>${t.label}</span>
1186
1186
  ${t.description!==void 0&&t.description!==""?c`<small>${t.description}</small>`:null}
1187
1187
  </button>
@@ -1190,7 +1190,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1190
1190
  </div>
1191
1191
  </section>
1192
1192
  </div>
1193
- `}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const e=this.filteredOptions().findIndex(t=>t.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){const e=this.query.trim().toLowerCase();return e===""?this.options:this.options.filter(t=>`${t.label} ${t.description??""} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredOptions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i&&this.onPick?.(i.value)}}};Re.styles=ya;Fe([d()],Re.prototype,"title",2);Fe([d({type:Boolean})],Re.prototype,"searchable",2);Fe([d({attribute:!1})],Re.prototype,"options",2);Fe([d({attribute:!1})],Re.prototype,"selectedValue",2);Fe([d({attribute:!1})],Re.prototype,"onPick",2);Fe([d({attribute:!1})],Re.prototype,"onCancel",2);Fe([y()],Re.prototype,"selectedIndex",2);Fe([y()],Re.prototype,"query",2);Re=Fe([E("command-picker")],Re);var ob=Object.defineProperty,nb=Object.getOwnPropertyDescriptor,it=(e,t,i,s)=>{for(var r=s>1?void 0:s?nb(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&&ob(t,i,r),r};let Le=class extends M{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return c`
1193
+ `}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const e=this.filteredOptions().findIndex(t=>t.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){const e=this.query.trim().toLowerCase();return e===""?this.options:this.options.filter(t=>`${t.label} ${t.description??""} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredOptions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i&&this.onPick?.(i.value)}}};Re.styles=ka;Fe([d()],Re.prototype,"title",2);Fe([d({type:Boolean})],Re.prototype,"searchable",2);Fe([d({attribute:!1})],Re.prototype,"options",2);Fe([d({attribute:!1})],Re.prototype,"selectedValue",2);Fe([d({attribute:!1})],Re.prototype,"onPick",2);Fe([d({attribute:!1})],Re.prototype,"onCancel",2);Fe([S()],Re.prototype,"selectedIndex",2);Fe([S()],Re.prototype,"query",2);Re=Fe([D("command-picker")],Re);var gb=Object.defineProperty,mb=Object.getOwnPropertyDescriptor,it=(e,t,i,s)=>{for(var o=s>1?void 0:s?mb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&gb(t,i,o),o};let Oe=class extends M{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return c`
1194
1194
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1195
1195
  <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1196
1196
  <header>
@@ -1203,19 +1203,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1203
1203
  </header>
1204
1204
  <div class="options">
1205
1205
  ${e.length===0?c`<div class="empty">未找到操作。</div>`:e.map((t,i)=>c`
1206
- <button class=${i===this.selectedIndex?"selected":""} ${$r(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1206
+ <button class=${i===this.selectedIndex?"selected":""} ${Ro(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1207
1207
  <span class="main">
1208
1208
  <strong>${t.title}</strong>
1209
1209
  ${t.description!==void 0&&t.description!==""?c`<small>${t.description}</small>`:null}
1210
1210
  </span>
1211
- ${t.shortcut!==void 0?c`<kbd>${ai(t.shortcut)}</kbd>`:null}
1211
+ ${t.shortcut!==void 0?c`<kbd>${ci(t.shortcut)}</kbd>`:null}
1212
1212
  ${t.group!==void 0&&t.group!==""?c`<small class="group">${t.group}</small>`:null}
1213
1213
  </button>
1214
1214
  `)}
1215
1215
  </div>
1216
1216
  </section>
1217
1217
  </div>
1218
- `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){const e=this.queryText.trim().toLowerCase();return this.actions.filter(t=>t.enabled!==!1).filter(t=>e===""?!0:[t.title,t.description??"",t.group??"",t.shortcut??""].join(" ").toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){this.onRun?.(e)}};Le.styles=ug;it([d({attribute:!1})],Le.prototype,"actions",2);it([d({attribute:!1})],Le.prototype,"onRun",2);it([d({attribute:!1})],Le.prototype,"onCancel",2);it([B("input")],Le.prototype,"input",2);it([y()],Le.prototype,"queryText",2);it([y()],Le.prototype,"selectedIndex",2);Le=it([E("action-palette")],Le);var ab=Object.defineProperty,cb=Object.getOwnPropertyDescriptor,we=(e,t,i,s)=>{for(var r=s>1?void 0:s?cb(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&&ab(t,i,r),r};let re=class extends M{render(){const e=this.state;return e===void 0?null:c`
1218
+ `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){const e=this.queryText.trim().toLowerCase();return this.actions.filter(t=>t.enabled!==!1).filter(t=>e===""?!0:[t.title,t.description??"",t.group??"",t.shortcut??""].join(" ").toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){this.onRun?.(e)}};Oe.styles=kg;it([d({attribute:!1})],Oe.prototype,"actions",2);it([d({attribute:!1})],Oe.prototype,"onRun",2);it([d({attribute:!1})],Oe.prototype,"onCancel",2);it([B("input")],Oe.prototype,"input",2);it([S()],Oe.prototype,"queryText",2);it([S()],Oe.prototype,"selectedIndex",2);Oe=it([D("action-palette")],Oe);var vb=Object.defineProperty,bb=Object.getOwnPropertyDescriptor,we=(e,t,i,s)=>{for(var o=s>1?void 0:s?bb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&vb(t,i,o),o};let oe=class extends M{render(){const e=this.state;return e===void 0?null:c`
1219
1219
  <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
1220
1220
  <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1221
1221
  <header>
@@ -1238,11 +1238,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1238
1238
  <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>
1239
1239
  </div>
1240
1240
  `;case"oauth":return this.renderOAuth(e);case"logout":return c`<div class="options">${e.providers.length===0?c`<div class="empty">没有已保存的凭据。环境变量和 models.json 设置不会变化。</div>`:e.providers.map(t=>c`
1241
- <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Xo(t.authType)}</small></button>
1241
+ <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${en(t.authType)}</small></button>
1242
1242
  `)}</div>`}}renderProviderButton(e){return c`
1243
1243
  <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
1244
- <span>${e.name}${e.status.source!==void 0?c` <em>${db(e)}</em>`:null}</span>
1245
- <small>${e.id} · ${Xo(e.authType)}</small>
1244
+ <span>${e.name}${e.status.source!==void 0?c` <em>${yb(e)}</em>`:null}</span>
1245
+ <small>${e.id} · ${en(e.authType)}</small>
1246
1246
  </button>
1247
1247
  `}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return c`
1248
1248
  <div class="form">
@@ -1251,21 +1251,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1251
1251
  <p><a href=${t.auth.url} target="_blank" rel="noreferrer">${t.auth.url}</a></p>
1252
1252
  ${t.auth.instructions!==void 0?c`<p class="warning">${t.auth.instructions}</p>`:null}
1253
1253
  `:c`<p>正在启动登录流程…</p>`}
1254
- ${t.progress.length>0?c`<ul class="progress">${t.progress.map(r=>c`<li>${r}</li>`)}</ul>`:null}
1254
+ ${t.progress.length>0?c`<ul class="progress">${t.progress.map(o=>c`<li>${o}</li>`)}</ul>`:null}
1255
1255
  ${i!==void 0?c`
1256
1256
  <label>${i.message}</label>
1257
- <input .value=${e.inputValue??""} placeholder=${i.placeholder??""} @input=${r=>{r.target instanceof HTMLInputElement&&this.onOAuthInput?.(r.target.value)}}>
1257
+ <input .value=${e.inputValue??""} placeholder=${i.placeholder??""} @input=${o=>{o.target instanceof HTMLInputElement&&this.onOAuthInput?.(o.target.value)}}>
1258
1258
  <div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button><button class="primary" ?disabled=${e.responding===!0} @click=${()=>{this.onOAuthRespond?.()}}>提交</button></div>
1259
1259
  `:null}
1260
1260
  ${s!==void 0?c`
1261
1261
  <p>${s.message}</p>
1262
- <div class="inline-options">${s.options.map(r=>c`<button @click=${()=>{this.onOAuthRespond?.(r.value)}}>${r.label}</button>`)}</div>
1262
+ <div class="inline-options">${s.options.map(o=>c`<button @click=${()=>{this.onOAuthRespond?.(o.value)}}>${o.label}</button>`)}</div>
1263
1263
  `:null}
1264
1264
  ${e.error!==void 0&&e.error!==""?c`<div class="error-text">${e.error}</div>`:null}
1265
- ${t.status==="error"||t.status==="cancelled"?c`<div class="error-text">${t.error??pb(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
1265
+ ${t.status==="error"||t.status==="cancelled"?c`<div class="error-text">${t.error??Sb(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
1266
1266
  ${i===void 0&&s===void 0&&t.status==="running"?c`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button></div>`:null}
1267
1267
  </div>
1268
- `}focusInputIfNeeded(){const e=lb(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?.()}};re.styles=[ya,_`
1268
+ `}focusInputIfNeeded(){const e=wb(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?.()}};oe.styles=[ka,_`
1269
1269
  .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
1270
1270
  .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
1271
1271
  .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
@@ -1280,7 +1280,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1280
1280
  .progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
1281
1281
  .inline-options { display: grid; gap: 8px; }
1282
1282
  em { color: var(--pi-success); font-style: normal; font-size: 12px; }
1283
- `];we([d({attribute:!1})],re.prototype,"state",2);we([d({attribute:!1})],re.prototype,"onChooseMethod",2);we([d({attribute:!1})],re.prototype,"onSelectProvider",2);we([d({attribute:!1})],re.prototype,"onApiKeyInput",2);we([d({attribute:!1})],re.prototype,"onSaveApiKey",2);we([d({attribute:!1})],re.prototype,"onLogoutProvider",2);we([d({attribute:!1})],re.prototype,"onOAuthInput",2);we([d({attribute:!1})],re.prototype,"onOAuthRespond",2);we([d({attribute:!1})],re.prototype,"onOAuthCancel",2);we([d({attribute:!1})],re.prototype,"onCancel",2);we([B("input")],re.prototype,"input",2);re=we([E("auth-dialog")],re);function Xo(e){return e==="oauth"?"订阅":"API key"}function lb(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 db(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 pb(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var hb=Object.defineProperty,ub=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var r=s>1?void 0:s?ub(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&&hb(t,i,r),r};let me=class extends M{constructor(){super(...arguments),this.machineId="local",this.path="",this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}firstUpdated(){this.pathInput?.focus()}async loadSuggestions(){const e=++this.requestId;this.loading=!0;try{const t=await z.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==""&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="Enter")e.preventDefault(),this.submit();else if(e.key==="ArrowDown")e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key==="ArrowUp")e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key==="Tab"){const t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return c`
1283
+ `];we([d({attribute:!1})],oe.prototype,"state",2);we([d({attribute:!1})],oe.prototype,"onChooseMethod",2);we([d({attribute:!1})],oe.prototype,"onSelectProvider",2);we([d({attribute:!1})],oe.prototype,"onApiKeyInput",2);we([d({attribute:!1})],oe.prototype,"onSaveApiKey",2);we([d({attribute:!1})],oe.prototype,"onLogoutProvider",2);we([d({attribute:!1})],oe.prototype,"onOAuthInput",2);we([d({attribute:!1})],oe.prototype,"onOAuthRespond",2);we([d({attribute:!1})],oe.prototype,"onOAuthCancel",2);we([d({attribute:!1})],oe.prototype,"onCancel",2);we([B("input")],oe.prototype,"input",2);oe=we([D("auth-dialog")],oe);function en(e){return e==="oauth"?"订阅":"API key"}function wb(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 yb(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 Sb(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var xb=Object.defineProperty,kb=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var o=s>1?void 0:s?kb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&xb(t,i,o),o};let me=class extends M{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 c`
1284
1284
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1285
1285
  <section @click=${e=>{e.stopPropagation()}}>
1286
1286
  <header>
@@ -1330,7 +1330,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1330
1330
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1331
1331
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1332
1332
  button:disabled { opacity: .5; cursor: not-allowed; }
1333
- `;De([d({attribute:!1})],me.prototype,"onSubmit",2);De([d({attribute:!1})],me.prototype,"onCancel",2);De([d()],me.prototype,"machineId",2);De([y()],me.prototype,"path",2);De([y()],me.prototype,"createMissing",2);De([y()],me.prototype,"suggestions",2);De([y()],me.prototype,"selected",2);De([y()],me.prototype,"loading",2);De([B("input")],me.prototype,"pathInput",2);me=De([E("project-dialog")],me);var fb=Object.defineProperty,gb=Object.getOwnPropertyDescriptor,We=(e,t,i,s)=>{for(var r=s>1?void 0:s?gb(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&&fb(t,i,r),r};let ve=class extends M{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=mb(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"&&us(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===""||us(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?us(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return c`
1333
+ `;De([d({attribute:!1})],me.prototype,"onSubmit",2);De([d({attribute:!1})],me.prototype,"onCancel",2);De([d()],me.prototype,"machineId",2);De([S()],me.prototype,"path",2);De([S()],me.prototype,"createMissing",2);De([S()],me.prototype,"suggestions",2);De([S()],me.prototype,"selected",2);De([S()],me.prototype,"loading",2);De([B("input")],me.prototype,"pathInput",2);me=De([D("project-dialog")],me);var $b=Object.defineProperty,Pb=Object.getOwnPropertyDescriptor,We=(e,t,i,s)=>{for(var o=s>1?void 0:s?Pb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&$b(t,i,o),o};let ve=class extends M{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=Rb(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 c`
1334
1334
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1335
1335
  <section @click=${s=>{s.stopPropagation()}}>
1336
1336
  <form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
@@ -1385,8 +1385,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1385
1385
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1386
1386
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1387
1387
  button:disabled { opacity: .5; cursor: not-allowed; }
1388
- `;We([d({attribute:!1})],ve.prototype,"onSubmit",2);We([d({attribute:!1})],ve.prototype,"onCancel",2);We([d()],ve.prototype,"error",2);We([y()],ve.prototype,"url",2);We([y()],ve.prototype,"name",2);We([y()],ve.prototype,"token",2);We([y()],ve.prototype,"submitting",2);We([B("input[name='baseUrl']")],ve.prototype,"urlInput",2);We([B("input[name='name']")],ve.prototype,"nameInput",2);ve=We([E("machine-dialog")],ve);function mb(e){const t=e.trim();if(t==="")return"";const i=Yo(t)??Yo(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):vb(t)}function us(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 Yo(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function vb(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 bb(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function wb(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(`
1389
- `):""}}function yb(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins},...t.spawnSessions===void 0?{}:{spawnSessions:t.spawnSessions}},s=e.host.trim(),r=e.port.trim();if(s!==""&&(i.host=s),r!==""){const o=Number(r);if(!Number.isInteger(o)||o<1||o>65535)throw new Error("端口必须是 1 到 65535 之间的整数。");i.port=o}return i.allowedHosts=e.allowedHostsMode==="all"?!0:Sb(e.allowedHostsText),i}function Sb(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}var xb=Object.defineProperty,kb=Object.getOwnPropertyDescriptor,_e=(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&&xb(t,i,r),r};let be=class extends M{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=bb(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=wb(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return c`
1388
+ `;We([d({attribute:!1})],ve.prototype,"onSubmit",2);We([d({attribute:!1})],ve.prototype,"onCancel",2);We([d()],ve.prototype,"error",2);We([S()],ve.prototype,"url",2);We([S()],ve.prototype,"name",2);We([S()],ve.prototype,"token",2);We([S()],ve.prototype,"submitting",2);We([B("input[name='baseUrl']")],ve.prototype,"urlInput",2);We([B("input[name='name']")],ve.prototype,"nameInput",2);ve=We([D("machine-dialog")],ve);function Rb(e){const t=e.trim();if(t==="")return"";const i=tn(t)??tn(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):Ib(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 tn(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function Ib(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 Cb(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function Mb(e){return{host:e.host??"",port:e.port===void 0?"":String(e.port),allowedHostsMode:e.allowedHosts===!0?"all":"list",allowedHostsText:Array.isArray(e.allowedHosts)?e.allowedHosts.join(`
1389
+ `):""}}function Tb(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins},...t.spawnSessions===void 0?{}:{spawnSessions:t.spawnSessions},...t.subsessions===void 0?{}:{subsessions:t.subsessions}},s=e.host.trim(),o=e.port.trim();if(s!==""&&(i.host=s),o!==""){const r=Number(o);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("端口必须是 1 到 65535 之间的整数。");i.port=r}return i.allowedHosts=e.allowedHostsMode==="all"?!0:Ab(e.allowedHostsText),i}function Ab(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}var Eb=Object.defineProperty,Db=Object.getOwnPropertyDescriptor,_e=(e,t,i,s)=>{for(var o=s>1?void 0:s?Db(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Eb(t,i,o),o};let be=class extends M{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=Cb(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=Mb(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return c`
1390
1390
  <div class="section-heading">
1391
1391
  <div>
1392
1392
  <h2>通用配置</h2>
@@ -1407,7 +1407,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1407
1407
  <span>Host</span>
1408
1408
  ${this.renderOverrideBadge("host")}
1409
1409
  </span>
1410
- <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:en(t)})}}>
1410
+ <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:sn(t)})}}>
1411
1411
  <small>Web 服务器应绑定的地址。留空则使用 PI WEB 默认值。</small>
1412
1412
  </label>
1413
1413
 
@@ -1416,7 +1416,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1416
1416
  <span>Port</span>
1417
1417
  ${this.renderOverrideBadge("port")}
1418
1418
  </span>
1419
- <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:en(t)})}}>
1419
+ <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:sn(t)})}}>
1420
1420
  <small>TCP 端口,范围 1 到 65535。留空则使用 PI WEB 默认值。</small>
1421
1421
  </label>
1422
1422
 
@@ -1425,11 +1425,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1425
1425
  <span>允许的 hosts</span>
1426
1426
  ${this.renderOverrideBadge("allowedHosts")}
1427
1427
  </span>
1428
- <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:Pb(t)==="all"?"all":"list"})}}>
1428
+ <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:_b(t)==="all"?"all":"list"})}}>
1429
1429
  <option value="list">仅允许列出的 hosts</option>
1430
1430
  <option value="all">允许所有 host</option>
1431
1431
  </select>
1432
- <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:Rb(t)})}}></textarea>
1432
+ <textarea .value=${this.draft.allowedHostsText} ?disabled=${this.draft.allowedHostsMode==="all"} rows="4" placeholder="example.local&#10;192.168.1.20" spellcheck="false" @input=${t=>{this.updateDraft({allowedHostsText:Lb(t)})}}></textarea>
1433
1433
  <small>每行输入一个 host,或选择“允许所有 host”写入 <code>true</code>。</small>
1434
1434
  </div>
1435
1435
 
@@ -1446,10 +1446,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1446
1446
  <dl>
1447
1447
  <div><dt>Host</dt><dd>${e.host??c`<span class="muted">默认 127.0.0.1</span>`}</dd></div>
1448
1448
  <div><dt>端口</dt><dd>${e.port??c`<span class="muted">默认 8504</span>`}</dd></div>
1449
- <div><dt>允许的 hosts</dt><dd>${$b(e.allowedHosts)}</dd></div>
1449
+ <div><dt>允许的 hosts</dt><dd>${Wb(e.allowedHosts)}</dd></div>
1450
1450
  </dl>
1451
1451
  </section>
1452
- `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(yb(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=Ib(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};be.styles=_`
1452
+ `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(Tb(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=Ob(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};be.styles=_`
1453
1453
  :host { display: block; }
1454
1454
  .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1455
1455
  .section-heading > div { display: grid; gap: 6px; min-width: 0; }
@@ -1491,7 +1491,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1491
1491
  .section-heading .secondary { justify-self: start; }
1492
1492
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1493
1493
  }
1494
- `;_e([d({attribute:!1})],be.prototype,"configResponse",2);_e([d({type:Boolean})],be.prototype,"loading",2);_e([d({type:Boolean})],be.prototype,"saving",2);_e([d()],be.prototype,"error",2);_e([d()],be.prototype,"savedMessage",2);_e([d({attribute:!1})],be.prototype,"onReload",2);_e([d({attribute:!1})],be.prototype,"onSave",2);_e([y()],be.prototype,"draft",2);_e([y()],be.prototype,"localError",2);be=_e([E("settings-general-panel")],be);function $b(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?c`<span class="muted">未列出</span>`:e.join(", "):c`<span class="muted">未设置</span>`}function en(e){return e.target instanceof HTMLInputElement?e.target.value:""}function Pb(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function Rb(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function Ib(e){return e instanceof Error?e.message:String(e)}var Cb=Object.defineProperty,Mb=Object.getOwnPropertyDescriptor,He=(e,t,i,s)=>{for(var r=s>1?void 0:s?Mb(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&&Cb(t,i,r),r};let Ee=class extends M{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;return c`
1494
+ `;_e([d({attribute:!1})],be.prototype,"configResponse",2);_e([d({type:Boolean})],be.prototype,"loading",2);_e([d({type:Boolean})],be.prototype,"saving",2);_e([d()],be.prototype,"error",2);_e([d()],be.prototype,"savedMessage",2);_e([d({attribute:!1})],be.prototype,"onReload",2);_e([d({attribute:!1})],be.prototype,"onSave",2);_e([S()],be.prototype,"draft",2);_e([S()],be.prototype,"localError",2);be=_e([D("settings-general-panel")],be);function Wb(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?c`<span class="muted">未列出</span>`:e.join(", "):c`<span class="muted">未设置</span>`}function sn(e){return e.target instanceof HTMLInputElement?e.target.value:""}function _b(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function Lb(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function Ob(e){return e instanceof Error?e.message:String(e)}var jb=Object.defineProperty,Fb=Object.getOwnPropertyDescriptor,He=(e,t,i,s)=>{for(var o=s>1?void 0:s?Fb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&jb(t,i,o),o};let Ee=class extends M{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,i=e?.effectiveConfig.spawnSessions!==!1,s=e?.envOverrides.subsessions===!0,o=e?.effectiveConfig.subsessions===!0&&i;return c`
1495
1495
  <div class="section-heading">
1496
1496
  <div>
1497
1497
  <h2>会话守护进程</h2>
@@ -1516,20 +1516,38 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1516
1516
  type="checkbox"
1517
1517
  .checked=${i}
1518
1518
  ?disabled=${this.loading||this.saving||t}
1519
- @change=${s=>{this.toggleSpawnSessions(s)}}
1519
+ @change=${r=>{this.toggleSpawnSessions(r)}}
1520
1520
  >
1521
1521
  <span>启用 <code>spawn_session</code> 工具</span>
1522
1522
  </label>
1523
1523
  <small>启用后,LLM 可以启动新会话,但会被限制在同一个已注册项目的工作区(包括任意 worktree)内,因此每个派生会话都会显示在这里。默认启用。</small>
1524
1524
  </div>
1525
- <section class="effective-card" aria-label="生效配置摘要">
1526
- <h3>应用环境变量覆盖后的生效配置</h3>
1525
+ <div class="field">
1526
+ <span class="field-heading">
1527
+ <span>允许代理启动受跟踪的子会话</span>
1528
+ <span class="beta-badge">beta</span>
1529
+ ${s?c`<span class="override-badge">环境变量覆盖</span>`:null}
1530
+ </span>
1531
+ <label class="toggle">
1532
+ <input
1533
+ type="checkbox"
1534
+ .checked=${o}
1535
+ ?disabled=${this.loading||this.saving||s||!i}
1536
+ @change=${r=>{this.toggleSubsessions(r)}}
1537
+ >
1538
+ <span>启用 <code>spawn_subsession</code> 工具</span>
1539
+ </label>
1540
+ <small>Beta:代理可以启动自己持续关联的子会话(<code>spawn_subsession</code>、<code>list_subsessions</code>、<code>check_subsession</code>、<code>read_subsession</code>),并在子会话完成时收到通知。需要先启用“允许代理启动会话”。默认关闭。</small>
1541
+ </div>
1542
+ <section class="effective-card" aria-label="最终生效配置摘要">
1543
+ <h3>环境变量覆盖后的生效配置</h3>
1527
1544
  <dl>
1528
1545
  <div><dt>派生会话</dt><dd>${i?"已启用":c`<span class="muted">已禁用</span>`}</dd></div>
1546
+ <div><dt>子会话</dt><dd>${o?"已启用":c`<span class="muted">已禁用</span>`}</dd></div>
1529
1547
  </dl>
1530
1548
  </section>
1531
1549
  `}
1532
- `}renderMessages(){return this.error!==""?c`<div class="message error-message">${this.error}</div>`:this.savedMessage!==""?c`<div class="message success-message">${this.savedMessage}</div>`:null}async toggleSpawnSessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,spawnSessions:t})}};Ee.styles=_`
1550
+ `}renderMessages(){return this.error!==""?c`<div class="message error-message">${this.error}</div>`:this.savedMessage!==""?c`<div class="message success-message">${this.savedMessage}</div>`:null}async toggleSpawnSessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,spawnSessions:t})}async toggleSubsessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,subsessions:t})}};Ee.styles=_`
1533
1551
  :host { display: block; }
1534
1552
  .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1535
1553
  .section-heading > div { display: grid; gap: 6px; min-width: 0; }
@@ -1557,6 +1575,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1557
1575
  .toggle input { width: 16px; height: 16px; }
1558
1576
  .toggle input:disabled { cursor: not-allowed; }
1559
1577
  .override-badge { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); background: var(--pi-warning-surface); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: none; }
1578
+ .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; }
1560
1579
  .effective-card { display: grid; gap: 10px; }
1561
1580
  .effective-card dl { display: grid; gap: 8px; margin: 0; }
1562
1581
  .effective-card dl > div { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 12px; align-items: baseline; }
@@ -1568,7 +1587,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1568
1587
  .section-heading .secondary { justify-self: start; }
1569
1588
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1570
1589
  }
1571
- `;He([d({attribute:!1})],Ee.prototype,"configResponse",2);He([d({type:Boolean})],Ee.prototype,"loading",2);He([d({type:Boolean})],Ee.prototype,"saving",2);He([d()],Ee.prototype,"error",2);He([d()],Ee.prototype,"savedMessage",2);He([d({attribute:!1})],Ee.prototype,"onReload",2);He([d({attribute:!1})],Ee.prototype,"onSave",2);Ee=He([E("settings-sessiond-panel")],Ee);var Tb=Object.defineProperty,Ab=Object.getOwnPropertyDescriptor,Ne=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ab(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&&Tb(t,i,r),r};let Ie=class extends M{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return c`
1590
+ `;He([d({attribute:!1})],Ee.prototype,"configResponse",2);He([d({type:Boolean})],Ee.prototype,"loading",2);He([d({type:Boolean})],Ee.prototype,"saving",2);He([d()],Ee.prototype,"error",2);He([d()],Ee.prototype,"savedMessage",2);He([d({attribute:!1})],Ee.prototype,"onReload",2);He([d({attribute:!1})],Ee.prototype,"onSave",2);Ee=He([D("settings-sessiond-panel")],Ee);var zb=Object.defineProperty,Nb=Object.getOwnPropertyDescriptor,ze=(e,t,i,s)=>{for(var o=s>1?void 0:s?Nb(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&zb(t,i,o),o};let Ie=class extends M{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return c`
1572
1591
  <div class="section-heading">
1573
1592
  <div>
1574
1593
  <h2>插件</h2>
@@ -1628,7 +1647,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1628
1647
  .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
1629
1648
  .toggle { justify-self: start; }
1630
1649
  }
1631
- `;Ne([d({attribute:!1})],Ie.prototype,"pluginsResponse",2);Ne([d({attribute:!1})],Ie.prototype,"configResponse",2);Ne([d({type:Boolean})],Ie.prototype,"loading",2);Ne([d({type:Boolean})],Ie.prototype,"saving",2);Ne([d()],Ie.prototype,"error",2);Ne([d()],Ie.prototype,"savedMessage",2);Ne([d({attribute:!1})],Ie.prototype,"onReload",2);Ne([d({attribute:!1})],Ie.prototype,"onTogglePlugin",2);Ie=Ne([E("settings-plugins-panel")],Ie);var Eb=Object.defineProperty,Db=Object.getOwnPropertyDescriptor,ye=(e,t,i,s)=>{for(var r=s>1?void 0:s?Db(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&&Eb(t,i,r),r};const tn={capture:!0};let oe=class extends M{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{const t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key==="Escape"){this.stopRecording();return}const i=Qn(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&&!Ot(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=Lb(this.actions),t=this.shortcutResolutions();return c`
1650
+ `;ze([d({attribute:!1})],Ie.prototype,"pluginsResponse",2);ze([d({attribute:!1})],Ie.prototype,"configResponse",2);ze([d({type:Boolean})],Ie.prototype,"loading",2);ze([d({type:Boolean})],Ie.prototype,"saving",2);ze([d()],Ie.prototype,"error",2);ze([d()],Ie.prototype,"savedMessage",2);ze([d({attribute:!1})],Ie.prototype,"onReload",2);ze([d({attribute:!1})],Ie.prototype,"onTogglePlugin",2);Ie=ze([D("settings-plugins-panel")],Ie);var Bb=Object.defineProperty,Ub=Object.getOwnPropertyDescriptor,ye=(e,t,i,s)=>{for(var o=s>1?void 0:s?Ub(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Bb(t,i,o),o};const on={capture:!0};let re=class extends M{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{const t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key==="Escape"){this.stopRecording();return}const i=Yn(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&&!Ot(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=Vb(this.actions),t=this.shortcutResolutions();return c`
1632
1651
  <div class="section-heading">
1633
1652
  <div>
1634
1653
  <h2>键盘快捷键</h2>
@@ -1652,44 +1671,44 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1652
1671
  </section>
1653
1672
  `)}
1654
1673
  `}
1655
- `}renderMessages(){const e=this.localError||this.error;return e!==""?c`<div class="message error-message">${e}</div>`:this.savedMessage!==""?c`<div class="message success-message">${this.savedMessage}</div>`:null}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=Ti(e.id,i),r=zb(e,i),o=this.shortcutInputText(e),n=o.trim()===""?void 0:ts(o),a=n?.ok===!0?n.shortcut:Nb(e,i),l=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&o.trim()!==""?"custom":r,h=this.recordingHint(e.id),g=Ob(t);return c`
1656
- <article class=${Wb(t)}>
1674
+ `}renderMessages(){const e=this.localError||this.error;return e!==""?c`<div class="message error-message">${e}</div>`:this.savedMessage!==""?c`<div class="message success-message">${this.savedMessage}</div>`:null}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=Ai(e.id,i),o=Zb(e,i),r=this.shortcutInputText(e),n=r.trim()===""?void 0:is(r),a=n?.ok===!0?n.shortcut:Qb(e,i),l=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&r.trim()!==""?"custom":o,h=this.recordingHint(e.id),g=Kb(t);return c`
1675
+ <article class=${Hb(t)}>
1657
1676
  <div class="shortcut-main">
1658
1677
  <strong>${e.title}</strong>
1659
1678
  ${e.description!==void 0&&e.description!==""?c`<small>${e.description}</small>`:null}
1660
1679
  <small class="shortcut-id">${e.id}</small>
1661
- <small>${e.shortcut!==void 0&&e.shortcut!==""?c`Default: <kbd>${ai(e.shortcut)}</kbd>`:"No default shortcut"}</small>
1680
+ <small>${e.shortcut!==void 0&&e.shortcut!==""?c`Default: <kbd>${ci(e.shortcut)}</kbd>`:"No default shortcut"}</small>
1662
1681
  </div>
1663
1682
  <div class="shortcut-editor">
1664
1683
  <div class="shortcut-status">
1665
- ${a!==void 0&&a!==""?c`<kbd>${ai(a)}</kbd>`:c`<span class="unassigned">${r==="disabled"?"已禁用":"未分配"}</span>`}
1666
- <small class=${u}>${Bb(u)}${p?" · 未保存":""}</small>
1667
- ${g===void 0?null:c`<small class=${_b(t)}>${g}</small>`}
1684
+ ${a!==void 0&&a!==""?c`<kbd>${ci(a)}</kbd>`:c`<span class="unassigned">${o==="disabled"?"已禁用":"未分配"}</span>`}
1685
+ <small class=${u}>${Xb(u)}${p?" · 未保存":""}</small>
1686
+ ${g===void 0?null:c`<small class=${qb(t)}>${g}</small>`}
1668
1687
  </div>
1669
1688
  <label class="shortcut-input-label">
1670
1689
  <span>快捷键</span>
1671
1690
  <input
1672
1691
  class="shortcut-input"
1673
1692
  data-action-id=${e.id}
1674
- .value=${o}
1693
+ .value=${r}
1675
1694
  placeholder=${e.shortcut??"mod+k"}
1676
1695
  autocomplete="off"
1677
1696
  autocapitalize="off"
1678
1697
  spellcheck="false"
1679
1698
  ?disabled=${this.saving}
1680
- @input=${w=>{this.updateDraft(e.id,Ub(w))}}
1699
+ @input=${w=>{this.updateDraft(e.id,Yb(w))}}
1681
1700
  >
1682
1701
  </label>
1683
1702
  ${h!==""?c`<small class="recording-hint">${h}</small>`:null}
1684
1703
  <div class="shortcut-actions">
1685
- <button class="primary" ?disabled=${this.loading||this.saving||!p||o.trim()===""} @click=${()=>{this.saveShortcut(e)}}>保存</button>
1704
+ <button class="primary" ?disabled=${this.loading||this.saving||!p||r.trim()===""} @click=${()=>{this.saveShortcut(e)}}>保存</button>
1686
1705
  <button ?disabled=${this.loading||this.saving} @click=${()=>{this.toggleRecording(e.id)}}>${this.recording?.actionId===e.id?"取消录制":"录制"}</button>
1687
1706
  <button ?disabled=${this.loading||this.saving||s===null} @click=${()=>{this.setShortcutNone(e.id)}}>无</button>
1688
1707
  <button ?disabled=${this.loading||this.saving||!l} @click=${()=>{this.resetShortcut(e.id)}}>重置</button>
1689
1708
  </div>
1690
1709
  </div>
1691
1710
  </article>
1692
- `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=Ti(e.id,this.configResponse?.config.shortcuts);return i===null?"":i??e.shortcut??""}recordingHint(e){const t=this.recording;return t?.actionId!==e?"":t.tokens.length===0?"Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.":`Recording: ${ai(t.tokens.join(" "))}. Press another key to add a sequence, or wait to finish.`}updateDraft(e,t){this.drafts={[e]:t},this.localError=""}async saveShortcut(e){this.stopRecording();const t=this.shortcutInputText(e).trim(),i=ts(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?Fb(s,e):{...s,[e]:t};Object.keys(r).length===0?delete i.shortcuts:i.shortcuts=r,await this.onSave?.(i)}shortcutResolutions(){return new Map(or(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=ts(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()},Gn)}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,tn),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,tn),this.recordingListenerActive=!1)}};oe.styles=_`
1711
+ `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=Ai(e.id,this.configResponse?.config.shortcuts);return i===null?"":i??e.shortcut??""}recordingHint(e){const t=this.recording;return t?.actionId!==e?"":t.tokens.length===0?"Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.":`Recording: ${ci(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=is(t);if(!i.ok){this.localError=i.message;return}this.localError="",await this.saveShortcutPreference(e.id,i.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){const i={...this.configResponse?.config??{}},s=i.shortcuts??{},o=t===void 0?Jb(s,e):{...s,[e]:t};Object.keys(o).length===0?delete i.shortcuts:i.shortcuts=o,await this.onSave?.(i)}shortcutResolutions(){return new Map(no(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){const e={...this.configResponse?.config.shortcuts??{}};for(const[t,i]of Object.entries(this.drafts)){const s=i.trim();if(s==="")continue;const o=is(s);o.ok&&(e[t]=o.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError="",this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(const t of this.renderRoot.querySelectorAll(".shortcut-input"))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},Zn)}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,on),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,on),this.recordingListenerActive=!1)}};re.styles=_`
1693
1712
  :host { display: block; }
1694
1713
  .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1695
1714
  .section-heading > div { display: grid; gap: 6px; min-width: 0; }
@@ -1744,7 +1763,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1744
1763
  .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
1745
1764
  .shortcut-status, .shortcut-actions { justify-content: flex-start; }
1746
1765
  }
1747
- `;ye([d({attribute:!1})],oe.prototype,"actions",2);ye([d({attribute:!1})],oe.prototype,"configResponse",2);ye([d({type:Boolean})],oe.prototype,"loading",2);ye([d({type:Boolean})],oe.prototype,"saving",2);ye([d()],oe.prototype,"error",2);ye([d()],oe.prototype,"savedMessage",2);ye([d({attribute:!1})],oe.prototype,"onReload",2);ye([d({attribute:!1})],oe.prototype,"onSave",2);ye([y()],oe.prototype,"drafts",2);ye([y()],oe.prototype,"localError",2);ye([y()],oe.prototype,"recording",2);oe=ye([E("settings-shortcuts-panel")],oe);function Wb(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function _b(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function Ob(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 Lb(e){const t=new Map;for(const i of[...e].sort(jb)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function jb(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function Ti(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Fb(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Nb(e,t){const i=Ti(e.id,t);if(i!==null)return i??e.shortcut}function zb(e,t){const i=Ti(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function Bb(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}function Ub(e){return e.target instanceof HTMLInputElement?e.target.value:""}var Hb=Object.defineProperty,qb=Object.getOwnPropertyDescriptor,Se=(e,t,i,s)=>{for(var r=s>1?void 0:s?qb(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&&Hb(t,i,r),r};let ne=class extends M{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 c`
1766
+ `;ye([d({attribute:!1})],re.prototype,"actions",2);ye([d({attribute:!1})],re.prototype,"configResponse",2);ye([d({type:Boolean})],re.prototype,"loading",2);ye([d({type:Boolean})],re.prototype,"saving",2);ye([d()],re.prototype,"error",2);ye([d()],re.prototype,"savedMessage",2);ye([d({attribute:!1})],re.prototype,"onReload",2);ye([d({attribute:!1})],re.prototype,"onSave",2);ye([S()],re.prototype,"drafts",2);ye([S()],re.prototype,"localError",2);ye([S()],re.prototype,"recording",2);re=ye([D("settings-shortcuts-panel")],re);function Hb(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function qb(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function Kb(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??"another action"}`;const t=e.shadows.length;if(t===0)return;const i=e.shadows.slice(0,2).map(o=>o.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function Vb(e){const t=new Map;for(const i of[...e].sort(Gb)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function Gb(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function Ai(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Jb(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Qb(e,t){const i=Ai(e.id,t);if(i!==null)return i??e.shortcut}function Zb(e,t){const i=Ai(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function Xb(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}function Yb(e){return e.target instanceof HTMLInputElement?e.target.value:""}var ew=Object.defineProperty,tw=Object.getOwnPropertyDescriptor,Se=(e,t,i,s)=>{for(var o=s>1?void 0:s?tw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&ew(t,i,o),o};let ne=class extends M{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 c`
1748
1767
  <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
1749
1768
  <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB 设置" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
1750
1769
  <header class="settings-header">
@@ -1814,7 +1833,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1814
1833
  <strong>${t}</strong>
1815
1834
  <small>${i}</small>
1816
1835
  </button>
1817
- `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([fi.config(),ks.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`加载设置失败:${fs(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 fi.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.config),this.showSavedMessage()}catch(t){this.error=`保存配置失败:${fs(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await ks.plugins()}catch(e){this.error=`刷新插件失败:${fs(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?.())}};ne.styles=_`
1836
+ `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([gi.config(),$s.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`加载设置失败:${gs(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},o=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...o,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await gi.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.config),this.showSavedMessage()}catch(t){this.error=`保存配置失败:${gs(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await $s.plugins()}catch(e){this.error=`刷新插件失败:${gs(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?.())}};ne.styles=_`
1818
1837
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1819
1838
  .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; }
1820
1839
  .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; }
@@ -1841,15 +1860,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1841
1860
  .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
1842
1861
  .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
1843
1862
  }
1844
- `;Se([d({attribute:!1})],ne.prototype,"section",2);Se([d({attribute:!1})],ne.prototype,"actions",2);Se([d({attribute:!1})],ne.prototype,"onNavigate",2);Se([d({attribute:!1})],ne.prototype,"onClose",2);Se([d({attribute:!1})],ne.prototype,"onConfigSaved",2);Se([y()],ne.prototype,"configResponse",2);Se([y()],ne.prototype,"pluginsResponse",2);Se([y()],ne.prototype,"loading",2);Se([y()],ne.prototype,"saving",2);Se([y()],ne.prototype,"error",2);Se([y()],ne.prototype,"savedMessage",2);ne=Se([E("settings-dialog")],ne);function fs(e){return e instanceof Error?e.message:String(e)}var Kb=Object.defineProperty,Vb=Object.getOwnPropertyDescriptor,Ce=(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&&Kb(t,i,r),r};let de=class extends M{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 c`
1863
+ `;Se([d({attribute:!1})],ne.prototype,"section",2);Se([d({attribute:!1})],ne.prototype,"actions",2);Se([d({attribute:!1})],ne.prototype,"onNavigate",2);Se([d({attribute:!1})],ne.prototype,"onClose",2);Se([d({attribute:!1})],ne.prototype,"onConfigSaved",2);Se([S()],ne.prototype,"configResponse",2);Se([S()],ne.prototype,"pluginsResponse",2);Se([S()],ne.prototype,"loading",2);Se([S()],ne.prototype,"saving",2);Se([S()],ne.prototype,"error",2);Se([S()],ne.prototype,"savedMessage",2);ne=Se([D("settings-dialog")],ne);function gs(e){return e instanceof Error?e.message:String(e)}var iw=Object.defineProperty,sw=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var o=s>1?void 0:s?sw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&iw(t,i,o),o};let de=class extends M{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(o=>o.id===this.tool)??i[0];return c`
1845
1864
  ${this.hideToolTabs?null:c`
1846
1865
  <header>
1847
1866
  <div class=${this.workspaceHeaderFrameClass()}>
1848
1867
  <div class="workspace-header-strip" @scroll=${this.onWorkspaceHeaderScroll}>
1849
1868
  <div class="tabs">
1850
- ${i.map(r=>{const o=s?.id===r.id,n=r.badge?.(t),a=this.panelTabAriaLabel(r,n);return c`
1851
- <button class=${this.panelTabClass(r,o)} title=${a} aria-label=${a} aria-pressed=${String(o)} @click=${()=>{this.onSelectTool(r.id)}}>
1852
- ${this.renderPanelTabContent(r,n)}
1869
+ ${i.map(o=>{const r=s?.id===o.id,n=o.badge?.(t),a=this.panelTabAriaLabel(o,n);return c`
1870
+ <button class=${this.panelTabClass(o,r)} title=${a} aria-label=${a} aria-pressed=${String(r)} @click=${()=>{this.onSelectTool(o.id)}}>
1871
+ ${this.renderPanelTabContent(o,n)}
1853
1872
  </button>
1854
1873
  `})}
1855
1874
  </div>
@@ -1871,34 +1890,34 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1871
1890
  <h2>${e.title}</h2>
1872
1891
  ${e.body===void 0?null:c`<p>${e.body}</p>`}
1873
1892
  </section>
1874
- `}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}};de.styles=cg;Ce([d({attribute:!1})],de.prototype,"workspace",2);Ce([d({attribute:!1})],de.prototype,"panelContext",2);Ce([d({attribute:!1})],de.prototype,"emptyState",2);Ce([d()],de.prototype,"tool",2);Ce([d({attribute:!1})],de.prototype,"panels",2);Ce([d({type:Boolean})],de.prototype,"hideToolTabs",2);Ce([d({attribute:!1})],de.prototype,"onSelectTool",2);Ce([B(".workspace-header-strip")],de.prototype,"workspaceHeaderStrip",2);Ce([y()],de.prototype,"workspaceHeaderCanScrollLeft",2);Ce([y()],de.prototype,"workspaceHeaderCanScrollRight",2);de=Ce([E("workspace-panel")],de);var Gb=Object.defineProperty,Jb=Object.getOwnPropertyDescriptor,xe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Jb(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&&Gb(t,i,r),r};let ae=class extends M{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=Qb(this.machines),t=Zb(this.machine),i=Yb(this.project),s=tw(this.workspace),r=sw(this.session);return c`
1893
+ `}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}};de.styles=bg;Ce([d({attribute:!1})],de.prototype,"workspace",2);Ce([d({attribute:!1})],de.prototype,"panelContext",2);Ce([d({attribute:!1})],de.prototype,"emptyState",2);Ce([d()],de.prototype,"tool",2);Ce([d({attribute:!1})],de.prototype,"panels",2);Ce([d({type:Boolean})],de.prototype,"hideToolTabs",2);Ce([d({attribute:!1})],de.prototype,"onSelectTool",2);Ce([B(".workspace-header-strip")],de.prototype,"workspaceHeaderStrip",2);Ce([S()],de.prototype,"workspaceHeaderCanScrollLeft",2);Ce([S()],de.prototype,"workspaceHeaderCanScrollRight",2);de=Ce([D("workspace-panel")],de);var ow=Object.defineProperty,rw=Object.getOwnPropertyDescriptor,xe=(e,t,i,s)=>{for(var o=s>1?void 0:s?rw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&ow(t,i,o),o};let ae=class extends M{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=nw(this.machines),t=aw(this.machine),i=lw(this.project),s=pw(this.workspace),o=uw(this.session);return c`
1875
1894
  <nav class=${this.contextBarClass()} aria-label="当前位置">
1876
1895
  <span class="context-bar-label">位置</span>
1877
1896
  <ol class="context-items" @scroll=${this.onContextScroll}>
1878
1897
  ${e?c`
1879
1898
  <li class="context-item">
1880
- <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${Xb(this.machine)} aria-label=${`机器:${t}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
1899
+ <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${cw(this.machine)} aria-label=${`机器:${t}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
1881
1900
  <span class="context-kind">机器</span>
1882
1901
  <span class="context-value">${t}</span>
1883
1902
  </button>
1884
1903
  </li>
1885
1904
  `:null}
1886
1905
  <li class="context-item">
1887
- <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${ew(this.project)} aria-label=${`项目:${i}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
1906
+ <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${dw(this.project)} aria-label=${`项目:${i}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
1888
1907
  <span class="context-kind">项目</span>
1889
1908
  <span class="context-value">${i}</span>
1890
1909
  </button>
1891
1910
  </li>
1892
1911
  <li class="context-item">
1893
- <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${iw(this.workspace)} aria-label=${`工作区:${s}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
1912
+ <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${hw(this.workspace)} aria-label=${`工作区:${s}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
1894
1913
  <span class="context-kind">工作区</span>
1895
1914
  <span class="context-value">${s}</span>
1896
1915
  </button>
1897
1916
  </li>
1898
1917
  <li class="context-item">
1899
- <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${rw(this.session)} aria-label=${`会话:${r}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
1918
+ <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${fw(this.session)} aria-label=${`会话:${o}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
1900
1919
  <span class="context-kind">会话</span>
1901
- <span class="context-value">${r}</span>
1920
+ <span class="context-value">${o}</span>
1902
1921
  </button>
1903
1922
  </li>
1904
1923
  </ol>
@@ -1936,7 +1955,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1936
1955
  .context-kind { display: none; }
1937
1956
  .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
1938
1957
  button { cursor: pointer; }
1939
- `;xe([d({attribute:!1})],ae.prototype,"machines",2);xe([d({attribute:!1})],ae.prototype,"machine",2);xe([d({attribute:!1})],ae.prototype,"project",2);xe([d({attribute:!1})],ae.prototype,"workspace",2);xe([d({attribute:!1})],ae.prototype,"session",2);xe([d({attribute:!1})],ae.prototype,"refreshControl",2);xe([d({attribute:!1})],ae.prototype,"onOpenSection",2);xe([d({attribute:!1})],ae.prototype,"onShowActions",2);xe([B(".context-items")],ae.prototype,"contextItems",2);xe([y()],ae.prototype,"canScrollLeft",2);xe([y()],ae.prototype,"canScrollRight",2);ae=xe([E("app-context-bar")],ae);function Qb(e){return e.length>1}function Zb(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function Xb(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function Yb(e){return e?.name??"未选择项目"}function ew(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function tw(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function iw(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function sw(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 rw(e){return e===void 0?"未选择会话":e.path}var ow=Object.defineProperty,nw=Object.getOwnPropertyDescriptor,st=(e,t,i,s)=>{for(var r=s>1?void 0:s?nw(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&&ow(t,i,r),r};let je=class extends M{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 c`
1958
+ `;xe([d({attribute:!1})],ae.prototype,"machines",2);xe([d({attribute:!1})],ae.prototype,"machine",2);xe([d({attribute:!1})],ae.prototype,"project",2);xe([d({attribute:!1})],ae.prototype,"workspace",2);xe([d({attribute:!1})],ae.prototype,"session",2);xe([d({attribute:!1})],ae.prototype,"refreshControl",2);xe([d({attribute:!1})],ae.prototype,"onOpenSection",2);xe([d({attribute:!1})],ae.prototype,"onShowActions",2);xe([B(".context-items")],ae.prototype,"contextItems",2);xe([S()],ae.prototype,"canScrollLeft",2);xe([S()],ae.prototype,"canScrollRight",2);ae=xe([D("app-context-bar")],ae);function nw(e){return e.length>1}function aw(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function cw(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function lw(e){return e?.name??"未选择项目"}function dw(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function pw(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function hw(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function uw(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 fw(e){return e===void 0?"未选择会话":e.path}var gw=Object.defineProperty,mw=Object.getOwnPropertyDescriptor,st=(e,t,i,s)=>{for(var o=s>1?void 0:s?mw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&gw(t,i,o),o};let je=class extends M{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 c`
1940
1959
  <div class=${this.frameClass()}>
1941
1960
  <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
1942
1961
  ${this.tabs.map(t=>{const i=this.selectedView===t.id;return c`
@@ -1948,7 +1967,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1948
1967
  `})}
1949
1968
  </div>
1950
1969
  </div>
1951
- `}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?c`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:yu(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}};je.styles=_`
1970
+ `}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?c`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:Iu(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const o=this.initialsLabel(s.label);t.set(o,(t.get(o)??0)+1)}const i=new Map;for(const s of e){const o=this.initialsLabel(s.label);i.set(s.id,(t.get(o)??0)>1?this.fullFallbackLabel(s.label):o)}return i}initialsLabel(e){const i=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(s=>Array.from(s)[0]??"").join("").toLocaleUpperCase();return i===""?"?":i}fullFallbackLabel(e){const t=e.trim();return t===""?"?":t}observeMobileTabs(){const e=this.mobileTabsElement();this.observedMobileTabs!==e&&(this.mobileTabsResizeObserver?.disconnect(),this.observedMobileTabs=e,this.mobileTabsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.mobileTabsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.mobileTabsResizeObserver.observe(e)))}updateScrollState(){const e=this.mobileTabsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}mobileTabsElement(){const e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}};je.styles=_`
1952
1971
  :host { flex: 0 0 auto; min-width: 0; }
1953
1972
  .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); }
1954
1973
  .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; }
@@ -1974,12 +1993,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1974
1993
  .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; }
1975
1994
  .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
1976
1995
  }
1977
- `;st([d({attribute:!1})],je.prototype,"tabs",2);st([d({attribute:!1})],je.prototype,"selectedView",2);st([d({attribute:!1})],je.prototype,"onSelect",2);st([B(".mobile-tabs")],je.prototype,"mobileTabs",2);st([y()],je.prototype,"canScrollLeft",2);st([y()],je.prototype,"canScrollRight",2);je=st([E("app-mobile-main-tabs")],je);var aw=Object.defineProperty,cw=Object.getOwnPropertyDescriptor,he=(e,t,i,s)=>{for(var r=s>1?void 0:s?cw(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};let te=class extends M{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=gs(e,this.statuses),i=e.name;return c`
1996
+ `;st([d({attribute:!1})],je.prototype,"tabs",2);st([d({attribute:!1})],je.prototype,"selectedView",2);st([d({attribute:!1})],je.prototype,"onSelect",2);st([B(".mobile-tabs")],je.prototype,"mobileTabs",2);st([S()],je.prototype,"canScrollLeft",2);st([S()],je.prototype,"canScrollRight",2);je=st([D("app-mobile-main-tabs")],je);var vw=Object.defineProperty,bw=Object.getOwnPropertyDescriptor,he=(e,t,i,s)=>{for(var o=s>1?void 0:s?bw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&vw(t,i,o),o};let te=class extends M{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=ms(e,this.statuses),i=e.name;return c`
1978
1997
  <div class="machine-switcher">
1979
1998
  <button
1980
1999
  type="button"
1981
2000
  class="machine-switcher-button"
1982
- title=${rn(e)}
2001
+ title=${nn(e)}
1983
2002
  aria-label=${`Machine: ${i}. Switch machine.`}
1984
2003
  aria-expanded=${String(this.open)}
1985
2004
  @click=${s=>{this.toggleMenu(s.currentTarget)}}
@@ -1990,7 +2009,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1990
2009
  <span class="machine-switcher-kicker">Machine</span>
1991
2010
  <span class="machine-switcher-label">${i}</span>
1992
2011
  </span>
1993
- <span class=${`machine-status ${t}`}>${sn(t)}</span>
2012
+ <span class=${`machine-status ${t}`}>${rn(t)}</span>
1994
2013
  <span class="machine-chevron" aria-hidden="true">▾</span>
1995
2014
  </button>
1996
2015
  ${this.open?c`
@@ -1999,18 +2018,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1999
2018
  </div>
2000
2019
  `:null}
2001
2020
  </div>
2002
- `}renderMachineOption(e){const t=this.selected?.id===e.id,i=gs(e,this.statuses),s=Sa(e)&&this.onRemove!==void 0,r=this.openActionsMachineId===e.id;return c`
2021
+ `}renderMachineOption(e){const t=this.selected?.id===e.id,i=ms(e,this.statuses),s=$a(e)&&this.onRemove!==void 0,o=this.openActionsMachineId===e.id;return c`
2003
2022
  <div class=${`machine-option ${t?"selected":""} ${s?"":"no-actions"}`}>
2004
2023
  <button
2005
2024
  type="button"
2006
2025
  class="machine-option-main"
2007
- title=${rn(e)}
2026
+ title=${nn(e)}
2008
2027
  data-machine-id=${e.id}
2009
2028
  @click=${()=>{this.select(e)}}
2010
- @keydown=${o=>{this.handleMachineOptionKeydown(o)}}
2029
+ @keydown=${r=>{this.handleMachineOptionKeydown(r)}}
2011
2030
  >
2012
2031
  <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
2013
- <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${sn(i)}</small>
2032
+ <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${rn(i)}</small>
2014
2033
  </button>
2015
2034
  ${s?c`
2016
2035
  <div class="machine-option-actions">
@@ -2019,18 +2038,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2019
2038
  class="machine-option-actions-toggle"
2020
2039
  title="Machine actions"
2021
2040
  aria-label=${`Actions for ${e.name}`}
2022
- aria-expanded=${String(r)}
2023
- @click=${o=>{o.stopPropagation(),this.toggleActionsMenu(e.id,o.currentTarget)}}
2041
+ aria-expanded=${String(o)}
2042
+ @click=${r=>{r.stopPropagation(),this.toggleActionsMenu(e.id,r.currentTarget)}}
2024
2043
  >⋯</button>
2025
- ${r?c`
2026
- <div class="machine-option-actions-panel" style=${this.actionMenuStyle} @click=${o=>{o.stopPropagation()}}>
2044
+ ${o?c`
2045
+ <div class="machine-option-actions-panel" style=${this.actionMenuStyle} @click=${r=>{r.stopPropagation()}}>
2027
2046
  <button class="danger" title=${`Remove ${e.name}`} @click=${()=>{this.removeMachine(e)}}>Remove</button>
2028
2047
  </div>
2029
2048
  `:null}
2030
2049
  </div>
2031
2050
  `:null}
2032
2051
  </div>
2033
- `}renderActivity(e){const t=gs(e,this.statuses);if(t==="offline"||t==="error")return;const i=ha(this.activities[e.id]);return ga(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=on(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=on(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=Ht(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)}};te.styles=_`
2052
+ `}renderActivity(e){const t=ms(e,this.statuses);if(t==="offline"||t==="error")return;const i=ga(this.activities[e.id]);return ba(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=an(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=an(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){const e=this.renderRoot.querySelector(".machine-option.selected .machine-option-main"),t=this.machineOptionButtons()[0],i=e??t;return i===void 0?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}focusRelativeMachineOption(e,t,i){i.preventDefault(),i.stopPropagation();const s=this.machineOptionButtons();if(s.length===0||!(e instanceof HTMLElement))return;const o=s.indexOf(e);o<0||this.focusMachineOptionAt(o+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){const t=this.machineOptionButtons(),i=t[Math.min(Math.max(e,0),t.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(".machine-option-main"))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=qt(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)}};te.styles=_`
2034
2053
  :host { min-width: 0; display: block; }
2035
2054
  .machine-switcher { min-width: 0; }
2036
2055
  .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; }
@@ -2063,10 +2082,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2063
2082
  .machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
2064
2083
  .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); }
2065
2084
  @keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
2066
- `;he([d({attribute:!1})],te.prototype,"machines",2);he([d({attribute:!1})],te.prototype,"selected",2);he([d({attribute:!1})],te.prototype,"statuses",2);he([d({attribute:!1})],te.prototype,"activities",2);he([d({attribute:!1})],te.prototype,"onSelect",2);he([d({attribute:!1})],te.prototype,"onRemove",2);he([d({attribute:!1})],te.prototype,"onFocusNextSection",2);he([d({attribute:!1})],te.prototype,"onCancelKeyboardNavigation",2);he([y()],te.prototype,"open",2);he([y()],te.prototype,"menuStyle",2);he([y()],te.prototype,"openActionsMachineId",2);he([y()],te.prototype,"actionMenuStyle",2);te=he([E("machine-switcher")],te);function gs(e,t){return t[e.id]?.status??e.status??"unknown"}function sn(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function rn(e){return e.baseUrl??e.name}function on(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: ${ti(t.bottom)};`,`left: ${ti(r)};`,`width: ${ti(s)};`,`max-height: ${ti(o)};`].join(" ")}function ti(e){return`${String(Math.round(e))}px`}var lw=Object.defineProperty,dw=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var r=s>1?void 0:s?dw(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&&lw(t,i,r),r};let x=class extends M{constructor(){super(...arguments),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions."}async focusSection(e){switch(await this.updateComplete,e){case"machines":return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case"projects":return await this.focusNavigableSection(this.projectList);case"workspaces":return await this.focusNavigableSection(this.workspaceList);case"sessions":return await this.focusNavigableSection(this.sessionList)}}render(){return c`
2085
+ `;he([d({attribute:!1})],te.prototype,"machines",2);he([d({attribute:!1})],te.prototype,"selected",2);he([d({attribute:!1})],te.prototype,"statuses",2);he([d({attribute:!1})],te.prototype,"activities",2);he([d({attribute:!1})],te.prototype,"onSelect",2);he([d({attribute:!1})],te.prototype,"onRemove",2);he([d({attribute:!1})],te.prototype,"onFocusNextSection",2);he([d({attribute:!1})],te.prototype,"onCancelKeyboardNavigation",2);he([S()],te.prototype,"open",2);he([S()],te.prototype,"menuStyle",2);he([S()],te.prototype,"openActionsMachineId",2);he([S()],te.prototype,"actionMenuStyle",2);te=he([D("machine-switcher")],te);function ms(e,t){return t[e.id]?.status??e.status??"unknown"}function rn(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function nn(e){return e.baseUrl??e.name}function an(e){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const t=e.getBoundingClientRect(),i=8,s=Math.min(280,Math.max(0,window.innerWidth-i*2)),o=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),r=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${ii(t.bottom)};`,`left: ${ii(o)};`,`width: ${ii(s)};`,`max-height: ${ii(r)};`].join(" ")}function ii(e){return`${String(Math.round(e))}px`}var ww=Object.defineProperty,yw=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var o=s>1?void 0:s?yw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&ww(t,i,o),o};let x=class extends M{constructor(){super(...arguments),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions."}async focusSection(e){switch(await this.updateComplete,e){case"machines":return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case"projects":return await this.focusNavigableSection(this.projectList);case"workspaces":return await this.focusNavigableSection(this.workspaceList);case"sessions":return await this.focusNavigableSection(this.sessionList)}}render(){return c`
2067
2086
  <header>
2068
2087
  <strong>PI WEB</strong>
2069
- ${Ai(this.machines)?c`
2088
+ ${Ei(this.machines)?c`
2070
2089
  <machine-switcher
2071
2090
  .machines=${this.machines}
2072
2091
  .selected=${this.selectedMachine}
@@ -2083,7 +2102,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2083
2102
  <button title="显示操作" aria-label="显示操作" @click=${()=>{this.onShowActions?.()}}>操作</button>
2084
2103
  </div>
2085
2104
  </header>
2086
- ${this.compact&&Ai(this.machines)?c`
2105
+ ${this.compact&&Ei(this.machines)?c`
2087
2106
  <machine-list
2088
2107
  .machines=${this.machines}
2089
2108
  .selected=${this.selectedMachine}
@@ -2156,7 +2175,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2156
2175
  .onFocusNextSection=${()=>{this.focusNextFrom("sessions")}}
2157
2176
  .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2158
2177
  ></session-list>
2159
- `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=pw(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(hw(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};x.styles=_`
2178
+ `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=Sw(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(xw(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};x.styles=_`
2160
2179
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
2161
2180
  :host([compact]) { flex: 1 1 auto; }
2162
2181
  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); }
@@ -2179,7 +2198,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2179
2198
  :host([compact]) workspace-list[collapsed],
2180
2199
  :host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
2181
2200
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2182
- `;k([d({attribute:!1})],x.prototype,"machines",2);k([d({attribute:!1})],x.prototype,"selectedMachine",2);k([d({attribute:!1})],x.prototype,"machineStatuses",2);k([d({attribute:!1})],x.prototype,"machineActivities",2);k([d({attribute:!1})],x.prototype,"projects",2);k([d({attribute:!1})],x.prototype,"selectedProject",2);k([d({attribute:!1})],x.prototype,"workspaces",2);k([d({attribute:!1})],x.prototype,"selectedWorkspace",2);k([d({attribute:!1})],x.prototype,"sessions",2);k([d({attribute:!1})],x.prototype,"selectedSession",2);k([d({attribute:!1})],x.prototype,"workspaceActivities",2);k([d({attribute:!1})],x.prototype,"sessionActivities",2);k([d({attribute:!1})],x.prototype,"sessionStatuses",2);k([d({attribute:!1})],x.prototype,"sendingPrompts",2);k([d({attribute:!1})],x.prototype,"workspacesByProjectId",2);k([d({attribute:!1})],x.prototype,"deletingWorkspaceIds",2);k([d({attribute:!1})],x.prototype,"workspaceLabelItems",2);k([d({attribute:!1})],x.prototype,"refreshControl",2);k([d({type:Boolean,reflect:!0})],x.prototype,"collapsible",2);k([d({type:Boolean,reflect:!0})],x.prototype,"compact",2);k([d({type:Boolean})],x.prototype,"machinesCollapsed",2);k([d({type:Boolean})],x.prototype,"projectsCollapsed",2);k([d({type:Boolean})],x.prototype,"workspacesCollapsed",2);k([d({type:Boolean})],x.prototype,"sessionsCollapsed",2);k([d({type:Boolean})],x.prototype,"canStartSession",2);k([d({type:Boolean})],x.prototype,"canDeleteArchivedSessions",2);k([d({type:Boolean})],x.prototype,"canReloadSessions",2);k([d({type:String})],x.prototype,"archivedDeleteUnavailableMessage",2);k([d({attribute:!1})],x.prototype,"onShowActions",2);k([d({attribute:!1})],x.prototype,"onToggleMachines",2);k([d({attribute:!1})],x.prototype,"onToggleProjects",2);k([d({attribute:!1})],x.prototype,"onToggleWorkspaces",2);k([d({attribute:!1})],x.prototype,"onToggleSessions",2);k([d({attribute:!1})],x.prototype,"onSelectProject",2);k([d({attribute:!1})],x.prototype,"onCloseProject",2);k([d({attribute:!1})],x.prototype,"onSelectWorkspace",2);k([d({attribute:!1})],x.prototype,"onDeleteWorkspace",2);k([d({attribute:!1})],x.prototype,"onStartSession",2);k([d({attribute:!1})],x.prototype,"onSelectSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSessionWithDescendants",2);k([d({attribute:!1})],x.prototype,"onArchiveSessions",2);k([d({attribute:!1})],x.prototype,"onRestoreSession",2);k([d({attribute:!1})],x.prototype,"onDeleteCachedNewSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSessions",2);k([d({attribute:!1})],x.prototype,"onDetachParentSession",2);k([d({attribute:!1})],x.prototype,"onReloadSession",2);k([d({attribute:!1})],x.prototype,"onArchivedCollapsed",2);k([d({attribute:!1})],x.prototype,"onSelectMachine",2);k([d({attribute:!1})],x.prototype,"onRemoveMachine",2);k([d({attribute:!1})],x.prototype,"onFocusNavigationTarget",2);k([d({attribute:!1})],x.prototype,"onCancelKeyboardNavigation",2);k([B("machine-list")],x.prototype,"machineList",2);k([B("machine-switcher")],x.prototype,"machineSwitcher",2);k([B("project-list")],x.prototype,"projectList",2);k([B("workspace-list")],x.prototype,"workspaceList",2);k([B("session-list")],x.prototype,"sessionList",2);x=k([E("app-navigation-panel")],x);function Ai(e){return e.length>1}function pw(e,t){const i=Ua(t);return i[i.indexOf(e)-1]}function hw(e,t){const i=Ua(t);return i[i.indexOf(e)+1]??"chat"}function Ua(e){return $i.filter(t=>t!=="machines"||Ai(e))}var uw=Object.defineProperty,fw=Object.getOwnPropertyDescriptor,Y=(e,t,i,s)=>{for(var r=s>1?void 0:s?fw(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&&uw(t,i,r),r};const gw=new Set(["ArrowLeft","ArrowRight","Home","End"]),mw=420,vw=4;let K=class extends M{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 c`
2201
+ `;k([d({attribute:!1})],x.prototype,"machines",2);k([d({attribute:!1})],x.prototype,"selectedMachine",2);k([d({attribute:!1})],x.prototype,"machineStatuses",2);k([d({attribute:!1})],x.prototype,"machineActivities",2);k([d({attribute:!1})],x.prototype,"projects",2);k([d({attribute:!1})],x.prototype,"selectedProject",2);k([d({attribute:!1})],x.prototype,"workspaces",2);k([d({attribute:!1})],x.prototype,"selectedWorkspace",2);k([d({attribute:!1})],x.prototype,"sessions",2);k([d({attribute:!1})],x.prototype,"selectedSession",2);k([d({attribute:!1})],x.prototype,"workspaceActivities",2);k([d({attribute:!1})],x.prototype,"sessionActivities",2);k([d({attribute:!1})],x.prototype,"sessionStatuses",2);k([d({attribute:!1})],x.prototype,"sendingPrompts",2);k([d({attribute:!1})],x.prototype,"workspacesByProjectId",2);k([d({attribute:!1})],x.prototype,"deletingWorkspaceIds",2);k([d({attribute:!1})],x.prototype,"workspaceLabelItems",2);k([d({attribute:!1})],x.prototype,"refreshControl",2);k([d({type:Boolean,reflect:!0})],x.prototype,"collapsible",2);k([d({type:Boolean,reflect:!0})],x.prototype,"compact",2);k([d({type:Boolean})],x.prototype,"machinesCollapsed",2);k([d({type:Boolean})],x.prototype,"projectsCollapsed",2);k([d({type:Boolean})],x.prototype,"workspacesCollapsed",2);k([d({type:Boolean})],x.prototype,"sessionsCollapsed",2);k([d({type:Boolean})],x.prototype,"canStartSession",2);k([d({type:Boolean})],x.prototype,"canDeleteArchivedSessions",2);k([d({type:Boolean})],x.prototype,"canReloadSessions",2);k([d({type:String})],x.prototype,"archivedDeleteUnavailableMessage",2);k([d({attribute:!1})],x.prototype,"onShowActions",2);k([d({attribute:!1})],x.prototype,"onToggleMachines",2);k([d({attribute:!1})],x.prototype,"onToggleProjects",2);k([d({attribute:!1})],x.prototype,"onToggleWorkspaces",2);k([d({attribute:!1})],x.prototype,"onToggleSessions",2);k([d({attribute:!1})],x.prototype,"onSelectProject",2);k([d({attribute:!1})],x.prototype,"onCloseProject",2);k([d({attribute:!1})],x.prototype,"onSelectWorkspace",2);k([d({attribute:!1})],x.prototype,"onDeleteWorkspace",2);k([d({attribute:!1})],x.prototype,"onStartSession",2);k([d({attribute:!1})],x.prototype,"onSelectSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSession",2);k([d({attribute:!1})],x.prototype,"onArchiveSessionWithDescendants",2);k([d({attribute:!1})],x.prototype,"onArchiveSessions",2);k([d({attribute:!1})],x.prototype,"onRestoreSession",2);k([d({attribute:!1})],x.prototype,"onDeleteCachedNewSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSession",2);k([d({attribute:!1})],x.prototype,"onDeleteArchivedSessions",2);k([d({attribute:!1})],x.prototype,"onDetachParentSession",2);k([d({attribute:!1})],x.prototype,"onReloadSession",2);k([d({attribute:!1})],x.prototype,"onArchivedCollapsed",2);k([d({attribute:!1})],x.prototype,"onSelectMachine",2);k([d({attribute:!1})],x.prototype,"onRemoveMachine",2);k([d({attribute:!1})],x.prototype,"onFocusNavigationTarget",2);k([d({attribute:!1})],x.prototype,"onCancelKeyboardNavigation",2);k([B("machine-list")],x.prototype,"machineList",2);k([B("machine-switcher")],x.prototype,"machineSwitcher",2);k([B("project-list")],x.prototype,"projectList",2);k([B("workspace-list")],x.prototype,"workspaceList",2);k([B("session-list")],x.prototype,"sessionList",2);x=k([D("app-navigation-panel")],x);function Ei(e){return e.length>1}function Sw(e,t){const i=Ka(t);return i[i.indexOf(e)-1]}function xw(e,t){const i=Ka(t);return i[i.indexOf(e)+1]??"chat"}function Ka(e){return Pi.filter(t=>t!=="machines"||Ei(e))}var kw=Object.defineProperty,$w=Object.getOwnPropertyDescriptor,Y=(e,t,i,s)=>{for(var o=s>1?void 0:s?$w(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&kw(t,i,o),o};const Pw=new Set(["ArrowLeft","ArrowRight","Home","End"]),Rw=420,Iw=4;let K=class extends M{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 c`
2183
2202
  ${this.renderResizeHandle()}
2184
2203
  <button
2185
2204
  type="button"
@@ -2209,7 +2228,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2209
2228
  @dblclick=${t=>{this.onResizeDoubleClick(t)}}
2210
2229
  @keydown=${t=>{this.onResizeKeyDown(t)}}
2211
2230
  ></div>
2212
- `}resizeAriaValueNow(){return this.panelWidth===void 0?F:String(Math.round(this.panelWidth))}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return c`<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)<=vw)&&(t.moved=!0,this.commitPanelWidth(Df(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||!gw.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=Wf(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<=mw){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 fe(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(fe(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=Ut(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};K.styles=_`
2231
+ `}resizeAriaValueNow(){return this.panelWidth===void 0?F:String(Math.round(this.panelWidth))}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return c`<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)<=Iw)&&(t.moved=!0,this.commitPanelWidth(Uf(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||!Pw.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=Hf(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<=Rw){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 fe(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(fe(this.side,e,this.resizeConstraints()))}finishActiveResize(){const e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute("resizing",!1),this.onResizeEnd?.()}}resizeConstraints(){const e=Ht(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};K.styles=_`
2213
2232
  :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; }
2214
2233
  :host([side="navigation"]) { grid-column: 2; }
2215
2234
  :host([side="workspace"]) { grid-column: 4; }
@@ -2228,7 +2247,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2228
2247
  @media (max-width: 760px) {
2229
2248
  :host([side="navigation"]) { display: none; }
2230
2249
  }
2231
- `;Y([d({reflect:!0})],K.prototype,"side",2);Y([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);Y([d({type:Boolean})],K.prototype,"resizable",2);Y([d({type:Number})],K.prototype,"panelWidth",2);Y([d({type:Number})],K.prototype,"minWidth",2);Y([d({type:Number})],K.prototype,"maxWidth",2);Y([d()],K.prototype,"controls",2);Y([d()],K.prototype,"resizeLabel",2);Y([d()],K.prototype,"expandLabel",2);Y([d()],K.prototype,"collapseLabel",2);Y([d({attribute:!1})],K.prototype,"onToggle",2);Y([d({attribute:!1})],K.prototype,"onResizeStart",2);Y([d({attribute:!1})],K.prototype,"onResize",2);Y([d({attribute:!1})],K.prototype,"onResizeEnd",2);Y([d({attribute:!1})],K.prototype,"onReset",2);K=Y([E("app-panel-edge-control")],K);var bw=Object.defineProperty,ww=Object.getOwnPropertyDescriptor,Ha=(e,t,i,s)=>{for(var r=s>1?void 0:s?ww(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&&bw(t,i,r),r};let Ei=class extends M{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="完整重载页面";return c`
2250
+ `;Y([d({reflect:!0})],K.prototype,"side",2);Y([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);Y([d({type:Boolean})],K.prototype,"resizable",2);Y([d({type:Number})],K.prototype,"panelWidth",2);Y([d({type:Number})],K.prototype,"minWidth",2);Y([d({type:Number})],K.prototype,"maxWidth",2);Y([d()],K.prototype,"controls",2);Y([d()],K.prototype,"resizeLabel",2);Y([d()],K.prototype,"expandLabel",2);Y([d()],K.prototype,"collapseLabel",2);Y([d({attribute:!1})],K.prototype,"onToggle",2);Y([d({attribute:!1})],K.prototype,"onResizeStart",2);Y([d({attribute:!1})],K.prototype,"onResize",2);Y([d({attribute:!1})],K.prototype,"onResizeEnd",2);Y([d({attribute:!1})],K.prototype,"onReset",2);K=Y([D("app-panel-edge-control")],K);var Cw=Object.defineProperty,Mw=Object.getOwnPropertyDescriptor,Va=(e,t,i,s)=>{for(var o=s>1?void 0:s?Mw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Cw(t,i,o),o};let Di=class extends M{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="完整重载页面";return c`
2232
2251
  <button
2233
2252
  class="app-refresh-button"
2234
2253
  title=${e}
@@ -2242,12 +2261,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2242
2261
  <path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
2243
2262
  <path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
2244
2263
  </svg>
2245
- `}};Ei.styles=_`
2264
+ `}};Di.styles=_`
2246
2265
  :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; }
2247
2266
  :host, :host * { -webkit-user-select: none; user-select: none; }
2248
2267
  .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; }
2249
2268
  .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
2250
- `;Ha([d({attribute:!1})],Ei.prototype,"onReload",2);Ei=Ha([E("app-refresh-control")],Ei);var yw=Object.defineProperty,Sw=Object.getOwnPropertyDescriptor,Me=(e,t,i,s)=>{for(var r=s>1?void 0:s?Sw(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 xw=900*1e3,kw=750,Ns=[1e3,3e3,8e3,15e3,3e4],nn={capture:!0},ms="auto:on",an="auto:off",ii="theme:",vs=jt("core:workspace.files"),bs=jt("core:workspace.git"),si=jt("core:workspace.terminal"),$w=320,Pw=2,Rw="(min-width: 1181px)";let pe=class extends M{constructor(){super(...arguments),this.state=md(),this.sessions=new oh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Yp),this.activity=new vd(()=>this.state,e=>{this.setState(e)}),this.auth=new yd(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new wh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new vh),this.projects=new Ad(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Td(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new $d(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Md(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Eh,this.realtime=new no,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new kh,this.terminalSelection=new Th,this.appShell=new bf(this),this.panelCollapse=new Mf(this),this.panelResize=new Af(this),this.navigationSections=new Rf(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=Iw(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Vh()??Hh,this.activeThemeId=ar,this.isRefreshingApp=!1,this.settingsSection=Ro(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}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,nn),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},xw),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,nn),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(!Tw(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),Cw(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=Po();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=kw){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 Tn.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=>qa(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await fi.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(Po(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const r=f(this.state),o=e.projectId===void 0||e.projectId===""?dn():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:s??e.view??this.defaultRouteView(),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 l=this.state.projects.find(p=>p.id===e.projectId);if(!l){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(l,{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===""?dn():{selectedFilePath:Zi(vs,"file"),selectedDiffPath:Zi(bs,"diff"),selectedTerminalId:Zi(si,"terminal")}}routeForSelectedMachine(e){const t=this.state.selectedMachine?.id??"local";return(e.machineId??"local")===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){rs(e,{replace:!0}),le(vs,"file",void 0,{replace:!0}),le(bs,"diff",void 0,{replace:!0}),le(si,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.kind!=="remote"||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===""?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=Ew(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>=Ns.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){this.chatView?.saveScrollPosition(),await e(),await this.updateComplete,await this.chatView?.updateComplete,await ws(),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()}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(lo(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(lo(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){rs(po(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){le(vs,"file",e.selectedFilePath,{replace:!0}),le(bs,"diff",e.selectedDiffPath,{replace:!0}),le(si,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??$h(e.id);if(await this.restoreRouteFor(po(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=pn(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const r=Gf(e,{api:{runTerminalCommand:(o,n)=>lt.runTerminalCommand(o,n,t),listCommandRuns:o=>lt.listCommandRuns(o,t),getCommandRun:o=>lt.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){le(si,"terminal",e,t)}terminalWorkspaceKey(e){return`${f(this.state)}:${e.path}`}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e="general"){this.settingsSection=e,os(e)}closeSettings(){this.settingsSection=void 0,os(void 0)}navigateSettings(e){this.settingsSection=e,os(e)}restoreSettingsRoute(){this.settingsSection=Ro()}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 no;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=>Mw(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):Aw(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 lt.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=ln(e),s=ln(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return c`
2269
+ `;Va([d({attribute:!1})],Di.prototype,"onReload",2);Di=Va([D("app-refresh-control")],Di);var Tw=Object.defineProperty,Aw=Object.getOwnPropertyDescriptor,Me=(e,t,i,s)=>{for(var o=s>1?void 0:s?Aw(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Tw(t,i,o),o};const Ew=900*1e3,Dw=750,Ns=[1e3,3e3,8e3,15e3,3e4],cn={capture:!0},vs="auto:on",ln="auto:off",si="theme:",bs=Ft("core:workspace.files"),ws=Ft("core:workspace.git"),oi=Ft("core:workspace.terminal"),Ww=320,_w=2,Lw="(min-width: 1181px)";let pe=class extends M{constructor(){super(...arguments),this.state=bd(),this.sessions=new hh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new nh),this.activity=new wd(()=>this.state,e=>{this.setState(e)}),this.auth=new xd(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Rh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new $h),this.projects=new Dd(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Ed(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new Rd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Ad(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Fh,this.realtime=new lr,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Th,this.terminalSelection=new Oh,this.appShell=new Rf(this),this.panelCollapse=new Ff(this),this.panelResize=new Nf(this),this.navigationSections=new Lf(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=Ow(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=eu()??Zh,this.activeThemeId=co,this.isRefreshingApp=!1,this.settingsSection=Cr(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.previousStackedWorkspaceLayout=this.appShell.isStackedWorkspaceLayout,this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode),this.normalizeMainViewForLayoutChange()}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,cn),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},Ew),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,cn),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(!zw(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),jw(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=Ir();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=Dw){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 En.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=>Ga(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await gi.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(Ir(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=f(this.state),r=e.projectId===void 0||e.projectId===""?hn():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=r.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(n))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:this.appShell.normalizedMainView(s??e.view,e.sessionId!==void 0),selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const l=this.state.projects.find(p=>p.id===e.projectId);if(!l){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(l,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),f(this.state)!==o&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?hn():{selectedFilePath:Xi(bs,"file"),selectedDiffPath:Xi(ws,"diff"),selectedTerminalId:Xi(oi,"terminal")}}routeForSelectedMachine(e){const t=this.state.selectedMachine?.id??"local";return(e.machineId??"local")===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){rs(e,{replace:!0}),le(bs,"file",void 0,{replace:!0}),le(ws,"diff",void 0,{replace:!0}),le(oi,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.kind!=="remote"||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===""?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=Bw(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>=Ns.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",r=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),n=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${n}${r===void 0?"":` ${r}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(o=>o.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e){this.chatView?.saveScrollPosition(),await e(),await this.updateComplete,await this.chatView?.updateComplete,await ys(),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(hr(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(hr(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){rs(ur(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){le(bs,"file",e.selectedFilePath,{replace:!0}),le(ws,"diff",e.selectedDiffPath,{replace:!0}),le(oi,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??Ah(e.id);if(await this.restoreRouteFor(ur(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=un(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=og(e,{api:{runTerminalCommand:(r,n)=>dt.runTerminalCommand(r,n,t),listCommandRuns:r=>dt.listCommandRuns(r,t),getCommandRun:r=>dt.getCommandRun(r,t)},openTerminal:(r,n)=>{this.openRuntimeTerminal(t,r,n)}});return this.terminalCommandRunRuntimes.set(i,o),o}async openRuntimeTerminal(e,t,i){if((f(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:"core:workspace.terminal",view:"core:workspace.terminal"},!1,{selectedTerminalId:i?.terminalId},"core:workspace.terminal"),f(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){le(oi,"terminal",e,t)}terminalWorkspaceKey(e){return`${f(this.state)}:${e.path}`}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e="general"){this.settingsSection=e,ns(e)}closeSettings(){this.settingsSection=void 0,ns(void 0)}navigateSettings(e){this.settingsSection=e,ns(e)}restoreSettingsRoute(){this.settingsSection=Cr()}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 lr;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=>Fw(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):Nw(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const t=this.state.selectedWorkspace;t===void 0||(e.type==="terminal.closed"?e.cwd:e.terminal.cwd)!==t.path||(e.type==="terminal.created"&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type==="terminal.closed"?e.terminalId:e.terminal.id),e.type==="terminal.closed"&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){const t=f(this.state);try{const i=await dt.terminals(e.projectId,e.id,t);if(f(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=pn(e),s=pn(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return c`
2251
2270
  <workspace-panel
2252
2271
  id="workspace-panel"
2253
2272
  .workspace=${e}
@@ -2293,7 +2312,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2293
2312
  .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
2294
2313
  .onReset=${()=>{this.resetResizablePanel("workspace")}}
2295
2314
  ></app-panel-edge-control>
2296
- `}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-Pw-$w);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(Rw).matches}measuredPanelWidth(e){const i=(e==="navigation"?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return i===void 0||i<=0?void 0:i}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&_t(e,pt.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&_t(e,pt.sessionsReload)}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??"this machine"} to delete archived sessions.`}selectedMachineRuntime(){return this.state.machineRuntimes[f(this.state)]}renderNavigationPanel(){return c`
2315
+ `}startPanelResize(e){return e==="navigation"?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){const t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){const i=this.getBoundingClientRect().width||(typeof window>"u"?0:window.innerWidth);if(i<=0)return t.maxWidth;const s=this.oppositeResizablePanelWidth(e),o=Math.floor(i-s-_w-Ww);return Math.max(t.minWidth,Math.min(t.maxWidth,o))}oppositeResizablePanelWidth(e){const t=e==="navigation"?"workspace":"navigation";return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e==="navigation"?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>"u"||!("matchMedia"in window)?!0:window.matchMedia(Lw).matches}measuredPanelWidth(e){const i=(e==="navigation"?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return i===void 0||i<=0?void 0:i}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&Lt(e,ht.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&Lt(e,ht.sessionsReload)}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??"this machine"} to delete archived sessions.`}selectedMachineRuntime(){return this.state.machineRuntimes[f(this.state)]}renderNavigationPanel(){return c`
2297
2316
  <app-navigation-panel
2298
2317
  .machines=${this.state.machines}
2299
2318
  .selectedMachine=${this.state.selectedMachine}
@@ -2309,7 +2328,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2309
2328
  .workspacesByProjectId=${this.state.workspacesByProjectId}
2310
2329
  .workspaces=${this.state.workspaces}
2311
2330
  .selectedWorkspace=${this.state.selectedWorkspace}
2312
- .deletingWorkspaceIds=${pu(this.state.workspaceDeletionRuns)}
2331
+ .deletingWorkspaceIds=${bu(this.state.workspaceDeletionRuns)}
2313
2332
  .sessions=${this.state.sessions}
2314
2333
  .sessionStatuses=${this.state.sessionStatuses}
2315
2334
  .sessionActivities=${this.state.sessionActivities}
@@ -2349,14 +2368,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2349
2368
  .onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
2350
2369
  .onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
2351
2370
  ></app-navigation-panel>
2352
- `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()}),await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!Ai(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 ws(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await ws(),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=cn(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=>$s.workspaceFile(e.projectId,e.id,i,t)}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=cn(this.state),i=t.id,s=r=>{const o=this.terminalCommandRunsForOrigin(r,i);return nf({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),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,onRefreshFiles:()=>{this.files.refreshFiles()},onUploadFiles:n=>{this.files.uploadFiles(n)},onCreateFile:n=>{this.files.createFile(n)},onCreateDirectory:n=>{this.files.createDirectory(n)},onMoveSelectedPath:n=>{this.files.moveSelectedPath(n)},onDeleteSelectedPath:()=>{this.files.deleteSelectedPath()},onDownloadSelectedFile:()=>{this.files.downloadSelectedFile()},onExpandDir:n=>{this.files.expandDir(n)},onSelectDirectory:n=>{this.files.selectDirectory(n)},onSelectFile:n=>{this.files.selectFile(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return Kf(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.navigationFocusActions(),...this.panelLayoutActions()]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"重置导航面板宽度",description:"将导航面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"重置工作区面板宽度",description:"将工作区面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"重置面板宽度",description:"将所有侧边面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"聚焦机器",description:"将键盘焦点移到机器选择器",shortcut:"mod+g m",group:"导航",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"聚焦项目",description:"将键盘焦点移到项目列表",shortcut:"mod+g p",group:"导航",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"聚焦工作区",description:"将键盘焦点移到工作区列表",shortcut:"mod+g w",group:"导航",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"聚焦会话",description:"将键盘焦点移到会话列表",shortcut:"mod+g s",group:"导航",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>So())}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}`,()=>So(`/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}}createPluginRuntimeContext(){const e=t=>of({state:this.state,piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!yh(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(ia(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
2371
+ `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()}),await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!Ei(this.state.machines)){await this.focusNavigationSection("projects");return}this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView("navigation"),this.navigationSections.expand(e),await this.updateComplete,await ys(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await ys(),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=dn(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=>Ps.workspaceFile(e.projectId,e.id,i,t)}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=dn(this.state),i=t.id,s=o=>{const r=this.terminalCommandRunsForOrigin(o,i);return uf({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>r.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:r},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,onRefreshFiles:()=>{this.files.refreshFiles()},onUploadFiles:n=>{this.files.uploadFiles(n)},onCreateFile:n=>{this.files.createFile(n)},onCreateDirectory:n=>{this.files.createDirectory(n)},onMoveSelectedPath:n=>{this.files.moveSelectedPath(n)},onDeleteSelectedPath:()=>{this.files.deleteSelectedPath()},onDownloadSelectedFile:()=>{this.files.downloadSelectedFile()},onExpandDir:n=>{this.files.expandDir(n)},onSelectDirectory:n=>{this.files.selectDirectory(n)},onSelectFile:n=>{this.files.selectFile(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return ig(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.navigationFocusActions(),...this.panelLayoutActions()]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"重置导航面板宽度",description:"将导航面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"重置工作区面板宽度",description:"将工作区面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"重置面板宽度",description:"将所有侧边面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"聚焦机器",description:"将键盘焦点移到机器选择器",shortcut:"mod+g m",group:"导航",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"聚焦项目",description:"将键盘焦点移到项目列表",shortcut:"mod+g p",group:"导航",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"聚焦工作区",description:"将键盘焦点移到工作区列表",shortcut:"mod+g w",group:"导航",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"聚焦会话",description:"将键盘焦点移到会话列表",shortcut:"mod+g s",group:"导航",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>kr())}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}`,()=>kr(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:s=>this.plugins.shouldLoadRemotePlugin(s.id,s.machineSpecific)})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(o){console.warn(`Failed to register PI WEB plugin ${s.id}`,o)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPluginRuntimeContext(){const e=t=>hf({state:this.state,piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Ih(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(ra(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
2353
2372
 
2354
2373
  This will run git worktree remove and delete:
2355
2374
  ${e.path}
2356
2375
 
2357
- The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=await $s.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:`启动工作区删除失败:${Dw(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=As(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(lu(t.id));if(f(this.state)!==e)return;const s=du(i);this.setState({workspaceDeletionRuns:s});for(const r of Object.values(s))xi(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(xi);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=f(this.state)){if(f(this.state)!==t)return;const i=pn(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=As(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:Ww(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}?
2376
+ The Git branch will not be deleted.`))return;const s=f(this.state);try{const o=await Ps.deleteWorkspace(e.projectId,e.id,s);if(f(this.state)!==s)return;this.recordWorkspaceDeletionRun(o,s);const r=await this.workspaceForCommandRun(o);if(f(this.state)!==s)return;r!==void 0&&this.openRuntimeTerminal(s,r,{terminalId:o.terminalId})}catch(o){f(this.state)===s&&this.setState({error:`启动工作区删除失败:${Uw(o)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(i=>i.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(f(this.state)!==t)return;const i=Es(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(mu(t.id));if(f(this.state)!==e)return;const s=vu(i);this.setState({workspaceDeletionRuns:s});for(const o of Object.values(s))ki(o)||await this.handleCompletedWorkspaceDeletionRun(o,e)}catch(i){console.warn("Failed to refresh workspace deletion runs",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(ki);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=f(this.state)){if(f(this.state)!==t)return;const i=un(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Es(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:Hw(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}?
2358
2377
 
2359
- 这只会从当前 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?an:ms;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${ii}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开启":"关闭"}`,description:this.autoThemeDescription(t)},...e.map(r=>({value:`${ii}${r.id}`,label:this.themeOptionLabel(r,i),description:this.themeOptionDescription(r)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===ms||e===an){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===ms},this.applyPreferredTheme(!0);return}if(!e.startsWith(ii))return;const t=e.slice(ii.length),i=this.plugins.getThemes().find(s=>s.id===t);i!==void 0&&(this.themePreference={themeId:i.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){const t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,Jh(t),e&&Gh(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Qh({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return ta(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=_w(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?c`
2378
+ 这只会从当前 PI WEB 网关移除它。`))return;const t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();const i=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(s=>s.id===e.id)||this.machineNavigation.forget(e.id),t&&i!==void 0&&await this.selectMachineWithMemory(i,{rememberCurrent:!1})}openSelectedMachine(){const e=this.state.selectedMachine;e?.kind!=="remote"||e.baseUrl===void 0||window.open(e.baseUrl,"_blank","noopener,noreferrer")}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{const i=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`操作失败:${i}`})})}async openModelDialog(){const e=await this.sessions.listModels(),t=this.state.status?.model?.provider,i=this.state.status?.model?.id;this.setState({modelDialog:{title:"选择模型",...t!==void 0&&i!==void 0?{selectedValue:`${t}/${i}`}:{},options:e.map(s=>{const o=s.provider??"",r=s.id??"",n=o===t&&r===i;return{value:`${o}/${r}`,label:`${r}${n?" ✓ 当前":""}`,description:o}})}})}async pickModel(e){this.setState({modelDialog:void 0});const t=e.indexOf("/");t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){const e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?ln:vs;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${si}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开启":"关闭"}`,description:this.autoThemeDescription(t)},...e.map(o=>({value:`${si}${o.id}`,label:this.themeOptionLabel(o,i),description:this.themeOptionDescription(o)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===vs||e===ln){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===vs},this.applyPreferredTheme(!0);return}if(!e.startsWith(si))return;const t=e.slice(si.length),i=this.plugins.getThemes().find(s=>s.id===t);i!==void 0&&(this.themePreference={themeId:i.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){const t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,iu(t),e&&tu(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return su({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return oa(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=qw(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?c`
2360
2379
  <app-context-bar
2361
2380
  .machines=${this.state.machines}
2362
2381
  .machine=${this.state.selectedMachine}
@@ -2377,14 +2396,14 @@ The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=a
2377
2396
  <div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints("navigation"),workspace:this.resizablePanelConstraints("workspace")})}>
2378
2397
  <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
2379
2398
  ${this.renderNavigationPanelEdgeControl()}
2380
- <main class=${la(e.mainView)}>
2399
+ <main class=${ha(e.mainView)}>
2381
2400
  ${this.renderContextBar()}
2382
2401
  ${this.renderMobileMainTabs()}
2383
2402
  ${e.error?c`<div class="error">${e.error}</div>`:null}
2384
2403
  <div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
2385
2404
  ${e.selectedSession?c`
2386
2405
  <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>
2387
- <prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${f(e)} .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=${(t,i,s,r)=>{this.sendPrompt(t,i,s,r)}} .onStop=${()=>this.sessions.stopActiveWork()} .onSelectModel=${()=>{this.openModelDialog()}} .onSelectThinking=${()=>{this.openThinkingDialog()}}></prompt-editor>
2406
+ <prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${f(e)} .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=${(t,i,s,o)=>{this.sendPrompt(t,i,s,o)}} .onStop=${()=>this.sessions.stopActiveWork()} .onSelectModel=${()=>{this.openModelDialog()}} .onSelectThinking=${()=>{this.openThinkingDialog()}}></prompt-editor>
2388
2407
  <status-bar .status=${e.status}></status-bar>
2389
2408
  ${e.commandDialog!==void 0?c`<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}
2390
2409
  ${e.modelDialog!==void 0?c`<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}
@@ -2400,4 +2419,4 @@ The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=a
2400
2419
  ${e.themeDialog!==void 0?c`<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}
2401
2420
  ${this.settingsSection!==void 0?c`<settings-dialog .section=${this.settingsSection} .actions=${this.getDefaultActions()} .onNavigate=${t=>{this.navigateSettings(t)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${t=>{this.applyClientConfig(t)}}></settings-dialog>`:null}
2402
2421
  </div>
2403
- `}};pe.styles=ag;Me([y()],pe.prototype,"state",2);Me([B("chat-view")],pe.prototype,"chatView",2);Me([B("prompt-editor")],pe.prototype,"promptEditor",2);Me([B("app-navigation-panel")],pe.prototype,"navigationPanel",2);Me([B("#navigation-panel")],pe.prototype,"navigationPanelFrame",2);Me([B("#workspace-panel")],pe.prototype,"workspacePanelFrame",2);Me([y()],pe.prototype,"activeThemeId",2);Me([y()],pe.prototype,"isRefreshingApp",2);Me([y()],pe.prototype,"settingsSection",2);Me([y()],pe.prototype,"shortcutConfig",2);pe=Me([E("pi-web-app")],pe);function Iw(){const e=new sf;return e.register({id:"core",plugin:Fu}),e.register({id:"themes",plugin:Uu}),e}function cn(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 Cw(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function Mw(e,t){return qa(e,t)}function qa(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function Tw(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function ln(e){return Xe(e.status,e.activity)}function Aw(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function dn(){return{}}function pn(e,t){return JSON.stringify([e,t])}function Ew(e){const t=Math.min(e,Ns.length-1);return Ns[t]??3e4}function Dw(e){return e instanceof Error?e.message:String(e)}function Ww(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function ws(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function _w(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{_ as a,c as b,lt as c,Vw as d,B as e,qw as f,M as i,d as n,y as r,Kw as s,E as t};
2422
+ `}};pe.styles=vg;Me([S()],pe.prototype,"state",2);Me([B("chat-view")],pe.prototype,"chatView",2);Me([B("prompt-editor")],pe.prototype,"promptEditor",2);Me([B("app-navigation-panel")],pe.prototype,"navigationPanel",2);Me([B("#navigation-panel")],pe.prototype,"navigationPanelFrame",2);Me([B("#workspace-panel")],pe.prototype,"workspacePanelFrame",2);Me([S()],pe.prototype,"activeThemeId",2);Me([S()],pe.prototype,"isRefreshingApp",2);Me([S()],pe.prototype,"settingsSection",2);Me([S()],pe.prototype,"shortcutConfig",2);pe=Me([D("pi-web-app")],pe);function Ow(){const e=new df;return e.register({id:"core",plugin:Ku}),e.register({id:"themes",plugin:Qu}),e}function dn(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 jw(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function Fw(e,t){return Ga(e,t)}function Ga(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function zw(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function pn(e){return Xe(e.status,e.activity)}function Nw(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function hn(){return{}}function un(e,t){return JSON.stringify([e,t])}function Bw(e){const t=Math.min(e,Ns.length-1);return Ns[t]??3e4}function Uw(e){return e instanceof Error?e.message:String(e)}function Hw(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function ys(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function qw(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{_ as a,c as b,dt as c,oy as d,B as e,iy as f,M as i,d as n,S as r,sy as s,D as t};