@chainingintention/pi-web-cn 1.202606.26 → 1.202606.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,29 +1,29 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-CEaJIjgA.js","assets/vendor-editor-core-C7aWiQy0.js","assets/vendor-editor-languages-EW34FfVy.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/UnifiedDiffViewer-Dkgg-4fh.js","assets/TerminalPanel-BdMJbtLB.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
- import{Q as Xr,v as tt,J as hs,R as Bl,S as Nl,G as Hl,U as ql,V as Kl,W as Vl,A as Gl,X as Jl,Y as Ql,Z as Yr,w as eo,_ as Zl}from"./vendor-editor-core-C7aWiQy0.js";import{m as Xl,d as Yl,i as ec}from"./vendor-editor-languages-EW34FfVy.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const n of o.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=i(r);fetch(r.href,o)}})();const ui=globalThis,lr=ui.ShadowRoot&&(ui.ShadyCSS===void 0||ui.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,cr=Symbol(),to=new WeakMap;let Yn=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==cr)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(lr&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=to.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&to.set(i,t))}return t}toString(){return this.cssText}};const tc=e=>new Yn(typeof e=="string"?e:e+"",void 0,cr),E=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,r,o)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+e[o+1],e[0]);return new Yn(i,e,cr)},ic=(e,t)=>{if(lr)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),r=ui.litNonce;r!==void 0&&s.setAttribute("nonce",r),s.textContent=i.cssText,e.appendChild(s)}},io=lr?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return tc(i)})(e):e;const{is:sc,defineProperty:rc,getOwnPropertyDescriptor:oc,getOwnPropertyNames:nc,getOwnPropertySymbols:ac,getPrototypeOf:lc}=Object,Vi=globalThis,so=Vi.trustedTypes,cc=so?so.emptyScript:"",dc=Vi.reactiveElementPolyfillSupport,zt=(e,t)=>e,ki={toAttribute(e,t){switch(t){case Boolean:e=e?cc: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}},dr=(e,t)=>!sc(e,t),ro={attribute:!0,type:String,converter:ki,reflect:!1,useDefault:!1,hasChanged:dr};Symbol.metadata??=Symbol("metadata"),Vi.litPropertyMetadata??=new WeakMap;let bt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=ro){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&&rc(this.prototype,t,r)}}static getPropertyDescriptor(t,i,s){const{get:r,set:o}=oc(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)??ro}static _$Ei(){if(this.hasOwnProperty(zt("elementProperties")))return;const t=lc(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(zt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(zt("properties"))){const i=this.properties,s=[...nc(i),...ac(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(io(r))}else t!==void 0&&i.push(io(t));return i}static _$Eu(t,i){const s=i.attribute;return s===!1?void 0:typeof s=="string"?s:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,i=this.constructor.elementProperties;for(const s of i.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return ic(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$ET(t,i){const s=this.constructor.elementProperties.get(t),r=this.constructor._$Eu(t,s);if(r!==void 0&&s.reflect===!0){const o=(s.converter?.toAttribute!==void 0?s.converter:ki).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:ki;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??dr)(o,i)||s.useDefault&&s.reflect&&o===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:r,wrapped:o},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),o!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),r===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,o]of s){const{wrapped:n}=o,a=this[r];n!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,o,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};bt.elementStyles=[],bt.shadowRootOptions={mode:"open"},bt[zt("elementProperties")]=new Map,bt[zt("finalized")]=new Map,dc?.({ReactiveElement:bt}),(Vi.reactiveElementVersions??=[]).push("2.1.2");const pr=globalThis,oo=e=>e,$i=pr.trustedTypes,no=$i?$i.createPolicy("lit-html",{createHTML:e=>e}):void 0,ea="$lit$",Je=`lit$${Math.random().toFixed(9).slice(2)}$`,ta="?"+Je,pc=`<${ta}>`,ct=document,Nt=()=>ct.createComment(""),Ht=e=>e===null||typeof e!="object"&&typeof e!="function",hr=Array.isArray,hc=e=>hr(e)||typeof e?.[Symbol.iterator]=="function",us=`[
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-hxitRRG6.js","assets/vendor-editor-core-C7aWiQy0.js","assets/vendor-editor-languages-EW34FfVy.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/UnifiedDiffViewer-DTCywBXP.js","assets/TerminalPanel-DTn18hoY.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
+ import{Q as Xr,v as tt,J as hs,R as Kl,S as Vl,G as Gl,U as Jl,V as Ql,W as Zl,A as Xl,X as Yl,Y as ec,Z as Yr,w as eo,_ as tc}from"./vendor-editor-core-C7aWiQy0.js";import{m as ic,d as sc,i as rc}from"./vendor-editor-languages-EW34FfVy.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const n of o.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=i(r);fetch(r.href,o)}})();const ui=globalThis,lr=ui.ShadowRoot&&(ui.ShadyCSS===void 0||ui.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,cr=Symbol(),to=new WeakMap;let sa=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==cr)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(lr&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=to.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&to.set(i,t))}return t}toString(){return this.cssText}};const oc=e=>new sa(typeof e=="string"?e:e+"",void 0,cr),E=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,r,o)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+e[o+1],e[0]);return new sa(i,e,cr)},nc=(e,t)=>{if(lr)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),r=ui.litNonce;r!==void 0&&s.setAttribute("nonce",r),s.textContent=i.cssText,e.appendChild(s)}},io=lr?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return oc(i)})(e):e;const{is:ac,defineProperty:lc,getOwnPropertyDescriptor:cc,getOwnPropertyNames:dc,getOwnPropertySymbols:pc,getPrototypeOf:hc}=Object,Vi=globalThis,so=Vi.trustedTypes,uc=so?so.emptyScript:"",fc=Vi.reactiveElementPolyfillSupport,zt=(e,t)=>e,ki={toAttribute(e,t){switch(t){case Boolean:e=e?uc: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}},dr=(e,t)=>!ac(e,t),ro={attribute:!0,type:String,converter:ki,reflect:!1,useDefault:!1,hasChanged:dr};Symbol.metadata??=Symbol("metadata"),Vi.litPropertyMetadata??=new WeakMap;let bt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=ro){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&&lc(this.prototype,t,r)}}static getPropertyDescriptor(t,i,s){const{get:r,set:o}=cc(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:r,set(n){const a=r?.call(this);o?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??ro}static _$Ei(){if(this.hasOwnProperty(zt("elementProperties")))return;const t=hc(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(zt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(zt("properties"))){const i=this.properties,s=[...dc(i),...pc(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(io(r))}else t!==void 0&&i.push(io(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 nc(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:ki).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:ki;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??dr)(o,i)||s.useDefault&&s.reflect&&o===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:r,wrapped:o},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),o!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),r===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,o]of s){const{wrapped:n}=o,a=this[r];n!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,o,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};bt.elementStyles=[],bt.shadowRootOptions={mode:"open"},bt[zt("elementProperties")]=new Map,bt[zt("finalized")]=new Map,fc?.({ReactiveElement:bt}),(Vi.reactiveElementVersions??=[]).push("2.1.2");const pr=globalThis,oo=e=>e,$i=pr.trustedTypes,no=$i?$i.createPolicy("lit-html",{createHTML:e=>e}):void 0,ra="$lit$",Je=`lit$${Math.random().toFixed(9).slice(2)}$`,oa="?"+Je,gc=`<${oa}>`,ct=document,Nt=()=>ct.createComment(""),Ht=e=>e===null||typeof e!="object"&&typeof e!="function",hr=Array.isArray,mc=e=>hr(e)||typeof e?.[Symbol.iterator]=="function",us=`[
3
3
  \f\r]`,At=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ao=/-->/g,lo=/>/g,it=RegExp(`>|${us}(?:([^\\s"'>=/]+)(${us}*=${us}*(?:[^
4
- \f\r"'\`<>=]|("|')|))|$)`,"g"),co=/'/g,po=/"/g,ia=/^(?:script|style|textarea|title)$/i,sa=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=sa(1),be=sa(2),Ze=Symbol.for("lit-noChange"),z=Symbol.for("lit-nothing"),ho=new WeakMap,nt=ct.createTreeWalker(ct,129);function ra(e,t){if(!hr(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return no!==void 0?no.createHTML(t):t}const uc=(e,t)=>{const i=e.length-1,s=[];let r,o=t===2?"<svg>":t===3?"<math>":"",n=At;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,g=0;for(;g<c.length&&(n.lastIndex=g,u=n.exec(c),u!==null);)g=n.lastIndex,n===At?u[1]==="!--"?n=ao:u[1]!==void 0?n=lo:u[2]!==void 0?(ia.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=it):u[3]!==void 0&&(n=it):n===it?u[0]===">"?(n=r??At,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?it:u[3]==='"'?po:co):n===po||n===co?n=it:n===ao||n===lo?n=At:(n=it,r=void 0);const b=n===it&&e[a+1].startsWith("/>")?" ":"";o+=n===At?c+pc:h>=0?(s.push(p),c.slice(0,h)+ea+c.slice(h)+Je+b):c+Je+(h===-2?a:b)}return[ra(e,o+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class qt{constructor({strings:t,_$litType$:i},s){let r;this.parts=[];let o=0,n=0;const a=t.length-1,c=this.parts,[p,u]=uc(t,i);if(this.el=qt.createElement(p,s),nt.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(r=nt.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const h of r.getAttributeNames())if(h.endsWith(ea)){const g=u[n++],b=r.getAttribute(h).split(Je),P=/([.?@])?(.*)/.exec(g);c.push({type:1,index:o,name:P[2],strings:b,ctor:P[1]==="."?gc:P[1]==="?"?mc:P[1]==="@"?vc:Gi}),r.removeAttribute(h)}else h.startsWith(Je)&&(c.push({type:6,index:o}),r.removeAttribute(h));if(ia.test(r.tagName)){const h=r.textContent.split(Je),g=h.length-1;if(g>0){r.textContent=$i?$i.emptyScript:"";for(let b=0;b<g;b++)r.append(h[b],Nt()),nt.nextNode(),c.push({type:2,index:++o});r.append(h[g],Nt())}}}else if(r.nodeType===8)if(r.data===ta)c.push({type:2,index:o});else{let h=-1;for(;(h=r.data.indexOf(Je,h+1))!==-1;)c.push({type:7,index:o}),h+=Je.length-1}o++}}static createElement(t,i){const s=ct.createElement("template");return s.innerHTML=t,s}}function St(e,t,i=e,s){if(t===Ze)return t;let r=s!==void 0?i._$Co?.[s]:i._$Cl;const o=Ht(t)?void 0:t._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(e),r._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=r:i._$Cl=r),r!==void 0&&(t=St(e,r._$AS(e,t.values),r,s)),t}class fc{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,r=(t?.creationScope??ct).importNode(i,!0);nt.currentNode=r;let o=nt.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new Pt(o,o.nextSibling,this,t):c.type===1?p=new c.ctor(o,c.name,c.strings,this,t):c.type===6&&(p=new bc(o,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(o=nt.nextNode(),n++)}return nt.currentNode=ct,r}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class Pt{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,r){this.type=2,this._$AH=z,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=St(this,t,i),Ht(t)?t===z||t==null||t===""?(this._$AH!==z&&this._$AR(),this._$AH=z):t!==this._$AH&&t!==Ze&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):hc(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==z&&Ht(this._$AH)?this._$AA.nextSibling.data=t:this.T(ct.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,r=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=qt.createElement(ra(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(i);else{const o=new fc(r,this),n=o.u(this.options);o.p(i),this.T(n),this._$AH=o}}_$AC(t){let i=ho.get(t.strings);return i===void 0&&ho.set(t.strings,i=new qt(t)),i}k(t){hr(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 Pt(this.O(Nt()),this.O(Nt()),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=oo(t).nextSibling;oo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Gi=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,r,o){this.type=1,this._$AH=z,this._$AN=void 0,this.element=t,this.name=i,this._$AM=r,this.options=o,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=z}_$AI(t,i=this,s,r){const o=this.strings;let n=!1;if(o===void 0)t=St(this,t,i,0),n=!Ht(t)||t!==this._$AH&&t!==Ze,n&&(this._$AH=t);else{const a=t;let c,p;for(t=o[0],c=0;c<o.length-1;c++)p=St(this,a[s+c],i,c),p===Ze&&(p=this._$AH[c]),n||=!Ht(p)||p!==this._$AH[c],p===z?t=z:t!==z&&(t+=(p??"")+o[c+1]),this._$AH[c]=p}n&&!r&&this.j(t)}j(t){t===z?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},gc=class extends Gi{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===z?void 0:t}},mc=class extends Gi{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==z)}},vc=class extends Gi{constructor(t,i,s,r,o){super(t,i,s,r,o),this.type=5}_$AI(t,i=this){if((t=St(this,t,i,0)??z)===Ze)return;const s=this._$AH,r=t===z&&s!==z||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,o=t!==z&&(s===z||r);r&&this.element.removeEventListener(this.name,this,s),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},bc=class{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){St(this,t)}};const wc={I:Pt},yc=pr.litHtmlPolyfillSupport;yc?.(qt,Pt),(pr.litHtmlVersions??=[]).push("3.3.3");const xc=(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 Pt(t.insertBefore(Nt(),o),o,void 0,i??{})}return r._$AI(e),r};const ur=globalThis;let A=class extends bt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=xc(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ze}};A._$litElement$=!0,A.finalized=!0,ur.litElementHydrateSupport?.({LitElement:A});const Sc=ur.litElementPolyfillSupport;Sc?.({LitElement:A});(ur.litElementVersions??=[]).push("4.2.2");const W=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const kc={attribute:!0,type:String,converter:ki,reflect:!1,hasChanged:dr},$c=(e=kc,t,i)=>{const{kind:s,metadata:r}=i;let o=globalThis.litPropertyMetadata.get(r);if(o===void 0&&globalThis.litPropertyMetadata.set(r,o=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),o.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,c,e,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,e,a),a}}}if(s==="setter"){const{name:n}=i;return function(a){const c=this[n];t.call(this,a),this.requestUpdate(n,c,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?$c(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 Pc=(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 Pc(i,s,{get(){return o(this)}})}}function oa(e,t=Rc()){if(t===void 0)return e;const i=Cc(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 Cc(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 Rc(){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 w(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&!s.has("content-type")&&s.set("content-type","application/json");const r=await fetch(oa(e),{...i,headers:s});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(Ic(n)??r.statusText)}const o=await r.json();return t(o)}function Ic(e){if(Ac(e))return typeof e.error=="string"?e.error:void 0}function Ac(e){return typeof e=="object"&&e!==null}function ze(e){return typeof e=="object"&&e!==null}function x(e){if(!ze(e))throw new Error("Expected object response");return e}function m(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function $(e,t){const i=e[t];if(i!==void 0){if(typeof i!="string")throw new Error(`Expected optional string field: ${t}`);return i}}function q(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function ne(e,t){const i=e[t];if(i!==void 0){if(typeof i!="number")throw new Error(`Expected optional number field: ${t}`);return i}}function D(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function F(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function Ye(e,t){if(x(e)[t]!==!0)throw new Error(`Expected ${t} response`);return!0}function v(e,t){return t===void 0?{}:{[e]:t}}const Qe={sessionsDeleteArchived:"sessions.deleteArchived",sessionsCleanup:"sessions.cleanup",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments",workspaceFileSuggestions:"workspace.fileSuggestions"},Tc=Object.values(Qe),Mc=new Set(Tc);function Ec(e){return typeof e=="string"&&Mc.has(e)}function at(e,t){return e?.capabilities?.includes(t)===!0}function uo(e){const t=x(e);return{path:m(t,"path"),exists:D(t,"exists"),config:fo(t.config),effectiveConfig:fo(t.effectiveConfig),envOverrides:Fc(t.envOverrides)}}function fo(e){const t=x(e);return{...v("host",$(t,"host")),...v("port",ne(t,"port")),...v("allowedHosts",Dc(t.allowedHosts)),...v("shortcuts",Lc(t.shortcuts)),...v("plugins",jc(t.plugins)),...v("pathAccess",Wc(t.pathAccess)),...v("uploads",_c(t.uploads)),...v("maxUploadBytes",ne(t,"maxUploadBytes")),...v("spawnSessions",mo(t,"spawnSessions")),...v("subsessions",mo(t,"subsessions"))}}function Dc(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 Wc(e){if(e===void 0)return;if(!ze(e)||Array.isArray(e))throw new Error("Invalid PI WEB pathAccess field");const t=e.allowedPaths;return{...v("allowedPaths",Oc(t,"pathAccess.allowedPaths"))}}function Oc(e,t){if(e!==void 0){if(Array.isArray(e)&&e.every(i=>typeof i=="string"&&i!==""))return e;throw new Error(`Invalid PI WEB ${t} field`)}}function _c(e){if(e!==void 0){if(!ze(e)||Array.isArray(e))throw new Error("Invalid PI WEB uploads field");return{...v("defaultFolder",$(e,"defaultFolder"))}}}function Lc(e){if(e!==void 0){if(!ze(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 jc(e){if(e!==void 0){if(!ze(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!ze(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&&(!ze(r)||Array.isArray(r)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Fc(e){const t=x(e);return{host:D(t,"host"),port:D(t,"port"),allowedHosts:D(t,"allowedHosts"),spawnSessions:D(t,"spawnSessions"),subsessions:D(t,"subsessions")}}function Uc(e){const t=x(e);return{plugins:F(zc)(t.plugins)}}function zc(e){const t=x(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:Bc(t.scope),machineSpecific:Zc(t.machineSpecific,"machineSpecific")??!1,enabled:D(t,"enabled")}}function Bc(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function Nc(e){const t=x(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:qc(t.components),release:Vc(t.release),commands:Gc(t.commands),messages:F(Jc)(t.messages)}}function Hc(e){const t=x(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:na(t.components),capabilities:fr(t.capabilities)}}function qc(e){const t=x(e);return{web:Pi(t.web),sessiond:Pi(t.sessiond)}}function na(e){const t=x(e);return{web:go(t.web),sessiond:go(t.sessiond)}}function go(e){const t=x(e);return{component:aa(t.component),label:m(t,"label"),...v("runtimeVersion",$(t,"runtimeVersion")),available:D(t,"available"),capabilities:fr(t.capabilities),...v("error",$(t,"error"))}}function Pi(e){const t=x(e);return{component:aa(t.component),label:m(t,"label"),...v("runtimeVersion",$(t,"runtimeVersion")),...v("installedVersion",$(t,"installedVersion")),stale:D(t,"stale"),available:D(t,"available"),...v("installation",Kc(t.installation)),...v("error",$(t,"error"))}}function Kc(e){if(e===void 0)return;const t=x(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");return{kind:i,...v("path",$(t,"path")),...v("source",$(t,"source")),...s===void 0?{}:{scope:s},...v("npmRoot",$(t,"npmRoot"))}}function Vc(e){const t=x(e);return{packageName:m(t,"packageName"),...v("latestVersion",$(t,"latestVersion")),updateAvailable:D(t,"updateAvailable"),...v("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...v("error",$(t,"error"))}}function Gc(e){const t=x(e);return{...v("update",$(t,"update")),...v("restart",$(t,"restart")),...v("restartWeb",$(t,"restartWeb")),...v("restartSessiond",$(t,"restartSessiond")),...v("status",$(t,"status"))}}function Jc(e){const t=x(e);return{id:m(t,"id"),severity:Qc(t.severity),title:m(t,"title"),body:m(t,"body"),...v("command",$(t,"command"))}}function aa(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function fr(e){if(!Array.isArray(e)||!e.every(Ec))throw new Error("Invalid PI WEB capabilities");return e}function Qc(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Zc(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function mo(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 Xc(e){const t=x(e);return F(la)(t.machines)}function la(e){const t=x(e),i=td(t,"kind"),s=$(t,"baseUrl"),r=ca(t,"status"),o=$(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...r===void 0?{}:{status:r},...o===void 0?{}:{statusMessage:o}}}function Yc(e){const t=x(e),i=ca(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:D(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:Pi(t.web)},...t.sessiond===void 0?{}:{sessiond:Pi(t.sessiond)},...s===void 0?{}:{error:s}}}function ed(e){const t=x(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:D(t,"ok"),checkedAt:m(t,"checkedAt"),...v("packageName",$(t,"packageName")),...v("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:na(t.components)},...t.capabilities===void 0?{}:{capabilities:fr(t.capabilities)},...i===void 0?{}:{error:i}}}function td(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function ca(e,t){const i=$(e,t);if(i!==void 0){if(i!=="unknown"&&i!=="online"&&i!=="offline"&&i!=="error")throw new Error(`Expected machine status field: ${t}`);return i}}function id(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function Ci(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function sd(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=x(e);return{messages:id(t.messages),start:q(t,"start"),total:q(t,"total")}}function vo(e){const t=x(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function rd(e){const t=x(e),i=$(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:D(t,"isMain"),isGitRepo:D(t,"isGitRepo"),isGitWorktree:D(t,"isGitWorktree"),...v("effectiveConfig",od(t.effectiveConfig))}}function od(e){if(e!==void 0){if(!ze(e)||Array.isArray(e))throw new Error("Invalid workspace effectiveConfig field");return{...v("uploads",Nd(e.uploads))}}}function zs(e){const t=x(e);return{path:m(t,"path"),size:q(t,"size"),modifiedAt:m(t,"modifiedAt")}}function bo(e){const t=x(e);return{path:m(t,"path")}}function nd(e){const t=x(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function Bs(e){const t=x(e),i=$(t,"name"),s=$(t,"parentSessionPath"),r=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:q(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...r===void 0?{}:{archivedAt:r}}}function Tt(e){const t=x(e);return{sessionId:m(t,"sessionId"),isStreaming:D(t,"isStreaming"),isCompacting:D(t,"isCompacting"),isBashRunning:D(t,"isBashRunning"),pendingMessageCount:q(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:F(pd)(t.queuedMessages),...v("messageCount",ne(t,"messageCount")),tokens:hd(t.tokens),cost:q(t,"cost"),...gd(t.model),...Id(t.contextUsage),...v("thinkingLevel",$(t,"thinkingLevel"))}}function da(e){const t=x(e),i=t.skippedBusySessionIds===void 0?void 0:Ci(t.skippedBusySessionIds,"skippedBusySessionIds");return{generatedAt:m(t,"generatedAt"),thresholds:ld(t.thresholds),projects:F(cd)(t.projects),totals:dd(t.totals),...i===void 0?{}:{skippedBusySessionIds:i}}}function ad(e){const t=x(e);return{...da(t),archivedSessionIds:Ci(t.archivedSessionIds,"archivedSessionIds"),deletedSessionIds:Ci(t.deletedSessionIds,"deletedSessionIds")}}function ld(e){const t=x(e);return{...v("archiveIdleDays",ne(t,"archiveIdleDays")),...v("deleteArchivedDays",ne(t,"deleteArchivedDays"))}}function cd(e){const t=x(e);return{cwd:m(t,"cwd"),archiveCount:q(t,"archiveCount"),deleteCount:q(t,"deleteCount")}}function dd(e){const t=x(e);return{archiveCount:q(t,"archiveCount"),deleteCount:q(t,"deleteCount")}}function pd(e){const t=x(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text"),...v("imageCount",ne(t,"imageCount"))}}function hd(e){const t=x(e);return{input:q(t,"input"),output:q(t,"output"),cacheRead:q(t,"cacheRead"),cacheWrite:q(t,"cacheWrite"),total:q(t,"total")}}function pa(e){const t=x(e);return{...v("provider",$(t,"provider")),...v("id",$(t,"id")),...v("name",$(t,"name")),...v("contextWindow",ne(t,"contextWindow")),...v("reasoning",t.reasoning),...v("input",ud(t.input))}}function ud(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Invalid model input");return e.map(fd)}}function fd(e){if(e==="text"||e==="image")return e;throw new Error("Invalid model input")}function gd(e){return e===void 0?{}:{model:pa(e)}}function md(e){const t=x(e);return{models:F(pa)(t.models)}}function vd(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function bd(e){const t=x(e);return{levels:F(vd)(t.levels)}}function wd(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function yd(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 xd(e){const t=x(e),i=t.source===void 0?void 0:yd(t.source);return{configured:D(t,"configured"),...v("source",i),...v("label",$(t,"label"))}}function Sd(e){const t=x(e);return{id:m(t,"id"),name:m(t,"name"),authType:wd(t.authType),status:xd(t.status)}}function kd(e){const t=x(e);return{providers:F(Sd)(t.providers)}}function ti(e){const t=x(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:$d(t.status),progress:F(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...v("error",$(t,"error")),...v("auth",Pd(t.auth)),...v("prompt",Cd(t.prompt)),...v("select",Rd(t.select))}}function $d(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Pd(e){if(e===void 0)return;const t=x(e);return{url:m(t,"url"),...v("instructions",$(t,"instructions"))}}function Cd(e){if(e===void 0)return;const t=x(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...v("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function Rd(e){if(e===void 0)return;const t=x(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:F(ua)(t.options)}}function Id(e){if(e===void 0)return{};const t=x(e);return{contextUsage:{tokens:So(t,"tokens"),contextWindow:q(t,"contextWindow"),percent:So(t,"percent")}}}function Ad(e){const t=x(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...v("description",$(t,"description"))}}function Ns(e){const t=x(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function Td(e){const t=x(e);return{path:m(t,"path"),entries:F(Md)(t.entries),scannedAt:m(t,"scannedAt"),truncated:D(t,"truncated")}}function Md(e){const t=x(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...v("size",ne(t,"size")),...v("modifiedAt",$(t,"modifiedAt"))}}function Ed(e){const t=x(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...v("language",$(t,"language")),...v("mediaType",Od(t.mediaType)),...v("mimeType",$(t,"mimeType")),encoding:i,size:q(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:D(t,"truncated"),binary:D(t,"binary")}}function ha(e){const t=x(e);return{path:m(t,"path"),size:q(t,"size"),modifiedAt:m(t,"modifiedAt"),created:D(t,"created")}}function Dd(e){const t=x(e);return{path:m(t,"path"),existed:D(t,"existed")}}function Wd(e){const t=x(e);return{fromPath:m(t,"fromPath"),toPath:m(t,"toPath"),size:q(t,"size"),modifiedAt:m(t,"modifiedAt")}}function Od(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function _d(e){const t=x(e);return{isGitRepo:D(t,"isGitRepo"),hash:m(t,"hash"),...v("branch",$(t,"branch")),...v("upstream",$(t,"upstream")),...v("ahead",ne(t,"ahead")),...v("behind",ne(t,"behind")),files:F(Ld)(t.files)}}function Ld(e){const t=x(e);return{path:m(t,"path"),...v("oldPath",$(t,"oldPath")),index:wo(t.index),workingTree:wo(t.workingTree)}}function wo(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 jd(e){const t=x(e);return{...v("path",$(t,"path")),staged:D(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:D(t,"truncated")}}function fs(e){const t=x(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:D(t,"exited"),...v("exitCode",ne(t,"exitCode")),...v("commandRunId",$(t,"commandRunId"))}}function Bt(e){const t=x(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:Fd(t.status),...v("exitCode",ne(t,"exitCode")),createdAt:m(t,"createdAt"),...v("startedAt",$(t,"startedAt")),...v("completedAt",$(t,"completedAt")),metadata:Ud(t.metadata,"metadata")}}function Fd(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function Ud(e,t){const i=x(e);return Object.fromEntries(Object.entries(i).map(([s,r])=>{if(typeof r!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,r]}))}function zd(e){const t=x(e);return{cwd:m(t,"cwd"),hasSessionActivity:D(t,"hasSessionActivity"),hasTerminalActivity:D(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function Bd(e){const t=x(e);return{workspaces:F(zd)(t.workspaces),generatedAt:m(t,"generatedAt")}}function Nd(e){if(e!==void 0){if(!ze(e)||Array.isArray(e))throw new Error("Invalid uploads field");return{...v("defaultFolder",$(e,"defaultFolder"))}}}function yo(e){const t=x(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:F(ua)(t.options)};if(i==="done")return{type:i,...v("message",$(t,"message")),...Hd(t.session),...v("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function ua(e){const t=x(e);return{value:m(t,"value"),label:m(t,"label"),...v("description",$(t,"description"))}}function Hd(e){return e===void 0?{}:{session:Bs(e)}}function ii(e){return{accepted:Ye(e,"accepted")}}function qd(e){const t=x(e);return F(Kd)(t.attachments)}function Kd(e){const t=x(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:q(t,"size")}}function Hs(e){return{closed:Ye(e,"closed")}}function Vd(e){return{aborted:Ye(e,"aborted")}}function Gd(e){return{stopped:Ye(e,"stopped")}}function xo(e){const t=x(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:Ci(t.sessionIds,"sessionIds"),s=ne(t,"archivedCount"),r=ne(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...r===void 0?{}:{skippedAlreadyArchivedCount:r}}}function Jd(e){return{restored:Ye(e,"restored")}}function Qd(e){return{deleted:Ye(e,"deleted")}}function Zd(e){return{detached:Ye(e,"detached")}}function Xd(e){return{reloaded:Ye(e,"reloaded")}}function So(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 Yd(e){return typeof e=="string"?e:e.id}function ep(e){return typeof e=="string"?void 0:e.cwd}function tp(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 ip(e,t,i="local"){const s=new URLSearchParams,r=ep(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(Yd(e))}/messages${o===""?"":`?${o}`}`}function sp(e,t,i,s){const r=new URLSearchParams({path:i});return s?.createDirs===!1&&r.set("createDirs","false"),s?.overwrite===!1&&r.set("overwrite","false"),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`}function rp(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 fa(e,t,i,s){const r=new URLSearchParams;r.set("path",i);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return oa(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${r.toString()}`)}const C=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function op(e){return typeof e=="string"?e:e.id}function ga(e){return typeof e=="string"?void 0:e.cwd}function ma(e,t="local"){return`${C(t)}/sessions/${encodeURIComponent(op(e))}`}function G(e,t,i="local"){return`${ma(e,i)}/${t}`}function si(e,t,i="local"){return`${G(e,t,i)}${va(e)}`}function np(e,t="local"){return`${ma(e,t)}${va(e)}`}function va(e){const t=ga(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function Q(e,t={}){const i=ga(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}const ba={piWebStatus:(e="local")=>w(e==="local"?"/api/pi-web/status":`${C(e)}/pi-web/status`,Nc),piWebRuntime:()=>w("/api/pi-web/runtime",Hc)},ap={machines:()=>w("/api/machines",Xc),addMachine:e=>w("/api/machines",la,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>w(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>w(`/api/machines/${encodeURIComponent(e)}/health`,Yc),runtime:e=>w(`/api/machines/${encodeURIComponent(e)}/runtime`,ed)},Ri={config:()=>w("/api/config",uo),saveConfig:e=>w("/api/config",uo,{method:"PUT",body:JSON.stringify({config:e})})},qs={plugins:()=>w("/api/plugins",Uc)},wa={workspaceActivity:(e="local")=>w(`${C(e)}/activity`,Bd)},lp={projects:(e="local")=>w(`${C(e)}/projects`,F(vo)),addProject:(e,t,i,s="local")=>w(`${C(s)}/projects`,vo,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>w(`${C(t)}/projects/${encodeURIComponent(e)}`,Hs,{method:"DELETE"}),projectDirectories:(e,t="local")=>w(`${C(t)}/project-directories?q=${encodeURIComponent(e)}`,F(Ns))},wt={workspaces:(e,t="local")=>w(`${C(t)}/projects/${e}/workspaces`,F(rd)),deleteWorkspace:(e,t,i="local")=>w(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Bt,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Td),workspaceFile:(e,t,i,s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Ed),uploadWorkspaceFile:async(e,t,i,s,r="local")=>r==="local"?up(e,t,i,s):w(`${C(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,zs,{method:"POST",body:JSON.stringify({path:i,contentBase64:await pp(s)})}),createWorkspaceFile:(e,t,i,s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,zs,{method:"POST",body:JSON.stringify({path:i,contentBase64:""})}),writeWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({path:i});r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!1&&n.set("overwrite","false");const a=s instanceof Uint8Array,c=a?new Uint8Array(s):new TextEncoder().encode(s);return w(`${C(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${n.toString()}`,ha,{method:"PUT",body:c,headers:{"Content-Type":a?"application/octet-stream":"text/plain"}})},deleteWorkspaceFile:(e,t,i,s="local")=>{const r=new URLSearchParams({path:i});return w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`,Dd,{method:"DELETE"})},moveWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({fromPath:i,toPath:s});return r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!0&&n.set("overwrite","true"),w(`${C(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${n.toString()}`,Wd,{method:"POST"})},createWorkspaceDirectory:(e,t,i,s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,bo,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,r="local")=>w(`${C(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,bo,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,nd,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>fa(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>fp(e,t,i,s)},Ks={sessions:(e,t="local")=>w(`${C(t)}/sessions?cwd=${encodeURIComponent(e)}`,F(Bs)),startSession:(e,t="local")=>w(`${C(t)}/sessions`,Bs,{method:"POST",body:JSON.stringify({cwd:e})}),cleanupPreview:(e,t="local")=>w(`${C(t)}/sessions/cleanup/preview`,da,{method:"POST",body:JSON.stringify(e)}),cleanup:(e,t="local")=>w(`${C(t)}/sessions/cleanup`,ad,{method:"POST",body:JSON.stringify(e)}),messages:(e,t,i="local")=>w(ip(e,t,i),sd),status:(e,t="local")=>w(si(e,"status",t),Tt),models:(e,t="local")=>w(si(e,"models",t),md),setModel:(e,t,i,s="local")=>w(G(e,"model",s),Tt,{method:"POST",body:Q(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>w(G(e,"model/cycle",i),Tt,{method:"POST",body:Q(e,{direction:t})}),thinkingLevels:(e,t="local")=>w(si(e,"thinking-levels",t),bd),setThinkingLevel:(e,t,i="local")=>w(G(e,"thinking-level",i),Tt,{method:"POST",body:Q(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>w(G(e,"thinking-level/cycle",t),Tt,{method:"POST",body:Q(e)}),commands:(e,t="local")=>w(si(e,"commands",t),F(Ad)),prompt:(e,t,i,s="local",r)=>w(G(e,"prompt",s),ii,{method:"POST",body:Q(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...r!==void 0&&r.length>0?{attachments:r}:{}})}),saveAttachments:(e,t,i="local",s)=>w(G(e,"attachments",i),qd,{method:"POST",body:Q(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>w(G(e,"shell",i),ii,{method:"POST",body:Q(e,{text:t})}),runCommand:(e,t,i="local")=>w(G(e,"commands/run",i),yo,{method:"POST",body:Q(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>w(G(e,"commands/respond",s),yo,{method:"POST",body:Q(e,{requestId:t,value:i})}),abort:(e,t="local")=>w(G(e,"abort",t),Vd,{method:"POST",body:Q(e)}),stop:(e,t="local")=>w(G(e,"stop",t),Gd,{method:"POST",body:Q(e)}),archive:(e,t="local")=>w(G(e,"archive",t),xo,{method:"POST",body:Q(e)}),archiveWithDescendants:(e,t="local")=>w(G(e,"archive-tree",t),xo,{method:"POST",body:Q(e)}),restore:(e,t="local")=>w(G(e,"restore",t),Jd,{method:"POST",body:Q(e)}),deleteArchived:(e,t="local")=>w(np(e,t),Qd,{method:"DELETE"}),detachParent:(e,t="local")=>w(G(e,"detach-parent",t),Zd,{method:"POST",body:Q(e)}),reloadSession:(e,t="local")=>w(G(e,"reload",t),Xd,{method:"POST",body:Q(e)}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return w(`${C(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,kd)},saveApiKey:(e,t,i="local")=>w(`${C(i)}/auth/api-key`,ii,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>w(`${C(t)}/auth/logout`,ii,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>w(`${C(t)}/auth/oauth`,ti,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>w(`${C(t)}/auth/oauth/${encodeURIComponent(e)}`,ti),respondOAuthFlow:(e,t,i,s="local")=>w(`${C(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,ti,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>w(`${C(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,ti,{method:"POST"})},yt={terminals:(e,t,i="local")=>w(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,F(fs)),startTerminal:(e,t,i,s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,fs,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>w(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Hs,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,Hs,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,fs,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>w(`${C(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Bt,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>w(`${C(t)}/terminal-command-runs${dp(e)}`,F(Bt)),getCommandRun:(e,t="local")=>cp(e,t),cancelCommandRun:(e,t="local")=>w(`${C(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Bt,{method:"POST"})};async function cp(e,t){const i=await fetch(`${C(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(gr(s)??i.statusText)}return Bt(await i.json())}}function dp(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 gr(e){if(!gp(e))return;const t=e.error;return typeof t=="string"?t:void 0}async function pp(e){return hp(await e.arrayBuffer())}function hp(e){const t=new Uint8Array(e);let i="";for(const s of t)i+=String.fromCharCode(s);return btoa(i)}async function up(e,t,i,s){const r=new FormData;r.set("path",i),r.set("file",s,s.name);const o=await fetch(`${C("local")}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,{method:"POST",body:r});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(gr(n)??o.statusText)}return zs(await o.json())}async function fp(e,t,i,s){const r=await fetch(fa(e,t,i,{machineId:s}));if(!r.ok){const p=await r.json().catch(()=>({}));throw new Error(gr(p)??r.statusText)}const o=await r.blob(),n=URL.createObjectURL(o),a=document.createElement("a");a.href=n;const c=i.split("/").pop();a.download=c===void 0||c===""?"download":c,document.body.append(a),a.click(),a.remove(),URL.revokeObjectURL(n)}function gp(e){return typeof e=="object"&&e!==null}const mp={files:(e,t,i={})=>{const s=new URLSearchParams({q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),i.workspaceScoped===!0&&i.projectId!==void 0&&i.workspaceId!==void 0?w(`${C(i.machineId)}/projects/${encodeURIComponent(i.projectId)}/workspaces/${encodeURIComponent(i.workspaceId)}/files?${s.toString()}`,F(Ns)):(s.set("cwd",e),w(`${C(i.machineId)}/files?${s.toString()}`,F(Ns)))}},vp={gitStatus:(e,t,i="local")=>w(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,_d),gitDiff:(e,t,i,s="local")=>w(tp(s,e,t,i),jd)},N={...ba,...ap,...Ri,...qs,...wa,...lp,...wt,...Ks,...yt,...mp,...vp};function bp(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(`${vr()}${mr(t)}/sessions/${encodeURIComponent(r)}/events${s}`)}function K0(e,t,i,s,r="local"){const o=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${vr()}${mr(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${o}`)}function wp(e="local"){return new WebSocket(`${vr()}${mr(e)}/events`)}function mr(e){return`/api/machines/${encodeURIComponent(e)}`}function vr(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}const ya=".pi-web/uploads";class Ji extends Error{constructor(t="Workspace upload cancelled"){super(t),this.name="WorkspaceUploadCancelledError"}}class xa extends Error{constructor(t,i){super(Rp(t)),this.name="WorkspaceUploadBatchError",this.failures=t.map(s=>({...s})),this.responses=i.map(s=>({...s}))}}function ko(e){return e?.uploads?.defaultFolder??ya}function yp(e,t){return e?.uploads?.defaultFolder??t}function br(e,t){const i=$o(e,"upload destination",{allowEmpty:!0}),s=$o(t,"upload file name",{allowEmpty:!1});return i===""?s:`${i}/${s}`}function xp(e,t,i,s={}){const r=s.xhrFactory?.()??new XMLHttpRequest;let o=!1,n=!1;return{promise:new Promise((c,p)=>{const u=g=>{o||(o=!0,p(g))},h=g=>{o||(o=!0,c(g))};r.open("PUT",sp(e,t,i.path,$p(s)),!0),r.responseType="json",r.setRequestHeader("Content-Type",(i.contentType??i.file.type)||"application/octet-stream"),r.upload.onprogress=g=>{s.onProgress?.(Pp(g,i.file.size))},r.onload=()=>{if(r.status>=200&&r.status<300){try{s.onProgress?.({loaded:i.file.size,total:i.file.size,percent:1,lengthComputable:!0}),h(ha(Sa(r)))}catch(g){u(g instanceof Error?g:new Error(String(g)))}return}u(new Error(Mp(r)))},r.onerror=()=>{u(new Error("Workspace upload failed"))},r.onabort=()=>{u(new Ji(n?void 0:"Workspace upload aborted"))},r.send(i.file)}),cancel:()=>{o||(n=!0,r.abort())}}}function Sp(e,t,i,s={}){const r=s.destinationFolder??ya,o=i.map((h,g)=>({index:g,name:h.name,path:br(r,h.name),loaded:0,total:h.size,percent:wr(0,h.size),lengthComputable:!0,done:!1}));let n,a=0;const c={requested:!1},p=()=>{s.onProgress?.(Cp(o,a,o.every(h=>h.done)))};return{promise:(async()=>{const h=[],g=[];for(let b=0;b<i.length;b+=1){if(c.requested)throw new Ji;a=b;const P=i[b],R=o[b];if(!(P===void 0||R===void 0)){n=xp(e,t,{path:R.path,file:P},{...kp(s),onProgress:V=>{R.total=V.total,R.loaded=Math.min(V.loaded,R.total),R.percent=V.percent,R.lengthComputable=V.lengthComputable,p()}});try{const V=await n.promise;R.loaded=R.total,R.percent=1,R.lengthComputable=!0,R.done=!0,h.push(V),p()}catch(V){if(Ap(V,c))throw V;const Ve=Ip(V);R.loaded=R.total,R.percent=1,R.lengthComputable=!0,R.done=!0,R.error=Ve,g.push({index:b,name:P.name,path:R.path,error:Ve}),p()}finally{n=void 0}}}if(g.length>0)throw new xa(g,h);return h})(),cancel:()=>{c.requested=!0,n?.cancel()}}}function kp(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function $p(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Pp(e,t){const i=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:i,percent:wr(e.loaded,i),lengthComputable:e.lengthComputable}}function Cp(e,t,i){const s=e.reduce((o,n)=>o+n.total,0),r=e.reduce((o,n)=>o+n.loaded,0);return{currentFileIndex:t,files:e.map(o=>({...o})),loaded:r,total:s,percent:wr(r,s),done:i}}function wr(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Rp(e){return e.length===1?e[0]?.error??"Workspace upload failed":`${String(e.length)} files failed to upload`}function Ip(e){return e instanceof Error?e.message:String(e)}function Ap(e,t){return t.requested||e instanceof Ji}function $o(e,t,i){const s=e.trim();if(s===""){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(Tp(s))throw new Error(`${t} must be workspace-relative`);const r=s.split(/[\\/]+/u).filter(o=>o!==""&&o!==".");if(r.length===0){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(r.some(o=>o===".."))throw new Error(`${t} must not contain path traversal`);return r.join("/")}function Tp(e){const t=e.replace(/\\/g,"/");return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}function Sa(e){return e.response!==void 0&&e.response!==null&&e.response!==""?e.response:e.responseText===""?{}:JSON.parse(e.responseText)}function Mp(e){const t=Ep(e);return Dp(t)&&typeof t.error=="string"?t.error:e.statusText||`HTTP ${String(e.status)}`}function Ep(e){try{return Sa(e)}catch{return}}function Dp(e){return typeof e=="object"&&e!==null}function fi(){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 Wp(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Xe(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function ka(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const $a="local";function gs(e,t){return`${e}:${t}`}function Pa(e,t){return`${e}:${t}`}function f(e){return e.selectedMachine?.id??$a}class Op{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??wa}async refresh(t=f(this.getState())){this.applyMachineActivitySnapshot(t,_p(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=Lp(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 _p(e){const t={};for(const i of e.workspaces)ka(i)&&(t[i.cwd]=i);return t}function Lp(e,t){const i={...e};return ka(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class jp{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=r.api??N,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=Fp(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:f(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const r=s.providers.find(o=>o.id===t&&(i===void 0||o.authType===i));r!==void 0&&(r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({authDialog:{...t,saving:!1,error:String(r)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:f(this.getState())});if(t!==void 0&&t!==""){const s=i.find(r=>r.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(r=>r.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({error:String(r)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const r=t??i.inputValue??"",o={...i};delete o.error,this.setState({authDialog:{...o,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,r,f(this.getState()));this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...i,responding:!1,error:String(n)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,f(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:f(this.getState())}),s=i.filter(o=>o.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const r=s[0];if(r===void 0)return;r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,f(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const r=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${r}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",r=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,o=t.prompt?.requestId??t.select?.requestId,n=r!==void 0&&r===o,a=n?s:"",c=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:c}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t,f(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.session();if(t!==void 0)try{this.applyStatus(await this.api.status(t,f(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function Fp(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 Gt(e){return e.replaceAll(":",".")}function Up(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 ms(e,t){const i=Up(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function he(e,t,i,s){const r=new URL(window.location.href),o=`${e}--${t}`;if(r.searchParams.delete(o),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)r.searchParams.append(o,String(n));else r.searchParams.set(o,String(i));zp(r,s)}function zp(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}function Bp(e){const t=e.files.map((s,r)=>{const o=s.size;return{index:r,name:s.name,path:br(e.destinationFolder,s.name),size:s.size,loaded:0,total:o,percent:Co(0,o),lengthComputable:!0,status:r===0?"uploading":"pending"}}),i=t.reduce((s,r)=>s+r.total,0);return{id:e.id,projectId:e.projectId,workspaceId:e.workspaceId,machineId:e.machineId,destinationFolder:e.destinationFolder,overwrite:e.overwrite,createDirs:e.createDirs,files:t,currentFileIndex:t.length===0?-1:0,loaded:0,total:i,percent:Co(0,i),status:"uploading",startedAt:e.startedAt}}function Np(e,t){const i=new Map(t.files.map(r=>[r.index,r])),s=e.files.map(r=>{const o=i.get(r.index);if(o===void 0)return r;const n={...r,path:o.path,loaded:o.loaded,total:o.total,percent:o.percent,lengthComputable:o.lengthComputable,status:o.error!==void 0?"error":o.done?"completed":t.currentFileIndex===r.index?"uploading":r.status};return o.error===void 0?delete n.error:n.error=o.error,n});return{...e,files:s,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function Hp(e,t,i){const s=e.files.map((o,n)=>{const a=t[n];return{...o,...a===void 0?{}:{path:a.path,response:a},loaded:o.total,percent:1,lengthComputable:!0,status:"completed"}}),r=yr(s);return{...e,files:s,currentFileIndex:s.length===0?-1:s.length-1,...r,status:"completed",completedAt:i}}function qp(e,t,i){const s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:r.status==="uploading"||r.index===e.currentFileIndex?{...r,status:"error",error:t}:{...r,status:"cancelled",error:"Not uploaded because an earlier file failed."});return{...e,files:s,...yr(s),status:"error",error:t,completedAt:i}}function Po(e,t){const i="Upload cancelled",s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:{...r,status:"cancelled",error:i});return{...e,files:s,...yr(s),status:"cancelled",error:i,completedAt:t}}function yr(e){const t=e.reduce((i,s)=>i+s.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function Co(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}const ri=Gt("core:workspace.files");class Kp{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??N,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??Sp,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=f(this.getState()),r=await this.api.workspaceTree(t.id,i.id,"",s),o=await Promise.all(Object.keys(this.getState().expandedDirs).map(async a=>{try{const c=await this.api.workspaceTree(t.id,i.id,a,s);return[a,c.entries]}catch(c){if(Ro(c))return;throw c}})),n=Object.fromEntries(o.filter(a=>a!==void 0));this.setState({fileTree:r.entries,expandedDirs:n,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:Io(this.getState().expandedDirs,t)});return}try{const r=await this.api.workspaceTree(i.id,s.id,t,f(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:r.entries},error:""})}catch(r){this.setState({error:String(r)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),he(ri,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}selectDirectory(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),he(ri,"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(Ro(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),he(ri,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}async createFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceFile(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),await this.selectFile(t),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async createDirectory(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceDirectory(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),this.selectDirectory(t),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async moveSelectedPath(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace,r=this.getState().selectedFilePath;if(!(i===void 0||s===void 0||r===void 0||r===""||t===""))try{const o=f(this.getState());vs(this.getState())==="directory"?(await this.api.moveWorkspaceDirectory(i.id,s.id,r,t,o),await this.refreshFiles(),this.selectDirectory(t)):(await this.api.moveWorkspaceFile(i.id,s.id,r,t,void 0,o),await this.refreshFiles(),await this.selectFile(t)),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async deleteSelectedPath(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""))try{const r=f(this.getState());vs(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===""||vs(this.getState())==="directory"))try{await this.api.downloadWorkspaceFile(t.id,i.id,s,f(this.getState())),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),he(ri,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}startWorkspaceUpload(t,i){const s=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(s===void 0||r===void 0){this.setState({error:"Select a workspace before uploading files."});return}if(t.length===0)return;const o=f(this.getState()),n=i.overwrite??!1,a=i.createDirs??!0;let c;try{c=Bp({id:this.createUploadBatchId(),projectId:s.id,workspaceId:r.id,machineId:o,destinationFolder:i.destinationFolder,overwrite:n,createDirs:a,files:t,startedAt:this.now()})}catch(h){this.setState({error:String(h)});return}this.setUploadBatch(c);let p;try{p=this.uploadWorkspaceFiles(s.id,r.id,t,{destinationFolder:i.destinationFolder,machineId:o,overwrite:n,createDirs:a,onProgress:h=>{this.updateUploadProgress(c.id,h)}})}catch(h){return this.failUploadBatch(c.id,h),{batchId:c.id,done:Promise.resolve()}}this.uploadTasks.set(c.id,p);const u=p.promise.then(async h=>{await this.completeUploadBatch(c.id,h,i)}).catch(async h=>{await this.handleUploadFailure(c.id,h,i)}).finally(()=>{this.uploadTasks.delete(c.id)});return{batchId:c.id,done:u}}cancelWorkspaceUpload(t){const i=this.getUploadBatch(t);i?.status==="uploading"&&(this.setUploadBatch(Po(i,this.now())),this.uploadTasks.get(t)?.cancel())}clearWorkspaceUpload(t){this.uploadTasks.get(t)?.cancel(),this.uploadTasks.delete(t),this.setState({workspaceUploadBatches:Io(this.getState().workspaceUploadBatches,t)})}updateUploadProgress(t,i){const s=this.getUploadBatch(t);s?.status==="uploading"&&this.setUploadBatch(Np(s,i))}async completeUploadBatch(t,i,s){const r=this.getUploadBatch(t);if(r?.status!=="uploading"||(this.setUploadBatch(Hp(r,i,this.now()),{error:""}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();const o=i[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}async handleUploadFailure(t,i,s){const r=this.failUploadBatch(t,i);if(!(i instanceof xa)||i.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshFiles();const o=i.responses[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}failUploadBatch(t,i){const s=this.getUploadBatch(t);if(s?.status!=="uploading")return;if(Vp(i)){const n=Po(s,this.now());return this.setUploadBatch(n),n}const r=Gp(i),o=qp(s,r,this.now());return this.setUploadBatch(o,{error:r}),o}getUploadBatch(t){return this.getState().workspaceUploadBatches[t]}setUploadBatch(t,i={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[t.id]:t},...i})}isCurrentWorkspaceBatch(t){const i=this.getState();return i.selectedProject?.id===t.projectId&&i.selectedWorkspace?.id===t.workspaceId&&f(i)===t.machineId}}function Ro(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function Vp(e){return e instanceof Ji}function Gp(e){return e instanceof Error?e.message:String(e)}function Io(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function vs(e){const t=e.selectedFilePath;return t===void 0?"file":Jp(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function Jp(e,t,i){const s=e.find(r=>r.path===i);if(s!==void 0)return s;for(const r of Object.values(t)){const o=r.find(n=>n.path===i);if(o!==void 0)return o}}const Ao=Gt("core:workspace.git");class Qp{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await N.gitStatus(t.id,i.id,f(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const r=this.getState().selectedDiffPath;r!==void 0&&(s.files.some(o=>o.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),he(Ao,"diff",void 0,{replace:!0})))}catch(s){this.setState({error:String(s)})}}async selectDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),he(Ao,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[r,o]=await Promise.all([N.gitDiff(i.id,s.id,{path:t},f(this.getState())),N.gitDiff(i.id,s.id,{path:t,staged:!0},f(this.getState()))]);this.setState({selectedDiff:r,selectedStagedDiff:o,error:""})}catch(r){this.setState({error:String(r)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class Zp{constructor(t,i,s,r){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=r}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await N.machines(),s=await this.selectInitialMachine(i,t),r=new Set(i.map(o=>o.id));this.setState({machines:i,selectedMachine:s,machineActivities:To(this.getState().machineActivities,r),machineRuntimes:To(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,...fi()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await N.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await N.deleteMachine(t.id);const r=this.getState().machines.filter(n=>n.id!==t.id),o=r.find(n=>n.id==="local")??r[0];return this.setState({machines:r,machineStatuses:bs(this.getState().machineStatuses,t.id),machineRuntimes:bs(this.getState().machineRuntimes,t.id),machineActivities:bs(this.getState().machineActivities,t.id)}),s&&o!==void 0?(i.selectFallback===!1||await this.selectMachine(o),o):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await N.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await N.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(o=>o.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const r=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await N.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(r=>N.health(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(r=>N.runtime(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function bs(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function To(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class Xp{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=f(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await N.projects(t);if(f(this.getState())!==t)return;const s=new Set(i.map(o=>o.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([o])=>s.has(o)));this.setState({projects:i,workspacesByProjectId:r})}catch(i){f(this.getState())===t&&this.setState({error:String(i)})}finally{f(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await N.addProject(t.trim(),void 0,i,f(this.getState())),r=this.getState().projects;this.setState({projects:[...r.filter(o=>o.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await N.closeProject(t,f(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const Vs="pi-web:cached-new-sessions:v1",Yp="browserCachedNew",Ct="local";function Jt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Mo(e,t=Ct,i=Jt()){if(e.messageCount!==0||e.archived===!0)return;const s=xr(i).filter(r=>r.id!==e.id||r.machineId!==t);Sr([Gs(e,t),...s],i)}function Gs(e,t=Ct){return{...e,browserCachedNew:!0,machineId:t}}function Eo(e,t=Ct,i=Jt()){const s=xr(i).filter(r=>r.id!==e||r.machineId!==t);Sr(s,i)}function Ca(e,t,i=Ct,s=Jt()){const r=new Set(t.map(c=>c.id)),o=xr(s),n=o.filter(c=>c.machineId!==i||!r.has(c.id));return n.length!==o.length&&Sr(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function Z(e){return e===void 0?!1:ih(e)&&e.browserCachedNew===!0}function eh(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:Ct},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function xr(e=Jt()){try{const t=e?.getItem(Vs);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>th(s)):[]}catch{return[]}}function Sr(e,t=Jt()){try{e.length===0?t?.removeItem(Vs):t?.setItem(Vs,JSON.stringify(e))}catch{}}function th(e){if(!sh(e))return[];const t=gt(e,"id"),i=gt(e,"path"),s=gt(e,"cwd"),r=gt(e,"created"),o=gt(e,"modified"),n=gt(e,"firstMessage"),a=rh(e,"messageCount");if(t===void 0||i===void 0||s===void 0||r===void 0||o===void 0||n===void 0||a!==0)return[];const c=ws(e,"name"),p=ws(e,"parentSessionPath"),u=ws(e,"machineId")??Ct;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:r,modified:o,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function ih(e){return Yp in e}function sh(e){return typeof e=="object"&&e!==null}function gt(e,t){const i=e[t];return typeof i=="string"?i:void 0}function ws(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function rh(e,t){const i=e[t];return typeof i=="number"?i:void 0}function oh(e){return xh(e.flatMap(kr)).filter(t=>t.parts.length>0)}function Oe(e,t){return{role:e,parts:[{type:"text",text:t}]}}function Mt(e,t){const i=uh(t);return i===void 0?e:{...e,meta:i}}function nh(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,Oe(t,i)]}function ah(e,t){if(t==="")return e;const i=e.at(-1),s=i?.parts.at(-1);return i?.role==="assistant"&&s?.type==="thinking"?[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+t}]}]:i?.role==="assistant"?[...e.slice(0,-1),{...i,parts:[...i.parts,{type:"thinking",text:t}]}]:[...e,{role:"assistant",parts:[{type:"thinking",text:t}]}]}function kr(e){if(ch(e))return[e];if(_(e,"role")==="bashExecution")return[Mt(mh(e),e)];const t=vh(_(e,"role")),i=bh(ye(e,"content"),e),s=t==="user"?dh(i):void 0;if(s!==void 0)return s.map(p=>Mt(p,e));const r=hh(e);if(t==="tool")return[Mt({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?[Mt({role:n,parts:o,...r===void 0?{}:{source:r}},e)]:[],c=lh(e);return c===void 0?a:[...a,Mt(c,e)]}function lh(e){if(_(e,"role")!=="assistant"||_(e,"stopReason")!=="error")return;const t=_(e,"errorMessage")?.trim();return Oe("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function ch(e){const t=_(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(ye(e,"parts"))}function dh(e){if(e.length!==1||e[0]?.type!=="text")return;const t=ph(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 ph(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 hh(e){const t=_(e,"source");if(t==="compaction"||t==="branch_summary")return t}function uh(e){const t=fh(ye(e,"timestamp")),i=gh(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function fh(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 gh(e){if(_(e,"role")!=="assistant")return;const t=_(e,"provider"),i=_(e,"model"),s=_(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function mh(e){const t=_(e,"command")??"",i=gi(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=ye(e,"output");s!=null&&i.push("",Ai(s));const r=ye(e,"exitCode");r!=null&&i.push("",`exit ${Ai(r)}`),gi(e,"cancelled")===!0&&i.push("","cancelled"),gi(e,"truncated")===!0&&i.push("","output truncated");const o=_(e,"fullOutputPath");return o!==void 0&&o!==""&&i.push("",`full output: ${o}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
- `)}]}}function vh(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function bh(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=_(i,"type"),r=_(i,"text");if(s==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(s==="thinking"){const o=_(i,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}if(s==="toolCall"){const o=_(i,"name")??"tool",n=ye(i,"arguments"),a=_(i,"id"),c=o==="read"?yh(_(n,"path")):void 0;return c!==void 0?[{type:"skillRead",...c,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:o,summary:Qt(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const o=_(i,"data"),n=_(i,"mimeType");return o!==void 0&&o!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:o}]:[{type:"text",text:"[image]"}]}return Do(i)}).map(i=>i.type==="text"&&_(t,"role")==="toolResult"?wh(i.text,t):i):Do(e)}function wh(e,t){const i=_(t,"toolCallId"),s=ye(t,"content"),r=ye(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:_(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...r===void 0?{}:{details:r},isError:gi(t,"isError")===!0}}function yh(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 xh(e){const t=[],i=new Map;for(const s of e){let r=[];const o={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{r.length!==0&&(t.push({role:s.role,parts:r,...o}),r=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=Sh(a),p=t.length;t.push({role:"tool",parts:[c],...o}),c.toolCallId!==void 0&&i.set(c.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const c=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(c!==void 0&&kh(t,c,a)){i.delete(a.toolCallId??"");continue}}r.push(a)}n()}return t}function Sh(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 kh(e,t,i){const s=e[t.lineIndex],r=s?.parts[t.partIndex];if(s===void 0||r?.type!=="toolExecution")return!1;const o=Ii(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 Ii(e){const t=ye(e,"preview");if(!$r(t))return;const i=_(t,"diff"),s=_(t,"error"),r=Ph(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 Do(e){return e==null?[]:typeof e=="object"?[{type:"text",text:Qt(e)}]:[{type:"text",text:Ai(e)}]}function Qt(e){if(!$r(e))return Ai(e);const t=_(e,"command");if(t!==void 0)return t;const i=_(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} edit${s.length===1?"":"s"}`:Object.entries(e).filter(([,o])=>o!=null).slice(0,3).map(([o,n])=>`${o}: ${$h(n)}`).join(" · ")}function $h(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 $r(e){return typeof e=="object"&&e!==null}function ye(e,t){return $r(e)?e[t]:void 0}function _(e,t){const i=ye(e,t);return typeof i=="string"?i:void 0}function gi(e,t){const i=ye(e,t);return typeof i=="boolean"?i:void 0}function Ph(e,t){const i=ye(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function Ai(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const Ch="pi-web:prompt-draft:";function Ti(e){return`${Ch}${e}`}function Qi(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Ra(e,t=Qi()){try{return t?.getItem(Ti(e))??""}catch{return""}}function Mi(e,t,i=Qi()){try{t?i?.setItem(Ti(e),t):i?.removeItem(Ti(e))}catch{}}function Pr(e,t=Qi()){try{t?.removeItem(Ti(e))}catch{}}function Rh(e,t,i=Qi()){const s=Ra(e,i);s!==""&&(Mi(t,s,i),Pr(e,i))}function Ih(e,t){return Oe("bash",`${t===!0?`不加入上下文
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),co=/'/g,po=/"/g,na=/^(?:script|style|textarea|title)$/i,aa=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=aa(1),be=aa(2),Ze=Symbol.for("lit-noChange"),z=Symbol.for("lit-nothing"),ho=new WeakMap,nt=ct.createTreeWalker(ct,129);function la(e,t){if(!hr(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return no!==void 0?no.createHTML(t):t}const vc=(e,t)=>{const i=e.length-1,s=[];let r,o=t===2?"<svg>":t===3?"<math>":"",n=At;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,g=0;for(;g<c.length&&(n.lastIndex=g,u=n.exec(c),u!==null);)g=n.lastIndex,n===At?u[1]==="!--"?n=ao:u[1]!==void 0?n=lo:u[2]!==void 0?(na.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=it):u[3]!==void 0&&(n=it):n===it?u[0]===">"?(n=r??At,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?it:u[3]==='"'?po:co):n===po||n===co?n=it:n===ao||n===lo?n=At:(n=it,r=void 0);const b=n===it&&e[a+1].startsWith("/>")?" ":"";o+=n===At?c+gc:h>=0?(s.push(p),c.slice(0,h)+ra+c.slice(h)+Je+b):c+Je+(h===-2?a:b)}return[la(e,o+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class qt{constructor({strings:t,_$litType$:i},s){let r;this.parts=[];let o=0,n=0;const a=t.length-1,c=this.parts,[p,u]=vc(t,i);if(this.el=qt.createElement(p,s),nt.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(r=nt.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const h of r.getAttributeNames())if(h.endsWith(ra)){const g=u[n++],b=r.getAttribute(h).split(Je),P=/([.?@])?(.*)/.exec(g);c.push({type:1,index:o,name:P[2],strings:b,ctor:P[1]==="."?wc:P[1]==="?"?yc:P[1]==="@"?xc:Gi}),r.removeAttribute(h)}else h.startsWith(Je)&&(c.push({type:6,index:o}),r.removeAttribute(h));if(na.test(r.tagName)){const h=r.textContent.split(Je),g=h.length-1;if(g>0){r.textContent=$i?$i.emptyScript:"";for(let b=0;b<g;b++)r.append(h[b],Nt()),nt.nextNode(),c.push({type:2,index:++o});r.append(h[g],Nt())}}}else if(r.nodeType===8)if(r.data===oa)c.push({type:2,index:o});else{let h=-1;for(;(h=r.data.indexOf(Je,h+1))!==-1;)c.push({type:7,index:o}),h+=Je.length-1}o++}}static createElement(t,i){const s=ct.createElement("template");return s.innerHTML=t,s}}function St(e,t,i=e,s){if(t===Ze)return t;let r=s!==void 0?i._$Co?.[s]:i._$Cl;const o=Ht(t)?void 0:t._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(e),r._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=r:i._$Cl=r),r!==void 0&&(t=St(e,r._$AS(e,t.values),r,s)),t}class bc{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,r=(t?.creationScope??ct).importNode(i,!0);nt.currentNode=r;let o=nt.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new Pt(o,o.nextSibling,this,t):c.type===1?p=new c.ctor(o,c.name,c.strings,this,t):c.type===6&&(p=new Sc(o,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(o=nt.nextNode(),n++)}return nt.currentNode=ct,r}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class Pt{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,r){this.type=2,this._$AH=z,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=St(this,t,i),Ht(t)?t===z||t==null||t===""?(this._$AH!==z&&this._$AR(),this._$AH=z):t!==this._$AH&&t!==Ze&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):mc(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==z&&Ht(this._$AH)?this._$AA.nextSibling.data=t:this.T(ct.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,r=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=qt.createElement(la(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(i);else{const o=new bc(r,this),n=o.u(this.options);o.p(i),this.T(n),this._$AH=o}}_$AC(t){let i=ho.get(t.strings);return i===void 0&&ho.set(t.strings,i=new qt(t)),i}k(t){hr(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 Pt(this.O(Nt()),this.O(Nt()),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=oo(t).nextSibling;oo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Gi=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,r,o){this.type=1,this._$AH=z,this._$AN=void 0,this.element=t,this.name=i,this._$AM=r,this.options=o,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=z}_$AI(t,i=this,s,r){const o=this.strings;let n=!1;if(o===void 0)t=St(this,t,i,0),n=!Ht(t)||t!==this._$AH&&t!==Ze,n&&(this._$AH=t);else{const a=t;let c,p;for(t=o[0],c=0;c<o.length-1;c++)p=St(this,a[s+c],i,c),p===Ze&&(p=this._$AH[c]),n||=!Ht(p)||p!==this._$AH[c],p===z?t=z:t!==z&&(t+=(p??"")+o[c+1]),this._$AH[c]=p}n&&!r&&this.j(t)}j(t){t===z?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},wc=class extends Gi{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===z?void 0:t}},yc=class extends Gi{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==z)}},xc=class extends Gi{constructor(t,i,s,r,o){super(t,i,s,r,o),this.type=5}_$AI(t,i=this){if((t=St(this,t,i,0)??z)===Ze)return;const s=this._$AH,r=t===z&&s!==z||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,o=t!==z&&(s===z||r);r&&this.element.removeEventListener(this.name,this,s),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Sc=class{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){St(this,t)}};const kc={I:Pt},$c=pr.litHtmlPolyfillSupport;$c?.(qt,Pt),(pr.litHtmlVersions??=[]).push("3.3.3");const Pc=(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 Pt(t.insertBefore(Nt(),o),o,void 0,i??{})}return r._$AI(e),r};const ur=globalThis;let A=class extends bt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=Pc(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ze}};A._$litElement$=!0,A.finalized=!0,ur.litElementHydrateSupport?.({LitElement:A});const Cc=ur.litElementPolyfillSupport;Cc?.({LitElement:A});(ur.litElementVersions??=[]).push("4.2.2");const W=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const Ic={attribute:!0,type:String,converter:ki,reflect:!1,hasChanged:dr},Rc=(e=Ic,t,i)=>{const{kind:s,metadata:r}=i;let o=globalThis.litPropertyMetadata.get(r);if(o===void 0&&globalThis.litPropertyMetadata.set(r,o=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),o.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,c,e,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,e,a),a}}}if(s==="setter"){const{name:n}=i;return function(a){const c=this[n];t.call(this,a),this.requestUpdate(n,c,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?Rc(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 ca(e,t=Mc()){if(t===void 0)return e;const i=Tc(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 Tc(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 Mc(){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 w(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&!s.has("content-type")&&s.set("content-type","application/json");const r=await fetch(ca(e),{...i,headers:s});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(Ec(n)??r.statusText)}const o=await r.json();return t(o)}function Ec(e){if(Dc(e))return typeof e.error=="string"?e.error:void 0}function Dc(e){return typeof e=="object"&&e!==null}function ze(e){return typeof e=="object"&&e!==null}function x(e){if(!ze(e))throw new Error("Expected object response");return e}function m(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function $(e,t){const i=e[t];if(i!==void 0){if(typeof i!="string")throw new Error(`Expected optional string field: ${t}`);return i}}function q(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function ne(e,t){const i=e[t];if(i!==void 0){if(typeof i!="number")throw new Error(`Expected optional number field: ${t}`);return i}}function D(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function F(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function Ye(e,t){if(x(e)[t]!==!0)throw new Error(`Expected ${t} response`);return!0}function v(e,t){return t===void 0?{}:{[e]:t}}const Qe={sessionsDeleteArchived:"sessions.deleteArchived",sessionsCleanup:"sessions.cleanup",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments",workspaceFileSuggestions:"workspace.fileSuggestions"},Wc=Object.values(Qe),Oc=new Set(Wc);function _c(e){return typeof e=="string"&&Oc.has(e)}function at(e,t){return e?.capabilities?.includes(t)===!0}function uo(e){const t=x(e);return{path:m(t,"path"),exists:D(t,"exists"),config:fo(t.config),effectiveConfig:fo(t.effectiveConfig),envOverrides:Nc(t.envOverrides)}}function fo(e){const t=x(e);return{...v("host",$(t,"host")),...v("port",ne(t,"port")),...v("allowedHosts",Lc(t.allowedHosts)),...v("shortcuts",zc(t.shortcuts)),...v("plugins",Bc(t.plugins)),...v("pathAccess",jc(t.pathAccess)),...v("uploads",Uc(t.uploads)),...v("maxUploadBytes",ne(t,"maxUploadBytes")),...v("spawnSessions",mo(t,"spawnSessions")),...v("subsessions",mo(t,"subsessions"))}}function Lc(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 jc(e){if(e===void 0)return;if(!ze(e)||Array.isArray(e))throw new Error("Invalid PI WEB pathAccess field");const t=e.allowedPaths;return{...v("allowedPaths",Fc(t,"pathAccess.allowedPaths"))}}function Fc(e,t){if(e!==void 0){if(Array.isArray(e)&&e.every(i=>typeof i=="string"&&i!==""))return e;throw new Error(`Invalid PI WEB ${t} field`)}}function Uc(e){if(e!==void 0){if(!ze(e)||Array.isArray(e))throw new Error("Invalid PI WEB uploads field");return{...v("defaultFolder",$(e,"defaultFolder"))}}}function zc(e){if(e!==void 0){if(!ze(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 Bc(e){if(e!==void 0){if(!ze(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!ze(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&&(!ze(r)||Array.isArray(r)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Nc(e){const t=x(e);return{host:D(t,"host"),port:D(t,"port"),allowedHosts:D(t,"allowedHosts"),spawnSessions:D(t,"spawnSessions"),subsessions:D(t,"subsessions")}}function Hc(e){const t=x(e);return{plugins:F(qc)(t.plugins)}}function qc(e){const t=x(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:Kc(t.scope),machineSpecific:td(t.machineSpecific,"machineSpecific")??!1,enabled:D(t,"enabled")}}function Kc(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function Vc(e){const t=x(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:Jc(t.components),release:Zc(t.release),commands:Xc(t.commands),messages:F(Yc)(t.messages)}}function Gc(e){const t=x(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:da(t.components),capabilities:fr(t.capabilities)}}function Jc(e){const t=x(e);return{web:Pi(t.web),sessiond:Pi(t.sessiond)}}function da(e){const t=x(e);return{web:go(t.web),sessiond:go(t.sessiond)}}function go(e){const t=x(e);return{component:pa(t.component),label:m(t,"label"),...v("runtimeVersion",$(t,"runtimeVersion")),available:D(t,"available"),capabilities:fr(t.capabilities),...v("error",$(t,"error"))}}function Pi(e){const t=x(e);return{component:pa(t.component),label:m(t,"label"),...v("runtimeVersion",$(t,"runtimeVersion")),...v("installedVersion",$(t,"installedVersion")),stale:D(t,"stale"),available:D(t,"available"),...v("installation",Qc(t.installation)),...v("error",$(t,"error"))}}function Qc(e){if(e===void 0)return;const t=x(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");return{kind:i,...v("path",$(t,"path")),...v("source",$(t,"source")),...s===void 0?{}:{scope:s},...v("npmRoot",$(t,"npmRoot"))}}function Zc(e){const t=x(e);return{packageName:m(t,"packageName"),...v("latestVersion",$(t,"latestVersion")),updateAvailable:D(t,"updateAvailable"),...v("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...v("error",$(t,"error"))}}function Xc(e){const t=x(e);return{...v("update",$(t,"update")),...v("restart",$(t,"restart")),...v("restartWeb",$(t,"restartWeb")),...v("restartSessiond",$(t,"restartSessiond")),...v("status",$(t,"status"))}}function Yc(e){const t=x(e);return{id:m(t,"id"),severity:ed(t.severity),title:m(t,"title"),body:m(t,"body"),...v("command",$(t,"command"))}}function pa(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function fr(e){if(!Array.isArray(e)||!e.every(_c))throw new Error("Invalid PI WEB capabilities");return e}function ed(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function td(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function mo(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 id(e){const t=x(e);return F(ha)(t.machines)}function ha(e){const t=x(e),i=od(t,"kind"),s=$(t,"baseUrl"),r=ua(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 sd(e){const t=x(e),i=ua(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:D(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:Pi(t.web)},...t.sessiond===void 0?{}:{sessiond:Pi(t.sessiond)},...s===void 0?{}:{error:s}}}function rd(e){const t=x(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:D(t,"ok"),checkedAt:m(t,"checkedAt"),...v("packageName",$(t,"packageName")),...v("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:da(t.components)},...t.capabilities===void 0?{}:{capabilities:fr(t.capabilities)},...i===void 0?{}:{error:i}}}function od(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function ua(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 nd(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function Ci(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function ad(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=x(e);return{messages:nd(t.messages),start:q(t,"start"),total:q(t,"total")}}function vo(e){const t=x(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function ld(e){const t=x(e),i=$(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:D(t,"isMain"),isGitRepo:D(t,"isGitRepo"),isGitWorktree:D(t,"isGitWorktree"),...v("effectiveConfig",cd(t.effectiveConfig))}}function cd(e){if(e!==void 0){if(!ze(e)||Array.isArray(e))throw new Error("Invalid workspace effectiveConfig field");return{...v("uploads",Vd(e.uploads))}}}function zs(e){const t=x(e);return{path:m(t,"path"),size:q(t,"size"),modifiedAt:m(t,"modifiedAt")}}function bo(e){const t=x(e);return{path:m(t,"path")}}function dd(e){const t=x(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function Bs(e){const t=x(e),i=$(t,"name"),s=$(t,"parentSessionPath"),r=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:q(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...r===void 0?{}:{archivedAt:r}}}function Tt(e){const t=x(e);return{sessionId:m(t,"sessionId"),isStreaming:D(t,"isStreaming"),isCompacting:D(t,"isCompacting"),isBashRunning:D(t,"isBashRunning"),pendingMessageCount:q(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:F(gd)(t.queuedMessages),...v("messageCount",ne(t,"messageCount")),tokens:md(t.tokens),cost:q(t,"cost"),...wd(t.model),...Ed(t.contextUsage),...v("thinkingLevel",$(t,"thinkingLevel"))}}function fa(e){const t=x(e),i=t.skippedBusySessionIds===void 0?void 0:Ci(t.skippedBusySessionIds,"skippedBusySessionIds");return{generatedAt:m(t,"generatedAt"),thresholds:hd(t.thresholds),projects:F(ud)(t.projects),totals:fd(t.totals),...i===void 0?{}:{skippedBusySessionIds:i}}}function pd(e){const t=x(e);return{...fa(t),archivedSessionIds:Ci(t.archivedSessionIds,"archivedSessionIds"),deletedSessionIds:Ci(t.deletedSessionIds,"deletedSessionIds")}}function hd(e){const t=x(e);return{...v("archiveIdleDays",ne(t,"archiveIdleDays")),...v("deleteArchivedDays",ne(t,"deleteArchivedDays"))}}function ud(e){const t=x(e);return{cwd:m(t,"cwd"),archiveCount:q(t,"archiveCount"),deleteCount:q(t,"deleteCount")}}function fd(e){const t=x(e);return{archiveCount:q(t,"archiveCount"),deleteCount:q(t,"deleteCount")}}function gd(e){const t=x(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text"),...v("imageCount",ne(t,"imageCount"))}}function md(e){const t=x(e);return{input:q(t,"input"),output:q(t,"output"),cacheRead:q(t,"cacheRead"),cacheWrite:q(t,"cacheWrite"),total:q(t,"total")}}function ga(e){const t=x(e);return{...v("provider",$(t,"provider")),...v("id",$(t,"id")),...v("name",$(t,"name")),...v("contextWindow",ne(t,"contextWindow")),...v("reasoning",t.reasoning),...v("input",vd(t.input))}}function vd(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Invalid model input");return e.map(bd)}}function bd(e){if(e==="text"||e==="image")return e;throw new Error("Invalid model input")}function wd(e){return e===void 0?{}:{model:ga(e)}}function yd(e){const t=x(e);return{models:F(ga)(t.models)}}function xd(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function Sd(e){const t=x(e);return{levels:F(xd)(t.levels)}}function kd(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function $d(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 Pd(e){const t=x(e),i=t.source===void 0?void 0:$d(t.source);return{configured:D(t,"configured"),...v("source",i),...v("label",$(t,"label"))}}function Cd(e){const t=x(e);return{id:m(t,"id"),name:m(t,"name"),authType:kd(t.authType),status:Pd(t.status)}}function Id(e){const t=x(e);return{providers:F(Cd)(t.providers)}}function ti(e){const t=x(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:Rd(t.status),progress:F(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...v("error",$(t,"error")),...v("auth",Ad(t.auth)),...v("prompt",Td(t.prompt)),...v("select",Md(t.select))}}function Rd(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Ad(e){if(e===void 0)return;const t=x(e);return{url:m(t,"url"),...v("instructions",$(t,"instructions"))}}function Td(e){if(e===void 0)return;const t=x(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...v("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function Md(e){if(e===void 0)return;const t=x(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:F(va)(t.options)}}function Ed(e){if(e===void 0)return{};const t=x(e);return{contextUsage:{tokens:So(t,"tokens"),contextWindow:q(t,"contextWindow"),percent:So(t,"percent")}}}function Dd(e){const t=x(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...v("description",$(t,"description"))}}function Ns(e){const t=x(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function Wd(e){const t=x(e);return{path:m(t,"path"),entries:F(Od)(t.entries),scannedAt:m(t,"scannedAt"),truncated:D(t,"truncated")}}function Od(e){const t=x(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...v("size",ne(t,"size")),...v("modifiedAt",$(t,"modifiedAt"))}}function _d(e){const t=x(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...v("language",$(t,"language")),...v("mediaType",Fd(t.mediaType)),...v("mimeType",$(t,"mimeType")),encoding:i,size:q(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:D(t,"truncated"),binary:D(t,"binary")}}function ma(e){const t=x(e);return{path:m(t,"path"),size:q(t,"size"),modifiedAt:m(t,"modifiedAt"),created:D(t,"created")}}function Ld(e){const t=x(e);return{path:m(t,"path"),existed:D(t,"existed")}}function jd(e){const t=x(e);return{fromPath:m(t,"fromPath"),toPath:m(t,"toPath"),size:q(t,"size"),modifiedAt:m(t,"modifiedAt")}}function Fd(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function Ud(e){const t=x(e);return{isGitRepo:D(t,"isGitRepo"),hash:m(t,"hash"),...v("branch",$(t,"branch")),...v("upstream",$(t,"upstream")),...v("ahead",ne(t,"ahead")),...v("behind",ne(t,"behind")),files:F(zd)(t.files)}}function zd(e){const t=x(e);return{path:m(t,"path"),...v("oldPath",$(t,"oldPath")),index:wo(t.index),workingTree:wo(t.workingTree)}}function wo(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 Bd(e){const t=x(e);return{...v("path",$(t,"path")),staged:D(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:D(t,"truncated")}}function fs(e){const t=x(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:D(t,"exited"),...v("exitCode",ne(t,"exitCode")),...v("commandRunId",$(t,"commandRunId"))}}function Bt(e){const t=x(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:Nd(t.status),...v("exitCode",ne(t,"exitCode")),createdAt:m(t,"createdAt"),...v("startedAt",$(t,"startedAt")),...v("completedAt",$(t,"completedAt")),metadata:Hd(t.metadata,"metadata")}}function Nd(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function Hd(e,t){const i=x(e);return Object.fromEntries(Object.entries(i).map(([s,r])=>{if(typeof r!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,r]}))}function qd(e){const t=x(e);return{cwd:m(t,"cwd"),hasSessionActivity:D(t,"hasSessionActivity"),hasTerminalActivity:D(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function Kd(e){const t=x(e);return{workspaces:F(qd)(t.workspaces),generatedAt:m(t,"generatedAt")}}function Vd(e){if(e!==void 0){if(!ze(e)||Array.isArray(e))throw new Error("Invalid uploads field");return{...v("defaultFolder",$(e,"defaultFolder"))}}}function yo(e){const t=x(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:F(va)(t.options)};if(i==="done")return{type:i,...v("message",$(t,"message")),...Gd(t.session),...v("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function va(e){const t=x(e);return{value:m(t,"value"),label:m(t,"label"),...v("description",$(t,"description"))}}function Gd(e){return e===void 0?{}:{session:Bs(e)}}function ii(e){return{accepted:Ye(e,"accepted")}}function Jd(e){const t=x(e);return F(Qd)(t.attachments)}function Qd(e){const t=x(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:q(t,"size")}}function Hs(e){return{closed:Ye(e,"closed")}}function Zd(e){return{aborted:Ye(e,"aborted")}}function Xd(e){return{stopped:Ye(e,"stopped")}}function xo(e){const t=x(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:Ci(t.sessionIds,"sessionIds"),s=ne(t,"archivedCount"),r=ne(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...r===void 0?{}:{skippedAlreadyArchivedCount:r}}}function Yd(e){return{restored:Ye(e,"restored")}}function ep(e){return{deleted:Ye(e,"deleted")}}function tp(e){return{detached:Ye(e,"detached")}}function ip(e){return{reloaded:Ye(e,"reloaded")}}function So(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 sp(e){return typeof e=="string"?e:e.id}function rp(e){return typeof e=="string"?void 0:e.cwd}function op(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 np(e,t,i="local"){const s=new URLSearchParams,r=rp(e);r!==void 0&&r!==""&&s.set("cwd",r),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const o=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(sp(e))}/messages${o===""?"":`?${o}`}`}function ap(e,t,i,s){const r=new URLSearchParams({path:i});return s?.createDirs===!1&&r.set("createDirs","false"),s?.overwrite===!1&&r.set("overwrite","false"),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`}function lp(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 ba(e,t,i,s){const r=new URLSearchParams;r.set("path",i);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return ca(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${r.toString()}`)}const C=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function cp(e){return typeof e=="string"?e:e.id}function wa(e){return typeof e=="string"?void 0:e.cwd}function ya(e,t="local"){return`${C(t)}/sessions/${encodeURIComponent(cp(e))}`}function G(e,t,i="local"){return`${ya(e,i)}/${t}`}function si(e,t,i="local"){return`${G(e,t,i)}${xa(e)}`}function dp(e,t="local"){return`${ya(e,t)}${xa(e)}`}function xa(e){const t=wa(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function Q(e,t={}){const i=wa(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}const Sa={piWebStatus:(e="local")=>w(e==="local"?"/api/pi-web/status":`${C(e)}/pi-web/status`,Vc),piWebRuntime:()=>w("/api/pi-web/runtime",Gc)},pp={machines:()=>w("/api/machines",id),addMachine:e=>w("/api/machines",ha,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>w(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>w(`/api/machines/${encodeURIComponent(e)}/health`,sd),runtime:e=>w(`/api/machines/${encodeURIComponent(e)}/runtime`,rd)},Ii={config:()=>w("/api/config",uo),saveConfig:e=>w("/api/config",uo,{method:"PUT",body:JSON.stringify({config:e})})},qs={plugins:()=>w("/api/plugins",Hc)},ka={workspaceActivity:(e="local")=>w(`${C(e)}/activity`,Kd)},hp={projects:(e="local")=>w(`${C(e)}/projects`,F(vo)),addProject:(e,t,i,s="local")=>w(`${C(s)}/projects`,vo,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>w(`${C(t)}/projects/${encodeURIComponent(e)}`,Hs,{method:"DELETE"}),projectDirectories:(e,t="local")=>w(`${C(t)}/project-directories?q=${encodeURIComponent(e)}`,F(Ns))},wt={workspaces:(e,t="local")=>w(`${C(t)}/projects/${e}/workspaces`,F(ld)),deleteWorkspace:(e,t,i="local")=>w(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Bt,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Wd),workspaceFile:(e,t,i,s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,_d),uploadWorkspaceFile:async(e,t,i,s,r="local")=>r==="local"?vp(e,t,i,s):w(`${C(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,zs,{method:"POST",body:JSON.stringify({path:i,contentBase64:await gp(s)})}),createWorkspaceFile:(e,t,i,s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,zs,{method:"POST",body:JSON.stringify({path:i,contentBase64:""})}),writeWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({path:i});r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!1&&n.set("overwrite","false");const a=s instanceof Uint8Array,c=a?new Uint8Array(s):new TextEncoder().encode(s);return w(`${C(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${n.toString()}`,ma,{method:"PUT",body:c,headers:{"Content-Type":a?"application/octet-stream":"text/plain"}})},deleteWorkspaceFile:(e,t,i,s="local")=>{const r=new URLSearchParams({path:i});return w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`,Ld,{method:"DELETE"})},moveWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({fromPath:i,toPath:s});return r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!0&&n.set("overwrite","true"),w(`${C(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${n.toString()}`,jd,{method:"POST"})},createWorkspaceDirectory:(e,t,i,s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,bo,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,r="local")=>w(`${C(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,bo,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,dd,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>ba(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>bp(e,t,i,s)},Ks={sessions:(e,t="local")=>w(`${C(t)}/sessions?cwd=${encodeURIComponent(e)}`,F(Bs)),startSession:(e,t="local")=>w(`${C(t)}/sessions`,Bs,{method:"POST",body:JSON.stringify({cwd:e})}),cleanupPreview:(e,t="local")=>w(`${C(t)}/sessions/cleanup/preview`,fa,{method:"POST",body:JSON.stringify(e)}),cleanup:(e,t="local")=>w(`${C(t)}/sessions/cleanup`,pd,{method:"POST",body:JSON.stringify(e)}),messages:(e,t,i="local")=>w(np(e,t,i),ad),status:(e,t="local")=>w(si(e,"status",t),Tt),models:(e,t="local")=>w(si(e,"models",t),yd),setModel:(e,t,i,s="local")=>w(G(e,"model",s),Tt,{method:"POST",body:Q(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>w(G(e,"model/cycle",i),Tt,{method:"POST",body:Q(e,{direction:t})}),thinkingLevels:(e,t="local")=>w(si(e,"thinking-levels",t),Sd),setThinkingLevel:(e,t,i="local")=>w(G(e,"thinking-level",i),Tt,{method:"POST",body:Q(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>w(G(e,"thinking-level/cycle",t),Tt,{method:"POST",body:Q(e)}),commands:(e,t="local")=>w(si(e,"commands",t),F(Dd)),prompt:(e,t,i,s="local",r)=>w(G(e,"prompt",s),ii,{method:"POST",body:Q(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...r!==void 0&&r.length>0?{attachments:r}:{}})}),saveAttachments:(e,t,i="local",s)=>w(G(e,"attachments",i),Jd,{method:"POST",body:Q(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>w(G(e,"shell",i),ii,{method:"POST",body:Q(e,{text:t})}),runCommand:(e,t,i="local")=>w(G(e,"commands/run",i),yo,{method:"POST",body:Q(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>w(G(e,"commands/respond",s),yo,{method:"POST",body:Q(e,{requestId:t,value:i})}),abort:(e,t="local")=>w(G(e,"abort",t),Zd,{method:"POST",body:Q(e)}),stop:(e,t="local")=>w(G(e,"stop",t),Xd,{method:"POST",body:Q(e)}),archive:(e,t="local")=>w(G(e,"archive",t),xo,{method:"POST",body:Q(e)}),archiveWithDescendants:(e,t="local")=>w(G(e,"archive-tree",t),xo,{method:"POST",body:Q(e)}),restore:(e,t="local")=>w(G(e,"restore",t),Yd,{method:"POST",body:Q(e)}),deleteArchived:(e,t="local")=>w(dp(e,t),ep,{method:"DELETE"}),detachParent:(e,t="local")=>w(G(e,"detach-parent",t),tp,{method:"POST",body:Q(e)}),reloadSession:(e,t="local")=>w(G(e,"reload",t),ip,{method:"POST",body:Q(e)}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return w(`${C(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Id)},saveApiKey:(e,t,i="local")=>w(`${C(i)}/auth/api-key`,ii,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>w(`${C(t)}/auth/logout`,ii,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>w(`${C(t)}/auth/oauth`,ti,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>w(`${C(t)}/auth/oauth/${encodeURIComponent(e)}`,ti),respondOAuthFlow:(e,t,i,s="local")=>w(`${C(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,ti,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>w(`${C(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,ti,{method:"POST"})},yt={terminals:(e,t,i="local")=>w(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,F(fs)),startTerminal:(e,t,i,s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,fs,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>w(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Hs,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,Hs,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>w(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,fs,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>w(`${C(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Bt,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>w(`${C(t)}/terminal-command-runs${fp(e)}`,F(Bt)),getCommandRun:(e,t="local")=>up(e,t),cancelCommandRun:(e,t="local")=>w(`${C(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Bt,{method:"POST"})};async function up(e,t){const i=await fetch(`${C(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(gr(s)??i.statusText)}return Bt(await i.json())}}function fp(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 gr(e){if(!wp(e))return;const t=e.error;return typeof t=="string"?t:void 0}async function gp(e){return mp(await e.arrayBuffer())}function mp(e){const t=new Uint8Array(e);let i="";for(const s of t)i+=String.fromCharCode(s);return btoa(i)}async function vp(e,t,i,s){const r=new FormData;r.set("path",i),r.set("file",s,s.name);const o=await fetch(`${C("local")}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,{method:"POST",body:r});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(gr(n)??o.statusText)}return zs(await o.json())}async function bp(e,t,i,s){const r=await fetch(ba(e,t,i,{machineId:s}));if(!r.ok){const p=await r.json().catch(()=>({}));throw new Error(gr(p)??r.statusText)}const o=await r.blob(),n=URL.createObjectURL(o),a=document.createElement("a");a.href=n;const c=i.split("/").pop();a.download=c===void 0||c===""?"download":c,document.body.append(a),a.click(),a.remove(),URL.revokeObjectURL(n)}function wp(e){return typeof e=="object"&&e!==null}const yp={files:(e,t,i={})=>{const s=new URLSearchParams({q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),i.workspaceScoped===!0&&i.projectId!==void 0&&i.workspaceId!==void 0?w(`${C(i.machineId)}/projects/${encodeURIComponent(i.projectId)}/workspaces/${encodeURIComponent(i.workspaceId)}/files?${s.toString()}`,F(Ns)):(s.set("cwd",e),w(`${C(i.machineId)}/files?${s.toString()}`,F(Ns)))}},xp={gitStatus:(e,t,i="local")=>w(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Ud),gitDiff:(e,t,i,s="local")=>w(op(s,e,t,i),Bd)},N={...Sa,...pp,...Ii,...qs,...ka,...hp,...wt,...Ks,...yt,...yp,...xp};function Sp(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(`${vr()}${mr(t)}/sessions/${encodeURIComponent(r)}/events${s}`)}function X0(e,t,i,s,r="local"){const o=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${vr()}${mr(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${o}`)}function kp(e="local"){return new WebSocket(`${vr()}${mr(e)}/events`)}function mr(e){return`/api/machines/${encodeURIComponent(e)}`}function vr(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}const $a=".pi-web/uploads";class Ji extends Error{constructor(t="Workspace upload cancelled"){super(t),this.name="WorkspaceUploadCancelledError"}}class Pa extends Error{constructor(t,i){super(Mp(t)),this.name="WorkspaceUploadBatchError",this.failures=t.map(s=>({...s})),this.responses=i.map(s=>({...s}))}}function ko(e){return e?.uploads?.defaultFolder??$a}function $p(e,t){return e?.uploads?.defaultFolder??t}function br(e,t){const i=$o(e,"upload destination",{allowEmpty:!0}),s=$o(t,"upload file name",{allowEmpty:!1});return i===""?s:`${i}/${s}`}function Pp(e,t,i,s={}){const r=s.xhrFactory?.()??new XMLHttpRequest;let o=!1,n=!1;return{promise:new Promise((c,p)=>{const u=g=>{o||(o=!0,p(g))},h=g=>{o||(o=!0,c(g))};r.open("PUT",ap(e,t,i.path,Rp(s)),!0),r.responseType="json",r.setRequestHeader("Content-Type",(i.contentType??i.file.type)||"application/octet-stream"),r.upload.onprogress=g=>{s.onProgress?.(Ap(g,i.file.size))},r.onload=()=>{if(r.status>=200&&r.status<300){try{s.onProgress?.({loaded:i.file.size,total:i.file.size,percent:1,lengthComputable:!0}),h(ma(Ca(r)))}catch(g){u(g instanceof Error?g:new Error(String(g)))}return}u(new Error(Op(r)))},r.onerror=()=>{u(new Error("Workspace upload failed"))},r.onabort=()=>{u(new Ji(n?void 0:"Workspace upload aborted"))},r.send(i.file)}),cancel:()=>{o||(n=!0,r.abort())}}}function Cp(e,t,i,s={}){const r=s.destinationFolder??$a,o=i.map((h,g)=>({index:g,name:h.name,path:br(r,h.name),loaded:0,total:h.size,percent:wr(0,h.size),lengthComputable:!0,done:!1}));let n,a=0;const c={requested:!1},p=()=>{s.onProgress?.(Tp(o,a,o.every(h=>h.done)))};return{promise:(async()=>{const h=[],g=[];for(let b=0;b<i.length;b+=1){if(c.requested)throw new Ji;a=b;const P=i[b],I=o[b];if(!(P===void 0||I===void 0)){n=Pp(e,t,{path:I.path,file:P},{...Ip(s),onProgress:V=>{I.total=V.total,I.loaded=Math.min(V.loaded,I.total),I.percent=V.percent,I.lengthComputable=V.lengthComputable,p()}});try{const V=await n.promise;I.loaded=I.total,I.percent=1,I.lengthComputable=!0,I.done=!0,h.push(V),p()}catch(V){if(Dp(V,c))throw V;const Ve=Ep(V);I.loaded=I.total,I.percent=1,I.lengthComputable=!0,I.done=!0,I.error=Ve,g.push({index:b,name:P.name,path:I.path,error:Ve}),p()}finally{n=void 0}}}if(g.length>0)throw new Pa(g,h);return h})(),cancel:()=>{c.requested=!0,n?.cancel()}}}function Ip(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function Rp(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Ap(e,t){const i=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:i,percent:wr(e.loaded,i),lengthComputable:e.lengthComputable}}function Tp(e,t,i){const s=e.reduce((o,n)=>o+n.total,0),r=e.reduce((o,n)=>o+n.loaded,0);return{currentFileIndex:t,files:e.map(o=>({...o})),loaded:r,total:s,percent:wr(r,s),done:i}}function wr(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Mp(e){return e.length===1?e[0]?.error??"Workspace upload failed":`${String(e.length)} files failed to upload`}function Ep(e){return e instanceof Error?e.message:String(e)}function Dp(e,t){return t.requested||e instanceof Ji}function $o(e,t,i){const s=e.trim();if(s===""){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(Wp(s))throw new Error(`${t} must be workspace-relative`);const r=s.split(/[\\/]+/u).filter(o=>o!==""&&o!==".");if(r.length===0){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(r.some(o=>o===".."))throw new Error(`${t} must not contain path traversal`);return r.join("/")}function Wp(e){const t=e.replace(/\\/g,"/");return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}function Ca(e){return e.response!==void 0&&e.response!==null&&e.response!==""?e.response:e.responseText===""?{}:JSON.parse(e.responseText)}function Op(e){const t=_p(e);return Lp(t)&&typeof t.error=="string"?t.error:e.statusText||`HTTP ${String(e.status)}`}function _p(e){try{return Ca(e)}catch{return}}function Lp(e){return typeof e=="object"&&e!==null}function fi(){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 jp(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Xe(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Ia(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const Ra="local";function gs(e,t){return`${e}:${t}`}function Aa(e,t){return`${e}:${t}`}function f(e){return e.selectedMachine?.id??Ra}class Fp{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??ka}async refresh(t=f(this.getState())){this.applyMachineActivitySnapshot(t,Up(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=zp(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 Up(e){const t={};for(const i of e.workspaces)Ia(i)&&(t[i.cwd]=i);return t}function zp(e,t){const i={...e};return Ia(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class Bp{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=r.api??N,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=Np(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:f(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const r=s.providers.find(o=>o.id===t&&(i===void 0||o.authType===i));r!==void 0&&(r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({authDialog:{...t,saving:!1,error:String(r)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:f(this.getState())});if(t!==void 0&&t!==""){const s=i.find(r=>r.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(r=>r.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({error:String(r)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const r=t??i.inputValue??"",o={...i};delete o.error,this.setState({authDialog:{...o,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,r,f(this.getState()));this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...i,responding:!1,error:String(n)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,f(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:f(this.getState())}),s=i.filter(o=>o.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const r=s[0];if(r===void 0)return;r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,f(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const r=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${r}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",r=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,o=t.prompt?.requestId??t.select?.requestId,n=r!==void 0&&r===o,a=n?s:"",c=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:c}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t,f(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.session();if(t!==void 0)try{this.applyStatus(await this.api.status(t,f(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function Np(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 Gt(e){return e.replaceAll(":",".")}function Hp(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 ms(e,t){const i=Hp(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function he(e,t,i,s){const r=new URL(window.location.href),o=`${e}--${t}`;if(r.searchParams.delete(o),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)r.searchParams.append(o,String(n));else r.searchParams.set(o,String(i));qp(r,s)}function qp(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}function Kp(e){const t=e.files.map((s,r)=>{const o=s.size;return{index:r,name:s.name,path:br(e.destinationFolder,s.name),size:s.size,loaded:0,total:o,percent:Co(0,o),lengthComputable:!0,status:r===0?"uploading":"pending"}}),i=t.reduce((s,r)=>s+r.total,0);return{id:e.id,projectId:e.projectId,workspaceId:e.workspaceId,machineId:e.machineId,destinationFolder:e.destinationFolder,overwrite:e.overwrite,createDirs:e.createDirs,files:t,currentFileIndex:t.length===0?-1:0,loaded:0,total:i,percent:Co(0,i),status:"uploading",startedAt:e.startedAt}}function Vp(e,t){const i=new Map(t.files.map(r=>[r.index,r])),s=e.files.map(r=>{const o=i.get(r.index);if(o===void 0)return r;const n={...r,path:o.path,loaded:o.loaded,total:o.total,percent:o.percent,lengthComputable:o.lengthComputable,status:o.error!==void 0?"error":o.done?"completed":t.currentFileIndex===r.index?"uploading":r.status};return o.error===void 0?delete n.error:n.error=o.error,n});return{...e,files:s,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function Gp(e,t,i){const s=e.files.map((o,n)=>{const a=t[n];return{...o,...a===void 0?{}:{path:a.path,response:a},loaded:o.total,percent:1,lengthComputable:!0,status:"completed"}}),r=yr(s);return{...e,files:s,currentFileIndex:s.length===0?-1:s.length-1,...r,status:"completed",completedAt:i}}function Jp(e,t,i){const s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:r.status==="uploading"||r.index===e.currentFileIndex?{...r,status:"error",error:t}:{...r,status:"cancelled",error:"Not uploaded because an earlier file failed."});return{...e,files:s,...yr(s),status:"error",error:t,completedAt:i}}function Po(e,t){const i="Upload cancelled",s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:{...r,status:"cancelled",error:i});return{...e,files:s,...yr(s),status:"cancelled",error:i,completedAt:t}}function yr(e){const t=e.reduce((i,s)=>i+s.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function Co(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}const ri=Gt("core:workspace.files");class Qp{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??N,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??Cp,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=f(this.getState()),r=await this.api.workspaceTree(t.id,i.id,"",s),o=await Promise.all(Object.keys(this.getState().expandedDirs).map(async a=>{try{const c=await this.api.workspaceTree(t.id,i.id,a,s);return[a,c.entries]}catch(c){if(Io(c))return;throw c}})),n=Object.fromEntries(o.filter(a=>a!==void 0));this.setState({fileTree:r.entries,expandedDirs:n,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:Ro(this.getState().expandedDirs,t)});return}try{const r=await this.api.workspaceTree(i.id,s.id,t,f(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:r.entries},error:""})}catch(r){this.setState({error:String(r)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),he(ri,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}selectDirectory(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),he(ri,"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(Io(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),he(ri,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}async createFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceFile(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),await this.selectFile(t),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async createDirectory(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceDirectory(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),this.selectDirectory(t),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async moveSelectedPath(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace,r=this.getState().selectedFilePath;if(!(i===void 0||s===void 0||r===void 0||r===""||t===""))try{const o=f(this.getState());vs(this.getState())==="directory"?(await this.api.moveWorkspaceDirectory(i.id,s.id,r,t,o),await this.refreshFiles(),this.selectDirectory(t)):(await this.api.moveWorkspaceFile(i.id,s.id,r,t,void 0,o),await this.refreshFiles(),await this.selectFile(t)),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async deleteSelectedPath(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""))try{const r=f(this.getState());vs(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===""||vs(this.getState())==="directory"))try{await this.api.downloadWorkspaceFile(t.id,i.id,s,f(this.getState())),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),he(ri,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}startWorkspaceUpload(t,i){const s=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(s===void 0||r===void 0){this.setState({error:"Select a workspace before uploading files."});return}if(t.length===0)return;const o=f(this.getState()),n=i.overwrite??!1,a=i.createDirs??!0;let c;try{c=Kp({id:this.createUploadBatchId(),projectId:s.id,workspaceId:r.id,machineId:o,destinationFolder:i.destinationFolder,overwrite:n,createDirs:a,files:t,startedAt:this.now()})}catch(h){this.setState({error:String(h)});return}this.setUploadBatch(c);let p;try{p=this.uploadWorkspaceFiles(s.id,r.id,t,{destinationFolder:i.destinationFolder,machineId:o,overwrite:n,createDirs:a,onProgress:h=>{this.updateUploadProgress(c.id,h)}})}catch(h){return this.failUploadBatch(c.id,h),{batchId:c.id,done:Promise.resolve()}}this.uploadTasks.set(c.id,p);const u=p.promise.then(async h=>{await this.completeUploadBatch(c.id,h,i)}).catch(async h=>{await this.handleUploadFailure(c.id,h,i)}).finally(()=>{this.uploadTasks.delete(c.id)});return{batchId:c.id,done:u}}cancelWorkspaceUpload(t){const i=this.getUploadBatch(t);i?.status==="uploading"&&(this.setUploadBatch(Po(i,this.now())),this.uploadTasks.get(t)?.cancel())}clearWorkspaceUpload(t){this.uploadTasks.get(t)?.cancel(),this.uploadTasks.delete(t),this.setState({workspaceUploadBatches:Ro(this.getState().workspaceUploadBatches,t)})}updateUploadProgress(t,i){const s=this.getUploadBatch(t);s?.status==="uploading"&&this.setUploadBatch(Vp(s,i))}async completeUploadBatch(t,i,s){const r=this.getUploadBatch(t);if(r?.status!=="uploading"||(this.setUploadBatch(Gp(r,i,this.now()),{error:""}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();const o=i[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}async handleUploadFailure(t,i,s){const r=this.failUploadBatch(t,i);if(!(i instanceof Pa)||i.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshFiles();const o=i.responses[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}failUploadBatch(t,i){const s=this.getUploadBatch(t);if(s?.status!=="uploading")return;if(Zp(i)){const n=Po(s,this.now());return this.setUploadBatch(n),n}const r=Xp(i),o=Jp(s,r,this.now());return this.setUploadBatch(o,{error:r}),o}getUploadBatch(t){return this.getState().workspaceUploadBatches[t]}setUploadBatch(t,i={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[t.id]:t},...i})}isCurrentWorkspaceBatch(t){const i=this.getState();return i.selectedProject?.id===t.projectId&&i.selectedWorkspace?.id===t.workspaceId&&f(i)===t.machineId}}function Io(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function Zp(e){return e instanceof Ji}function Xp(e){return e instanceof Error?e.message:String(e)}function Ro(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function vs(e){const t=e.selectedFilePath;return t===void 0?"file":Yp(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function Yp(e,t,i){const s=e.find(r=>r.path===i);if(s!==void 0)return s;for(const r of Object.values(t)){const o=r.find(n=>n.path===i);if(o!==void 0)return o}}const Ao=Gt("core:workspace.git");class eh{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await N.gitStatus(t.id,i.id,f(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const r=this.getState().selectedDiffPath;r!==void 0&&(s.files.some(o=>o.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),he(Ao,"diff",void 0,{replace:!0})))}catch(s){this.setState({error:String(s)})}}async selectDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),he(Ao,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[r,o]=await Promise.all([N.gitDiff(i.id,s.id,{path:t},f(this.getState())),N.gitDiff(i.id,s.id,{path:t,staged:!0},f(this.getState()))]);this.setState({selectedDiff:r,selectedStagedDiff:o,error:""})}catch(r){this.setState({error:String(r)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class th{constructor(t,i,s,r){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=r}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await N.machines(),s=await this.selectInitialMachine(i,t),r=new Set(i.map(o=>o.id));this.setState({machines:i,selectedMachine:s,machineActivities:To(this.getState().machineActivities,r),machineRuntimes:To(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,...fi()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await N.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await N.deleteMachine(t.id);const r=this.getState().machines.filter(n=>n.id!==t.id),o=r.find(n=>n.id==="local")??r[0];return this.setState({machines:r,machineStatuses:bs(this.getState().machineStatuses,t.id),machineRuntimes:bs(this.getState().machineRuntimes,t.id),machineActivities:bs(this.getState().machineActivities,t.id)}),s&&o!==void 0?(i.selectFallback===!1||await this.selectMachine(o),o):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await N.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await N.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(o=>o.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const r=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await N.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(r=>N.health(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(r=>N.runtime(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function bs(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function To(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class ih{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=f(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await N.projects(t);if(f(this.getState())!==t)return;const s=new Set(i.map(o=>o.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([o])=>s.has(o)));this.setState({projects:i,workspacesByProjectId:r})}catch(i){f(this.getState())===t&&this.setState({error:String(i)})}finally{f(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await N.addProject(t.trim(),void 0,i,f(this.getState())),r=this.getState().projects;this.setState({projects:[...r.filter(o=>o.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await N.closeProject(t,f(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const Vs="pi-web:cached-new-sessions:v1",sh="browserCachedNew",Ct="local";function Jt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Mo(e,t=Ct,i=Jt()){if(e.messageCount!==0||e.archived===!0)return;const s=xr(i).filter(r=>r.id!==e.id||r.machineId!==t);Sr([Gs(e,t),...s],i)}function Gs(e,t=Ct){return{...e,browserCachedNew:!0,machineId:t}}function Eo(e,t=Ct,i=Jt()){const s=xr(i).filter(r=>r.id!==e||r.machineId!==t);Sr(s,i)}function Ta(e,t,i=Ct,s=Jt()){const r=new Set(t.map(c=>c.id)),o=xr(s),n=o.filter(c=>c.machineId!==i||!r.has(c.id));return n.length!==o.length&&Sr(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function Z(e){return e===void 0?!1:nh(e)&&e.browserCachedNew===!0}function rh(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:Ct},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function xr(e=Jt()){try{const t=e?.getItem(Vs);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>oh(s)):[]}catch{return[]}}function Sr(e,t=Jt()){try{e.length===0?t?.removeItem(Vs):t?.setItem(Vs,JSON.stringify(e))}catch{}}function oh(e){if(!ah(e))return[];const t=gt(e,"id"),i=gt(e,"path"),s=gt(e,"cwd"),r=gt(e,"created"),o=gt(e,"modified"),n=gt(e,"firstMessage"),a=lh(e,"messageCount");if(t===void 0||i===void 0||s===void 0||r===void 0||o===void 0||n===void 0||a!==0)return[];const c=ws(e,"name"),p=ws(e,"parentSessionPath"),u=ws(e,"machineId")??Ct;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:r,modified:o,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function nh(e){return sh in e}function ah(e){return typeof e=="object"&&e!==null}function gt(e,t){const i=e[t];return typeof i=="string"?i:void 0}function ws(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function lh(e,t){const i=e[t];return typeof i=="number"?i:void 0}function ch(e){return Ph(e.flatMap(kr)).filter(t=>t.parts.length>0)}function Oe(e,t){return{role:e,parts:[{type:"text",text:t}]}}function Mt(e,t){const i=vh(t);return i===void 0?e:{...e,meta:i}}function dh(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,Oe(t,i)]}function ph(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 kr(e){if(uh(e))return[e];if(_(e,"role")==="bashExecution")return[Mt(yh(e),e)];const t=xh(_(e,"role")),i=Sh(ye(e,"content"),e),s=t==="user"?fh(i):void 0;if(s!==void 0)return s.map(p=>Mt(p,e));const r=mh(e);if(t==="tool")return[Mt({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?[Mt({role:n,parts:o,...r===void 0?{}:{source:r}},e)]:[],c=hh(e);return c===void 0?a:[...a,Mt(c,e)]}function hh(e){if(_(e,"role")!=="assistant"||_(e,"stopReason")!=="error")return;const t=_(e,"errorMessage")?.trim();return Oe("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function uh(e){const t=_(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(ye(e,"parts"))}function fh(e){if(e.length!==1||e[0]?.type!=="text")return;const t=gh(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 gh(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 mh(e){const t=_(e,"source");if(t==="compaction"||t==="branch_summary")return t}function vh(e){const t=bh(ye(e,"timestamp")),i=wh(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function bh(e){if(typeof e=="number"&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!="string"||e==="")return;const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function wh(e){if(_(e,"role")!=="assistant")return;const t=_(e,"provider"),i=_(e,"model"),s=_(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function yh(e){const t=_(e,"command")??"",i=gi(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=ye(e,"output");s!=null&&i.push("",Ai(s));const r=ye(e,"exitCode");r!=null&&i.push("",`exit ${Ai(r)}`),gi(e,"cancelled")===!0&&i.push("","cancelled"),gi(e,"truncated")===!0&&i.push("","output truncated");const o=_(e,"fullOutputPath");return o!==void 0&&o!==""&&i.push("",`full output: ${o}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
+ `)}]}}function xh(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function Sh(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=_(i,"type"),r=_(i,"text");if(s==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(s==="thinking"){const o=_(i,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}if(s==="toolCall"){const o=_(i,"name")??"tool",n=ye(i,"arguments"),a=_(i,"id"),c=o==="read"?$h(_(n,"path")):void 0;return c!==void 0?[{type:"skillRead",...c,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:o,summary:Qt(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const o=_(i,"data"),n=_(i,"mimeType");return o!==void 0&&o!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:o}]:[{type:"text",text:"[image]"}]}return Do(i)}).map(i=>i.type==="text"&&_(t,"role")==="toolResult"?kh(i.text,t):i):Do(e)}function kh(e,t){const i=_(t,"toolCallId"),s=ye(t,"content"),r=ye(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:_(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...r===void 0?{}:{details:r},isError:gi(t,"isError")===!0}}function $h(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 Ph(e){const t=[],i=new Map;for(const s of e){let r=[];const o={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{r.length!==0&&(t.push({role:s.role,parts:r,...o}),r=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=Ch(a),p=t.length;t.push({role:"tool",parts:[c],...o}),c.toolCallId!==void 0&&i.set(c.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const c=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(c!==void 0&&Ih(t,c,a)){i.delete(a.toolCallId??"");continue}}r.push(a)}n()}return t}function Ch(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 Ih(e,t,i){const s=e[t.lineIndex],r=s?.parts[t.partIndex];if(s===void 0||r?.type!=="toolExecution")return!1;const o=Ri(i.details)??r.preview,n={...r,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...o===void 0?{}:{preview:o}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function Ri(e){const t=ye(e,"preview");if(!$r(t))return;const i=_(t,"diff"),s=_(t,"error"),r=Ah(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 Do(e){return e==null?[]:typeof e=="object"?[{type:"text",text:Qt(e)}]:[{type:"text",text:Ai(e)}]}function Qt(e){if(!$r(e))return Ai(e);const t=_(e,"command");if(t!==void 0)return t;const i=_(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} edit${s.length===1?"":"s"}`:Object.entries(e).filter(([,o])=>o!=null).slice(0,3).map(([o,n])=>`${o}: ${Rh(n)}`).join(" · ")}function Rh(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 $r(e){return typeof e=="object"&&e!==null}function ye(e,t){return $r(e)?e[t]:void 0}function _(e,t){const i=ye(e,t);return typeof i=="string"?i:void 0}function gi(e,t){const i=ye(e,t);return typeof i=="boolean"?i:void 0}function Ah(e,t){const i=ye(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function Ai(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const Th="pi-web:prompt-draft:";function Ti(e){return`${Th}${e}`}function Qi(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Ma(e,t=Qi()){try{return t?.getItem(Ti(e))??""}catch{return""}}function Mi(e,t,i=Qi()){try{t?i?.setItem(Ti(e),t):i?.removeItem(Ti(e))}catch{}}function Pr(e,t=Qi()){try{t?.removeItem(Ti(e))}catch{}}function Mh(e,t,i=Qi()){const s=Ma(e,i);s!==""&&(Mi(t,s,i),Pr(e,i))}function Eh(e,t){return Oe("bash",`${t===!0?`不加入上下文
6
6
 
7
- `:""}$ ${e}`)}function Ah(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Oe("bash",t)];const r=Mh(s.text)?"":`
7
+ `:""}$ ${e}`)}function Dh(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Oe("bash",t)];const r=Oh(s.text)?"":`
8
8
 
9
- `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+r+t}]}]}function Th(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const r=[];return!s.text.includes(`
9
+ `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+r+t}]}]}function Wh(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const r=[];return!s.text.includes(`
10
10
 
11
11
  `)&&(t.output===void 0||t.output==="")&&r.push("(no output)"),t.isError===!0&&r.push(t.output??"Bash 命令失败"),t.exitCode!=null&&r.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&r.push("cancelled"),t.truncated===!0&&r.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&r.push(`完整输出:${t.fullOutputPath}`),r.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
12
12
 
13
13
  ${r.join(`
14
- `)}`}]}]}function Mh(e){const t=e.lastIndexOf(`
14
+ `)}`}]}]}function Oh(e){const t=e.lastIndexOf(`
15
15
 
16
- `),i=e.lastIndexOf("$ ");return t>i}function Eh(e,t){if(t.type==="message.append")return Kh(e,t.message);if(t.type==="assistant.delta")return nh(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return ah(e,t.text);if(t.type==="tool.start")return Lh(e,t);if(t.type==="tool.update")return Aa(e,t.toolCallId,i=>jh(i,t));if(t.type==="tool.end")return Ia(e,t.toolCallId,t.toolName,Qt(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,Ih(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return Ah(e,t.chunk);if(t.type==="shell.end")return Th(e,t);if(t.type==="command.output")return[...e,Oe(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,Oe("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:Dh(e,t.message)}function Dh(e,t){const i=Fh(t);if(i!==void 0)return Ia(e,i.toolCallId,i.toolName,Qt(i.content),i.text,i.isError,i.content,i.details);const s=kr(t);if(s.length===0)return;const r=s.map(o=>o.role==="assistant"?Oh(o):o).filter(o=>o.parts.length>0);return r.length===0?e:r.reduce((o,n)=>Wh(o,n),e)}function Wh(e,t){const i=Uh(e,t);if(i.length>0)return zh(e,i,t);const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||qh(s,t)?[...e.slice(0,-1),t]:[...e,t]}function Oh(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function _h(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 Lh(e,t){const i=t.toolName==="read"?_h(lt(t.args,"path")):void 0;if(i!==void 0)return Vh(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||Qt(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function jh(e,t){const i=Ii(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 Ia(e,t,i,s,r,o,n,a){const c=Aa(e,t,h=>{const g=Ii(a)??h.preview;return{...h,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...g===void 0?{}:{preview:g}}});if(c!==e)return c;const p=Ii(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 Aa(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const r=e[s];if(r===void 0)continue;const o=r.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(o<0)continue;const n=r.parts[o];if(n?.type!=="toolExecution")continue;const a={...r,parts:[...r.parts.slice(0,o),i(n),...r.parts.slice(o+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function Fh(e){if(lt(e,"role")!=="toolResult")return;const t=lt(e,"toolCallId"),i=Di(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:lt(e,"toolName")??"tool",text:Ta(i),isError:Zh(e,"isError")===!0,content:i,details:Di(e,"details")}}function Ta(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Ta).filter(t=>t!=="").join(`
17
- `);if(typeof e=="object"&&e!==null){const t=lt(e,"text")??lt(e,"content")??lt(e,"output");if(t!==void 0)return t}return""}function Uh(e,t){const i=Ei(t);if(i.length===0)return[];const s=[];let r=i.length;const o=Ea(e)+1;for(let n=e.length-1;n>=o;n--){const a=Ei(e[n]);if(a.length===0)continue;const c=r-a.length;if(!(c<0)&&Hh(a,i.slice(c,r))&&(s.unshift(n),r=c,r===0))return s}return[]}function zh(e,t,i){const s=Bh(e,t,i),r=s[0];if(r===void 0)return e;const o=new Set(s),n=[];for(let a=0;a<e.length;a++){a===r&&n.push(i);const c=e[a];c!==void 0&&!o.has(a)&&n.push(c)}return n}function Bh(e,t,i){const s=t[0];if(i.role!=="assistant"||s===void 0)return t;const r=s-1;return Nh(e[r])?[r,...t]:t}function Nh(e){return e?.role==="assistant"&&e.parts.length>0&&e.parts.every(t=>t.type==="text"||t.type==="thinking")}function Ei(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function Hh(e,t){return e.length===t.length&&e.every((i,s)=>Ma(i,t[s]))}function Ma(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:Wo(e.path)===Wo(t.path)||e.name===t.name}function Wo(e){return e.replace(/\\/g,"/")}function qh(e,t){return Oo(e)===Oo(t)}function Oo(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
16
+ `),i=e.lastIndexOf("$ ");return t>i}function _h(e,t){if(t.type==="message.append")return Qh(e,t.message);if(t.type==="assistant.delta")return dh(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return ph(e,t.text);if(t.type==="tool.start")return zh(e,t);if(t.type==="tool.update")return Da(e,t.toolCallId,i=>Bh(i,t));if(t.type==="tool.end")return Ea(e,t.toolCallId,t.toolName,Qt(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,Eh(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return Dh(e,t.chunk);if(t.type==="shell.end")return Wh(e,t);if(t.type==="command.output")return[...e,Oe(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,Oe("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:Lh(e,t.message)}function Lh(e,t){const i=Nh(t);if(i!==void 0)return Ea(e,i.toolCallId,i.toolName,Qt(i.content),i.text,i.isError,i.content,i.details);const s=kr(t);if(s.length===0)return;const r=s.map(o=>o.role==="assistant"?Fh(o):o).filter(o=>o.parts.length>0);return r.length===0?e:r.reduce((o,n)=>jh(o,n),e)}function jh(e,t){const i=Hh(e,t);if(i.length>0)return qh(e,i,t);const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||Jh(s,t)?[...e.slice(0,-1),t]:[...e,t]}function Fh(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function Uh(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 zh(e,t){const i=t.toolName==="read"?Uh(lt(t.args,"path")):void 0;if(i!==void 0)return Zh(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||Qt(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function Bh(e,t){const i=Ri(t.details)??e.preview;return{...e,status:e.status==="pending"?"running":e.status,...t.text===""?{}:{resultText:t.text},...t.content===void 0?{}:{content:t.content},...t.details===void 0?{}:{details:t.details},...i===void 0?{}:{preview:i}}}function Ea(e,t,i,s,r,o,n,a){const c=Da(e,t,h=>{const g=Ri(a)??h.preview;return{...h,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...g===void 0?{}:{preview:g}}});if(c!==e)return c;const p=Ri(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function Da(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const r=e[s];if(r===void 0)continue;const o=r.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(o<0)continue;const n=r.parts[o];if(n?.type!=="toolExecution")continue;const a={...r,parts:[...r.parts.slice(0,o),i(n),...r.parts.slice(o+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function Nh(e){if(lt(e,"role")!=="toolResult")return;const t=lt(e,"toolCallId"),i=Di(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:lt(e,"toolName")??"tool",text:Wa(i),isError:tu(e,"isError")===!0,content:i,details:Di(e,"details")}}function Wa(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Wa).filter(t=>t!=="").join(`
17
+ `);if(typeof e=="object"&&e!==null){const t=lt(e,"text")??lt(e,"content")??lt(e,"output");if(t!==void 0)return t}return""}function Hh(e,t){const i=Ei(t);if(i.length===0)return[];const s=[];let r=i.length;const o=_a(e)+1;for(let n=e.length-1;n>=o;n--){const a=Ei(e[n]);if(a.length===0)continue;const c=r-a.length;if(!(c<0)&&Gh(a,i.slice(c,r))&&(s.unshift(n),r=c,r===0))return s}return[]}function qh(e,t,i){const s=Kh(e,t,i),r=s[0];if(r===void 0)return e;const o=new Set(s),n=[];for(let a=0;a<e.length;a++){a===r&&n.push(i);const c=e[a];c!==void 0&&!o.has(a)&&n.push(c)}return n}function Kh(e,t,i){const s=t[0];if(i.role!=="assistant"||s===void 0)return t;const r=s-1;return Vh(e[r])?[r,...t]:t}function Vh(e){return e?.role==="assistant"&&e.parts.length>0&&e.parts.every(t=>t.type==="text"||t.type==="thinking")}function Ei(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function Gh(e,t){return e.length===t.length&&e.every((i,s)=>Oa(i,t[s]))}function Oa(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:Wo(e.path)===Wo(t.path)||e.name===t.name}function Wo(e){return e.replace(/\\/g,"/")}function Jh(e,t){return Oo(e)===Oo(t)}function Oo(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
18
18
 
19
- `)}function Kh(e,t){const i=kr(t);return i.length===0?e:[...e,...i]}function Vh(e,t){const i=e.at(-1);return Gh(e,t)?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Gh(e,t){const i=Ei(t);if(t.role!=="skill"||i.length===0)return!1;const s=Ea(e)+1;return i.every(r=>Jh(e,r,s))}function Jh(e,t,i){for(let s=e.length-1;s>=i;s--)if(Ei(e[s]).some(r=>Ma(r,t)))return!0;return!1}function Ea(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="user")return t;return-1}function Qh(e){return typeof e=="object"&&e!==null}function Di(e,t){return Qh(e)?e[t]:void 0}function lt(e,t){const i=Di(e,t);return typeof i=="string"?i:void 0}function Zh(e,t){const i=Di(e,t);return typeof i=="boolean"?i:void 0}const Xh="pi-web:chat-history:v2:",Yh=1800*1e3;function eu(e){try{const t=sessionStorage.getItem(Wi(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!nu(i))return;if(Date.now()-i.savedAt>Yh){sessionStorage.removeItem(Wi(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function tu(e,t){try{sessionStorage.setItem(Wi(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function iu(e){try{sessionStorage.removeItem(Wi(e))}catch{}}function su(e,t){if(e===void 0||!Js(e))return t;if(!Js(t))return e;if(ru(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 _o(r,i,e),_o(r,i,t),ou(r)?t:{start:i,total:Math.max(e.total,t.total),messages:r}}function ru(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function ou(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function _o(e,t,i){i.messages.forEach((s,r)=>{e[i.start-t+r]=s})}function Wi(e){return`${Xh}${e}`}function nu(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"&&Js({messages:t,start:i,total:s})}function Js(e){return Number.isInteger(e.start)&&Number.isInteger(e.total)&&e.start>=0&&e.total>=e.start&&e.messages.length<=e.total-e.start&&!e.messages.some(au)}function au(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&!("content"in e)&&typeof e.role=="string"&&Array.isArray(e.parts)}const lu={read:eu,write:tu,remove:iu};class cu{constructor(t=lu){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return Lo(this.rawHistoryPage(t))}mergeHistory(t,i){const s=su(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),Lo(s)}applyLiveEvent(t,i){return Eh(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 Lo(e){const t=e?.start??0;return{messages:oh(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Da(e,t=e.length){const i=e.slice(0,t),s=du(i,t);if(s!==void 0)return s;const r=pu(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 Wa(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function du(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 pu(e,t){const i=e.lastIndexOf(`
21
- `)+1,s=e.slice(i),r=jo(s,"@ "),o=jo(s,"!@"),n=Math.max(r,o);if(n===-1)return;const a=n===o?"!@":"@ ",c=i+n,p=c+a.length;return{kind:"file",query:e.slice(p),from:c,to:t,fileScope:"all",allPrefix:a}}function jo(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||hu(e[i-1]))return i;return-1}function hu(e){return e===" "||e===" "}function Oi(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:gu(e).startsWith("/")?{kind:"command"}:Da(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function uu(e){return Oi(e).kind==="shell"}function fu(e,t){return e.kind!==t.kind?!1:e.kind==="shell"&&t.kind==="shell"?e.excludeFromContext===t.excludeFromContext:!0}function gu(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
- `))+1;return e.slice(t)}class mu{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),_a(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=bp(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 Oa(t);vu(i)&&this.onEvent?.(i)}}class Fo{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),_a(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=wp(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 Oa(t);wu(i)&&this.onEvent?.(i)}}function vu(e){const t=Cr(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 bu(e){const t=Cr(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function wu(e){const t=Cr(e);return bu(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function Cr(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Oa(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 _a(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 Zi{constructor(t,i,s=Zt()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[r,o]of yu(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 yu(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const r=JSON.parse(s);if(!xu(r))return[];const o=[];for(const n of r.entries){const a=n[0],c=t(n[1]);c!==void 0&&o.push([a,c])}return o}catch{return[]}}function xu(e){return!Su(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 Su(e){return typeof e=="object"&&e!==null}class ku{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 $u="pi-web:session-selection:v1";class Pu{constructor(t=Zt()){this.sessionIdsByCwd=new Zi($u,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 Cu(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return Iu(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 Ru(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function Iu(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function Au(e,t,i){return mi(e,[t],i)}function mi(e,t,i){const s=new Set(t);return e.map(r=>s.has(r.id)?{...r,archived:!0,archivedAt:i}:r)}function Tu(e,t,i){return vi(e,t,[i])}function vi(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 Et=100;class Mu{constructor(t,i,s,r=new ku,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.socket=o.socket??new mu,this.api=o.api??N,this.transcripts=o.transcripts??new cu}applyGlobalEvent(t){t.type==="status.update"?this.queueStatusUpdate(t.status):t.type==="activity.update"?this.queueActivityUpdate(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingUpdates()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0,availableThinkingLevels:[]})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();Ru(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);Mo(s,i);const r=Gs(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 Cu(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates();const r=this.sessionCacheKey(t.id),o=this.transcripts.cachedView(r);this.setState({selectedSession:t,...o,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const u=await this.api.messages(t,{limit:Et},f(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(r,u);this.setState({...h,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t,u=>n.push(u),()=>{this.refreshSelectedSession(t.id)},f(this.getState()));const[a,c]=await Promise.all([this.api.messages(t,{limit:Et},f(this.getState())),this.api.status(t,f(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(r,a);this.setState({...p,isLoadingEarlierMessages:!1,...this.setStreamCatchup(c.isStreaming?t.id:void 0),status:c,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(c),this.refreshAvailableThinkingLevels();for(const u of n)this.applyEvent(u);this.socket.setHandler(u=>{this.applyEvent(u)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(Z(t)&&Uu(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:Et},f(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(r)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i,s,r="inline"){const o=t.trim(),n=s!==void 0&&s.length>0;if(!n&&o.startsWith("/"))return this.runCommand(t);if(!n&&uu(t))return this.runShell(t);const a=this.getState().selectedSession;if(!a||a.archived===!0)return;const c=a.id,p=f(this.getState());n&&this.markSendingPrompt(c,!0);try{if(n&&r==="folder"){const h=(await this.api.saveAttachments(a,s,p)).map(b=>Wa(b.path,!1)).join(" "),g=t===""?h:`${t}
19
+ `)}function Qh(e,t){const i=kr(t);return i.length===0?e:[...e,...i]}function Zh(e,t){const i=e.at(-1);return Xh(e,t)?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Xh(e,t){const i=Ei(t);if(t.role!=="skill"||i.length===0)return!1;const s=_a(e)+1;return i.every(r=>Yh(e,r,s))}function Yh(e,t,i){for(let s=e.length-1;s>=i;s--)if(Ei(e[s]).some(r=>Oa(r,t)))return!0;return!1}function _a(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="user")return t;return-1}function eu(e){return typeof e=="object"&&e!==null}function Di(e,t){return eu(e)?e[t]:void 0}function lt(e,t){const i=Di(e,t);return typeof i=="string"?i:void 0}function tu(e,t){const i=Di(e,t);return typeof i=="boolean"?i:void 0}const iu="pi-web:chat-history:v2:",su=1800*1e3;function ru(e){try{const t=sessionStorage.getItem(Wi(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!du(i))return;if(Date.now()-i.savedAt>su){sessionStorage.removeItem(Wi(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function ou(e,t){try{sessionStorage.setItem(Wi(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function nu(e){try{sessionStorage.removeItem(Wi(e))}catch{}}function au(e,t){if(e===void 0||!Js(e))return t;if(!Js(t))return e;if(lu(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 _o(r,i,e),_o(r,i,t),cu(r)?t:{start:i,total:Math.max(e.total,t.total),messages:r}}function lu(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function cu(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function _o(e,t,i){i.messages.forEach((s,r)=>{e[i.start-t+r]=s})}function Wi(e){return`${iu}${e}`}function du(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"&&Js({messages:t,start:i,total:s})}function Js(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(pu)}function pu(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 hu={read:ru,write:ou,remove:nu};class uu{constructor(t=hu){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return Lo(this.rawHistoryPage(t))}mergeHistory(t,i){const s=au(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),Lo(s)}applyLiveEvent(t,i){return _h(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 Lo(e){const t=e?.start??0;return{messages:ch(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function La(e,t=e.length){const i=e.slice(0,t),s=fu(i,t);if(s!==void 0)return s;const r=gu(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 ja(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function fu(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 gu(e,t){const i=e.lastIndexOf(`
21
+ `)+1,s=e.slice(i),r=jo(s,"@ "),o=jo(s,"!@"),n=Math.max(r,o);if(n===-1)return;const a=n===o?"!@":"@ ",c=i+n,p=c+a.length;return{kind:"file",query:e.slice(p),from:c,to:t,fileScope:"all",allPrefix:a}}function jo(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||mu(e[i-1]))return i;return-1}function mu(e){return e===" "||e===" "}function Oi(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:wu(e).startsWith("/")?{kind:"command"}:La(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function vu(e){return Oi(e).kind==="shell"}function bu(e,t){return e.kind!==t.kind?!1:e.kind==="shell"&&t.kind==="shell"?e.excludeFromContext===t.excludeFromContext:!0}function wu(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
+ `))+1;return e.slice(t)}class yu{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),Ua(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=Sp(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 Fa(t);xu(i)&&this.onEvent?.(i)}}class Fo{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),Ua(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=kp(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 Fa(t);ku(i)&&this.onEvent?.(i)}}function xu(e){const t=Cr(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 Su(e){const t=Cr(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function ku(e){const t=Cr(e);return Su(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function Cr(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Fa(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 Ua(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 Zi{constructor(t,i,s=Zt()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[r,o]of $u(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 Ir(e){return typeof e=="string"&&e!==""?e:void 0}function $u(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const r=JSON.parse(s);if(!Pu(r))return[];const o=[];for(const n of r.entries){const a=n[0],c=t(n[1]);c!==void 0&&o.push([a,c])}return o}catch{return[]}}function Pu(e){return!Cu(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 Cu(e){return typeof e=="object"&&e!==null}class Iu{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 Ru="pi-web:session-selection:v1";class Au{constructor(t=Zt()){this.sessionIdsByCwd=new Zi(Ru,Ir,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function Tu(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return Eu(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 Mu(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function Eu(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function Du(e,t,i){return mi(e,[t],i)}function mi(e,t,i){const s=new Set(t);return e.map(r=>s.has(r.id)?{...r,archived:!0,archivedAt:i}:r)}function Wu(e,t,i){return vi(e,t,[i])}function vi(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 Et=100;class Ou{constructor(t,i,s,r=new Iu,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.socket=o.socket??new yu,this.api=o.api??N,this.transcripts=o.transcripts??new uu}applyGlobalEvent(t){t.type==="status.update"?this.queueStatusUpdate(t.status):t.type==="activity.update"?this.queueActivityUpdate(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingUpdates()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0,availableThinkingLevels:[]})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();Mu(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);Mo(s,i);const r=Gs(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 Tu(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates();const r=this.sessionCacheKey(t.id),o=this.transcripts.cachedView(r);this.setState({selectedSession:t,...o,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const u=await this.api.messages(t,{limit:Et},f(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(r,u);this.setState({...h,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t,u=>n.push(u),()=>{this.refreshSelectedSession(t.id)},f(this.getState()));const[a,c]=await Promise.all([this.api.messages(t,{limit:Et},f(this.getState())),this.api.status(t,f(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(r,a);this.setState({...p,isLoadingEarlierMessages:!1,...this.setStreamCatchup(c.isStreaming?t.id:void 0),status:c,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(c),this.refreshAvailableThinkingLevels();for(const u of n)this.applyEvent(u);this.socket.setHandler(u=>{this.applyEvent(u)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(Z(t)&&Hu(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:Et},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&&vu(t))return this.runShell(t);const a=this.getState().selectedSession;if(!a||a.archived===!0)return;const c=a.id,p=f(this.getState());n&&this.markSendingPrompt(c,!0);try{if(n&&r==="folder"){const h=(await this.api.saveAttachments(a,s,p)).map(b=>ja(b.path,!1)).join(" "),g=t===""?h:`${t}
23
23
 
24
- ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.markCachedNewSessionPersisted(a)}catch(u){this.setState({error:String(u)})}finally{n&&this.markSendingPrompt(c,!1)}}markSendingPrompt(t,i){const s=this.getState().sendingPrompts;i?s[t]!==!0&&this.setState({sendingPrompts:{...s,[t]:!0}}):t in s&&this.setState({sendingPrompts:La(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Oe("user",t)]});try{await this.api.shell(i,t,f(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Oe("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,Oe("system",String(r))],error:String(r)})}finally{this.markSendingPrompt(s,!1)}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s,t,i,f(this.getState())))}catch(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(Z(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,f(this.getState()));const i=this.getState(),s=Au(i.sessions,t.id,new Date().toISOString()),r=Tu(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),r.type==="select"?await this.selectSession(r.session):r.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||Z(t)))try{const i=await this.api.archiveWithDescendants(t,f(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],r=this.getState(),o=mi(r.sessions,s,new Date().toISOString()),n=vi(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=zo(t).filter(n=>n.archived!==!0&&!Z(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=Bo(r);if(o.length>0){const n=this.getState(),a=mi(n.sessions,o,new Date().toISOString()),c=vi(a,n.selectedSession?.id,o);this.setState({sessions:a}),c.type==="select"?await this.selectSession(c.session):c.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionError("Archive",r)}async deleteArchivedSessions(t){const i=zo(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||!at(r,Qe.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=Bo(o);if(n.length>0){const a=new Set(n),c=this.getState(),p=c.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),c.selectedSession!==void 0&&a.has(c.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionError("Delete",o)}async applySessionCleanupResult(t,i=f(this.getState())){if(f(this.getState())!==i)return;const s=t.archivedSessionIds,r=t.deletedSessionIds;if(s.length>0||r.length>0){const o=this.getState(),n=new Set(r),a=[...s,...r],c=mi(o.sessions,s,t.generatedAt).filter(u=>!n.has(u.id)),p=o.selectedSession!==void 0&&a.includes(o.selectedSession.id);if(this.setState({sessions:c,sessionStatuses:Uo(o.sessionStatuses,a),sessionActivities:Uo(o.sessionActivities,a),...p?{status:void 0,activity:void 0}:{}}),o.selectedSession!==void 0&&n.has(o.selectedSession.id)){const u=c.find(h=>h.archived!==!0)??c[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}else{const u=vi(c,o.selectedSession?.id,s);u.type==="select"?await this.selectSession(u.session):u.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(i)}async refreshCurrentWorkspaceSessions(t=f(this.getState())){const i=this.getState().selectedWorkspace;if(i!==void 0)try{const s=Ca(i.path,await this.api.sessions(i.path,t),t);if(f(this.getState())!==t||this.getState().selectedWorkspace?.id!==i.id)return;const r=this.getState().selectedSession;if(this.setState({sessions:s}),r===void 0)return;const o=s.find(a=>a.id===r.id);if(o!==void 0){o!==r&&this.setState({selectedSession:o});return}const n=s.find(a=>a.archived!==!0)??s[0];n!==void 0?await this.selectSession(n):this.deselectSession({forgetRememberedSelection:!0})}catch(s){f(this.getState())===t&&this.getState().selectedWorkspace?.id===i.id&&this.setState({error:String(s)})}}async deleteCachedNewSession(t=this.getState().selectedSession){if(!Z(t))return;this.api.stop(t,f(this.getState())).catch(()=>{}),Eo(t.id,f(this.getState())),Pr(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(r=>r.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(r=>r.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t,f(this.getState()));const i={...t};delete i.archived,delete i.archivedAt,this.replaceSession(i),this.getState().selectedSession?.id===i.id&&await this.selectSession(i)}catch(i){this.setState({error:String(i)})}}async reloadSession(t=this.getState().selectedSession){if(t===void 0||Z(t)||t.archived===!0)return;const i=f(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!at(s,Qe.sessionsReload)){this.setState({error:"Reloading sessions requires an updated Pi-Web runtime on this machine."});return}try{await this.api.reloadSession(t.id,i),this.transcripts.discard(this.sessionCacheKey(t.id)),this.getState().selectedSession?.id===t.id&&await this.selectSession(t,{updateUrl:!1})}catch(r){this.setState({error:String(r)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t,f(this.getState()));const i={...t};delete i.parentSessionPath,this.replaceSession(i)}catch(i){this.setState({error:String(i)})}}async listModels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.models(t,f(this.getState()))).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s,t,i,f(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(r){this.setState({error:String(r)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,f(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(s){this.setState({error:String(s)})}}async listThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.thinkingLevels(t,f(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async refreshAvailableThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}const i=await this.listThinkingLevels();this.getState().selectedSession?.id===t.id&&this.setState({availableThinkingLevels:i})}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i,t,f(this.getState())))}catch(s){this.setState({error:String(s)})}}async cycleThinkingLevel(){const t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(t,f(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,f(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingUpdates();const[s,r]=await Promise.all([this.api.messages(i,{limit:Et},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=Du(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return Pa(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);Mo(r,s),Rh(this.sessionCacheKey(t.id),this.sessionCacheKey(r.id)),Eo(t.id,s);const o=Gs(r,s);this.setState({sessions:[o,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(o,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!Z(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(eh(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,Oe(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&Mi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,r=[t.session,...this.getState().sessions.filter(o=>o.id!==t.session?.id)];this.setState({sessions:r,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();i.selectedWorkspace?.path===t.cwd&&(i.sessions.some(s=>s.id===t.id)||this.setState({sessions:[t,...i.sessions]}))}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Xe(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...Lu(i,t.sessionId,t.messageCount),...s?{sessionActivities:Eu(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(ju(t))return}if(t.type==="status.update"){this.queueStatusUpdate(t.status);return}if(t.type==="activity.update"){this.queueActivityUpdate(t.activity);return}if(Fu(t)){this.queueTranscriptEvent(t);return}this.flushPendingUpdates();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.schedulePendingFlush()}queueStatusUpdate(t){this.pendingStatusBySession.set(t.sessionId,t),this.schedulePendingFlush()}queueActivityUpdate(t){this.pendingActivityBySession.set(t.sessionId,t),this.schedulePendingFlush()}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}if(this.pendingActivityBySession.size>0){const t=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(const i of t)this.applyActivity(i)}if(this.pendingStatusBySession.size>0){const t=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(const i of t)this.applyStatus(i)}}clearPendingUpdates(){this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0)}setStreamCatchup(t){return this.catchupStreamSessionId=t,{isReceivingPartialStream:t!==void 0}}finishStreamCatchup(t){const i=this.getState().selectedSession?.id===t;(this.catchupStreamSessionId===t||i&&this.getState().isReceivingPartialStream)&&(this.catchupStreamSessionId=void 0,i&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:Et},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 Eu(e,t){return La(e,t)}function La(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Uo(e,t){if(t.length===0)return e;const i=new Set(t);return Object.fromEntries(Object.entries(e).filter(([s])=>!i.has(s)))}function zo(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 Bo(e){return e.filter(Wu).map(t=>t.value)}function Du(e){return e.filter(Ou).map(t=>_u(t.reason))}function Wu(e){return e.status==="fulfilled"}function Ou(e){return e.status==="rejected"}function _u(e){return e instanceof Error?e.message:String(e)}function Lu(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 ju(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 Fu(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function Uu(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("session not found")||t.includes("未找到会话")}class zu{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 Bu="pi-web:workspace-selection:v1";class Nu{constructor(t=Zt()){this.workspaceIdsByProject=new Zi(Bu,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 Hu(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 qu{constructor(t,i,s,r,o=new zu,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=r,this.workspaceSelection=o,this.api=n.api??N}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...fi()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(gs(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,...fi()});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=Hu(r,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(gs(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:gs(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...fi()});try{const r=Ca(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=Vu(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 Ku(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function Vu(e){return e.find(t=>t.isMain)??e[0]}const Gu="pi-web:machine-navigation:v1";class Ju{constructor(t=Zt()){this.snapshotsByMachine=new Zi(Gu,Zu,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?qo(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,qo(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Qu(e){return{machineId:e,surface:{}}}function No(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??$a,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 Ho(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 qo(e){return{...e,surface:{...e.surface}}}function Zu(e){if(!Fa(e))return;const t=Ue(e,"machineId");if(t===void 0)return;const i=ja(Ue(e,"tool")),s=Yu(Ue(e,"view"));return{machineId:t,projectId:Ue(e,"projectId"),workspaceId:Ue(e,"workspaceId"),sessionId:Ue(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:Xu(e.surface)}}function Xu(e){return Fa(e)?{selectedFilePath:Ue(e,"selectedFilePath"),selectedDiffPath:Ue(e,"selectedDiffPath"),selectedTerminalId:Ue(e,"selectedTerminalId")}:{}}function Yu(e){return e==="navigation"||e==="chat"?e:ja(e)}function ja(e){return ef(e)?e:void 0}function ef(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Ue(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Fa(e){return typeof e=="object"&&e!==null}const tf="pi-web:terminal-selection:v1";class sf{constructor(t=Zt()){this.terminalIdsByCwd=new Zi(tf,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 V0(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 G0(e){return e.find(t=>!t.exited)??e[0]}const Ua=1200,rf=["mod","alt","shift"];class of{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const r=Ba(t);if(r===void 0)return!1;const o=Ir(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(),!Kt(r))return!1}else if(!Kt(r))return!1;return this.handleSequence([r],o)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(o=>gf(o.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(o=>Ar(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},Ua)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Ir(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=nf(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(Qs)[0];u!==void 0&&o.set(u.key,u)}const n=[...o.values()].sort(cf),a=new Map,c=new Map;for(const p of s){const u=o.get(p.key);if(u===void 0)continue;const h=df(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,g=u===void 0||h?void 0:Ko(u),b=h?[...a.get(p)??[]].sort(Qs).map(Ko):[];return{...p,active:h,shadows:b,...g===void 0?{}:{shadowedBy:g}}}).sort((p,u)=>p.order-u.order)}function ys(e){return Na(e,{requireFirstChordActivator:!0})}function za(e){const t=Na(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function bi(e){return za(e).map(t=>t.split("+").map(qa).join("+")).join(" ")}function Ba(e){if(e.isComposing)return;const t=uf(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 Kt(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function nf(e,t,i){const s=af(e.id,t);if(s===null)return;const r=s??e.shortcut;if(r===void 0||r==="")return;const o=za(r),n=o[0];if(!(n===void 0||!Kt(n)))return{action:e,shortcut:o.join(" "),source:s===void 0?"default":"custom",tokens:o,key:lf(o),order:i}}function af(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function lf(e){return e.join("\0")}function Ko(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Qs(e,t){return Vo(e.source)-Vo(t.source)||Go(e.action.id,t.action.id)||Go(e.action.title,t.action.title)||e.order-t.order}function cf(e,t){return e.tokens.length-t.tokens.length||Qs(e,t)}function df(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&Ar(e.tokens,i.tokens))}function Vo(e){switch(e){case"custom":return 0;case"default":return 1}}function Go(e,t){return e<t?-1:e>t?1:0}function Na(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=pf(n);if(!a.ok)return a;if(o===0&&t.requireFirstChordActivator&&!Kt(a.token))return{ok:!1,message:"快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。"};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function pf(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=hf(o);if(n!==void 0){if(i.has(n))return{ok:!1,message:`快捷键包含重复的 ${qa(n)} 修饰键。`};i.add(n);continue}const a=Ha(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:[...rf.filter(o=>i.has(o)),s].join("+")}}function hf(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 Ha(e){const t=ff(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function uf(e){if(e===" ")return"space";const t=e.toLowerCase();return Ha(t)}function ff(e){switch(e){case" ":case"spacebar":case"space":return"space";case"esc":case"escape":return"escape";case"return":case"enter":return"enter";case"del":case"delete":return"delete";case"backspace":return"backspace";case"tab":return"tab";case"up":case"arrowup":return"arrowup";case"down":case"arrowdown":return"arrowdown";case"left":case"arrowleft":return"arrowleft";case"right":case"arrowright":return"arrowright";case"pageup":case"pagedown":case"home":case"end":return e;case"+":case"plus":return"plus";case"period":case"dot":return".";case"comma":return",";case"slash":return"/";case"backslash":return"\\";case"minus":return"-";default:return}}function qa(e){return e==="mod"?Jo()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?Jo()?"⌥":"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 gf(e,t){return e.length===t.length&&Ar(e,t)}function Ar(e,t){return t.every((i,s)=>e[s]===i)}function Jo(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const mf={archiveIdleEnabled:!0,archiveIdleDays:"30",deleteArchivedEnabled:!1,deleteArchivedDays:"90"};function Ft(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:"Enable at least one cleanup action."};const t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){const i=Xo(e.archiveIdleDays,"Archive idle sessions after");if(typeof i=="string")return{ok:!1,error:i};t.archiveIdleDays=i}if(e.deleteArchivedEnabled){const i=Xo(e.deleteArchivedDays,"Delete archived sessions after");if(typeof i=="string")return{ok:!1,error:i};t.deleteArchivedDays=i}return{ok:!0,request:t}}function kt(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function Qo(e){if(!e.canCleanup||e.loading===!0||e.running===!0||e.preview===void 0)return!1;const t=Ft(e.draft);return!t.ok||kt(t.request)!==kt(e.previewRequest)?!1:wi(e.preview)}function wi(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function Ka(e,t){const i=e.projects.map(r=>r.cwd);if(t===void 0)return i;const s=new Set(t);return i.filter(r=>s.has(r))}function Zo(e,t){const i=new Set(Ka(e,t)),s=e.projects.filter(r=>i.has(r.cwd));return{...e,projects:s,totals:s.reduce((r,o)=>({archiveCount:r.archiveCount+o.archiveCount,deleteCount:r.deleteCount+o.deleteCount}),{archiveCount:0,deleteCount:0})}}function vf(e,t){return t(bf(e))}function bf(e){const t=e.totals.archiveCount,i=e.totals.deleteCount,s=[];return t>0&&s.push(`archive ${String(t)} idle ${t===1?"session":"sessions"}`),i>0&&s.push(`permanently delete ${String(i)} archived ${i===1?"session":"sessions"}`),`Run cleanup and ${s.length===0?"run cleanup":s.join(" and ")}?
24
+ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.markCachedNewSessionPersisted(a)}catch(u){this.setState({error:String(u)})}finally{n&&this.markSendingPrompt(c,!1)}}markSendingPrompt(t,i){const s=this.getState().sendingPrompts;i?s[t]!==!0&&this.setState({sendingPrompts:{...s,[t]:!0}}):t in s&&this.setState({sendingPrompts:za(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Oe("user",t)]});try{await this.api.shell(i,t,f(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Oe("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,Oe("system",String(r))],error:String(r)})}finally{this.markSendingPrompt(s,!1)}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s,t,i,f(this.getState())))}catch(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(Z(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,f(this.getState()));const i=this.getState(),s=Du(i.sessions,t.id,new Date().toISOString()),r=Wu(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),r.type==="select"?await this.selectSession(r.session):r.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||Z(t)))try{const i=await this.api.archiveWithDescendants(t,f(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],r=this.getState(),o=mi(r.sessions,s,new Date().toISOString()),n=vi(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=zo(t).filter(n=>n.archived!==!0&&!Z(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=Bo(r);if(o.length>0){const n=this.getState(),a=mi(n.sessions,o,new Date().toISOString()),c=vi(a,n.selectedSession?.id,o);this.setState({sessions:a}),c.type==="select"?await this.selectSession(c.session):c.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionError("Archive",r)}async deleteArchivedSessions(t){const i=zo(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||!at(r,Qe.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=Bo(o);if(n.length>0){const a=new Set(n),c=this.getState(),p=c.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),c.selectedSession!==void 0&&a.has(c.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionError("Delete",o)}async applySessionCleanupResult(t,i=f(this.getState())){if(f(this.getState())!==i)return;const s=t.archivedSessionIds,r=t.deletedSessionIds;if(s.length>0||r.length>0){const o=this.getState(),n=new Set(r),a=[...s,...r],c=mi(o.sessions,s,t.generatedAt).filter(u=>!n.has(u.id)),p=o.selectedSession!==void 0&&a.includes(o.selectedSession.id);if(this.setState({sessions:c,sessionStatuses:Uo(o.sessionStatuses,a),sessionActivities:Uo(o.sessionActivities,a),...p?{status:void 0,activity:void 0}:{}}),o.selectedSession!==void 0&&n.has(o.selectedSession.id)){const u=c.find(h=>h.archived!==!0)??c[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}else{const u=vi(c,o.selectedSession?.id,s);u.type==="select"?await this.selectSession(u.session):u.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(i)}async refreshCurrentWorkspaceSessions(t=f(this.getState())){const i=this.getState().selectedWorkspace;if(i!==void 0)try{const s=Ta(i.path,await this.api.sessions(i.path,t),t);if(f(this.getState())!==t||this.getState().selectedWorkspace?.id!==i.id)return;const r=this.getState().selectedSession;if(this.setState({sessions:s}),r===void 0)return;const o=s.find(a=>a.id===r.id);if(o!==void 0){o!==r&&this.setState({selectedSession:o});return}const n=s.find(a=>a.archived!==!0)??s[0];n!==void 0?await this.selectSession(n):this.deselectSession({forgetRememberedSelection:!0})}catch(s){f(this.getState())===t&&this.getState().selectedWorkspace?.id===i.id&&this.setState({error:String(s)})}}async deleteCachedNewSession(t=this.getState().selectedSession){if(!Z(t))return;this.api.stop(t,f(this.getState())).catch(()=>{}),Eo(t.id,f(this.getState())),Pr(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(r=>r.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(r=>r.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t,f(this.getState()));const i={...t};delete i.archived,delete i.archivedAt,this.replaceSession(i),this.getState().selectedSession?.id===i.id&&await this.selectSession(i)}catch(i){this.setState({error:String(i)})}}async reloadSession(t=this.getState().selectedSession){if(t===void 0||Z(t)||t.archived===!0)return;const i=f(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!at(s,Qe.sessionsReload)){this.setState({error:"Reloading sessions requires an updated Pi-Web runtime on this machine."});return}try{await this.api.reloadSession(t.id,i),this.transcripts.discard(this.sessionCacheKey(t.id)),this.getState().selectedSession?.id===t.id&&await this.selectSession(t,{updateUrl:!1})}catch(r){this.setState({error:String(r)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t,f(this.getState()));const i={...t};delete i.parentSessionPath,this.replaceSession(i)}catch(i){this.setState({error:String(i)})}}async listModels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.models(t,f(this.getState()))).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s,t,i,f(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(r){this.setState({error:String(r)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,f(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(s){this.setState({error:String(s)})}}async listThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.thinkingLevels(t,f(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async refreshAvailableThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}const i=await this.listThinkingLevels();this.getState().selectedSession?.id===t.id&&this.setState({availableThinkingLevels:i})}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i,t,f(this.getState())))}catch(s){this.setState({error:String(s)})}}async cycleThinkingLevel(){const t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(t,f(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,f(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingUpdates();const[s,r]=await Promise.all([this.api.messages(i,{limit:Et},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=Lu(i);s.length!==0&&this.setState({error:`${t} failed for ${String(s.length)} session${s.length===1?"":"s"}: ${s.join("; ")}`})}sessionCacheKey(t){return Aa(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);Mo(r,s),Mh(this.sessionCacheKey(t.id),this.sessionCacheKey(r.id)),Eo(t.id,s);const o=Gs(r,s);this.setState({sessions:[o,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(o,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!Z(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(rh(i))}applyCommandResult(t){if(t.type==="select"){this.setState({commandDialog:t});return}const i=(t.type==="unsupported",t.message);if(i!==void 0&&i!==""&&this.setState({messages:[...this.getState().messages,Oe(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&Mi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,r=[t.session,...this.getState().sessions.filter(o=>o.id!==t.session?.id)];this.setState({sessions:r,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();i.selectedWorkspace?.path===t.cwd&&(i.sessions.some(s=>s.id===t.id)||this.setState({sessions:[t,...i.sessions]}))}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Xe(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...zu(i,t.sessionId,t.messageCount),...s?{sessionActivities:_u(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(Bu(t))return}if(t.type==="status.update"){this.queueStatusUpdate(t.status);return}if(t.type==="activity.update"){this.queueActivityUpdate(t.activity);return}if(Nu(t)){this.queueTranscriptEvent(t);return}this.flushPendingUpdates();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.schedulePendingFlush()}queueStatusUpdate(t){this.pendingStatusBySession.set(t.sessionId,t),this.schedulePendingFlush()}queueActivityUpdate(t){this.pendingActivityBySession.set(t.sessionId,t),this.schedulePendingFlush()}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}if(this.pendingActivityBySession.size>0){const t=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(const i of t)this.applyActivity(i)}if(this.pendingStatusBySession.size>0){const t=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(const i of t)this.applyStatus(i)}}clearPendingUpdates(){this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0)}setStreamCatchup(t){return this.catchupStreamSessionId=t,{isReceivingPartialStream:t!==void 0}}finishStreamCatchup(t){const i=this.getState().selectedSession?.id===t;(this.catchupStreamSessionId===t||i&&this.getState().isReceivingPartialStream)&&(this.catchupStreamSessionId=void 0,i&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:Et},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 _u(e,t){return za(e,t)}function za(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Uo(e,t){if(t.length===0)return e;const i=new Set(t);return Object.fromEntries(Object.entries(e).filter(([s])=>!i.has(s)))}function zo(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 Bo(e){return e.filter(ju).map(t=>t.value)}function Lu(e){return e.filter(Fu).map(t=>Uu(t.reason))}function ju(e){return e.status==="fulfilled"}function Fu(e){return e.status==="rejected"}function Uu(e){return e instanceof Error?e.message:String(e)}function zu(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 Bu(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 Nu(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function Hu(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("session not found")||t.includes("未找到会话")}class qu{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 Ku="pi-web:workspace-selection:v1";class Vu{constructor(t=Zt()){this.workspaceIdsByProject=new Zi(Ku,Ir,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function Gu(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 Ju{constructor(t,i,s,r,o=new qu,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=r,this.workspaceSelection=o,this.api=n.api??N}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...fi()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(gs(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,...fi()});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=Gu(r,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(gs(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:gs(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...fi()});try{const r=Ta(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=Zu(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 Qu(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function Zu(e){return e.find(t=>t.isMain)??e[0]}const Xu="pi-web:machine-navigation:v1";class Yu{constructor(t=Zt()){this.snapshotsByMachine=new Zi(Xu,tf,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?qo(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,qo(t))}forget(t){this.snapshotsByMachine.delete(t)}}function ef(e){return{machineId:e,surface:{}}}function No(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??Ra,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 Ho(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 qo(e){return{...e,surface:{...e.surface}}}function tf(e){if(!Na(e))return;const t=Ue(e,"machineId");if(t===void 0)return;const i=Ba(Ue(e,"tool")),s=rf(Ue(e,"view"));return{machineId:t,projectId:Ue(e,"projectId"),workspaceId:Ue(e,"workspaceId"),sessionId:Ue(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:sf(e.surface)}}function sf(e){return Na(e)?{selectedFilePath:Ue(e,"selectedFilePath"),selectedDiffPath:Ue(e,"selectedDiffPath"),selectedTerminalId:Ue(e,"selectedTerminalId")}:{}}function rf(e){return e==="navigation"||e==="chat"?e:Ba(e)}function Ba(e){return of(e)?e:void 0}function of(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Ue(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Na(e){return typeof e=="object"&&e!==null}const nf="pi-web:terminal-selection:v1";class af{constructor(t=Zt()){this.terminalIdsByCwd=new Zi(nf,Ir,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 Y0(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 ex(e){return e.find(t=>!t.exited)??e[0]}const Ha=1200,lf=["mod","alt","shift"];class cf{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const r=Ka(t);if(r===void 0)return!1;const o=Rr(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(),!Kt(r))return!1}else if(!Kt(r))return!1;return this.handleSequence([r],o)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(o=>wf(o.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(o=>Ar(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},Ha)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Rr(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=df(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(Qs)[0];u!==void 0&&o.set(u.key,u)}const n=[...o.values()].sort(uf),a=new Map,c=new Map;for(const p of s){const u=o.get(p.key);if(u===void 0)continue;const h=ff(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,g=u===void 0||h?void 0:Ko(u),b=h?[...a.get(p)??[]].sort(Qs).map(Ko):[];return{...p,active:h,shadows:b,...g===void 0?{}:{shadowedBy:g}}}).sort((p,u)=>p.order-u.order)}function ys(e){return Va(e,{requireFirstChordActivator:!0})}function qa(e){const t=Va(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function bi(e){return qa(e).map(t=>t.split("+").map(Ja).join("+")).join(" ")}function Ka(e){if(e.isComposing)return;const t=vf(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 Kt(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function df(e,t,i){const s=pf(e.id,t);if(s===null)return;const r=s??e.shortcut;if(r===void 0||r==="")return;const o=qa(r),n=o[0];if(!(n===void 0||!Kt(n)))return{action:e,shortcut:o.join(" "),source:s===void 0?"default":"custom",tokens:o,key:hf(o),order:i}}function pf(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function hf(e){return e.join("\0")}function Ko(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Qs(e,t){return Vo(e.source)-Vo(t.source)||Go(e.action.id,t.action.id)||Go(e.action.title,t.action.title)||e.order-t.order}function uf(e,t){return e.tokens.length-t.tokens.length||Qs(e,t)}function ff(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&Ar(e.tokens,i.tokens))}function Vo(e){switch(e){case"custom":return 0;case"default":return 1}}function Go(e,t){return e<t?-1:e>t?1:0}function Va(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=gf(n);if(!a.ok)return a;if(o===0&&t.requireFirstChordActivator&&!Kt(a.token))return{ok:!1,message:"快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。"};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function gf(e){const t=e.split("+").filter(o=>o!=="");if(t.length===0)return{ok:!1,message:"快捷键组合必须包含一个按键。"};const i=new Set;let s;for(const o of t){const n=mf(o);if(n!==void 0){if(i.has(n))return{ok:!1,message:`快捷键包含重复的 ${Ja(n)} 修饰键。`};i.add(n);continue}const a=Ga(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:[...lf.filter(o=>i.has(o)),s].join("+")}}function mf(e){switch(e){case"mod":case"meta":case"cmd":case"command":case"ctrl":case"control":case"primary":return"mod";case"alt":case"option":case"opt":return"alt";case"shift":return"shift";default:return}}function Ga(e){const t=bf(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 vf(e){if(e===" ")return"space";const t=e.toLowerCase();return Ga(t)}function bf(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 Ja(e){return e==="mod"?Jo()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?Jo()?"⌥":"Alt":e==="enter"?"Enter":e==="escape"?"Esc":e==="space"?"Space":e==="tab"?"Tab":e==="backspace"?"Backspace":e==="delete"?"Delete":e==="arrowup"?"↑":e==="arrowdown"?"↓":e==="arrowleft"?"←":e==="arrowright"?"→":e==="pageup"?"PageUp":e==="pagedown"?"PageDown":e==="home"?"Home":e==="end"?"End":e==="plus"?"+":/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function wf(e,t){return e.length===t.length&&Ar(e,t)}function Ar(e,t){return t.every((i,s)=>e[s]===i)}function Jo(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const yf={archiveIdleEnabled:!0,archiveIdleDays:"30",deleteArchivedEnabled:!1,deleteArchivedDays:"90"};function Ft(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:"请至少启用一项清理操作。"};const t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){const i=Xo(e.archiveIdleDays,"归档空闲会话天数");if(typeof i=="string")return{ok:!1,error:i};t.archiveIdleDays=i}if(e.deleteArchivedEnabled){const i=Xo(e.deleteArchivedDays,"删除已归档会话天数");if(typeof i=="string")return{ok:!1,error:i};t.deleteArchivedDays=i}return{ok:!0,request:t}}function kt(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function Qo(e){if(!e.canCleanup||e.loading===!0||e.running===!0||e.preview===void 0)return!1;const t=Ft(e.draft);return!t.ok||kt(t.request)!==kt(e.previewRequest)?!1:wi(e.preview)}function wi(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function Qa(e,t){const i=e.projects.map(r=>r.cwd);if(t===void 0)return i;const s=new Set(t);return i.filter(r=>s.has(r))}function Zo(e,t){const i=new Set(Qa(e,t)),s=e.projects.filter(r=>i.has(r.cwd));return{...e,projects:s,totals:s.reduce((r,o)=>({archiveCount:r.archiveCount+o.archiveCount,deleteCount:r.deleteCount+o.deleteCount}),{archiveCount:0,deleteCount:0})}}function xf(e,t){return t(Sf(e))}function Sf(e){const t=e.totals.archiveCount,i=e.totals.deleteCount,s=[];return t>0&&s.push(`归档 ${String(t)} 个空闲会话`),i>0&&s.push(`永久删除 ${String(i)} 个已归档会话`),`运行清理并${s.length===0?"执行清理":s.join("并")}?
25
25
 
26
- Permanent deletion only applies to archived sessions and cannot be undone.`}function wf(e){return`Update and restart Pi-Web on ${e??"this machine"} to clean up sessions.`}function Xo(e,t){const i=e.trim();if(i==="")return`${t} must be set.`;const s=Number(i);return!Number.isInteger(s)||s<0?`${t} must be a non-negative whole number of days.`:s}const Tr="themes:classic",yf="themes:pi-web-dark",xf={themeId:yf,auto:!0},Va="pi-web-app-theme",Sf=["--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"],kf=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function $f(){try{const e=window.localStorage.getItem(Va);return e===null?void 0:Af(e)}catch{return}}function Pf(e){try{window.localStorage.setItem(Va,JSON.stringify(e))}catch{}}function Cf(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of Sf){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function Rf(e){const t=If(e.themes,e.fallbackThemeId??Tr),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=Ga(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 If(e,t=Tr){return e.find(i=>i.id===t)??e[0]}function Ga(e,t){return e.find(i=>i.light===t||i.dark===t)}function Af(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return Tf(i)?i:void 0}catch{return}}function Tf(e){if(!Mf(e))return!1;const t=e.themeId,i=e.auto;return Ef(t)&&typeof i=="boolean"}function Mf(e){return typeof e=="object"&&e!==null}function Ef(e){return typeof e=="string"&&kf.test(e)}const Df="management";function Wf(e){return Of(_f())===Df}function Of(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function _f(){return typeof window>"u"?void 0:window.location.search}const Lf="workspace.delete",jf="pi.operation",Ff="target.workspaceId";function Uf(e){return{...e===void 0?{}:{projectId:e},metadata:{[jf]:Lf}}}function zf(e){const t={};for(const i of e){const s=Zs(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 Bf(e){return Object.entries(e).filter(([,t])=>_i(t)).map(([t])=>t)}function Ja(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&_i(i)}function Zs(e){return e.metadata[Ff]}function _i(e){return e.status==="queued"||e.status==="running"}function Yo(){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:Dt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:en,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:Dt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:Dt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:en,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:Dt,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:Nf,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:Dt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:Hf,run:e=>e.archiveSession()},{id:"session.reload",title:"重新加载会话",description:"从磁盘重新读取所选会话,以获取其他进程写入的条目",group:"会话",enabled:Kf,disabledReason:Qa,run:e=>e.reloadSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:qf,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 Dt(e){return e.state.selectedWorkspace!==void 0}function en(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Nf(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!Ja(e.state,t)}function Hf(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!Z(t)}function qf(e){return Z(e.state.selectedSession)}function Kf(e){const t=e.state.selectedSession;return t===void 0||t.archived===!0||Z(t)||Qa(e)!==void 0?!1:!Xe(e.state.status,e.state.activity)}function Qa(e){const t=e.state.selectedSession;if(!(t===void 0||t.archived===!0||Z(t))&&!Xe(e.state.status,e.state.activity))return Vf(e.state,Qe.sessionsReload,"reload sessions")}function Vf(e,t,i){const s=e.machineRuntimes[f(e)];if(!(s?.ok===!0&&at(s,t)))return`Update and restart Pi-Web on ${e.selectedMachine?.name??"this machine"} to ${i}.`}const Gf="modulepreload",Jf=function(e){return"/"+e},tn={},Mr=function(t,i,s){let r=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");r=c(i.map(p=>{if(p=Jf(p),p in tn)return;tn[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":Gf,u||(g.as="script"),g.crossOrigin="",g.href=p,a&&g.setAttribute("nonce",a),document.head.appendChild(g),u)return new Promise((b,P)=>{g.addEventListener("load",b),g.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function o(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return r.then(n=>{for(const a of n||[])a.status==="rejected"&&o(a.reason);return t().catch(o)})};function Qf(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:yi(e)}function yi(e){switch(e){case"navigation":return be`
26
+ 永久删除只适用于已归档会话,且无法撤销。`}function kf(e){return`请更新并重启 ${e??"此机器"} 上的 Pi-Web 后再清理会话。`}function Xo(e,t){const i=e.trim();if(i==="")return`${t}必须设置。`;const s=Number(i);return!Number.isInteger(s)||s<0?`${t}必须是非负整数天数。`:s}const Tr="themes:classic",$f="themes:pi-web-dark",Pf={themeId:$f,auto:!0},Za="pi-web-app-theme",Cf=["--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"],If=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Rf(){try{const e=window.localStorage.getItem(Za);return e===null?void 0:Df(e)}catch{return}}function Af(e){try{window.localStorage.setItem(Za,JSON.stringify(e))}catch{}}function Tf(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of Cf){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function Mf(e){const t=Ef(e.themes,e.fallbackThemeId??Tr),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=Xa(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 Ef(e,t=Tr){return e.find(i=>i.id===t)??e[0]}function Xa(e,t){return e.find(i=>i.light===t||i.dark===t)}function Df(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return Wf(i)?i:void 0}catch{return}}function Wf(e){if(!Of(e))return!1;const t=e.themeId,i=e.auto;return _f(t)&&typeof i=="boolean"}function Of(e){return typeof e=="object"&&e!==null}function _f(e){return typeof e=="string"&&If.test(e)}const Lf="management";function jf(e){return Ff(Uf())===Lf}function Ff(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function Uf(){return typeof window>"u"?void 0:window.location.search}const zf="workspace.delete",Bf="pi.operation",Nf="target.workspaceId";function Hf(e){return{...e===void 0?{}:{projectId:e},metadata:{[Bf]:zf}}}function qf(e){const t={};for(const i of e){const s=Zs(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 Kf(e){return Object.entries(e).filter(([,t])=>_i(t)).map(([t])=>t)}function Ya(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&_i(i)}function Zs(e){return e.metadata[Nf]}function _i(e){return e.status==="queued"||e.status==="running"}function Yo(){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:Dt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:en,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:Dt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:Dt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:en,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:Dt,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:Vf,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:Dt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:Gf,run:e=>e.archiveSession()},{id:"session.reload",title:"重新加载会话",description:"从磁盘重新读取所选会话,以获取其他进程写入的条目",group:"会话",enabled:Qf,disabledReason:el,run:e=>e.reloadSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:Jf,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 Dt(e){return e.state.selectedWorkspace!==void 0}function en(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Vf(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!Ya(e.state,t)}function Gf(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!Z(t)}function Jf(e){return Z(e.state.selectedSession)}function Qf(e){const t=e.state.selectedSession;return t===void 0||t.archived===!0||Z(t)||el(e)!==void 0?!1:!Xe(e.state.status,e.state.activity)}function el(e){const t=e.state.selectedSession;if(!(t===void 0||t.archived===!0||Z(t))&&!Xe(e.state.status,e.state.activity))return Zf(e.state,Qe.sessionsReload,"reload sessions")}function Zf(e,t,i){const s=e.machineRuntimes[f(e)];if(!(s?.ok===!0&&at(s,t)))return`Update and restart Pi-Web on ${e.selectedMachine?.name??"this machine"} to ${i}.`}const Xf="modulepreload",Yf=function(e){return"/"+e},tn={},Mr=function(t,i,s){let r=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");r=c(i.map(p=>{if(p=Yf(p),p in tn)return;tn[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":Xf,u||(g.as="script"),g.crossOrigin="",g.href=p,a&&g.setAttribute("nonce",a),document.head.appendChild(g),u)return new Promise((b,P)=>{g.addEventListener("load",b),g.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function o(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return r.then(n=>{for(const a of n||[])a.status==="rejected"&&o(a.reason);return t().catch(o)})};function eg(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:yi(e)}function yi(e){switch(e){case"navigation":return be`
27
27
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
28
28
  <circle cx="6" cy="7" r="1.5"></circle>
29
29
  <path d="M10 7h8"></path>
@@ -57,7 +57,7 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
57
57
  <path d="m7 10 3 3-3 3"></path>
58
58
  <path d="M12 16h5"></path>
59
59
  </svg>
60
- `}}const Zf=10*1024*1024,Xf="10 MB",Yf=E`
60
+ `}}const tg=10*1024*1024,ig="10 MB",sg=E`
61
61
  :host { display: flex; flex-direction: column; min-height: 0; color: var(--pi-text); background: var(--pi-bg); font: 13px system-ui, sans-serif; container-type: inline-size; }
62
62
  header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
63
63
  .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
@@ -112,7 +112,7 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
112
112
  .image-preview img { display: block; max-width: 100%; max-height: 100%; object-fit: contain; border: 1px solid var(--pi-border-muted); border-radius: 8px; background-color: var(--pi-surface); background-image: linear-gradient(45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(-45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%), linear-gradient(-45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%); background-position: 0 0, 0 8px, 8px -8px, -8px 0; background-size: 16px 16px; box-shadow: 0 8px 24px var(--pi-shadow-soft); }
113
113
  pre { margin: 0; padding: 10px; overflow: auto; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; }
114
114
  p { margin: 10px; }
115
- `,eg=E`
115
+ `,rg=E`
116
116
  :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
117
117
  footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
118
118
  footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
@@ -163,7 +163,7 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
163
163
  button { padding: 5px 7px; }
164
164
  .icon-button { width: 34px; height: 34px; }
165
165
  }
166
- `;var tg=Object.defineProperty,ig=Object.getOwnPropertyDescriptor,He=(e,t,i,s)=>{for(var r=s>1?void 0:s?ig(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&&tg(t,i,r),r};let Te=class extends A{constructor(){super(...arguments),this.destinationFolder="",this.overwrite=!1,this.createDirs=!0,this.formError="",this.dragActive=!1,this.dragDepth=0,this.openFilePicker=()=>{this.uploadInput?.click()},this.handleFileInputChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0,i=rn(t?.files);t!==void 0&&(t.value=""),i.length>0&&this.openUploadReview(i)},this.handleDragEnter=e=>{oi(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{oi(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect="copy"),this.dragActive=!0)},this.handleDragLeave=e=>{oi(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!oi(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;const t=rn(e.dataTransfer?.files),i=this.context;t.length>0&&i!==void 0&&ng(i,t)},this.handleDestinationInput=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.destinationFolder=t?.value??"",this.formError=""},this.handleCreateDirsChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.createDirs=t?.checked??!0},this.handleOverwriteChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.overwrite=t?.checked??!1},this.handleDialogKeyDown=e=>{e.key==="Escape"&&(e.preventDefault(),this.closeUploadDialog())}}willUpdate(e){if(!e.has("context"))return;const t=e.get("context");t!==void 0&&this.context!==void 0&&sn(t)!==sn(this.context)&&this.resetPendingUpload()}render(){const e=this.context;return e===void 0?l`<p class="muted">文件不可用。</p>`:l`
166
+ `;var og=Object.defineProperty,ng=Object.getOwnPropertyDescriptor,He=(e,t,i,s)=>{for(var r=s>1?void 0:s?ng(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&&og(t,i,r),r};let Te=class extends A{constructor(){super(...arguments),this.destinationFolder="",this.overwrite=!1,this.createDirs=!0,this.formError="",this.dragActive=!1,this.dragDepth=0,this.openFilePicker=()=>{this.uploadInput?.click()},this.handleFileInputChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0,i=ln(t?.files);t!==void 0&&(t.value=""),i.length>0&&this.openUploadReview(i)},this.handleDragEnter=e=>{oi(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{oi(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect="copy"),this.dragActive=!0)},this.handleDragLeave=e=>{oi(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!oi(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;const t=ln(e.dataTransfer?.files),i=this.context;t.length>0&&i!==void 0&&dg(i,t)},this.handleDestinationInput=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.destinationFolder=t?.value??"",this.formError=""},this.handleCreateDirsChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.createDirs=t?.checked??!0},this.handleOverwriteChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.overwrite=t?.checked??!1},this.handleDialogKeyDown=e=>{e.key==="Escape"&&(e.preventDefault(),this.closeUploadDialog())}}willUpdate(e){if(!e.has("context"))return;const t=e.get("context");t!==void 0&&this.context!==void 0&&on(t)!==on(this.context)&&this.resetPendingUpload()}render(){const e=this.context;if(e===void 0)return l`<p class="muted">文件不可用。</p>`;const t=e.selectedFilePath,i=sn(e.fileTree,e.expandedDirs,t),s=t!==void 0&&t!=="";return l`
167
167
  <section
168
168
  class=${this.dragActive?"files-panel dragging":"files-panel"}
169
169
  @dragenter=${this.handleDragEnter}
@@ -175,7 +175,10 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
175
175
  <strong>文件</strong>
176
176
  ${e.fileTreeStale?l`<span class="stale">过期</span>`:null}
177
177
  <div class="toolbar-actions">
178
+ <button @click=${()=>{this.promptCreateFile(e,i)}}>新建文件</button>
179
+ <button @click=${()=>{this.promptCreateDirectory(e,i)}}>新建文件夹</button>
178
180
  <button aria-label="上传文件" @click=${this.openFilePicker}>上传</button>
181
+ <button class="danger" title=${s?`删除 ${t}`:"请选择要删除的文件或文件夹"} ?disabled=${!s} @click=${()=>{this.confirmDeleteSelectedPath(e)}}>删除</button>
179
182
  <button @click=${e.onRefreshFiles}>刷新</button>
180
183
  </div>
181
184
  <input id="workspace-upload-input" class="visually-hidden" type="file" multiple @change=${this.handleFileInputChange} />
@@ -183,7 +186,7 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
183
186
  ${this.renderUploadProgress(e)}
184
187
  <section class="split">
185
188
  <div class="list tree">
186
- ${e.fileTree.length===0?l`<p class="muted">尚未加载文件。</p>`:e.fileTree.map(t=>this.renderTreeEntry(e,t,0))}
189
+ ${e.fileTree.length===0?l`<p class="muted">尚未加载文件。</p>`:e.fileTree.map(r=>this.renderTreeEntry(e,r,0))}
187
190
  </div>
188
191
  <div class="viewer">
189
192
  ${this.renderFileViewer(e)}
@@ -197,28 +200,28 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
197
200
  </div>
198
201
  ${this.pendingUpload===void 0?null:this.renderUploadDialog(e,this.pendingUpload)}
199
202
  </section>
200
- `}renderTreeEntry(e,t,i){const s=e.expandedDirs[t.path],r=s!==void 0,o=t.type!=="directory"&&e.selectedFilePath===t.path;return l`
203
+ `}renderTreeEntry(e,t,i){const s=e.expandedDirs[t.path],r=s!==void 0,o=e.selectedFilePath===t.path;return l`
201
204
  <button class=${o?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{this.selectTreeEntry(e,t)}}>
202
205
  <span>${t.type==="directory"?r?"▾":"▸":"·"}</span>
203
206
  <span>${t.name}</span>
204
207
  </button>
205
208
  ${r?s.map(n=>this.renderTreeEntry(e,n,i+1)):null}
206
- `}selectTreeEntry(e,t){t.type==="directory"?e.onExpandDir(t.path):e.onSelectFile(t.path)}renderFileViewer(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">请选择文件。</p>`:t===void 0?l`<p class="muted">正在加载 ${e.selectedFilePath}…</p>`:t.mediaType==="image"?this.renderImageViewer(e,t):t.binary?l`<p class="muted">二进制文件:${t.path} · ${xt(t.size)}</p>`:(ug(),l`
209
+ `}selectTreeEntry(e,t){if(t.type==="directory"){e.onSelectDirectory(t.path),e.onExpandDir(t.path);return}e.onSelectFile(t.path)}renderFileViewer(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">请选择文件。</p>`:sn(e.fileTree,e.expandedDirs,e.selectedFilePath)==="directory"?l`<p class="muted">已选择文件夹:${e.selectedFilePath}</p>`:t===void 0?l`<p class="muted">正在加载 ${e.selectedFilePath}…</p>`:t.mediaType==="image"?this.renderImageViewer(e,t):t.binary?l`<p class="muted">二进制文件:${t.path} · ${xt(t.size)}</p>`:(wg(),l`
207
210
  <div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"文本"}${t.truncated?" · 已截断":""}</small></div>
208
211
  <code-viewer .content=${t.content} .language=${t.language}></code-viewer>
209
- `)}renderImageViewer(e,t){const i=`${t.mimeType??"image"} · ${xt(t.size)}`;if(t.size>Zf)return l`
212
+ `)}renderImageViewer(e,t){const i=`${t.mimeType??"image"} · ${xt(t.size)}`;if(t.size>tg)return l`
210
213
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
211
- <p class="muted">图片过大,无法预览:${xt(t.size)} · 限制 ${Xf}</p>
212
- `;const s=rp(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
214
+ <p class="muted">图片过大,无法预览:${xt(t.size)} · 限制 ${ig}</p>
215
+ `;const s=lp(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
213
216
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
214
217
  <div class="image-preview">
215
218
  <img src=${s} alt=${t.path} decoding="async" />
216
219
  </div>
217
- `}renderUploadProgress(e){const t=sg(e.state.workspaceUploadBatches,{projectId:e.workspace.projectId,workspaceId:e.workspace.id,machineId:e.machine.id});return t.length===0?null:l`
220
+ `}renderUploadProgress(e){const t=ag(e.state.workspaceUploadBatches,{projectId:e.workspace.projectId,workspaceId:e.workspace.id,machineId:e.machine.id});return t.length===0?null:l`
218
221
  <section class="upload-progress" aria-label="工作区上传">
219
222
  <div class="upload-progress-header">
220
223
  <strong>上传</strong>
221
- <small>${ag(t)}</small>
224
+ <small>${ug(t)}</small>
222
225
  </div>
223
226
  ${t.map(i=>this.renderUploadBatch(e,i))}
224
227
  </section>
@@ -226,12 +229,12 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
226
229
  <article class=${`upload-batch ${t.status}`}>
227
230
  <div class="upload-batch-heading">
228
231
  <div>
229
- <strong>${lg(t)}</strong>
232
+ <strong>${fg(t)}</strong>
230
233
  <small>${t.destinationFolder===""?"工作区根目录":t.destinationFolder}</small>
231
234
  </div>
232
- <span>${cg(t)}</span>
235
+ <span>${gg(t)}</span>
233
236
  </div>
234
- <progress max="1" .value=${dg(t)}></progress>
237
+ <progress max="1" .value=${mg(t)}></progress>
235
238
  <div class="upload-file-list">
236
239
  ${t.files.map(i=>this.renderUploadFile(i))}
237
240
  </div>
@@ -239,13 +242,13 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
239
242
  ${t.status==="uploading"?l`<button @click=${()=>{e.onCancelWorkspaceUpload(t.id)}}>取消</button>`:l`<button @click=${()=>{e.onClearWorkspaceUpload(t.id)}}>关闭</button>`}
240
243
  </div>
241
244
  </article>
242
- `}renderUploadFile(e){const t=hg(e);return l`
245
+ `}renderUploadFile(e){const t=bg(e);return l`
243
246
  <div class=${`upload-file ${e.status}`}>
244
247
  <div class="upload-file-main">
245
248
  <span>${e.name}</span>
246
249
  <small>${t}</small>
247
250
  </div>
248
- <span class="upload-file-status">${pg(e)}</span>
251
+ <span class="upload-file-status">${vg(e)}</span>
249
252
  </div>
250
253
  `}renderUploadDialog(e,t){const i=t.files.length;return l`
251
254
  <div class="dialog-backdrop" @mousedown=${()=>{this.closeUploadDialog()}}>
@@ -290,11 +293,13 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
290
293
  </form>
291
294
  </section>
292
295
  </div>
293
- `}openUploadReview(e){const t=this.context,i=og(t?.workspaceUploadDefaultFolder??"");this.pendingUpload={files:e},this.destinationFolder=i.destinationFolder,this.overwrite=i.overwrite,this.createDirs=i.createDirs,this.formError=""}submitUploadReview(e,t,i){e.preventDefault();const s=rg(i.files,this.destinationFolder);if(s!==void 0){this.formError=s;return}t.onStartWorkspaceUpload(i.files,{destinationFolder:this.destinationFolder,createDirs:this.createDirs,overwrite:this.overwrite,selectUploadedFile:!0})!==void 0&&this.closeUploadDialog()}closeUploadDialog(){this.pendingUpload=void 0,this.formError=""}resetPendingUpload(){this.closeUploadDialog(),this.dragDepth=0,this.dragActive=!1}};Te.styles=[Yf,E`
296
+ `}promptCreateFile(e,t){const i=nn("新建文件路径",rn(e.selectedFilePath,t,"new-file.txt"));i!==void 0&&e.onCreateFile(i)}promptCreateDirectory(e,t){const i=nn("新建文件夹路径",rn(e.selectedFilePath,t,"new-folder"));i!==void 0&&e.onCreateDirectory(i)}confirmDeleteSelectedPath(e){const t=e.selectedFilePath;t===void 0||t===""||window.confirm(`删除 ${t}?此操作无法撤销。`)&&e.onDeleteSelectedPath()}openUploadReview(e){const t=this.context,i=cg(t?.workspaceUploadDefaultFolder??"");this.pendingUpload={files:e},this.destinationFolder=i.destinationFolder,this.overwrite=i.overwrite,this.createDirs=i.createDirs,this.formError=""}submitUploadReview(e,t,i){e.preventDefault();const s=lg(i.files,this.destinationFolder);if(s!==void 0){this.formError=s;return}t.onStartWorkspaceUpload(i.files,{destinationFolder:this.destinationFolder,createDirs:this.createDirs,overwrite:this.overwrite,selectUploadedFile:!0})!==void 0&&this.closeUploadDialog()}closeUploadDialog(){this.pendingUpload=void 0,this.formError=""}resetPendingUpload(){this.closeUploadDialog(),this.dragDepth=0,this.dragActive=!1}};Te.styles=[sg,E`
294
297
  :host { flex: 1 1 auto; }
295
298
  .files-panel { position: relative; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
296
299
  .toolbar-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
297
300
  .toolbar .toolbar-actions button { margin-left: 0; }
301
+ .toolbar .toolbar-actions button.danger { color: var(--pi-danger); }
302
+ .toolbar .toolbar-actions button.danger:not(:disabled):hover { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
298
303
  .visually-hidden { 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; }
299
304
  .drop-overlay { position: absolute; inset: 52px 10px 10px; z-index: 15; display: grid; place-items: center; border: 2px dashed var(--pi-accent); border-radius: 12px; background: color-mix(in srgb, var(--pi-bg-overlay) 90%, var(--pi-accent) 10%); color: var(--pi-text); opacity: 0; pointer-events: none; transition: opacity .12s ease; }
300
305
  .files-panel.dragging .drop-overlay { opacity: 1; }
@@ -336,7 +341,7 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
336
341
  .review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
337
342
  .dialog-error { border: 1px solid var(--pi-danger); border-radius: 8px; background: color-mix(in srgb, var(--pi-danger) 10%, transparent); color: var(--pi-danger); padding: 9px; line-height: 1.35; overflow-wrap: anywhere; }
338
343
  footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
339
- `];He([d({attribute:!1})],Te.prototype,"context",2);He([B("#workspace-upload-input")],Te.prototype,"uploadInput",2);He([y()],Te.prototype,"pendingUpload",2);He([y()],Te.prototype,"destinationFolder",2);He([y()],Te.prototype,"overwrite",2);He([y()],Te.prototype,"createDirs",2);He([y()],Te.prototype,"formError",2);He([y()],Te.prototype,"dragActive",2);Te=He([W("workspace-files-panel")],Te);function sg(e,t){return Object.values(e).filter(i=>i.projectId===t.projectId&&i.workspaceId===t.workspaceId&&i.machineId===t.machineId).sort((i,s)=>s.startedAt.localeCompare(i.startedAt))}function rg(e,t){if(e.length===0)return"请至少选择一个要上传的文件。";for(const i of e)try{br(t,i.name)}catch(s){return s instanceof Error?s.message:String(s)}}function og(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function ng(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function sn(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function rn(e){return e==null?[]:Array.from(e)}function oi(e){return Array.from(e.dataTransfer?.types??[]).includes("Files")}function ag(e){const t=e.filter(i=>i.status==="uploading").length;return t===0?`${String(e.length)} 个最近`:`${String(t)} 个上传中`}function lg(e){const t=String(e.files.length);switch(e.status){case"completed":return`已上传 ${t} 个文件`;case"error":return`${t} 个文件上传失败`;case"cancelled":return`已取消 ${t} 个文件的上传`;case"uploading":return`正在上传 ${t} 个文件`}}function cg(e){switch(e.status){case"completed":return"完成";case"error":return"失败";case"cancelled":return"已取消";case"uploading":return Za(e.percent)}}function dg(e){return e.status==="uploading"?e.percent:1}function pg(e){switch(e.status){case"pending":return"待处理";case"uploading":return Za(e.percent);case"completed":return"完成";case"error":return"错误";case"cancelled":return"已取消"}}function hg(e){return e.error!==void 0?e.error:e.response!==void 0?`已写入 ${e.response.path}`:`${e.path} · ${xt(e.loaded)} / ${xt(e.total)}`}function Za(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function ug(){Mr(()=>import("./CodeViewer-CEaJIjgA.js"),__vite__mapDeps([0,1,2,3]))}function xt(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${xs(t)} KB`;const i=t/1024;return i<1024?`${xs(i)} MB`:`${xs(i/1024)} GB`}function xs(e){return e>=10?String(Math.round(e)):e.toFixed(1)}function on(){return[{id:"workspace.files",title:"文件",icon:yi("files"),order:10,render:fg},{id:"workspace.git",title:"Git",icon:yi("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:mg},{id:"workspace.terminal",title:"终端",icon:yi("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:gg}]}function fg(e){return l`<workspace-files-panel .context=${e}></workspace-files-panel>`}function gg(e){return yg(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function mg(e){const t=e.gitStatus;return l`
344
+ `];He([d({attribute:!1})],Te.prototype,"context",2);He([B("#workspace-upload-input")],Te.prototype,"uploadInput",2);He([y()],Te.prototype,"pendingUpload",2);He([y()],Te.prototype,"destinationFolder",2);He([y()],Te.prototype,"overwrite",2);He([y()],Te.prototype,"createDirs",2);He([y()],Te.prototype,"formError",2);He([y()],Te.prototype,"dragActive",2);Te=He([W("workspace-files-panel")],Te);function ag(e,t){return Object.values(e).filter(i=>i.projectId===t.projectId&&i.workspaceId===t.workspaceId&&i.machineId===t.machineId).sort((i,s)=>s.startedAt.localeCompare(i.startedAt))}function lg(e,t){if(e.length===0)return"请至少选择一个要上传的文件。";for(const i of e)try{br(t,i.name)}catch(s){return s instanceof Error?s.message:String(s)}}function cg(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function sn(e,t,i){if(i!==void 0)return pg(e,t,i)?.type}function rn(e,t,i){if(e===void 0||e==="")return i;if(t==="directory")return an(e,i);const s=hg(e);return s===""?i:an(s,i)}function dg(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function on(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function nn(e,t){const i=window.prompt(e,t);if(i===null)return;const s=i.trim();return s===""?void 0:s}function pg(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 hg(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function an(e,t){return e===""?t:`${e.replace(/\/+$/u,"")}/${t.replace(/^\/+/u,"")}`}function ln(e){return e==null?[]:Array.from(e)}function oi(e){return Array.from(e.dataTransfer?.types??[]).includes("Files")}function ug(e){const t=e.filter(i=>i.status==="uploading").length;return t===0?`${String(e.length)} 个最近`:`${String(t)} 个上传中`}function fg(e){const t=String(e.files.length);switch(e.status){case"completed":return`已上传 ${t} 个文件`;case"error":return`${t} 个文件上传失败`;case"cancelled":return`已取消 ${t} 个文件的上传`;case"uploading":return`正在上传 ${t} 个文件`}}function gg(e){switch(e.status){case"completed":return"完成";case"error":return"失败";case"cancelled":return"已取消";case"uploading":return tl(e.percent)}}function mg(e){return e.status==="uploading"?e.percent:1}function vg(e){switch(e.status){case"pending":return"待处理";case"uploading":return tl(e.percent);case"completed":return"完成";case"error":return"错误";case"cancelled":return"已取消"}}function bg(e){return e.error!==void 0?e.error:e.response!==void 0?`已写入 ${e.response.path}`:`${e.path} · ${xt(e.loaded)} / ${xt(e.total)}`}function tl(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function wg(){Mr(()=>import("./CodeViewer-hxitRRG6.js"),__vite__mapDeps([0,1,2,3]))}function xt(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${xs(t)} KB`;const i=t/1024;return i<1024?`${xs(i)} MB`:`${xs(i/1024)} GB`}function xs(e){return e>=10?String(Math.round(e)):e.toFixed(1)}function cn(){return[{id:"workspace.files",title:"文件",icon:yi("files"),order:10,render:yg},{id:"workspace.git",title:"Git",icon:yi("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:Sg},{id:"workspace.terminal",title:"终端",icon:yi("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:xg}]}function yg(e){return l`<workspace-files-panel .context=${e}></workspace-files-panel>`}function xg(e){return Cg(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Sg(e){const t=e.gitStatus;return l`
340
345
  <section class="toolbar">
341
346
  <strong>Git</strong>
342
347
  ${e.gitStale?l`<span class="stale">过期</span>`:null}
@@ -345,29 +350,29 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
345
350
  <section class="split">
346
351
  <div class="list">
347
352
  ${t===void 0?l`<p class="muted">尚未加载状态。</p>`:t.isGitRepo?l`
348
- <p class="summary">${xg(t)}</p>
353
+ <p class="summary">${Ig(t)}</p>
349
354
  ${t.files.length===0?l`<p class="muted">没有变更。</p>`:t.files.map(i=>l`
350
355
  <button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
351
- <span>${Sg(i.index,i.workingTree)}</span>
356
+ <span>${Rg(i.index,i.workingTree)}</span>
352
357
  <span>${i.path}</span>
353
358
  </button>
354
359
  `)}
355
360
  `:l`<p class="muted">不是 Git 仓库。</p>`}
356
361
  </div>
357
362
  <div class="viewer">
358
- ${vg(e)}
363
+ ${kg(e)}
359
364
  </div>
360
365
  </section>
361
- `}function vg(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return l`<p class="muted">请选择一个已变更文件。</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return l`<p class="muted">正在加载 diff…</p>`;const s=[i,t].filter(r=>r.diff!=="");return s.length===0?l`<p class="muted">没有 staged 或 unstaged diff。</p>`:l`
366
+ `}function kg(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return l`<p class="muted">请选择一个已变更文件。</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return l`<p class="muted">正在加载 diff…</p>`;const s=[i,t].filter(r=>r.diff!=="");return s.length===0?l`<p class="muted">没有 staged 或 unstaged diff。</p>`:l`
362
367
  <div class=${s.length===1?"diffs single":"diffs"}>
363
- ${s.map(r=>bg(r))}
368
+ ${s.map(r=>$g(r))}
364
369
  </div>
365
- `}function bg(e){return wg(),l`
370
+ `}function $g(e){return Pg(),l`
366
371
  <section class="diff-section">
367
372
  <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"已暂存":"未暂存"}${e.truncated?" · 已截断":""}</small></div>
368
373
  <unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
369
374
  </section>
370
- `}function wg(){Mr(()=>import("./UnifiedDiffViewer-Dkgg-4fh.js"),__vite__mapDeps([4,1,2]))}function yg(){Mr(()=>import("./TerminalPanel-BdMJbtLB.js"),__vite__mapDeps([5,6,7,1,2]))}function xg(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 Sg(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}const kg={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!Wf();return{contributions:{actions:e?Yo():Yo().filter(t=>t.id!=="view.terminal"),workspacePanels:e?on():on().filter(t=>t.id!=="workspace.terminal")}}}},$g={"--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"},Pg={"--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"},Cg={"--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"},Rg={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:Pg},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Cg},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:$g}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},Ig=/^[a-z][a-z0-9.-]*$/u;function Ag(e){return Ig.test(e)}const Tg="machine.";function Mg(e,t){if(e==="")throw new Error("Machine id is required");if(!Ag(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Tg}${Eg(e)}.${t}`}function Eg(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function nn(e="/pi-web-plugins/manifest.json",t={}){const i=await Dg(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=_g(n,o);s.push({id:t.machineId===void 0?r.id:Mg(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 Dg(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 Wg(await t.json())}}function Wg(e){if(!Li(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!Li(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module,machineSpecific:Og(t.machineSpecific)}})}}function Og(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function _g(e,t){if(!Li(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!Lg(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function Lg(e){return Li(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function Li(e){return typeof e=="object"&&e!==null}const jg=/^[a-z][a-z0-9.-]*$/u,Fg=/^[a-z][a-z0-9.-]*$/u,Xa=new WeakMap,Ya=new WeakMap;class Ug{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;this.validatePluginId(i);const r=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,r))return;this.pluginIds.add(i);const o=s.apiVersion;if(o!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(o)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:be}).contributions;for(const c of a.actions??[])this.actions.push(this.qualifyAction(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,c,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const c of a.themes??[])this.themes.push(this.qualifyTheme(i,c));for(const c of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,c));this.gatewayPluginIds.add(i),r&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&r&&Hg(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=Kg(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const r=zg(t,s.pluginId),o=s.enabled?.(r),n=o===!1?s.disabledReason?.(r):void 0,a={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(r)};return s.description!==void 0&&(a.description=s.description),s.shortcut!==void 0&&(a.shortcut=s.shortcut),s.group!==void 0&&(a.group=s.group),o!==void 0&&(a.enabled=o),n!==void 0&&n!==""&&(a.disabledReason=n),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,r){const o=this.qualify(t,i.id);return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(t,i,s,r){const o=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,r)&&(a?.(Ss(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,r)?n(Ss(c,t)):void 0},render:c=>i.render(Ss(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,r){const o=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,r)&&(n?.(c)??!0),items:c=>this.isContributionActive(t,s,c.machine.id,r)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}isContributionActive(t,i,s,r){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(r,i)}isRemoteDuplicateHiddenByGateway(t,i,s){return t!==void 0&&i!==void 0&&this.gatewayPluginIds.has(t)&&!this.gatewayMachineSpecificPluginIds.has(t)&&!s}isRemotePluginHiddenByGateway(t,i){return t===void 0||this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0?!1:this.gatewayPluginIds.has(t)}isGatewayPluginHiddenForMachine(t,i){return i!=="local"&&(this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0)}validatePluginId(t){if(!jg.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!Fg.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}: ${qg(i)}`);return i}}function zg(e,t){return Xa.get(e)?.(t)??e}function Ss(e,t){return Ya.get(e)?.(t)??e}function Bg(e,t){return Xa.set(e,t),e}function Ng(e,t){return Ya.set(e,t),e}function Hg(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function qg(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 Kg(e){return e.state.selectedMachine?.id??"local"}const Vg=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function Gg(){return typeof window>"u"||!("matchMedia"in window)?[]:Vg.map(e=>window.matchMedia(e))}function an(e,t=Jg()){return e.some(i=>i.matches)||Qg(t)}function Jg(){return typeof navigator>"u"?void 0:navigator}function Qg(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const Zg=250;class Xg{constructor(t=Yg()){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()},Zg)}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 Yg(){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 em="(max-width: 760px)",tm="(max-width: 1180px)";class im{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=an(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??sm(),this.stackedWorkspaceMedia=i.stackedWorkspaceMedia??rm(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??Gg(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Xg,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=an(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 om(t,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:i})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function sm(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(em)}function rm(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(tm)}function om(e,t){const i=e??(t.isMobileNavigationLayout?"navigation":"chat");return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||i==="navigation"||i==="chat"?i:"chat"}const ji=["machines","projects","workspaces","sessions"];function nm(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function Er(e,t){if(e!=="none")return e??nm(t)}function am(e,t){return t.isMobileLayout?Er(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function lm(e,t,i){return Er(e,i.state)===t?"none":t}function cm(e,t,i){return i?t:e}function dm(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),um(i)}function pm(e){return ji[ji.indexOf(e)+1]}class hm{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return Er(this.expanded,this.getState())}isCollapsed(t){return am(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(lm(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(dm(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(cm(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=pm(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){fm(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function um(e){const t=new Set(e);return ji.filter(i=>t.has(i))}function fm(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class gm{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",el(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function el(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const Xs="pi-web:panel-sizes:v1",mm={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class vm{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??Dr(),this.panelSizes=xm(this.storage)}hostConnected(){}constraints(t){return Xt(t)}panelWidth(t,i){return we(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const r=we(t,i);this.storedPanelWidth(t)!==r&&(this.panelSizes=$m(this.panelSizes,t,r),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Pm(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(){Sm(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${cn(we("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${cn(we("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Xt(e){return mm[e]}function bm(e,t,i){return e==="navigation"?i-t:t-i}function wm(e,t,i,s,r=Xt(e)){return we(e,t+bm(e,i,s),r)}function ym(e,t,i,s={}){const r=s.constraints??Xt(e);if(i==="Home")return r.minWidth;if(i==="End")return r.maxWidth;const o=s.largeStep===!0?r.largeKeyboardStep:r.keyboardStep,n=Cm(e,i,o);if(n!==void 0)return we(e,t+n,r)}function we(e,t,i=Xt(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function xm(e=Dr()){try{const t=e?.getItem(Xs);if(t==null||t==="")return{};const i=JSON.parse(t);return km(i)}catch{return{}}}function Sm(e,t=Dr()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Xs);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=we("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=we("workspace",e.workspacePanelWidth)),t.setItem(Xs,JSON.stringify(i))}catch{}}function km(e){if(!Rm(e)||e.version!==1)return{};const t={},i=ln(e.navigationPanelWidth),s=ln(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=we("navigation",i)),s!==void 0&&(t.workspacePanelWidth=we("workspace",s)),t}function ln(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function $m(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Pm(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Cm(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 cn(e){return`${String(Math.round(e))}px`}function Dr(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Rm(e){return typeof e=="object"&&e!==null}function dn(){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:Im(e.get("tool")),view:Am(e.get("view"))}}function ks(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 Im(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":tl(e)?e:void 0}function Am(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":tl(e)?e:void 0}function tl(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function pn(){return Tm(new URLSearchParams(window.location.search).get("settings"))}function $s(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 Tm(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 Mm(e,t){return t===void 0?e:e.map(i=>Dm(i,t))}function Em(e,t){const i=new Set(Ir(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return Mm(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?il(s):s)}function Dm(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?il(e):{...e,shortcut:i}}function il(e){const t={...e};return delete t.shortcut,t}function Wm(e,t){const i=t.api??yt,s=t.pollIntervalMs??1e3,r=t.setTimeout??_m(),o=t.clearTimeout??Lm();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:Om(a,i,s,r,o)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function Om(e,t,i,s,r){return hn(e)?Promise.resolve(e):new Promise((o,n)=>{let a,c=!1;const p=g=>{c||(c=!0,a!==void 0&&r(a),o(g))},u=g=>{c||(c=!0,a!==void 0&&r(a),n(g instanceof Error?g:new Error(String(g))))},h=()=>{t.getCommandRun(e.id).then(g=>{if(g!==void 0&&hn(g)){p(g);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function hn(e){return e.status==="succeeded"||e.status==="failed"}function _m(){return(e,t)=>globalThis.setTimeout(e,t)}function Lm(){return e=>{globalThis.clearTimeout(e)}}function jm(e,t){return t[e.path]}function Fm(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function Um(e,t,i){return rl(zm(e,t,i))}function sl(e){return rl(Object.values(e??{}))}function rl(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function zm(e,t,i){const s=new Set(t.filter(o=>o.projectId===e.id).map(o=>o.path)),r=new Map;for(const o of s){const n=i[o];n!==void 0&&r.set(n.cwd,n)}for(const o of Object.values(i))(o.cwd===e.path||o.cwd.startsWith(`${e.path}/`))&&r.set(o.cwd,o);return[...r.values()]}function ol(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Xi(e,t="活跃"){const i=ol(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const ni=0,Bm=120;function nl(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?al():Nm(e),r=window.innerWidth,o=window.innerHeight,n=Math.max(0,s.left),a=Math.min(r,s.right),c=Math.max(0,s.top),p=Math.min(o,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-ni,g=i.top-c-ni;return[...h<Bm&&g>h?[`bottom: ${mt(o-i.top+ni)};`,`max-height: ${mt(Math.max(0,g))};`]:[`top: ${mt(i.bottom+ni)};`,`max-height: ${mt(Math.max(0,h))};`],`right: ${mt(Math.max(0,r-u))};`,`max-width: ${mt(Math.max(0,u-n))};`].join(" ")}function Nm(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():al()}function al(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function mt(e){return`${String(Math.round(e))}px`}class Yi{constructor(t){this.host=t,this.menuStyle="",this.onDocumentClick=i=>{i.composedPath().includes(this.host)||this.close()},t.addController(this)}hostConnected(){document.addEventListener("click",this.onDocumentClick)}hostDisconnected(){document.removeEventListener("click",this.onDocumentClick)}isOpen(t){return this.openId===t}toggle(t,i){if(this.openId===t){this.close();return}this.menuStyle=nl(i,{constrainTo:"viewport"}),this.openId=t,this.host.requestUpdate()}close(){this.openId===void 0&&this.menuStyle===""||(this.openId=void 0,this.menuStyle="",this.host.requestUpdate())}closeIfOpenIdMissing(t){this.openId!==void 0&&!t(this.openId)&&this.close()}closeIf(t){t&&this.close()}closeForEscape(t,i){return t.key!=="Escape"||this.openId!==i?!1:(t.preventDefault(),t.stopPropagation(),this.close(),!0)}}const Hm=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function ll(e){return e.composedPath().some(t=>qm(t,Hm))}function qm(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 es(e,t){ll(e)||t()}function ts(e,t){return ll(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?st(e,()=>{un(e.currentTarget,-1)}):e.key==="ArrowDown"?st(e,()=>{un(e.currentTarget,1)}):e.key==="Home"?st(e,()=>{fn(e.currentTarget,0)}):e.key==="End"?st(e,()=>{fn(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?st(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?st(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?st(e,t.cancel):!1}function is(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 st(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function un(e,t){const i=dl(e),s=pl(e);if(s===void 0||i.length===0)return;const r=i.indexOf(s);r<0||cl(i,r+t)}function fn(e,t){const i=dl(e);i.length!==0&&cl(i,t<0?i.length-1:t)}function cl(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function dl(e){const t=pl(e)?.getRootNode();return t===void 0||!Km(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function Km(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function pl(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const ss=E`
375
+ `}function Pg(){Mr(()=>import("./UnifiedDiffViewer-DTCywBXP.js"),__vite__mapDeps([4,1,2]))}function Cg(){Mr(()=>import("./TerminalPanel-DTn18hoY.js"),__vite__mapDeps([5,6,7,1,2]))}function Ig(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 Rg(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}const Ag={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!jf();return{contributions:{actions:e?Yo():Yo().filter(t=>t.id!=="view.terminal"),workspacePanels:e?cn():cn().filter(t=>t.id!=="workspace.terminal")}}}},Tg={"--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"},Mg={"--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"},Eg={"--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"},Dg={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:Mg},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Eg},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Tg}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},Wg=/^[a-z][a-z0-9.-]*$/u;function Og(e){return Wg.test(e)}const _g="machine.";function Lg(e,t){if(e==="")throw new Error("Machine id is required");if(!Og(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${_g}${jg(e)}.${t}`}function jg(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function dn(e="/pi-web-plugins/manifest.json",t={}){const i=await Fg(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=Bg(n,o);s.push({id:t.machineId===void 0?r.id:Lg(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 Fg(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 Ug(await t.json())}}function Ug(e){if(!Li(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!Li(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module,machineSpecific:zg(t.machineSpecific)}})}}function zg(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function Bg(e,t){if(!Li(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!Ng(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function Ng(e){return Li(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function Li(e){return typeof e=="object"&&e!==null}const Hg=/^[a-z][a-z0-9.-]*$/u,qg=/^[a-z][a-z0-9.-]*$/u,il=new WeakMap,sl=new WeakMap;class Kg{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;this.validatePluginId(i);const r=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,r))return;this.pluginIds.add(i);const o=s.apiVersion;if(o!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(o)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:be}).contributions;for(const c of a.actions??[])this.actions.push(this.qualifyAction(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,c,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const c of a.themes??[])this.themes.push(this.qualifyTheme(i,c));for(const c of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,c));this.gatewayPluginIds.add(i),r&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&r&&Qg(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=Xg(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const r=Vg(t,s.pluginId),o=s.enabled?.(r),n=o===!1?s.disabledReason?.(r):void 0,a={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(r)};return s.description!==void 0&&(a.description=s.description),s.shortcut!==void 0&&(a.shortcut=s.shortcut),s.group!==void 0&&(a.group=s.group),o!==void 0&&(a.enabled=o),n!==void 0&&n!==""&&(a.disabledReason=n),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,r){const o=this.qualify(t,i.id);return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(t,i,s,r){const o=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,r)&&(a?.(Ss(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,r)?n(Ss(c,t)):void 0},render:c=>i.render(Ss(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,r){const o=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,r)&&(n?.(c)??!0),items:c=>this.isContributionActive(t,s,c.machine.id,r)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}isContributionActive(t,i,s,r){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(r,i)}isRemoteDuplicateHiddenByGateway(t,i,s){return t!==void 0&&i!==void 0&&this.gatewayPluginIds.has(t)&&!this.gatewayMachineSpecificPluginIds.has(t)&&!s}isRemotePluginHiddenByGateway(t,i){return t===void 0||this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0?!1:this.gatewayPluginIds.has(t)}isGatewayPluginHiddenForMachine(t,i){return i!=="local"&&(this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0)}validatePluginId(t){if(!Hg.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!qg.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}: ${Zg(i)}`);return i}}function Vg(e,t){return il.get(e)?.(t)??e}function Ss(e,t){return sl.get(e)?.(t)??e}function Gg(e,t){return il.set(e,t),e}function Jg(e,t){return sl.set(e,t),e}function Qg(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function Zg(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 Xg(e){return e.state.selectedMachine?.id??"local"}const Yg=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function em(){return typeof window>"u"||!("matchMedia"in window)?[]:Yg.map(e=>window.matchMedia(e))}function pn(e,t=tm()){return e.some(i=>i.matches)||im(t)}function tm(){return typeof navigator>"u"?void 0:navigator}function im(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const sm=250;class rm{constructor(t=om()){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()},sm)}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 om(){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 nm="(max-width: 760px)",am="(max-width: 1180px)";class lm{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=pn(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??cm(),this.stackedWorkspaceMedia=i.stackedWorkspaceMedia??dm(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??em(),this.viewportPositionRepairer=i.viewportPositionRepairer??new rm,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=pn(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 pm(t,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:i})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function cm(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(nm)}function dm(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(am)}function pm(e,t){const i=e??(t.isMobileNavigationLayout?"navigation":"chat");return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||i==="navigation"||i==="chat"?i:"chat"}const ji=["machines","projects","workspaces","sessions"];function hm(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function Er(e,t){if(e!=="none")return e??hm(t)}function um(e,t){return t.isMobileLayout?Er(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function fm(e,t,i){return Er(e,i.state)===t?"none":t}function gm(e,t,i){return i?t:e}function mm(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),wm(i)}function vm(e){return ji[ji.indexOf(e)+1]}class bm{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return Er(this.expanded,this.getState())}isCollapsed(t){return um(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(fm(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(mm(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(gm(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=vm(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){ym(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function wm(e){const t=new Set(e);return ji.filter(i=>t.has(i))}function ym(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class xm{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",rl(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function rl(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const Xs="pi-web:panel-sizes:v1",Sm={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class km{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??Dr(),this.panelSizes=Im(this.storage)}hostConnected(){}constraints(t){return Xt(t)}panelWidth(t,i){return we(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const r=we(t,i);this.storedPanelWidth(t)!==r&&(this.panelSizes=Tm(this.panelSizes,t,r),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Mm(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(){Rm(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${un(we("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${un(we("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Xt(e){return Sm[e]}function $m(e,t,i){return e==="navigation"?i-t:t-i}function Pm(e,t,i,s,r=Xt(e)){return we(e,t+$m(e,i,s),r)}function Cm(e,t,i,s={}){const r=s.constraints??Xt(e);if(i==="Home")return r.minWidth;if(i==="End")return r.maxWidth;const o=s.largeStep===!0?r.largeKeyboardStep:r.keyboardStep,n=Em(e,i,o);if(n!==void 0)return we(e,t+n,r)}function we(e,t,i=Xt(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Im(e=Dr()){try{const t=e?.getItem(Xs);if(t==null||t==="")return{};const i=JSON.parse(t);return Am(i)}catch{return{}}}function Rm(e,t=Dr()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Xs);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=we("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=we("workspace",e.workspacePanelWidth)),t.setItem(Xs,JSON.stringify(i))}catch{}}function Am(e){if(!Dm(e)||e.version!==1)return{};const t={},i=hn(e.navigationPanelWidth),s=hn(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=we("navigation",i)),s!==void 0&&(t.workspacePanelWidth=we("workspace",s)),t}function hn(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Tm(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Mm(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Em(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 un(e){return`${String(Math.round(e))}px`}function Dr(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Dm(e){return typeof e=="object"&&e!==null}function fn(){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:Wm(e.get("tool")),view:Om(e.get("view"))}}function ks(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 Wm(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":ol(e)?e:void 0}function Om(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":ol(e)?e:void 0}function ol(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function gn(){return _m(new URLSearchParams(window.location.search).get("settings"))}function $s(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 _m(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 Lm(e,t){return t===void 0?e:e.map(i=>Fm(i,t))}function jm(e,t){const i=new Set(Rr(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return Lm(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?nl(s):s)}function Fm(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?nl(e):{...e,shortcut:i}}function nl(e){const t={...e};return delete t.shortcut,t}function Um(e,t){const i=t.api??yt,s=t.pollIntervalMs??1e3,r=t.setTimeout??Bm(),o=t.clearTimeout??Nm();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:zm(a,i,s,r,o)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function zm(e,t,i,s,r){return mn(e)?Promise.resolve(e):new Promise((o,n)=>{let a,c=!1;const p=g=>{c||(c=!0,a!==void 0&&r(a),o(g))},u=g=>{c||(c=!0,a!==void 0&&r(a),n(g instanceof Error?g:new Error(String(g))))},h=()=>{t.getCommandRun(e.id).then(g=>{if(g!==void 0&&mn(g)){p(g);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function mn(e){return e.status==="succeeded"||e.status==="failed"}function Bm(){return(e,t)=>globalThis.setTimeout(e,t)}function Nm(){return e=>{globalThis.clearTimeout(e)}}function Hm(e,t){return t[e.path]}function qm(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function Km(e,t,i){return ll(Vm(e,t,i))}function al(e){return ll(Object.values(e??{}))}function ll(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function Vm(e,t,i){const s=new Set(t.filter(o=>o.projectId===e.id).map(o=>o.path)),r=new Map;for(const o of s){const n=i[o];n!==void 0&&r.set(n.cwd,n)}for(const o of Object.values(i))(o.cwd===e.path||o.cwd.startsWith(`${e.path}/`))&&r.set(o.cwd,o);return[...r.values()]}function cl(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Xi(e,t="活跃"){const i=cl(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const ni=0,Gm=120;function dl(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?pl():Jm(e),r=window.innerWidth,o=window.innerHeight,n=Math.max(0,s.left),a=Math.min(r,s.right),c=Math.max(0,s.top),p=Math.min(o,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-ni,g=i.top-c-ni;return[...h<Gm&&g>h?[`bottom: ${mt(o-i.top+ni)};`,`max-height: ${mt(Math.max(0,g))};`]:[`top: ${mt(i.bottom+ni)};`,`max-height: ${mt(Math.max(0,h))};`],`right: ${mt(Math.max(0,r-u))};`,`max-width: ${mt(Math.max(0,u-n))};`].join(" ")}function Jm(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():pl()}function pl(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function mt(e){return`${String(Math.round(e))}px`}class Yi{constructor(t){this.host=t,this.menuStyle="",this.onDocumentClick=i=>{i.composedPath().includes(this.host)||this.close()},t.addController(this)}hostConnected(){document.addEventListener("click",this.onDocumentClick)}hostDisconnected(){document.removeEventListener("click",this.onDocumentClick)}isOpen(t){return this.openId===t}toggle(t,i){if(this.openId===t){this.close();return}this.menuStyle=dl(i,{constrainTo:"viewport"}),this.openId=t,this.host.requestUpdate()}close(){this.openId===void 0&&this.menuStyle===""||(this.openId=void 0,this.menuStyle="",this.host.requestUpdate())}closeIfOpenIdMissing(t){this.openId!==void 0&&!t(this.openId)&&this.close()}closeIf(t){t&&this.close()}closeForEscape(t,i){return t.key!=="Escape"||this.openId!==i?!1:(t.preventDefault(),t.stopPropagation(),this.close(),!0)}}const Qm=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function hl(e){return e.composedPath().some(t=>Zm(t,Qm))}function Zm(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 es(e,t){hl(e)||t()}function ts(e,t){return hl(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?st(e,()=>{vn(e.currentTarget,-1)}):e.key==="ArrowDown"?st(e,()=>{vn(e.currentTarget,1)}):e.key==="Home"?st(e,()=>{bn(e.currentTarget,0)}):e.key==="End"?st(e,()=>{bn(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?st(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?st(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?st(e,t.cancel):!1}function is(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 st(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function vn(e,t){const i=fl(e),s=gl(e);if(s===void 0||i.length===0)return;const r=i.indexOf(s);r<0||ul(i,r+t)}function bn(e,t){const i=fl(e);i.length!==0&&ul(i,t<0?i.length-1:t)}function ul(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function fl(e){const t=gl(e)?.getRootNode();return t===void 0||!Xm(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function Xm(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function gl(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const ss=E`
371
376
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
372
377
  :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
373
378
  section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
@@ -428,7 +433,7 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
428
433
  .workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
429
434
  .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; }
430
435
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
431
- `;var Vm=Object.defineProperty,Gm=Object.getOwnPropertyDescriptor,$e=(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&&Vm(t,i,r),r};let ae=class extends A{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menu=new Yi(this)}updated(e){e.has("machines")&&this.menu.closeIfOpenIdMissing(t=>this.machines.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,is(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
436
+ `;var Ym=Object.defineProperty,ev=Object.getOwnPropertyDescriptor,$e=(e,t,i,s)=>{for(var r=s>1?void 0:s?ev(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ym(t,i,r),r};let ae=class extends A{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menu=new Yi(this)}updated(e){e.has("machines")&&this.menu.closeIfOpenIdMissing(t=>this.machines.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,is(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
432
437
  <section>
433
438
  <h2>${this.renderHeading()}</h2>
434
439
  ${this.collapsed?null:l`
@@ -437,7 +442,7 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
437
442
  </div>
438
443
  `}
439
444
  </section>
440
- `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=hl(e)&&this.onRemove!==void 0;return l`
445
+ `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=ml(e)&&this.onRemove!==void 0;return l`
441
446
  <div
442
447
  class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
443
448
  tabindex="0"
@@ -450,7 +455,7 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
450
455
  </div>
451
456
  ${s?this.renderMachineMenu(e):null}
452
457
  </div>
453
- `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=sl(this.activities[e.id]);return Xi(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.menu.isOpen(e.id),i=Jm(e.id);return l`
458
+ `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=al(this.activities[e.id]);return Xi(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.menu.isOpen(e.id),i=tv(e.id);return l`
454
459
  <div class="action-menu">
455
460
  <button
456
461
  class="action-menu-toggle"
@@ -472,7 +477,7 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
472
477
  .machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
473
478
  .machine-menu-panel button.danger { color: var(--pi-danger); }
474
479
  .machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
475
- `];$e([d({attribute:!1})],ae.prototype,"machines",2);$e([d({attribute:!1})],ae.prototype,"selected",2);$e([d({attribute:!1})],ae.prototype,"statuses",2);$e([d({attribute:!1})],ae.prototype,"activities",2);$e([d({type:Boolean,reflect:!0})],ae.prototype,"collapsible",2);$e([d({type:Boolean,reflect:!0})],ae.prototype,"collapsed",2);$e([d({attribute:!1})],ae.prototype,"onSelect",2);$e([d({attribute:!1})],ae.prototype,"onRemove",2);$e([d({attribute:!1})],ae.prototype,"onToggleCollapsed",2);$e([d({attribute:!1})],ae.prototype,"onFocusNextSection",2);$e([d({attribute:!1})],ae.prototype,"onCancelKeyboardNavigation",2);ae=$e([W("machine-list")],ae);function hl(e){return e.kind==="remote"}function Jm(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Qm=Object.defineProperty,Zm=Object.getOwnPropertyDescriptor,fe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Zm(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&&Qm(t,i,r),r};let te=class extends A{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menu=new Yi(this)}updated(e){e.has("projects")&&this.menu.closeIfOpenIdMissing(t=>this.projects.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,is(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
480
+ `];$e([d({attribute:!1})],ae.prototype,"machines",2);$e([d({attribute:!1})],ae.prototype,"selected",2);$e([d({attribute:!1})],ae.prototype,"statuses",2);$e([d({attribute:!1})],ae.prototype,"activities",2);$e([d({type:Boolean,reflect:!0})],ae.prototype,"collapsible",2);$e([d({type:Boolean,reflect:!0})],ae.prototype,"collapsed",2);$e([d({attribute:!1})],ae.prototype,"onSelect",2);$e([d({attribute:!1})],ae.prototype,"onRemove",2);$e([d({attribute:!1})],ae.prototype,"onToggleCollapsed",2);$e([d({attribute:!1})],ae.prototype,"onFocusNextSection",2);$e([d({attribute:!1})],ae.prototype,"onCancelKeyboardNavigation",2);ae=$e([W("machine-list")],ae);function ml(e){return e.kind==="remote"}function tv(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var iv=Object.defineProperty,sv=Object.getOwnPropertyDescriptor,fe=(e,t,i,s)=>{for(var r=s>1?void 0:s?sv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&iv(t,i,r),r};let te=class extends A{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menu=new Yi(this)}updated(e){e.has("projects")&&this.menu.closeIfOpenIdMissing(t=>this.projects.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,is(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
476
481
  <section>
477
482
  <h2>${this.renderHeading()}</h2>
478
483
  ${this.collapsed?null:l`
@@ -507,14 +512,14 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
507
512
  </div>
508
513
  `}
509
514
  </section>
510
- `}handleProjectKeydown(e,t){ts(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return"项目";const e=this.selected?.name??"未选择项目",t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 项目</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=Um(e,this.workspacesByProjectId[e.id]??[],this.activities);return Xi(t,t==="terminal"?"项目终端活跃":"项目活跃")}close(e){this.menu.close(),confirm(`关闭 ${e.name}?
515
+ `}handleProjectKeydown(e,t){ts(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return"项目";const e=this.selected?.name??"未选择项目",t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 项目</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=Km(e,this.workspacesByProjectId[e.id]??[],this.activities);return Xi(t,t==="terminal"?"项目终端活跃":"项目活跃")}close(e){this.menu.close(),confirm(`关闭 ${e.name}?
511
516
 
512
- 这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};te.styles=ss;fe([d({attribute:!1})],te.prototype,"projects",2);fe([d({attribute:!1})],te.prototype,"selected",2);fe([d({attribute:!1})],te.prototype,"activities",2);fe([d({attribute:!1})],te.prototype,"workspacesByProjectId",2);fe([d({type:Boolean,reflect:!0})],te.prototype,"collapsible",2);fe([d({type:Boolean,reflect:!0})],te.prototype,"collapsed",2);fe([d({attribute:!1})],te.prototype,"onSelect",2);fe([d({attribute:!1})],te.prototype,"onClose",2);fe([d({attribute:!1})],te.prototype,"onToggleCollapsed",2);fe([d({attribute:!1})],te.prototype,"onFocusPreviousSection",2);fe([d({attribute:!1})],te.prototype,"onFocusNextSection",2);fe([d({attribute:!1})],te.prototype,"onCancelKeyboardNavigation",2);te=fe([W("project-list")],te);function gn(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Xm(t)}`)}function Xm(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&Ym(e.href)){const t=e.target??"_blank",i=t==="_blank"?"noopener noreferrer":void 0;return l`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${i??void 0}>${e.text}</a>`}return l`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function Ym(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var ev=Object.defineProperty,tv=Object.getOwnPropertyDescriptor,pe=(e,t,i,s)=>{for(var r=s>1?void 0:s?tv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&ev(t,i,r),r};let Y=class extends A{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menu=new Yi(this)}updated(e){e.has("workspaces")&&this.menu.closeIfOpenIdMissing(t=>this.workspaces.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,is(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
517
+ 这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};te.styles=ss;fe([d({attribute:!1})],te.prototype,"projects",2);fe([d({attribute:!1})],te.prototype,"selected",2);fe([d({attribute:!1})],te.prototype,"activities",2);fe([d({attribute:!1})],te.prototype,"workspacesByProjectId",2);fe([d({type:Boolean,reflect:!0})],te.prototype,"collapsible",2);fe([d({type:Boolean,reflect:!0})],te.prototype,"collapsed",2);fe([d({attribute:!1})],te.prototype,"onSelect",2);fe([d({attribute:!1})],te.prototype,"onClose",2);fe([d({attribute:!1})],te.prototype,"onToggleCollapsed",2);fe([d({attribute:!1})],te.prototype,"onFocusPreviousSection",2);fe([d({attribute:!1})],te.prototype,"onFocusNextSection",2);fe([d({attribute:!1})],te.prototype,"onCancelKeyboardNavigation",2);te=fe([W("project-list")],te);function wn(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${rv(t)}`)}function rv(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&ov(e.href)){const t=e.target??"_blank",i=t==="_blank"?"noopener noreferrer":void 0;return l`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${i??void 0}>${e.text}</a>`}return l`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function ov(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var nv=Object.defineProperty,av=Object.getOwnPropertyDescriptor,pe=(e,t,i,s)=>{for(var r=s>1?void 0:s?av(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&&nv(t,i,r),r};let Y=class extends A{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menu=new Yi(this)}updated(e){e.has("workspaces")&&this.menu.closeIfOpenIdMissing(t=>this.workspaces.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,is(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
513
518
  <section>
514
519
  <h2>${this.renderHeading()}</h2>
515
520
  ${this.collapsed?null:l`
516
521
  <div class="list-body">
517
- ${this.workspaces.map(e=>{const t=iv(e),i=this.workspaceLabelItems(e);return l`
522
+ ${this.workspaces.map(e=>{const t=lv(e),i=this.workspaceLabelItems(e);return l`
518
523
  <div
519
524
  class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
520
525
  tabindex="0"
@@ -531,18 +536,18 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
531
536
  </div>
532
537
  `}
533
538
  </section>
534
- `}renderHeading(){if(!this.collapsible)return"工作区";const e=this.selected===void 0?"未选择工作区":`${this.selected.label}${this.selected.isMain?" · 主工作区":""} · ${this.selected.path}`,t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 工作区</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=Fm(jm(e,this.activities));return Xi(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return l`
539
+ `}renderHeading(){if(!this.collapsible)return"工作区";const e=this.selected===void 0?"未选择工作区":`${this.selected.label}${this.selected.isMain?" · 主工作区":""} · ${this.selected.path}`,t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 工作区</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=qm(Hm(e,this.activities));return Xi(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return l`
535
540
  <span class="workspace-primary">
536
541
  <span class="workspace-primary-label">${e}</span>
537
542
  ${this.isDeleting(i)?l`<span class="workspace-status">正在删除…</span>`:null}
538
543
  </span>
539
544
  ${t.length===0?null:l`
540
545
  <small class="workspace-secondary">
541
- <span class="workspace-label">${gn(t)}</span>
546
+ <span class="workspace-label">${wn(t)}</span>
542
547
  </small>
543
548
  `}
544
549
  ${this.renderActivity(i)}
545
- `}renderWorkspaceMenu(e,t,i){const s=this.menu.isOpen(i.id),r=rv(i.id);return l`
550
+ `}renderWorkspaceMenu(e,t,i){const s=this.menu.isOpen(i.id),r=dv(i.id);return l`
546
551
  <div class="action-menu">
547
552
  <button
548
553
  class="action-menu-toggle"
@@ -559,7 +564,7 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
559
564
  </div>
560
565
  `:null}
561
566
  </div>
562
- `}renderWorkspaceActions(e){if(!sv(e))return;const t=this.isDeleting(e);return l`
567
+ `}renderWorkspaceActions(e){if(!cv(e))return;const t=this.isDeleting(e);return l`
563
568
  <div class="workspace-menu-actions">
564
569
  <button class="danger" title=${t?"正在删除工作区":"删除工作区"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"正在删除…":"删除工作区"}</button>
565
570
  </div>
@@ -576,11 +581,11 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
576
581
  ${t.length===0?null:l`
577
582
  <div class="workspace-detail-row">
578
583
  <dt>详情</dt>
579
- <dd><span class="workspace-label">${gn(t)}</span></dd>
584
+ <dd><span class="workspace-label">${wn(t)}</span></dd>
580
585
  </div>
581
586
  `}
582
587
  </dl>
583
- `}delete(e){this.isDeleting(e)||(this.menu.close(),this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}handleWorkspaceKeydown(e,t){this.menu.closeForEscape(e,t.id)||ts(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};Y.styles=ss;pe([d({attribute:!1})],Y.prototype,"workspaces",2);pe([d({attribute:!1})],Y.prototype,"selected",2);pe([d({type:Boolean,reflect:!0})],Y.prototype,"collapsible",2);pe([d({type:Boolean,reflect:!0})],Y.prototype,"collapsed",2);pe([d({attribute:!1})],Y.prototype,"workspaceLabelItems",2);pe([d({attribute:!1})],Y.prototype,"activities",2);pe([d({attribute:!1})],Y.prototype,"deletingWorkspaceIds",2);pe([d({attribute:!1})],Y.prototype,"onSelect",2);pe([d({attribute:!1})],Y.prototype,"onDelete",2);pe([d({attribute:!1})],Y.prototype,"onToggleCollapsed",2);pe([d({attribute:!1})],Y.prototype,"onFocusPreviousSection",2);pe([d({attribute:!1})],Y.prototype,"onFocusNextSection",2);pe([d({attribute:!1})],Y.prototype,"onCancelKeyboardNavigation",2);Y=pe([W("workspace-list")],Y);function iv(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function sv(e){return e.isGitWorktree&&!e.isMain}function rv(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var ov=Object.defineProperty,nv=Object.getOwnPropertyDescriptor,M=(e,t,i,s)=>{for(var r=s>1?void 0:s?nv(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&&ov(t,i,r),r};function Wt(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let I=class extends A{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.cleanupUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。",this.collapsible=!1,this.collapsed=!1,this.menu=new Yi(this),this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set}updated(e){e.has("sessions")&&(this.menu.closeIfOpenIdMissing(i=>this.sessions.some(s=>s.id===i)),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.menu.closeIf(this.collapsed);const t=e.get("selected");if(e.has("selected")&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(e.has("selected")||e.has("sessions")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,is(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=cv(this.sessions),t=new Set(e.map(o=>o.session.id)),i=e.map(o=>o.session).filter(o=>Ot(o)==="current"),s=ul(this.sessions.filter(o=>o.archived===!0&&!t.has(o.id))),r=av(this.sessions);return l`
588
+ `}delete(e){this.isDeleting(e)||(this.menu.close(),this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}handleWorkspaceKeydown(e,t){this.menu.closeForEscape(e,t.id)||ts(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};Y.styles=ss;pe([d({attribute:!1})],Y.prototype,"workspaces",2);pe([d({attribute:!1})],Y.prototype,"selected",2);pe([d({type:Boolean,reflect:!0})],Y.prototype,"collapsible",2);pe([d({type:Boolean,reflect:!0})],Y.prototype,"collapsed",2);pe([d({attribute:!1})],Y.prototype,"workspaceLabelItems",2);pe([d({attribute:!1})],Y.prototype,"activities",2);pe([d({attribute:!1})],Y.prototype,"deletingWorkspaceIds",2);pe([d({attribute:!1})],Y.prototype,"onSelect",2);pe([d({attribute:!1})],Y.prototype,"onDelete",2);pe([d({attribute:!1})],Y.prototype,"onToggleCollapsed",2);pe([d({attribute:!1})],Y.prototype,"onFocusPreviousSection",2);pe([d({attribute:!1})],Y.prototype,"onFocusNextSection",2);pe([d({attribute:!1})],Y.prototype,"onCancelKeyboardNavigation",2);Y=pe([W("workspace-list")],Y);function lv(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function cv(e){return e.isGitWorktree&&!e.isMain}function dv(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var pv=Object.defineProperty,hv=Object.getOwnPropertyDescriptor,M=(e,t,i,s)=>{for(var r=s>1?void 0:s?hv(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&&pv(t,i,r),r};function Wt(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let R=class extends A{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.cleanupUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。",this.collapsible=!1,this.collapsed=!1,this.menu=new Yi(this),this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set}updated(e){e.has("sessions")&&(this.menu.closeIfOpenIdMissing(i=>this.sessions.some(s=>s.id===i)),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.menu.closeIf(this.collapsed);const t=e.get("selected");if(e.has("selected")&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(e.has("selected")||e.has("sessions")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,is(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=gv(this.sessions),t=new Set(e.map(o=>o.session.id)),i=e.map(o=>o.session).filter(o=>Ot(o)==="current"),s=vl(this.sessions.filter(o=>o.archived===!0&&!t.has(o.id))),r=uv(this.sessions);return l`
584
589
  <section>
585
590
  ${this.renderHeading(e.length+s.length,i)}
586
591
  ${this.collapsed?null:l`
@@ -612,7 +617,7 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
612
617
  ${this.renderCleanupButton()}
613
618
  <button ?disabled=${!this.canStart} @click=${r=>{r.stopPropagation(),this.onStart?.()}}>+</button>
614
619
  </h2>
615
- `}renderCurrentSelectionButton(e){if(this.collapsed||e.length===0)return null;const t=this.selectionScopes.has("current");return l`<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>`}renderCleanupButton(){return l`<button class="cleanup-entry" title=${this.canCleanup?"Preview session cleanup":this.cleanupUnavailableMessage} @click=${e=>{e.stopPropagation(),this.onCleanup?.()}}>Clean up</button>`}renderArchivedHeading(e){const t=this.selectionScopes.has("archived");return l`
620
+ `}renderCurrentSelectionButton(e){if(this.collapsed||e.length===0)return null;const t=this.selectionScopes.has("current");return l`<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>`}renderCleanupButton(){return l`<button class="cleanup-entry" title=${this.canCleanup?"预览会话清理":this.cleanupUnavailableMessage} @click=${e=>{e.stopPropagation(),this.onCleanup?.()}}>清理</button>`}renderArchivedHeading(e){const t=this.selectionScopes.has("archived");return l`
616
621
  <h2 class="subheading">
617
622
  <button class="section-toggle" aria-expanded=${String(this.archivedExpanded)} @click=${()=>{this.toggleArchived()}}><span>${this.archivedExpanded?"▾":"▸"} 已归档</span></button>
618
623
  ${this.archivedExpanded?l`<button class="bulk-select-entry ${t?"selected":""}" title=${t?"关闭已归档会话选择":"选择已归档会话"} aria-label=${t?"关闭已归档会话选择":"选择已归档会话"} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${()=>{this.toggleSelection("archived",e)}}>☑</button>`:null}
@@ -666,7 +671,7 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
666
671
  `:null}
667
672
  </div>
668
673
  </div>
669
- `}handleSessionKeydown(e,t,i){ts(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)&&Ot(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){confirm(`归档“${Wt(e)}”及其 ${String(t)} 个后代会话?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`永久删除已归档会话“${Wt(e)}”?此操作无法撤销。`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");e.length!==0&&confirm(`永久删除 ${String(e.length)} 个所选已归档会话?此操作无法撤销。`)&&(this.selectedSessionIds=Ps(this.selectedSessionIds,e.map(t=>t.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>!Z(t));this.selectedSessionIds=Ps(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=>Ot(i)===e).map(i=>i.id);this.selectedSessionIds=Ps(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)&&Ot(t)===e)}pruneSelectedSessionIds(){const e=new Set(this.sessions.map(i=>i.id)),t=new Set([...this.selectedSessionIds].filter(i=>e.has(i)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has("archived")&&!this.sessions.some(i=>i.archived===!0)&&this.closeSelection("archived"),this.selectionScopes.has("current")&&!this.sessions.some(i=>i.archived!==!0)&&this.closeSelection("current")}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.menu.close(),this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return Z(e)?"新建 · ":e.archived===!0?"只读 · ":""}renderActivity(e){const t=lv(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return Xi(t,t==="sending"?"正在发送消息":"会话活跃")}};I.styles=[ss,E`
674
+ `}handleSessionKeydown(e,t,i){ts(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)&&Ot(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){confirm(`归档“${Wt(e)}”及其 ${String(t)} 个后代会话?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`永久删除已归档会话“${Wt(e)}”?此操作无法撤销。`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");e.length!==0&&confirm(`永久删除 ${String(e.length)} 个所选已归档会话?此操作无法撤销。`)&&(this.selectedSessionIds=Ps(this.selectedSessionIds,e.map(t=>t.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>!Z(t));this.selectedSessionIds=Ps(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=>Ot(i)===e).map(i=>i.id);this.selectedSessionIds=Ps(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)&&Ot(t)===e)}pruneSelectedSessionIds(){const e=new Set(this.sessions.map(i=>i.id)),t=new Set([...this.selectedSessionIds].filter(i=>e.has(i)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has("archived")&&!this.sessions.some(i=>i.archived===!0)&&this.closeSelection("archived"),this.selectionScopes.has("current")&&!this.sessions.some(i=>i.archived!==!0)&&this.closeSelection("current")}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.menu.close(),this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return Z(e)?"新建 · ":e.archived===!0?"只读 · ":""}renderActivity(e){const t=fv(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return Xi(t,t==="sending"?"正在发送消息":"会话活跃")}};R.styles=[ss,E`
670
675
  h2 { min-height: 30px; }
671
676
  h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
672
677
  .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; }
@@ -682,27 +687,27 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
682
687
  .action-row.bulk-selected .action-main { border-color: var(--pi-accent); box-shadow: inset 3px 0 0 var(--pi-accent); }
683
688
  .action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
684
689
  .session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
685
- `];M([d({attribute:!1})],I.prototype,"sessions",2);M([d({attribute:!1})],I.prototype,"statuses",2);M([d({attribute:!1})],I.prototype,"activities",2);M([d({attribute:!1})],I.prototype,"sending",2);M([d({attribute:!1})],I.prototype,"selected",2);M([d({type:Boolean})],I.prototype,"canStart",2);M([d({type:Boolean})],I.prototype,"canDeleteArchived",2);M([d({type:Boolean})],I.prototype,"canReload",2);M([d({type:Boolean})],I.prototype,"canCleanup",2);M([d({type:String})],I.prototype,"archivedDeleteUnavailableMessage",2);M([d({type:String})],I.prototype,"cleanupUnavailableMessage",2);M([d({type:Boolean,reflect:!0})],I.prototype,"collapsible",2);M([d({type:Boolean,reflect:!0})],I.prototype,"collapsed",2);M([d({attribute:!1})],I.prototype,"onSelect",2);M([d({attribute:!1})],I.prototype,"onStart",2);M([d({attribute:!1})],I.prototype,"onToggleCollapsed",2);M([d({attribute:!1})],I.prototype,"onArchivedCollapsed",2);M([d({attribute:!1})],I.prototype,"onFocusPreviousSection",2);M([d({attribute:!1})],I.prototype,"onFocusNextSection",2);M([d({attribute:!1})],I.prototype,"onCancelKeyboardNavigation",2);M([d({attribute:!1})],I.prototype,"onArchive",2);M([d({attribute:!1})],I.prototype,"onArchiveWithDescendants",2);M([d({attribute:!1})],I.prototype,"onArchiveMany",2);M([d({attribute:!1})],I.prototype,"onRestore",2);M([d({attribute:!1})],I.prototype,"onDelete",2);M([d({attribute:!1})],I.prototype,"onDeleteArchived",2);M([d({attribute:!1})],I.prototype,"onDeleteArchivedMany",2);M([d({attribute:!1})],I.prototype,"onDetachParent",2);M([d({attribute:!1})],I.prototype,"onReload",2);M([d({attribute:!1})],I.prototype,"onCleanup",2);M([y()],I.prototype,"archivedExpanded",2);M([y()],I.prototype,"selectionScopes",2);M([y()],I.prototype,"selectedSessionIds",2);I=M([W("session-list")],I);function Ot(e){return e.archived===!0?"archived":"current"}function Ps(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function av(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 lv(e,t,i,s){if(!(Z(e)||e.archived===!0))return s?"sending":Xe(t,i)?"session":void 0}function cv(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 ul(e.filter(s=>i.has(s.id)))}function ul(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,c=a===void 0?void 0:t.get(a);if(c===void 0){s.push(n);continue}const p=i.get(c.path)??[];p.push(n),i.set(c.path,p)}const r=[],o=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;r.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])o(h,a+1,u)};for(const n of s)o(n,0,new Set);return r}var dv=Object.defineProperty,pv=Object.getOwnPropertyDescriptor,oe=(e,t,i,s)=>{for(var r=s>1?void 0:s?pv(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&&dv(t,i,r),r};let J=class extends A{constructor(){super(...arguments),this.canCleanup=!0,this.unavailableMessage="Update and restart Pi-Web on this machine to clean up sessions.",this.loading=!1,this.running=!1,this.error="",this.draft={...mf},this.formError=""}willUpdate(e){e.has("preview")&&(this.selectedProjectCwds=this.preview?.projects.map(t=>t.cwd))}render(){const e=Ft(this.draft),t=this.selectedPreview(),i=Qo({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),s=i?"Run cleanup":t!==void 0&&!wi(t)?"Select at least one project to run cleanup":"Preview cleanup before running it";return l`
690
+ `];M([d({attribute:!1})],R.prototype,"sessions",2);M([d({attribute:!1})],R.prototype,"statuses",2);M([d({attribute:!1})],R.prototype,"activities",2);M([d({attribute:!1})],R.prototype,"sending",2);M([d({attribute:!1})],R.prototype,"selected",2);M([d({type:Boolean})],R.prototype,"canStart",2);M([d({type:Boolean})],R.prototype,"canDeleteArchived",2);M([d({type:Boolean})],R.prototype,"canReload",2);M([d({type:Boolean})],R.prototype,"canCleanup",2);M([d({type:String})],R.prototype,"archivedDeleteUnavailableMessage",2);M([d({type:String})],R.prototype,"cleanupUnavailableMessage",2);M([d({type:Boolean,reflect:!0})],R.prototype,"collapsible",2);M([d({type:Boolean,reflect:!0})],R.prototype,"collapsed",2);M([d({attribute:!1})],R.prototype,"onSelect",2);M([d({attribute:!1})],R.prototype,"onStart",2);M([d({attribute:!1})],R.prototype,"onToggleCollapsed",2);M([d({attribute:!1})],R.prototype,"onArchivedCollapsed",2);M([d({attribute:!1})],R.prototype,"onFocusPreviousSection",2);M([d({attribute:!1})],R.prototype,"onFocusNextSection",2);M([d({attribute:!1})],R.prototype,"onCancelKeyboardNavigation",2);M([d({attribute:!1})],R.prototype,"onArchive",2);M([d({attribute:!1})],R.prototype,"onArchiveWithDescendants",2);M([d({attribute:!1})],R.prototype,"onArchiveMany",2);M([d({attribute:!1})],R.prototype,"onRestore",2);M([d({attribute:!1})],R.prototype,"onDelete",2);M([d({attribute:!1})],R.prototype,"onDeleteArchived",2);M([d({attribute:!1})],R.prototype,"onDeleteArchivedMany",2);M([d({attribute:!1})],R.prototype,"onDetachParent",2);M([d({attribute:!1})],R.prototype,"onReload",2);M([d({attribute:!1})],R.prototype,"onCleanup",2);M([y()],R.prototype,"archivedExpanded",2);M([y()],R.prototype,"selectionScopes",2);M([y()],R.prototype,"selectedSessionIds",2);R=M([W("session-list")],R);function Ot(e){return e.archived===!0?"archived":"current"}function Ps(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function uv(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 fv(e,t,i,s){if(!(Z(e)||e.archived===!0))return s?"sending":Xe(t,i)?"session":void 0}function gv(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 vl(e.filter(s=>i.has(s.id)))}function vl(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,c=a===void 0?void 0:t.get(a);if(c===void 0){s.push(n);continue}const p=i.get(c.path)??[];p.push(n),i.set(c.path,p)}const r=[],o=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;r.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])o(h,a+1,u)};for(const n of s)o(n,0,new Set);return r}var mv=Object.defineProperty,vv=Object.getOwnPropertyDescriptor,oe=(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&&mv(t,i,r),r};let J=class extends A{constructor(){super(...arguments),this.canCleanup=!0,this.unavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。",this.loading=!1,this.running=!1,this.error="",this.draft={...yf},this.formError=""}willUpdate(e){e.has("preview")&&(this.selectedProjectCwds=this.preview?.projects.map(t=>t.cwd))}render(){const e=Ft(this.draft),t=this.selectedPreview(),i=Qo({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),s=i?"运行清理":t!==void 0&&!wi(t)?"至少选择一个项目才能运行清理":"运行清理前请先预览";return l`
686
691
  <div class="backdrop" @mousedown=${()=>{this.onClose?.()}}>
687
- <section role="dialog" aria-modal="true" aria-label="Clean up sessions" @mousedown=${r=>{r.stopPropagation()}} @keydown=${r=>{this.handleKeyDown(r)}}>
692
+ <section role="dialog" aria-modal="true" aria-label="清理会话" @mousedown=${r=>{r.stopPropagation()}} @keydown=${r=>{this.handleKeyDown(r)}}>
688
693
  <header>
689
694
  <div>
690
- <span class="eyebrow">Sessions</span>
691
- <h1>Clean up sessions</h1>
695
+ <span class="eyebrow">会话</span>
696
+ <h1>清理会话</h1>
692
697
  </div>
693
- <button class="close-button" title="Close cleanup" aria-label="Close cleanup" @click=${()=>{this.onClose?.()}}>×</button>
698
+ <button class="close-button" title="关闭清理" aria-label="关闭清理" @click=${()=>{this.onClose?.()}}>×</button>
694
699
  </header>
695
700
  <div class="body">
696
- <p class="intro">Preview manual cleanup for this machine before archiving idle sessions or permanently deleting old archived sessions.</p>
701
+ <p class="intro">归档空闲会话或永久删除旧的已归档会话前,先预览此机器的手动清理结果。</p>
697
702
  ${this.canCleanup?this.renderForm(e.ok?"":e.error):this.renderUnavailable()}
698
703
  ${this.renderMessage()}
699
704
  ${this.preview===void 0?null:this.renderPreview(this.preview)}
700
705
  ${this.result===void 0?null:this.renderResult(this.result)}
701
706
  </div>
702
707
  <footer>
703
- <button @click=${()=>{this.onClose?.()}}>${this.result===void 0?"Cancel":"Close"}</button>
704
- <button ?disabled=${!this.canCleanup||this.loading||this.running} @click=${()=>{this.previewCleanup()}}>${this.loading?"Previewing…":"Preview"}</button>
705
- <button class="danger" ?disabled=${!i} title=${s} @click=${()=>{this.runCleanup()}}>${this.running?"Running…":"Run cleanup"}</button>
708
+ <button @click=${()=>{this.onClose?.()}}>${this.result===void 0?"取消":"关闭"}</button>
709
+ <button ?disabled=${!this.canCleanup||this.loading||this.running} @click=${()=>{this.previewCleanup()}}>${this.loading?"正在预览…":"预览"}</button>
710
+ <button class="danger" ?disabled=${!i} title=${s} @click=${()=>{this.runCleanup()}}>${this.running?"正在运行…":"运行清理"}</button>
706
711
  </footer>
707
712
  </section>
708
713
  </div>
@@ -710,61 +715,61 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
710
715
  <fieldset ?disabled=${t}>
711
716
  <label class="toggle-row">
712
717
  <input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${r=>{this.updateDraft({archiveIdleEnabled:Cs(r)})}}>
713
- <span>Archive non-archived sessions idle for more than</span>
714
- <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${r=>{this.updateDraft({archiveIdleDays:mn(r)})}}>
715
- <span>days</span>
718
+ <span>归档空闲超过</span>
719
+ <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${r=>{this.updateDraft({archiveIdleDays:yn(r)})}}>
720
+ <span>天的未归档会话</span>
716
721
  </label>
717
722
  <label class="toggle-row delete-row">
718
723
  <input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${r=>{this.updateDraft({deleteArchivedEnabled:Cs(r)})}}>
719
- <span>Delete archived sessions archived for more than</span>
720
- <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${r=>{this.updateDraft({deleteArchivedDays:mn(r)})}}>
721
- <span>days</span>
724
+ <span>删除已归档超过</span>
725
+ <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${r=>{this.updateDraft({deleteArchivedDays:yn(r)})}}>
726
+ <span>天的已归档会话</span>
722
727
  </label>
723
728
  </fieldset>
724
- <p class="warning"><strong>Deletion is permanent.</strong> Cleanup only deletes sessions that are already archived.</p>
729
+ <p class="warning"><strong>删除是永久操作。</strong>清理只会删除已经归档的会话。</p>
725
730
  ${e===""?null:l`<div class="dialog-error" role="alert">${e}</div>`}
726
- ${s?l`<div class="hint" role="status">Thresholds changed. Preview again before running cleanup.</div>`:null}
731
+ ${s?l`<div class="hint" role="status">阈值已更改。运行清理前请重新预览。</div>`:null}
727
732
  `}renderUnavailable(){return l`<div class="unavailable" role="status">${this.unavailableMessage}</div>`}renderMessage(){const e=this.formError||this.error;return e===""?null:l`<div class="dialog-error" role="alert">${e}</div>`}renderPreview(e){const t=this.selectedProjectCwdsForPreview(),i=new Set(t),s=Zo(e,t);return l`
728
- <section class="preview" aria-label="Cleanup preview">
729
- <h2>Preview</h2>
730
- ${e.projects.length===0?l`<p class="empty">No sessions match these thresholds.</p>`:l`
733
+ <section class="preview" aria-label="清理预览">
734
+ <h2>预览</h2>
735
+ ${e.projects.length===0?l`<p class="empty">没有会话匹配这些阈值。</p>`:l`
731
736
  ${this.renderSelectionControls(e,t)}
732
- <div class="table-scroll" tabindex="0" aria-label="Cleanup projects table">
737
+ <div class="table-scroll" tabindex="0" aria-label="清理项目表">
733
738
  <table>
734
739
  <thead>
735
- <tr><th>Clean up</th><th>Project/workspace path</th><th>Archive</th><th>Delete archived</th></tr>
740
+ <tr><th>清理</th><th>项目/工作区路径</th><th>归档</th><th>删除已归档</th></tr>
736
741
  </thead>
737
742
  <tbody>
738
743
  ${e.projects.map(r=>this.renderProjectRow(r,i.has(r.cwd)))}
739
744
  </tbody>
740
745
  <tfoot>
741
- <tr><th colspan="2">Selected totals</th><td>${s.totals.archiveCount}</td><td>${s.totals.deleteCount}</td></tr>
746
+ <tr><th colspan="2">已选合计</th><td>${s.totals.archiveCount}</td><td>${s.totals.deleteCount}</td></tr>
742
747
  </tfoot>
743
748
  </table>
744
749
  </div>
745
750
  `}
746
- ${e.skippedBusySessionIds===void 0||e.skippedBusySessionIds.length===0?null:l`<p class="hint">${e.skippedBusySessionIds.length} busy ${e.skippedBusySessionIds.length===1?"session was":"sessions were"} skipped.</p>`}
751
+ ${e.skippedBusySessionIds===void 0||e.skippedBusySessionIds.length===0?null:l`<p class="hint">已跳过 ${e.skippedBusySessionIds.length} 个忙碌会话。</p>`}
747
752
  </section>
748
753
  `}renderSelectionControls(e,t){const i=this.loading||this.running;return l`
749
- <div class="selection-controls" role="group" aria-label="Project selection">
750
- <span>${t.length} of ${e.projects.length} projects selected</span>
751
- <button ?disabled=${i||t.length===e.projects.length} @click=${()=>{this.selectAllProjects()}}>Select all</button>
752
- <button ?disabled=${i||t.length===0} @click=${()=>{this.deselectAllProjects()}}>Deselect all</button>
754
+ <div class="selection-controls" role="group" aria-label="项目选择">
755
+ <span>已选择 ${t.length} / ${e.projects.length} 个项目</span>
756
+ <button ?disabled=${i||t.length===e.projects.length} @click=${()=>{this.selectAllProjects()}}>全选</button>
757
+ <button ?disabled=${i||t.length===0} @click=${()=>{this.deselectAllProjects()}}>取消全选</button>
753
758
  </div>
754
- ${t.length===0?l`<p class="hint" role="status">Select at least one project to run cleanup.</p>`:null}
759
+ ${t.length===0?l`<p class="hint" role="status">至少选择一个项目才能运行清理。</p>`:null}
755
760
  `}renderProjectRow(e,t){return l`
756
761
  <tr class=${t?"":"unselected"}>
757
- <td class="select-cell"><input type="checkbox" aria-label=${`Clean up ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${i=>{this.setProjectSelected(e.cwd,Cs(i))}}></td>
762
+ <td class="select-cell"><input type="checkbox" aria-label=${`清理 ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${i=>{this.setProjectSelected(e.cwd,Cs(i))}}></td>
758
763
  <th title=${e.cwd} dir="auto">${e.cwd}</th>
759
764
  <td>${e.archiveCount}</td>
760
765
  <td>${e.deleteCount}</td>
761
766
  </tr>
762
767
  `}renderResult(e){return l`
763
- <section class="result" aria-label="Cleanup result">
764
- <h2>Cleanup complete</h2>
765
- <p>Archived ${e.archivedSessionIds.length} ${e.archivedSessionIds.length===1?"session":"sessions"}; permanently deleted ${e.deletedSessionIds.length} archived ${e.deletedSessionIds.length===1?"session":"sessions"}.</p>
768
+ <section class="result" aria-label="清理结果">
769
+ <h2>清理完成</h2>
770
+ <p>已归档 ${e.archivedSessionIds.length} 个会话;已永久删除 ${e.deletedSessionIds.length} 个已归档会话。</p>
766
771
  </section>
767
- `}updateDraft(e){this.draft={...this.draft,...e},this.formError=""}selectedPreview(){return this.preview===void 0?void 0:Zo(this.preview,this.selectedProjectCwdsForPreview())}selectedProjectCwdsForPreview(){return this.preview===void 0?[]:Ka(this.preview,this.selectedProjectCwds)}selectAllProjects(){this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd)??[],this.formError=""}deselectAllProjects(){this.selectedProjectCwds=[],this.formError=""}setProjectSelected(e,t){const i=this.preview;if(i===void 0)return;const s=new Set(this.selectedProjectCwdsForPreview());t?s.add(e):s.delete(e),this.selectedProjectCwds=i.projects.map(r=>r.cwd).filter(r=>s.has(r)),this.formError=""}previewCleanup(){const e=Ft(this.draft);if(!e.ok){this.formError=e.error;return}this.formError="",this.onPreview?.(e.request)}runCleanup(){const e=Ft(this.draft);if(!e.ok){this.formError=e.error;return}const t=this.selectedPreview(),i=this.selectedProjectCwdsForPreview();if(!Qo({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest})){this.formError=t!==void 0&&!wi(t)?"Select at least one project to run cleanup.":"Preview cleanup before running it.";return}t===void 0||!vf(t,s=>confirm(s))||(this.formError="",this.onRun?.({...e.request,projectCwds:i}))}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};J.styles=E`
772
+ `}updateDraft(e){this.draft={...this.draft,...e},this.formError=""}selectedPreview(){return this.preview===void 0?void 0:Zo(this.preview,this.selectedProjectCwdsForPreview())}selectedProjectCwdsForPreview(){return this.preview===void 0?[]:Qa(this.preview,this.selectedProjectCwds)}selectAllProjects(){this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd)??[],this.formError=""}deselectAllProjects(){this.selectedProjectCwds=[],this.formError=""}setProjectSelected(e,t){const i=this.preview;if(i===void 0)return;const s=new Set(this.selectedProjectCwdsForPreview());t?s.add(e):s.delete(e),this.selectedProjectCwds=i.projects.map(r=>r.cwd).filter(r=>s.has(r)),this.formError=""}previewCleanup(){const e=Ft(this.draft);if(!e.ok){this.formError=e.error;return}this.formError="",this.onPreview?.(e.request)}runCleanup(){const e=Ft(this.draft);if(!e.ok){this.formError=e.error;return}const t=this.selectedPreview(),i=this.selectedProjectCwdsForPreview();if(!Qo({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest})){this.formError=t!==void 0&&!wi(t)?"至少选择一个项目才能运行清理。":"运行清理前请先预览。";return}t===void 0||!xf(t,s=>confirm(s))||(this.formError="",this.onRun?.({...e.request,projectCwds:i}))}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};J.styles=E`
768
773
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
769
774
  .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; }
770
775
  section[role="dialog"] { width: min(760px, 100%); max-height: min(760px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr) auto; border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -814,7 +819,7 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
814
819
  table { min-width: 560px; }
815
820
  thead th:first-child, td.select-cell { width: 58px; }
816
821
  }
817
- `;oe([d({type:Boolean})],J.prototype,"canCleanup",2);oe([d({type:String})],J.prototype,"unavailableMessage",2);oe([d({attribute:!1})],J.prototype,"preview",2);oe([d({attribute:!1})],J.prototype,"previewRequest",2);oe([d({attribute:!1})],J.prototype,"result",2);oe([d({type:Boolean})],J.prototype,"loading",2);oe([d({type:Boolean})],J.prototype,"running",2);oe([d({type:String})],J.prototype,"error",2);oe([d({attribute:!1})],J.prototype,"onPreview",2);oe([d({attribute:!1})],J.prototype,"onRun",2);oe([d({attribute:!1})],J.prototype,"onClose",2);oe([y()],J.prototype,"draft",2);oe([y()],J.prototype,"formError",2);oe([y()],J.prototype,"selectedProjectCwds",2);J=oe([W("session-cleanup-dialog")],J);function Cs(e){return e.target instanceof HTMLInputElement?e.target.checked:!1}function mn(e){return e.target instanceof HTMLInputElement?e.target.value:""}const Wr={CHILD:2,ELEMENT:6},Or=e=>(...t)=>({_$litDirective$:e,values:t});let _r=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:hv}=wc,vn=e=>e,bn=()=>document.createComment(""),_t=(e,t,i)=>{const s=e._$AA.parentNode,r=t===void 0?e._$AB:t._$AA;if(i===void 0){const o=s.insertBefore(bn(),r),n=s.insertBefore(bn(),r);i=new hv(o,n,e,e.options)}else{const o=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let c;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(c=e._$AU)!==n._$AU&&i._$AP(c)}if(o!==r||a){let c=i._$AA;for(;c!==o;){const p=vn(c).nextSibling;vn(s).insertBefore(c,r),c=p}}}return i},rt=(e,t,i=e)=>(e._$AI(t,i),e),uv={},fv=(e,t=uv)=>e._$AH=t,gv=e=>e._$AH,Rs=e=>{e._$AR(),e._$AA.remove()};const wn=(e,t,i)=>{const s=new Map;for(let r=t;r<=i;r++)s.set(e[r],r);return s},mv=Or(class extends _r{constructor(e){if(super(e),e.type!==Wr.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=gv(e),{values:o,keys:n}=this.dt(t,i,s);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],c=[];let p,u,h=0,g=r.length-1,b=0,P=o.length-1;for(;h<=g&&b<=P;)if(r[h]===null)h++;else if(r[g]===null)g--;else if(a[h]===n[b])c[b]=rt(r[h],o[b]),h++,b++;else if(a[g]===n[P])c[P]=rt(r[g],o[P]),g--,P--;else if(a[h]===n[P])c[P]=rt(r[h],o[P]),_t(e,c[P+1],r[h]),h++,P--;else if(a[g]===n[b])c[b]=rt(r[g],o[b]),_t(e,r[h],r[g]),g--,b++;else if(p===void 0&&(p=wn(n,b,P),u=wn(a,h,g)),p.has(a[h]))if(p.has(a[g])){const R=u.get(n[b]),V=R!==void 0?r[R]:null;if(V===null){const Ve=_t(e,r[h]);rt(Ve,o[b]),c[b]=Ve}else c[b]=rt(V,o[b]),_t(e,r[h],V),r[R]=null;b++}else Rs(r[g]),g--;else Rs(r[h]),h++;for(;b<=P;){const R=_t(e,c[P+1]);rt(R,o[b]),c[b++]=R}for(;h<=g;){const R=r[h++];R!==null&&Rs(R)}return this.ut=n,fv(e,c),Ze}}),vv="pi-web:chat-groups:",bv={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(yn(e));return t===null||t===""?void 0:yv(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(yn(e),JSON.stringify(t))}catch{}}};class wv{constructor(t=bv){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&&xn(o,this.openGroupKeys)&&xn(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 yn(e){return`${vv}${e}`}function yv(e){if(Array.isArray(e))return{open:Is(e),closedDefaultOpen:[]};if(xv(e))return{open:Array.isArray(e.open)?Is(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Is(e.closedDefaultOpen):[]}}function Is(e){return e.filter(t=>typeof t=="string")}function xn(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function xv(e){return typeof e=="object"&&e!==null}function Sv(e,t=0){const i=[];let s=[],r=0;const o=(a,c)=>{s.length||(r=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:r,endIndex:r+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(b=>Sn(a,b)),u=a.parts.filter(b=>!Sn(a,b)),h=t+c,g={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&o({role:a.role,parts:u,...g},h),p.length){n();const b=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:b,parts:p,...g},index:h})}}),n(),i}function kv(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)} ${$v(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function $v(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Sn(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 Pv=30;function Cv(e,t){const i=Iv(Mv(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Rv(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Av(s,t.markerOffset);return}e.scrollTop=Tv(e.scrollHeight,t.distanceFromBottom)}function Iv(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 Av(e,t){return e-t}function Tv(e,t){return Math.max(0,e-t)}function Mv(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 Ev=600,Dv=1;function Wv(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:Ov(e)||_v(e)}function Ov(e){return e.scrollTop<(e.topThreshold??Math.max(Ev,e.clientHeight))}function _v(e){return e.scrollHeight<=e.clientHeight+Dv}const Lv="pi-web:chat-scroll:",jv=180,Fv=48,Uv=2,zv={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)}},Bv={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class Nv{constructor(t=zv,i=Bv){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=jv){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,r=Uv){if(t===""||i===void 0||!Ts(i))return"skipped";try{if(gl(i,r)){const a={mode:"bottom"};return this.storage.setItem(As(t),JSON.stringify(a)),"saved"}const o=Kv(i,s);if(o===void 0)return"skipped";const n=qv(i,o);return this.storage.setItem(As(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||!Ts(i))return{status:"skipped"};const o=Vv(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(As(t));if(i===null||i==="")return;const s=JSON.parse(i);return Hv(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!Ts(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function As(e){return`${Lv}${e}`}function Hv(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 Ts(e){return e.clientHeight>0&&e.scrollHeight>0}function fl(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function gl(e,t=Fv){return fl(e)<t}function qv(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:Lr(t)??"",offset:t.getBoundingClientRect().top-i}}function Kv(e,t){const i=e.getBoundingClientRect();let s,r=Number.NEGATIVE_INFINITY,o,n=Number.POSITIVE_INFINITY;for(const a of t){if(Lr(a)===void 0)continue;const c=a.getBoundingClientRect();if(c.bottom<=c.top||c.bottom<i.top||c.top>i.bottom)continue;const p=c.top-i.top;p<=0&&p>=r?(s=a,r=p):p>0&&p<n&&(o=a,n=p)}return s??o}function kn(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const r=s.getBoundingClientRect();return r.bottom>=i.top&&r.top<=i.bottom})}function Vv(e,t){return e.find(i=>Lr(i)===t)}function Lr(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}async function jr(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}const Gv=E`
822
+ `;oe([d({type:Boolean})],J.prototype,"canCleanup",2);oe([d({type:String})],J.prototype,"unavailableMessage",2);oe([d({attribute:!1})],J.prototype,"preview",2);oe([d({attribute:!1})],J.prototype,"previewRequest",2);oe([d({attribute:!1})],J.prototype,"result",2);oe([d({type:Boolean})],J.prototype,"loading",2);oe([d({type:Boolean})],J.prototype,"running",2);oe([d({type:String})],J.prototype,"error",2);oe([d({attribute:!1})],J.prototype,"onPreview",2);oe([d({attribute:!1})],J.prototype,"onRun",2);oe([d({attribute:!1})],J.prototype,"onClose",2);oe([y()],J.prototype,"draft",2);oe([y()],J.prototype,"formError",2);oe([y()],J.prototype,"selectedProjectCwds",2);J=oe([W("session-cleanup-dialog")],J);function Cs(e){return e.target instanceof HTMLInputElement?e.target.checked:!1}function yn(e){return e.target instanceof HTMLInputElement?e.target.value:""}const Wr={CHILD:2,ELEMENT:6},Or=e=>(...t)=>({_$litDirective$:e,values:t});let _r=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:bv}=kc,xn=e=>e,Sn=()=>document.createComment(""),_t=(e,t,i)=>{const s=e._$AA.parentNode,r=t===void 0?e._$AB:t._$AA;if(i===void 0){const o=s.insertBefore(Sn(),r),n=s.insertBefore(Sn(),r);i=new bv(o,n,e,e.options)}else{const o=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let c;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(c=e._$AU)!==n._$AU&&i._$AP(c)}if(o!==r||a){let c=i._$AA;for(;c!==o;){const p=xn(c).nextSibling;xn(s).insertBefore(c,r),c=p}}}return i},rt=(e,t,i=e)=>(e._$AI(t,i),e),wv={},yv=(e,t=wv)=>e._$AH=t,xv=e=>e._$AH,Is=e=>{e._$AR(),e._$AA.remove()};const kn=(e,t,i)=>{const s=new Map;for(let r=t;r<=i;r++)s.set(e[r],r);return s},Sv=Or(class extends _r{constructor(e){if(super(e),e.type!==Wr.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=xv(e),{values:o,keys:n}=this.dt(t,i,s);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],c=[];let p,u,h=0,g=r.length-1,b=0,P=o.length-1;for(;h<=g&&b<=P;)if(r[h]===null)h++;else if(r[g]===null)g--;else if(a[h]===n[b])c[b]=rt(r[h],o[b]),h++,b++;else if(a[g]===n[P])c[P]=rt(r[g],o[P]),g--,P--;else if(a[h]===n[P])c[P]=rt(r[h],o[P]),_t(e,c[P+1],r[h]),h++,P--;else if(a[g]===n[b])c[b]=rt(r[g],o[b]),_t(e,r[h],r[g]),g--,b++;else if(p===void 0&&(p=kn(n,b,P),u=kn(a,h,g)),p.has(a[h]))if(p.has(a[g])){const I=u.get(n[b]),V=I!==void 0?r[I]:null;if(V===null){const Ve=_t(e,r[h]);rt(Ve,o[b]),c[b]=Ve}else c[b]=rt(V,o[b]),_t(e,r[h],V),r[I]=null;b++}else Is(r[g]),g--;else Is(r[h]),h++;for(;b<=P;){const I=_t(e,c[P+1]);rt(I,o[b]),c[b++]=I}for(;h<=g;){const I=r[h++];I!==null&&Is(I)}return this.ut=n,yv(e,c),Ze}}),kv="pi-web:chat-groups:",$v={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem($n(e));return t===null||t===""?void 0:Cv(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem($n(e),JSON.stringify(t))}catch{}}};class Pv{constructor(t=$v){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&&Pn(o,this.openGroupKeys)&&Pn(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 $n(e){return`${kv}${e}`}function Cv(e){if(Array.isArray(e))return{open:Rs(e),closedDefaultOpen:[]};if(Iv(e))return{open:Array.isArray(e.open)?Rs(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Rs(e.closedDefaultOpen):[]}}function Rs(e){return e.filter(t=>typeof t=="string")}function Pn(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Iv(e){return typeof e=="object"&&e!==null}function Rv(e,t=0){const i=[];let s=[],r=0;const o=(a,c)=>{s.length||(r=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:r,endIndex:r+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(b=>Cn(a,b)),u=a.parts.filter(b=>!Cn(a,b)),h=t+c,g={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&o({role:a.role,parts:u,...g},h),p.length){n();const b=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:b,parts:p,...g},index:h})}}),n(),i}function Av(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)} ${Tv(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Tv(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Cn(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 Mv=30;function Ev(e,t){const i=Wv(Lv(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Dv(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Ov(s,t.markerOffset);return}e.scrollTop=_v(e.scrollHeight,t.distanceFromBottom)}function Wv(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 Ov(e,t){return e-t}function _v(e,t){return Math.max(0,e-t)}function Lv(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 jv=600,Fv=1;function Uv(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:zv(e)||Bv(e)}function zv(e){return e.scrollTop<(e.topThreshold??Math.max(jv,e.clientHeight))}function Bv(e){return e.scrollHeight<=e.clientHeight+Fv}const Nv="pi-web:chat-scroll:",Hv=180,qv=48,Kv=2,Vv={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)}},Gv={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class Jv{constructor(t=Vv,i=Gv){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=Hv){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,r=Kv){if(t===""||i===void 0||!Ts(i))return"skipped";try{if(wl(i,r)){const a={mode:"bottom"};return this.storage.setItem(As(t),JSON.stringify(a)),"saved"}const o=Xv(i,s);if(o===void 0)return"skipped";const n=Zv(i,o);return this.storage.setItem(As(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||!Ts(i))return{status:"skipped"};const o=Yv(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(As(t));if(i===null||i==="")return;const s=JSON.parse(i);return Qv(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!Ts(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function As(e){return`${Nv}${e}`}function Qv(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 Ts(e){return e.clientHeight>0&&e.scrollHeight>0}function bl(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function wl(e,t=qv){return bl(e)<t}function Zv(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:Lr(t)??"",offset:t.getBoundingClientRect().top-i}}function Xv(e,t){const i=e.getBoundingClientRect();let s,r=Number.NEGATIVE_INFINITY,o,n=Number.POSITIVE_INFINITY;for(const a of t){if(Lr(a)===void 0)continue;const c=a.getBoundingClientRect();if(c.bottom<=c.top||c.bottom<i.top||c.top>i.bottom)continue;const p=c.top-i.top;p<=0&&p>=r?(s=a,r=p):p>0&&p<n&&(o=a,n=p)}return s??o}function In(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const r=s.getBoundingClientRect();return r.bottom>=i.top&&r.top<=i.bottom})}function Yv(e,t){return e.find(i=>Lr(i)===t)}function Lr(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}async function jr(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}const eb=E`
818
823
  :host { position: relative; z-index: 0; display: flex; flex: 1 1 0; flex-direction: column; min-height: 0; max-height: 100%; overflow: hidden; contain: size layout; color: var(--pi-text); font: 14px system-ui, sans-serif; }
819
824
  .chat-wrap { position: relative; flex: 1 1 0; min-height: 0; max-height: 100%; overflow: hidden; }
820
825
  .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
@@ -903,7 +908,7 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
903
908
  pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
904
909
  .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
905
910
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
906
- `;var Jv=Object.defineProperty,Qv=Object.getOwnPropertyDescriptor,Fr=(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&&Jv(t,i,r),r};let Vt=class extends A{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=$n(this.positionPercent),t=$n(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return l`
911
+ `;var tb=Object.defineProperty,ib=Object.getOwnPropertyDescriptor,Fr=(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 Vt=class extends A{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=Rn(this.positionPercent),t=Rn(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return l`
907
912
  <div
908
913
  class="meter"
909
914
  style=${`--position:${e.toFixed(2)}%;`}
@@ -926,12 +931,12 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
926
931
  .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); }
927
932
  .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)); }
928
933
  .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%); }
929
- `;Fr([d({type:Number})],Vt.prototype,"positionPercent",2);Fr([d({type:Number})],Vt.prototype,"loadedPercent",2);Vt=Fr([W("conversation-meter")],Vt);function $n(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class Ys extends _r{constructor(t){if(super(t),this.it=z,t.type!==Wr.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===z||t==null)return this._t=void 0,this.it=t;if(t===Ze)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:[]}}}Ys.directiveName="unsafeHTML",Ys.resultType=1;const Zv=Or(Ys);function Ur(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ht=Ur();function ml(e){ht=e}var ot={exec:()=>null};function vt(e){let t=[];return i=>{let s=Math.max(0,Math.min(3,i-1)),r=t[s];return r||(r=e(s),t[s]=r),r}}function T(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(r,o)=>{let n=typeof o=="string"?o:o.source;return n=n.replace(X.caret,"$1"),i=i.replace(r,n),s},getRegex:()=>new RegExp(i,t)};return s}var Xv=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),X={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:vt(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:vt(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:vt(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:vt(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:vt(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:vt(e=>new RegExp(`^ {0,${e}}>`))},Yv=/^(?:[ \t]*(?:\n|$))+/,eb=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,tb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Yt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ib=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,zr=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,vl=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,bl=T(vl).replace(/bull/g,zr).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),sb=T(vl).replace(/bull/g,zr).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Br=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,rb=/^[^\n]+/,Nr=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,ob=T(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Nr).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),nb=T(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,zr).getRegex(),rs="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",Hr=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ab=T("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Hr).replace("tag",rs).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),wl=T(Br).replace("hr",Yt).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",rs).getRegex(),lb=T(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",wl).getRegex(),qr={blockquote:lb,code:eb,def:ob,fences:tb,heading:ib,hr:Yt,html:ab,lheading:bl,list:nb,newline:Yv,paragraph:wl,table:ot,text:rb},Pn=T("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Yt).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",rs).getRegex(),cb={...qr,lheading:sb,table:Pn,paragraph:T(Br).replace("hr",Yt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Pn).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",rs).getRegex()},db={...qr,html:T(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Hr).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:ot,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:T(Br).replace("hr",Yt).replace("heading",` *#{1,6} *[^
930
- ]`).replace("lheading",bl).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},pb=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,hb=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,yl=/^( {2,}|\\)\n(?!\s*$)/,ub=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Rt=/[\p{P}\p{S}]/u,os=/[\s\p{P}\p{S}]/u,Kr=/[^\s\p{P}\p{S}]/u,fb=T(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,os).getRegex(),xl=/(?!~)[\p{P}\p{S}]/u,gb=/(?!~)[\s\p{P}\p{S}]/u,mb=/(?:[^\s\p{P}\p{S}]|~)/u,vb=T(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Xv?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Sl=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,bb=T(Sl,"u").replace(/punct/g,Rt).getRegex(),wb=T(Sl,"u").replace(/punct/g,xl).getRegex(),kl="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",yb=T(kl,"gu").replace(/notPunctSpace/g,Kr).replace(/punctSpace/g,os).replace(/punct/g,Rt).getRegex(),xb=T(kl,"gu").replace(/notPunctSpace/g,mb).replace(/punctSpace/g,gb).replace(/punct/g,xl).getRegex(),Sb=T("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Kr).replace(/punctSpace/g,os).replace(/punct/g,Rt).getRegex(),kb=T(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Rt).getRegex(),$b="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Pb=T($b,"gu").replace(/notPunctSpace/g,Kr).replace(/punctSpace/g,os).replace(/punct/g,Rt).getRegex(),Cb=T(/\\(punct)/,"gu").replace(/punct/g,Rt).getRegex(),Rb=T(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Ib=T(Hr).replace("(?:-->|$)","-->").getRegex(),Ab=T("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Ib).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Fi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Tb=T(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Fi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),$l=T(/^!?\[(label)\]\[(ref)\]/).replace("label",Fi).replace("ref",Nr).getRegex(),Pl=T(/^!?\[(ref)\](?:\[\])?/).replace("ref",Nr).getRegex(),Mb=T("reflink|nolink(?!\\()","g").replace("reflink",$l).replace("nolink",Pl).getRegex(),Cn=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Vr={_backpedal:ot,anyPunctuation:Cb,autolink:Rb,blockSkip:vb,br:yl,code:hb,del:ot,delLDelim:ot,delRDelim:ot,emStrongLDelim:bb,emStrongRDelimAst:yb,emStrongRDelimUnd:Sb,escape:pb,link:Tb,nolink:Pl,punctuation:fb,reflink:$l,reflinkSearch:Mb,tag:Ab,text:ub,url:ot},Eb={...Vr,link:T(/^!?\[(label)\]\((.*?)\)/).replace("label",Fi).getRegex(),reflink:T(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Fi).getRegex()},er={...Vr,emStrongRDelimAst:xb,emStrongLDelim:wb,delLDelim:kb,delRDelim:Pb,url:T(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Cn).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:T(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Cn).getRegex()},Db={...er,br:T(yl).replace("{2,}","*").getRegex(),text:T(er.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ai={normal:qr,gfm:cb,pedantic:db},Lt={normal:Vr,gfm:er,breaks:Db,pedantic:Eb},Wb={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Rn=e=>Wb[e];function We(e,t){if(t){if(X.escapeTest.test(e))return e.replace(X.escapeReplace,Rn)}else if(X.escapeTestNoEncode.test(e))return e.replace(X.escapeReplaceNoEncode,Rn);return e}function In(e){try{e=encodeURI(e).replace(X.percentDecode,"%")}catch{return null}return e}function An(e,t){let i=e.replace(X.findPipe,(o,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(X.splitPipe),r=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;r<s.length;r++)s[r]=s[r].trim().replace(X.slashPipe,"|");return s}function Ge(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 Tn(e){let t=e.split(`
934
+ `;Fr([d({type:Number})],Vt.prototype,"positionPercent",2);Fr([d({type:Number})],Vt.prototype,"loadedPercent",2);Vt=Fr([W("conversation-meter")],Vt);function Rn(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class Ys extends _r{constructor(t){if(super(t),this.it=z,t.type!==Wr.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===z||t==null)return this._t=void 0,this.it=t;if(t===Ze)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:[]}}}Ys.directiveName="unsafeHTML",Ys.resultType=1;const sb=Or(Ys);function Ur(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ht=Ur();function yl(e){ht=e}var ot={exec:()=>null};function vt(e){let t=[];return i=>{let s=Math.max(0,Math.min(3,i-1)),r=t[s];return r||(r=e(s),t[s]=r),r}}function T(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(r,o)=>{let n=typeof o=="string"?o:o.source;return n=n.replace(X.caret,"$1"),i=i.replace(r,n),s},getRegex:()=>new RegExp(i,t)};return s}var rb=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),X={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:vt(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:vt(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:vt(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:vt(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:vt(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:vt(e=>new RegExp(`^ {0,${e}}>`))},ob=/^(?:[ \t]*(?:\n|$))+/,nb=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,ab=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Yt=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,lb=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,zr=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,xl=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Sl=T(xl).replace(/bull/g,zr).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),cb=T(xl).replace(/bull/g,zr).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Br=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,db=/^[^\n]+/,Nr=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,pb=T(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Nr).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),hb=T(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,zr).getRegex(),rs="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",Hr=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,ub=T("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Hr).replace("tag",rs).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),kl=T(Br).replace("hr",Yt).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",rs).getRegex(),fb=T(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",kl).getRegex(),qr={blockquote:fb,code:nb,def:pb,fences:ab,heading:lb,hr:Yt,html:ub,lheading:Sl,list:hb,newline:ob,paragraph:kl,table:ot,text:db},An=T("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Yt).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",rs).getRegex(),gb={...qr,lheading:cb,table:An,paragraph:T(Br).replace("hr",Yt).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",An).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",rs).getRegex()},mb={...qr,html:T(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Hr).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:ot,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:T(Br).replace("hr",Yt).replace("heading",` *#{1,6} *[^
935
+ ]`).replace("lheading",Sl).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},vb=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,bb=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,$l=/^( {2,}|\\)\n(?!\s*$)/,wb=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,It=/[\p{P}\p{S}]/u,os=/[\s\p{P}\p{S}]/u,Kr=/[^\s\p{P}\p{S}]/u,yb=T(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,os).getRegex(),Pl=/(?!~)[\p{P}\p{S}]/u,xb=/(?!~)[\s\p{P}\p{S}]/u,Sb=/(?:[^\s\p{P}\p{S}]|~)/u,kb=T(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",rb?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Cl=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,$b=T(Cl,"u").replace(/punct/g,It).getRegex(),Pb=T(Cl,"u").replace(/punct/g,Pl).getRegex(),Il="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Cb=T(Il,"gu").replace(/notPunctSpace/g,Kr).replace(/punctSpace/g,os).replace(/punct/g,It).getRegex(),Ib=T(Il,"gu").replace(/notPunctSpace/g,Sb).replace(/punctSpace/g,xb).replace(/punct/g,Pl).getRegex(),Rb=T("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Kr).replace(/punctSpace/g,os).replace(/punct/g,It).getRegex(),Ab=T(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,It).getRegex(),Tb="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Mb=T(Tb,"gu").replace(/notPunctSpace/g,Kr).replace(/punctSpace/g,os).replace(/punct/g,It).getRegex(),Eb=T(/\\(punct)/,"gu").replace(/punct/g,It).getRegex(),Db=T(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Wb=T(Hr).replace("(?:-->|$)","-->").getRegex(),Ob=T("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Wb).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Fi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,_b=T(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Fi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Rl=T(/^!?\[(label)\]\[(ref)\]/).replace("label",Fi).replace("ref",Nr).getRegex(),Al=T(/^!?\[(ref)\](?:\[\])?/).replace("ref",Nr).getRegex(),Lb=T("reflink|nolink(?!\\()","g").replace("reflink",Rl).replace("nolink",Al).getRegex(),Tn=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Vr={_backpedal:ot,anyPunctuation:Eb,autolink:Db,blockSkip:kb,br:$l,code:bb,del:ot,delLDelim:ot,delRDelim:ot,emStrongLDelim:$b,emStrongRDelimAst:Cb,emStrongRDelimUnd:Rb,escape:vb,link:_b,nolink:Al,punctuation:yb,reflink:Rl,reflinkSearch:Lb,tag:Ob,text:wb,url:ot},jb={...Vr,link:T(/^!?\[(label)\]\((.*?)\)/).replace("label",Fi).getRegex(),reflink:T(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Fi).getRegex()},er={...Vr,emStrongRDelimAst:Ib,emStrongLDelim:Pb,delLDelim:Ab,delRDelim:Mb,url:T(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Tn).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:T(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Tn).getRegex()},Fb={...er,br:T($l).replace("{2,}","*").getRegex(),text:T(er.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ai={normal:qr,gfm:gb,pedantic:mb},Lt={normal:Vr,gfm:er,breaks:Fb,pedantic:jb},Ub={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Mn=e=>Ub[e];function We(e,t){if(t){if(X.escapeTest.test(e))return e.replace(X.escapeReplace,Mn)}else if(X.escapeTestNoEncode.test(e))return e.replace(X.escapeReplaceNoEncode,Mn);return e}function En(e){try{e=encodeURI(e).replace(X.percentDecode,"%")}catch{return null}return e}function Dn(e,t){let i=e.replace(X.findPipe,(o,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(X.splitPipe),r=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;r<s.length;r++)s[r]=s[r].trim().replace(X.slashPipe,"|");return s}function Ge(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 Wn(e){let t=e.split(`
931
936
  `),i=t.length-1;for(;i>=0&&X.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
932
- `)}function Ob(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 _b(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 Mn(e,t,i,s,r){let o=t.href,n=t.title||null,a=e[1].replace(r.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:o,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function Lb(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(`
937
+ `)}function zb(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 Bb(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 On(e,t,i,s,r){let o=t.href,n=t.title||null,a=e[1].replace(r.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:o,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function Nb(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(`
933
938
  `).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(`
934
- `)}var Ui=class{options;rules;lexer;constructor(e){this.options=e||ht}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:Tn(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=Lb(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=Ge(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Ge(t[0],`
939
+ `)}var Ui=class{options;rules;lexer;constructor(e){this.options=e||ht}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:Wn(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=Nb(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=Ge(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Ge(t[0],`
935
940
  `),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:Ge(t[0],`
936
941
  `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Ge(t[0],`
937
942
  `).split(`
@@ -941,22 +946,22 @@ Permanent deletion only applies to archived sessions and cannot be undone.`}func
941
946
  ${p}`:p,r=r?`${r}
942
947
  ${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 b=g,P=b.raw+`
943
948
  `+i.join(`
944
- `),R=this.blockquote(P);o[o.length-1]=R,s=s.substring(0,s.length-b.raw.length)+R.raw,r=r.substring(0,r.length-b.text.length)+R.text;break}else if(g?.type==="list"){let b=g,P=b.raw+`
949
+ `),I=this.blockquote(P);o[o.length-1]=I,s=s.substring(0,s.length-b.raw.length)+I.raw,r=r.substring(0,r.length-b.text.length)+I.text;break}else if(g?.type==="list"){let b=g,P=b.raw+`
945
950
  `+i.join(`
946
- `),R=this.list(P);o[o.length-1]=R,s=s.substring(0,s.length-g.raw.length)+R.raw,r=r.substring(0,r.length-b.raw.length)+R.raw,i=P.substring(o.at(-1).raw.length).split(`
947
- `);continue}}return{type:"blockquote",raw:s,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,r={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let o=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=_b(t[2].split(`
951
+ `),I=this.list(P);o[o.length-1]=I,s=s.substring(0,s.length-g.raw.length)+I.raw,r=r.substring(0,r.length-b.raw.length)+I.raw,i=P.substring(o.at(-1).raw.length).split(`
952
+ `);continue}}return{type:"blockquote",raw:s,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,r={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let o=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=Bb(t[2].split(`
948
953
  `,1)[0],t[1].length),g=e.split(`
949
954
  `,1)[0],b=!h.trim(),P=0;if(this.options.pedantic?(P=2,u=h.trimStart()):b?P=t[1].length+1:(P=h.search(this.rules.other.nonSpaceChar),P=P>4?1:P,u=h.slice(P),P+=t[1].length),b&&this.rules.other.blankLine.test(g)&&(p+=g+`
950
- `,e=e.substring(g.length+1),c=!0),!c){let R=this.rules.other.nextBulletRegex(P),V=this.rules.other.hrRegex(P),Ve=this.rules.other.fencesBeginRegex(P),Zr=this.rules.other.headingBeginRegex(P),Ul=this.rules.other.htmlBeginRegex(P),zl=this.rules.other.blockquoteBeginRegex(P);for(;e;){let ps=e.split(`
951
- `,1)[0],It;if(g=ps,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),It=g):It=g.replace(this.rules.other.tabCharGlobal," "),Ve.test(g)||Zr.test(g)||Ul.test(g)||zl.test(g)||R.test(g)||V.test(g))break;if(It.search(this.rules.other.nonSpaceChar)>=P||!g.trim())u+=`
952
- `+It.slice(P);else{if(b||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||Ve.test(h)||Zr.test(h)||V.test(h))break;u+=`
955
+ `,e=e.substring(g.length+1),c=!0),!c){let I=this.rules.other.nextBulletRegex(P),V=this.rules.other.hrRegex(P),Ve=this.rules.other.fencesBeginRegex(P),Zr=this.rules.other.headingBeginRegex(P),Hl=this.rules.other.htmlBeginRegex(P),ql=this.rules.other.blockquoteBeginRegex(P);for(;e;){let ps=e.split(`
956
+ `,1)[0],Rt;if(g=ps,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),Rt=g):Rt=g.replace(this.rules.other.tabCharGlobal," "),Ve.test(g)||Zr.test(g)||Hl.test(g)||ql.test(g)||I.test(g)||V.test(g))break;if(Rt.search(this.rules.other.nonSpaceChar)>=P||!g.trim())u+=`
957
+ `+Rt.slice(P);else{if(b||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||Ve.test(h)||Zr.test(h)||V.test(h))break;u+=`
953
958
  `+g}b=!g.trim(),p+=ps+`
954
- `,e=e.substring(ps.length+1),h=It.slice(P)}}r.loose||(n?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),r.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),r.raw+=p}let a=r.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let c of r.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let p=c.tokens[0];if(c.task&&(p?.type==="text"||p?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=h.checked,r.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=h.raw+c.tokens[0].raw,c.tokens[0].text=h.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(h)):c.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):c.tokens.unshift(h)}}else c.task&&(c.task=!1);if(!r.loose){let u=c.tokens.filter(g=>g.type==="space"),h=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));r.loose=h}}if(r.loose)for(let c of r.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Tn(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:Ge(t[0],`
955
- `),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=An(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
959
+ `,e=e.substring(ps.length+1),h=Rt.slice(P)}}r.loose||(n?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),r.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),r.raw+=p}let a=r.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let c of r.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let p=c.tokens[0];if(c.task&&(p?.type==="text"||p?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=h.checked,r.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=h.raw+c.tokens[0].raw,c.tokens[0].text=h.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(h)):c.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):c.tokens.unshift(h)}}else c.task&&(c.task=!1);if(!r.loose){let u=c.tokens.filter(g=>g.type==="space"),h=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));r.loose=h}}if(r.loose)for(let c of r.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Wn(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:Ge(t[0],`
960
+ `),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=Dn(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
956
961
  `):[],o={type:"table",raw:Ge(t[0],`
957
- `),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(An(n,o.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:Ge(t[0],`
962
+ `),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(Dn(n,o.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:Ge(t[0],`
958
963
  `),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)===`
959
- `?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=Ge(i.slice(0,-1),"\\");if((i.length-o.length)%2===0)return}else{let o=Ob(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)),Mn(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 Mn(i,r,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&i.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!i||this.rules.inline.punctuation.exec(i))){let r=[...s[0]].length-1,o,n,a=r,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+r);(s=p.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(n=[...o].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&r%3&&!((r+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let u=[...s[0]][0].length,h=e.slice(0,r+s.index+u+n);if(Math.min(r,n)%2){let b=h.slice(1,-1);return{type:"em",raw:h,text:b,tokens:this.lexer.inlineTokens(b)}}let g=h.slice(2,-2);return{type:"strong",raw:h,text:g,tokens:this.lexer.inlineTokens(g)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(i),r=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&r&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!i||this.rules.inline.punctuation.exec(i))){let r=[...s[0]].length-1,o,n,a=r,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+r);(s=c.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(n=[...o].length,n!==r))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,u=e.slice(0,r+s.index+p+n),h=u.slice(r,-r);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,s;return t[2]==="@"?(i=t[1],s="mailto:"+i):(i=t[1],s=i),{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:i}}}},Ie=class tr{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||ht,this.options.tokenizer=this.options.tokenizer||new Ui,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let i={other:X,block:ai.normal,inline:Lt.normal};this.options.pedantic?(i.block=ai.pedantic,i.inline=Lt.pedantic):this.options.gfm&&(i.block=ai.gfm,this.options.breaks?i.inline=Lt.breaks:i.inline=Lt.gfm),this.tokenizer.rules=i}static get rules(){return{block:ai,inline:Lt}}static lex(t,i){return new tr(i).lex(t)}static lexInline(t,i){return new tr(i).inlineTokens(t)}lex(t){t=t.replace(X.carriageReturn,`
964
+ `?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=Ge(i.slice(0,-1),"\\");if((i.length-o.length)%2===0)return}else{let o=zb(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)),On(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 On(i,r,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&i.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!i||this.rules.inline.punctuation.exec(i))){let r=[...s[0]].length-1,o,n,a=r,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+r);(s=p.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(n=[...o].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&r%3&&!((r+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let u=[...s[0]][0].length,h=e.slice(0,r+s.index+u+n);if(Math.min(r,n)%2){let b=h.slice(1,-1);return{type:"em",raw:h,text:b,tokens:this.lexer.inlineTokens(b)}}let g=h.slice(2,-2);return{type:"strong",raw:h,text:g,tokens:this.lexer.inlineTokens(g)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(i),r=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&r&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!i||this.rules.inline.punctuation.exec(i))){let r=[...s[0]].length-1,o,n,a=r,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+r);(s=c.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(n=[...o].length,n!==r))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,u=e.slice(0,r+s.index+p+n),h=u.slice(r,-r);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,s;return t[2]==="@"?(i=t[1],s="mailto:"+i):(i=t[1],s=i),{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:i}}}},Re=class tr{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||ht,this.options.tokenizer=this.options.tokenizer||new Ui,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let i={other:X,block:ai.normal,inline:Lt.normal};this.options.pedantic?(i.block=ai.pedantic,i.inline=Lt.pedantic):this.options.gfm&&(i.block=ai.gfm,this.options.breaks?i.inline=Lt.breaks:i.inline=Lt.gfm),this.tokenizer.rules=i}static get rules(){return{block:ai,inline:Lt}}static lex(t,i){return new tr(i).lex(t)}static lexInline(t,i){return new tr(i).inlineTokens(t)}lex(t){t=t.replace(X.carriageReturn,`
960
965
  `),this.blockTokens(t,this.tokens);for(let i=0;i<this.inlineQueue.length;i++){let s=this.inlineQueue[i];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,i=[],s=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(X.tabCharGlobal," ").replace(X.spaceLine,""));let r=1/0;for(;t;){if(t.length<r)r=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},t,i))?(t=t.substring(o.raw.length),i.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let a=i.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
961
966
  `: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(`
962
967
  `)?"":`
@@ -988,8 +993,8 @@ ${this.parser.parse(e)}</blockquote>
988
993
  `}tablerow({text:e}){return`<tr>
989
994
  ${e}</tr>
990
995
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
991
- `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${We(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:i}){let s=this.parser.parseInline(i),r=In(e);if(r===null)return s;e=r;let o='<a href="'+e+'"';return t&&(o+=' title="'+We(t)+'"'),o+=">"+s+"</a>",o}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let r=In(e);if(r===null)return We(i);e=r;let o=`<img src="${e}" alt="${We(i)}"`;return t&&(o+=` title="${We(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:We(e.text)}},Gr=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Ae=class ir{options;renderer;textRenderer;constructor(t){this.options=t||ht,this.options.renderer=this.options.renderer||new zi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Gr}static parse(t,i){return new ir(i).parse(t)}static parseInline(t,i){return new ir(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}},Ut=class{options;block;constructor(e){this.options=e||ht}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Ie.lex:Ie.lexInline}provideParser(e=this.block){return e?Ae.parse:Ae.parseInline}},jb=class{defaults=Ur();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ae;Renderer=zi;TextRenderer=Gr;Lexer=Ie;Tokenizer=Ui;Hooks=Ut;constructor(...e){this.use(...e)}walkTokens(e,t){let i=[];for(let s of e)switch(i=i.concat(t.call(this,s)),s.type){case"table":{let r=s;for(let o of r.header)i=i.concat(this.walkTokens(o.tokens,t));for(let o of r.rows)for(let n of o)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let r=s;i=i.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let n=r[o].flat(1/0);i=i.concat(this.walkTokens(n,t))}):r.tokens&&(i=i.concat(this.walkTokens(r.tokens,t)))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let s={...i};if(s.async=this.defaults.async||s.async||!1,i.extensions&&(i.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...n){let a=r.renderer.apply(this,n);return a===!1&&(a=o.apply(this,n)),a}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),i.renderer){let r=this.defaults.renderer||new zi(this.defaults);for(let o in i.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let n=o,a=i.renderer[n],c=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u||""}}s.renderer=r}if(i.tokenizer){let r=this.defaults.tokenizer||new Ui(this.defaults);for(let o in i.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let n=o,a=i.tokenizer[n],c=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u}}s.tokenizer=r}if(i.hooks){let r=this.defaults.hooks||new Ut;for(let o in i.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let n=o,a=i.hooks[n],c=r[n];Ut.passThroughHooks.has(o)?r[n]=p=>{if(this.defaults.async&&Ut.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await a.call(r,p);return c.call(r,h)})();let u=a.call(r,p);return c.call(r,u)}:r[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(r,p);return h===!1&&(h=await c.apply(r,p)),h})();let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u}}s.hooks=r}if(i.walkTokens){let r=this.defaults.walkTokens,o=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(o.call(this,n)),r&&(a=a.concat(r.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ie.lex(e,t??this.defaults)}parser(e,t){return Ae.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},r={...this.defaults,...s},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let n=r.hooks?await r.hooks.preprocess(t):t,a=await(r.hooks?await r.hooks.provideLexer(e):e?Ie.lex:Ie.lexInline)(n,r),c=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(c,r.walkTokens));let p=await(r.hooks?await r.hooks.provideParser(e):e?Ae.parse:Ae.parseInline)(c,r);return r.hooks?await r.hooks.postprocess(p):p})().catch(o);try{r.hooks&&(t=r.hooks.preprocess(t));let n=(r.hooks?r.hooks.provideLexer(e):e?Ie.lex:Ie.lexInline)(t,r);r.hooks&&(n=r.hooks.processAllTokens(n)),r.walkTokens&&this.walkTokens(n,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(e):e?Ae.parse:Ae.parseInline)(n,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(n){return o(n)}}}onError(e,t){return i=>{if(i.message+=`
992
- Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+We(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},dt=new jb;function O(e,t){return dt.parse(e,t)}O.options=O.setOptions=function(e){return dt.setOptions(e),O.defaults=dt.defaults,ml(O.defaults),O};O.getDefaults=Ur;O.defaults=ht;O.use=function(...e){return dt.use(...e),O.defaults=dt.defaults,ml(O.defaults),O};O.walkTokens=function(e,t){return dt.walkTokens(e,t)};O.parseInline=dt.parseInline;O.Parser=Ae;O.parser=Ae.parse;O.Renderer=zi;O.TextRenderer=Gr;O.Lexer=Ie;O.lexer=Ie.lex;O.Tokenizer=Ui;O.Hooks=Ut;O.parse=O;O.options;O.setOptions;O.use;O.walkTokens;O.parseInline;Ae.parse;Ie.lex;const Cl=new O.Renderer;Cl.html=({text:e})=>zb(e);const Fb=300,jt=new Map;function Ub(e){const t=jt.get(e);if(t!==void 0)return t;const i=O.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:Cl}),s=Bb(i);if(jt.set(e,s),jt.size>Fb){const r=jt.keys().next().value;r!==void 0&&jt.delete(r)}return s}function zb(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Bb(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")&&!Nb(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function Nb(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var Hb=Object.defineProperty,qb=Object.getOwnPropertyDescriptor,Rl=(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};const Kb=E`
996
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${We(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:i}){let s=this.parser.parseInline(i),r=En(e);if(r===null)return s;e=r;let o='<a href="'+e+'"';return t&&(o+=' title="'+We(t)+'"'),o+=">"+s+"</a>",o}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let r=En(e);if(r===null)return We(i);e=r;let o=`<img src="${e}" alt="${We(i)}"`;return t&&(o+=` title="${We(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:We(e.text)}},Gr=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Ae=class ir{options;renderer;textRenderer;constructor(t){this.options=t||ht,this.options.renderer=this.options.renderer||new zi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Gr}static parse(t,i){return new ir(i).parse(t)}static parseInline(t,i){return new ir(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}},Ut=class{options;block;constructor(e){this.options=e||ht}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Re.lex:Re.lexInline}provideParser(e=this.block){return e?Ae.parse:Ae.parseInline}},Hb=class{defaults=Ur();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ae;Renderer=zi;TextRenderer=Gr;Lexer=Re;Tokenizer=Ui;Hooks=Ut;constructor(...e){this.use(...e)}walkTokens(e,t){let i=[];for(let s of e)switch(i=i.concat(t.call(this,s)),s.type){case"table":{let r=s;for(let o of r.header)i=i.concat(this.walkTokens(o.tokens,t));for(let o of r.rows)for(let n of o)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let r=s;i=i.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let n=r[o].flat(1/0);i=i.concat(this.walkTokens(n,t))}):r.tokens&&(i=i.concat(this.walkTokens(r.tokens,t)))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let s={...i};if(s.async=this.defaults.async||s.async||!1,i.extensions&&(i.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...n){let a=r.renderer.apply(this,n);return a===!1&&(a=o.apply(this,n)),a}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),i.renderer){let r=this.defaults.renderer||new zi(this.defaults);for(let o in i.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let n=o,a=i.renderer[n],c=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u||""}}s.renderer=r}if(i.tokenizer){let r=this.defaults.tokenizer||new Ui(this.defaults);for(let o in i.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let n=o,a=i.tokenizer[n],c=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u}}s.tokenizer=r}if(i.hooks){let r=this.defaults.hooks||new Ut;for(let o in i.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let n=o,a=i.hooks[n],c=r[n];Ut.passThroughHooks.has(o)?r[n]=p=>{if(this.defaults.async&&Ut.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await a.call(r,p);return c.call(r,h)})();let u=a.call(r,p);return c.call(r,u)}:r[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(r,p);return h===!1&&(h=await c.apply(r,p)),h})();let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u}}s.hooks=r}if(i.walkTokens){let r=this.defaults.walkTokens,o=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(o.call(this,n)),r&&(a=a.concat(r.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Re.lex(e,t??this.defaults)}parser(e,t){return Ae.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},r={...this.defaults,...s},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let n=r.hooks?await r.hooks.preprocess(t):t,a=await(r.hooks?await r.hooks.provideLexer(e):e?Re.lex:Re.lexInline)(n,r),c=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(c,r.walkTokens));let p=await(r.hooks?await r.hooks.provideParser(e):e?Ae.parse:Ae.parseInline)(c,r);return r.hooks?await r.hooks.postprocess(p):p})().catch(o);try{r.hooks&&(t=r.hooks.preprocess(t));let n=(r.hooks?r.hooks.provideLexer(e):e?Re.lex:Re.lexInline)(t,r);r.hooks&&(n=r.hooks.processAllTokens(n)),r.walkTokens&&this.walkTokens(n,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(e):e?Ae.parse:Ae.parseInline)(n,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(n){return o(n)}}}onError(e,t){return i=>{if(i.message+=`
997
+ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+We(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},dt=new Hb;function O(e,t){return dt.parse(e,t)}O.options=O.setOptions=function(e){return dt.setOptions(e),O.defaults=dt.defaults,yl(O.defaults),O};O.getDefaults=Ur;O.defaults=ht;O.use=function(...e){return dt.use(...e),O.defaults=dt.defaults,yl(O.defaults),O};O.walkTokens=function(e,t){return dt.walkTokens(e,t)};O.parseInline=dt.parseInline;O.Parser=Ae;O.parser=Ae.parse;O.Renderer=zi;O.TextRenderer=Gr;O.Lexer=Re;O.lexer=Re.lex;O.Tokenizer=Ui;O.Hooks=Ut;O.parse=O;O.options;O.setOptions;O.use;O.walkTokens;O.parseInline;Ae.parse;Re.lex;const Tl=new O.Renderer;Tl.html=({text:e})=>Vb(e);const qb=300,jt=new Map;function Kb(e){const t=jt.get(e);if(t!==void 0)return t;const i=O.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:Tl}),s=Gb(i);if(jt.set(e,s),jt.size>qb){const r=jt.keys().next().value;r!==void 0&&jt.delete(r)}return s}function Vb(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Gb(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")&&!Jb(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function Jb(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var Qb=Object.defineProperty,Zb=Object.getOwnPropertyDescriptor,Ml=(e,t,i,s)=>{for(var r=s>1?void 0:s?Zb(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&&Qb(t,i,r),r};const Xb=E`
993
998
  :host { display: block; }
994
999
  .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
995
1000
  p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
@@ -1014,18 +1019,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1014
1019
  table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
1015
1020
  th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
1016
1021
  th { background: var(--pi-surface); }
1017
- `;let Bi=class extends A{constructor(){super(...arguments),this.text="",this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;const t=e.target.closest(".code-copy-button");if(!(t instanceof HTMLButtonElement))return;const i=t.closest(".code-block-wrapper");if(!(i instanceof HTMLElement))return;const s=i.querySelector("pre code");s instanceof HTMLElement&&this.copyCode(s.textContent,t)}}render(){return l`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${Zv(Ub(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 jr(e);this.setCopyButtonState(t,i?"copied":"failed"),window.setTimeout(()=>{this.setCopyButtonState(t,"idle")},1200)}setCopyButtonState(e,t){const i=e.querySelector("span");i!==null&&(i.textContent=t==="copied"?"✓":"⧉");const s=t==="copied"?"已复制代码块":t==="failed"?"复制代码块失败":"复制代码块";e.title=s,e.setAttribute("aria-label",s)}};Bi.styles=Kb;Rl([d()],Bi.prototype,"text",2);Bi=Rl([W("formatted-text")],Bi);var Vb=Object.defineProperty,Gb=Object.getOwnPropertyDescriptor,ei=(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&&Vb(t,i,r),r};const En=180;let pt=class extends A{constructor(){super(...arguments),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){const e=this.execution;if(e===void 0)return null;const t=e.toolName==="edit",i=Jb(e.args),s=Qb(e.details),r=e.preview,o=s??r?.diff,n=o===void 0?void 0:Zb(o),a=s!==void 0&&r?.diff!==void 0&&s!==r.diff,c=e.status==="error"?e.resultText:r?.error,p=o===void 0?e.resultText:void 0;return l`
1022
+ `;let Bi=class extends A{constructor(){super(...arguments),this.text="",this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;const t=e.target.closest(".code-copy-button");if(!(t instanceof HTMLButtonElement))return;const i=t.closest(".code-block-wrapper");if(!(i instanceof HTMLElement))return;const s=i.querySelector("pre code");s instanceof HTMLElement&&this.copyCode(s.textContent,t)}}render(){return l`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${sb(Kb(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 jr(e);this.setCopyButtonState(t,i?"copied":"failed"),window.setTimeout(()=>{this.setCopyButtonState(t,"idle")},1200)}setCopyButtonState(e,t){const i=e.querySelector("span");i!==null&&(i.textContent=t==="copied"?"✓":"⧉");const s=t==="copied"?"已复制代码块":t==="failed"?"复制代码块失败":"复制代码块";e.title=s,e.setAttribute("aria-label",s)}};Bi.styles=Xb;Ml([d()],Bi.prototype,"text",2);Bi=Ml([W("formatted-text")],Bi);var Yb=Object.defineProperty,ew=Object.getOwnPropertyDescriptor,ei=(e,t,i,s)=>{for(var r=s>1?void 0:s?ew(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&&Yb(t,i,r),r};const _n=180;let pt=class extends A{constructor(){super(...arguments),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){const e=this.execution;if(e===void 0)return null;const t=e.toolName==="edit",i=tw(e.args),s=iw(e.details),r=e.preview,o=s??r?.diff,n=o===void 0?void 0:sw(o),a=s!==void 0&&r?.diff!==void 0&&s!==r.diff,c=e.status==="error"?e.resultText:r?.error,p=o===void 0?e.resultText:void 0;return l`
1018
1023
  <section class=${`tool-card ${e.status}`}>
1019
1024
  <div class="tool-header">
1020
1025
  <div class="tool-title">
1021
- <span class="status-icon" aria-hidden="true">${Yb(e.status)}</span>
1026
+ <span class="status-icon" aria-hidden="true">${ow(e.status)}</span>
1022
1027
  <strong>${e.toolName}</strong>
1023
1028
  ${i===void 0?l`<span class="summary">${e.summary}</span>`:l`<span class="path">${i}</span>`}
1024
1029
  </div>
1025
1030
  <div class="tool-meta">
1026
- ${Dn(e)===void 0?null:l`<span>${Dn(e)}</span>`}
1031
+ ${Ln(e)===void 0?null:l`<span>${Ln(e)}</span>`}
1027
1032
  ${n===void 0?null:l`<span class="diff-stats"><b class="added">+${n.added}</b><span>/</span><b class="removed">-${n.removed}</b></span>`}
1028
- <span class="status-label">${ew(e.status)}</span>
1033
+ <span class="status-label">${nw(e.status)}</span>
1029
1034
  </div>
1030
1035
  </div>
1031
1036
 
@@ -1040,7 +1045,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1040
1045
  <pre>${e}</pre>
1041
1046
  </details>
1042
1047
  `}renderDiffBody(e,t){const i=e.split(`
1043
- `),s=!this.showFullDiff&&i.length>En,r=s?i.slice(0,En):i;return l`
1048
+ `),s=!this.showFullDiff&&i.length>_n,r=s?i.slice(0,_n):i;return l`
1044
1049
  <details class="diff-details" ?open=${this.diffOpen} @toggle=${o=>{this.onDiffToggle(o)}}>
1045
1050
  <summary>
1046
1051
  <span>${t}</span>
@@ -1050,7 +1055,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1050
1055
  <span>${s?`显示 ${String(r.length)} / ${String(i.length)} 行`:"完整 diff"}</span>
1051
1056
  <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"已复制":"复制 diff"}</button>
1052
1057
  </div>
1053
- <pre class="diff" aria-label=${t}><code class="diff-content">${r.map(o=>l`<span class=${Xb(o)}>${o}</span>`)}</code></pre>
1058
+ <pre class="diff" aria-label=${t}><code class="diff-content">${r.map(o=>l`<span class=${rw(o)}>${o}</span>`)}</code></pre>
1054
1059
  ${s?l`
1055
1060
  <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
1056
1061
  显示全部 ${String(i.length)} 行 diff
@@ -1097,19 +1102,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1097
1102
  .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
1098
1103
  .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
1099
1104
  .show-more { justify-self: start; }
1100
- `;ei([d({attribute:!1})],pt.prototype,"execution",2);ei([y()],pt.prototype,"showFullDiff",2);ei([y()],pt.prototype,"copied",2);ei([y()],pt.prototype,"diffOpen",2);pt=ei([W("tool-execution-view")],pt);function Jb(e){return sr(e,"path")??sr(e,"file_path")}function Dn(e){if(e.toolName!=="edit")return;const t=xi(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof xi(e.args,"oldText")=="string"&&typeof xi(e.args,"newText")=="string")return"1 处编辑"}function Qb(e){return sr(e,"diff")}function Zb(e){let t=0,i=0;for(const s of e.split(`
1101
- `))Il(s)?t++:Al(s)&&i++;return{added:t,removed:i}}function Xb(e){return Il(e)?"added":Al(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function Il(e){return e.startsWith("+")&&!e.startsWith("+++")}function Al(e){return e.startsWith("-")&&!e.startsWith("---")}function Yb(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function ew(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function tw(e){return typeof e=="object"&&e!==null}function xi(e,t){return tw(e)?e[t]:void 0}function sr(e,t){const i=xi(e,t);return typeof i=="string"?i:void 0}var iw=Object.defineProperty,sw=Object.getOwnPropertyDescriptor,H=(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&&iw(t,i,r),r};const rw=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),ow=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),Ms=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"],nw={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 Wn(){return Ms[Math.floor(Math.random()*Ms.length)]??Ms[0]}function On(e){return Si(e,0,100)}function Si(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let U=class extends A{constructor(){super(...arguments),this.messages=[],this.sessionId="",this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isReceivingPartialStream=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.disclosures=new wv,this.scrollController=new Nv,this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onPageHide=()=>{this.saveScrollPosition()}}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.onViewportResize),window.addEventListener("pagehide",this.onPageHide),window.visualViewport?.addEventListener("resize",this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),window.removeEventListener("resize",this.onViewportResize),window.removeEventListener("pagehide",this.onPageHide),window.visualViewport?.removeEventListener("resize",this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!="string"||e===""||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has("sessionId")&&(this.savePreviousSessionScrollPosition(e.get("sessionId")),this.prepareSessionUiState()),(e.has("isReceivingPartialStream")||e.has("sessionId")&&this.isReceivingPartialStream)&&this.syncPartialStreamNoticeBody(),e.has("messages")&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){const t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),t!==void 0&&this.restorePrependScrollAnchor(t)}updated(e){e.has("loadingMore")&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has("hasMore")&&!this.hasMore&&(this.loadMoreRequested=!1),e.has("sessionId")&&this.restoreScrollPosition(),!e.has("sessionId")&&e.has("messages")&&this.pinnedToBottom&&this.scrollToBottom(),(e.has("messages")||e.has("messageStart")||e.has("messageTotal")||e.has("hasMore")||e.has("loadingMore"))&&this.scheduleConversationRailUpdate(),(e.has("messages")||e.has("messageStart")||e.has("hasMore")||e.has("loadingMore"))&&this.continuePendingScrollRestore(),(e.has("messages")||e.has("hasMore")||e.has("loadingMore"))&&this.requestLoadMoreIfNeeded()}render(){const e=this.groupedMessages();return l`
1105
+ `;ei([d({attribute:!1})],pt.prototype,"execution",2);ei([y()],pt.prototype,"showFullDiff",2);ei([y()],pt.prototype,"copied",2);ei([y()],pt.prototype,"diffOpen",2);pt=ei([W("tool-execution-view")],pt);function tw(e){return sr(e,"path")??sr(e,"file_path")}function Ln(e){if(e.toolName!=="edit")return;const t=xi(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof xi(e.args,"oldText")=="string"&&typeof xi(e.args,"newText")=="string")return"1 处编辑"}function iw(e){return sr(e,"diff")}function sw(e){let t=0,i=0;for(const s of e.split(`
1106
+ `))El(s)?t++:Dl(s)&&i++;return{added:t,removed:i}}function rw(e){return El(e)?"added":Dl(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function El(e){return e.startsWith("+")&&!e.startsWith("+++")}function Dl(e){return e.startsWith("-")&&!e.startsWith("---")}function ow(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function nw(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function aw(e){return typeof e=="object"&&e!==null}function xi(e,t){return aw(e)?e[t]:void 0}function sr(e,t){const i=xi(e,t);return typeof i=="string"?i:void 0}var lw=Object.defineProperty,cw=Object.getOwnPropertyDescriptor,H=(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&&lw(t,i,r),r};const dw=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),pw=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),Ms=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"],hw={active:"活跃","agent running":"助手运行中","bash complete":"Shell 已完成","bash failed":"Shell 失败","compaction complete":"压缩已完成","compaction failed":"压缩失败",compacting:"正在压缩","duplicate queued message ignored":"已忽略重复排队消息",error:"错误",idle:"空闲","message complete":"消息已完成","message queued":"消息已排队","message queued during compaction":"压缩期间消息已排队","message started":"消息已开始","prompt accepted":"提示已接受",queued:"已排队","receiving response":"正在接收回复","running bash":"Shell 运行中","running tool":"工具运行中","steering queued":"引导已排队",stopped:"已停止","tool complete":"工具已完成","tool failed":"工具失败","turn complete":"回合已完成"};function jn(){return Ms[Math.floor(Math.random()*Ms.length)]??Ms[0]}function Fn(e){return Si(e,0,100)}function Si(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let U=class extends A{constructor(){super(...arguments),this.messages=[],this.sessionId="",this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isReceivingPartialStream=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.disclosures=new Pv,this.scrollController=new Jv,this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onPageHide=()=>{this.saveScrollPosition()}}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.onViewportResize),window.addEventListener("pagehide",this.onPageHide),window.visualViewport?.addEventListener("resize",this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),window.removeEventListener("resize",this.onViewportResize),window.removeEventListener("pagehide",this.onPageHide),window.visualViewport?.removeEventListener("resize",this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!="string"||e===""||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has("sessionId")&&(this.savePreviousSessionScrollPosition(e.get("sessionId")),this.prepareSessionUiState()),(e.has("isReceivingPartialStream")||e.has("sessionId")&&this.isReceivingPartialStream)&&this.syncPartialStreamNoticeBody(),e.has("messages")&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){const t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),t!==void 0&&this.restorePrependScrollAnchor(t)}updated(e){e.has("loadingMore")&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has("hasMore")&&!this.hasMore&&(this.loadMoreRequested=!1),e.has("sessionId")&&this.restoreScrollPosition(),!e.has("sessionId")&&e.has("messages")&&this.pinnedToBottom&&this.scrollToBottom(),(e.has("messages")||e.has("messageStart")||e.has("messageTotal")||e.has("hasMore")||e.has("loadingMore"))&&this.scheduleConversationRailUpdate(),(e.has("messages")||e.has("messageStart")||e.has("hasMore")||e.has("loadingMore"))&&this.continuePendingScrollRestore(),(e.has("messages")||e.has("hasMore")||e.has("loadingMore"))&&this.requestLoadMoreIfNeeded()}render(){const e=this.groupedMessages();return l`
1102
1107
  <div class="chat-wrap">
1103
1108
  ${this.renderConversationRail()}
1104
1109
  <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
1105
1110
  ${this.renderHistoryBoundary()}
1106
- ${mv(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)))}
1111
+ ${Sv(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)))}
1107
1112
  ${this.renderQueuedMessages()}
1108
1113
  ${this.renderSessionActivity()}
1109
1114
  </div>
1110
1115
  ${this.renderActivityDock()}
1111
1116
  </div>
1112
- `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Sv(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){if(this.isSendingPrompt)return l`
1117
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Rv(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){if(this.isSendingPrompt)return l`
1113
1118
  <div class="activity-dock active" aria-live="polite">
1114
1119
  <span class="dot"></span>
1115
1120
  <span class="activity-text">正在发送你的消息…</span>
@@ -1144,7 +1149,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1144
1149
  <span>助手正在总结早前上下文。压缩完成前,新提示会排队等待。</span>
1145
1150
  ${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} 条消息已排队</small>`:null}
1146
1151
  </aside>
1147
- `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Wn():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Wn(),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 Es(e);const i=Es(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?On(this.messages.length/e*100):100;return l`<conversation-meter .positionPercent=${t} .loadedPercent=${i}></conversation-meter>`}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;const t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,i=Si(this.currentConversationIndex??t,0,e-1);return On(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?l`
1152
+ `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?jn():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=jn(),this.partialStreamNoticeBody}activityState(){const e=this.status;return e===void 0?this.activity?.label:e.isCompacting?"compacting":e.isBashRunning?"bash":e.isStreaming?"running":e.pendingMessageCount>0?"queued":"idle"}activityText(e){const t=this.activity;if(t===void 0||e!=="idle"&&t.phase==="idle")return Es(e);const i=Es(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?Fn(this.messages.length/e*100):100;return l`<conversation-meter .positionPercent=${t} .loadedPercent=${i}></conversation-meter>`}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;const t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,i=Si(this.currentConversationIndex??t,0,e-1);return Fn(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?l`
1148
1153
  <div class="history-boundary">
1149
1154
  <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>加载更早的消息</button>
1150
1155
  <span>向上滚动加载更早的消息</span>
@@ -1161,7 +1166,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1161
1166
  <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)}}>
1162
1167
  <summary>
1163
1168
  <b class="label">${s?"实时事件":"事件"}</b>
1164
- <span>${kv(e)}</span>
1169
+ <span>${Av(e)}</span>
1165
1170
  </summary>
1166
1171
  <div class="group-body">
1167
1172
  ${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
@@ -1174,7 +1179,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1174
1179
  </details>
1175
1180
  `}renderScrollMarker(e){return l`<span class="scroll-marker" data-marker-id=${e} aria-hidden="true"></span>`}renderMessageHeader(e,t){const i=this.messageMetaLabel(e),s=this.expandedMetaKey===t;return l`
1176
1181
  <div class="msg-header">
1177
- <b class="label">${_n(e.role)}</b>
1182
+ <b class="label">${Un(e.role)}</b>
1178
1183
  <div class="msg-header-trailing">
1179
1184
  ${this.renderMessageActions(e,t)}
1180
1185
  <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>
@@ -1182,13 +1187,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1182
1187
  </div>
1183
1188
  `}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return l`
1184
1189
  <div class="msg-actions" aria-label="消息操作">
1185
- <button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${_n(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
1190
+ <button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${Un(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
1186
1191
  <span aria-hidden="true">${i?"✓":"⧉"}</span>
1187
1192
  </button>
1188
1193
  </div>
1189
1194
  `}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(`
1190
1195
 
1191
- `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await jr(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const c={short:"无信息",full:"没有可用的 Pi 消息元数据"};return this.messageMetaCache.set(e,c),c}const r=i===void 0?void 0:this.formatTimestamp(i),o=[r?.short,s].filter(c=>c!==void 0&&c!==""),n=[r?.full,s===void 0?void 0:`模型:${s}`].filter(c=>c!==void 0&&c!==""),a={short:o.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:rw.format(t),full:ow.format(t)}}modelLabel(e){const t=e.meta?.model;if(t===void 0)return;const i=t.responseId??t.id;return i===void 0||i===""?t.provider:t.provider!==void 0&&t.provider!==""?`${t.provider}/${i}`:i}renderPart(e,t){return e.type==="text"&&t?.role==="bash"?l`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?l`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="image"?l`<figure class="part chat-image"><img src=${`data:${e.mimeType};base64,${e.data}`} alt="用户上传的图片" loading="lazy"></figure>`:e.type==="thinking"?l`<details class="part"><summary>思考</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
1196
+ `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await jr(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const c={short:"无信息",full:"没有可用的 Pi 消息元数据"};return this.messageMetaCache.set(e,c),c}const r=i===void 0?void 0:this.formatTimestamp(i),o=[r?.short,s].filter(c=>c!==void 0&&c!==""),n=[r?.full,s===void 0?void 0:`模型:${s}`].filter(c=>c!==void 0&&c!==""),a={short:o.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:dw.format(t),full:pw.format(t)}}modelLabel(e){const t=e.meta?.model;if(t===void 0)return;const i=t.responseId??t.id;return i===void 0||i===""?t.provider:t.provider!==void 0&&t.provider!==""?`${t.provider}/${i}`:i}renderPart(e,t){return e.type==="text"&&t?.role==="bash"?l`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?l`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="image"?l`<figure class="part chat-image"><img src=${`data:${e.mimeType};base64,${e.data}`} alt="用户上传的图片" loading="lazy"></figure>`:e.type==="thinking"?l`<details class="part"><summary>思考</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
1192
1197
  <details class="part skill-invocation">
1193
1198
  <summary><b>[技能]</b> ${e.name}</summary>
1194
1199
  <small>${e.location}</small>
@@ -1204,31 +1209,31 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1204
1209
  <summary>${e.isError?"✖":"✓"} ${e.toolName} 结果</summary>
1205
1210
  <formatted-text .text=${e.text}></formatted-text>
1206
1211
  </details>
1207
- `: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&&Wv({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?gl(e):!0}isAtBottom(){const e=this.chat;return e?fl(e)<2:!0}canScrollUp(){const e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;const e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){const e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){const e=this.pendingScrollRestoreSessionId,t=this.pendingScrollRestorePosition;e===void 0||t===void 0||e!==this.sessionId||this.restoreScrollFrame!==void 0||(this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const i=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,i)})}))}handleScrollRestoreResult(e,t){if(this.syncScrollMetrics(),t.status!=="missing"){this.updatePinnedToBottomAfterRestore(t.status),(t.status==="restored"||t.status==="bottom")&&this.cancelPrependRestore(),this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0;return}this.pinnedToBottom=!1,this.pendingScrollRestoreSessionId=e,this.pendingScrollRestorePosition=t.position;const i=this.chat;i===void 0||!this.hasMore||this.loadingMore||(i.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore&&!this.isReceivingPartialStream}updatePinnedToBottomAfterRestore(e){e==="bottom"?this.pinnedToBottom=!0:e==="restored"&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){const e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){const e=this.chat;if(e)return Cv(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(Rv(r,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=r.scrollTop,i+=1,i<Pv){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=Si(i,0,Math.max(0,e-1));return}this.currentConversationIndex=Si(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 kn(e,t)??kn(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll("[data-scroll-anchor-id]"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,i){return i?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return`m:${String(e)}`}groupRenderKey(e){return`g:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}eventAnchorKey(e){return`e:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}};U.styles=Gv;H([d({attribute:!1})],U.prototype,"messages",2);H([d()],U.prototype,"sessionId",2);H([d({type:Number})],U.prototype,"messageStart",2);H([d({type:Number})],U.prototype,"messageEnd",2);H([d({type:Number})],U.prototype,"messageTotal",2);H([d({type:Boolean})],U.prototype,"hasMore",2);H([d({type:Boolean})],U.prototype,"loadingMore",2);H([d({type:Boolean})],U.prototype,"isReceivingPartialStream",2);H([d({type:Boolean})],U.prototype,"isSendingPrompt",2);H([d({type:Boolean})],U.prototype,"isCompacting",2);H([d({type:Number})],U.prototype,"pendingMessageCount",2);H([d({attribute:!1})],U.prototype,"status",2);H([d({attribute:!1})],U.prototype,"activity",2);H([d({attribute:!1})],U.prototype,"onLoadMore",2);H([B(".chat")],U.prototype,"chat",2);H([y()],U.prototype,"pinnedToBottom",2);H([y()],U.prototype,"expandedMetaKey",2);H([y()],U.prototype,"copiedMessageKey",2);H([y()],U.prototype,"currentConversationIndex",2);H([y()],U.prototype,"loadMoreRequested",2);U=H([W("chat-view")],U);function _n(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Es(e){return e==="bash"?"Shell 运行中":e==="running"?"运行中":nw[e]??e}const aw=["image/jpeg","image/png","image/gif","image/webp"],lw=new Set(aw);function Jr(e){return typeof e=="string"&&lw.has(e)}function cw(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 dw="application/octet-stream",pw="读取附件失败。";async function hw(e,t){const i=[];let s;for(const r of e)try{const o=await t(r);i.push(fw(r,o))}catch{s=pw}return{attachments:i,...s===void 0?{}:{error:s}}}function rr(e){return e.kind==="image"&&Jr(e.mimeType)}function or(e){return e.every(t=>rr(t))}function uw(e,t){return or(t)?e:"folder"}function fw(e,t){return Jr(e.type)?{kind:"image",name:Ln(e),mimeType:e.type,data:t,size:e.size}:{kind:"file",name:Ln(e),mimeType:gw(e),data:t,size:e.size}}function gw(e){const t=e.type.trim();return t===""?dw:t}function Ln(e){return e.name!==""?e.name:Jr(e.type)?`pasted-image.${cw(e.type)}`:"pasted-file.bin"}const Tl="pi-web:attachment-delivery";function Ml(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function mw(e=Ml()){try{return e?.getItem(Tl)==="folder"?"folder":"inline"}catch{return"inline"}}function vw(e,t=Ml()){try{t?.setItem(Tl,e)}catch{}}const bw="(pointer: coarse), (max-width: 760px)",El="pi-web.promptEnterPreference";function ns(){return typeof window<"u"&&"matchMedia"in window?window.matchMedia(bw):void 0}function ww(e){return e==="send"||e==="newline"?e:"auto"}function as(e=Dl()){if(e===void 0)return"auto";try{return ww(e.getItem(El))}catch{return"auto"}}function yw(e,t=Dl()){if(t!==void 0)try{t.setItem(El,e)}catch{}}function xw(e=ns(),t=as()){return t==="send"?!0:t==="newline"?!1:e?.matches!==!0}function Sw(e,t,i=ns()){return e?i?.matches===!0?t:!0:!1}function kw(e,t=ns(),i=as()){const s=xw(t,i);return e?!s:s}function Dl(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function $w(){return be`
1212
+ `: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&&Uv({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?wl(e):!0}isAtBottom(){const e=this.chat;return e?bl(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 Ev(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(Dv(r,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=r.scrollTop,i+=1,i<Mv){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=Si(i,0,Math.max(0,e-1));return}this.currentConversationIndex=Si(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 In(e,t)??In(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll("[data-scroll-anchor-id]"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,i){return i?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return`m:${String(e)}`}groupRenderKey(e){return`g:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}eventAnchorKey(e){return`e:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}};U.styles=eb;H([d({attribute:!1})],U.prototype,"messages",2);H([d()],U.prototype,"sessionId",2);H([d({type:Number})],U.prototype,"messageStart",2);H([d({type:Number})],U.prototype,"messageEnd",2);H([d({type:Number})],U.prototype,"messageTotal",2);H([d({type:Boolean})],U.prototype,"hasMore",2);H([d({type:Boolean})],U.prototype,"loadingMore",2);H([d({type:Boolean})],U.prototype,"isReceivingPartialStream",2);H([d({type:Boolean})],U.prototype,"isSendingPrompt",2);H([d({type:Boolean})],U.prototype,"isCompacting",2);H([d({type:Number})],U.prototype,"pendingMessageCount",2);H([d({attribute:!1})],U.prototype,"status",2);H([d({attribute:!1})],U.prototype,"activity",2);H([d({attribute:!1})],U.prototype,"onLoadMore",2);H([B(".chat")],U.prototype,"chat",2);H([y()],U.prototype,"pinnedToBottom",2);H([y()],U.prototype,"expandedMetaKey",2);H([y()],U.prototype,"copiedMessageKey",2);H([y()],U.prototype,"currentConversationIndex",2);H([y()],U.prototype,"loadMoreRequested",2);U=H([W("chat-view")],U);function Un(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Es(e){return e==="bash"?"Shell 运行中":e==="running"?"运行中":hw[e]??e}const uw=["image/jpeg","image/png","image/gif","image/webp"],fw=new Set(uw);function Jr(e){return typeof e=="string"&&fw.has(e)}function gw(e){switch(e){case"image/jpeg":return"jpg";case"image/png":return"png";case"image/gif":return"gif";case"image/webp":return"webp";default:return"bin"}}const mw="application/octet-stream",vw="读取附件失败。";async function bw(e,t){const i=[];let s;for(const r of e)try{const o=await t(r);i.push(yw(r,o))}catch{s=vw}return{attachments:i,...s===void 0?{}:{error:s}}}function rr(e){return e.kind==="image"&&Jr(e.mimeType)}function or(e){return e.every(t=>rr(t))}function ww(e,t){return or(t)?e:"folder"}function yw(e,t){return Jr(e.type)?{kind:"image",name:zn(e),mimeType:e.type,data:t,size:e.size}:{kind:"file",name:zn(e),mimeType:xw(e),data:t,size:e.size}}function xw(e){const t=e.type.trim();return t===""?mw:t}function zn(e){return e.name!==""?e.name:Jr(e.type)?`pasted-image.${gw(e.type)}`:"pasted-file.bin"}const Wl="pi-web:attachment-delivery";function Ol(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Sw(e=Ol()){try{return e?.getItem(Wl)==="folder"?"folder":"inline"}catch{return"inline"}}function kw(e,t=Ol()){try{t?.setItem(Wl,e)}catch{}}const $w="(pointer: coarse), (max-width: 760px)",_l="pi-web.promptEnterPreference";function ns(){return typeof window<"u"&&"matchMedia"in window?window.matchMedia($w):void 0}function Pw(e){return e==="send"||e==="newline"?e:"auto"}function as(e=Ll()){if(e===void 0)return"auto";try{return Pw(e.getItem(_l))}catch{return"auto"}}function Cw(e,t=Ll()){if(t!==void 0)try{t.setItem(_l,e)}catch{}}function Iw(e=ns(),t=as()){return t==="send"?!0:t==="newline"?!1:e?.matches!==!0}function Rw(e,t,i=ns()){return e?i?.matches===!0?t:!0:!1}function Aw(e,t=ns(),i=as()){const s=Iw(t,i);return e?!s:s}function Ll(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function Tw(){return be`
1208
1213
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1209
1214
  <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>
1210
1215
  </svg>
1211
- `}function Wl(){return be`
1216
+ `}function jl(){return be`
1212
1217
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1213
1218
  <path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
1214
1219
  <path d="M21 3 11.5 12.5"></path>
1215
1220
  </svg>
1216
- `}function Pw(){return be`
1221
+ `}function Mw(){return be`
1217
1222
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1218
1223
  <path d="M4 7h11"></path>
1219
1224
  <path d="M4 12h7"></path>
1220
1225
  <path d="M4 17h7"></path>
1221
1226
  <path d="m15 14 5 3-5 3z"></path>
1222
1227
  </svg>
1223
- `}function Cw(){return Wl()}function Rw(){return be`
1228
+ `}function Ew(){return jl()}function Dw(){return be`
1224
1229
  <svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1225
1230
  <rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
1226
1231
  </svg>
1227
- `}function Iw(e){const t=Math.max(e.total,1),i=t>1?1.2:0,s=3,n=(21-s-i*(t-1))/t,a=Array.from({length:t},(c,p)=>{const u=s+p*(n+i),h=4+(p+1)/t*12,g=20-h,b=p<e.filled;return be`<rect class=${b?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${g} width=${n} height=${h} rx="1"></rect>`});return be`
1232
+ `}function Ww(e){const t=Math.max(e.total,1),i=t>1?1.2:0,s=3,n=(21-s-i*(t-1))/t,a=Array.from({length:t},(c,p)=>{const u=s+p*(n+i),h=4+(p+1)/t*12,g=20-h,b=p<e.filled;return be`<rect class=${b?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${g} width=${n} height=${h} rx="1"></rect>`});return be`
1228
1233
  <svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1229
1234
  ${a}
1230
1235
  </svg>
1231
- `}const Aw=["off","minimal","low","medium","high","xhigh"];function nr(e){return e===void 0||e===""?"off":e}function Tw(e,t){const i=t.length>=2?t:Aw,s=i.length-1,r=nr(e),o=i.indexOf(r),n=o<=0?0:Math.min(o,s);return{total:s,filled:n}}class Mw extends _r{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===Wr.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 Qr=Or(Mw);var Ew=Object.defineProperty,Dw=Object.getOwnPropertyDescriptor,ls=(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&&Ew(t,i,r),r};const Ww=E`
1236
+ `}const Ow=["off","minimal","low","medium","high","xhigh"];function nr(e){return e===void 0||e===""?"off":e}function _w(e,t){const i=t.length>=2?t:Ow,s=i.length-1,r=nr(e),o=i.indexOf(r),n=o<=0?0:Math.min(o,s);return{total:s,filled:n}}class Lw extends _r{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===Wr.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 Qr=Or(Lw);var jw=Object.defineProperty,Fw=Object.getOwnPropertyDescriptor,ls=(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&&jw(t,i,r),r};const Uw=E`
1232
1237
  :host { display: block; }
1233
1238
  .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); }
1234
1239
  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; }
@@ -1246,12 +1251,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1246
1251
  </button>
1247
1252
  `)}
1248
1253
  </div>
1249
- `:null}};$t.styles=Ww;ls([d({attribute:!1})],$t.prototype,"items",2);ls([d({type:Number})],$t.prototype,"selectedIndex",2);ls([d({attribute:!1})],$t.prototype,"onPick",2);$t=ls([W("autocomplete-menu")],$t);var Ow=Object.defineProperty,_w=Object.getOwnPropertyDescriptor,j=(e,t,i,s)=>{for(var r=s>1?void 0:s?_w(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ow(t,i,r),r};let L=class extends A{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft="",this.currentInputMode={kind:"normal"},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=mw(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new Xr,this.readOnlyCompartment=new Xr,this.mobilePromptEnterMedia=ns(),this.explicitShiftKeyActive=!1}willUpdate(e){if(!e.has("sessionId")&&!e.has("machineId"))return;const t=e.has("sessionId")?e.get("sessionId"):this.sessionId,i=e.has("machineId")?e.get("machineId"):this.machineId,s=li(i,t);s!==void 0&&Mi(s,this.draft);const r=li(this.machineId,this.sessionId);this.draft=r!==void 0?Ra(r):"",this.currentInputMode=Oi(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has("status")&&e.size===1?!Lw(e.get("status"),this.status):!0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=this.currentInputMode.kind==="shell"?this.currentInputMode:void 0,t=e!==void 0,i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return l`
1254
+ `:null}};$t.styles=Uw;ls([d({attribute:!1})],$t.prototype,"items",2);ls([d({type:Number})],$t.prototype,"selectedIndex",2);ls([d({attribute:!1})],$t.prototype,"onPick",2);$t=ls([W("autocomplete-menu")],$t);var zw=Object.defineProperty,Bw=Object.getOwnPropertyDescriptor,j=(e,t,i,s)=>{for(var r=s>1?void 0:s?Bw(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&zw(t,i,r),r};let L=class extends A{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft="",this.currentInputMode={kind:"normal"},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=Sw(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new Xr,this.readOnlyCompartment=new Xr,this.mobilePromptEnterMedia=ns(),this.explicitShiftKeyActive=!1}willUpdate(e){if(!e.has("sessionId")&&!e.has("machineId"))return;const t=e.has("sessionId")?e.get("sessionId"):this.sessionId,i=e.has("machineId")?e.get("machineId"):this.machineId,s=li(i,t);s!==void 0&&Mi(s,this.draft);const r=li(this.machineId,this.sessionId);this.draft=r!==void 0?Ma(r):"",this.currentInputMode=Oi(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has("status")&&e.size===1?!Nw(e.get("status"),this.status):!0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=this.currentInputMode.kind==="shell"?this.currentInputMode:void 0,t=e!==void 0,i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return l`
1250
1255
  <footer class=${t?"shell-mode":""} @paste=${r=>{this.handlePaste(r)}} @dragover=${r=>{this.handleDragOver(r)}} @drop=${r=>{this.handleDrop(r)}}>
1251
1256
  <div class="editor-wrap">
1252
1257
  <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="给 pi 发送消息" aria-disabled=${this.disabled?"true":"false"}></div>
1253
1258
  <input class="attachment-input" type="file" multiple hidden @change=${r=>{this.handleFileInput(r)}} />
1254
- <button class="editor-attach icon-button" ?disabled=${s} title="附加文件" aria-label="附加文件" @click=${()=>{this.attachmentInput?.click()}}>${$w()}</button>
1259
+ <button class="editor-attach icon-button" ?disabled=${s} title="附加文件" aria-label="附加文件" @click=${()=>{this.attachmentInput?.click()}}>${Tw()}</button>
1255
1260
  ${t?l`<div class="mode-hint">Shell 命令${e.excludeFromContext?" · 已排除上下文":""}</div>`:null}
1256
1261
  ${this.isCompacting&&!t?l`<div class="mode-hint">正在压缩历史 · 消息将排队发送</div>`:null}
1257
1262
  ${this.renderAttachments()}
@@ -1259,15 +1264,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1259
1264
  </div>
1260
1265
  <div class="actions">
1261
1266
  ${this.renderCompactStatus()}
1262
- <button class="icon-button send-button" ?disabled=${s} title=${i?"当前活动结束后排队发送":"发送"} aria-label=${i?"排队发送":"发送"} @click=${()=>{this.send("followUp")}}>${i?Pw():Wl()}</button>
1263
- ${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send("steer")}}>${Cw()}</button>`:null}
1264
- <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} aria-label="停止" @click=${()=>this.onStop?.()}>${Rw()}</button>
1267
+ <button class="icon-button send-button" ?disabled=${s} title=${i?"当前活动结束后排队发送":"发送"} aria-label=${i?"排队发送":"发送"} @click=${()=>{this.send("followUp")}}>${i?Mw():jl()}</button>
1268
+ ${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send("steer")}}>${Ew()}</button>`:null}
1269
+ <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} aria-label="停止" @click=${()=>this.onStop?.()}>${Dw()}</button>
1265
1270
  </div>
1266
1271
  </footer>
1267
1272
  `}focusInput(){this.editor?.focus()}get view(){return this.editor}renderCompactStatus(){const e=this.status;if(e===void 0)return null;const t=e.model?.id??"无模型",i=e.model?.provider!==void 0&&e.model.provider!==""?`${e.model.provider}/`:"";return l`
1268
1273
  <div class="compact-status" aria-label="会话状态">
1269
1274
  <button class="select-model" title="选择模型" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
1270
- <button class="select-thinking icon-button" title=${`思考级别:${nr(e.thinkingLevel)}`} aria-label=${`思考级别:${nr(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${Iw(Tw(e.thinkingLevel,this.availableThinkingLevels))}</button>
1275
+ <button class="select-thinking icon-button" title=${`思考级别:${nr(e.thinkingLevel)}`} aria-label=${`思考级别:${nr(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${Ww(_w(e.thinkingLevel,this.availableThinkingLevels))}</button>
1271
1276
  </div>
1272
1277
  `}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;const e=or(this.attachments),t=this.effectiveAttachmentDelivery();return l`
1273
1278
  <div class="attachments" aria-label="待发送附件">
@@ -1288,9 +1293,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1288
1293
  ${this.attachmentError!==void 0?l`<div class="attachment-error">${this.attachmentError}</div>`:null}
1289
1294
  </div>
1290
1295
  `}renderAttachmentPreview(e){return rr(e)?l`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:l`
1291
- <div class="attachment-file-preview" aria-hidden="true">${Bw(e.name)}</div>
1296
+ <div class="attachment-file-preview" aria-hidden="true">${Gw(e.name)}</div>
1292
1297
  <span class="attachment-file-name">${e.name}</span>
1293
- `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;const t=e.target.value==="folder"?"folder":"inline";if(t==="inline"&&!or(this.attachments)){e.target.value="folder";return}this.attachmentDelivery=t,vw(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=jn(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&Uw(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){const t=jn(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 hw(e,Nw);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=>zw(e))}effectiveAttachmentDelivery(){return uw(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new tt({parent:this.editorHost,state:hs.create({doc:this.draft,extensions:[Bl(),Xl(),Nl(),Hl.of(" "),ql(Kl,{fallback:!0}),tt.lineWrapping,tt.contentAttributes.of(e=>Kw(e.state.sliceDoc(0,e.state.selection.main.head))),tt.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),Vl("给 pi 发送消息... 使用 / 输入命令,@ 输入已跟踪文件,@ 空格显示所有文件"),this.editableCompartment.of(tt.editable.of(!this.disabled)),this.readOnlyCompartment.of(hs.readOnly.of(this.disabled)),tt.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Gl.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>Yr.shift?.(e)??!1},{key:"Backspace",run:e=>Yl(e)},...Jl,...Ql])]})}))}syncEditorDoc(){const e=this.editor;if(!e)return;const t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:eo.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(tt.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(hs.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=li(this.machineId,this.sessionId);t!==void 0&&Mi(t,this.draft);const i=Oi(this.draft);fu(i,this.currentInputMode)||(this.currentInputMode=i),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""&&this.cwd!==void 0&&this.cwd!==""){const i=await N.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(jw);if(t!==this.requestVersion)return;this.completions=i.filter(s=>s.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(s=>({kind:"command",replaceFrom:e.from,replaceTo:e.to,insertText:`/${s.name}`,detail:s.source,...s.description===void 0?{}:{description:s.description}}))}else if(e.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const i=await N.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(Fw);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const r=Wa(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 Da(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key==="Shift")return this.explicitShiftKeyActive=!0,!1;if(e.key!=="Enter")return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;const i=Sw(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,i)}handleEditorKeyUp(e){return e.key==="Shift"&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(!t&&this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return kw(t,this.mobilePromptEnterMedia,as())?(this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0):ec(e)||Zl(e)}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):Yr.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:eo.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;const t=this.draft.trim(),i=this.attachments;if(t===""&&i.length===0)return;const s=this.canSteer||this.isCompacting?e:void 0,r=i.length>0?this.currentAttachments():void 0,o=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,s,r,r===void 0?void 0:o)}resetComposer(){this.draft="",this.currentInputMode={kind:"normal"};const e=li(this.machineId,this.sessionId);e!==void 0&&Pr(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}};L.styles=eg;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()],L.prototype,"projectId",2);j([d()],L.prototype,"workspaceId",2);j([d({type:Boolean})],L.prototype,"workspaceScopedFileSuggestions",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([y()],L.prototype,"currentInputMode",2);j([y()],L.prototype,"completions",2);j([y()],L.prototype,"selectedIndex",2);j([y()],L.prototype,"attachments",2);j([y()],L.prototype,"attachmentDelivery",2);j([y()],L.prototype,"attachmentError",2);L=j([W("prompt-editor")],L);function Lw(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel}function li(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return Pa(e,t)}function jw(){return[]}function Fw(){return[]}function jn(e){return e===null?[]:Array.from(e.files)}function Uw(e){const t=Array.from(e.items);return t.length>0?t.some(i=>i.kind==="file"):Array.from(e.types).includes("Files")}function zw(e){return e.kind==="image"?{kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}:{kind:"file",mimeType:e.mimeType,data:e.data,name:e.name}}function Bw(e){const t=e.trim(),i=t.lastIndexOf(".");return i>=0&&i<t.length-1?t.slice(i+1,i+5).toUpperCase():"FILE"}function Nw(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 Hw={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true",dir:"auto"},qw={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",dir:"auto"};function Kw(e){return Oi(e).kind==="normal"?Hw:qw}function ci(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 Vw(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var Gw=Object.defineProperty,Jw=Object.getOwnPropertyDescriptor,Ol=(e,t,i,s)=>{for(var r=s>1?void 0:s?Jw(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&&Gw(t,i,r),r};const Qw=E`
1298
+ `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;const t=e.target.value==="folder"?"folder":"inline";if(t==="inline"&&!or(this.attachments)){e.target.value="folder";return}this.attachmentDelivery=t,kw(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=Bn(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&Kw(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){const t=Bn(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 bw(e,Jw);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=>Vw(e))}effectiveAttachmentDelivery(){return ww(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new tt({parent:this.editorHost,state:hs.create({doc:this.draft,extensions:[Kl(),ic(),Vl(),Gl.of(" "),Jl(Ql,{fallback:!0}),tt.lineWrapping,tt.contentAttributes.of(e=>Xw(e.state.sliceDoc(0,e.state.selection.main.head))),tt.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),Zl("给 pi 发送消息... 使用 / 输入命令,@ 输入已跟踪文件,@ 空格显示所有文件"),this.editableCompartment.of(tt.editable.of(!this.disabled)),this.readOnlyCompartment.of(hs.readOnly.of(this.disabled)),tt.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Xl.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>Yr.shift?.(e)??!1},{key:"Backspace",run:e=>sc(e)},...Yl,...ec])]})}))}syncEditorDoc(){const e=this.editor;if(!e)return;const t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:eo.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(tt.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(hs.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=li(this.machineId,this.sessionId);t!==void 0&&Mi(t,this.draft);const i=Oi(this.draft);bu(i,this.currentInputMode)||(this.currentInputMode=i),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""&&this.cwd!==void 0&&this.cwd!==""){const i=await N.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(Hw);if(t!==this.requestVersion)return;this.completions=i.filter(s=>s.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(s=>({kind:"command",replaceFrom:e.from,replaceTo:e.to,insertText:`/${s.name}`,detail:s.source,...s.description===void 0?{}:{description:s.description}}))}else if(e.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const i=await N.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(qw);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const r=ja(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 La(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key==="Shift")return this.explicitShiftKeyActive=!0,!1;if(e.key!=="Enter")return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;const i=Rw(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,i)}handleEditorKeyUp(e){return e.key==="Shift"&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(!t&&this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return Aw(t,this.mobilePromptEnterMedia,as())?(this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0):rc(e)||tc(e)}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):Yr.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:eo.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;const t=this.draft.trim(),i=this.attachments;if(t===""&&i.length===0)return;const s=this.canSteer||this.isCompacting?e:void 0,r=i.length>0?this.currentAttachments():void 0,o=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,s,r,r===void 0?void 0:o)}resetComposer(){this.draft="",this.currentInputMode={kind:"normal"};const e=li(this.machineId,this.sessionId);e!==void 0&&Pr(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}};L.styles=rg;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()],L.prototype,"projectId",2);j([d()],L.prototype,"workspaceId",2);j([d({type:Boolean})],L.prototype,"workspaceScopedFileSuggestions",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([y()],L.prototype,"currentInputMode",2);j([y()],L.prototype,"completions",2);j([y()],L.prototype,"selectedIndex",2);j([y()],L.prototype,"attachments",2);j([y()],L.prototype,"attachmentDelivery",2);j([y()],L.prototype,"attachmentError",2);L=j([W("prompt-editor")],L);function Nw(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel}function li(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return Aa(e,t)}function Hw(){return[]}function qw(){return[]}function Bn(e){return e===null?[]:Array.from(e.files)}function Kw(e){const t=Array.from(e.items);return t.length>0?t.some(i=>i.kind==="file"):Array.from(e.types).includes("Files")}function Vw(e){return e.kind==="image"?{kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}:{kind:"file",mimeType:e.mimeType,data:e.data,name:e.name}}function Gw(e){const t=e.trim(),i=t.lastIndexOf(".");return i>=0&&i<t.length-1?t.slice(i+1,i+5).toUpperCase():"FILE"}function Jw(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 Qw={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true",dir:"auto"},Zw={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",dir:"auto"};function Xw(e){return Oi(e).kind==="normal"?Qw:Zw}function ci(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 Yw(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var ey=Object.defineProperty,ty=Object.getOwnPropertyDescriptor,Fl=(e,t,i,s)=>{for(var r=s>1?void 0:s?ty(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&ey(t,i,r),r};const iy=E`
1294
1299
  :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
1295
1300
  .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; }
1296
1301
  span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
@@ -1305,10 +1310,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1305
1310
  <span>↑${ci(s.input)}</span>
1306
1311
  <span>↓${ci(s.output)}</span>
1307
1312
  <span class="context">${i}</span>
1308
- <span>${Vw(e.cost)}</span>
1313
+ <span>${Yw(e.cost)}</span>
1309
1314
  ${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} 条排队</span>`:null}
1310
1315
  </div>
1311
- `}};Ni.styles=Qw;Ol([d({attribute:!1})],Ni.prototype,"status",2);Ni=Ol([W("status-bar")],Ni);const _l=E`
1316
+ `}};Ni.styles=iy;Fl([d({attribute:!1})],Ni.prototype,"status",2);Ni=Fl([W("status-bar")],Ni);const Ul=E`
1312
1317
  :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1313
1318
  .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
1314
1319
  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; }
@@ -1322,7 +1327,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1322
1327
  .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
1323
1328
  small { display: block; margin-top: 4px; color: var(--pi-muted); }
1324
1329
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
1325
- `;var Zw=Object.defineProperty,Xw=Object.getOwnPropertyDescriptor,qe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Xw(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Zw(t,i,r),r};let Me=class extends A{constructor(){super(...arguments),this.title="选择",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
1330
+ `;var sy=Object.defineProperty,ry=Object.getOwnPropertyDescriptor,qe=(e,t,i,s)=>{for(var r=s>1?void 0:s?ry(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&&sy(t,i,r),r};let Me=class extends A{constructor(){super(...arguments),this.title="选择",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
1326
1331
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1327
1332
  <section @mousedown=${t=>{t.stopPropagation()}}>
1328
1333
  <header>
@@ -1341,7 +1346,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1341
1346
  </div>
1342
1347
  </section>
1343
1348
  </div>
1344
- `}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const e=this.filteredOptions().findIndex(t=>t.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){const e=this.query.trim().toLowerCase();return e===""?this.options:this.options.filter(t=>`${t.label} ${t.description??""} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredOptions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i&&this.onPick?.(i.value)}}};Me.styles=_l;qe([d()],Me.prototype,"title",2);qe([d({type:Boolean})],Me.prototype,"searchable",2);qe([d({attribute:!1})],Me.prototype,"options",2);qe([d({attribute:!1})],Me.prototype,"selectedValue",2);qe([d({attribute:!1})],Me.prototype,"onPick",2);qe([d({attribute:!1})],Me.prototype,"onCancel",2);qe([y()],Me.prototype,"selectedIndex",2);qe([y()],Me.prototype,"query",2);Me=qe([W("command-picker")],Me);var Yw=Object.defineProperty,ey=Object.getOwnPropertyDescriptor,ut=(e,t,i,s)=>{for(var r=s>1?void 0:s?ey(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Yw(t,i,r),r};const ty=E`
1349
+ `}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const e=this.filteredOptions().findIndex(t=>t.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){const e=this.query.trim().toLowerCase();return e===""?this.options:this.options.filter(t=>`${t.label} ${t.description??""} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredOptions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i&&this.onPick?.(i.value)}}};Me.styles=Ul;qe([d()],Me.prototype,"title",2);qe([d({type:Boolean})],Me.prototype,"searchable",2);qe([d({attribute:!1})],Me.prototype,"options",2);qe([d({attribute:!1})],Me.prototype,"selectedValue",2);qe([d({attribute:!1})],Me.prototype,"onPick",2);qe([d({attribute:!1})],Me.prototype,"onCancel",2);qe([y()],Me.prototype,"selectedIndex",2);qe([y()],Me.prototype,"query",2);Me=qe([W("command-picker")],Me);var oy=Object.defineProperty,ny=Object.getOwnPropertyDescriptor,ut=(e,t,i,s)=>{for(var r=s>1?void 0:s?ny(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&oy(t,i,r),r};const ay=E`
1345
1350
  :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1346
1351
  .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; }
1347
1352
  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; }
@@ -1385,7 +1390,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1385
1390
  </div>
1386
1391
  </section>
1387
1392
  </div>
1388
- `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return iy(this.actions,this.queryText)}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){e.enabled!==!1&&this.onRun?.(e)}};Be.styles=ty;ut([d({attribute:!1})],Be.prototype,"actions",2);ut([d({attribute:!1})],Be.prototype,"onRun",2);ut([d({attribute:!1})],Be.prototype,"onCancel",2);ut([B("input")],Be.prototype,"input",2);ut([y()],Be.prototype,"queryText",2);ut([y()],Be.prototype,"selectedIndex",2);Be=ut([W("action-palette")],Be);function iy(e,t){const i=t.trim().toLowerCase();return e.filter(s=>s.enabled!==!1||s.disabledReason!==void 0).filter(s=>i===""?!0:[s.title,s.description??"",s.disabledReason??"",s.group??"",s.shortcut??""].join(" ").toLowerCase().includes(i))}var sy=Object.defineProperty,ry=Object.getOwnPropertyDescriptor,Pe=(e,t,i,s)=>{for(var r=s>1?void 0:s?ry(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&&sy(t,i,r),r};let le=class extends A{render(){const e=this.state;return e===void 0?null:l`
1393
+ `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return ly(this.actions,this.queryText)}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){e.enabled!==!1&&this.onRun?.(e)}};Be.styles=ay;ut([d({attribute:!1})],Be.prototype,"actions",2);ut([d({attribute:!1})],Be.prototype,"onRun",2);ut([d({attribute:!1})],Be.prototype,"onCancel",2);ut([B("input")],Be.prototype,"input",2);ut([y()],Be.prototype,"queryText",2);ut([y()],Be.prototype,"selectedIndex",2);Be=ut([W("action-palette")],Be);function ly(e,t){const i=t.trim().toLowerCase();return e.filter(s=>s.enabled!==!1||s.disabledReason!==void 0).filter(s=>i===""?!0:[s.title,s.description??"",s.disabledReason??"",s.group??"",s.shortcut??""].join(" ").toLowerCase().includes(i))}var cy=Object.defineProperty,dy=Object.getOwnPropertyDescriptor,Pe=(e,t,i,s)=>{for(var r=s>1?void 0:s?dy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&cy(t,i,r),r};let le=class extends A{render(){const e=this.state;return e===void 0?null:l`
1389
1394
  <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
1390
1395
  <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1391
1396
  <header>
@@ -1408,11 +1413,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1408
1413
  <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>
1409
1414
  </div>
1410
1415
  `;case"oauth":return this.renderOAuth(e);case"logout":return l`<div class="options">${e.providers.length===0?l`<div class="empty">没有已保存的凭据。环境变量和 models.json 设置不会变化。</div>`:e.providers.map(t=>l`
1411
- <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Fn(t.authType)}</small></button>
1416
+ <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Nn(t.authType)}</small></button>
1412
1417
  `)}</div>`}}renderProviderButton(e){return l`
1413
1418
  <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
1414
- <span>${e.name}${e.status.source!==void 0?l` <em>${ny(e)}</em>`:null}</span>
1415
- <small>${e.id} · ${Fn(e.authType)}</small>
1419
+ <span>${e.name}${e.status.source!==void 0?l` <em>${hy(e)}</em>`:null}</span>
1420
+ <small>${e.id} · ${Nn(e.authType)}</small>
1416
1421
  </button>
1417
1422
  `}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
1418
1423
  <div class="form">
@@ -1432,10 +1437,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1432
1437
  <div class="inline-options">${s.options.map(r=>l`<button @click=${()=>{this.onOAuthRespond?.(r.value)}}>${r.label}</button>`)}</div>
1433
1438
  `:null}
1434
1439
  ${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
1435
- ${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??ay(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
1440
+ ${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??uy(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
1436
1441
  ${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button></div>`:null}
1437
1442
  </div>
1438
- `}focusInputIfNeeded(){const e=oy(this.state);if(e===void 0){this.lastFocusedInputKey=void 0;return}e!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=e,this.input?.focus())}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.cancel();return}if(e.key!=="Enter")return;const t=this.state;t?.step==="apiKey"?(e.preventDefault(),this.onSaveApiKey?.()):t?.step==="oauth"&&t.flow.prompt!==void 0&&(e.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step==="oauth"?this.onOAuthCancel?.():this.onCancel?.()}};le.styles=[_l,E`
1443
+ `}focusInputIfNeeded(){const e=py(this.state);if(e===void 0){this.lastFocusedInputKey=void 0;return}e!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=e,this.input?.focus())}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.cancel();return}if(e.key!=="Enter")return;const t=this.state;t?.step==="apiKey"?(e.preventDefault(),this.onSaveApiKey?.()):t?.step==="oauth"&&t.flow.prompt!==void 0&&(e.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step==="oauth"?this.onOAuthCancel?.():this.onCancel?.()}};le.styles=[Ul,E`
1439
1444
  .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
1440
1445
  .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
1441
1446
  .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
@@ -1450,7 +1455,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1450
1455
  .progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
1451
1456
  .inline-options { display: grid; gap: 8px; }
1452
1457
  em { color: var(--pi-success); font-style: normal; font-size: 12px; }
1453
- `];Pe([d({attribute:!1})],le.prototype,"state",2);Pe([d({attribute:!1})],le.prototype,"onChooseMethod",2);Pe([d({attribute:!1})],le.prototype,"onSelectProvider",2);Pe([d({attribute:!1})],le.prototype,"onApiKeyInput",2);Pe([d({attribute:!1})],le.prototype,"onSaveApiKey",2);Pe([d({attribute:!1})],le.prototype,"onLogoutProvider",2);Pe([d({attribute:!1})],le.prototype,"onOAuthInput",2);Pe([d({attribute:!1})],le.prototype,"onOAuthRespond",2);Pe([d({attribute:!1})],le.prototype,"onOAuthCancel",2);Pe([d({attribute:!1})],le.prototype,"onCancel",2);Pe([B("input")],le.prototype,"input",2);le=Pe([W("auth-dialog")],le);function Fn(e){return e==="oauth"?"订阅":"API key"}function oy(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 ny(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 ay(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var ly=Object.defineProperty,cy=Object.getOwnPropertyDescriptor,Le=(e,t,i,s)=>{for(var r=s>1?void 0:s?cy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&ly(t,i,r),r};let xe=class extends A{constructor(){super(...arguments),this.machineId="local",this.path="",this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}firstUpdated(){this.pathInput?.focus()}async loadSuggestions(){const e=++this.requestId;this.loading=!0;try{const t=await N.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==""&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="Enter")e.preventDefault(),this.submit();else if(e.key==="ArrowDown")e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key==="ArrowUp")e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key==="Tab"){const t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return l`
1458
+ `];Pe([d({attribute:!1})],le.prototype,"state",2);Pe([d({attribute:!1})],le.prototype,"onChooseMethod",2);Pe([d({attribute:!1})],le.prototype,"onSelectProvider",2);Pe([d({attribute:!1})],le.prototype,"onApiKeyInput",2);Pe([d({attribute:!1})],le.prototype,"onSaveApiKey",2);Pe([d({attribute:!1})],le.prototype,"onLogoutProvider",2);Pe([d({attribute:!1})],le.prototype,"onOAuthInput",2);Pe([d({attribute:!1})],le.prototype,"onOAuthRespond",2);Pe([d({attribute:!1})],le.prototype,"onOAuthCancel",2);Pe([d({attribute:!1})],le.prototype,"onCancel",2);Pe([B("input")],le.prototype,"input",2);le=Pe([W("auth-dialog")],le);function Nn(e){return e==="oauth"?"订阅":"API key"}function py(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 hy(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 uy(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var fy=Object.defineProperty,gy=Object.getOwnPropertyDescriptor,Le=(e,t,i,s)=>{for(var r=s>1?void 0:s?gy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&fy(t,i,r),r};let xe=class extends A{constructor(){super(...arguments),this.machineId="local",this.path="",this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}firstUpdated(){this.pathInput?.focus()}async loadSuggestions(){const e=++this.requestId;this.loading=!0;try{const t=await N.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==""&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="Enter")e.preventDefault(),this.submit();else if(e.key==="ArrowDown")e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key==="ArrowUp")e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key==="Tab"){const t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return l`
1454
1459
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1455
1460
  <section @click=${e=>{e.stopPropagation()}}>
1456
1461
  <header>
@@ -1500,7 +1505,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1500
1505
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1501
1506
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1502
1507
  button:disabled { opacity: .5; cursor: not-allowed; }
1503
- `;Le([d({attribute:!1})],xe.prototype,"onSubmit",2);Le([d({attribute:!1})],xe.prototype,"onCancel",2);Le([d()],xe.prototype,"machineId",2);Le([y()],xe.prototype,"path",2);Le([y()],xe.prototype,"createMissing",2);Le([y()],xe.prototype,"suggestions",2);Le([y()],xe.prototype,"selected",2);Le([y()],xe.prototype,"loading",2);Le([B("input")],xe.prototype,"pathInput",2);xe=Le([W("project-dialog")],xe);var dy=Object.defineProperty,py=Object.getOwnPropertyDescriptor,je=(e,t,i,s)=>{for(var r=s>1?void 0:s?py(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&dy(t,i,r),r};let Se=class extends A{constructor(){super(...arguments),this.error="",this.url="",this.name="",this.token="",this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=""}firstUpdated(){this.urlInput?.focus()}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;const t=e.target.value,i=hy(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"&&Ds(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===""||Ds(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?Ds(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1508
+ `;Le([d({attribute:!1})],xe.prototype,"onSubmit",2);Le([d({attribute:!1})],xe.prototype,"onCancel",2);Le([d()],xe.prototype,"machineId",2);Le([y()],xe.prototype,"path",2);Le([y()],xe.prototype,"createMissing",2);Le([y()],xe.prototype,"suggestions",2);Le([y()],xe.prototype,"selected",2);Le([y()],xe.prototype,"loading",2);Le([B("input")],xe.prototype,"pathInput",2);xe=Le([W("project-dialog")],xe);var my=Object.defineProperty,vy=Object.getOwnPropertyDescriptor,je=(e,t,i,s)=>{for(var r=s>1?void 0:s?vy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&my(t,i,r),r};let Se=class extends A{constructor(){super(...arguments),this.error="",this.url="",this.name="",this.token="",this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=""}firstUpdated(){this.urlInput?.focus()}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;const t=e.target.value,i=by(t);(!this.nameEdited||this.name.trim()===""||this.name===this.previousSuggestedName)&&(this.name=i),this.previousSuggestedName=i,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.onCancel?.();return}e.key==="Enter"&&e.target instanceof HTMLInputElement&&e.target.name==="baseUrl"&&Ds(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===""||Ds(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?Ds(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1504
1509
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1505
1510
  <section @click=${s=>{s.stopPropagation()}}>
1506
1511
  <form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
@@ -1555,10 +1560,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1555
1560
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1556
1561
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1557
1562
  button:disabled { opacity: .5; cursor: not-allowed; }
1558
- `;je([d({attribute:!1})],Se.prototype,"onSubmit",2);je([d({attribute:!1})],Se.prototype,"onCancel",2);je([d()],Se.prototype,"error",2);je([y()],Se.prototype,"url",2);je([y()],Se.prototype,"name",2);je([y()],Se.prototype,"token",2);je([y()],Se.prototype,"submitting",2);je([B("input[name='baseUrl']")],Se.prototype,"urlInput",2);je([B("input[name='name']")],Se.prototype,"nameInput",2);Se=je([W("machine-dialog")],Se);function hy(e){const t=e.trim();if(t==="")return"";const i=Un(t)??Un(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):uy(t)}function Ds(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 Un(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function uy(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 fy(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:"",allowedPathsText:""}}function gy(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(`
1563
+ `;je([d({attribute:!1})],Se.prototype,"onSubmit",2);je([d({attribute:!1})],Se.prototype,"onCancel",2);je([d()],Se.prototype,"error",2);je([y()],Se.prototype,"url",2);je([y()],Se.prototype,"name",2);je([y()],Se.prototype,"token",2);je([y()],Se.prototype,"submitting",2);je([B("input[name='baseUrl']")],Se.prototype,"urlInput",2);je([B("input[name='name']")],Se.prototype,"nameInput",2);Se=je([W("machine-dialog")],Se);function by(e){const t=e.trim();if(t==="")return"";const i=Hn(t)??Hn(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):wy(t)}function Ds(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 Hn(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function wy(e){const t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,""),s=t.slice(t.lastIndexOf("@")+1).split(/[/?#]/u)[0]??"";return s.startsWith("[")&&s.includes("]")?s.slice(1,s.indexOf("]")):s.replace(/:\d+$/u,"")}function yy(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:"",allowedPathsText:""}}function xy(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(`
1559
1564
  `):"",allowedPathsText:e.pathAccess?.allowedPaths?.join(`
1560
- `)??""}}function my(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins},...t.uploads===void 0?{}:{uploads:t.uploads},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes},...t.spawnSessions===void 0?{}:{spawnSessions:t.spawnSessions},...t.subsessions===void 0?{}:{subsessions:t.subsessions}},s=e.host.trim(),r=e.port.trim();if(s!==""&&(i.host=s),r!==""){const n=Number(r);if(!Number.isInteger(n)||n<1||n>65535)throw new Error("端口必须是 1 到 65535 之间的整数。");i.port=n}i.allowedHosts=e.allowedHostsMode==="all"?!0:vy(e.allowedHostsText);const o=by(e.allowedPathsText);return o.length>0&&(i.pathAccess={allowedPaths:o}),i}function vy(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}function by(e){const t=e.split(`
1561
- `).map(s=>s.trim()).filter(s=>s!==""),i=t.find(s=>!wy(s));if(i!==void 0)throw new Error(`Allowed external paths must be absolute paths or start with ~: ${i}`);return t}function wy(e){return e==="~"||e.startsWith("~/")||e.startsWith("~\\")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:[\\/]/u.test(e)}function cs(e,t){return e!==""?l`<div class="message error-message">${e}</div>`:t!==""?l`<div class="message success-message">${t}</div>`:null}const ds=E`
1565
+ `)??""}}function Sy(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins},...t.uploads===void 0?{}:{uploads:t.uploads},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes},...t.spawnSessions===void 0?{}:{spawnSessions:t.spawnSessions},...t.subsessions===void 0?{}:{subsessions:t.subsessions}},s=e.host.trim(),r=e.port.trim();if(s!==""&&(i.host=s),r!==""){const n=Number(r);if(!Number.isInteger(n)||n<1||n>65535)throw new Error("端口必须是 1 到 65535 之间的整数。");i.port=n}i.allowedHosts=e.allowedHostsMode==="all"?!0:ky(e.allowedHostsText);const o=$y(e.allowedPathsText);return o.length>0&&(i.pathAccess={allowedPaths:o}),i}function ky(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}function $y(e){const t=e.split(`
1566
+ `).map(s=>s.trim()).filter(s=>s!==""),i=t.find(s=>!Py(s));if(i!==void 0)throw new Error(`Allowed external paths must be absolute paths or start with ~: ${i}`);return t}function Py(e){return e==="~"||e.startsWith("~/")||e.startsWith("~\\")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:[\\/]/u.test(e)}function cs(e,t){return e!==""?l`<div class="message error-message">${e}</div>`:t!==""?l`<div class="message success-message">${t}</div>`:null}const ds=E`
1562
1567
  :host { display: block; }
1563
1568
  .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1564
1569
  .section-heading > div { display: grid; gap: 6px; min-width: 0; }
@@ -1594,7 +1599,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1594
1599
  .section-heading .secondary { justify-self: start; }
1595
1600
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1596
1601
  }
1597
- `;var yy=Object.defineProperty,xy=Object.getOwnPropertyDescriptor,Fe=(e,t,i,s)=>{for(var r=s>1?void 0:s?xy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&yy(t,i,r),r};let ke=class extends A{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=fy(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=gy(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
1602
+ `;var Cy=Object.defineProperty,Iy=Object.getOwnPropertyDescriptor,Fe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Iy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Cy(t,i,r),r};let ke=class extends A{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=yy(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=xy(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
1598
1603
  <div class="section-heading">
1599
1604
  <div>
1600
1605
  <h2>通用配置</h2>
@@ -1615,7 +1620,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1615
1620
  <span>Host</span>
1616
1621
  ${this.renderOverrideBadge("host")}
1617
1622
  </span>
1618
- <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:zn(t)})}}>
1623
+ <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:qn(t)})}}>
1619
1624
  <small>Web 服务器应绑定的地址。留空则使用 PI WEB 默认值。</small>
1620
1625
  </label>
1621
1626
 
@@ -1624,7 +1629,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1624
1629
  <span>Port</span>
1625
1630
  ${this.renderOverrideBadge("port")}
1626
1631
  </span>
1627
- <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:zn(t)})}}>
1632
+ <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:qn(t)})}}>
1628
1633
  <small>TCP 端口,范围 1 到 65535。留空则使用 PI WEB 默认值。</small>
1629
1634
  </label>
1630
1635
 
@@ -1633,11 +1638,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1633
1638
  <span>允许的 hosts</span>
1634
1639
  ${this.renderOverrideBadge("allowedHosts")}
1635
1640
  </span>
1636
- <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:$y(t)==="all"?"all":"list"})}}>
1641
+ <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:Ty(t)==="all"?"all":"list"})}}>
1637
1642
  <option value="list">仅允许列出的 hosts</option>
1638
1643
  <option value="all">允许所有 host</option>
1639
1644
  </select>
1640
- <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:Bn(t)})}}></textarea>
1645
+ <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:Kn(t)})}}></textarea>
1641
1646
  <small>每行输入一个 host,或选择“允许所有 host”写入 <code>true</code>。</small>
1642
1647
  </div>
1643
1648
 
@@ -1645,7 +1650,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1645
1650
  <span class="field-heading">
1646
1651
  <span>External filesystem roots</span>
1647
1652
  </span>
1648
- <textarea .value=${this.draft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${t=>{this.updateDraft({allowedPathsText:Bn(t)})}}></textarea>
1653
+ <textarea .value=${this.draft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${t=>{this.updateDraft({allowedPathsText:Kn(t)})}}></textarea>
1649
1654
  <small>Global allowlist for absolute <code>@</code> completions and file explorer reads outside a workspace. Enter one absolute path, Windows absolute path, or <code>~</code>-prefixed path per line. Leave empty to deny external paths by default.</small>
1650
1655
  </label>
1651
1656
 
@@ -1662,18 +1667,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1662
1667
  <dl>
1663
1668
  <div><dt>Host</dt><dd>${e.host??l`<span class="muted">默认 127.0.0.1</span>`}</dd></div>
1664
1669
  <div><dt>端口</dt><dd>${e.port??l`<span class="muted">默认 8504</span>`}</dd></div>
1665
- <div><dt>允许的 hosts</dt><dd>${Sy(e.allowedHosts)}</dd></div>
1666
- <div><dt>外部根目录</dt><dd>${ky(e.pathAccess?.allowedPaths)}</dd></div>
1670
+ <div><dt>允许的 hosts</dt><dd>${Ry(e.allowedHosts)}</dd></div>
1671
+ <div><dt>外部根目录</dt><dd>${Ay(e.pathAccess?.allowedPaths)}</dd></div>
1667
1672
  </dl>
1668
1673
  </section>
1669
- `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(my(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=Py(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};ke.styles=[ds,E`
1674
+ `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(Sy(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=My(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};ke.styles=[ds,E`
1670
1675
  .config-form { display: grid; gap: 14px; }
1671
1676
  input, select, textarea { box-sizing: border-box; width: 100%; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px 10px; outline: none; font: var(--pi-control-font-size, 16px) var(--pi-control-font-family, system-ui, sans-serif); }
1672
1677
  input:focus, select:focus, textarea:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
1673
1678
  textarea { resize: vertical; min-height: 94px; font-family: var(--pi-control-monospace-font-family, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); }
1674
1679
  textarea:disabled { opacity: .55; }
1675
1680
  .form-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 2px; }
1676
- `];Fe([d({attribute:!1})],ke.prototype,"configResponse",2);Fe([d({type:Boolean})],ke.prototype,"loading",2);Fe([d({type:Boolean})],ke.prototype,"saving",2);Fe([d()],ke.prototype,"error",2);Fe([d()],ke.prototype,"savedMessage",2);Fe([d({attribute:!1})],ke.prototype,"onReload",2);Fe([d({attribute:!1})],ke.prototype,"onSave",2);Fe([y()],ke.prototype,"draft",2);Fe([y()],ke.prototype,"localError",2);ke=Fe([W("settings-general-panel")],ke);function Sy(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?l`<span class="muted">未列出</span>`:e.join(", "):l`<span class="muted">未设置</span>`}function ky(e){return e===void 0||e.length===0?l`<span class="muted">已禁止外部路径</span>`:e.join(", ")}function zn(e){return e.target instanceof HTMLInputElement?e.target.value:""}function $y(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function Bn(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function Py(e){return e instanceof Error?e.message:String(e)}var Cy=Object.defineProperty,Ry=Object.getOwnPropertyDescriptor,et=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ry(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Cy(t,i,r),r};let _e=class extends A{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,i=e?.effectiveConfig.spawnSessions!==!1,s=e?.envOverrides.subsessions===!0,r=e?.effectiveConfig.subsessions===!0&&i;return l`
1681
+ `];Fe([d({attribute:!1})],ke.prototype,"configResponse",2);Fe([d({type:Boolean})],ke.prototype,"loading",2);Fe([d({type:Boolean})],ke.prototype,"saving",2);Fe([d()],ke.prototype,"error",2);Fe([d()],ke.prototype,"savedMessage",2);Fe([d({attribute:!1})],ke.prototype,"onReload",2);Fe([d({attribute:!1})],ke.prototype,"onSave",2);Fe([y()],ke.prototype,"draft",2);Fe([y()],ke.prototype,"localError",2);ke=Fe([W("settings-general-panel")],ke);function Ry(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?l`<span class="muted">未列出</span>`:e.join(", "):l`<span class="muted">未设置</span>`}function Ay(e){return e===void 0||e.length===0?l`<span class="muted">已禁止外部路径</span>`:e.join(", ")}function qn(e){return e.target instanceof HTMLInputElement?e.target.value:""}function Ty(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function Kn(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function My(e){return e instanceof Error?e.message:String(e)}var Ey=Object.defineProperty,Dy=Object.getOwnPropertyDescriptor,et=(e,t,i,s)=>{for(var r=s>1?void 0:s?Dy(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&&Ey(t,i,r),r};let _e=class extends A{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,i=e?.effectiveConfig.spawnSessions!==!1,s=e?.envOverrides.subsessions===!0,r=e?.effectiveConfig.subsessions===!0&&i;return l`
1677
1682
  <div class="section-heading">
1678
1683
  <div>
1679
1684
  <h2>会话守护进程</h2>
@@ -1737,7 +1742,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1737
1742
  .toggle input { width: 16px; height: 16px; }
1738
1743
  .toggle input:disabled { cursor: not-allowed; }
1739
1744
  .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; }
1740
- `];et([d({attribute:!1})],_e.prototype,"configResponse",2);et([d({type:Boolean})],_e.prototype,"loading",2);et([d({type:Boolean})],_e.prototype,"saving",2);et([d()],_e.prototype,"error",2);et([d()],_e.prototype,"savedMessage",2);et([d({attribute:!1})],_e.prototype,"onReload",2);et([d({attribute:!1})],_e.prototype,"onSave",2);_e=et([W("settings-sessiond-panel")],_e);var Iy=Object.defineProperty,Ay=Object.getOwnPropertyDescriptor,Ke=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ay(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Iy(t,i,r),r};let Ee=class extends A{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
1745
+ `];et([d({attribute:!1})],_e.prototype,"configResponse",2);et([d({type:Boolean})],_e.prototype,"loading",2);et([d({type:Boolean})],_e.prototype,"saving",2);et([d()],_e.prototype,"error",2);et([d()],_e.prototype,"savedMessage",2);et([d({attribute:!1})],_e.prototype,"onReload",2);et([d({attribute:!1})],_e.prototype,"onSave",2);_e=et([W("settings-sessiond-panel")],_e);var Wy=Object.defineProperty,Oy=Object.getOwnPropertyDescriptor,Ke=(e,t,i,s)=>{for(var r=s>1?void 0:s?Oy(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&&Wy(t,i,r),r};let Ee=class extends A{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
1741
1746
  <div class="section-heading">
1742
1747
  <div>
1743
1748
  <h2>插件</h2>
@@ -1781,7 +1786,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1781
1786
  .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
1782
1787
  .toggle { justify-self: start; }
1783
1788
  }
1784
- `];Ke([d({attribute:!1})],Ee.prototype,"pluginsResponse",2);Ke([d({attribute:!1})],Ee.prototype,"configResponse",2);Ke([d({type:Boolean})],Ee.prototype,"loading",2);Ke([d({type:Boolean})],Ee.prototype,"saving",2);Ke([d()],Ee.prototype,"error",2);Ke([d()],Ee.prototype,"savedMessage",2);Ke([d({attribute:!1})],Ee.prototype,"onReload",2);Ke([d({attribute:!1})],Ee.prototype,"onTogglePlugin",2);Ee=Ke([W("settings-plugins-panel")],Ee);var Ty=Object.defineProperty,My=Object.getOwnPropertyDescriptor,ge=(e,t,i,s)=>{for(var r=s>1?void 0:s?My(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ty(t,i,r),r};const Nn={capture:!0},Ey=[{value:"auto",label:"Auto/default",description:"Desktop-like Enter sends; mobile, coarse pointer, or narrow screens insert a new line."},{value:"send",label:"Enter sends message",description:"Enter sends the chat message; Shift+Enter adds a new line when supported."},{value:"newline",label:"Enter inserts new line",description:"Enter adds a line break; Shift+Enter sends the chat message when supported."}];let ie=class extends A{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.promptEnterPreference=as(),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=Ba(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&&!Kt(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=_y(this.actions),t=this.shortcutResolutions();return l`
1789
+ `];Ke([d({attribute:!1})],Ee.prototype,"pluginsResponse",2);Ke([d({attribute:!1})],Ee.prototype,"configResponse",2);Ke([d({type:Boolean})],Ee.prototype,"loading",2);Ke([d({type:Boolean})],Ee.prototype,"saving",2);Ke([d()],Ee.prototype,"error",2);Ke([d()],Ee.prototype,"savedMessage",2);Ke([d({attribute:!1})],Ee.prototype,"onReload",2);Ke([d({attribute:!1})],Ee.prototype,"onTogglePlugin",2);Ee=Ke([W("settings-plugins-panel")],Ee);var _y=Object.defineProperty,Ly=Object.getOwnPropertyDescriptor,ge=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ly(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&_y(t,i,r),r};const Vn={capture:!0},jy=[{value:"auto",label:"Auto/default",description:"Desktop-like Enter sends; mobile, coarse pointer, or narrow screens insert a new line."},{value:"send",label:"Enter sends message",description:"Enter sends the chat message; Shift+Enter adds a new line when supported."},{value:"newline",label:"Enter inserts new line",description:"Enter adds a line break; Shift+Enter sends the chat message when supported."}];let ie=class extends A{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.promptEnterPreference=as(),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=Ka(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&&!Kt(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=By(this.actions),t=this.shortcutResolutions();return l`
1785
1790
  <div class="section-heading">
1786
1791
  <div>
1787
1792
  <h2>键盘快捷键</h2>
@@ -1814,7 +1819,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1814
1819
  <p>Choose what Enter does in this browser. Shift+Enter does the opposite when supported; automatic touch-keyboard capitalization is ignored to avoid accidental sends.</p>
1815
1820
  </div>
1816
1821
  <div class="prompt-enter-options" role="radiogroup" aria-label="Enter and Shift Enter behavior in the chat composer">
1817
- ${Ey.map(e=>l`
1822
+ ${jy.map(e=>l`
1818
1823
  <label class="prompt-enter-option">
1819
1824
  <input
1820
1825
  type="radio"
@@ -1831,8 +1836,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1831
1836
  `)}
1832
1837
  </div>
1833
1838
  </section>
1834
- `}updatePromptEnterPreference(e){this.promptEnterPreference=e,yw(e)}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=Hi(e.id,i),r=Uy(e,i),o=this.shortcutInputText(e),n=o.trim()===""?void 0:ys(o),a=n?.ok===!0?n.shortcut:Fy(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&o.trim()!==""?"custom":r,h=this.recordingHint(e.id),g=Oy(t);return l`
1835
- <article class=${Dy(t)}>
1839
+ `}updatePromptEnterPreference(e){this.promptEnterPreference=e,Cw(e)}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=Hi(e.id,i),r=Ky(e,i),o=this.shortcutInputText(e),n=o.trim()===""?void 0:ys(o),a=n?.ok===!0?n.shortcut:qy(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&o.trim()!==""?"custom":r,h=this.recordingHint(e.id),g=zy(t);return l`
1840
+ <article class=${Fy(t)}>
1836
1841
  <div class="shortcut-main">
1837
1842
  <strong>${e.title}</strong>
1838
1843
  ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
@@ -1842,8 +1847,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1842
1847
  <div class="shortcut-editor">
1843
1848
  <div class="shortcut-status">
1844
1849
  ${a!==void 0&&a!==""?l`<kbd>${bi(a)}</kbd>`:l`<span class="unassigned">${r==="disabled"?"已禁用":"未分配"}</span>`}
1845
- <small class=${u}>${zy(u)}${p?" · 未保存":""}</small>
1846
- ${g===void 0?null:l`<small class=${Wy(t)}>${g}</small>`}
1850
+ <small class=${u}>${Vy(u)}${p?" · 未保存":""}</small>
1851
+ ${g===void 0?null:l`<small class=${Uy(t)}>${g}</small>`}
1847
1852
  </div>
1848
1853
  <label class="shortcut-input-label">
1849
1854
  <span>快捷键</span>
@@ -1856,7 +1861,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1856
1861
  autocapitalize="off"
1857
1862
  spellcheck="false"
1858
1863
  ?disabled=${this.saving}
1859
- @input=${b=>{this.updateDraft(e.id,By(b))}}
1864
+ @input=${b=>{this.updateDraft(e.id,Gy(b))}}
1860
1865
  >
1861
1866
  </label>
1862
1867
  ${h!==""?l`<small class="recording-hint">${h}</small>`:null}
@@ -1868,7 +1873,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1868
1873
  </div>
1869
1874
  </div>
1870
1875
  </article>
1871
- `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=Hi(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: ${bi(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=ys(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?jy(s,e):{...s,[e]:t};Object.keys(r).length===0?delete i.shortcuts:i.shortcuts=r,await this.onSave?.(i)}shortcutResolutions(){return new Map(Ir(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=ys(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()},Ua)}stopRecording(){this.clearRecordingTimer(),this.removeRecordingListener(),this.recording=void 0}clearRecordingTimer(){this.recordingTimer!==void 0&&(window.clearTimeout(this.recordingTimer),this.recordingTimer=void 0)}ensureRecordingListener(){this.recordingListenerActive||(window.addEventListener("keydown",this.onRecordKeyDown,Nn),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,Nn),this.recordingListenerActive=!1)}};ie.styles=[ds,E`
1876
+ `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=Hi(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: ${bi(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=ys(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?Hy(s,e):{...s,[e]:t};Object.keys(r).length===0?delete i.shortcuts:i.shortcuts=r,await this.onSave?.(i)}shortcutResolutions(){return new Map(Rr(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=ys(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()},Ha)}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,Vn),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,Vn),this.recordingListenerActive=!1)}};ie.styles=[ds,E`
1872
1877
  .prompt-enter-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; display: grid; grid-template-columns: minmax(0, .85fr) minmax(260px, 1fr); gap: 12px; align-items: start; margin-bottom: 14px; }
1873
1878
  .prompt-enter-copy { display: grid; gap: 5px; min-width: 0; }
1874
1879
  .prompt-enter-copy p, .prompt-enter-option small { font-size: 12px; }
@@ -1911,7 +1916,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1911
1916
  .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
1912
1917
  .shortcut-status, .shortcut-actions { justify-content: flex-start; }
1913
1918
  }
1914
- `];ge([d({attribute:!1})],ie.prototype,"actions",2);ge([d({attribute:!1})],ie.prototype,"configResponse",2);ge([d({type:Boolean})],ie.prototype,"loading",2);ge([d({type:Boolean})],ie.prototype,"saving",2);ge([d()],ie.prototype,"error",2);ge([d()],ie.prototype,"savedMessage",2);ge([d({attribute:!1})],ie.prototype,"onReload",2);ge([d({attribute:!1})],ie.prototype,"onSave",2);ge([y()],ie.prototype,"drafts",2);ge([y()],ie.prototype,"localError",2);ge([y()],ie.prototype,"promptEnterPreference",2);ge([y()],ie.prototype,"recording",2);ie=ge([W("settings-shortcuts-panel")],ie);function Dy(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function Wy(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function Oy(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 _y(e){const t=new Map;for(const i of[...e].sort(Ly)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function Ly(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function Hi(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function jy(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Fy(e,t){const i=Hi(e.id,t);if(i!==null)return i??e.shortcut}function Uy(e,t){const i=Hi(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function zy(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}function By(e){return e.target instanceof HTMLInputElement?e.target.value:""}var Ny=Object.defineProperty,Hy=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var r=s>1?void 0:s?Hy(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&&Ny(t,i,r),r};let ce=class extends A{constructor(){super(...arguments),this.section="general",this.actions=[],this.loading=!0,this.saving=!1,this.error="",this.savedMessage=""}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}render(){return l`
1919
+ `];ge([d({attribute:!1})],ie.prototype,"actions",2);ge([d({attribute:!1})],ie.prototype,"configResponse",2);ge([d({type:Boolean})],ie.prototype,"loading",2);ge([d({type:Boolean})],ie.prototype,"saving",2);ge([d()],ie.prototype,"error",2);ge([d()],ie.prototype,"savedMessage",2);ge([d({attribute:!1})],ie.prototype,"onReload",2);ge([d({attribute:!1})],ie.prototype,"onSave",2);ge([y()],ie.prototype,"drafts",2);ge([y()],ie.prototype,"localError",2);ge([y()],ie.prototype,"promptEnterPreference",2);ge([y()],ie.prototype,"recording",2);ie=ge([W("settings-shortcuts-panel")],ie);function Fy(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function Uy(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function zy(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 By(e){const t=new Map;for(const i of[...e].sort(Ny)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function Ny(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function Hi(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Hy(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function qy(e,t){const i=Hi(e.id,t);if(i!==null)return i??e.shortcut}function Ky(e,t){const i=Hi(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function Vy(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}function Gy(e){return e.target instanceof HTMLInputElement?e.target.value:""}var Jy=Object.defineProperty,Qy=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var r=s>1?void 0:s?Qy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Jy(t,i,r),r};let ce=class extends A{constructor(){super(...arguments),this.section="general",this.actions=[],this.loading=!0,this.saving=!1,this.error="",this.savedMessage=""}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}render(){return l`
1915
1920
  <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
1916
1921
  <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB 设置" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
1917
1922
  <header class="settings-header">
@@ -1981,7 +1986,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1981
1986
  <strong>${t}</strong>
1982
1987
  <small>${i}</small>
1983
1988
  </button>
1984
- `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([Ri.config(),qs.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`加载设置失败:${Ws(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 Ri.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(t){this.error=`保存配置失败:${Ws(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await qs.plugins()}catch(e){this.error=`刷新插件失败:${Ws(e)}`}}showSavedMessage(){this.savedMessage="配置已保存。",this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage==="配置已保存。"&&(this.savedMessage=""),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};ce.styles=E`
1989
+ `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([Ii.config(),qs.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`加载设置失败:${Ws(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},r=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...r,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await Ii.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(t){this.error=`保存配置失败:${Ws(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await qs.plugins()}catch(e){this.error=`刷新插件失败:${Ws(e)}`}}showSavedMessage(){this.savedMessage="配置已保存。",this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage==="配置已保存。"&&(this.savedMessage=""),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};ce.styles=E`
1985
1990
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1986
1991
  .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; }
1987
1992
  .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; }
@@ -2008,7 +2013,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2008
2013
  .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
2009
2014
  .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
2010
2015
  }
2011
- `;Ce([d({attribute:!1})],ce.prototype,"section",2);Ce([d({attribute:!1})],ce.prototype,"actions",2);Ce([d({attribute:!1})],ce.prototype,"onNavigate",2);Ce([d({attribute:!1})],ce.prototype,"onClose",2);Ce([d({attribute:!1})],ce.prototype,"onConfigSaved",2);Ce([y()],ce.prototype,"configResponse",2);Ce([y()],ce.prototype,"pluginsResponse",2);Ce([y()],ce.prototype,"loading",2);Ce([y()],ce.prototype,"saving",2);Ce([y()],ce.prototype,"error",2);Ce([y()],ce.prototype,"savedMessage",2);ce=Ce([W("settings-dialog")],ce);function Ws(e){return e instanceof Error?e.message:String(e)}var qy=Object.defineProperty,Ky=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ky(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&qy(t,i,r),r};const Vy=E`
2016
+ `;Ce([d({attribute:!1})],ce.prototype,"section",2);Ce([d({attribute:!1})],ce.prototype,"actions",2);Ce([d({attribute:!1})],ce.prototype,"onNavigate",2);Ce([d({attribute:!1})],ce.prototype,"onClose",2);Ce([d({attribute:!1})],ce.prototype,"onConfigSaved",2);Ce([y()],ce.prototype,"configResponse",2);Ce([y()],ce.prototype,"pluginsResponse",2);Ce([y()],ce.prototype,"loading",2);Ce([y()],ce.prototype,"saving",2);Ce([y()],ce.prototype,"error",2);Ce([y()],ce.prototype,"savedMessage",2);ce=Ce([W("settings-dialog")],ce);function Ws(e){return e instanceof Error?e.message:String(e)}var Zy=Object.defineProperty,Xy=Object.getOwnPropertyDescriptor,De=(e,t,i,s)=>{for(var r=s>1?void 0:s?Xy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Zy(t,i,r),r};const Yy=E`
2012
2017
  :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; }
2013
2018
  header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
2014
2019
  .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
@@ -2097,32 +2102,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2097
2102
  <h2>${e.title}</h2>
2098
2103
  ${e.body===void 0?null:l`<p>${e.body}</p>`}
2099
2104
  </section>
2100
- `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?" can-scroll-left":""}${this.workspaceHeaderCanScrollRight?" can-scroll-right":""}`}observeWorkspaceHeaderStrip(){const e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){const e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==i&&(this.workspaceHeaderCanScrollLeft=i),this.workspaceHeaderCanScrollRight!==s&&(this.workspaceHeaderCanScrollRight=s)}workspaceHeaderStripElement(){const e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}};ue.styles=Vy;De([d({attribute:!1})],ue.prototype,"workspace",2);De([d({attribute:!1})],ue.prototype,"panelContext",2);De([d({attribute:!1})],ue.prototype,"emptyState",2);De([d()],ue.prototype,"tool",2);De([d({attribute:!1})],ue.prototype,"panels",2);De([d({type:Boolean})],ue.prototype,"hideToolTabs",2);De([d({attribute:!1})],ue.prototype,"onSelectTool",2);De([B(".workspace-header-strip")],ue.prototype,"workspaceHeaderStrip",2);De([y()],ue.prototype,"workspaceHeaderCanScrollLeft",2);De([y()],ue.prototype,"workspaceHeaderCanScrollRight",2);ue=De([W("workspace-panel")],ue);var Gy=Object.defineProperty,Jy=Object.getOwnPropertyDescriptor,Re=(e,t,i,s)=>{for(var r=s>1?void 0:s?Jy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Gy(t,i,r),r};let de=class extends A{constructor(){super(...arguments),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){const e=Qy(this.machines),t=Zy(this.machine),i=Yy(this.project),s=t0(this.workspace),r=s0(this.session);return l`
2105
+ `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?" can-scroll-left":""}${this.workspaceHeaderCanScrollRight?" can-scroll-right":""}`}observeWorkspaceHeaderStrip(){const e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){const e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==i&&(this.workspaceHeaderCanScrollLeft=i),this.workspaceHeaderCanScrollRight!==s&&(this.workspaceHeaderCanScrollRight=s)}workspaceHeaderStripElement(){const e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}};ue.styles=Yy;De([d({attribute:!1})],ue.prototype,"workspace",2);De([d({attribute:!1})],ue.prototype,"panelContext",2);De([d({attribute:!1})],ue.prototype,"emptyState",2);De([d()],ue.prototype,"tool",2);De([d({attribute:!1})],ue.prototype,"panels",2);De([d({type:Boolean})],ue.prototype,"hideToolTabs",2);De([d({attribute:!1})],ue.prototype,"onSelectTool",2);De([B(".workspace-header-strip")],ue.prototype,"workspaceHeaderStrip",2);De([y()],ue.prototype,"workspaceHeaderCanScrollLeft",2);De([y()],ue.prototype,"workspaceHeaderCanScrollRight",2);ue=De([W("workspace-panel")],ue);var e0=Object.defineProperty,t0=Object.getOwnPropertyDescriptor,Ie=(e,t,i,s)=>{for(var r=s>1?void 0:s?t0(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&&e0(t,i,r),r};let de=class extends A{constructor(){super(...arguments),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){const e=i0(this.machines),t=s0(this.machine),i=o0(this.project),s=a0(this.workspace),r=c0(this.session);return l`
2101
2106
  <nav class=${this.contextBarClass()} aria-label="当前位置">
2102
2107
  <span class="context-bar-label">位置</span>
2103
2108
  <ol class="context-items" @scroll=${this.onContextScroll}>
2104
2109
  ${e?l`
2105
2110
  <li class="context-item">
2106
- <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${Xy(this.machine)} aria-label=${`机器:${t}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
2111
+ <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${r0(this.machine)} aria-label=${`机器:${t}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
2107
2112
  <span class="context-kind">机器</span>
2108
2113
  <span class="context-value">${t}</span>
2109
2114
  </button>
2110
2115
  </li>
2111
2116
  `:null}
2112
2117
  <li class="context-item">
2113
- <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${e0(this.project)} aria-label=${`项目:${i}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
2118
+ <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${n0(this.project)} aria-label=${`项目:${i}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
2114
2119
  <span class="context-kind">项目</span>
2115
2120
  <span class="context-value">${i}</span>
2116
2121
  </button>
2117
2122
  </li>
2118
2123
  <li class="context-item">
2119
- <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${i0(this.workspace)} aria-label=${`工作区:${s}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
2124
+ <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${l0(this.workspace)} aria-label=${`工作区:${s}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
2120
2125
  <span class="context-kind">工作区</span>
2121
2126
  <span class="context-value">${s}</span>
2122
2127
  </button>
2123
2128
  </li>
2124
2129
  <li class="context-item">
2125
- <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${r0(this.session)} aria-label=${`会话:${r}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
2130
+ <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${d0(this.session)} aria-label=${`会话:${r}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
2126
2131
  <span class="context-kind">会话</span>
2127
2132
  <span class="context-value">${r}</span>
2128
2133
  </button>
@@ -2162,7 +2167,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2162
2167
  .context-kind { display: none; }
2163
2168
  .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
2164
2169
  button { cursor: pointer; }
2165
- `;Re([d({attribute:!1})],de.prototype,"machines",2);Re([d({attribute:!1})],de.prototype,"machine",2);Re([d({attribute:!1})],de.prototype,"project",2);Re([d({attribute:!1})],de.prototype,"workspace",2);Re([d({attribute:!1})],de.prototype,"session",2);Re([d({attribute:!1})],de.prototype,"refreshControl",2);Re([d({attribute:!1})],de.prototype,"onOpenSection",2);Re([d({attribute:!1})],de.prototype,"onShowActions",2);Re([B(".context-items")],de.prototype,"contextItems",2);Re([y()],de.prototype,"canScrollLeft",2);Re([y()],de.prototype,"canScrollRight",2);de=Re([W("app-context-bar")],de);function Qy(e){return e.length>1}function Zy(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function Xy(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function Yy(e){return e?.name??"未选择项目"}function e0(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function t0(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function i0(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function s0(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 r0(e){return e===void 0?"未选择会话":e.path}var o0=Object.defineProperty,n0=Object.getOwnPropertyDescriptor,ft=(e,t,i,s)=>{for(var r=s>1?void 0:s?n0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&o0(t,i,r),r};let Ne=class extends A{constructor(){super(...arguments),this.tabs=[],this.selectedView="chat",this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){const e=this.fallbackLabels();return l`
2170
+ `;Ie([d({attribute:!1})],de.prototype,"machines",2);Ie([d({attribute:!1})],de.prototype,"machine",2);Ie([d({attribute:!1})],de.prototype,"project",2);Ie([d({attribute:!1})],de.prototype,"workspace",2);Ie([d({attribute:!1})],de.prototype,"session",2);Ie([d({attribute:!1})],de.prototype,"refreshControl",2);Ie([d({attribute:!1})],de.prototype,"onOpenSection",2);Ie([d({attribute:!1})],de.prototype,"onShowActions",2);Ie([B(".context-items")],de.prototype,"contextItems",2);Ie([y()],de.prototype,"canScrollLeft",2);Ie([y()],de.prototype,"canScrollRight",2);de=Ie([W("app-context-bar")],de);function i0(e){return e.length>1}function s0(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function r0(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function o0(e){return e?.name??"未选择项目"}function n0(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function a0(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function l0(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function c0(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 d0(e){return e===void 0?"未选择会话":e.path}var p0=Object.defineProperty,h0=Object.getOwnPropertyDescriptor,ft=(e,t,i,s)=>{for(var r=s>1?void 0:s?h0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&p0(t,i,r),r};let Ne=class extends A{constructor(){super(...arguments),this.tabs=[],this.selectedView="chat",this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){const e=this.fallbackLabels();return l`
2166
2171
  <div class=${this.frameClass()}>
2167
2172
  <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
2168
2173
  ${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
@@ -2174,7 +2179,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2174
2179
  `})}
2175
2180
  </div>
2176
2181
  </div>
2177
- `}frameClass(){return`mobile-tabs-frame${this.canScrollLeft?" can-scroll-left":""}${this.canScrollRight?" can-scroll-right":""}`}tabClass(e){return[...e.className===void 0?[]:[e.className],...this.selectedView===e.id?["selected"]:[]].join(" ")}tabAriaLabel(e){if(typeof e.badge!="string"&&typeof e.badge!="number")return e.label;const t=String(e.badge).trim();return t===""?e.label:`${e.label}, ${t}`}isEmptyBadge(e){return e===void 0||e===""}renderTabMark(e,t){return e.icon===void 0?l`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:Qf(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}};Ne.styles=E`
2182
+ `}frameClass(){return`mobile-tabs-frame${this.canScrollLeft?" can-scroll-left":""}${this.canScrollRight?" can-scroll-right":""}`}tabClass(e){return[...e.className===void 0?[]:[e.className],...this.selectedView===e.id?["selected"]:[]].join(" ")}tabAriaLabel(e){if(typeof e.badge!="string"&&typeof e.badge!="number")return e.label;const t=String(e.badge).trim();return t===""?e.label:`${e.label}, ${t}`}isEmptyBadge(e){return e===void 0||e===""}renderTabMark(e,t){return e.icon===void 0?l`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:eg(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}};Ne.styles=E`
2178
2183
  :host { flex: 0 0 auto; min-width: 0; }
2179
2184
  .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); }
2180
2185
  .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; }
@@ -2200,12 +2205,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2200
2205
  .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; }
2201
2206
  .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
2202
2207
  }
2203
- `;ft([d({attribute:!1})],Ne.prototype,"tabs",2);ft([d({attribute:!1})],Ne.prototype,"selectedView",2);ft([d({attribute:!1})],Ne.prototype,"onSelect",2);ft([B(".mobile-tabs")],Ne.prototype,"mobileTabs",2);ft([y()],Ne.prototype,"canScrollLeft",2);ft([y()],Ne.prototype,"canScrollRight",2);Ne=ft([W("app-mobile-main-tabs")],Ne);var a0=Object.defineProperty,l0=Object.getOwnPropertyDescriptor,me=(e,t,i,s)=>{for(var r=s>1?void 0:s?l0(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&&a0(t,i,r),r};let se=class extends A{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.open=!1,this.menuStyle="",this.actionMenuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has("machines")&&this.openActionsMachineId!==void 0&&!this.machines.some(t=>t.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){const e=this.switcherButton();return e===null?!1:await this.openMenuAndFocusOption(e)}render(){const e=this.selectedMachine();if(e===void 0)return null;const t=Os(e,this.statuses),i=e.name;return l`
2208
+ `;ft([d({attribute:!1})],Ne.prototype,"tabs",2);ft([d({attribute:!1})],Ne.prototype,"selectedView",2);ft([d({attribute:!1})],Ne.prototype,"onSelect",2);ft([B(".mobile-tabs")],Ne.prototype,"mobileTabs",2);ft([y()],Ne.prototype,"canScrollLeft",2);ft([y()],Ne.prototype,"canScrollRight",2);Ne=ft([W("app-mobile-main-tabs")],Ne);var u0=Object.defineProperty,f0=Object.getOwnPropertyDescriptor,me=(e,t,i,s)=>{for(var r=s>1?void 0:s?f0(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&&u0(t,i,r),r};let se=class extends A{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.open=!1,this.menuStyle="",this.actionMenuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has("machines")&&this.openActionsMachineId!==void 0&&!this.machines.some(t=>t.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){const e=this.switcherButton();return e===null?!1:await this.openMenuAndFocusOption(e)}render(){const e=this.selectedMachine();if(e===void 0)return null;const t=Os(e,this.statuses),i=e.name;return l`
2204
2209
  <div class="machine-switcher">
2205
2210
  <button
2206
2211
  type="button"
2207
2212
  class="machine-switcher-button"
2208
- title=${qn(e)}
2213
+ title=${Jn(e)}
2209
2214
  aria-label=${`Machine: ${i}. Switch machine.`}
2210
2215
  aria-expanded=${String(this.open)}
2211
2216
  @click=${s=>{this.toggleMenu(s.currentTarget)}}
@@ -2216,7 +2221,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2216
2221
  <span class="machine-switcher-kicker">Machine</span>
2217
2222
  <span class="machine-switcher-label">${i}</span>
2218
2223
  </span>
2219
- <span class=${`machine-status ${t}`}>${Hn(t)}</span>
2224
+ <span class=${`machine-status ${t}`}>${Gn(t)}</span>
2220
2225
  <span class="machine-chevron" aria-hidden="true">▾</span>
2221
2226
  </button>
2222
2227
  ${this.open?l`
@@ -2225,18 +2230,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2225
2230
  </div>
2226
2231
  `:null}
2227
2232
  </div>
2228
- `}renderMachineOption(e){const t=this.selected?.id===e.id,i=Os(e,this.statuses),s=hl(e)&&this.onRemove!==void 0,r=this.openActionsMachineId===e.id;return l`
2233
+ `}renderMachineOption(e){const t=this.selected?.id===e.id,i=Os(e,this.statuses),s=ml(e)&&this.onRemove!==void 0,r=this.openActionsMachineId===e.id;return l`
2229
2234
  <div class=${`machine-option ${t?"selected":""} ${s?"":"no-actions"}`}>
2230
2235
  <button
2231
2236
  type="button"
2232
2237
  class="machine-option-main"
2233
- title=${qn(e)}
2238
+ title=${Jn(e)}
2234
2239
  data-machine-id=${e.id}
2235
2240
  @click=${()=>{this.select(e)}}
2236
2241
  @keydown=${o=>{this.handleMachineOptionKeydown(o)}}
2237
2242
  >
2238
2243
  <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
2239
- <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${Hn(i)}</small>
2244
+ <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${Gn(i)}</small>
2240
2245
  </button>
2241
2246
  ${s?l`
2242
2247
  <div class="machine-option-actions">
@@ -2256,7 +2261,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2256
2261
  </div>
2257
2262
  `:null}
2258
2263
  </div>
2259
- `}renderActivity(e){const t=Os(e,this.statuses);if(t==="offline"||t==="error")return;const i=sl(this.activities[e.id]);return ol(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=Kn(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=Kn(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=nl(t,{constrainTo:"viewport"}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}};se.styles=E`
2264
+ `}renderActivity(e){const t=Os(e,this.statuses);if(t==="offline"||t==="error")return;const i=al(this.activities[e.id]);return cl(i,i==="terminal"?"Machine terminal active":"Machine active")}selectedMachine(){return this.selected??this.machines.find(e=>e.id==="local")??this.machines[0]}switcherButton(){return this.renderRoot.querySelector(".machine-switcher-button")}handleSwitcherButtonKeydown(e){if(e.key==="ArrowDown"||e.key==="ArrowUp"){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key==="Escape"&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key==="ArrowUp"){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key==="ArrowDown"){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key==="Home"){this.focusIndexedMachineOption(0,e);return}if(e.key==="End"){this.focusIndexedMachineOption(-1,e);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key==="ArrowLeft"||e.key==="Escape")&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=Qn(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=Qn(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=dl(t,{constrainTo:"viewport"}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}};se.styles=E`
2260
2265
  :host { min-width: 0; display: block; }
2261
2266
  .machine-switcher { min-width: 0; }
2262
2267
  .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; }
@@ -2289,7 +2294,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2289
2294
  .machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
2290
2295
  .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); }
2291
2296
  @keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
2292
- `;me([d({attribute:!1})],se.prototype,"machines",2);me([d({attribute:!1})],se.prototype,"selected",2);me([d({attribute:!1})],se.prototype,"statuses",2);me([d({attribute:!1})],se.prototype,"activities",2);me([d({attribute:!1})],se.prototype,"onSelect",2);me([d({attribute:!1})],se.prototype,"onRemove",2);me([d({attribute:!1})],se.prototype,"onFocusNextSection",2);me([d({attribute:!1})],se.prototype,"onCancelKeyboardNavigation",2);me([y()],se.prototype,"open",2);me([y()],se.prototype,"menuStyle",2);me([y()],se.prototype,"openActionsMachineId",2);me([y()],se.prototype,"actionMenuStyle",2);se=me([W("machine-switcher")],se);function Os(e,t){return t[e.id]?.status??e.status??"unknown"}function Hn(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function qn(e){return e.baseUrl??e.name}function Kn(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: ${di(t.bottom)};`,`left: ${di(r)};`,`width: ${di(s)};`,`max-height: ${di(o)};`].join(" ")}function di(e){return`${String(Math.round(e))}px`}var c0=Object.defineProperty,d0=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var r=s>1?void 0:s?d0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&c0(t,i,r),r};let S=class extends A{constructor(){super(...arguments),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canCleanupSessions=!1,this.archivedDeleteUnavailableMessage="Update and restart Pi-Web on this machine to delete archived sessions.",this.cleanupUnavailableMessage="Update and restart Pi-Web on this machine to clean up sessions."}async focusSection(e){switch(await this.updateComplete,e){case"machines":return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case"projects":return await this.focusNavigableSection(this.projectList);case"workspaces":return await this.focusNavigableSection(this.workspaceList);case"sessions":return await this.focusNavigableSection(this.sessionList)}}render(){return l`
2297
+ `;me([d({attribute:!1})],se.prototype,"machines",2);me([d({attribute:!1})],se.prototype,"selected",2);me([d({attribute:!1})],se.prototype,"statuses",2);me([d({attribute:!1})],se.prototype,"activities",2);me([d({attribute:!1})],se.prototype,"onSelect",2);me([d({attribute:!1})],se.prototype,"onRemove",2);me([d({attribute:!1})],se.prototype,"onFocusNextSection",2);me([d({attribute:!1})],se.prototype,"onCancelKeyboardNavigation",2);me([y()],se.prototype,"open",2);me([y()],se.prototype,"menuStyle",2);me([y()],se.prototype,"openActionsMachineId",2);me([y()],se.prototype,"actionMenuStyle",2);se=me([W("machine-switcher")],se);function Os(e,t){return t[e.id]?.status??e.status??"unknown"}function Gn(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function Jn(e){return e.baseUrl??e.name}function Qn(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: ${di(t.bottom)};`,`left: ${di(r)};`,`width: ${di(s)};`,`max-height: ${di(o)};`].join(" ")}function di(e){return`${String(Math.round(e))}px`}var g0=Object.defineProperty,m0=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var r=s>1?void 0:s?m0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&g0(t,i,r),r};let S=class extends A{constructor(){super(...arguments),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canCleanupSessions=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.cleanupUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。"}async focusSection(e){switch(await this.updateComplete,e){case"machines":return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case"projects":return await this.focusNavigableSection(this.projectList);case"workspaces":return await this.focusNavigableSection(this.workspaceList);case"sessions":return await this.focusNavigableSection(this.sessionList)}}render(){return l`
2293
2298
  <header>
2294
2299
  <strong>PI WEB</strong>
2295
2300
  ${qi(this.machines)?l`
@@ -2385,7 +2390,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2385
2390
  .onFocusNextSection=${()=>{this.focusNextFrom("sessions")}}
2386
2391
  .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2387
2392
  ></session-list>
2388
- `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=p0(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(h0(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};S.styles=E`
2393
+ `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=v0(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(b0(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};S.styles=E`
2389
2394
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
2390
2395
  :host([compact]) { flex: 1 1 auto; }
2391
2396
  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); }
@@ -2408,7 +2413,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2408
2413
  :host([compact]) workspace-list[collapsed],
2409
2414
  :host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
2410
2415
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2411
- `;k([d({attribute:!1})],S.prototype,"machines",2);k([d({attribute:!1})],S.prototype,"selectedMachine",2);k([d({attribute:!1})],S.prototype,"machineStatuses",2);k([d({attribute:!1})],S.prototype,"machineActivities",2);k([d({attribute:!1})],S.prototype,"projects",2);k([d({attribute:!1})],S.prototype,"selectedProject",2);k([d({attribute:!1})],S.prototype,"workspaces",2);k([d({attribute:!1})],S.prototype,"selectedWorkspace",2);k([d({attribute:!1})],S.prototype,"sessions",2);k([d({attribute:!1})],S.prototype,"selectedSession",2);k([d({attribute:!1})],S.prototype,"workspaceActivities",2);k([d({attribute:!1})],S.prototype,"sessionActivities",2);k([d({attribute:!1})],S.prototype,"sessionStatuses",2);k([d({attribute:!1})],S.prototype,"sendingPrompts",2);k([d({attribute:!1})],S.prototype,"workspacesByProjectId",2);k([d({attribute:!1})],S.prototype,"deletingWorkspaceIds",2);k([d({attribute:!1})],S.prototype,"workspaceLabelItems",2);k([d({attribute:!1})],S.prototype,"refreshControl",2);k([d({type:Boolean,reflect:!0})],S.prototype,"collapsible",2);k([d({type:Boolean,reflect:!0})],S.prototype,"compact",2);k([d({type:Boolean})],S.prototype,"machinesCollapsed",2);k([d({type:Boolean})],S.prototype,"projectsCollapsed",2);k([d({type:Boolean})],S.prototype,"workspacesCollapsed",2);k([d({type:Boolean})],S.prototype,"sessionsCollapsed",2);k([d({type:Boolean})],S.prototype,"canStartSession",2);k([d({type:Boolean})],S.prototype,"canDeleteArchivedSessions",2);k([d({type:Boolean})],S.prototype,"canReloadSessions",2);k([d({type:Boolean})],S.prototype,"canCleanupSessions",2);k([d({type:String})],S.prototype,"archivedDeleteUnavailableMessage",2);k([d({type:String})],S.prototype,"cleanupUnavailableMessage",2);k([d({attribute:!1})],S.prototype,"onShowActions",2);k([d({attribute:!1})],S.prototype,"onToggleMachines",2);k([d({attribute:!1})],S.prototype,"onToggleProjects",2);k([d({attribute:!1})],S.prototype,"onToggleWorkspaces",2);k([d({attribute:!1})],S.prototype,"onToggleSessions",2);k([d({attribute:!1})],S.prototype,"onSelectProject",2);k([d({attribute:!1})],S.prototype,"onCloseProject",2);k([d({attribute:!1})],S.prototype,"onSelectWorkspace",2);k([d({attribute:!1})],S.prototype,"onDeleteWorkspace",2);k([d({attribute:!1})],S.prototype,"onStartSession",2);k([d({attribute:!1})],S.prototype,"onSelectSession",2);k([d({attribute:!1})],S.prototype,"onArchiveSession",2);k([d({attribute:!1})],S.prototype,"onArchiveSessionWithDescendants",2);k([d({attribute:!1})],S.prototype,"onArchiveSessions",2);k([d({attribute:!1})],S.prototype,"onRestoreSession",2);k([d({attribute:!1})],S.prototype,"onDeleteCachedNewSession",2);k([d({attribute:!1})],S.prototype,"onDeleteArchivedSession",2);k([d({attribute:!1})],S.prototype,"onDeleteArchivedSessions",2);k([d({attribute:!1})],S.prototype,"onDetachParentSession",2);k([d({attribute:!1})],S.prototype,"onReloadSession",2);k([d({attribute:!1})],S.prototype,"onCleanupSessions",2);k([d({attribute:!1})],S.prototype,"onArchivedCollapsed",2);k([d({attribute:!1})],S.prototype,"onSelectMachine",2);k([d({attribute:!1})],S.prototype,"onRemoveMachine",2);k([d({attribute:!1})],S.prototype,"onFocusNavigationTarget",2);k([d({attribute:!1})],S.prototype,"onCancelKeyboardNavigation",2);k([B("machine-list")],S.prototype,"machineList",2);k([B("machine-switcher")],S.prototype,"machineSwitcher",2);k([B("project-list")],S.prototype,"projectList",2);k([B("workspace-list")],S.prototype,"workspaceList",2);k([B("session-list")],S.prototype,"sessionList",2);S=k([W("app-navigation-panel")],S);function qi(e){return e.length>1}function p0(e,t){const i=Ll(t);return i[i.indexOf(e)-1]}function h0(e,t){const i=Ll(t);return i[i.indexOf(e)+1]??"chat"}function Ll(e){return ji.filter(t=>t!=="machines"||qi(e))}var u0=Object.defineProperty,f0=Object.getOwnPropertyDescriptor,ee=(e,t,i,s)=>{for(var r=s>1?void 0:s?f0(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&&u0(t,i,r),r};const g0=new Set(["ArrowLeft","ArrowRight","Home","End"]),m0=420,v0=4;let K=class extends A{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.resizable=!1,this.controls="",this.resizeLabel="调整面板宽度",this.expandLabel="展开面板",this.collapseLabel="折叠面板",this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
2416
+ `;k([d({attribute:!1})],S.prototype,"machines",2);k([d({attribute:!1})],S.prototype,"selectedMachine",2);k([d({attribute:!1})],S.prototype,"machineStatuses",2);k([d({attribute:!1})],S.prototype,"machineActivities",2);k([d({attribute:!1})],S.prototype,"projects",2);k([d({attribute:!1})],S.prototype,"selectedProject",2);k([d({attribute:!1})],S.prototype,"workspaces",2);k([d({attribute:!1})],S.prototype,"selectedWorkspace",2);k([d({attribute:!1})],S.prototype,"sessions",2);k([d({attribute:!1})],S.prototype,"selectedSession",2);k([d({attribute:!1})],S.prototype,"workspaceActivities",2);k([d({attribute:!1})],S.prototype,"sessionActivities",2);k([d({attribute:!1})],S.prototype,"sessionStatuses",2);k([d({attribute:!1})],S.prototype,"sendingPrompts",2);k([d({attribute:!1})],S.prototype,"workspacesByProjectId",2);k([d({attribute:!1})],S.prototype,"deletingWorkspaceIds",2);k([d({attribute:!1})],S.prototype,"workspaceLabelItems",2);k([d({attribute:!1})],S.prototype,"refreshControl",2);k([d({type:Boolean,reflect:!0})],S.prototype,"collapsible",2);k([d({type:Boolean,reflect:!0})],S.prototype,"compact",2);k([d({type:Boolean})],S.prototype,"machinesCollapsed",2);k([d({type:Boolean})],S.prototype,"projectsCollapsed",2);k([d({type:Boolean})],S.prototype,"workspacesCollapsed",2);k([d({type:Boolean})],S.prototype,"sessionsCollapsed",2);k([d({type:Boolean})],S.prototype,"canStartSession",2);k([d({type:Boolean})],S.prototype,"canDeleteArchivedSessions",2);k([d({type:Boolean})],S.prototype,"canReloadSessions",2);k([d({type:Boolean})],S.prototype,"canCleanupSessions",2);k([d({type:String})],S.prototype,"archivedDeleteUnavailableMessage",2);k([d({type:String})],S.prototype,"cleanupUnavailableMessage",2);k([d({attribute:!1})],S.prototype,"onShowActions",2);k([d({attribute:!1})],S.prototype,"onToggleMachines",2);k([d({attribute:!1})],S.prototype,"onToggleProjects",2);k([d({attribute:!1})],S.prototype,"onToggleWorkspaces",2);k([d({attribute:!1})],S.prototype,"onToggleSessions",2);k([d({attribute:!1})],S.prototype,"onSelectProject",2);k([d({attribute:!1})],S.prototype,"onCloseProject",2);k([d({attribute:!1})],S.prototype,"onSelectWorkspace",2);k([d({attribute:!1})],S.prototype,"onDeleteWorkspace",2);k([d({attribute:!1})],S.prototype,"onStartSession",2);k([d({attribute:!1})],S.prototype,"onSelectSession",2);k([d({attribute:!1})],S.prototype,"onArchiveSession",2);k([d({attribute:!1})],S.prototype,"onArchiveSessionWithDescendants",2);k([d({attribute:!1})],S.prototype,"onArchiveSessions",2);k([d({attribute:!1})],S.prototype,"onRestoreSession",2);k([d({attribute:!1})],S.prototype,"onDeleteCachedNewSession",2);k([d({attribute:!1})],S.prototype,"onDeleteArchivedSession",2);k([d({attribute:!1})],S.prototype,"onDeleteArchivedSessions",2);k([d({attribute:!1})],S.prototype,"onDetachParentSession",2);k([d({attribute:!1})],S.prototype,"onReloadSession",2);k([d({attribute:!1})],S.prototype,"onCleanupSessions",2);k([d({attribute:!1})],S.prototype,"onArchivedCollapsed",2);k([d({attribute:!1})],S.prototype,"onSelectMachine",2);k([d({attribute:!1})],S.prototype,"onRemoveMachine",2);k([d({attribute:!1})],S.prototype,"onFocusNavigationTarget",2);k([d({attribute:!1})],S.prototype,"onCancelKeyboardNavigation",2);k([B("machine-list")],S.prototype,"machineList",2);k([B("machine-switcher")],S.prototype,"machineSwitcher",2);k([B("project-list")],S.prototype,"projectList",2);k([B("workspace-list")],S.prototype,"workspaceList",2);k([B("session-list")],S.prototype,"sessionList",2);S=k([W("app-navigation-panel")],S);function qi(e){return e.length>1}function v0(e,t){const i=zl(t);return i[i.indexOf(e)-1]}function b0(e,t){const i=zl(t);return i[i.indexOf(e)+1]??"chat"}function zl(e){return ji.filter(t=>t!=="machines"||qi(e))}var w0=Object.defineProperty,y0=Object.getOwnPropertyDescriptor,ee=(e,t,i,s)=>{for(var r=s>1?void 0:s?y0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&w0(t,i,r),r};const x0=new Set(["ArrowLeft","ArrowRight","Home","End"]),S0=420,k0=4;let K=class extends A{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.resizable=!1,this.controls="",this.resizeLabel="调整面板宽度",this.expandLabel="展开面板",this.collapseLabel="折叠面板",this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
2412
2417
  ${this.renderResizeHandle()}
2413
2418
  <button
2414
2419
  type="button"
@@ -2438,7 +2443,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2438
2443
  @dblclick=${t=>{this.onResizeDoubleClick(t)}}
2439
2444
  @keydown=${t=>{this.onResizeKeyDown(t)}}
2440
2445
  ></div>
2441
- `}resizeAriaValueNow(){return this.panelWidth===void 0?z:String(Math.round(this.panelWidth))}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return l`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${t}/></svg>`}iconDirection(){return this.side==="navigation"?this.collapsed?"right":"left":this.collapsed?"left":"right"}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=this.resizeStartWidth();i!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:i,handle:t,moved:!1},this.toggleAttribute("resizing",!0))}onResizePointerMove(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=v0)&&(t.moved=!0,this.commitPanelWidth(wm(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||!g0.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=ym(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<=m0){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){const e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return we(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(we(this.side,e,this.resizeConstraints()))}finishActiveResize(){const e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute("resizing",!1),this.onResizeEnd?.()}}resizeConstraints(){const e=Xt(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};K.styles=E`
2446
+ `}resizeAriaValueNow(){return this.panelWidth===void 0?z:String(Math.round(this.panelWidth))}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return l`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${t}/></svg>`}iconDirection(){return this.side==="navigation"?this.collapsed?"right":"left":this.collapsed?"left":"right"}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=this.resizeStartWidth();i!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:i,handle:t,moved:!1},this.toggleAttribute("resizing",!0))}onResizePointerMove(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=k0)&&(t.moved=!0,this.commitPanelWidth(Pm(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||!x0.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=Cm(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<=S0){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){const e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return we(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(we(this.side,e,this.resizeConstraints()))}finishActiveResize(){const e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute("resizing",!1),this.onResizeEnd?.()}}resizeConstraints(){const e=Xt(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};K.styles=E`
2442
2447
  :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; }
2443
2448
  :host([side="navigation"]) { grid-column: 2; }
2444
2449
  :host([side="workspace"]) { grid-column: 4; }
@@ -2457,7 +2462,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2457
2462
  @media (max-width: 760px) {
2458
2463
  :host([side="navigation"]) { display: none; }
2459
2464
  }
2460
- `;ee([d({reflect:!0})],K.prototype,"side",2);ee([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);ee([d({type:Boolean})],K.prototype,"resizable",2);ee([d({type:Number})],K.prototype,"panelWidth",2);ee([d({type:Number})],K.prototype,"minWidth",2);ee([d({type:Number})],K.prototype,"maxWidth",2);ee([d()],K.prototype,"controls",2);ee([d()],K.prototype,"resizeLabel",2);ee([d()],K.prototype,"expandLabel",2);ee([d()],K.prototype,"collapseLabel",2);ee([d({attribute:!1})],K.prototype,"onToggle",2);ee([d({attribute:!1})],K.prototype,"onResizeStart",2);ee([d({attribute:!1})],K.prototype,"onResize",2);ee([d({attribute:!1})],K.prototype,"onResizeEnd",2);ee([d({attribute:!1})],K.prototype,"onReset",2);K=ee([W("app-panel-edge-control")],K);var b0=Object.defineProperty,w0=Object.getOwnPropertyDescriptor,jl=(e,t,i,s)=>{for(var r=s>1?void 0:s?w0(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&&b0(t,i,r),r};let Ki=class extends A{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="完整重载页面";return l`
2465
+ `;ee([d({reflect:!0})],K.prototype,"side",2);ee([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);ee([d({type:Boolean})],K.prototype,"resizable",2);ee([d({type:Number})],K.prototype,"panelWidth",2);ee([d({type:Number})],K.prototype,"minWidth",2);ee([d({type:Number})],K.prototype,"maxWidth",2);ee([d()],K.prototype,"controls",2);ee([d()],K.prototype,"resizeLabel",2);ee([d()],K.prototype,"expandLabel",2);ee([d()],K.prototype,"collapseLabel",2);ee([d({attribute:!1})],K.prototype,"onToggle",2);ee([d({attribute:!1})],K.prototype,"onResizeStart",2);ee([d({attribute:!1})],K.prototype,"onResize",2);ee([d({attribute:!1})],K.prototype,"onResizeEnd",2);ee([d({attribute:!1})],K.prototype,"onReset",2);K=ee([W("app-panel-edge-control")],K);var $0=Object.defineProperty,P0=Object.getOwnPropertyDescriptor,Bl=(e,t,i,s)=>{for(var r=s>1?void 0:s?P0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&$0(t,i,r),r};let Ki=class extends A{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="完整重载页面";return l`
2461
2466
  <button
2462
2467
  class="app-refresh-button"
2463
2468
  title=${e}
@@ -2476,7 +2481,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2476
2481
  :host, :host * { -webkit-user-select: none; user-select: none; }
2477
2482
  .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; }
2478
2483
  .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
2479
- `;jl([d({attribute:!1})],Ki.prototype,"onReload",2);Ki=jl([W("app-refresh-control")],Ki);var y0=Object.defineProperty,x0=Object.getOwnPropertyDescriptor,ve=(e,t,i,s)=>{for(var r=s>1?void 0:s?x0(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&&y0(t,i,r),r};const S0=E`
2484
+ `;Bl([d({attribute:!1})],Ki.prototype,"onReload",2);Ki=Bl([W("app-refresh-control")],Ki);var C0=Object.defineProperty,I0=Object.getOwnPropertyDescriptor,ve=(e,t,i,s)=>{for(var r=s>1?void 0:s?I0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&C0(t,i,r),r};const R0=E`
2480
2485
  /* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
2481
2486
  :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; }
2482
2487
  :host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
@@ -2575,7 +2580,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2575
2580
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2576
2581
  .empty { margin: auto; color: var(--pi-muted); }
2577
2582
  .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
2578
- `,k0=900*1e3,$0=750,ar=[1e3,3e3,8e3,15e3,3e4],Vn={capture:!0},_s="auto:on",Gn="auto:off",pi="theme:",Ls=Gt("core:workspace.files"),js=Gt("core:workspace.git"),hi=Gt("core:workspace.terminal"),P0=320,C0=2,R0="(min-width: 1181px)";let re=class extends A{constructor(){super(...arguments),this.state=Wp(),this.sessions=new Mu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Pu),this.activity=new Op(()=>this.state,e=>{this.setState(e)}),this.auth=new jp(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new qu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Nu),this.projects=new Xp(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Zp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new Kp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Qp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new of,this.realtime=new Fo,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Ju,this.terminalSelection=new sf,this.appShell=new im(this),this.panelCollapse=new gm(this),this.panelResize=new vm(this),this.navigationSections=new hm(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=I0(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=$f()??xf,this.activeThemeId=Tr,this.isRefreshingApp=!1,this.settingsSection=pn(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=ko(void 0),this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.previousStackedWorkspaceLayout=this.appShell.isStackedWorkspaceLayout,this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,i,s)=>{this.sendPrompt(e,t,i,s)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode),this.normalizeMainViewForLayoutChange()}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,Vn),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},k0),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,Vn),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(!M0(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),A0(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=dn();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=$0){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 ba.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=>Fl(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 Ri.config()).effectiveConfig)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=ko(e)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(dn(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const r=f(this.state),o=e.projectId===void 0||e.projectId===""?Zn():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=o.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(n))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:this.appShell.normalizedMainView(s??e.view,e.sessionId!==void 0),selectedFilePath:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const c=this.state.projects.find(p=>p.id===e.projectId);if(!c){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(c,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),f(this.state)!==r&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?Zn():{selectedFilePath:ms(Ls,"file"),selectedDiffPath:ms(js,"diff"),selectedTerminalId:ms(hi,"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){ks(e,{replace:!0}),he(Ls,"file",void 0,{replace:!0}),he(js,"diff",void 0,{replace:!0}),he(hi,"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=D0(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>=ar.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",o=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),n=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${n}${o===void 0?"":` ${o}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(r=>r.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await Us(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}normalizeMainViewForLayoutChange(){const e=this.previousStackedWorkspaceLayout,t=this.appShell.isStackedWorkspaceLayout;if(this.previousStackedWorkspaceLayout=t,e||!t)return;const i=this.appShell.normalizedMainView(this.state.mainView,this.state.selectedSession!==void 0);i!==this.state.mainView&&(this.setState({mainView:i}),this.updateUrl({replace:!0}))}updateUrl(e){this.rememberCurrentMachineNavigation(),ks({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(No(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(No(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){ks(Ho(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){he(Ls,"file",e.selectedFilePath,{replace:!0}),he(js,"diff",e.selectedDiffPath,{replace:!0}),he(hi,"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)??Qu(e.id);if(await this.restoreRouteFor(Ho(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=Xn(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const r=Wm(e,{api:{runTerminalCommand:(o,n)=>yt.runTerminalCommand(o,n,t),listCommandRuns:o=>yt.listCommandRuns(o,t),getCommandRun:o=>yt.getCommandRun(o,t)},openTerminal:(o,n)=>{this.openRuntimeTerminal(t,o,n)}});return this.terminalCommandRunRuntimes.set(i,r),r}async openRuntimeTerminal(e,t,i){if((f(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:"core:workspace.terminal",view:"core:workspace.terminal"},!1,{selectedTerminalId:i?.terminalId},"core:workspace.terminal"),f(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){he(hi,"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,$s(e)}closeSettings(){this.settingsSection=void 0,$s(void 0)}navigateSettings(e){this.settingsSection=e,$s(e)}restoreSettingsRoute(){this.settingsSection=pn()}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 Fo;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=>T0(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):E0(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const t=this.state.selectedWorkspace;t===void 0||(e.type==="terminal.closed"?e.cwd:e.terminal.cwd)!==t.path||(e.type==="terminal.created"&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type==="terminal.closed"?e.terminalId:e.terminal.id),e.type==="terminal.closed"&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){const t=f(this.state);try{const i=await yt.terminals(e.projectId,e.id,t);if(f(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=Qn(e),s=Qn(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return l`
2583
+ `,A0=900*1e3,T0=750,ar=[1e3,3e3,8e3,15e3,3e4],Zn={capture:!0},_s="auto:on",Xn="auto:off",pi="theme:",Ls=Gt("core:workspace.files"),js=Gt("core:workspace.git"),hi=Gt("core:workspace.terminal"),M0=320,E0=2,D0="(min-width: 1181px)";let re=class extends A{constructor(){super(...arguments),this.state=jp(),this.sessions=new Ou(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Au),this.activity=new Fp(()=>this.state,e=>{this.setState(e)}),this.auth=new Bp(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Ju(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Vu),this.projects=new ih(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new th(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new Qp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new eh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new cf,this.realtime=new Fo,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Yu,this.terminalSelection=new af,this.appShell=new lm(this),this.panelCollapse=new xm(this),this.panelResize=new km(this),this.navigationSections=new bm(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=W0(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Rf()??Pf,this.activeThemeId=Tr,this.isRefreshingApp=!1,this.settingsSection=gn(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=ko(void 0),this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.previousStackedWorkspaceLayout=this.appShell.isStackedWorkspaceLayout,this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,i,s)=>{this.sendPrompt(e,t,i,s)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode),this.normalizeMainViewForLayoutChange()}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,Zn),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},A0),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,Zn),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(!L0(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),O0(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=fn();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=T0){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 Sa.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=>Nl(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await Ii.config()).effectiveConfig)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=ko(e)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(fn(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const r=f(this.state),o=e.projectId===void 0||e.projectId===""?ta():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=o.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(n))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:this.appShell.normalizedMainView(s??e.view,e.sessionId!==void 0),selectedFilePath:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const c=this.state.projects.find(p=>p.id===e.projectId);if(!c){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(c,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),f(this.state)!==r&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?ta():{selectedFilePath:ms(Ls,"file"),selectedDiffPath:ms(js,"diff"),selectedTerminalId:ms(hi,"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){ks(e,{replace:!0}),he(Ls,"file",void 0,{replace:!0}),he(js,"diff",void 0,{replace:!0}),he(hi,"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=F0(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>=ar.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",o=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),n=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${n}${o===void 0?"":` ${o}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(r=>r.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await Us(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}normalizeMainViewForLayoutChange(){const e=this.previousStackedWorkspaceLayout,t=this.appShell.isStackedWorkspaceLayout;if(this.previousStackedWorkspaceLayout=t,e||!t)return;const i=this.appShell.normalizedMainView(this.state.mainView,this.state.selectedSession!==void 0);i!==this.state.mainView&&(this.setState({mainView:i}),this.updateUrl({replace:!0}))}updateUrl(e){this.rememberCurrentMachineNavigation(),ks({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(No(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(No(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){ks(Ho(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){he(Ls,"file",e.selectedFilePath,{replace:!0}),he(js,"diff",e.selectedDiffPath,{replace:!0}),he(hi,"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)??ef(e.id);if(await this.restoreRouteFor(Ho(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=ia(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const r=Um(e,{api:{runTerminalCommand:(o,n)=>yt.runTerminalCommand(o,n,t),listCommandRuns:o=>yt.listCommandRuns(o,t),getCommandRun:o=>yt.getCommandRun(o,t)},openTerminal:(o,n)=>{this.openRuntimeTerminal(t,o,n)}});return this.terminalCommandRunRuntimes.set(i,r),r}async openRuntimeTerminal(e,t,i){if((f(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:"core:workspace.terminal",view:"core:workspace.terminal"},!1,{selectedTerminalId:i?.terminalId},"core:workspace.terminal"),f(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){he(hi,"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,$s(e)}closeSettings(){this.settingsSection=void 0,$s(void 0)}navigateSettings(e){this.settingsSection=e,$s(e)}restoreSettingsRoute(){this.settingsSection=gn()}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 Fo;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=>_0(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):j0(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const t=this.state.selectedWorkspace;t===void 0||(e.type==="terminal.closed"?e.cwd:e.terminal.cwd)!==t.path||(e.type==="terminal.created"&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type==="terminal.closed"?e.terminalId:e.terminal.id),e.type==="terminal.closed"&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){const t=f(this.state);try{const i=await yt.terminals(e.projectId,e.id,t);if(f(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=ea(e),s=ea(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return l`
2579
2584
  <workspace-panel
2580
2585
  id="workspace-panel"
2581
2586
  .workspace=${e}
@@ -2621,7 +2626,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2621
2626
  .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
2622
2627
  .onReset=${()=>{this.resetResizablePanel("workspace")}}
2623
2628
  ></app-panel-edge-control>
2624
- `}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-C0-P0);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(R0).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&&at(e,Qe.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&at(e,Qe.sessionsReload)}canCleanupSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&at(e,Qe.sessionsCleanup)}supportsWorkspaceFileSuggestions(e=f(this.state)){if(e==="local")return!0;const t=this.state.machineRuntimes[e];return t?.ok===!0&&at(t,Qe.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??"this machine"} to delete archived sessions.`}sessionCleanupUnavailableMessage(){return wf(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[f(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:""}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}const t=f(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:"",preview:void 0,previewRequest:void 0,result:void 0};try{const i=await Ks.cleanupPreview(e,t);if(f(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:i,previewRequest:e,result:void 0,loading:!1,error:""}}catch(i){f(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${Fs(i)}`})}}async runSessionCleanup(e){const t=this.sessionCleanupDialog;if(t?.preview===void 0||kt(t.previewRequest)!==kt(e)){this.sessionCleanupDialog={...t??{},error:"Preview cleanup before running it."};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}const i=f(this.state);this.sessionCleanupDialog={...t,running:!0,error:""};try{const s=await Ks.cleanup(e,i);if(f(this.state)!==i)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:s,previewRequest:e,result:s,running:!1,error:""},await this.sessions.applySessionCleanupResult(s,i)}catch(s){f(this.state)===i&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${Fs(s)}`})}}renderNavigationPanel(){return l`
2629
+ `}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-E0-M0);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(D0).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&&at(e,Qe.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&at(e,Qe.sessionsReload)}canCleanupSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&at(e,Qe.sessionsCleanup)}supportsWorkspaceFileSuggestions(e=f(this.state)){if(e==="local")return!0;const t=this.state.machineRuntimes[e];return t?.ok===!0&&at(t,Qe.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`请更新并重启 ${this.state.selectedMachine?.name??"此机器"} 上的 Pi-Web 后再删除已归档会话。`}sessionCleanupUnavailableMessage(){return kf(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[f(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:""}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}const t=f(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:"",preview:void 0,previewRequest:void 0,result:void 0};try{const i=await Ks.cleanupPreview(e,t);if(f(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:i,previewRequest:e,result:void 0,loading:!1,error:""}}catch(i){f(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`预览清理失败:${Fs(i)}`})}}async runSessionCleanup(e){const t=this.sessionCleanupDialog;if(t?.preview===void 0||kt(t.previewRequest)!==kt(e)){this.sessionCleanupDialog={...t??{},error:"运行清理前请先预览。"};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}const i=f(this.state);this.sessionCleanupDialog={...t,running:!0,error:""};try{const s=await Ks.cleanup(e,i);if(f(this.state)!==i)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:s,previewRequest:e,result:s,running:!1,error:""},await this.sessions.applySessionCleanupResult(s,i)}catch(s){f(this.state)===i&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`运行清理失败:${Fs(s)}`})}}renderNavigationPanel(){return l`
2625
2630
  <app-navigation-panel
2626
2631
  .machines=${this.state.machines}
2627
2632
  .selectedMachine=${this.state.selectedMachine}
@@ -2637,7 +2642,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2637
2642
  .workspacesByProjectId=${this.state.workspacesByProjectId}
2638
2643
  .workspaces=${this.state.workspaces}
2639
2644
  .selectedWorkspace=${this.state.selectedWorkspace}
2640
- .deletingWorkspaceIds=${Bf(this.state.workspaceDeletionRuns)}
2645
+ .deletingWorkspaceIds=${Kf(this.state.workspaceDeletionRuns)}
2641
2646
  .sessions=${this.state.sessions}
2642
2647
  .sessionStatuses=${this.state.sessionStatuses}
2643
2648
  .sessionActivities=${this.state.sessionActivities}
@@ -2680,14 +2685,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2680
2685
  .onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
2681
2686
  .onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
2682
2687
  ></app-navigation-panel>
2683
- `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){const s=++this.navigationSelectionSeq,r=()=>s===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()},r),r()&&await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!qi(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 Us(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await Us(),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=Jn(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:i=>wt.workspaceFile(e.projectId,e.id,i,t),writeFile:async(i,s,r)=>{const o=await wt.writeWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o},deleteFile:async i=>{const s=await wt.deleteWorkspaceFile(e.projectId,e.id,i,t);return this.files.refreshFiles(),s},moveFile:async(i,s,r)=>{const o=await wt.moveWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=Jn(this.state),i=t.id,s=r=>{const o=this.terminalCommandRunsForOrigin(r,i);return Ng({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),prompt:this.createPromptEditor(),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>o.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:o},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:yp(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onCreateFile:n=>{this.files.createFile(n)},onCreateDirectory:n=>{this.files.createDirectory(n)},onMoveSelectedPath:n=>{this.files.moveSelectedPath(n)},onDeleteSelectedPath:()=>{this.files.deleteSelectedPath()},onDownloadSelectedFile:()=>{this.files.downloadSelectedFile()},onExpandDir:n=>{this.files.expandDir(n)},onSelectDirectory:n=>{this.files.selectDirectory(n)},onSelectFile:n=>{this.files.selectFile(n)},onStartWorkspaceUpload:(n,a)=>this.files.startWorkspaceUpload(n,a),onCancelWorkspaceUpload:n=>{this.files.cancelWorkspaceUpload(n)},onClearWorkspaceUpload:n=>{this.files.clearWorkspaceUpload(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return Em(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}sessionActions(){return[{id:"app.sessions.cleanup",title:"Clean Up Sessions",description:"Preview and manually clean up idle or archived sessions on the selected machine",group:"Sessions",...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"重置导航面板宽度",description:"将导航面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"重置工作区面板宽度",description:"将工作区面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"重置面板宽度",description:"将所有侧边面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"聚焦机器",description:"将键盘焦点移到机器选择器",shortcut:"mod+g m",group:"导航",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"聚焦项目",description:"将键盘焦点移到项目列表",shortcut:"mod+g p",group:"导航",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"聚焦工作区",description:"将键盘焦点移到工作区列表",shortcut:"mod+g w",group:"导航",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"聚焦会话",description:"将键盘焦点移到会话列表",shortcut:"mod+g s",group:"导航",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>nn())}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}`,()=>nn(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:s=>this.plugins.shouldLoadRemotePlugin(s.id,s.machineSpecific)})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(r){console.warn(`Failed to register PI WEB plugin ${s.id}`,r)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPromptEditor(){return{insertText:e=>{const t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();const i=t.state.selection.main;t.dispatch({changes:{from:i.from,to:i.to,insert:e},selection:{anchor:i.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??"",getSelection:()=>{const e=this.promptEditor?.view;if(!e)return null;const t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){const e=t=>Bg({state:this.state,prompt:this.createPromptEditor(),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Ku(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(Ja(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
2688
+ `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){const s=++this.navigationSelectionSeq,r=()=>s===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()},r),r()&&await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!qi(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 Us(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await Us(),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=Yn(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:i=>wt.workspaceFile(e.projectId,e.id,i,t),writeFile:async(i,s,r)=>{const o=await wt.writeWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o},deleteFile:async i=>{const s=await wt.deleteWorkspaceFile(e.projectId,e.id,i,t);return this.files.refreshFiles(),s},moveFile:async(i,s,r)=>{const o=await wt.moveWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=Yn(this.state),i=t.id,s=r=>{const o=this.terminalCommandRunsForOrigin(r,i);return Jg({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),prompt:this.createPromptEditor(),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>o.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:o},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:$p(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onCreateFile:n=>{this.files.createFile(n)},onCreateDirectory:n=>{this.files.createDirectory(n)},onMoveSelectedPath:n=>{this.files.moveSelectedPath(n)},onDeleteSelectedPath:()=>{this.files.deleteSelectedPath()},onDownloadSelectedFile:()=>{this.files.downloadSelectedFile()},onExpandDir:n=>{this.files.expandDir(n)},onSelectDirectory:n=>{this.files.selectDirectory(n)},onSelectFile:n=>{this.files.selectFile(n)},onStartWorkspaceUpload:(n,a)=>this.files.startWorkspaceUpload(n,a),onCancelWorkspaceUpload:n=>{this.files.cancelWorkspaceUpload(n)},onClearWorkspaceUpload:n=>{this.files.clearWorkspaceUpload(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return jm(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}sessionActions(){return[{id:"app.sessions.cleanup",title:"清理会话",description:"预览并手动清理所选机器上的空闲或已归档会话",group:"Sessions",...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"重置导航面板宽度",description:"将导航面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"重置工作区面板宽度",description:"将工作区面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"重置面板宽度",description:"将所有侧边面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"聚焦机器",description:"将键盘焦点移到机器选择器",shortcut:"mod+g m",group:"导航",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"聚焦项目",description:"将键盘焦点移到项目列表",shortcut:"mod+g p",group:"导航",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"聚焦工作区",description:"将键盘焦点移到工作区列表",shortcut:"mod+g w",group:"导航",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"聚焦会话",description:"将键盘焦点移到会话列表",shortcut:"mod+g s",group:"导航",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>dn())}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}`,()=>dn(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:s=>this.plugins.shouldLoadRemotePlugin(s.id,s.machineSpecific)})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(r){console.warn(`Failed to register PI WEB plugin ${s.id}`,r)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPromptEditor(){return{insertText:e=>{const t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();const i=t.state.selection.main;t.dispatch({changes:{from:i.from,to:i.to,insert:e},selection:{anchor:i.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??"",getSelection:()=>{const e=this.promptEditor?.view;if(!e)return null;const t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){const e=t=>Gg({state:this.state,prompt:this.createPromptEditor(),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Qu(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(Ya(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
2684
2689
 
2685
2690
  This will run git worktree remove and delete:
2686
2691
  ${e.path}
2687
2692
 
2688
- The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=await wt.deleteWorkspace(e.projectId,e.id,s);if(f(this.state)!==s)return;this.recordWorkspaceDeletionRun(r,s);const o=await this.workspaceForCommandRun(r);if(f(this.state)!==s)return;o!==void 0&&this.openRuntimeTerminal(s,o,{terminalId:r.terminalId})}catch(r){f(this.state)===s&&this.setState({error:`启动工作区删除失败:${Fs(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=Zs(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(Uf(t.id));if(f(this.state)!==e)return;const s=zf(i);this.setState({workspaceDeletionRuns:s});for(const r of Object.values(s))_i(r)||await this.handleCompletedWorkspaceDeletionRun(r,e)}catch(i){console.warn("Failed to refresh workspace deletion runs",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(_i);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=f(this.state)){if(f(this.state)!==t)return;const i=Xn(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Zs(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:W0(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}?
2693
+ The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=await wt.deleteWorkspace(e.projectId,e.id,s);if(f(this.state)!==s)return;this.recordWorkspaceDeletionRun(r,s);const o=await this.workspaceForCommandRun(r);if(f(this.state)!==s)return;o!==void 0&&this.openRuntimeTerminal(s,o,{terminalId:r.terminalId})}catch(r){f(this.state)===s&&this.setState({error:`启动工作区删除失败:${Fs(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=Zs(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(Hf(t.id));if(f(this.state)!==e)return;const s=qf(i);this.setState({workspaceDeletionRuns:s});for(const r of Object.values(s))_i(r)||await this.handleCompletedWorkspaceDeletionRun(r,e)}catch(i){console.warn("Failed to refresh workspace deletion runs",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(_i);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=f(this.state)){if(f(this.state)!==t)return;const i=ia(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Zs(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:U0(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}?
2689
2694
 
2690
- 这只会从当前 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?Gn:_s;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${pi}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开启":"关闭"}`,description:this.autoThemeDescription(t)},...e.map(r=>({value:`${pi}${r.id}`,label:this.themeOptionLabel(r,i),description:this.themeOptionDescription(r)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===_s||e===Gn){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===_s},this.applyPreferredTheme(!0);return}if(!e.startsWith(pi))return;const t=e.slice(pi.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,Cf(t),e&&Pf(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Rf({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return Ga(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=O0(i);return{value:i,label:`${i}${i===t?" ✓ 当前":""}`,...s===void 0?{}:{description:s}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==""&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t,i,s){!(i!==void 0&&i.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,i,s)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
2695
+ 这只会从当前 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?Xn:_s;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${pi}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开启":"关闭"}`,description:this.autoThemeDescription(t)},...e.map(r=>({value:`${pi}${r.id}`,label:this.themeOptionLabel(r,i),description:this.themeOptionDescription(r)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===_s||e===Xn){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===_s},this.applyPreferredTheme(!0);return}if(!e.startsWith(pi))return;const t=e.slice(pi.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,Tf(t),e&&Af(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Mf({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return Xa(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=z0(i);return{value:i,label:`${i}${i===t?" ✓ 当前":""}`,...s===void 0?{}:{description:s}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==""&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t,i,s){!(i!==void 0&&i.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,i,s)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
2691
2696
  <app-context-bar
2692
2697
  .machines=${this.state.machines}
2693
2698
  .machine=${this.state.selectedMachine}
@@ -2708,7 +2713,7 @@ The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=a
2708
2713
  <div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints("navigation"),workspace:this.resizablePanelConstraints("workspace")})}>
2709
2714
  <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
2710
2715
  ${this.renderNavigationPanelEdgeControl()}
2711
- <main class=${el(e.mainView)}>
2716
+ <main class=${rl(e.mainView)}>
2712
2717
  ${this.renderContextBar()}
2713
2718
  ${this.renderMobileMainTabs()}
2714
2719
  ${e.error?l`<div class="error">${e.error}</div>`:null}
@@ -2732,4 +2737,4 @@ The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=a
2732
2737
  ${e.themeDialog!==void 0?l`<command-picker title=${e.themeDialog.title} .options=${e.themeDialog.options} .selectedValue=${e.themeDialog.selectedValue} .onPick=${t=>{this.pickTheme(t)}} .onCancel=${()=>{this.setState({themeDialog:void 0})}}></command-picker>`:null}
2733
2738
  ${this.settingsSection!==void 0?l`<settings-dialog .section=${this.settingsSection} .actions=${this.getDefaultActions()} .onNavigate=${t=>{this.navigateSettings(t)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${t=>{this.applyClientConfig(t)}}></settings-dialog>`:null}
2734
2739
  </div>
2735
- `}};re.styles=S0;ve([y()],re.prototype,"state",2);ve([B("chat-view")],re.prototype,"chatView",2);ve([B("prompt-editor")],re.prototype,"promptEditor",2);ve([B("app-navigation-panel")],re.prototype,"navigationPanel",2);ve([B("#navigation-panel")],re.prototype,"navigationPanelFrame",2);ve([B("#workspace-panel")],re.prototype,"workspacePanelFrame",2);ve([y()],re.prototype,"activeThemeId",2);ve([y()],re.prototype,"isRefreshingApp",2);ve([y()],re.prototype,"sessionCleanupDialog",2);ve([y()],re.prototype,"settingsSection",2);ve([y()],re.prototype,"shortcutConfig",2);ve([y()],re.prototype,"workspaceUploadDefaultFolder",2);re=ve([W("pi-web-app")],re);function I0(){const e=new Ug;return e.register({id:"core",plugin:kg}),e.register({id:"themes",plugin:Rg}),e}function Jn(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 A0(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function T0(e,t){return Fl(e,t)}function Fl(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function M0(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function Qn(e){return Xe(e.status,e.activity)}function E0(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function Zn(){return{}}function Xn(e,t){return JSON.stringify([e,t])}function D0(e){const t=Math.min(e,ar.length-1);return ar[t]??3e4}function Fs(e){return e instanceof Error?e.message:String(e)}function W0(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Us(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function O0(e){switch(e){case"off":return"不使用推理";case"minimal":return"极简推理(约 1k tokens)";case"low":return"轻量推理(约 2k tokens)";case"medium":return"中等推理(约 8k tokens)";case"high":return"深度推理(约 16k tokens)";case"xhigh":return"最大推理(约 32k tokens)";default:return}}export{E as a,l as b,yt as c,G0 as d,K0 as e,B as f,A as i,d as n,y as r,V0 as s,W as t};
2740
+ `}};re.styles=R0;ve([y()],re.prototype,"state",2);ve([B("chat-view")],re.prototype,"chatView",2);ve([B("prompt-editor")],re.prototype,"promptEditor",2);ve([B("app-navigation-panel")],re.prototype,"navigationPanel",2);ve([B("#navigation-panel")],re.prototype,"navigationPanelFrame",2);ve([B("#workspace-panel")],re.prototype,"workspacePanelFrame",2);ve([y()],re.prototype,"activeThemeId",2);ve([y()],re.prototype,"isRefreshingApp",2);ve([y()],re.prototype,"sessionCleanupDialog",2);ve([y()],re.prototype,"settingsSection",2);ve([y()],re.prototype,"shortcutConfig",2);ve([y()],re.prototype,"workspaceUploadDefaultFolder",2);re=ve([W("pi-web-app")],re);function W0(){const e=new Kg;return e.register({id:"core",plugin:Ag}),e.register({id:"themes",plugin:Dg}),e}function Yn(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 O0(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function _0(e,t){return Nl(e,t)}function Nl(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function L0(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function ea(e){return Xe(e.status,e.activity)}function j0(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function ta(){return{}}function ia(e,t){return JSON.stringify([e,t])}function F0(e){const t=Math.min(e,ar.length-1);return ar[t]??3e4}function Fs(e){return e instanceof Error?e.message:String(e)}function U0(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Us(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function z0(e){switch(e){case"off":return"不使用推理";case"minimal":return"极简推理(约 1k tokens)";case"low":return"轻量推理(约 2k tokens)";case"medium":return"中等推理(约 8k tokens)";case"high":return"深度推理(约 16k tokens)";case"xhigh":return"最大推理(约 32k tokens)";default:return}}export{E as a,l as b,yt as c,ex as d,X0 as e,B as f,A as i,d as n,y as r,Y0 as s,W as t};