@chainingintention/pi-web-cn 1.202607.3 → 1.202607.4

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.
Files changed (53) hide show
  1. package/README.md +9 -3
  2. package/dist/client/assets/{CodeViewer-CGV4uBeZ.js → CodeViewer-DssF-c9D.js} +1 -1
  3. package/dist/client/assets/{TerminalPanel-CeJN9p9P.js → TerminalPanel-8Or6pbwb.js} +1 -1
  4. package/dist/client/assets/{UnifiedDiffViewer-BSzsWx-m.js → UnifiedDiffViewer-D_OLq3Q4.js} +1 -1
  5. package/dist/client/assets/{index-BA1zmHnv.js → index-B06LjBQ0.js} +761 -479
  6. package/dist/client/index.html +1 -1
  7. package/dist/docker/piWebDockerCommandPlan.js +211 -0
  8. package/dist/docker/piWebDockerCommandPlan.js.map +1 -0
  9. package/dist/pi-web-plugins/updates/pi-web-plugin.js +15 -5
  10. package/dist/pi-web-plugins/updates/updatesLogic.js +37 -5
  11. package/dist/piWebVersionReport.js +4 -0
  12. package/dist/piWebVersionReport.js.map +1 -1
  13. package/dist/plugin-api.d.ts +1 -1
  14. package/dist/server/app.js +8 -1
  15. package/dist/server/app.js.map +1 -1
  16. package/dist/server/configRoutes.js +109 -2
  17. package/dist/server/configRoutes.js.map +1 -1
  18. package/dist/server/machines/machineProxyRoutes.js +64 -11
  19. package/dist/server/machines/machineProxyRoutes.js.map +1 -1
  20. package/dist/server/machines/machineService.js +4 -26
  21. package/dist/server/machines/machineService.js.map +1 -1
  22. package/dist/server/piPackageRoutes.js +87 -0
  23. package/dist/server/piPackageRoutes.js.map +1 -0
  24. package/dist/server/piPackageService.js +69 -0
  25. package/dist/server/piPackageService.js.map +1 -0
  26. package/dist/server/piWebPluginService.js +43 -8
  27. package/dist/server/piWebPluginService.js.map +1 -1
  28. package/dist/server/piWebStatus.js +57 -0
  29. package/dist/server/piWebStatus.js.map +1 -1
  30. package/dist/server/sessions/builtinCommands.js +1 -1
  31. package/dist/server/sessions/builtinCommands.js.map +1 -1
  32. package/dist/server/sessions/piSessionService.js +39 -2
  33. package/dist/server/sessions/piSessionService.js.map +1 -1
  34. package/dist/server/sessions/sessionCommandService.js +16 -0
  35. package/dist/server/sessions/sessionCommandService.js.map +1 -1
  36. package/dist/server/sessions/sessionNameGenerator.js +27 -44
  37. package/dist/server/sessions/sessionNameGenerator.js.map +1 -1
  38. package/dist/server/workspaces/fileSuggestions.js +7 -3
  39. package/dist/server/workspaces/fileSuggestions.js.map +1 -1
  40. package/dist/shared/activity.js +0 -15
  41. package/dist/shared/activity.js.map +1 -1
  42. package/dist/shared/apiTypes.d.ts +39 -1
  43. package/dist/shared/apiTypes.js +3 -0
  44. package/dist/shared/apiTypes.js.map +1 -1
  45. package/dist/shared/capabilities.js +27 -2
  46. package/dist/shared/capabilities.js.map +1 -1
  47. package/dist/shared/federatedRoutes.js +8 -0
  48. package/dist/shared/federatedRoutes.js.map +1 -1
  49. package/dist/shared/piWebStatusParsing.js +20 -8
  50. package/dist/shared/piWebStatusParsing.js.map +1 -1
  51. package/docs/config.md +21 -12
  52. package/docs/plugins.md +28 -14
  53. package/package.json +7 -7
@@ -1,29 +1,31 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-CGV4uBeZ.js","assets/vendor-editor-core-C7aWiQy0.js","assets/vendor-editor-languages-EW34FfVy.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/UnifiedDiffViewer-BSzsWx-m.js","assets/TerminalPanel-CeJN9p9P.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
- import{Q as lo,v as rt,J as vs,R as uc,S as fc,G as gc,U as mc,V as vc,W as bc,A as wc,X as yc,Y as xc,Z as co,w as po,_ as Sc}from"./vendor-editor-core-C7aWiQy0.js";import{m as kc,d as $c,i as Pc}from"./vendor-editor-languages-EW34FfVy.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const n of o.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=i(r);fetch(r.href,o)}})();const bi=globalThis,fr=bi.ShadowRoot&&(bi.ShadyCSS===void 0||bi.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,gr=Symbol(),ho=new WeakMap;let ba=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==gr)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=i}get styleSheet(){let t=this.o;const i=this.t;if(fr&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=ho.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&ho.set(i,t))}return t}toString(){return this.cssText}};const Cc=e=>new ba(typeof e=="string"?e:e+"",void 0,gr),D=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,r,o)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+e[o+1],e[0]);return new ba(i,e,gr)},Ic=(e,t)=>{if(fr)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),r=bi.litNonce;r!==void 0&&s.setAttribute("nonce",r),s.textContent=i.cssText,e.appendChild(s)}},uo=fr?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return Cc(i)})(e):e;const{is:Rc,defineProperty:Ac,getOwnPropertyDescriptor:Tc,getOwnPropertyNames:Mc,getOwnPropertySymbols:Ec,getPrototypeOf:Dc}=Object,Zi=globalThis,fo=Zi.trustedTypes,Wc=fo?fo.emptyScript:"",Oc=Zi.reactiveElementPolyfillSupport,Vt=(e,t)=>e,Ri={toAttribute(e,t){switch(t){case Boolean:e=e?Wc:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=e!==null;break;case Number:i=e===null?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch{i=null}}return i}},mr=(e,t)=>!Rc(e,t),go={attribute:!0,type:String,converter:Ri,reflect:!1,useDefault:!1,hasChanged:mr};Symbol.metadata??=Symbol("metadata"),Zi.litPropertyMetadata??=new WeakMap;let xt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=go){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const s=Symbol(),r=this.getPropertyDescriptor(t,s,i);r!==void 0&&Ac(this.prototype,t,r)}}static getPropertyDescriptor(t,i,s){const{get:r,set:o}=Tc(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:r,set(n){const a=r?.call(this);o?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??go}static _$Ei(){if(this.hasOwnProperty(Vt("elementProperties")))return;const t=Dc(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Vt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Vt("properties"))){const i=this.properties,s=[...Mc(i),...Ec(i)];for(const r of s)this.createProperty(r,i[r])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,r]of i)this.elementProperties.set(s,r)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const r=this._$Eu(i,s);r!==void 0&&this._$Eh.set(r,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const i=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const r of s)i.unshift(uo(r))}else t!==void 0&&i.push(uo(t));return i}static _$Eu(t,i){const s=i.attribute;return s===!1?void 0:typeof s=="string"?s:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,i=this.constructor.elementProperties;for(const s of i.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Ic(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$ET(t,i){const s=this.constructor.elementProperties.get(t),r=this.constructor._$Eu(t,s);if(r!==void 0&&s.reflect===!0){const o=(s.converter?.toAttribute!==void 0?s.converter:Ri).toAttribute(i,s.type);this._$Em=t,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(t,i){const s=this.constructor,r=s._$Eh.get(t);if(r!==void 0&&this._$Em!==r){const o=s.getPropertyOptions(r),n=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:Ri;this._$Em=r;const a=n.fromAttribute(i,o.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(t,i,s,r=!1,o){if(t!==void 0){const n=this.constructor;if(r===!1&&(o=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??mr)(o,i)||s.useDefault&&s.reflect&&o===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:r,wrapped:o},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),o!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),r===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,o]of s){const{wrapped:n}=o,a=this[r];n!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,o,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};xt.elementStyles=[],xt.shadowRootOptions={mode:"open"},xt[Vt("elementProperties")]=new Map,xt[Vt("finalized")]=new Map,Oc?.({ReactiveElement:xt}),(Zi.reactiveElementVersions??=[]).push("2.1.2");const vr=globalThis,mo=e=>e,Ai=vr.trustedTypes,vo=Ai?Ai.createPolicy("lit-html",{createHTML:e=>e}):void 0,wa="$lit$",Ye=`lit$${Math.random().toFixed(9).slice(2)}$`,ya="?"+Ye,_c=`<${ya}>`,ht=document,Jt=()=>ht.createComment(""),Qt=e=>e===null||typeof e!="object"&&typeof e!="function",br=Array.isArray,Lc=e=>br(e)||typeof e?.[Symbol.iterator]=="function",bs=`[
3
- \f\r]`,Wt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,bo=/-->/g,wo=/>/g,ot=RegExp(`>|${bs}(?:([^\\s"'>=/]+)(${bs}*=${bs}*(?:[^
4
- \f\r"'\`<>=]|("|')|))|$)`,"g"),yo=/'/g,xo=/"/g,xa=/^(?:script|style|textarea|title)$/i,Sa=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=Sa(1),be=Sa(2),et=Symbol.for("lit-noChange"),U=Symbol.for("lit-nothing"),So=new WeakMap,ct=ht.createTreeWalker(ht,129);function ka(e,t){if(!br(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return vo!==void 0?vo.createHTML(t):t}const jc=(e,t)=>{const i=e.length-1,s=[];let r,o=t===2?"<svg>":t===3?"<math>":"",n=Wt;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,g=0;for(;g<c.length&&(n.lastIndex=g,u=n.exec(c),u!==null);)g=n.lastIndex,n===Wt?u[1]==="!--"?n=bo:u[1]!==void 0?n=wo:u[2]!==void 0?(xa.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=ot):u[3]!==void 0&&(n=ot):n===ot?u[0]===">"?(n=r??Wt,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?ot:u[3]==='"'?xo:yo):n===xo||n===yo?n=ot:n===bo||n===wo?n=Wt:(n=ot,r=void 0);const y=n===ot&&e[a+1].startsWith("/>")?" ":"";o+=n===Wt?c+_c:h>=0?(s.push(p),c.slice(0,h)+wa+c.slice(h)+Ye+y):c+Ye+(h===-2?a:y)}return[ka(e,o+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Zt{constructor({strings:t,_$litType$:i},s){let r;this.parts=[];let o=0,n=0;const a=t.length-1,c=this.parts,[p,u]=jc(t,i);if(this.el=Zt.createElement(p,s),ct.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(r=ct.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const h of r.getAttributeNames())if(h.endsWith(wa)){const g=u[n++],y=r.getAttribute(h).split(Ye),P=/([.?@])?(.*)/.exec(g);c.push({type:1,index:o,name:P[2],strings:y,ctor:P[1]==="."?zc:P[1]==="?"?Uc:P[1]==="@"?Bc:Xi}),r.removeAttribute(h)}else h.startsWith(Ye)&&(c.push({type:6,index:o}),r.removeAttribute(h));if(xa.test(r.tagName)){const h=r.textContent.split(Ye),g=h.length-1;if(g>0){r.textContent=Ai?Ai.emptyScript:"";for(let y=0;y<g;y++)r.append(h[y],Jt()),ct.nextNode(),c.push({type:2,index:++o});r.append(h[g],Jt())}}}else if(r.nodeType===8)if(r.data===ya)c.push({type:2,index:o});else{let h=-1;for(;(h=r.data.indexOf(Ye,h+1))!==-1;)c.push({type:7,index:o}),h+=Ye.length-1}o++}}static createElement(t,i){const s=ht.createElement("template");return s.innerHTML=t,s}}function Ct(e,t,i=e,s){if(t===et)return t;let r=s!==void 0?i._$Co?.[s]:i._$Cl;const o=Qt(t)?void 0:t._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(e),r._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=r:i._$Cl=r),r!==void 0&&(t=Ct(e,r._$AS(e,t.values),r,s)),t}class Fc{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,r=(t?.creationScope??ht).importNode(i,!0);ct.currentNode=r;let o=ct.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new Tt(o,o.nextSibling,this,t):c.type===1?p=new c.ctor(o,c.name,c.strings,this,t):c.type===6&&(p=new Nc(o,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(o=ct.nextNode(),n++)}return ct.currentNode=ht,r}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class Tt{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,r){this.type=2,this._$AH=U,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=Ct(this,t,i),Qt(t)?t===U||t==null||t===""?(this._$AH!==U&&this._$AR(),this._$AH=U):t!==this._$AH&&t!==et&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Lc(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==U&&Qt(this._$AH)?this._$AA.nextSibling.data=t:this.T(ht.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,r=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Zt.createElement(ka(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(i);else{const o=new Fc(r,this),n=o.u(this.options);o.p(i),this.T(n),this._$AH=o}}_$AC(t){let i=So.get(t.strings);return i===void 0&&So.set(t.strings,i=new Zt(t)),i}k(t){br(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,r=0;for(const o of t)r===i.length?i.push(s=new Tt(this.O(Jt()),this.O(Jt()),this,this.options)):s=i[r],s._$AI(o),r++;r<i.length&&(this._$AR(s&&s._$AB.nextSibling,r),i.length=r)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=mo(t).nextSibling;mo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let Xi=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,r,o){this.type=1,this._$AH=U,this._$AN=void 0,this.element=t,this.name=i,this._$AM=r,this.options=o,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=U}_$AI(t,i=this,s,r){const o=this.strings;let n=!1;if(o===void 0)t=Ct(this,t,i,0),n=!Qt(t)||t!==this._$AH&&t!==et,n&&(this._$AH=t);else{const a=t;let c,p;for(t=o[0],c=0;c<o.length-1;c++)p=Ct(this,a[s+c],i,c),p===et&&(p=this._$AH[c]),n||=!Qt(p)||p!==this._$AH[c],p===U?t=U:t!==U&&(t+=(p??"")+o[c+1]),this._$AH[c]=p}n&&!r&&this.j(t)}j(t){t===U?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},zc=class extends Xi{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===U?void 0:t}},Uc=class extends Xi{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==U)}},Bc=class extends Xi{constructor(t,i,s,r,o){super(t,i,s,r,o),this.type=5}_$AI(t,i=this){if((t=Ct(this,t,i,0)??U)===et)return;const s=this._$AH,r=t===U&&s!==U||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,o=t!==U&&(s===U||r);r&&this.element.removeEventListener(this.name,this,s),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}},Nc=class{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){Ct(this,t)}};const Hc={I:Tt},qc=vr.litHtmlPolyfillSupport;qc?.(Zt,Tt),(vr.litHtmlVersions??=[]).push("3.3.3");const Kc=(e,t,i)=>{const s=i?.renderBefore??t;let r=s._$litPart$;if(r===void 0){const o=i?.renderBefore??null;s._$litPart$=r=new Tt(t.insertBefore(Jt(),o),o,void 0,i??{})}return r._$AI(e),r};const wr=globalThis;let R=class extends xt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=Kc(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return et}};R._$litElement$=!0,R.finalized=!0,wr.litElementHydrateSupport?.({LitElement:R});const Vc=wr.litElementPolyfillSupport;Vc?.({LitElement:R});(wr.litElementVersions??=[]).push("4.2.2");const W=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const Gc={attribute:!0,type:String,converter:Ri,reflect:!1,hasChanged:mr},Jc=(e=Gc,t,i)=>{const{kind:s,metadata:r}=i;let o=globalThis.litPropertyMetadata.get(r);if(o===void 0&&globalThis.litPropertyMetadata.set(r,o=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),o.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,c,e,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,e,a),a}}}if(s==="setter"){const{name:n}=i;return function(a){const c=this[n];t.call(this,a),this.requestUpdate(n,c,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?Jc(e,t,i):((s,r,o)=>{const n=r.hasOwnProperty(o);return r.constructor.createProperty(o,s),n?Object.getOwnPropertyDescriptor(r,o):void 0})(e,t,i)}function w(e){return d({...e,state:!0,attribute:!1})}const Qc=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function B(e,t){return(i,s,r)=>{const o=n=>n.renderRoot?.querySelector(e)??null;return Qc(i,s,{get(){return o(this)}})}}function yr(e=Sr()){return xr(e)===void 0?"normal":"management"}function Yi(e,t=Sr(),i="management"){if(i==="normal"||t===void 0)return e;const s=xr(t);if(s===void 0)return e;const r=new URL(e,t.origin);return r.searchParams.set("embed",s.embed),r.searchParams.set("token",s.token),`${r.pathname}${r.search}${r.hash}`}function $a(e,t=Sr(),i="management"){if(i==="normal"||t===void 0)return e;const s=xr(t);if(s===void 0)return e;const r=new URL(e,t.origin);return r.searchParams.set("embed",s.embed),r.searchParams.set("token",s.token),`${r.pathname}${r.search}`}function xr(e){if(e===void 0)return;const t=e.searchParams.get("embed"),i=e.searchParams.get("token")?.trim();if(!(t!=="management"||i===void 0||i===""))return{embed:t,token:i}}function Sr(){if(typeof globalThis.location>"u")return;const e=globalThis.location;if(typeof e.href=="string"&&e.href!=="")return new URL(e.href);const t=typeof e.protocol=="string"&&e.protocol!==""?e.protocol:"http:",i=typeof e.host=="string"&&e.host!==""?e.host:"localhost",s=typeof e.search=="string"?e.search:"";return new URL(`${t}//${i}/${s}`)}let Pa=yr();function Zc(e){Pa=e}function kr(e){return Yi(e,void 0,Pa)}async function v(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&!s.has("content-type")&&s.set("content-type","application/json");const r=await fetch(kr(e),{...i,headers:s});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(Ca(n)??r.statusText)}const o=await r.json();return t(o)}async function Xc(e,t){const i=await fetch(kr(e));if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(Ca(s)??i.statusText)}return t(await i.json())}}function Ca(e){if(Yc(e))return typeof e.error=="string"?e.error:void 0}function Yc(e){return typeof e=="object"&&e!==null}function je(e){return typeof e=="object"&&e!==null}function x(e){if(!je(e))throw new Error("Expected object response");return e}function m(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function $(e,t){const i=e[t];if(i!==void 0){if(typeof i!="string")throw new Error(`Expected optional string field: ${t}`);return i}}function q(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function ae(e,t){const i=e[t];if(i!==void 0){if(typeof i!="number")throw new Error(`Expected optional number field: ${t}`);return i}}function E(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function j(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function it(e,t){if(x(e)[t]!==!0)throw new Error(`Expected ${t} response`);return!0}function b(e,t){return t===void 0?{}:{[e]:t}}const _e={sessionsDeleteArchived:"sessions.deleteArchived",sessionsBulkMutations:"sessions.bulkMutations",sessionsCleanup:"sessions.cleanup",sessionsReload:"sessions.reload",promptAttachments:"prompt.attachments",workspaceFileSuggestions:"workspace.fileSuggestions"},ed=Object.values(_e),td=new Set(ed);function id(e){return typeof e=="string"&&td.has(e)}function qe(e,t){return e?.capabilities?.includes(t)===!0}function ko(e){const t=x(e);return{path:m(t,"path"),exists:E(t,"exists"),config:$o(t.config),effectiveConfig:$o(t.effectiveConfig),envOverrides:dd(t.envOverrides)}}function $o(e){const t=x(e);return{...b("host",$(t,"host")),...b("port",ae(t,"port")),...b("allowedHosts",rd(t.allowedHosts)),...b("shortcuts",ld(t.shortcuts)),...b("plugins",cd(t.plugins)),...b("normalAuth",sd(t.normalAuth)),...b("pathAccess",od(t.pathAccess)),...b("uploads",ad(t.uploads)),...b("maxUploadBytes",ae(t,"maxUploadBytes")),...b("spawnSessions",Co(t,"spawnSessions")),...b("subsessions",Co(t,"subsessions"))}}function sd(e){if(e!==void 0){if(!je(e)||Array.isArray(e))throw new Error("Invalid PI WEB normalAuth field");return{...b("passwordHash",$(e,"passwordHash"))}}}function rd(e){if(e!==void 0){if(e===!0)return!0;if(Array.isArray(e)&&e.every(t=>typeof t=="string"))return e;throw new Error("Invalid PI WEB allowedHosts field")}}function od(e){if(e===void 0)return;if(!je(e)||Array.isArray(e))throw new Error("Invalid PI WEB pathAccess field");const t=e.allowedPaths;return{...b("allowedPaths",nd(t,"pathAccess.allowedPaths"))}}function nd(e,t){if(e!==void 0){if(Array.isArray(e)&&e.every(i=>typeof i=="string"&&i!==""))return e;throw new Error(`Invalid PI WEB ${t} field`)}}function ad(e){if(e!==void 0){if(!je(e)||Array.isArray(e))throw new Error("Invalid PI WEB uploads field");return{...b("defaultFolder",$(e,"defaultFolder"))}}}function ld(e){if(e!==void 0){if(!je(e)||Array.isArray(e))throw new Error("Invalid PI WEB shortcuts field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(i!==null&&(typeof i!="string"||i===""))throw new Error("Invalid PI WEB shortcut field");return[t,i]}))}}function cd(e){if(e!==void 0){if(!je(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!je(i)||Array.isArray(i))throw new Error("Invalid PI WEB plugin config field");const s=i.enabled;if(s!==void 0&&typeof s!="boolean")throw new Error("Invalid PI WEB plugin enabled field");const r=i.settings;if(r!==void 0&&(!je(r)||Array.isArray(r)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function dd(e){const t=x(e);return{host:E(t,"host"),port:E(t,"port"),allowedHosts:E(t,"allowedHosts"),spawnSessions:E(t,"spawnSessions"),subsessions:E(t,"subsessions")}}function pd(e){const t=x(e);return{plugins:j(hd)(t.plugins)}}function hd(e){const t=x(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:ud(t.scope),machineSpecific:Sd(t.machineSpecific,"machineSpecific")??!1,enabled:E(t,"enabled")}}function ud(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function fd(e){const t=x(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:md(t.components),release:bd(t.release),commands:wd(t.commands),messages:j(yd)(t.messages)}}function gd(e){const t=x(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:Ia(t.components),capabilities:$r(t.capabilities)}}function md(e){const t=x(e);return{web:Ti(t.web),sessiond:Ti(t.sessiond)}}function Ia(e){const t=x(e);return{web:Po(t.web),sessiond:Po(t.sessiond)}}function Po(e){const t=x(e);return{component:Ra(t.component),label:m(t,"label"),...b("runtimeVersion",$(t,"runtimeVersion")),available:E(t,"available"),capabilities:$r(t.capabilities),...b("error",$(t,"error"))}}function Ti(e){const t=x(e);return{component:Ra(t.component),label:m(t,"label"),...b("runtimeVersion",$(t,"runtimeVersion")),...b("installedVersion",$(t,"installedVersion")),stale:E(t,"stale"),available:E(t,"available"),...b("installation",vd(t.installation)),...b("error",$(t,"error"))}}function vd(e){if(e===void 0)return;const t=x(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");return{kind:i,...b("path",$(t,"path")),...b("source",$(t,"source")),...s===void 0?{}:{scope:s},...b("npmRoot",$(t,"npmRoot"))}}function bd(e){const t=x(e);return{packageName:m(t,"packageName"),...b("latestVersion",$(t,"latestVersion")),updateAvailable:E(t,"updateAvailable"),...b("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...b("error",$(t,"error"))}}function wd(e){const t=x(e);return{...b("update",$(t,"update")),...b("restart",$(t,"restart")),...b("restartWeb",$(t,"restartWeb")),...b("restartSessiond",$(t,"restartSessiond")),...b("status",$(t,"status"))}}function yd(e){const t=x(e);return{id:m(t,"id"),severity:xd(t.severity),title:m(t,"title"),body:m(t,"body"),...b("command",$(t,"command"))}}function Ra(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function $r(e){if(!Array.isArray(e)||!e.every(id))throw new Error("Invalid PI WEB capabilities");return e}function xd(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Sd(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function Co(e,t){const i=e[t];if(i!==void 0){if(typeof i!="boolean")throw new Error(`Invalid PI WEB ${t} field`);return i}}function kd(e){const t=x(e);return j(Aa)(t.machines)}function Aa(e){const t=x(e),i=Cd(t,"kind"),s=$(t,"baseUrl"),r=Ta(t,"status"),o=$(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...r===void 0?{}:{status:r},...o===void 0?{}:{statusMessage:o}}}function $d(e){const t=x(e),i=Ta(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:Ti(t.web)},...t.sessiond===void 0?{}:{sessiond:Ti(t.sessiond)},...s===void 0?{}:{error:s}}}function Pd(e){const t=x(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...b("packageName",$(t,"packageName")),...b("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:Ia(t.components)},...t.capabilities===void 0?{}:{capabilities:$r(t.capabilities)},...i===void 0?{}:{error:i}}}function Cd(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function Ta(e,t){const i=$(e,t);if(i!==void 0){if(i!=="unknown"&&i!=="online"&&i!=="offline"&&i!=="error")throw new Error(`Expected machine status field: ${t}`);return i}}function Id(e){const t=x(e);return{configured:E(t,"configured"),authenticated:E(t,"authenticated")}}function Rd(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function It(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function Ad(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=x(e);return{messages:Rd(t.messages),start:q(t,"start"),total:q(t,"total")}}function Io(e){const t=x(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function Td(e){const t=x(e),i=$(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:E(t,"isMain"),isGitRepo:E(t,"isGitRepo"),isGitWorktree:E(t,"isGitWorktree"),...b("effectiveConfig",Md(t.effectiveConfig))}}function Md(e){if(e!==void 0){if(!je(e)||Array.isArray(e))throw new Error("Invalid workspace effectiveConfig field");return{...b("uploads",vp(e.uploads))}}}function Ks(e){const t=x(e);return{path:m(t,"path"),size:q(t,"size"),modifiedAt:m(t,"modifiedAt")}}function Ro(e){const t=x(e);return{path:m(t,"path")}}function Ed(e){const t=x(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function Vs(e){const t=x(e),i=$(t,"name"),s=$(t,"parentSessionPath"),r=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:q(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...r===void 0?{}:{archivedAt:r}}}function Ot(e){const t=x(e);return{sessionId:m(t,"sessionId"),isStreaming:E(t,"isStreaming"),isCompacting:E(t,"isCompacting"),isBashRunning:E(t,"isBashRunning"),pendingMessageCount:q(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:j(Fd)(t.queuedMessages),...b("messageCount",ae(t,"messageCount")),tokens:zd(t.tokens),cost:q(t,"cost"),...Nd(t.model),...ip(t.contextUsage),...b("thinkingLevel",$(t,"thinkingLevel"))}}function Ma(e){const t=x(e),i=t.skippedBusySessionIds===void 0?void 0:It(t.skippedBusySessionIds,"skippedBusySessionIds");return{generatedAt:m(t,"generatedAt"),thresholds:_d(t.thresholds),projects:j(Ld)(t.projects),totals:jd(t.totals),...i===void 0?{}:{skippedBusySessionIds:i}}}function Dd(e){const t=x(e);return{...Ma(t),archivedSessionIds:It(t.archivedSessionIds,"archivedSessionIds"),deletedSessionIds:It(t.deletedSessionIds,"deletedSessionIds")}}function Wd(e){const t=x(e);if(t.archived!==!0)throw new Error("Expected bulk archived response");return{archived:!0,archivedSessionIds:It(t.archivedSessionIds,"archivedSessionIds"),failures:j(Ea)(t.failures),generatedAt:m(t,"generatedAt")}}function Od(e){const t=x(e);if(t.deleted!==!0)throw new Error("Expected bulk deleted response");return{deleted:!0,deletedSessionIds:It(t.deletedSessionIds,"deletedSessionIds"),failures:j(Ea)(t.failures),generatedAt:m(t,"generatedAt")}}function Ea(e){const t=x(e);return{sessionId:m(t,"sessionId"),error:m(t,"error")}}function _d(e){const t=x(e);return{...b("archiveIdleDays",ae(t,"archiveIdleDays")),...b("deleteArchivedDays",ae(t,"deleteArchivedDays"))}}function Ld(e){const t=x(e);return{cwd:m(t,"cwd"),archiveCount:q(t,"archiveCount"),deleteCount:q(t,"deleteCount")}}function jd(e){const t=x(e);return{archiveCount:q(t,"archiveCount"),deleteCount:q(t,"deleteCount")}}function Fd(e){const t=x(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text"),...b("imageCount",ae(t,"imageCount"))}}function zd(e){const t=x(e);return{input:q(t,"input"),output:q(t,"output"),cacheRead:q(t,"cacheRead"),cacheWrite:q(t,"cacheWrite"),total:q(t,"total")}}function Da(e){const t=x(e);return{...b("provider",$(t,"provider")),...b("id",$(t,"id")),...b("name",$(t,"name")),...b("contextWindow",ae(t,"contextWindow")),...b("reasoning",t.reasoning),...b("input",Ud(t.input))}}function Ud(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Invalid model input");return e.map(Bd)}}function Bd(e){if(e==="text"||e==="image")return e;throw new Error("Invalid model input")}function Nd(e){return e===void 0?{}:{model:Da(e)}}function Hd(e){const t=x(e);return{models:j(Da)(t.models)}}function qd(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function Kd(e){const t=x(e);return{levels:j(qd)(t.levels)}}function Vd(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Gd(e){if(e!=="stored"&&e!=="runtime"&&e!=="environment"&&e!=="fallback"&&e!=="models_json_key"&&e!=="models_json_command")throw new Error("Invalid auth status source");return e}function Jd(e){const t=x(e),i=t.source===void 0?void 0:Gd(t.source);return{configured:E(t,"configured"),...b("source",i),...b("label",$(t,"label"))}}function Qd(e){const t=x(e);return{id:m(t,"id"),name:m(t,"name"),authType:Vd(t.authType),status:Jd(t.status)}}function Zd(e){const t=x(e);return{providers:j(Qd)(t.providers)}}function ai(e){const t=x(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:Xd(t.status),progress:j(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...b("error",$(t,"error")),...b("auth",Yd(t.auth)),...b("prompt",ep(t.prompt)),...b("select",tp(t.select))}}function Xd(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Yd(e){if(e===void 0)return;const t=x(e);return{url:m(t,"url"),...b("instructions",$(t,"instructions"))}}function ep(e){if(e===void 0)return;const t=x(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...b("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function tp(e){if(e===void 0)return;const t=x(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:j(Oa)(t.options)}}function ip(e){if(e===void 0)return{};const t=x(e);return{contextUsage:{tokens:Eo(t,"tokens"),contextWindow:q(t,"contextWindow"),percent:Eo(t,"percent")}}}function sp(e){const t=x(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...b("description",$(t,"description"))}}function Gs(e){const t=x(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function rp(e){const t=x(e);return{path:m(t,"path"),entries:j(op)(t.entries),scannedAt:m(t,"scannedAt"),truncated:E(t,"truncated")}}function op(e){const t=x(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...b("size",ae(t,"size")),...b("modifiedAt",$(t,"modifiedAt"))}}function np(e){const t=x(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...b("language",$(t,"language")),...b("mediaType",cp(t.mediaType)),...b("mimeType",$(t,"mimeType")),encoding:i,size:q(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:E(t,"truncated"),binary:E(t,"binary")}}function Wa(e){const t=x(e);return{path:m(t,"path"),size:q(t,"size"),modifiedAt:m(t,"modifiedAt"),created:E(t,"created")}}function ap(e){const t=x(e);return{path:m(t,"path"),existed:E(t,"existed")}}function lp(e){const t=x(e);return{fromPath:m(t,"fromPath"),toPath:m(t,"toPath"),size:q(t,"size"),modifiedAt:m(t,"modifiedAt")}}function cp(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function dp(e){const t=x(e);return{isGitRepo:E(t,"isGitRepo"),hash:m(t,"hash"),...b("branch",$(t,"branch")),...b("upstream",$(t,"upstream")),...b("ahead",ae(t,"ahead")),...b("behind",ae(t,"behind")),files:j(pp)(t.files)}}function pp(e){const t=x(e);return{path:m(t,"path"),...b("oldPath",$(t,"oldPath")),index:Ao(t.index),workingTree:Ao(t.workingTree)}}function Ao(e){switch(e){case"unmodified":case"modified":case"added":case"deleted":case"renamed":case"copied":case"untracked":case"ignored":case"conflicted":return e;default:throw new Error("Invalid git file state")}}function hp(e){const t=x(e);return{...b("path",$(t,"path")),staged:E(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:E(t,"truncated")}}function ws(e){const t=x(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:E(t,"exited"),...b("exitCode",ae(t,"exitCode")),...b("commandRunId",$(t,"commandRunId"))}}function Gt(e){const t=x(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:up(t.status),...b("exitCode",ae(t,"exitCode")),createdAt:m(t,"createdAt"),...b("startedAt",$(t,"startedAt")),...b("completedAt",$(t,"completedAt")),metadata:fp(t.metadata,"metadata")}}function up(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function fp(e,t){const i=x(e);return Object.fromEntries(Object.entries(i).map(([s,r])=>{if(typeof r!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,r]}))}function gp(e){const t=x(e);return{cwd:m(t,"cwd"),hasSessionActivity:E(t,"hasSessionActivity"),hasTerminalActivity:E(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function mp(e){const t=x(e);return{workspaces:j(gp)(t.workspaces),generatedAt:m(t,"generatedAt")}}function vp(e){if(e!==void 0){if(!je(e)||Array.isArray(e))throw new Error("Invalid uploads field");return{...b("defaultFolder",$(e,"defaultFolder"))}}}function To(e){const t=x(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:j(Oa)(t.options)};if(i==="done")return{type:i,...b("message",$(t,"message")),...bp(t.session),...b("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function Oa(e){const t=x(e);return{value:m(t,"value"),label:m(t,"label"),...b("description",$(t,"description"))}}function bp(e){return e===void 0?{}:{session:Vs(e)}}function dt(e){return{accepted:it(e,"accepted")}}function wp(e){const t=x(e);return j(yp)(t.attachments)}function yp(e){const t=x(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:q(t,"size")}}function Js(e){return{closed:it(e,"closed")}}function xp(e){return{aborted:it(e,"aborted")}}function Sp(e){return{stopped:it(e,"stopped")}}function Mo(e){const t=x(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:It(t.sessionIds,"sessionIds"),s=ae(t,"archivedCount"),r=ae(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...r===void 0?{}:{skippedAlreadyArchivedCount:r}}}function kp(e){return{restored:it(e,"restored")}}function $p(e){return{deleted:it(e,"deleted")}}function Pp(e){return{detached:it(e,"detached")}}function Cp(e){return{reloaded:it(e,"reloaded")}}function Eo(e,t){const i=e[t];if(i===null)return null;if(typeof i!="number")throw new Error(`Expected number|null field: ${t}`);return i}function Ip(e){return typeof e=="string"?e:e.id}function Rp(e){return typeof e=="string"?void 0:e.cwd}function Ap(e,t,i,s){const r=new URLSearchParams;s?.path!==void 0&&r.set("path",s.path),s?.staged===!0&&r.set("staged","true");const o=r.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${o?`?${o}`:""}`}function Tp(e,t,i="local"){const s=new URLSearchParams,r=Rp(e);r!==void 0&&r!==""&&s.set("cwd",r),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const o=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${encodeURIComponent(Ip(e))}/messages${o===""?"":`?${o}`}`}function Mp(e,t,i,s){const r=new URLSearchParams({path:i});s?.createDirs===!1&&r.set("createDirs","false"),s?.overwrite===!1&&r.set("overwrite","false");const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Yi(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`)}function Ep(e,t,i,s){const r=new URLSearchParams;r.set("path",i),s?.modifiedAt!==void 0&&r.set("v",s.modifiedAt);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Yi(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${r.toString()}`)}function _a(e,t,i,s){const r=new URLSearchParams;r.set("path",i);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Yi(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${r.toString()}`)}const C=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function La(e){return typeof e=="string"?e:e.id}function Pr(e){return typeof e=="string"?void 0:e.cwd}function ja(e,t="local"){return`${C(t)}/sessions/${encodeURIComponent(La(e))}`}function J(e,t,i="local"){return`${ja(e,i)}/${t}`}function li(e,t,i="local"){return`${J(e,t,i)}${Fa(e)}`}function Dp(e,t="local"){return`${ja(e,t)}${Fa(e)}`}function Fa(e){const t=Pr(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function X(e,t={}){const i=Pr(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}function Do(e){return JSON.stringify({sessions:e.map(Wp)})}function Wp(e){const t=La(e),i=Pr(e);return i===void 0||i===""?{id:t}:{id:t,cwd:i}}const za={piWebStatus:(e="local")=>v(e==="local"?"/api/pi-web/status":`${C(e)}/pi-web/status`,fd),piWebRuntime:()=>v("/api/pi-web/runtime",gd)},Op={machines:()=>v("/api/machines",kd),addMachine:e=>v("/api/machines",Aa,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>v(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>v(`/api/machines/${encodeURIComponent(e)}/health`,$d),runtime:e=>v(`/api/machines/${encodeURIComponent(e)}/runtime`,Pd)},Mi={config:()=>v("/api/config",ko),saveConfig:e=>v("/api/config",ko,{method:"PUT",body:JSON.stringify({config:e})})},St={status:()=>v("/api/normal-auth/status",Id),setup:e=>v("/api/normal-auth/setup",dt,{method:"POST",body:JSON.stringify({password:e})}),login:e=>v("/api/normal-auth/login",dt,{method:"POST",body:JSON.stringify({password:e})}),changePassword:(e,t)=>v("/api/normal-auth/change-password",dt,{method:"POST",body:JSON.stringify({currentPassword:e,newPassword:t})})},Qs={plugins:()=>v("/api/plugins",pd)},Ua={workspaceActivity:(e="local")=>v(`${C(e)}/activity`,mp)},_p={projects:(e="local")=>v(`${C(e)}/projects`,j(Io)),addProject:(e,t,i,s="local")=>v(`${C(s)}/projects`,Io,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>v(`${C(t)}/projects/${encodeURIComponent(e)}`,Js,{method:"DELETE"}),projectDirectories:(e,t="local")=>v(`${C(t)}/project-directories?q=${encodeURIComponent(e)}`,j(Gs))},kt={workspaces:(e,t="local")=>v(`${C(t)}/projects/${e}/workspaces`,j(Td)),deleteWorkspace:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Gt,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,rp),workspaceFile:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,np),uploadWorkspaceFile:async(e,t,i,s,r="local")=>r==="local"?Up(e,t,i,s):v(`${C(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Ks,{method:"POST",body:JSON.stringify({path:i,contentBase64:await Fp(s)})}),createWorkspaceFile:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Ks,{method:"POST",body:JSON.stringify({path:i,contentBase64:""})}),writeWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({path:i});r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!1&&n.set("overwrite","false");const a=s instanceof Uint8Array,c=a?new Uint8Array(s):new TextEncoder().encode(s);return v(`${C(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${n.toString()}`,Wa,{method:"PUT",body:c,headers:{"Content-Type":a?"application/octet-stream":"text/plain"}})},deleteWorkspaceFile:(e,t,i,s="local")=>{const r=new URLSearchParams({path:i});return v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`,ap,{method:"DELETE"})},moveWorkspaceFile:(e,t,i,s,r,o="local")=>{const n=new URLSearchParams({fromPath:i,toPath:s});return r?.createDirs===!1&&n.set("createDirs","false"),r?.overwrite===!0&&n.set("overwrite","true"),v(`${C(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${n.toString()}`,lp,{method:"POST"})},createWorkspaceDirectory:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Ro,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,r="local")=>v(`${C(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Ro,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,Ed,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>_a(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>Bp(e,t,i,s)},Zs={sessions:(e,t="local")=>v(`${C(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(Vs)),startSession:(e,t="local")=>v(`${C(t)}/sessions`,Vs,{method:"POST",body:JSON.stringify({cwd:e})}),cleanupPreview:(e,t="local")=>v(`${C(t)}/sessions/cleanup/preview`,Ma,{method:"POST",body:JSON.stringify(e)}),cleanup:(e,t="local")=>v(`${C(t)}/sessions/cleanup`,Dd,{method:"POST",body:JSON.stringify(e)}),archiveMany:(e,t="local")=>v(`${C(t)}/sessions/bulk/archive`,Wd,{method:"POST",body:Do(e)}),deleteArchivedMany:(e,t="local")=>v(`${C(t)}/sessions/bulk/delete-archived`,Od,{method:"POST",body:Do(e)}),messages:(e,t,i="local")=>v(Tp(e,t,i),Ad),status:(e,t="local")=>v(li(e,"status",t),Ot),models:(e,t="local")=>v(li(e,"models",t),Hd),setModel:(e,t,i,s="local")=>v(J(e,"model",s),Ot,{method:"POST",body:X(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>v(J(e,"model/cycle",i),Ot,{method:"POST",body:X(e,{direction:t})}),thinkingLevels:(e,t="local")=>v(li(e,"thinking-levels",t),Kd),setThinkingLevel:(e,t,i="local")=>v(J(e,"thinking-level",i),Ot,{method:"POST",body:X(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>v(J(e,"thinking-level/cycle",t),Ot,{method:"POST",body:X(e)}),commands:(e,t="local")=>v(li(e,"commands",t),j(sp)),prompt:(e,t,i,s="local",r)=>v(J(e,"prompt",s),dt,{method:"POST",body:X(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...r!==void 0&&r.length>0?{attachments:r}:{}})}),saveAttachments:(e,t,i="local",s)=>v(J(e,"attachments",i),wp,{method:"POST",body:X(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>v(J(e,"shell",i),dt,{method:"POST",body:X(e,{text:t})}),runCommand:(e,t,i="local")=>v(J(e,"commands/run",i),To,{method:"POST",body:X(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>v(J(e,"commands/respond",s),To,{method:"POST",body:X(e,{requestId:t,value:i})}),abort:(e,t="local")=>v(J(e,"abort",t),xp,{method:"POST",body:X(e)}),stop:(e,t="local")=>v(J(e,"stop",t),Sp,{method:"POST",body:X(e)}),archive:(e,t="local")=>v(J(e,"archive",t),Mo,{method:"POST",body:X(e)}),archiveWithDescendants:(e,t="local")=>v(J(e,"archive-tree",t),Mo,{method:"POST",body:X(e)}),restore:(e,t="local")=>v(J(e,"restore",t),kp,{method:"POST",body:X(e)}),deleteArchived:(e,t="local")=>v(Dp(e,t),$p,{method:"DELETE"}),detachParent:(e,t="local")=>v(J(e,"detach-parent",t),Pp,{method:"POST",body:X(e)}),reloadSession:(e,t="local")=>v(J(e,"reload",t),Cp,{method:"POST",body:X(e)}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return v(`${C(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Zd)},saveApiKey:(e,t,i="local")=>v(`${C(i)}/auth/api-key`,dt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>v(`${C(t)}/auth/logout`,dt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>v(`${C(t)}/auth/oauth`,ai,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>v(`${C(t)}/auth/oauth/${encodeURIComponent(e)}`,ai),respondOAuthFlow:(e,t,i,s="local")=>v(`${C(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,ai,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>v(`${C(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,ai,{method:"POST"})},$t={terminals:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(ws)),startTerminal:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ws,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Js,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,Js,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>v(`${C(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,ws,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Gt,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>v(`${C(t)}/terminal-command-runs${jp(e)}`,j(Gt)),getCommandRun:(e,t="local")=>Lp(e,t),cancelCommandRun:(e,t="local")=>v(`${C(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Gt,{method:"POST"})};async function Lp(e,t){return Xc(`${C(t)}/terminal-command-runs/${encodeURIComponent(e)}`,Gt)}function jp(e){if(e===void 0)return"";const t=new URLSearchParams;e.projectId!==void 0&&t.set("projectId",e.projectId),e.workspaceId!==void 0&&t.set("workspaceId",e.workspaceId),e.terminalId!==void 0&&t.set("terminalId",e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set("statuses",e.statuses.join(",")),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set("metadata",JSON.stringify(e.metadata));const i=t.toString();return i===""?"":`?${i}`}function Ba(e){if(!Np(e))return;const t=e.error;return typeof t=="string"?t:void 0}async function Fp(e){return zp(await e.arrayBuffer())}function zp(e){const t=new Uint8Array(e);let i="";for(const s of t)i+=String.fromCharCode(s);return btoa(i)}async function Up(e,t,i,s){const r=new FormData;r.set("path",i),r.set("file",s,s.name);const o=await fetch(kr(`${C("local")}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`),{method:"POST",body:r});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(Ba(n)??o.statusText)}return Ks(await o.json())}async function Bp(e,t,i,s){const r=await fetch(_a(e,t,i,{machineId:s}));if(!r.ok){const p=await r.json().catch(()=>({}));throw new Error(Ba(p)??r.statusText)}const o=await r.blob(),n=URL.createObjectURL(o),a=document.createElement("a");a.href=n;const c=i.split("/").pop();a.download=c===void 0||c===""?"download":c,document.body.append(a),a.click(),a.remove(),URL.revokeObjectURL(n)}function Np(e){return typeof e=="object"&&e!==null}const Hp={files:(e,t,i={})=>{const s=new URLSearchParams({q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),i.workspaceScoped===!0&&i.projectId!==void 0&&i.workspaceId!==void 0?v(`${C(i.machineId)}/projects/${encodeURIComponent(i.projectId)}/workspaces/${encodeURIComponent(i.workspaceId)}/files?${s.toString()}`,j(Gs)):(s.set("cwd",e),v(`${C(i.machineId)}/files?${s.toString()}`,j(Gs)))}},qp={gitStatus:(e,t,i="local")=>v(`${C(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,dp),gitDiff:(e,t,i,s="local")=>v(Ap(s,e,t,i),hp)},N={...za,...Op,...Mi,...St,...Qs,...Ua,..._p,...kt,...Zs,...$t,...Hp,...qp};function Kp(e,t="local",i=yr()){const s=typeof e=="string"?void 0:e.cwd,r=s===void 0||s===""?"":`?${new URLSearchParams({cwd:s}).toString()}`,o=typeof e=="string"?e:e.id,n=$a(`${Cr(t)}/sessions/${encodeURIComponent(o)}/events${r}`,void 0,i);return new WebSocket(`${Ir()}${n}`)}function kx(e,t,i,s,r="local"){const o=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Ir()}${Cr(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${o}`)}function Vp(e="local",t=yr()){const i=$a(`${Cr(e)}/events`,void 0,t);return new WebSocket(`${Ir()}${i}`)}function Cr(e){return`/api/machines/${encodeURIComponent(e)}`}function Ir(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}const Na=".pi-web/uploads";class es extends Error{constructor(t="Workspace upload cancelled"){super(t),this.name="WorkspaceUploadCancelledError"}}class Ha extends Error{constructor(t,i){super(th(t)),this.name="WorkspaceUploadBatchError",this.failures=t.map(s=>({...s})),this.responses=i.map(s=>({...s}))}}function Wo(e){return e?.uploads?.defaultFolder??Na}function Gp(e,t){return e?.uploads?.defaultFolder??t}function Rr(e,t){const i=Oo(e,"upload destination",{allowEmpty:!0}),s=Oo(t,"upload file name",{allowEmpty:!1});return i===""?s:`${i}/${s}`}function Jp(e,t,i,s={}){const r=s.xhrFactory?.()??new XMLHttpRequest;let o=!1,n=!1;return{promise:new Promise((c,p)=>{const u=g=>{o||(o=!0,p(g))},h=g=>{o||(o=!0,c(g))};r.open("PUT",Mp(e,t,i.path,Xp(s)),!0),r.responseType="json",r.setRequestHeader("Content-Type",(i.contentType??i.file.type)||"application/octet-stream"),r.upload.onprogress=g=>{s.onProgress?.(Yp(g,i.file.size))},r.onload=()=>{if(r.status>=200&&r.status<300){try{s.onProgress?.({loaded:i.file.size,total:i.file.size,percent:1,lengthComputable:!0}),h(Wa(qa(r)))}catch(g){u(g instanceof Error?g:new Error(String(g)))}return}u(new Error(oh(r)))},r.onerror=()=>{u(new Error("Workspace upload failed"))},r.onabort=()=>{u(new es(n?void 0:"Workspace upload aborted"))},r.send(i.file)}),cancel:()=>{o||(n=!0,r.abort())}}}function Qp(e,t,i,s={}){const r=s.destinationFolder??Na,o=i.map((h,g)=>({index:g,name:h.name,path:Rr(r,h.name),loaded:0,total:h.size,percent:Ar(0,h.size),lengthComputable:!0,done:!1}));let n,a=0;const c={requested:!1},p=()=>{s.onProgress?.(eh(o,a,o.every(h=>h.done)))};return{promise:(async()=>{const h=[],g=[];for(let y=0;y<i.length;y+=1){if(c.requested)throw new es;a=y;const P=i[y],I=o[y];if(!(P===void 0||I===void 0)){n=Jp(e,t,{path:I.path,file:P},{...Zp(s),onProgress:G=>{I.total=G.total,I.loaded=Math.min(G.loaded,I.total),I.percent=G.percent,I.lengthComputable=G.lengthComputable,p()}});try{const G=await n.promise;I.loaded=I.total,I.percent=1,I.lengthComputable=!0,I.done=!0,h.push(G),p()}catch(G){if(sh(G,c))throw G;const Ze=ih(G);I.loaded=I.total,I.percent=1,I.lengthComputable=!0,I.done=!0,I.error=Ze,g.push({index:y,name:P.name,path:I.path,error:Ze}),p()}finally{n=void 0}}}if(g.length>0)throw new Ha(g,h);return h})(),cancel:()=>{c.requested=!0,n?.cancel()}}}function Zp(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function Xp(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Yp(e,t){const i=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:i,percent:Ar(e.loaded,i),lengthComputable:e.lengthComputable}}function eh(e,t,i){const s=e.reduce((o,n)=>o+n.total,0),r=e.reduce((o,n)=>o+n.loaded,0);return{currentFileIndex:t,files:e.map(o=>({...o})),loaded:r,total:s,percent:Ar(r,s),done:i}}function Ar(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function th(e){return e.length===1?e[0]?.error??"Workspace upload failed":`${String(e.length)} files failed to upload`}function ih(e){return e instanceof Error?e.message:String(e)}function sh(e,t){return t.requested||e instanceof es}function Oo(e,t,i){const s=e.trim();if(s===""){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(rh(s))throw new Error(`${t} must be workspace-relative`);const r=s.split(/[\\/]+/u).filter(o=>o!==""&&o!==".");if(r.length===0){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(r.some(o=>o===".."))throw new Error(`${t} must not contain path traversal`);return r.join("/")}function rh(e){const t=e.replace(/\\/g,"/");return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}function qa(e){return e.response!==void 0&&e.response!==null&&e.response!==""?e.response:e.responseText===""?{}:JSON.parse(e.responseText)}function oh(e){const t=nh(e);return ah(t)&&typeof t.error=="string"?t.error:e.statusText||`HTTP ${String(e.status)}`}function nh(e){try{return qa(e)}catch{return}}function ah(e){return typeof e=="object"&&e!==null}function wi(){return{sessions:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:""}}function lh(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function tt(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Ka(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const Va="local";function ys(e,t){return`${e}:${t}`}function Ga(e,t){return`${e}:${t}`}function f(e){return e.selectedMachine?.id??Va}class ch{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??Ua}async refresh(t=f(this.getState())){this.applyMachineActivitySnapshot(t,dh(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=f(this.getState())){const s=this.getState(),r=f(s)===i,o=s.machineActivities[i]??(r?s.workspaceActivities:{}),n=ph(o,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...r?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...f(s)===t?{workspaceActivities:i}:{}})}}function dh(e){const t={};for(const i of e.workspaces)Ka(i)&&(t[i.cwd]=i);return t}function ph(e,t){const i={...e};return Ka(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class hh{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=r.api??N,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=uh(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:f(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const r=s.providers.find(o=>o.id===t&&(i===void 0||o.authType===i));r!==void 0&&(r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({authDialog:{...t,saving:!1,error:String(r)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:f(this.getState())});if(t!==void 0&&t!==""){const s=i.find(r=>r.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(r=>r.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,f(this.getState())),this.closeDialog(),this.refreshStatus()}catch(r){this.setState({error:String(r)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const r=t??i.inputValue??"",o={...i};delete o.error,this.setState({authDialog:{...o,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,r,f(this.getState()));this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...i,responding:!1,error:String(n)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,f(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:f(this.getState())}),s=i.filter(o=>o.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const r=s[0];if(r===void 0)return;r.authType==="oauth"?await this.startOAuth(r):this.setState({authDialog:{step:"apiKey",provider:r,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,f(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const r=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${r}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",r=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,o=t.prompt?.requestId??t.select?.requestId,n=r!==void 0&&r===o,a=n?s:"",c=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:c}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t,f(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.session();if(t!==void 0)try{this.applyStatus(await this.api.status(t,f(this.getState())))}catch{}}session(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t}}function uh(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const r=i[2];return r===void 0||r===""?{command:s}:{command:s,providerId:r}}function ei(e){return e.replaceAll(":",".")}function fh(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[r,o]of t.entries()){if(!r.startsWith(i))continue;const n=r.slice(i.length),a=s[n];a===void 0?s[n]=o:Array.isArray(a)?a.push(o):s[n]=[a,o]}return s}function xs(e,t){const i=fh(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function ue(e,t,i,s){const r=new URL(window.location.href),o=`${e}--${t}`;if(r.searchParams.delete(o),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)r.searchParams.append(o,String(n));else r.searchParams.set(o,String(i));gh(r,s)}function gh(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}function mh(e){const t=e.files.map((s,r)=>{const o=s.size;return{index:r,name:s.name,path:Rr(e.destinationFolder,s.name),size:s.size,loaded:0,total:o,percent:Lo(0,o),lengthComputable:!0,status:r===0?"uploading":"pending"}}),i=t.reduce((s,r)=>s+r.total,0);return{id:e.id,projectId:e.projectId,workspaceId:e.workspaceId,machineId:e.machineId,destinationFolder:e.destinationFolder,overwrite:e.overwrite,createDirs:e.createDirs,files:t,currentFileIndex:t.length===0?-1:0,loaded:0,total:i,percent:Lo(0,i),status:"uploading",startedAt:e.startedAt}}function vh(e,t){const i=new Map(t.files.map(r=>[r.index,r])),s=e.files.map(r=>{const o=i.get(r.index);if(o===void 0)return r;const n={...r,path:o.path,loaded:o.loaded,total:o.total,percent:o.percent,lengthComputable:o.lengthComputable,status:o.error!==void 0?"error":o.done?"completed":t.currentFileIndex===r.index?"uploading":r.status};return o.error===void 0?delete n.error:n.error=o.error,n});return{...e,files:s,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function bh(e,t,i){const s=e.files.map((o,n)=>{const a=t[n];return{...o,...a===void 0?{}:{path:a.path,response:a},loaded:o.total,percent:1,lengthComputable:!0,status:"completed"}}),r=Tr(s);return{...e,files:s,currentFileIndex:s.length===0?-1:s.length-1,...r,status:"completed",completedAt:i}}function wh(e,t,i){const s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:r.status==="uploading"||r.index===e.currentFileIndex?{...r,status:"error",error:t}:{...r,status:"cancelled",error:"Not uploaded because an earlier file failed."});return{...e,files:s,...Tr(s),status:"error",error:t,completedAt:i}}function _o(e,t){const i="Upload cancelled",s=e.files.map(r=>r.status==="completed"||r.status==="error"?r:{...r,status:"cancelled",error:i});return{...e,files:s,...Tr(s),status:"cancelled",error:i,completedAt:t}}function Tr(e){const t=e.reduce((i,s)=>i+s.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function Lo(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}const ci=ei("core:workspace.files");class yh{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??N,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??Qp,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=f(this.getState()),r=await this.api.workspaceTree(t.id,i.id,"",s),o=await Promise.all(Object.keys(this.getState().expandedDirs).map(async a=>{try{const c=await this.api.workspaceTree(t.id,i.id,a,s);return[a,c.entries]}catch(c){if(jo(c))return;throw c}})),n=Object.fromEntries(o.filter(a=>a!==void 0));this.setState({fileTree:r.entries,expandedDirs:n,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:Fo(this.getState().expandedDirs,t)});return}try{const r=await this.api.workspaceTree(i.id,s.id,t,f(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:r.entries},error:""})}catch(r){this.setState({error:String(r)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),ue(ci,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}selectDirectory(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),ue(ci,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}async restoreFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){this.setState({selectedFilePath:t,selectedFileContent:void 0});try{const r=await this.api.workspaceFile(i.id,s.id,t,f(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:r,error:""})}catch(r){if(this.getState().selectedFilePath!==t)return;if(jo(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),ue(ci,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}async createFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceFile(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),await this.selectFile(t),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async createDirectory(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceDirectory(i.id,s.id,t,f(this.getState())),await this.refreshFiles(),this.selectDirectory(t),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async moveSelectedPath(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace,r=this.getState().selectedFilePath;if(!(i===void 0||s===void 0||r===void 0||r===""||t===""))try{const o=f(this.getState());Ss(this.getState())==="directory"?(await this.api.moveWorkspaceDirectory(i.id,s.id,r,t,o),await this.refreshFiles(),this.selectDirectory(t)):(await this.api.moveWorkspaceFile(i.id,s.id,r,t,void 0,o),await this.refreshFiles(),await this.selectFile(t)),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async deleteSelectedPath(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""))try{const r=f(this.getState());Ss(this.getState())==="directory"?await this.api.deleteWorkspaceDirectory(t.id,i.id,s,r):await this.api.deleteWorkspaceFile(t.id,i.id,s,r),await this.refreshFiles(),this.clearSelection(),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async downloadSelectedFile(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""||Ss(this.getState())==="directory"))try{await this.api.downloadWorkspaceFile(t.id,i.id,s,f(this.getState())),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),ue(ci,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}startWorkspaceUpload(t,i){const s=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(s===void 0||r===void 0){this.setState({error:"Select a workspace before uploading files."});return}if(t.length===0)return;const o=f(this.getState()),n=i.overwrite??!1,a=i.createDirs??!0;let c;try{c=mh({id:this.createUploadBatchId(),projectId:s.id,workspaceId:r.id,machineId:o,destinationFolder:i.destinationFolder,overwrite:n,createDirs:a,files:t,startedAt:this.now()})}catch(h){this.setState({error:String(h)});return}this.setUploadBatch(c);let p;try{p=this.uploadWorkspaceFiles(s.id,r.id,t,{destinationFolder:i.destinationFolder,machineId:o,overwrite:n,createDirs:a,onProgress:h=>{this.updateUploadProgress(c.id,h)}})}catch(h){return this.failUploadBatch(c.id,h),{batchId:c.id,done:Promise.resolve()}}this.uploadTasks.set(c.id,p);const u=p.promise.then(async h=>{await this.completeUploadBatch(c.id,h,i)}).catch(async h=>{await this.handleUploadFailure(c.id,h,i)}).finally(()=>{this.uploadTasks.delete(c.id)});return{batchId:c.id,done:u}}cancelWorkspaceUpload(t){const i=this.getUploadBatch(t);i?.status==="uploading"&&(this.setUploadBatch(_o(i,this.now())),this.uploadTasks.get(t)?.cancel())}clearWorkspaceUpload(t){this.uploadTasks.get(t)?.cancel(),this.uploadTasks.delete(t),this.setState({workspaceUploadBatches:Fo(this.getState().workspaceUploadBatches,t)})}updateUploadProgress(t,i){const s=this.getUploadBatch(t);s?.status==="uploading"&&this.setUploadBatch(vh(s,i))}async completeUploadBatch(t,i,s){const r=this.getUploadBatch(t);if(r?.status!=="uploading"||(this.setUploadBatch(bh(r,i,this.now()),{error:""}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();const o=i[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}async handleUploadFailure(t,i,s){const r=this.failUploadBatch(t,i);if(!(i instanceof Ha)||i.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshFiles();const o=i.responses[0]?.path;s.selectUploadedFile!==!1&&o!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(o)}failUploadBatch(t,i){const s=this.getUploadBatch(t);if(s?.status!=="uploading")return;if(xh(i)){const n=_o(s,this.now());return this.setUploadBatch(n),n}const r=Sh(i),o=wh(s,r,this.now());return this.setUploadBatch(o,{error:r}),o}getUploadBatch(t){return this.getState().workspaceUploadBatches[t]}setUploadBatch(t,i={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[t.id]:t},...i})}isCurrentWorkspaceBatch(t){const i=this.getState();return i.selectedProject?.id===t.projectId&&i.selectedWorkspace?.id===t.workspaceId&&f(i)===t.machineId}}function jo(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function xh(e){return e instanceof es}function Sh(e){return e instanceof Error?e.message:String(e)}function Fo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Ss(e){const t=e.selectedFilePath;return t===void 0?"file":kh(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function kh(e,t,i){const s=e.find(r=>r.path===i);if(s!==void 0)return s;for(const r of Object.values(t)){const o=r.find(n=>n.path===i);if(o!==void 0)return o}}const zo=ei("core:workspace.git");class $h{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await N.gitStatus(t.id,i.id,f(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const r=this.getState().selectedDiffPath;r!==void 0&&(s.files.some(o=>o.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),ue(zo,"diff",void 0,{replace:!0})))}catch(s){this.setState({error:String(s)})}}async selectDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),ue(zo,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[r,o]=await Promise.all([N.gitDiff(i.id,s.id,{path:t},f(this.getState())),N.gitDiff(i.id,s.id,{path:t,staged:!0},f(this.getState()))]);this.setState({selectedDiff:r,selectedStagedDiff:o,error:""})}catch(r){this.setState({error:String(r)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class Ph{constructor(t,i,s,r){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=r}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await N.machines(),s=await this.selectInitialMachine(i,t),r=new Set(i.map(o=>o.id));this.setState({machines:i,selectedMachine:s,machineActivities:Uo(this.getState().machineActivities,r),machineRuntimes:Uo(this.getState().machineRuntimes,r)}),this.refreshMachineHealthFor(i),this.refreshMachineRuntimeFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...wi()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id),this.refreshMachineRuntime(t.id))}async addMachine(t){this.setState({error:""});try{const i=await N.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await N.deleteMachine(t.id);const r=this.getState().machines.filter(n=>n.id!==t.id),o=r.find(n=>n.id==="local")??r[0];return this.setState({machines:r,machineStatuses:ks(this.getState().machineStatuses,t.id),machineRuntimes:ks(this.getState().machineRuntimes,t.id),machineActivities:ks(this.getState().machineActivities,t.id)}),s&&o!==void 0?(i.selectFallback===!1||await this.selectMachine(o),o):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await N.health(t);return this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}}),i}catch(i){this.setState({error:String(i)});return}}async refreshMachineRuntime(t=this.getState().selectedMachine?.id??"local"){try{const i=await N.runtime(t);this.setState({machineRuntimes:{...this.getState().machineRuntimes,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(o=>o.id===(i??"local"));if(s===void 0)return this.localMachine(t);if(s.kind!=="remote")return s;const r=await this.safeRemoteHealth(s);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${s.name} is unavailable; reconnecting…`}}),s}async safeRemoteHealth(t){try{return await N.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(r=>N.health(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}async refreshMachineRuntimeFor(t){const i=await Promise.allSettled(t.map(r=>N.runtime(r.id))),s=Object.fromEntries(i.flatMap(r=>r.status==="fulfilled"?[[r.value.machineId,r.value]]:[]));Object.keys(s).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...s}})}}function ks(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Uo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class Ch{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=f(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await N.projects(t);if(f(this.getState())!==t)return;const s=new Set(i.map(o=>o.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([o])=>s.has(o)));this.setState({projects:i,workspacesByProjectId:r})}catch(i){f(this.getState())===t&&this.setState({error:String(i)})}finally{f(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await N.addProject(t.trim(),void 0,i,f(this.getState())),r=this.getState().projects;this.setState({projects:[...r.filter(o=>o.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await N.closeProject(t,f(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const Xs="pi-web:cached-new-sessions:v1",Ih="browserCachedNew",Mt="local";function ti(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Bo(e,t=Mt,i=ti()){if(e.messageCount!==0||e.archived===!0)return;const s=Mr(i).filter(r=>r.id!==e.id||r.machineId!==t);Er([Ys(e,t),...s],i)}function Ys(e,t=Mt){return{...e,browserCachedNew:!0,machineId:t}}function No(e,t=Mt,i=ti()){const s=Mr(i).filter(r=>r.id!==e||r.machineId!==t);Er(s,i)}function Ja(e,t,i=Mt,s=ti()){const r=new Set(t.map(c=>c.id)),o=Mr(s),n=o.filter(c=>c.machineId!==i||!r.has(c.id));return n.length!==o.length&&Er(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function Y(e){return e===void 0?!1:Th(e)&&e.browserCachedNew===!0}function Rh(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},..."machineId"in e&&typeof e.machineId=="string"?{machineId:e.machineId}:{machineId:Mt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Mr(e=ti()){try{const t=e?.getItem(Xs);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>Ah(s)):[]}catch{return[]}}function Er(e,t=ti()){try{e.length===0?t?.removeItem(Xs):t?.setItem(Xs,JSON.stringify(e))}catch{}}function Ah(e){if(!Mh(e))return[];const t=bt(e,"id"),i=bt(e,"path"),s=bt(e,"cwd"),r=bt(e,"created"),o=bt(e,"modified"),n=bt(e,"firstMessage"),a=Eh(e,"messageCount");if(t===void 0||i===void 0||s===void 0||r===void 0||o===void 0||n===void 0||a!==0)return[];const c=$s(e,"name"),p=$s(e,"parentSessionPath"),u=$s(e,"machineId")??Mt;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:r,modified:o,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function Th(e){return Ih in e}function Mh(e){return typeof e=="object"&&e!==null}function bt(e,t){const i=e[t];return typeof i=="string"?i:void 0}function $s(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Eh(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Dh(e){return Jh(e.flatMap(Dr)).filter(t=>t.parts.length>0)}function Le(e,t){return{role:e,parts:[{type:"text",text:t}]}}function _t(e,t){const i=Uh(t);return i===void 0?e:{...e,meta:i}}function Wh(e,t,i){if(i==="")return e;const s=e.at(-1),r=s?.parts.at(-1);return s?.role===t&&r?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...r,text:r.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,Le(t,i)]}function Oh(e,t){if(t==="")return e;const i=e.at(-1),s=i?.parts.at(-1);return i?.role==="assistant"&&s?.type==="thinking"?[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+t}]}]:i?.role==="assistant"?[...e.slice(0,-1),{...i,parts:[...i.parts,{type:"thinking",text:t}]}]:[...e,{role:"assistant",parts:[{type:"thinking",text:t}]}]}function Dr(e){if(Lh(e))return[e];if(_(e,"role")==="bashExecution")return[_t(Hh(e),e)];const t=qh(_(e,"role")),i=Kh(ye(e,"content"),e),s=t==="user"?jh(i):void 0;if(s!==void 0)return s.map(p=>_t(p,e));const r=zh(e);if(t==="tool")return[_t({role:t,parts:i,...r===void 0?{}:{source:r}},e)];const o=i.filter(p=>p.type!=="empty"),n=t==="assistant"&&o.length>0&&o.every(p=>p.type==="skillRead")?"skill":t,a=o.length>0?[_t({role:n,parts:o,...r===void 0?{}:{source:r}},e)]:[],c=_h(e);return c===void 0?a:[...a,_t(c,e)]}function _h(e){if(_(e,"role")!=="assistant"||_(e,"stopReason")!=="error")return;const t=_(e,"errorMessage")?.trim();return Le("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function Lh(e){const t=_(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(ye(e,"parts"))}function jh(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Fh(e[0].text);if(t!==void 0)return[{role:"user",parts:[{type:"skillInvocation",name:t.name,location:t.location,content:t.content}]},...t.userMessage===void 0?[]:[{role:"user",parts:[{type:"text",text:t.userMessage}]}]]}function Fh(e){const t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;const i=t[4]?.trim();return{name:t[1]??"skill",location:t[2]??"",content:t[3]??"",...i===void 0||i===""?{}:{userMessage:i}}}function zh(e){const t=_(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Uh(e){const t=Bh(ye(e,"timestamp")),i=Nh(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Bh(e){if(typeof e=="number"&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!="string"||e==="")return;const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function Nh(e){if(_(e,"role")!=="assistant")return;const t=_(e,"provider"),i=_(e,"model"),s=_(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function Hh(e){const t=_(e,"command")??"",i=yi(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=ye(e,"output");s!=null&&i.push("",Di(s));const r=ye(e,"exitCode");r!=null&&i.push("",`exit ${Di(r)}`),yi(e,"cancelled")===!0&&i.push("","cancelled"),yi(e,"truncated")===!0&&i.push("","output truncated");const o=_(e,"fullOutputPath");return o!==void 0&&o!==""&&i.push("",`full output: ${o}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
- `)}]}}function qh(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function Kh(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=_(i,"type"),r=_(i,"text");if(s==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(s==="thinking"){const o=_(i,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}if(s==="toolCall"){const o=_(i,"name")??"tool",n=ye(i,"arguments"),a=_(i,"id"),c=o==="read"?Gh(_(n,"path")):void 0;return c!==void 0?[{type:"skillRead",...c,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:o,summary:ii(n),...n===void 0?{}:{args:n}}]}if(s==="image"){const o=_(i,"data"),n=_(i,"mimeType");return o!==void 0&&o!==""&&n!==void 0&&n!==""?[{type:"image",mimeType:n,data:o}]:[{type:"text",text:"[image]"}]}return Ho(i)}).map(i=>i.type==="text"&&_(t,"role")==="toolResult"?Vh(i.text,t):i):Ho(e)}function Vh(e,t){const i=_(t,"toolCallId"),s=ye(t,"content"),r=ye(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:_(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...r===void 0?{}:{details:r},isError:yi(t,"isError")===!0}}function Gh(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function Jh(e){const t=[],i=new Map;for(const s of e){let r=[];const o={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{r.length!==0&&(t.push({role:s.role,parts:r,...o}),r=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=Qh(a),p=t.length;t.push({role:"tool",parts:[c],...o}),c.toolCallId!==void 0&&i.set(c.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const c=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(c!==void 0&&Zh(t,c,a)){i.delete(a.toolCallId??"");continue}}r.push(a)}n()}return t}function Qh(e){return{type:"toolExecution",...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.args===void 0?{}:{args:e.args},status:"pending"}}function Zh(e,t,i){const s=e[t.lineIndex],r=s?.parts[t.partIndex];if(s===void 0||r?.type!=="toolExecution")return!1;const o=Ei(i.details)??r.preview,n={...r,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...o===void 0?{}:{preview:o}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function Ei(e){const t=ye(e,"preview");if(!Wr(t))return;const i=_(t,"diff"),s=_(t,"error"),r=Yh(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&r===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...r===void 0?{}:{firstChangedLine:r}}}function Ho(e){return e==null?[]:typeof e=="object"?[{type:"text",text:ii(e)}]:[{type:"text",text:Di(e)}]}function ii(e){if(!Wr(e))return Di(e);const t=_(e,"command");if(t!==void 0)return t;const i=_(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} edit${s.length===1?"":"s"}`:Object.entries(e).filter(([,o])=>o!=null).slice(0,3).map(([o,n])=>`${o}: ${Xh(n)}`).join(" · ")}function Xh(e){return typeof e=="string"?e.length>80?`${e.slice(0,77)}…`:e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?"":"s"}`:typeof e=="object"&&e!==null?"object":""}function Wr(e){return typeof e=="object"&&e!==null}function ye(e,t){return Wr(e)?e[t]:void 0}function _(e,t){const i=ye(e,t);return typeof i=="string"?i:void 0}function yi(e,t){const i=ye(e,t);return typeof i=="boolean"?i:void 0}function Yh(e,t){const i=ye(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function Di(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const eu="pi-web:prompt-draft:";function Wi(e){return`${eu}${e}`}function ts(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Qa(e,t=ts()){try{return t?.getItem(Wi(e))??""}catch{return""}}function Oi(e,t,i=ts()){try{t?i?.setItem(Wi(e),t):i?.removeItem(Wi(e))}catch{}}function Or(e,t=ts()){try{t?.removeItem(Wi(e))}catch{}}function tu(e,t,i=ts()){const s=Qa(e,i);s!==""&&(Oi(t,s,i),Or(e,i))}function iu(e,t){return Le("bash",`${t===!0?`不加入上下文
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-DssF-c9D.js","assets/vendor-editor-core-C7aWiQy0.js","assets/vendor-editor-languages-EW34FfVy.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/UnifiedDiffViewer-D_OLq3Q4.js","assets/TerminalPanel-8Or6pbwb.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
+ import{Q as Eo,v as ut,J as _s,R as sd,S as rd,G as od,U as nd,V as ad,W as ld,A as cd,X as dd,Y as pd,Z as Do,w as Wo,_ as hd}from"./vendor-editor-core-C7aWiQy0.js";import{m as ud,d as fd,i as gd}from"./vendor-editor-languages-EW34FfVy.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const n of o.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=i(r);fetch(r.href,o)}})();const Fi=globalThis,Or=Fi.ShadowRoot&&(Fi.ShadyCSS===void 0||Fi.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Fr=Symbol(),Lo=new WeakMap;let Ya=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==Fr)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(Or&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=Lo.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&Lo.set(i,t))}return t}toString(){return this.cssText}};const md=e=>new Ya(typeof e=="string"?e:e+"",void 0,Fr),D=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,r,o)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+e[o+1],e[0]);return new Ya(i,e,Fr)},vd=(e,t)=>{if(Or)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),r=Fi.litNonce;r!==void 0&&s.setAttribute("nonce",r),s.textContent=i.cssText,e.appendChild(s)}},Oo=Or?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return md(i)})(e):e;const{is:bd,defineProperty:wd,getOwnPropertyDescriptor:yd,getOwnPropertyNames:Sd,getOwnPropertySymbols:xd,getPrototypeOf:kd}=Object,ws=globalThis,Fo=ws.trustedTypes,$d=Fo?Fo.emptyScript:"",Pd=ws.reactiveElementPolyfillSupport,li=(e,t)=>e,Gi={toAttribute(e,t){switch(t){case Boolean:e=e?$d: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}},_r=(e,t)=>!bd(e,t),_o={attribute:!0,type:String,converter:Gi,reflect:!1,useDefault:!1,hasChanged:_r};Symbol.metadata??=Symbol("metadata"),ws.litPropertyMetadata??=new WeakMap;let Dt=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=_o){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const s=Symbol(),r=this.getPropertyDescriptor(t,s,i);r!==void 0&&wd(this.prototype,t,r)}}static getPropertyDescriptor(t,i,s){const{get:r,set:o}=yd(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)??_o}static _$Ei(){if(this.hasOwnProperty(li("elementProperties")))return;const t=kd(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(li("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(li("properties"))){const i=this.properties,s=[...Sd(i),...xd(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(Oo(r))}else t!==void 0&&i.push(Oo(t));return i}static _$Eu(t,i){const s=i.attribute;return s===!1?void 0:typeof s=="string"?s:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,i=this.constructor.elementProperties;for(const s of i.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return vd(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:Gi).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:Gi;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??_r)(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){}};Dt.elementStyles=[],Dt.shadowRootOptions={mode:"open"},Dt[li("elementProperties")]=new Map,Dt[li("finalized")]=new Map,Pd?.({ReactiveElement:Dt}),(ws.reactiveElementVersions??=[]).push("2.1.2");const jr=globalThis,jo=e=>e,Qi=jr.trustedTypes,Uo=Qi?Qi.createPolicy("lit-html",{createHTML:e=>e}):void 0,el="$lit$",lt=`lit$${Math.random().toFixed(9).slice(2)}$`,tl="?"+lt,Cd=`<${tl}>`,kt=document,pi=()=>kt.createComment(""),hi=e=>e===null||typeof e!="object"&&typeof e!="function",Ur=Array.isArray,Rd=e=>Ur(e)||typeof e?.[Symbol.iterator]=="function",js=`[
3
+ \f\r]`,Kt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Bo=/-->/g,zo=/>/g,ft=RegExp(`>|${js}(?:([^\\s"'>=/]+)(${js}*=${js}*(?:[^
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),No=/'/g,qo=/"/g,il=/^(?:script|style|textarea|title)$/i,sl=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=sl(1),$e=sl(2),ct=Symbol.for("lit-noChange"),B=Symbol.for("lit-nothing"),Ho=new WeakMap,wt=kt.createTreeWalker(kt,129);function rl(e,t){if(!Ur(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Uo!==void 0?Uo.createHTML(t):t}const Id=(e,t)=>{const i=e.length-1,s=[];let r,o=t===2?"<svg>":t===3?"<math>":"",n=Kt;for(let a=0;a<i;a++){const d=e[a];let p,u,h=-1,g=0;for(;g<d.length&&(n.lastIndex=g,u=n.exec(d),u!==null);)g=n.lastIndex,n===Kt?u[1]==="!--"?n=Bo:u[1]!==void 0?n=zo:u[2]!==void 0?(il.test(u[2])&&(r=RegExp("</"+u[2],"g")),n=ft):u[3]!==void 0&&(n=ft):n===ft?u[0]===">"?(n=r??Kt,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?ft:u[3]==='"'?qo:No):n===qo||n===No?n=ft:n===Bo||n===zo?n=Kt:(n=ft,r=void 0);const S=n===ft&&e[a+1].startsWith("/>")?" ":"";o+=n===Kt?d+Cd:h>=0?(s.push(p),d.slice(0,h)+el+d.slice(h)+lt+S):d+lt+(h===-2?a:S)}return[rl(e,o+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class ui{constructor({strings:t,_$litType$:i},s){let r;this.parts=[];let o=0,n=0;const a=t.length-1,d=this.parts,[p,u]=Id(t,i);if(this.el=ui.createElement(p,s),wt.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(r=wt.nextNode())!==null&&d.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const h of r.getAttributeNames())if(h.endsWith(el)){const g=u[n++],S=r.getAttribute(h).split(lt),P=/([.?@])?(.*)/.exec(g);d.push({type:1,index:o,name:P[2],strings:S,ctor:P[1]==="."?Md:P[1]==="?"?Td:P[1]==="@"?Ed:ys}),r.removeAttribute(h)}else h.startsWith(lt)&&(d.push({type:6,index:o}),r.removeAttribute(h));if(il.test(r.tagName)){const h=r.textContent.split(lt),g=h.length-1;if(g>0){r.textContent=Qi?Qi.emptyScript:"";for(let S=0;S<g;S++)r.append(h[S],pi()),wt.nextNode(),d.push({type:2,index:++o});r.append(h[g],pi())}}}else if(r.nodeType===8)if(r.data===tl)d.push({type:2,index:o});else{let h=-1;for(;(h=r.data.indexOf(lt,h+1))!==-1;)d.push({type:7,index:o}),h+=lt.length-1}o++}}static createElement(t,i){const s=kt.createElement("template");return s.innerHTML=t,s}}function _t(e,t,i=e,s){if(t===ct)return t;let r=s!==void 0?i._$Co?.[s]:i._$Cl;const o=hi(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=_t(e,r._$AS(e,t.values),r,s)),t}class Ad{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??kt).importNode(i,!0);wt.currentNode=r;let o=wt.nextNode(),n=0,a=0,d=s[0];for(;d!==void 0;){if(n===d.index){let p;d.type===2?p=new zt(o,o.nextSibling,this,t):d.type===1?p=new d.ctor(o,d.name,d.strings,this,t):d.type===6&&(p=new Dd(o,this,t)),this._$AV.push(p),d=s[++a]}n!==d?.index&&(o=wt.nextNode(),n++)}return wt.currentNode=kt,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 zt{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,r){this.type=2,this._$AH=B,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=_t(this,t,i),hi(t)?t===B||t==null||t===""?(this._$AH!==B&&this._$AR(),this._$AH=B):t!==this._$AH&&t!==ct&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Rd(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!==B&&hi(this._$AH)?this._$AA.nextSibling.data=t:this.T(kt.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=ui.createElement(rl(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(i);else{const o=new Ad(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 ui(t)),i}k(t){Ur(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 zt(this.O(pi()),this.O(pi()),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=jo(t).nextSibling;jo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let ys=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,r,o){this.type=1,this._$AH=B,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=B}_$AI(t,i=this,s,r){const o=this.strings;let n=!1;if(o===void 0)t=_t(this,t,i,0),n=!hi(t)||t!==this._$AH&&t!==ct,n&&(this._$AH=t);else{const a=t;let d,p;for(t=o[0],d=0;d<o.length-1;d++)p=_t(this,a[s+d],i,d),p===ct&&(p=this._$AH[d]),n||=!hi(p)||p!==this._$AH[d],p===B?t=B:t!==B&&(t+=(p??"")+o[d+1]),this._$AH[d]=p}n&&!r&&this.j(t)}j(t){t===B?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Md=class extends ys{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===B?void 0:t}},Td=class extends ys{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==B)}},Ed=class extends ys{constructor(t,i,s,r,o){super(t,i,s,r,o),this.type=5}_$AI(t,i=this){if((t=_t(this,t,i,0)??B)===ct)return;const s=this._$AH,r=t===B&&s!==B||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,o=t!==B&&(s===B||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)}},Dd=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){_t(this,t)}};const Wd={I:zt},Ld=jr.litHtmlPolyfillSupport;Ld?.(ui,zt),(jr.litHtmlVersions??=[]).push("3.3.3");const Od=(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 zt(t.insertBefore(pi(),o),o,void 0,i??{})}return r._$AI(e),r};const Br=globalThis;let I=class extends Dt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=Od(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return ct}};I._$litElement$=!0,I.finalized=!0,Br.litElementHydrateSupport?.({LitElement:I});const Fd=Br.litElementPolyfillSupport;Fd?.({LitElement:I});(Br.litElementVersions??=[]).push("4.2.2");const W=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const _d={attribute:!0,type:String,converter:Gi,reflect:!1,hasChanged:_r},jd=(e=_d,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 d=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,d,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 d=this[n];t.call(this,a),this.requestUpdate(n,d,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function c(e){return(t,i)=>typeof i=="object"?jd(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 v(e){return c({...e,state:!0,attribute:!1})}const Ud=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function q(e,t){return(i,s,r)=>{const o=n=>n.renderRoot?.querySelector(e)??null;return Ud(i,s,{get(){return o(this)}})}}function zr(e=qr()){return Nr(e)===void 0?"normal":"management"}function Ss(e,t=qr(),i="management"){if(i==="normal"||t===void 0)return e;const s=Nr(t);if(s===void 0)return e;const r=new URL(e,t.origin);return r.searchParams.set("embed",s.embed),r.searchParams.set("token",s.token),`${r.pathname}${r.search}${r.hash}`}function ol(e,t=qr(),i="management"){if(i==="normal"||t===void 0)return e;const s=Nr(t);if(s===void 0)return e;const r=new URL(e,t.origin);return r.searchParams.set("embed",s.embed),r.searchParams.set("token",s.token),`${r.pathname}${r.search}`}function Nr(e){if(e===void 0)return;const t=e.searchParams.get("embed"),i=e.searchParams.get("token")?.trim();if(!(t!=="management"||i===void 0||i===""))return{embed:t,token:i}}function qr(){if(typeof globalThis.location>"u")return;const e=globalThis.location;if(typeof e.href=="string"&&e.href!=="")return new URL(e.href);const t=typeof e.protocol=="string"&&e.protocol!==""?e.protocol:"http:",i=typeof e.host=="string"&&e.host!==""?e.host:"localhost",s=typeof e.search=="string"?e.search:"";return new URL(`${t}//${i}/${s}`)}let nl=zr();function Bd(e){nl=e}function Hr(e){return Ss(e,void 0,nl)}async function b(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(Hr(e),{...i,headers:s});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(al(n)??r.statusText)}const o=await r.json();return t(o)}async function zd(e,t){const i=await fetch(Hr(e));if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(al(s)??i.statusText)}return t(await i.json())}}function al(e){if(Nd(e))return typeof e.error=="string"?e.error:void 0}function Nd(e){return typeof e=="object"&&e!==null}function Ke(e){return typeof e=="object"&&e!==null}function y(e){if(!Ke(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 V(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function he(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 T(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function j(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function pt(e,t){if(y(e)[t]!==!0)throw new Error(`Expected ${t} response`);return!0}function w(e,t){return t===void 0?{}:{[e]:t}}const we={sessionsDeleteArchived:"sessions.deleteArchived",sessionsBulkMutations:"sessions.bulkMutations",sessionsCleanup:"sessions.cleanup",sessionsReload:"sessions.reload",sessionsPersistedState:"sessions.persistedState",promptAttachments:"prompt.attachments",workspaceFileSuggestions:"workspace.fileSuggestions",piPackagesManage:"piPackages.manage",selectedMachineSettings:"settings.selectedMachine"},qd=Object.values(we),Hd=new Set(qd);function Kd(e){return typeof e=="string"&&Hd.has(e)}function Pe(e,t){return e?.capabilities?.includes(t)===!0}function Vd(e){if(!(!Array.isArray(e)||!e.every(t=>typeof t=="string")))return e.filter(Kd)}function Ko(e){const t=y(e);return{path:m(t,"path"),exists:T(t,"exists"),config:Vo(t.config),effectiveConfig:Vo(t.effectiveConfig),envOverrides:tp(t.envOverrides)}}function Vo(e){const t=y(e);return{...w("host",$(t,"host")),...w("port",he(t,"port")),...w("allowedHosts",Qd(t.allowedHosts)),...w("shortcuts",Yd(t.shortcuts)),...w("plugins",ep(t.plugins)),...w("normalAuth",Gd(t.normalAuth)),...w("pathAccess",Jd(t.pathAccess)),...w("uploads",Xd(t.uploads)),...w("maxUploadBytes",he(t,"maxUploadBytes")),...w("spawnSessions",Qo(t,"spawnSessions")),...w("subsessions",Qo(t,"subsessions"))}}function Gd(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid PI WEB normalAuth field");return{...w("passwordHash",$(e,"passwordHash"))}}}function Qd(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 Jd(e){if(e===void 0)return;if(!Ke(e)||Array.isArray(e))throw new Error("Invalid PI WEB pathAccess field");const t=e.allowedPaths;return{...w("allowedPaths",Zd(t,"pathAccess.allowedPaths"))}}function Zd(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 Xd(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid PI WEB uploads field");return{...w("defaultFolder",$(e,"defaultFolder"))}}}function Yd(e){if(e!==void 0){if(!Ke(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 ep(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!Ke(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&&(!Ke(r)||Array.isArray(r)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function tp(e){const t=y(e);return{host:T(t,"host"),port:T(t,"port"),allowedHosts:T(t,"allowedHosts"),spawnSessions:T(t,"spawnSessions"),subsessions:T(t,"subsessions")}}function ip(e){const t=y(e);return{plugins:j(sp)(t.plugins)}}function sp(e){const t=y(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:rp(t.scope),machineSpecific:up(t.machineSpecific,"machineSpecific")??!1,enabled:T(t,"enabled")}}function rp(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function op(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:ap(t.components),release:cp(t.release),commands:dp(t.commands),messages:j(pp)(t.messages)}}function np(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:ll(t.components),capabilities:Kr(t.capabilities)}}function ap(e){const t=y(e);return{web:Ji(t.web),sessiond:Ji(t.sessiond)}}function ll(e){const t=y(e);return{web:Go(t.web),sessiond:Go(t.sessiond)}}function Go(e){const t=y(e);return{component:cl(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),available:T(t,"available"),capabilities:Kr(t.capabilities),...w("error",$(t,"error"))}}function Ji(e){const t=y(e);return{component:cl(t.component),label:m(t,"label"),...w("runtimeVersion",$(t,"runtimeVersion")),...w("installedVersion",$(t,"installedVersion")),stale:T(t,"stale"),available:T(t,"available"),...w("installation",lp(t.installation)),...w("error",$(t,"error"))}}function lp(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="docker"&&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");const r=t.dockerMode;if(r!==void 0&&r!=="runtime"&&r!=="dev")throw new Error("Invalid PI WEB Docker mode");return{kind:i,...w("path",$(t,"path")),...w("source",$(t,"source")),...s===void 0?{}:{scope:s},...w("npmRoot",$(t,"npmRoot")),...r===void 0?{}:{dockerMode:r}}}function cp(e){const t=y(e);return{packageName:m(t,"packageName"),...w("latestVersion",$(t,"latestVersion")),updateAvailable:T(t,"updateAvailable"),...w("checkedAt",$(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...w("error",$(t,"error"))}}function dp(e){const t=y(e);return{...w("update",$(t,"update")),...w("restart",$(t,"restart")),...w("restartWeb",$(t,"restartWeb")),...w("restartSessiond",$(t,"restartSessiond")),...w("status",$(t,"status"))}}function pp(e){const t=y(e);return{id:m(t,"id"),severity:hp(t.severity),title:m(t,"title"),body:m(t,"body"),...w("command",$(t,"command"))}}function cl(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function Kr(e){const t=Vd(e);if(t===void 0)throw new Error("Invalid PI WEB capabilities");return t}function hp(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function up(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function Qo(e,t){const i=e[t];if(i!==void 0){if(typeof i!="boolean")throw new Error(`Invalid PI WEB ${t} field`);return i}}function fp(e){const t=y(e);return j(dl)(t.machines)}function dl(e){const t=y(e),i=vp(t,"kind"),s=$(t,"baseUrl"),r=pl(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 gp(e){const t=y(e),i=pl(t,"status"),s=$(t,"error");return{machineId:m(t,"machineId"),ok:T(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:Ji(t.web)},...t.sessiond===void 0?{}:{sessiond:Ji(t.sessiond)},...s===void 0?{}:{error:s}}}function mp(e){const t=y(e),i=$(t,"error");return{machineId:m(t,"machineId"),ok:T(t,"ok"),checkedAt:m(t,"checkedAt"),...w("packageName",$(t,"packageName")),...w("generatedAt",$(t,"generatedAt")),...t.components===void 0?{}:{components:ll(t.components)},...t.capabilities===void 0?{}:{capabilities:Kr(t.capabilities)},...i===void 0?{}:{error:i}}}function vp(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function pl(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 bp(e){const t=y(e);return{configured:T(t,"configured"),authenticated:T(t,"authenticated")}}function wp(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function jt(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function Vr(e,t){if(e!==void 0){if(typeof e!="boolean")throw new Error(`Expected optional boolean field: ${t}`);return e}}function yp(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=y(e);return{messages:wp(t.messages),start:V(t,"start"),total:V(t,"total")}}function Jo(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function Sp(e){const t=y(e),i=$(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:T(t,"isMain"),isGitRepo:T(t,"isGitRepo"),isGitWorktree:T(t,"isGitWorktree"),...w("effectiveConfig",xp(t.effectiveConfig))}}function xp(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid workspace effectiveConfig field");return{...w("uploads",lh(e.uploads))}}}function mr(e){const t=y(e);return{path:m(t,"path"),size:V(t,"size"),modifiedAt:m(t,"modifiedAt")}}function Zo(e){const t=y(e);return{path:m(t,"path")}}function kp(e){const t=y(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function vr(e){const t=y(e),i=$(t,"name"),s=Vr(t.persisted,"persisted"),r=$(t,"parentSessionPath"),o=$(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...s===void 0?{}:{persisted:s},...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:V(t,"messageCount"),firstMessage:m(t,"firstMessage"),...r===void 0?{}:{parentSessionPath:r},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function Vt(e){const t=y(e);return{sessionId:m(t,"sessionId"),...w("persisted",Vr(t.persisted,"persisted")),isStreaming:T(t,"isStreaming"),isCompacting:T(t,"isCompacting"),isBashRunning:T(t,"isBashRunning"),pendingMessageCount:V(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:j(Mp)(t.queuedMessages),...w("messageCount",he(t,"messageCount")),tokens:Tp(t.tokens),cost:V(t,"cost"),...Wp(t.model),...Vp(t.contextUsage),...w("thinkingLevel",$(t,"thinkingLevel"))}}function hl(e){const t=y(e),i=t.skippedBusySessionIds===void 0?void 0:jt(t.skippedBusySessionIds,"skippedBusySessionIds");return{generatedAt:m(t,"generatedAt"),thresholds:Rp(t.thresholds),projects:j(Ip)(t.projects),totals:Ap(t.totals),...i===void 0?{}:{skippedBusySessionIds:i}}}function $p(e){const t=y(e);return{...hl(t),archivedSessionIds:jt(t.archivedSessionIds,"archivedSessionIds"),deletedSessionIds:jt(t.deletedSessionIds,"deletedSessionIds")}}function Pp(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected bulk archived response");return{archived:!0,archivedSessionIds:jt(t.archivedSessionIds,"archivedSessionIds"),failures:j(ul)(t.failures),generatedAt:m(t,"generatedAt")}}function Cp(e){const t=y(e);if(t.deleted!==!0)throw new Error("Expected bulk deleted response");return{deleted:!0,deletedSessionIds:jt(t.deletedSessionIds,"deletedSessionIds"),failures:j(ul)(t.failures),generatedAt:m(t,"generatedAt")}}function ul(e){const t=y(e);return{sessionId:m(t,"sessionId"),error:m(t,"error")}}function Rp(e){const t=y(e);return{...w("archiveIdleDays",he(t,"archiveIdleDays")),...w("deleteArchivedDays",he(t,"deleteArchivedDays"))}}function Ip(e){const t=y(e);return{cwd:m(t,"cwd"),archiveCount:V(t,"archiveCount"),deleteCount:V(t,"deleteCount")}}function Ap(e){const t=y(e);return{archiveCount:V(t,"archiveCount"),deleteCount:V(t,"deleteCount")}}function Mp(e){const t=y(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text"),...w("imageCount",he(t,"imageCount"))}}function Tp(e){const t=y(e);return{input:V(t,"input"),output:V(t,"output"),cacheRead:V(t,"cacheRead"),cacheWrite:V(t,"cacheWrite"),total:V(t,"total")}}function fl(e){const t=y(e);return{...w("provider",$(t,"provider")),...w("id",$(t,"id")),...w("name",$(t,"name")),...w("contextWindow",he(t,"contextWindow")),...w("reasoning",t.reasoning),...w("input",Ep(t.input))}}function Ep(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Invalid model input");return e.map(Dp)}}function Dp(e){if(e==="text"||e==="image")return e;throw new Error("Invalid model input")}function Wp(e){return e===void 0?{}:{model:fl(e)}}function Lp(e){const t=y(e);return{models:j(fl)(t.models)}}function Op(e){if(typeof e!="string")throw new Error("Invalid thinking level");return e}function Fp(e){const t=y(e);return{levels:j(Op)(t.levels)}}function _p(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function jp(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 Up(e){const t=y(e),i=t.source===void 0?void 0:jp(t.source);return{configured:T(t,"configured"),...w("source",i),...w("label",$(t,"label"))}}function Bp(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),authType:_p(t.authType),status:Up(t.status)}}function zp(e){const t=y(e);return{providers:j(Bp)(t.providers)}}function $i(e){const t=y(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:Np(t.status),progress:j(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...w("error",$(t,"error")),...w("auth",qp(t.auth)),...w("prompt",Hp(t.prompt)),...w("select",Kp(t.select))}}function Np(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function qp(e){if(e===void 0)return;const t=y(e);return{url:m(t,"url"),...w("instructions",$(t,"instructions"))}}function Hp(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...w("placeholder",$(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function Kp(e){if(e===void 0)return;const t=y(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:j(bl)(t.options)}}function Vp(e){if(e===void 0)return{};const t=y(e);return{contextUsage:{tokens:tn(t,"tokens"),contextWindow:V(t,"contextWindow"),percent:tn(t,"percent")}}}function Gp(e){const t=y(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...w("description",$(t,"description"))}}function br(e){const t=y(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function Qp(e){const t=y(e);return{path:m(t,"path"),entries:j(Jp)(t.entries),scannedAt:m(t,"scannedAt"),truncated:T(t,"truncated")}}function Jp(e){const t=y(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...w("size",he(t,"size")),...w("modifiedAt",$(t,"modifiedAt"))}}function Zp(e){const t=y(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...w("language",$(t,"language")),...w("mediaType",eh(t.mediaType)),...w("mimeType",$(t,"mimeType")),encoding:i,size:V(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:T(t,"truncated"),binary:T(t,"binary")}}function gl(e){const t=y(e);return{path:m(t,"path"),size:V(t,"size"),modifiedAt:m(t,"modifiedAt"),created:T(t,"created")}}function Xp(e){const t=y(e);return{path:m(t,"path"),existed:T(t,"existed")}}function Yp(e){const t=y(e);return{fromPath:m(t,"fromPath"),toPath:m(t,"toPath"),size:V(t,"size"),modifiedAt:m(t,"modifiedAt")}}function eh(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function th(e){const t=y(e);return{isGitRepo:T(t,"isGitRepo"),hash:m(t,"hash"),...w("branch",$(t,"branch")),...w("upstream",$(t,"upstream")),...w("ahead",he(t,"ahead")),...w("behind",he(t,"behind")),files:j(ih)(t.files)}}function ih(e){const t=y(e);return{path:m(t,"path"),...w("oldPath",$(t,"oldPath")),index:Xo(t.index),workingTree:Xo(t.workingTree)}}function Xo(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 sh(e){const t=y(e);return{...w("path",$(t,"path")),staged:T(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:T(t,"truncated")}}function Us(e){const t=y(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:T(t,"exited"),...w("exitCode",he(t,"exitCode")),...w("commandRunId",$(t,"commandRunId"))}}function ci(e){const t=y(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:rh(t.status),...w("exitCode",he(t,"exitCode")),createdAt:m(t,"createdAt"),...w("startedAt",$(t,"startedAt")),...w("completedAt",$(t,"completedAt")),metadata:oh(t.metadata,"metadata")}}function rh(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function oh(e,t){const i=y(e);return Object.fromEntries(Object.entries(i).map(([s,r])=>{if(typeof r!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,r]}))}function nh(e){const t=y(e);return{cwd:m(t,"cwd"),hasSessionActivity:T(t,"hasSessionActivity"),hasTerminalActivity:T(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function ah(e){const t=y(e);return{workspaces:j(nh)(t.workspaces),generatedAt:m(t,"generatedAt")}}function lh(e){if(e!==void 0){if(!Ke(e)||Array.isArray(e))throw new Error("Invalid uploads field");return{...w("defaultFolder",$(e,"defaultFolder"))}}}function ch(e){const t=y(e);return{packages:j(ml)(t.packages)}}function Bs(e){const t=y(e),i=$(t,"source"),s=t.scope===void 0?void 0:vl(t.scope),r=Vr(t.removed,"removed");return{action:dh(t.action),...w("source",i),...w("scope",s),...w("removed",r),packages:j(ml)(t.packages)}}function ml(e){const t=y(e);return{source:m(t,"source"),scope:vl(t.scope),filtered:T(t,"filtered"),...w("installedPath",$(t,"installedPath"))}}function vl(e){if(e!=="user"&&e!=="project")throw new Error("Invalid Pi package scope");return e}function dh(e){if(e!=="install"&&e!=="remove"&&e!=="update")throw new Error("Invalid Pi package mutation action");return e}function Yo(e){const t=y(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:j(bl)(t.options)};if(i==="done")return{type:i,...w("message",$(t,"message")),...ph(t.session),...w("promptDraft",$(t,"promptDraft"))};throw new Error("Invalid command result type")}function bl(e){const t=y(e);return{value:m(t,"value"),label:m(t,"label"),...w("description",$(t,"description"))}}function ph(e){return e===void 0?{}:{session:vr(e)}}function yt(e){return{accepted:pt(e,"accepted")}}function hh(e){const t=y(e);return j(uh)(t.attachments)}function uh(e){const t=y(e);return{path:m(t,"path"),mimeType:m(t,"mimeType"),size:V(t,"size")}}function wr(e){return{closed:pt(e,"closed")}}function fh(e){return{aborted:pt(e,"aborted")}}function gh(e){return{stopped:pt(e,"stopped")}}function en(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:jt(t.sessionIds,"sessionIds"),s=he(t,"archivedCount"),r=he(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...r===void 0?{}:{skippedAlreadyArchivedCount:r}}}function mh(e){return{restored:pt(e,"restored")}}function vh(e){return{deleted:pt(e,"deleted")}}function bh(e){return{detached:pt(e,"detached")}}function wh(e){return{reloaded:pt(e,"reloaded")}}function tn(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 yh(e){return typeof e=="string"?e:e.id}function Sh(e){return typeof e=="string"?void 0:e.cwd}function xh(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 kh(e,t,i="local"){const s=new URLSearchParams,r=Sh(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(yh(e))}/messages${o===""?"":`?${o}`}`}function $h(e,t,i,s){const r=new URLSearchParams({path:i});s?.createDirs===!1&&r.set("createDirs","false"),s?.overwrite===!1&&r.set("overwrite","false");const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Ss(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`)}function Ph(e,t,i,s){const r=new URLSearchParams;r.set("path",i),s?.modifiedAt!==void 0&&r.set("v",s.modifiedAt);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Ss(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${r.toString()}`)}function wl(e,t,i,s){const r=new URLSearchParams;r.set("path",i);const o=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Ss(`${o}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${r.toString()}`)}const R=(e="local")=>`/api/machines/${encodeURIComponent(e)}`;function yl(e){return typeof e=="string"?e:e.id}function Gr(e){return typeof e=="string"?void 0:e.cwd}function Sl(e,t="local"){return`${R(t)}/sessions/${encodeURIComponent(yl(e))}`}function ee(e,t,i="local"){return`${Sl(e,i)}/${t}`}function Pi(e,t,i="local"){return`${ee(e,t,i)}${xl(e)}`}function Ch(e,t="local"){return`${Sl(e,t)}${xl(e)}`}function xl(e){const t=Gr(e);return t===void 0||t===""?"":`?${new URLSearchParams({cwd:t}).toString()}`}function se(e,t={}){const i=Gr(e);return JSON.stringify(i===void 0||i===""?t:{cwd:i,...t})}function sn(e){return JSON.stringify({sessions:e.map(Rh)})}function Rh(e){const t=yl(e),i=Gr(e);return i===void 0||i===""?{id:t}:{id:t,cwd:i}}const kl={piWebStatus:(e="local")=>b(e==="local"?"/api/pi-web/status":`${R(e)}/pi-web/status`,op),piWebRuntime:()=>b("/api/pi-web/runtime",np)},Ih={machines:()=>b("/api/machines",fp),addMachine:e=>b("/api/machines",dl,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>b(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>b(`/api/machines/${encodeURIComponent(e)}/health`,gp),runtime:e=>b(`/api/machines/${encodeURIComponent(e)}/runtime`,mp)};function rn(e){return e===void 0?"/api/config":`${R(e)}/config`}function Ah(e){return e===void 0?"/api/plugins":`${R(e)}/plugins`}const Ne={config:e=>b(rn(e),Ko),saveConfig:(e,t)=>b(rn(t),Ko,{method:"PUT",body:JSON.stringify({config:e})})},Wt={status:()=>b("/api/normal-auth/status",bp),setup:e=>b("/api/normal-auth/setup",yt,{method:"POST",body:JSON.stringify({password:e})}),login:e=>b("/api/normal-auth/login",yt,{method:"POST",body:JSON.stringify({password:e})}),changePassword:(e,t)=>b("/api/normal-auth/change-password",yt,{method:"POST",body:JSON.stringify({currentPassword:e,newPassword:t})})},si={plugins:e=>b(Ah(e),ip)};function Ci(e="",t){const i=t===void 0?"/api/pi-packages":`${R(t)}/pi-packages`;return e===""?i:`${i}/${e}`}const ri={packages:e=>b(Ci("",e),ch),install:(e,t)=>{const i={source:e};return b(Ci("install",t),Bs,{method:"POST",body:JSON.stringify(i)})},remove:(e,t,i)=>{const s=t===void 0?{source:e}:{source:e,scope:t};return b(Ci("remove",i),Bs,{method:"POST",body:JSON.stringify(s)})},update:(e,t)=>{const i=e===void 0?void 0:{source:e};return b(Ci("update",t),Bs,{method:"POST",...i===void 0?{}:{body:JSON.stringify(i)}})}},$l={workspaceActivity:(e="local")=>b(`${R(e)}/activity`,ah)},Mh={projects:(e="local")=>b(`${R(e)}/projects`,j(Jo)),addProject:(e,t,i,s="local")=>b(`${R(s)}/projects`,Jo,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>b(`${R(t)}/projects/${encodeURIComponent(e)}`,wr,{method:"DELETE"}),projectDirectories:(e,t="local")=>b(`${R(t)}/project-directories?q=${encodeURIComponent(e)}`,j(br))},Lt={workspaces:(e,t="local")=>b(`${R(t)}/projects/${e}/workspaces`,j(Sp)),deleteWorkspace:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,ci,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Qp),workspaceFile:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Zp),uploadWorkspaceFile:async(e,t,i,s,r="local")=>r==="local"?Lh(e,t,i,s):b(`${R(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,mr,{method:"POST",body:JSON.stringify({path:i,contentBase64:await Dh(s)})}),createWorkspaceFile:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,mr,{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,d=a?new Uint8Array(s):new TextEncoder().encode(s);return b(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${n.toString()}`,gl,{method:"PUT",body:d,headers:{"Content-Type":a?"application/octet-stream":"text/plain"}})},deleteWorkspaceFile:(e,t,i,s="local")=>{const r=new URLSearchParams({path:i});return b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${r.toString()}`,Xp,{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"),b(`${R(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${n.toString()}`,Yp,{method:"POST"})},createWorkspaceDirectory:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Zo,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,r="local")=>b(`${R(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Zo,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,kp,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>wl(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>Oh(e,t,i,s)},yr={sessions:(e,t="local")=>b(`${R(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(vr)),startSession:(e,t="local")=>b(`${R(t)}/sessions`,vr,{method:"POST",body:JSON.stringify({cwd:e})}),cleanupPreview:(e,t="local")=>b(`${R(t)}/sessions/cleanup/preview`,hl,{method:"POST",body:JSON.stringify(e)}),cleanup:(e,t="local")=>b(`${R(t)}/sessions/cleanup`,$p,{method:"POST",body:JSON.stringify(e)}),archiveMany:(e,t="local")=>b(`${R(t)}/sessions/bulk/archive`,Pp,{method:"POST",body:sn(e)}),deleteArchivedMany:(e,t="local")=>b(`${R(t)}/sessions/bulk/delete-archived`,Cp,{method:"POST",body:sn(e)}),messages:(e,t,i="local")=>b(kh(e,t,i),yp),status:(e,t="local")=>b(Pi(e,"status",t),Vt),models:(e,t="local")=>b(Pi(e,"models",t),Lp),setModel:(e,t,i,s="local")=>b(ee(e,"model",s),Vt,{method:"POST",body:se(e,{provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>b(ee(e,"model/cycle",i),Vt,{method:"POST",body:se(e,{direction:t})}),thinkingLevels:(e,t="local")=>b(Pi(e,"thinking-levels",t),Fp),setThinkingLevel:(e,t,i="local")=>b(ee(e,"thinking-level",i),Vt,{method:"POST",body:se(e,{level:t})}),cycleThinkingLevel:(e,t="local")=>b(ee(e,"thinking-level/cycle",t),Vt,{method:"POST",body:se(e)}),commands:(e,t="local")=>b(Pi(e,"commands",t),j(Gp)),prompt:(e,t,i,s="local",r)=>b(ee(e,"prompt",s),yt,{method:"POST",body:se(e,{text:t,...i===void 0?{}:{streamingBehavior:i},...r!==void 0&&r.length>0?{attachments:r}:{}})}),saveAttachments:(e,t,i="local",s)=>b(ee(e,"attachments",i),hh,{method:"POST",body:se(e,{attachments:t,...s===void 0?{}:{folder:s}})}),shell:(e,t,i="local")=>b(ee(e,"shell",i),yt,{method:"POST",body:se(e,{text:t})}),runCommand:(e,t,i="local")=>b(ee(e,"commands/run",i),Yo,{method:"POST",body:se(e,{text:t})}),respondToCommand:(e,t,i,s="local")=>b(ee(e,"commands/respond",s),Yo,{method:"POST",body:se(e,{requestId:t,value:i})}),abort:(e,t="local")=>b(ee(e,"abort",t),fh,{method:"POST",body:se(e)}),stop:(e,t="local")=>b(ee(e,"stop",t),gh,{method:"POST",body:se(e)}),archive:(e,t="local")=>b(ee(e,"archive",t),en,{method:"POST",body:se(e)}),archiveWithDescendants:(e,t="local")=>b(ee(e,"archive-tree",t),en,{method:"POST",body:se(e)}),restore:(e,t="local")=>b(ee(e,"restore",t),mh,{method:"POST",body:se(e)}),deleteArchived:(e,t="local")=>b(Ch(e,t),vh,{method:"DELETE"}),detachParent:(e,t="local")=>b(ee(e,"detach-parent",t),bh,{method:"POST",body:se(e)}),reloadSession:(e,t="local")=>b(ee(e,"reload",t),wh,{method:"POST",body:se(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 b(`${R(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,zp)},saveApiKey:(e,t,i="local")=>b(`${R(i)}/auth/api-key`,yt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>b(`${R(t)}/auth/logout`,yt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>b(`${R(t)}/auth/oauth`,$i,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>b(`${R(t)}/auth/oauth/${encodeURIComponent(e)}`,$i),respondOAuthFlow:(e,t,i,s="local")=>b(`${R(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,$i,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>b(`${R(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,$i,{method:"POST"})},Ot={terminals:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(Us)),startTerminal:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Us,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,wr,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,wr,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>b(`${R(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Us,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,ci,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>b(`${R(t)}/terminal-command-runs${Eh(e)}`,j(ci)),getCommandRun:(e,t="local")=>Th(e,t),cancelCommandRun:(e,t="local")=>b(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,ci,{method:"POST"})};async function Th(e,t){return zd(`${R(t)}/terminal-command-runs/${encodeURIComponent(e)}`,ci)}function Eh(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 Pl(e){if(!Fh(e))return;const t=e.error;return typeof t=="string"?t:void 0}async function Dh(e){return Wh(await e.arrayBuffer())}function Wh(e){const t=new Uint8Array(e);let i="";for(const s of t)i+=String.fromCharCode(s);return btoa(i)}async function Lh(e,t,i,s){const r=new FormData;r.set("path",i),r.set("file",s,s.name);const o=await fetch(Hr(`${R("local")}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`),{method:"POST",body:r});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(Pl(n)??o.statusText)}return mr(await o.json())}async function Oh(e,t,i,s){const r=await fetch(wl(e,t,i,{machineId:s}));if(!r.ok){const p=await r.json().catch(()=>({}));throw new Error(Pl(p)??r.statusText)}const o=await r.blob(),n=URL.createObjectURL(o),a=document.createElement("a");a.href=n;const d=i.split("/").pop();a.download=d===void 0||d===""?"download":d,document.body.append(a),a.click(),a.remove(),URL.revokeObjectURL(n)}function Fh(e){return typeof e=="object"&&e!==null}const _h={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?b(`${R(i.machineId)}/projects/${encodeURIComponent(i.projectId)}/workspaces/${encodeURIComponent(i.workspaceId)}/files?${s.toString()}`,j(br)):(s.set("cwd",e),b(`${R(i.machineId)}/files?${s.toString()}`,j(br)))}},jh={gitStatus:(e,t,i="local")=>b(`${R(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,th),gitDiff:(e,t,i,s="local")=>b(xh(s,e,t,i),sh)},K={...kl,...Ih,...Ne,...Wt,...si,...ri,...$l,...Mh,...Lt,...yr,...Ot,..._h,...jh};function Uh(e,t="local",i=zr()){const s=typeof e=="string"?void 0:e.cwd,r=s===void 0||s===""?"":`?${new URLSearchParams({cwd:s}).toString()}`,o=typeof e=="string"?e:e.id,n=ol(`${Qr(t)}/sessions/${encodeURIComponent(o)}/events${r}`,void 0,i);return new WebSocket(`${Jr()}${n}`)}function ck(e,t,i,s,r="local"){const o=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${Jr()}${Qr(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${o}`)}function Bh(e="local",t=zr()){const i=ol(`${Qr(e)}/events`,void 0,t);return new WebSocket(`${Jr()}${i}`)}function Qr(e){return`/api/machines/${encodeURIComponent(e)}`}function Jr(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}const di=".pi-web/uploads";class xs extends Error{constructor(t="Workspace upload cancelled"){super(t),this.name="WorkspaceUploadCancelledError"}}class Cl extends Error{constructor(t,i){super(Qh(t)),this.name="WorkspaceUploadBatchError",this.failures=t.map(s=>({...s})),this.responses=i.map(s=>({...s}))}}function on(e){return e?.uploads?.defaultFolder??di}function zh(e,t){return e?.uploads?.defaultFolder??t}function Zr(e,t){const i=nn(e,"upload destination",{allowEmpty:!0}),s=nn(t,"upload file name",{allowEmpty:!1});return i===""?s:`${i}/${s}`}function Nh(e,t,i,s={}){const r=s.xhrFactory?.()??new XMLHttpRequest;let o=!1,n=!1;return{promise:new Promise((d,p)=>{const u=g=>{o||(o=!0,p(g))},h=g=>{o||(o=!0,d(g))};r.open("PUT",$h(e,t,i.path,Kh(s)),!0),r.responseType="json",r.setRequestHeader("Content-Type",(i.contentType??i.file.type)||"application/octet-stream"),r.upload.onprogress=g=>{s.onProgress?.(Vh(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(gl(Rl(r)))}catch(g){u(g instanceof Error?g:new Error(String(g)))}return}u(new Error(Yh(r)))},r.onerror=()=>{u(new Error("Workspace upload failed"))},r.onabort=()=>{u(new xs(n?void 0:"Workspace upload aborted"))},r.send(i.file)}),cancel:()=>{o||(n=!0,r.abort())}}}function qh(e,t,i,s={}){const r=s.destinationFolder??di,o=i.map((h,g)=>({index:g,name:h.name,path:Zr(r,h.name),loaded:0,total:h.size,percent:Xr(0,h.size),lengthComputable:!0,done:!1}));let n,a=0;const d={requested:!1},p=()=>{s.onProgress?.(Gh(o,a,o.every(h=>h.done)))};return{promise:(async()=>{const h=[],g=[];for(let S=0;S<i.length;S+=1){if(d.requested)throw new xs;a=S;const P=i[S],C=o[S];if(!(P===void 0||C===void 0)){n=Nh(e,t,{path:C.path,file:P},{...Hh(s),onProgress:X=>{C.total=X.total,C.loaded=Math.min(X.loaded,C.total),C.percent=X.percent,C.lengthComputable=X.lengthComputable,p()}});try{const X=await n.promise;C.loaded=C.total,C.percent=1,C.lengthComputable=!0,C.done=!0,h.push(X),p()}catch(X){if(Zh(X,d))throw X;const ot=Jh(X);C.loaded=C.total,C.percent=1,C.lengthComputable=!0,C.done=!0,C.error=ot,g.push({index:S,name:P.name,path:C.path,error:ot}),p()}finally{n=void 0}}}if(g.length>0)throw new Cl(g,h);return h})(),cancel:()=>{d.requested=!0,n?.cancel()}}}function Hh(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 Kh(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Vh(e,t){const i=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:i,percent:Xr(e.loaded,i),lengthComputable:e.lengthComputable}}function Gh(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:Xr(r,s),done:i}}function Xr(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Qh(e){return e.length===1?e[0]?.error??"Workspace upload failed":`${String(e.length)} files failed to upload`}function Jh(e){return e instanceof Error?e.message:String(e)}function Zh(e,t){return t.requested||e instanceof xs}function nn(e,t,i){const s=e.trim();if(s===""){if(i.allowEmpty)return"";throw new Error(`${t} must not be empty`)}if(Xh(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 Xh(e){const t=e.replace(/\\/g,"/");return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}function Rl(e){return e.response!==void 0&&e.response!==null&&e.response!==""?e.response:e.responseText===""?{}:JSON.parse(e.responseText)}function Yh(e){const t=eu(e);return tu(t)&&typeof t.error=="string"?t.error:e.statusText||`HTTP ${String(e.status)}`}function eu(e){try{return Rl(e)}catch{return}}function tu(e){return typeof e=="object"&&e!==null}function _i(){return{sessions:[],clientQueuedSessionMessages:{},startingSessionCount:0,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 iu(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,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 dt(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Il(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const Al="local";function zs(e,t){return`${e}:${t}`}function oi(e,t){return`${e}:${t}`}function f(e){return e.selectedMachine?.id??Al}class su{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??$l}async refresh(t=f(this.getState())){this.applyMachineActivitySnapshot(t,ru(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=ou(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 ru(e){const t={};for(const i of e.workspaces)Il(i)&&(t[i.cwd]=i);return t}function ou(e,t){const i={...e};return Il(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class nu{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=r.api??K,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=au(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:"",d=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:d}})}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 au(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 vi(e){return e.replaceAll(":",".")}function lu(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 Ns(e,t){const i=lu(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function be(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));cu(r,s)}function cu(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 du(e){const t=e.files.map((s,r)=>{const o=s.size;return{index:r,name:s.name,path:Zr(e.destinationFolder,s.name),size:s.size,loaded:0,total:o,percent:ln(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:ln(0,i),status:"uploading",startedAt:e.startedAt}}function pu(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 hu(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 uu(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 an(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 ln(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}const Ri=vi("core:workspace.files");class fu{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??K,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??qh,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 d=await this.api.workspaceTree(t.id,i.id,a,s);return[a,d.entries]}catch(d){if(cn(d))return;throw d}})),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:dn(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"}),be(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"}),be(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(cn(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),be(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());qs(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());qs(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===""||qs(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}),be(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 d;try{d=du({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(d);let p;try{p=this.uploadWorkspaceFiles(s.id,r.id,t,{destinationFolder:i.destinationFolder,machineId:o,overwrite:n,createDirs:a,onProgress:h=>{this.updateUploadProgress(d.id,h)}})}catch(h){return this.failUploadBatch(d.id,h),{batchId:d.id,done:Promise.resolve()}}this.uploadTasks.set(d.id,p);const u=p.promise.then(async h=>{await this.completeUploadBatch(d.id,h,i)}).catch(async h=>{await this.handleUploadFailure(d.id,h,i)}).finally(()=>{this.uploadTasks.delete(d.id)});return{batchId:d.id,done:u}}cancelWorkspaceUpload(t){const i=this.getUploadBatch(t);i?.status==="uploading"&&(this.setUploadBatch(an(i,this.now())),this.uploadTasks.get(t)?.cancel())}clearWorkspaceUpload(t){this.uploadTasks.get(t)?.cancel(),this.uploadTasks.delete(t),this.setState({workspaceUploadBatches:dn(this.getState().workspaceUploadBatches,t)})}updateUploadProgress(t,i){const s=this.getUploadBatch(t);s?.status==="uploading"&&this.setUploadBatch(pu(s,i))}async completeUploadBatch(t,i,s){const r=this.getUploadBatch(t);if(r?.status!=="uploading"||(this.setUploadBatch(hu(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 Cl)||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(gu(i)){const n=an(s,this.now());return this.setUploadBatch(n),n}const r=mu(i),o=uu(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 cn(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function gu(e){return e instanceof xs}function mu(e){return e instanceof Error?e.message:String(e)}function dn(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function qs(e){const t=e.selectedFilePath;return t===void 0?"file":vu(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function vu(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 pn=vi("core:workspace.git");class bu{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 K.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}),be(pn,"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"}),be(pn,"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([K.gitDiff(i.id,s.id,{path:t},f(this.getState())),K.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 wu{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 K.machines(),s=await this.selectInitialMachine(i,t),r=new Set(i.map(o=>o.id));this.setState({machines:i,selectedMachine:s,machineActivities:hn(this.getState().machineActivities,r),machineRuntimes:hn(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,..._i()}),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 K.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 K.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:Hs(this.getState().machineStatuses,t.id),machineRuntimes:Hs(this.getState().machineRuntimes,t.id),machineActivities:Hs(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 K.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 K.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 K.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=>K.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=>K.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 Hs(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function hn(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class yu{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 K.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 K.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 K.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 Sr="pi-web:cached-new-sessions:v1",Su="browserCachedNew",Nt="local";function bi(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function un(e,t=Nt,i=bi()){if(e.messageCount!==0||e.archived===!0)return;const s=eo(i).filter(r=>r.id!==e.id||r.machineId!==t);to([xr(e,t),...s],i)}function xr(e,t=Nt){return{...e,browserCachedNew:!0,machineId:t}}function fn(e,t=Nt,i=bi()){const s=eo(i).filter(r=>r.id!==e||r.machineId!==t);to(s,i)}function Ml(e,t,i=Nt,s=bi()){const r=new Set(t.map(d=>d.id)),o=eo(s),n=o.filter(d=>d.machineId!==i||!r.has(d.id));return n.length!==o.length&&to(n,s),[...n.filter(d=>d.machineId===i&&d.cwd===e),...t]}function Zi(e){return e===void 0?!1:$u(e)&&e.browserCachedNew===!0}function xu(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.persisted===void 0?{}:{persisted:e.persisted},...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:Nt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function eo(e=bi()){try{const t=e?.getItem(Sr);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>ku(s)):[]}catch{return[]}}function to(e,t=bi()){try{e.length===0?t?.removeItem(Sr):t?.setItem(Sr,JSON.stringify(e))}catch{}}function ku(e){if(!Pu(e))return[];const t=At(e,"id"),i=At(e,"path"),s=At(e,"cwd"),r=At(e,"created"),o=At(e,"modified"),n=At(e,"firstMessage"),a=Cu(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 d=Ks(e,"name"),p=Ks(e,"parentSessionPath"),u=Ks(e,"machineId")??Nt;return[{id:t,path:i,cwd:s,...d===void 0?{}:{name:d},created:r,modified:o,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function $u(e){return Su in e}function Pu(e){return typeof e=="object"&&e!==null}function At(e,t){const i=e[t];return typeof i=="string"?i:void 0}function Ks(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Cu(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Ru(e){return Nu(e.flatMap(io)).filter(t=>t.parts.length>0)}function qe(e,t){return{role:e,parts:[{type:"text",text:t}]}}function Gt(e,t){const i=Lu(t);return i===void 0?e:{...e,meta:i}}function Iu(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,qe(t,i)]}function Au(e,t){if(t==="")return e;const i=e.at(-1),s=i?.parts.at(-1);return i?.role==="assistant"&&s?.type==="thinking"?[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+t}]}]:i?.role==="assistant"?[...e.slice(0,-1),{...i,parts:[...i.parts,{type:"thinking",text:t}]}]:[...e,{role:"assistant",parts:[{type:"thinking",text:t}]}]}function io(e){if(Tu(e))return[e];if(_(e,"role")==="bashExecution")return[Gt(_u(e),e)];const t=ju(_(e,"role")),i=Uu(Re(e,"content"),e),s=t==="user"?Eu(i):void 0;if(s!==void 0)return s.map(p=>Gt(p,e));const r=Wu(e);if(t==="tool")return[Gt({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?[Gt({role:n,parts:o,...r===void 0?{}:{source:r}},e)]:[],d=Mu(e);return d===void 0?a:[...a,Gt(d,e)]}function Mu(e){if(_(e,"role")!=="assistant"||_(e,"stopReason")!=="error")return;const t=_(e,"errorMessage")?.trim();return qe("system",`Model response failed: ${t===void 0||t===""?"The model returned an error.":t}`)}function Tu(e){const t=_(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(Re(e,"parts"))}function Eu(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Du(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 Du(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 Wu(e){const t=_(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Lu(e){const t=Ou(Re(e,"timestamp")),i=Fu(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Ou(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 Fu(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 _u(e){const t=_(e,"command")??"",i=ji(e,"excludeFromContext")===!0?["excluded from context","",`$ ${t}`]:[`$ ${t}`],s=Re(e,"output");s!=null&&i.push("",Yi(s));const r=Re(e,"exitCode");r!=null&&i.push("",`exit ${Yi(r)}`),ji(e,"cancelled")===!0&&i.push("","cancelled"),ji(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 ju(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function Uu(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=Re(i,"arguments"),a=_(i,"id"),d=o==="read"?zu(_(n,"path")):void 0;return d!==void 0?[{type:"skillRead",...d,...a===void 0?{}:{toolCallId:a}}]:[{type:"toolCall",...a===void 0?{}:{toolCallId:a},toolName:o,summary:wi(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 gn(i)}).map(i=>i.type==="text"&&_(t,"role")==="toolResult"?Bu(i.text,t):i):gn(e)}function Bu(e,t){const i=_(t,"toolCallId"),s=Re(t,"content"),r=Re(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:ji(t,"isError")===!0}}function zu(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 Nu(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 d=qu(a),p=t.length;t.push({role:"tool",parts:[d],...o}),d.toolCallId!==void 0&&i.set(d.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const d=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(d!==void 0&&Hu(t,d,a)){i.delete(a.toolCallId??"");continue}}r.push(a)}n()}return t}function qu(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 Hu(e,t,i){const s=e[t.lineIndex],r=s?.parts[t.partIndex];if(s===void 0||r?.type!=="toolExecution")return!1;const o=Xi(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 Xi(e){const t=Re(e,"preview");if(!so(t))return;const i=_(t,"diff"),s=_(t,"error"),r=Vu(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 gn(e){return e==null?[]:typeof e=="object"?[{type:"text",text:wi(e)}]:[{type:"text",text:Yi(e)}]}function wi(e){if(!so(e))return Yi(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}: ${Ku(n)}`).join(" · ")}function Ku(e){return typeof e=="string"?e.length>80?`${e.slice(0,77)}…`:e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?"":"s"}`:typeof e=="object"&&e!==null?"object":""}function so(e){return typeof e=="object"&&e!==null}function Re(e,t){return so(e)?e[t]:void 0}function _(e,t){const i=Re(e,t);return typeof i=="string"?i:void 0}function ji(e,t){const i=Re(e,t);return typeof i=="boolean"?i:void 0}function Vu(e,t){const i=Re(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function Yi(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const Gu="pi-web:prompt-draft:";function es(e){return`${Gu}${e}`}function ks(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Tl(e,t=ks()){try{return t?.getItem(es(e))??""}catch{return""}}function ts(e,t,i=ks()){try{t?i?.setItem(es(e),t):i?.removeItem(es(e))}catch{}}function is(e,t=ks()){try{t?.removeItem(es(e))}catch{}}function mn(e,t,i=ks()){const s=Tl(e,i);s!==""&&(ts(t,s,i),is(e,i))}function Qu(e,t){return qe("bash",`${t===!0?`不加入上下文
6
6
 
7
- `:""}$ ${e}`)}function su(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Le("bash",t)];const r=ou(s.text)?"":`
7
+ `:""}$ ${e}`)}function Ju(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,qe("bash",t)];const r=Xu(s.text)?"":`
8
8
 
9
- `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+r+t}]}]}function ru(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const r=[];return!s.text.includes(`
9
+ `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+r+t}]}]}function Zu(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 ou(e){const t=e.lastIndexOf(`
14
+ `)}`}]}]}function Xu(e){const t=e.lastIndexOf(`
15
15
 
16
- `),i=e.lastIndexOf("$ ");return t>i}function nu(e,t){if(t.type==="message.append")return yu(e,t.message);if(t.type==="assistant.delta")return Wh(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return Oh(e,t.text);if(t.type==="tool.start")return pu(e,t);if(t.type==="tool.update")return Xa(e,t.toolCallId,i=>hu(i,t));if(t.type==="tool.end")return Za(e,t.toolCallId,t.toolName,ii(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,iu(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return su(e,t.chunk);if(t.type==="shell.end")return ru(e,t);if(t.type==="command.output")return[...e,Le(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,Le("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:au(e,t.message)}function au(e,t){const i=uu(t);if(i!==void 0)return Za(e,i.toolCallId,i.toolName,ii(i.content),i.text,i.isError,i.content,i.details);const s=Dr(t);if(s.length===0)return;const r=s.map(o=>o.role==="assistant"?cu(o):o).filter(o=>o.parts.length>0);return r.length===0?e:r.reduce((o,n)=>lu(o,n),e)}function lu(e,t){const i=fu(e,t);if(i.length>0)return gu(e,i,t);const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||wu(s,t)?[...e.slice(0,-1),t]:[...e,t]}function cu(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function du(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function pu(e,t){const i=t.toolName==="read"?du(pt(t.args,"path")):void 0;if(i!==void 0)return xu(e,{role:"skill",parts:[{type:"skillRead",...i,...t.toolCallId===""?{}:{toolCallId:t.toolCallId}}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||ii(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function hu(e,t){const i=Ei(t.details)??e.preview;return{...e,status:e.status==="pending"?"running":e.status,...t.text===""?{}:{resultText:t.text},...t.content===void 0?{}:{content:t.content},...t.details===void 0?{}:{details:t.details},...i===void 0?{}:{preview:i}}}function Za(e,t,i,s,r,o,n,a){const c=Xa(e,t,h=>{const g=Ei(a)??h.preview;return{...h,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...g===void 0?{}:{preview:g}}});if(c!==e)return c;const p=Ei(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function Xa(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const r=e[s];if(r===void 0)continue;const o=r.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(o<0)continue;const n=r.parts[o];if(n?.type!=="toolExecution")continue;const a={...r,parts:[...r.parts.slice(0,o),i(n),...r.parts.slice(o+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function uu(e){if(pt(e,"role")!=="toolResult")return;const t=pt(e,"toolCallId"),i=Li(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:pt(e,"toolName")??"tool",text:Ya(i),isError:Pu(e,"isError")===!0,content:i,details:Li(e,"details")}}function Ya(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Ya).filter(t=>t!=="").join(`
17
- `);if(typeof e=="object"&&e!==null){const t=pt(e,"text")??pt(e,"content")??pt(e,"output");if(t!==void 0)return t}return""}function fu(e,t){const i=_i(t);if(i.length===0)return[];const s=[];let r=i.length;const o=tl(e)+1;for(let n=e.length-1;n>=o;n--){const a=_i(e[n]);if(a.length===0)continue;const c=r-a.length;if(!(c<0)&&bu(a,i.slice(c,r))&&(s.unshift(n),r=c,r===0))return s}return[]}function gu(e,t,i){const s=mu(e,t,i),r=s[0];if(r===void 0)return e;const o=new Set(s),n=[];for(let a=0;a<e.length;a++){a===r&&n.push(i);const c=e[a];c!==void 0&&!o.has(a)&&n.push(c)}return n}function mu(e,t,i){const s=t[0];if(i.role!=="assistant"||s===void 0)return t;const r=s-1;return vu(e[r])?[r,...t]:t}function vu(e){return e?.role==="assistant"&&e.parts.length>0&&e.parts.every(t=>t.type==="text"||t.type==="thinking")}function _i(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function bu(e,t){return e.length===t.length&&e.every((i,s)=>el(i,t[s]))}function el(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:qo(e.path)===qo(t.path)||e.name===t.name}function qo(e){return e.replace(/\\/g,"/")}function wu(e,t){return Ko(e)===Ko(t)}function Ko(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
16
+ `),i=e.lastIndexOf("$ ");return t>i}function Yu(e,t){if(t.type==="message.append")return ff(e,t.message);if(t.type==="assistant.delta")return Iu(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return Au(e,t.text);if(t.type==="tool.start")return of(e,t);if(t.type==="tool.update")return Dl(e,t.toolCallId,i=>nf(i,t));if(t.type==="tool.end")return El(e,t.toolCallId,t.toolName,wi(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,Qu(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return Ju(e,t.chunk);if(t.type==="shell.end")return Zu(e,t);if(t.type==="command.output")return[...e,qe(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,qe("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:ef(e,t.message)}function ef(e,t){const i=af(t);if(i!==void 0)return El(e,i.toolCallId,i.toolName,wi(i.content),i.text,i.isError,i.content,i.details);const s=io(t);if(s.length===0)return;const r=s.map(o=>o.role==="assistant"?sf(o):o).filter(o=>o.parts.length>0);return r.length===0?e:r.reduce((o,n)=>tf(o,n),e)}function tf(e,t){const i=lf(e,t);if(i.length>0)return cf(e,i,t);const s=e.at(-1);return s?.role!==t.role?[...e,t]:t.role==="assistant"||uf(s,t)?[...e.slice(0,-1),t]:[...e,t]}function sf(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function rf(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 of(e,t){const i=t.toolName==="read"?rf(St(t.args,"path")):void 0;if(i!==void 0)return gf(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||wi(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function nf(e,t){const i=Xi(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 El(e,t,i,s,r,o,n,a){const d=Dl(e,t,h=>{const g=Xi(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(d!==e)return d;const p=Xi(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 Dl(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(d=>d.type==="toolExecution"&&d.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 af(e){if(St(e,"role")!=="toolResult")return;const t=St(e,"toolCallId"),i=rs(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:St(e,"toolName")??"tool",text:Wl(i),isError:wf(e,"isError")===!0,content:i,details:rs(e,"details")}}function Wl(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Wl).filter(t=>t!=="").join(`
17
+ `);if(typeof e=="object"&&e!==null){const t=St(e,"text")??St(e,"content")??St(e,"output");if(t!==void 0)return t}return""}function lf(e,t){const i=ss(t);if(i.length===0)return[];const s=[];let r=i.length;const o=Ol(e)+1;for(let n=e.length-1;n>=o;n--){const a=ss(e[n]);if(a.length===0)continue;const d=r-a.length;if(!(d<0)&&hf(a,i.slice(d,r))&&(s.unshift(n),r=d,r===0))return s}return[]}function cf(e,t,i){const s=df(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 d=e[a];d!==void 0&&!o.has(a)&&n.push(d)}return n}function df(e,t,i){const s=t[0];if(i.role!=="assistant"||s===void 0)return t;const r=s-1;return pf(e[r])?[r,...t]:t}function pf(e){return e?.role==="assistant"&&e.parts.length>0&&e.parts.every(t=>t.type==="text"||t.type==="thinking")}function ss(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function hf(e,t){return e.length===t.length&&e.every((i,s)=>Ll(i,t[s]))}function Ll(e,t){return t===void 0?!1:e.toolCallId!==void 0&&t.toolCallId!==void 0?e.toolCallId===t.toolCallId:vn(e.path)===vn(t.path)||e.name===t.name}function vn(e){return e.replace(/\\/g,"/")}function uf(e,t){return bn(e)===bn(t)}function bn(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
18
18
 
19
- `)}function yu(e,t){const i=Dr(t);return i.length===0?e:[...e,...i]}function xu(e,t){const i=e.at(-1);return Su(e,t)?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Su(e,t){const i=_i(t);if(t.role!=="skill"||i.length===0)return!1;const s=tl(e)+1;return i.every(r=>ku(e,r,s))}function ku(e,t,i){for(let s=e.length-1;s>=i;s--)if(_i(e[s]).some(r=>el(r,t)))return!0;return!1}function tl(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="user")return t;return-1}function $u(e){return typeof e=="object"&&e!==null}function Li(e,t){return $u(e)?e[t]:void 0}function pt(e,t){const i=Li(e,t);return typeof i=="string"?i:void 0}function Pu(e,t){const i=Li(e,t);return typeof i=="boolean"?i:void 0}const Cu="pi-web:chat-history:v2:",Iu=1800*1e3;function Ru(e){try{const t=sessionStorage.getItem(ji(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!Wu(i))return;if(Date.now()-i.savedAt>Iu){sessionStorage.removeItem(ji(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function Au(e,t){try{sessionStorage.setItem(ji(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Tu(e){try{sessionStorage.removeItem(ji(e))}catch{}}function Mu(e,t){if(e===void 0||!er(e))return t;if(!er(t))return e;if(Eu(e,t))return t;const i=Math.min(e.start,t.start),s=Math.max(e.start+e.messages.length,t.start+t.messages.length),r=new Array(s-i);return Vo(r,i,e),Vo(r,i,t),Du(r)?t:{start:i,total:Math.max(e.total,t.total),messages:r}}function Eu(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Du(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function Vo(e,t,i){i.messages.forEach((s,r)=>{e[i.start-t+r]=s})}function ji(e){return`${Cu}${e}`}function Wu(e){if(typeof e!="object"||e===null||!("messages"in e)||!("start"in e)||!("total"in e)||!("savedAt"in e))return!1;const{messages:t,start:i,total:s,savedAt:r}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof r=="number"&&er({messages:t,start:i,total:s})}function er(e){return Number.isInteger(e.start)&&Number.isInteger(e.total)&&e.start>=0&&e.total>=e.start&&e.messages.length<=e.total-e.start&&!e.messages.some(Ou)}function Ou(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&!("content"in e)&&typeof e.role=="string"&&Array.isArray(e.parts)}const _u={read:Ru,write:Au,remove:Tu};class Lu{constructor(t=_u){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return Go(this.rawHistoryPage(t))}mergeHistory(t,i){const s=Mu(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),Go(s)}applyLiveEvent(t,i){return nu(t,i)}discard(t){this.rawHistoryPages.delete(t),this.cache.remove?.(t)}rawHistoryPage(t){const i=this.rawHistoryPages.get(t)??this.cache.read(t);return i!==void 0&&this.rawHistoryPages.set(t,i),i}}function Go(e){const t=e?.start??0;return{messages:Dh(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function il(e,t=e.length){const i=e.slice(0,t),s=ju(i,t);if(s!==void 0)return s;const r=Fu(i,t);if(r!==void 0)return r;const o=Math.max(i.lastIndexOf(" "),i.lastIndexOf(`
20
- `))+1,n=i.slice(o);if(i.slice(0,o).endsWith("@ "))return{kind:"file",query:n,from:o-2,to:t,fileScope:"all",allPrefix:"@ "};if(n.startsWith("/")&&o===0)return{kind:"command",query:n.slice(1),from:o,to:t};if(n.startsWith("!@"))return{kind:"file",query:n.slice(2),from:o,to:t,fileScope:"all",allPrefix:"!@"};if(n.startsWith("@"))return{kind:"file",query:n.slice(1),from:o,to:t,fileScope:"tracked"}}function sl(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function ju(e,t){const i=e.lastIndexOf('"');if(i===-1)return;const s=e.slice(0,i);if(s.endsWith("!@"))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"!@",quoted:!0};if(s.endsWith("@"))return{kind:"file",query:e.slice(i+1),from:s.length-1,to:t,fileScope:"tracked",quoted:!0};if(s.endsWith("@ "))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"@ ",quoted:!0}}function Fu(e,t){const i=e.lastIndexOf(`
21
- `)+1,s=e.slice(i),r=Jo(s,"@ "),o=Jo(s,"!@"),n=Math.max(r,o);if(n===-1)return;const a=n===o?"!@":"@ ",c=i+n,p=c+a.length;return{kind:"file",query:e.slice(p),from:c,to:t,fileScope:"all",allPrefix:a}}function Jo(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||zu(e[i-1]))return i;return-1}function zu(e){return e===" "||e===" "}function Fi(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Nu(e).startsWith("/")?{kind:"command"}:il(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function Uu(e){return Fi(e).kind==="shell"}function Bu(e,t){return e.kind!==t.kind?!1:e.kind==="shell"&&t.kind==="shell"?e.excludeFromContext===t.excludeFromContext:!0}function Nu(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
- `))+1;return e.slice(t)}class rl{constructor(t="normal"){this.scope=t,this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,r="local"){this.close(),this.machineId=r,this.session=t,this.onEvent=i,this.onReconnect=s,this.shouldReconnect=!0,this.open()}setHandler(t){this.onEvent=t}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),nl(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.session===void 0||this.session.id===""||this.session.cwd===""||!this.shouldReconnect)return;const t=Kp(this.session,this.machineId,this.scope);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await ol(t);Hu(i)&&this.onEvent?.(i)}}class Qo{constructor(t="normal"){this.scope=t,this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),nl(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Vp(this.machineId,this.scope);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await ol(t);Ku(i)&&this.onEvent?.(i)}}function Hu(e){const t=_r(e);return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","agent.start","agent.end","message.end","status.update","activity.update","command.output","session.error","session.name","session.created","pi.event"].includes(t)}function qu(e){const t=_r(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function Ku(e){const t=_r(e);return qu(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function _r(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function ol(e){try{return typeof e=="string"?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function nl(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}function si(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class is{constructor(t,i,s=si()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[r,o]of Vu(t,i,s))this.values.set(r,o)}get(t){return this.values.get(t)}set(t,i){this.values.set(t,i),this.save()}delete(t){this.values.delete(t),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}const t={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(t))}catch{}}}function Lr(e){return typeof e=="string"&&e!==""?e:void 0}function Vu(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const r=JSON.parse(s);if(!Gu(r))return[];const o=[];for(const n of r.entries){const a=n[0],c=t(n[1]);c!==void 0&&o.push([a,c])}return o}catch{return[]}}function Gu(e){return!Ju(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string"&&t[0]!=="")}function Ju(e){return typeof e=="object"&&e!==null}class Qu{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}const Zu="pi-web:session-selection:v1";class Xu{constructor(t=si()){this.sessionIdsByCwd=new is(Zu,Lr,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function Yu(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return tf(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>r.archived!==!0):e.find(r=>r.archived!==!0)}function ef(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function tf(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function sf(e,t,i){return xi(e,[t],i)}function xi(e,t,i){const s=new Set(t);return e.map(r=>s.has(r.id)?{...r,archived:!0,archivedAt:i}:r)}function rf(e,t,i){return Si(e,t,[i])}function Si(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),r=e.find(o=>!s.has(o.id)&&o.archived!==!0);return r===void 0?{type:"clear"}:{type:"select",session:r}}const Lt=100,Zo=4;class of{constructor(t,i,s,r=new Qu,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.socket=o.socket??new rl,this.api=o.api??N,this.transcripts=o.transcripts??new Lu}applyGlobalEvent(t){t.type==="status.update"?this.queueStatusUpdate(t.status):t.type==="activity.update"?this.queueActivityUpdate(t.activity):t.type==="session.created"?this.applyCreatedSession(t.session):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingUpdates()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0,availableThinkingLevels:[]})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();ef(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=f(this.getState()),s=await this.api.startSession(t.path,i);Bo(s,i);const r=Ys(s,i);this.setState({sessions:[r,...this.getState().sessions.filter(o=>o.id!==r.id)]}),await this.selectSession(r)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return Yu(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates();const r=this.sessionCacheKey(t.id),o=this.transcripts.cachedView(r);this.setState({selectedSession:t,...o,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const u=await this.api.messages(t,{limit:Lt},f(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const h=this.transcripts.mergeHistory(r,u);this.setState({...h,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t,u=>n.push(u),()=>{this.refreshSelectedSession(t.id)},f(this.getState()));const[a,c]=await Promise.all([this.api.messages(t,{limit:Lt},f(this.getState())),this.api.status(t,f(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(r,a);this.setState({...p,isLoadingEarlierMessages:!1,...this.setStreamCatchup(c.isStreaming?t.id:void 0),status:c,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(c),this.refreshAvailableThinkingLevels();for(const u of n)this.applyEvent(u);this.socket.setHandler(u=>{this.applyEvent(u)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(Y(t)&&hf(n)){await this.recreateCachedNewSession(t,i);return}this.setState({error:String(n)})}}async loadEarlierMessages(){const t=this.getState(),i=t.selectedSession;if(!(!i||t.isLoadingEarlierMessages||t.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{const s=await this.api.messages(i,{before:t.messagePageStart,limit:Lt},f(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(r)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i,s,r="inline"){const o=t.trim(),n=s!==void 0&&s.length>0;if(!n&&o.startsWith("/"))return this.runCommand(t);if(!n&&Uu(t))return this.runShell(t);const a=this.getState().selectedSession;if(!a||a.archived===!0)return;const c=a.id,p=f(this.getState());n&&this.markSendingPrompt(c,!0);try{if(n&&r==="folder"){const h=(await this.api.saveAttachments(a,s,p)).map(y=>sl(y.path,!1)).join(" "),g=t===""?h:`${t}
19
+ `)}function ff(e,t){const i=io(t);return i.length===0?e:[...e,...i]}function gf(e,t){const i=e.at(-1);return mf(e,t)?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function mf(e,t){const i=ss(t);if(t.role!=="skill"||i.length===0)return!1;const s=Ol(e)+1;return i.every(r=>vf(e,r,s))}function vf(e,t,i){for(let s=e.length-1;s>=i;s--)if(ss(e[s]).some(r=>Ll(r,t)))return!0;return!1}function Ol(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role==="user")return t;return-1}function bf(e){return typeof e=="object"&&e!==null}function rs(e,t){return bf(e)?e[t]:void 0}function St(e,t){const i=rs(e,t);return typeof i=="string"?i:void 0}function wf(e,t){const i=rs(e,t);return typeof i=="boolean"?i:void 0}const yf="pi-web:chat-history:v2:",Sf=1800*1e3;function xf(e){try{const t=sessionStorage.getItem(os(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!If(i))return;if(Date.now()-i.savedAt>Sf){sessionStorage.removeItem(os(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function kf(e,t){try{sessionStorage.setItem(os(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function $f(e){try{sessionStorage.removeItem(os(e))}catch{}}function Pf(e,t){if(e===void 0||!kr(e))return t;if(!kr(t))return e;if(Cf(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 wn(r,i,e),wn(r,i,t),Rf(r)?t:{start:i,total:Math.max(e.total,t.total),messages:r}}function Cf(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Rf(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function wn(e,t,i){i.messages.forEach((s,r)=>{e[i.start-t+r]=s})}function os(e){return`${yf}${e}`}function If(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"&&kr({messages:t,start:i,total:s})}function kr(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(Af)}function Af(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 Mf={read:xf,write:kf,remove:$f};class Tf{constructor(t=Mf){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return yn(this.rawHistoryPage(t))}mergeHistory(t,i){const s=Pf(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),yn(s)}applyLiveEvent(t,i){return Yu(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 yn(e){const t=e?.start??0;return{messages:Ru(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function Fl(e,t=e.length){const i=e.slice(0,t),s=Ef(i,t);if(s!==void 0)return s;const r=Df(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 _l(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Ef(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 Df(e,t){const i=e.lastIndexOf(`
21
+ `)+1,s=e.slice(i),r=Sn(s,"@ "),o=Sn(s,"!@"),n=Math.max(r,o);if(n===-1)return;const a=n===o?"!@":"@ ",d=i+n,p=d+a.length;return{kind:"file",query:e.slice(p),from:d,to:t,fileScope:"all",allPrefix:a}}function Sn(e,t){for(let i=e.lastIndexOf(t);i>=0;i=e.lastIndexOf(t,i-1))if(i===0||Wf(e[i-1]))return i;return-1}function Wf(e){return e===" "||e===" "}function ns(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Of(e).startsWith("/")?{kind:"command"}:Fl(e)?.kind==="file"?{kind:"file"}:{kind:"normal"}}function xn(e){return ns(e).kind==="shell"}function Lf(e,t){return e.kind!==t.kind?!1:e.kind==="shell"&&t.kind==="shell"?e.excludeFromContext===t.excludeFromContext:!0}function Of(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
22
+ `))+1;return e.slice(t)}class jl{constructor(t="normal"){this.scope=t,this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,r="local"){this.close(),this.machineId=r,this.session=t,this.onEvent=i,this.onReconnect=s,this.shouldReconnect=!0,this.open()}setHandler(t){this.onEvent=t}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Bl(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=Uh(this.session,this.machineId,this.scope);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Ul(t);Ff(i)&&this.onEvent?.(i)}}class kn{constructor(t="normal"){this.scope=t,this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Bl(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Bh(this.machineId,this.scope);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Ul(t);jf(i)&&this.onEvent?.(i)}}function Ff(e){const t=ro(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 _f(e){const t=ro(e);return t==="status.update"||t==="activity.update"||t==="session.name"||t==="session.created"}function jf(e){const t=ro(e);return _f(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function ro(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Ul(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 Bl(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 zl(e){return e?.ok===!0&&Pe(e,we.sessionsPersistedState)}function Nl(e){return{authoritative:zl(e)}}function ql(e,t,i={}){if(e===void 0)return"unknown";const r=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return r===!0?"persisted":r===!1||Zi(e)?"transient":i.authoritative!==!0?"persisted":"unknown"}function He(e,t,i){return e!==void 0&&e.archived!==!0&&ql(e,t,i)==="persisted"}function fi(e,t,i){return e!==void 0&&e.archived!==!0&&ql(e,t,i)==="transient"}function yi(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class $s{constructor(t,i,s=yi()){this.storageKey=t,this.storage=s,this.values=new Map;for(const[r,o]of Uf(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 oo(e){return typeof e=="string"&&e!==""?e:void 0}function Uf(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const r=JSON.parse(s);if(!Bf(r))return[];const o=[];for(const n of r.entries){const a=n[0],d=t(n[1]);d!==void 0&&o.push([a,d])}return o}catch{return[]}}function Bf(e){return!zf(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 zf(e){return typeof e=="object"&&e!==null}class Nf{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 qf="pi-web:session-selection:v1";class Hf{constructor(t=yi()){this.sessionIdsByCwd=new $s(qf,oo,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function Kf(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return Gf(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 Vf(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function Gf(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function Qf(e,t,i){return Ui(e,[t],i)}function Ui(e,t,i){const s=new Set(t);return e.map(r=>s.has(r.id)?{...r,archived:!0,archivedAt:i}:r)}function Jf(e,t,i){return Bi(e,t,[i])}function Bi(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),r=e.find(o=>!s.has(o.id)&&o.archived!==!0);return r===void 0?{type:"clear"}:{type:"select",session:r}}const Qt=100,$n=4;class Zf{constructor(t,i,s,r=new Nf,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.pendingSessionStartSeq=0,this.pendingQueuedSendSeq=0,this.pendingSessionStarts=new Map,this.suppressedCreatedSessions=new Map,this.socket=o.socket??new jl,this.api=o.api??K,this.transcripts=o.transcripts??new Tf}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();Vf(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(!t)return;const i=f(this.getState()),s=this.createPendingSessionStart(t,i);this.pendingSessionStarts.set(s.tempId,s),this.insertAndSelectPendingSession(s.session);try{const r=await this.api.startSession(t.path,i);await this.resolvePendingSessionStart(s.tempId,r)}catch(r){this.failPendingSessionStart(s.tempId,r)}}preferredSession(t,i,s){return Kf(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){if(gt(t)){this.selectClientPendingStartSession(t,i);return}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:Qt},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,d]=await Promise.all([this.api.messages(t,{limit:Qt},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(d.isStreaming?t.id:void 0),status:d,activity:this.getState().sessionActivities[t.id],availableThinkingLevels:[]}),this.applyStatus(d),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(Zi(t)&&lg(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:Qt},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=this.getState().selectedSession;if(!o||o.archived===!0)return;const n=t.trim(),a=s!==void 0&&s.length>0;if(gt(o)){!a&&n.startsWith("/")?this.enqueuePendingSessionSend(o,{type:"command",text:t}):!a&&xn(t)?this.enqueuePendingSessionSend(o,{type:"shell",text:t}):this.enqueuePendingSessionSend(o,{type:"prompt",text:t,streamingBehavior:i,attachments:s,delivery:r});return}if(!a&&n.startsWith("/"))return this.runCommand(t);if(!a&&xn(t))return this.runShell(t);await this.deliverPromptToSession(o,t,i,s,r,f(this.getState()),{markSending:a})}markSendingPrompt(t,i){const s=this.getState().sendingPrompts;i?s[t]!==!0&&this.setState({sendingPrompts:{...s,[t]:!0}}):t in s&&this.setState({sendingPrompts:Xe(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){if(gt(i)){this.enqueuePendingSessionSend(i,{type:"shell",text:t});return}await this.deliverShellToSession(i,t,f(this.getState()),{optimisticLine:!0})}}async runCommand(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){if(gt(i)){this.enqueuePendingSessionSend(i,{type:"command",text:t});return}await this.deliverCommandToSession(i,t,f(this.getState()),{applyResult:!0})}}enqueuePendingSessionSend(t,i){const s=this.pendingSessionStarts.get(t.id);if(s===void 0||s.discarded){this.setState({error:"The backend session is not ready for queued sends. Copy your message before discarding this failed start."});return}const r={...i,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`};s.queuedSends.push(r);const o=this.getState(),n=o.clientQueuedSessionMessages[t.id]??[],a=Gs(t.id,s.queuedSends.length);this.setState({clientQueuedSessionMessages:{...o.clientQueuedSessionMessages,[t.id]:[...n,eg(r)]},sessionActivities:{...o.sessionActivities,[t.id]:a},activity:o.selectedSession?.id===t.id?a:o.activity,error:""})}async flushQueuedPendingSends(t,i,s){for(const r of s){if(!await this.deliverQueuedPendingSend(t,i,r))return;this.dropNextQueuedSessionMessage(t.id)}}async deliverQueuedPendingSend(t,i,s){return s.type==="prompt"?this.deliverPromptToSession(t,s.text,s.streamingBehavior,s.attachments,s.delivery,i,{markSending:!0}):s.type==="shell"?this.deliverShellToSession(t,s.text,i,{optimisticLine:!0}):this.deliverCommandToSession(t,s.text,i,{applyResult:!0})}async deliverPromptToSession(t,i,s,r,o,n,a){const d=r!==void 0&&r.length>0;a.markSending&&this.markSendingPrompt(t.id,!0);try{if(d&&o==="folder"){const u=(await this.api.saveAttachments(t,r,n)).map(g=>_l(g.path,!1)).join(" "),h=i===""?u:`${i}
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:al(s,t)})}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Le("user",t)]});try{await this.api.shell(i,t,f(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Le("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!i||i.archived===!0)return;const s=i.id;this.markSendingPrompt(s,!0);try{this.applyCommandResult(await this.api.runCommand(i,t,f(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(r){this.setState({messages:[...this.getState().messages,Le("system",String(r))],error:String(r)})}finally{this.markSendingPrompt(s,!1)}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s,t,i,f(this.getState())))}catch(r){this.setState({error:String(r)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(Y(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t,f(this.getState()));const i=this.getState(),s=sf(i.sessions,t.id,new Date().toISOString()),r=rf(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),r.type==="select"?await this.selectSession(r.session):r.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||Y(t)))try{const i=await this.api.archiveWithDescendants(t,f(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],r=this.getState(),o=xi(r.sessions,s,new Date().toISOString()),n=Si(o,r.selectedSession?.id,s);this.setState({sessions:o}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async archiveSessions(t){const i=Yo(t).filter(s=>s.archived!==!0&&!Y(s));if(i.length!==0)try{const s=f(this.getState()),{succeededIds:r,failures:o,generatedAt:n}=await this.archiveSessionBatch(i,s);if(r.length>0){const a=this.getState(),c=xi(a.sessions,r,n??new Date().toISOString()),p=Si(c,a.selectedSession?.id,r);this.setState({sessions:c}),p.type==="select"?await this.selectSession(p.session):p.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures("Archive",o)}catch(s){this.setState({error:`Archive failed: ${tr(s)}`})}}async deleteArchivedSessions(t){const i=Yo(t).filter(o=>o.archived===!0);if(i.length===0)return;const s=f(this.getState()),r=this.getState().machineRuntimes[s];if(r?.ok!==!0||!qe(r,_e.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}try{const{succeededIds:o,failures:n}=await this.deleteArchivedSessionBatch(i,s);if(o.length>0){const a=new Set(o),c=this.getState(),p=c.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),c.selectedSession!==void 0&&a.has(c.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionFailures("Delete",n)}catch(o){this.setState({error:`Delete failed: ${tr(o)}`})}}async archiveSessionBatch(t,i){const s=this.getState().machineRuntimes[i];if(s?.ok===!0&&qe(s,_e.sessionsBulkMutations)){const o=await this.api.archiveMany(t,i);return{succeededIds:o.archivedSessionIds,failures:tn(o.failures),generatedAt:o.generatedAt}}const r=await rn(t,Zo,async o=>(await this.api.archive(o,i),o.id));return{succeededIds:en(r),failures:sn(t,r)}}async deleteArchivedSessionBatch(t,i){const s=this.getState().machineRuntimes[i];if(s?.ok===!0&&qe(s,_e.sessionsBulkMutations)){const o=await this.api.deleteArchivedMany(t,i);return{succeededIds:o.deletedSessionIds,failures:tn(o.failures)}}const r=await rn(t,Zo,async o=>(await this.api.deleteArchived(o,i),o.id));return{succeededIds:en(r),failures:sn(t,r)}}async applySessionCleanupResult(t,i=f(this.getState())){if(f(this.getState())!==i)return;const s=t.archivedSessionIds,r=t.deletedSessionIds;if(s.length>0||r.length>0){const o=this.getState(),n=new Set(r),a=[...s,...r],c=xi(o.sessions,s,t.generatedAt).filter(u=>!n.has(u.id)),p=o.selectedSession!==void 0&&a.includes(o.selectedSession.id);if(this.setState({sessions:c,sessionStatuses:Xo(o.sessionStatuses,a),sessionActivities:Xo(o.sessionActivities,a),...p?{status:void 0,activity:void 0}:{}}),o.selectedSession!==void 0&&n.has(o.selectedSession.id)){const u=c.find(h=>h.archived!==!0)??c[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}else{const u=Si(c,o.selectedSession?.id,s);u.type==="select"?await this.selectSession(u.session):u.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(i)}async refreshCurrentWorkspaceSessions(t=f(this.getState())){const i=this.getState().selectedWorkspace;if(i!==void 0)try{const s=Ja(i.path,await this.api.sessions(i.path,t),t);if(f(this.getState())!==t||this.getState().selectedWorkspace?.id!==i.id)return;const r=this.getState().selectedSession;if(this.setState({sessions:s}),r===void 0)return;const o=s.find(a=>a.id===r.id);if(o!==void 0){o!==r&&this.setState({selectedSession:o});return}const n=s.find(a=>a.archived!==!0)??s[0];n!==void 0?await this.selectSession(n):this.deselectSession({forgetRememberedSelection:!0})}catch(s){f(this.getState())===t&&this.getState().selectedWorkspace?.id===i.id&&this.setState({error:String(s)})}}async deleteCachedNewSession(t=this.getState().selectedSession){if(!Y(t))return;this.api.stop(t,f(this.getState())).catch(()=>{}),No(t.id,f(this.getState())),Or(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(r=>r.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(r=>r.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t,f(this.getState()));const i={...t};delete i.archived,delete i.archivedAt,this.replaceSession(i),this.getState().selectedSession?.id===i.id&&await this.selectSession(i)}catch(i){this.setState({error:String(i)})}}async reloadSession(t=this.getState().selectedSession){if(t===void 0||Y(t)||t.archived===!0)return;const i=f(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!qe(s,_e.sessionsReload)){this.setState({error:"Reloading sessions requires an updated Pi-Web runtime on this machine."});return}try{await this.api.reloadSession(t.id,i),this.transcripts.discard(this.sessionCacheKey(t.id)),this.getState().selectedSession?.id===t.id&&await this.selectSession(t,{updateUrl:!1})}catch(r){this.setState({error:String(r)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t,f(this.getState()));const i={...t};delete i.parentSessionPath,this.replaceSession(i)}catch(i){this.setState({error:String(i)})}}async listModels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.models(t,f(this.getState()))).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s,t,i,f(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(r){this.setState({error:String(r)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i,t,f(this.getState()))),await this.refreshAvailableThinkingLevels()}catch(s){this.setState({error:String(s)})}}async listThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.thinkingLevels(t,f(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async refreshAvailableThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}const i=await this.listThinkingLevels();this.getState().selectedSession?.id===t.id&&this.setState({availableThinkingLevels:i})}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i,t,f(this.getState())))}catch(s){this.setState({error:String(s)})}}async cycleThinkingLevel(){const t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(t,f(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t,f(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingUpdates();const[s,r]=await Promise.all([this.api.messages(i,{limit:Lt},f(this.getState())),this.api.status(i,f(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...o,status:r,activity:this.getState().sessionActivities[t],...this.setStreamCatchup(r.isStreaming?t:void 0)}),this.applyStatus(r)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionFailures(t,i){i.length!==0&&this.setState({error:`${t} failed for ${String(i.length)} session${i.length===1?"":"s"}: ${i.join("; ")}`})}sessionCacheKey(t){return Ga(f(this.getState()),t)}workspaceSelectionKey(t){return`${f(this.getState())}:${t}`}replaceSession(t){const i=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s=>s.id===t.id?t:s),selectedSession:i?.id===t.id?t:i})}async recreateCachedNewSession(t,i){try{const s=f(this.getState()),r=await this.api.startSession(t.cwd,s);Bo(r,s),tu(this.sessionCacheKey(t.id),this.sessionCacheKey(r.id)),No(t.id,s);const o=Ys(r,s);this.setState({sessions:[o,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(o,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!Y(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Rh(i))}applyCommandResult(t){if(t.type==="select"){this.setState({commandDialog:t});return}const i=(t.type==="unsupported",t.message);if(i!==void 0&&i!==""&&this.setState({messages:[...this.getState().messages,Le(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&Oi(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,r=[t.session,...this.getState().sessions.filter(o=>o.id!==t.session?.id)];this.setState({sessions:r,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyCreatedSession(t){const i=this.getState();i.selectedWorkspace?.path===t.cwd&&(i.sessions.some(s=>s.id===t.id)||this.setState({sessions:[t,...i.sessions]}))}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!tt(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...cf(i,t.sessionId,t.messageCount),...s?{sessionActivities:nf(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),t.isStreaming||this.finishStreamCatchup(t.sessionId)}applySessionName(t,i){const s=o=>{if(o.id!==t)return o;const n={...o};return i===void 0||i===""?delete n.name:n.name=i,n},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:r===void 0?void 0:s(r)})}applyEvent(t){const i=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===i){if(t.type==="message.end"||t.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(df(t))return}if(t.type==="status.update"){this.queueStatusUpdate(t.status);return}if(t.type==="activity.update"){this.queueActivityUpdate(t.activity);return}if(pf(t)){this.queueTranscriptEvent(t);return}this.flushPendingUpdates();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.schedulePendingFlush()}queueStatusUpdate(t){this.pendingStatusBySession.set(t.sessionId,t),this.schedulePendingFlush()}queueActivityUpdate(t){this.pendingActivityBySession.set(t.sessionId,t),this.schedulePendingFlush()}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}if(this.pendingActivityBySession.size>0){const t=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(const i of t)this.applyActivity(i)}if(this.pendingStatusBySession.size>0){const t=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(const i of t)this.applyStatus(i)}}clearPendingUpdates(){this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0)}setStreamCatchup(t){return this.catchupStreamSessionId=t,{isReceivingPartialStream:t!==void 0}}finishStreamCatchup(t){const i=this.getState().selectedSession?.id===t;(this.catchupStreamSessionId===t||i&&this.getState().isReceivingPartialStream)&&(this.catchupStreamSessionId=void 0,i&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=this.getState().selectedSession;if(i?.id!==t)return;const s=await this.api.messages(i,{limit:Lt},f(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),s))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function nf(e,t){return al(e,t)}function al(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Xo(e,t){if(t.length===0)return e;const i=new Set(t);return Object.fromEntries(Object.entries(e).filter(([s])=>!i.has(s)))}function Yo(e){const t=new Set,i=[];for(const s of e)t.has(s.id)||(t.add(s.id),i.push(s));return i}function en(e){return e.filter(af).map(t=>t.value)}function tn(e){return e.map(t=>`${t.sessionId}: ${t.error}`)}function sn(e,t){return t.flatMap((i,s)=>lf(i)?[`${e[s]?.id??"unknown"}: ${tr(i.reason)}`]:[])}async function rn(e,t,i){const s=e.map((c,p)=>({item:c,index:p})),r=[];let o=0;async function n(){for(;o<s.length;){const c=s[o];if(c===void 0)return;o+=1;try{r[c.index]={status:"fulfilled",value:await i(c.item)}}catch(p){r[c.index]={status:"rejected",reason:p}}}}const a=Math.min(Math.max(1,t),s.length);return await Promise.all(Array.from({length:a},()=>n())),r}function af(e){return e.status==="fulfilled"}function lf(e){return e.status==="rejected"}function tr(e){return e instanceof Error?e.message:String(e)}function cf(e,t,i){if(i===void 0)return{};const r=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,o=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...o!==e.selectedSession?{selectedSession:o}:{}}}function df(e){return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","command.output","session.error"].includes(e.type)}function pf(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function hf(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("session not found")||t.includes("未找到会话")}class uf{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}const ff="pi-web:workspace-selection:v1";class gf{constructor(t=si()){this.workspaceIdsByProject=new is(ff,Lr,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function mf(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e[0]:e[0]}class vf{constructor(t,i,s,r,o=new uf,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=r,this.workspaceSelection=o,this.api=n.api??N}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...wi()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(ys(f(this.getState()),t));const i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([s])=>s!==t));this.setState({workspacesByProjectId:i})}async selectProject(t,i){const s=f(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...wi()});try{const r=await this.api.workspaces(t.id,s);if(f(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:r,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:r},isLoadingWorkspaces:!1});const o=mf(r,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(ys(s,t.id))});o?await this.selectWorkspace(o,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){f(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(r),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=f(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:ys(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...wi()});try{const r=Ja(t.path,await this.api.sessions(t.path,s),s);if(f(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:r});const o=this.sessions.preferredSession(t.path,r,i?.sessionId);o?await this.sessions.selectSession(o,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){f(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(r)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(r=>r.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,f(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),r=this.getState();if(r.selectedProject?.id!==t||r.selectedWorkspace?.id!==i)return;const o=wf(s);o!==void 0?await this.selectWorkspace(o):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),r={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:r}):this.setState({workspacesByProjectId:r})}}function bf(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function wf(e){return e.find(t=>t.isMain)??e[0]}const yf="pi-web:machine-navigation:v1";class xf{constructor(t=si()){this.snapshotsByMachine=new is(yf,kf,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?an(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,an(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Sf(e){return{machineId:e,surface:{}}}function on(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??Va,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,tool:e.workspaceTool,view:e.mainView,surface:{selectedFilePath:t?e.selectedFilePath:void 0,selectedDiffPath:t?e.selectedDiffPath:void 0,selectedTerminalId:t?e.selectedTerminalId:void 0}}}function nn(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view==="navigation"?void 0:e.view}}function an(e){return{...e,surface:{...e.surface}}}function kf(e){if(!cl(e))return;const t=He(e,"machineId");if(t===void 0)return;const i=ll(He(e,"tool")),s=Pf(He(e,"view"));return{machineId:t,projectId:He(e,"projectId"),workspaceId:He(e,"workspaceId"),sessionId:He(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:$f(e.surface)}}function $f(e){return cl(e)?{selectedFilePath:He(e,"selectedFilePath"),selectedDiffPath:He(e,"selectedDiffPath"),selectedTerminalId:He(e,"selectedTerminalId")}:{}}function Pf(e){return e==="navigation"||e==="chat"?e:ll(e)}function ll(e){return Cf(e)?e:void 0}function Cf(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function He(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function cl(e){return typeof e=="object"&&e!==null}const If="pi-web:terminal-selection:v1";class Rf{constructor(t=si()){this.terminalIdsByCwd=new is(If,Lr,t)}latestTerminalId(t){return this.terminalIdsByCwd.get(t)}rememberTerminal(t,i){this.terminalIdsByCwd.set(t,i)}forgetWorkspace(t){this.terminalIdsByCwd.delete(t)}forgetTerminal(t){for(const[i,s]of this.terminalIdsByCwd.entries())s===t&&this.terminalIdsByCwd.delete(i)}}function $x(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(r=>r.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(r=>r.id===s)??e.find(r=>!r.exited)??e[0]:e.find(r=>!r.exited)??e[0]}function Px(e){return e.find(t=>!t.exited)??e[0]}const dl=1200,Af=["mod","alt","shift"];class Tf{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const r=hl(t);if(r===void 0)return!1;const o=jr(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,r],o))return!0;if(this.clearPending(),!Xt(r))return!1}else if(!Xt(r))return!1;return this.handleSequence([r],o)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(o=>zf(o.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(o=>Fr(o.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},dl)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function jr(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Mf(p,t,u);return h===void 0?[]:[h]}),r=new Map;for(const p of s)r.set(p.key,[...r.get(p.key)??[],p]);const o=new Map;for(const p of r.values()){const u=[...p].sort(ir)[0];u!==void 0&&o.set(u.key,u)}const n=[...o.values()].sort(Wf),a=new Map,c=new Map;for(const p of s){const u=o.get(p.key);if(u===void 0)continue;const h=Of(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,g=u===void 0||h?void 0:ln(u),y=h?[...a.get(p)??[]].sort(ir).map(ln):[];return{...p,active:h,shadows:y,...g===void 0?{}:{shadowedBy:g}}}).sort((p,u)=>p.order-u.order)}function Ps(e){return ul(e,{requireFirstChordActivator:!0})}function pl(e){const t=ul(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function ki(e){return pl(e).map(t=>t.split("+").map(gl).join("+")).join(" ")}function hl(e){if(e.isComposing)return;const t=jf(e.key);if(t===void 0)return;const i=[];return(e.metaKey||e.ctrlKey)&&i.push("mod"),e.altKey&&i.push("alt"),e.shiftKey&&i.push("shift"),i.push(t),i.join("+")}function Xt(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Mf(e,t,i){const s=Ef(e.id,t);if(s===null)return;const r=s??e.shortcut;if(r===void 0||r==="")return;const o=pl(r),n=o[0];if(!(n===void 0||!Xt(n)))return{action:e,shortcut:o.join(" "),source:s===void 0?"default":"custom",tokens:o,key:Df(o),order:i}}function Ef(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Df(e){return e.join("\0")}function ln(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function ir(e,t){return cn(e.source)-cn(t.source)||dn(e.action.id,t.action.id)||dn(e.action.title,t.action.title)||e.order-t.order}function Wf(e,t){return e.tokens.length-t.tokens.length||ir(e,t)}function Of(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&Fr(e.tokens,i.tokens))}function cn(e){switch(e){case"custom":return 0;case"default":return 1}}function dn(e,t){return e<t?-1:e>t?1:0}function ul(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"请输入快捷键,选择无,或重置为默认值。"};const s=[],r=i.split(/\s+/u).filter(o=>o!=="");for(const[o,n]of r.entries()){const a=_f(n);if(!a.ok)return a;if(o===0&&t.requireFirstChordActivator&&!Xt(a.token))return{ok:!1,message:"快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。"};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function _f(e){const t=e.split("+").filter(o=>o!=="");if(t.length===0)return{ok:!1,message:"快捷键组合必须包含一个按键。"};const i=new Set;let s;for(const o of t){const n=Lf(o);if(n!==void 0){if(i.has(n))return{ok:!1,message:`快捷键包含重复的 ${gl(n)} 修饰键。`};i.add(n);continue}const a=fl(o);if(a===void 0)return{ok:!1,message:`不支持的快捷键按键:${o}`};if(s!==void 0)return{ok:!1,message:"每个快捷键组合只能包含一个非修饰键。"};s=a}return s===void 0?{ok:!1,message:"快捷键组合必须包含一个按键。"}:{ok:!0,token:[...Af.filter(o=>i.has(o)),s].join("+")}}function Lf(e){switch(e){case"mod":case"meta":case"cmd":case"command":case"ctrl":case"control":case"primary":return"mod";case"alt":case"option":case"opt":return"alt";case"shift":return"shift";default:return}}function fl(e){const t=Ff(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function jf(e){if(e===" ")return"space";const t=e.toLowerCase();return fl(t)}function Ff(e){switch(e){case" ":case"spacebar":case"space":return"space";case"esc":case"escape":return"escape";case"return":case"enter":return"enter";case"del":case"delete":return"delete";case"backspace":return"backspace";case"tab":return"tab";case"up":case"arrowup":return"arrowup";case"down":case"arrowdown":return"arrowdown";case"left":case"arrowleft":return"arrowleft";case"right":case"arrowright":return"arrowright";case"pageup":case"pagedown":case"home":case"end":return e;case"+":case"plus":return"plus";case"period":case"dot":return".";case"comma":return",";case"slash":return"/";case"backslash":return"\\";case"minus":return"-";default:return}}function gl(e){return e==="mod"?pn()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?pn()?"⌥":"Alt":e==="enter"?"Enter":e==="escape"?"Esc":e==="space"?"Space":e==="tab"?"Tab":e==="backspace"?"Backspace":e==="delete"?"Delete":e==="arrowup"?"↑":e==="arrowdown"?"↓":e==="arrowleft"?"←":e==="arrowright"?"→":e==="pageup"?"PageUp":e==="pagedown"?"PageDown":e==="home"?"Home":e==="end"?"End":e==="plus"?"+":/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function zf(e,t){return e.length===t.length&&Fr(e,t)}function Fr(e,t){return t.every((i,s)=>e[s]===i)}function pn(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const Uf={archiveIdleEnabled:!0,archiveIdleDays:"30",deleteArchivedEnabled:!1,deleteArchivedDays:"90"};function qt(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:"请至少启用一项清理操作。"};const t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){const i=fn(e.archiveIdleDays,"归档空闲会话天数");if(typeof i=="string")return{ok:!1,error:i};t.archiveIdleDays=i}if(e.deleteArchivedEnabled){const i=fn(e.deleteArchivedDays,"删除已归档会话天数");if(typeof i=="string")return{ok:!1,error:i};t.deleteArchivedDays=i}return{ok:!0,request:t}}function Rt(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function hn(e){if(!e.canCleanup||e.loading===!0||e.running===!0||e.preview===void 0)return!1;const t=qt(e.draft);return!t.ok||Rt(t.request)!==Rt(e.previewRequest)?!1:$i(e.preview)}function $i(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function ml(e,t){const i=e.projects.map(r=>r.cwd);if(t===void 0)return i;const s=new Set(t);return i.filter(r=>s.has(r))}function un(e,t){const i=new Set(ml(e,t)),s=e.projects.filter(r=>i.has(r.cwd));return{...e,projects:s,totals:s.reduce((r,o)=>({archiveCount:r.archiveCount+o.archiveCount,deleteCount:r.deleteCount+o.deleteCount}),{archiveCount:0,deleteCount:0})}}function Bf(e,t){return t(Nf(e))}function Nf(e){const t=e.totals.archiveCount,i=e.totals.deleteCount,s=[];return t>0&&s.push(`归档 ${String(t)} 个空闲会话`),i>0&&s.push(`永久删除 ${String(i)} 个已归档会话`),`运行清理并${s.length===0?"执行清理":s.join("并")}?
24
+ ${u}`;await this.api.prompt(t,h,s,n)}else await this.api.prompt(t,i,s,n,r);return this.markCachedNewSessionPersisted(t),!0}catch(p){return this.setState({error:String(p)}),!1}finally{a.markSending&&this.markSendingPrompt(t.id,!1)}}async deliverShellToSession(t,i,s,r){r.optimisticLine&&this.getState().selectedSession?.id===t.id&&this.setState({messages:[...this.getState().messages,qe("user",i)]});try{return await this.api.shell(t,i,s),this.markCachedNewSessionPersisted(t),!0}catch(o){return this.getState().selectedSession?.id===t.id&&this.setState({messages:[...this.getState().messages,qe("system",String(o))]}),this.setState({error:String(o)}),!1}}async deliverCommandToSession(t,i,s,r){this.markSendingPrompt(t.id,!0);try{const o=await this.api.runCommand(t,i,s);return r.applyResult&&this.getState().selectedSession?.id===t.id?this.applyCommandResult(o):o.type==="select"&&this.setState({error:`Queued command “${i}” needs input; open the session and run it again.`}),this.markCachedNewSessionPersisted(t),!0}catch(o){return this.getState().selectedSession?.id===t.id&&this.setState({messages:[...this.getState().messages,qe("system",String(o))]}),this.setState({error:String(o)}),!1}finally{this.markSendingPrompt(t.id,!1)}}dropNextQueuedSessionMessage(t){const i=this.getState(),s=i.clientQueuedSessionMessages[t]??[];if(s.length===0)return;const r=s.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?Xe(i.clientQueuedSessionMessages,t):{...i.clientQueuedSessionMessages,[t]:r}})}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)return;const i=this.statusForSession(t),s=this.sessionPersistenceOptions();if(fi(t,i,s)){await this.deleteCachedNewSession(t);return}if(He(t,i,s))try{await this.api.archive(t,f(this.getState()));const r=this.getState(),o=Qf(r.sessions,t.id,new Date().toISOString()),n=Jf(o,r.selectedSession?.id,t.id);this.setState({sessions:o}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(r){this.setState({error:String(r)})}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(t===void 0||!He(t,this.statusForSession(t),this.sessionPersistenceOptions())))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=Ui(r.sessions,s,new Date().toISOString()),n=Bi(o,r.selectedSession?.id,s);this.setState({sessions:o}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async archiveSessions(t){const i=this.sessionPersistenceOptions(),s=Rn(t).filter(r=>He(r,this.statusForSession(r),i));if(s.length!==0)try{const r=f(this.getState()),{succeededIds:o,failures:n,generatedAt:a}=await this.archiveSessionBatch(s,r);if(o.length>0){const d=this.getState(),p=Ui(d.sessions,o,a??new Date().toISOString()),u=Bi(p,d.selectedSession?.id,o);this.setState({sessions:p}),u.type==="select"?await this.selectSession(u.session):u.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures("Archive",n)}catch(r){this.setState({error:`Archive failed: ${zi(r)}`})}}async deleteArchivedSessions(t){const i=Rn(t).filter(o=>o.archived===!0);if(i.length===0)return;const s=f(this.getState()),r=this.getState().machineRuntimes[s];if(r?.ok===!0&&!Pe(r,we.sessionsDeleteArchived)){this.setState({error:"Deleting archived sessions requires an updated Pi-Web runtime on this machine."});return}try{const{succeededIds:o,failures:n}=await this.deleteArchivedSessionBatch(i,s);if(o.length>0){const a=new Set(o),d=this.getState(),p=d.sessions.filter(u=>!a.has(u.id));if(this.setState({sessions:p}),d.selectedSession!==void 0&&a.has(d.selectedSession.id)){const u=p.find(h=>h.archived!==!0)??p[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}}this.applyBulkSessionFailures("Delete",n)}catch(o){this.setState({error:`Delete failed: ${zi(o)}`})}}async archiveSessionBatch(t,i){const s=this.getState().machineRuntimes[i];if(s?.ok===!0&&Pe(s,we.sessionsBulkMutations)){const o=await this.api.archiveMany(t,i);return{succeededIds:o.archivedSessionIds,failures:An(o.failures),generatedAt:o.generatedAt}}const r=await Tn(t,$n,async o=>(await this.api.archive(o,i),o.id));return{succeededIds:In(r),failures:Mn(t,r)}}async deleteArchivedSessionBatch(t,i){const s=this.getState().machineRuntimes[i];if(s?.ok===!0&&Pe(s,we.sessionsBulkMutations)){const o=await this.api.deleteArchivedMany(t,i);return{succeededIds:o.deletedSessionIds,failures:An(o.failures)}}const r=await Tn(t,$n,async o=>(await this.api.deleteArchived(o,i),o.id));return{succeededIds:In(r),failures:Mn(t,r)}}async applySessionCleanupResult(t,i=f(this.getState())){if(f(this.getState())!==i)return;const s=t.archivedSessionIds,r=t.deletedSessionIds;if(s.length>0||r.length>0){const o=this.getState(),n=new Set(r),a=[...s,...r],d=Ui(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:d,sessionStatuses:Pn(o.sessionStatuses,a),sessionActivities:Pn(o.sessionActivities,a),...p?{status:void 0,activity:void 0}:{}}),o.selectedSession!==void 0&&n.has(o.selectedSession.id)){const u=d.find(h=>h.archived!==!0)??d[0];u!==void 0?await this.selectSession(u):this.deselectSession({forgetRememberedSelection:!0})}else{const u=Bi(d,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=Ml(i.path,await this.api.sessions(i.path,t),t).filter(d=>!this.isSuppressedCreatedSession(d,t));if(f(this.getState())!==t||this.getState().selectedWorkspace?.id!==i.id)return;const r=this.mergePendingStartSessions(i.path,s,t),o=this.getState().selectedSession;if(this.setState({sessions:r}),o===void 0)return;const n=r.find(d=>d.id===o.id);if(n!==void 0){n!==o&&this.setState({selectedSession:n});return}const a=r.find(d=>d.archived!==!0)??r[0];a!==void 0?await this.selectSession(a):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(t===void 0||!fi(t,this.statusForSession(t),this.sessionPersistenceOptions()))return;const i=gt(t)?this.pendingSessionStarts.get(t.id):void 0;i!==void 0?(i.discarded=!0,i.queuedSends=[]):this.api.stop(t,f(this.getState())).catch(()=>{}),fn(t.id,f(this.getState())),is(this.sessionCacheKey(t.id));const s=this.getState(),r=s.sessions.filter(n=>n.id!==t.id);if(this.setState({sessions:r,sessionStatuses:Xe(s.sessionStatuses,t.id),sessionActivities:Vs(s.sessionActivities,t.id),sendingPrompts:Xe(s.sendingPrompts,t.id),clientQueuedSessionMessages:Xe(s.clientQueuedSessionMessages,t.id)}),this.getState().selectedSession?.id!==t.id)return;const o=r.find(n=>n.archived!==!0)??r[0];o!==void 0?await this.selectSession(o):(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||!He(t,this.statusForSession(t),this.sessionPersistenceOptions()))return;const i=f(this.getState()),s=this.getState().machineRuntimes[i];if(s?.ok!==!0||!Pe(s,we.sessionsReload)){this.setState({error:"Reloading sessions from disk 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||gt(i)))try{this.flushPendingUpdates();const[s,r]=await Promise.all([this.api.messages(i,{limit:Qt},f(this.getState())),this.api.status(i,f(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...o,status:r,activity:this.getState().sessionActivities[t],...this.setStreamCatchup(r.isStreaming?t:void 0)}),this.applyStatus(r)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}applyBulkSessionFailures(t,i){i.length!==0&&this.setState({error:`${t} failed for ${String(i.length)} session${i.length===1?"":"s"}: ${i.join("; ")}`})}sessionCacheKey(t){return oi(f(this.getState()),t)}statusForSession(t){if(t===void 0)return;const i=this.getState();return i.status?.sessionId===t.id&&i.selectedSession?.id===t.id?i.status:i.sessionStatuses[t.id]}sessionPersistenceOptions(){const t=this.getState();return Nl(t.machineRuntimes[f(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})}createPendingSessionStart(t,i){const s=`pending-session-${String(++this.pendingSessionStartSeq)}-${Date.now().toString(36)}`,r=new Date().toISOString(),o={id:s,path:`pi-web://pending-session/${s}`,cwd:t.path,persisted:!1,name:"New session",created:r,modified:r,messageCount:0,firstMessage:"",clientPendingStart:!0,machineId:i};return{tempId:s,workspaceId:t.id,cwd:t.path,machineId:i,session:o,queuedSends:[],discarded:!1}}insertAndSelectPendingSession(t){const i=this.getState();this.selectClientPendingStartSession(t,{activity:Gs(t.id),sessions:[t,...i.sessions.filter(s=>s.id!==t.id)]})}selectClientPendingStartSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)}),this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingUpdates();const s=this.getState(),r=this.pendingSessionStarts.get(t.id),o=i?.activity??s.sessionActivities[t.id]??(r!==void 0?Gs(t.id,r.queuedSends.length):void 0);this.setState({...i?.sessions===void 0?{}:{sessions:i.sessions},selectedSession:t,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:o,availableThinkingLevels:[],...o===void 0?{}:{sessionActivities:{...s.sessionActivities,[t.id]:o}},error:""}),i?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(t,i){const s=this.pendingSessionStarts.get(t);if(s===void 0)return;this.pendingSessionStarts.delete(t);const r=s.queuedSends.splice(0),o=this.takeSuppressedCreatedSessionsFor(s.cwd,s.machineId,i.id);if(s.discarded){is(oi(s.machineId,t)),this.setState({clientQueuedSessionMessages:Xe(this.getState().clientQueuedSessionMessages,t)}),this.applyReleasedCreatedSessions(o,s.machineId),this.api.stop(i,s.machineId).catch(()=>{});return}un(i,s.machineId),mn(oi(s.machineId,t),oi(s.machineId,i.id));const n=xr(i,s.machineId);if(!this.isCurrentPendingStart(s)){this.setState({clientQueuedSessionMessages:Xe(this.getState().clientQueuedSessionMessages,t)}),await this.flushQueuedPendingSends(n,s.machineId,r);return}const a=this.getState(),d=a.selectedSession?.id===t;this.setState({sessions:Xf(a.sessions,t,n),sessionActivities:Vs(a.sessionActivities,t),sendingPrompts:Cn(a.sendingPrompts,t,n.id),clientQueuedSessionMessages:Cn(a.clientQueuedSessionMessages,t,n.id),...d?{selectedSession:n,status:a.sessionStatuses[n.id],activity:a.sessionActivities[n.id]}:{},error:""}),this.applyReleasedCreatedSessions(o,s.machineId),d&&(this.updateUrl({replace:!0}),await this.selectSession(n,{updateUrl:!1})),await this.flushQueuedPendingSends(n,s.machineId,r)}failPendingSessionStart(t,i){const s=this.pendingSessionStarts.get(t);if(s===void 0)return;this.pendingSessionStarts.delete(t);const r=this.takeSuppressedCreatedSessionsFor(s.cwd,s.machineId),o=this.isCurrentPendingStart(s);if(s.discarded||!o){o&&this.applyReleasedCreatedSessions(r,s.machineId);return}const n=this.getState(),a=zi(i),d=Yf(t,a,s.queuedSends.length),p=n.sessions.some(u=>u.id===t);this.setState({sessions:p?n.sessions:[s.session,...n.sessions],sessionActivities:{...n.sessionActivities,[t]:d},activity:n.selectedSession?.id===t?d:n.activity,error:`Failed to start session: ${a}`}),this.applyReleasedCreatedSessions(r,s.machineId)}isCurrentPendingStart(t){const i=this.getState();return f(i)===t.machineId&&i.selectedWorkspace?.id===t.workspaceId}hasPendingStartFor(t,i){return Array.from(this.pendingSessionStarts.values()).some(s=>s.cwd===t&&s.machineId===i)}isSuppressedCreatedSession(t,i){const s=this.suppressedCreatedSessions.get(t.id);return s?.session.cwd===t.cwd&&s.machineId===i}takeSuppressedCreatedSessionsFor(t,i,s){if(s!==void 0&&this.suppressedCreatedSessions.delete(s),this.hasPendingStartFor(t,i))return[];const r=[];for(const[o,n]of this.suppressedCreatedSessions)n.session.cwd!==t||n.machineId!==i||(this.suppressedCreatedSessions.delete(o),r.push(n.session));return r}applyReleasedCreatedSessions(t,i){if(t.length===0||f(this.getState())!==i)return;const s=this.getState();if(s.selectedWorkspace===void 0)return;const r=new Set(s.sessions.map(n=>n.id)),o=t.filter(n=>n.cwd===s.selectedWorkspace?.path&&!r.has(n.id));o.length!==0&&this.setState({sessions:[...o.reverse(),...s.sessions]})}mergePendingStartSessions(t,i,s){const r=this.getState().sessions.filter(n=>gt(n)&&n.cwd===t&&n.machineId===s);if(r.length===0)return i;const o=new Set(r.map(n=>n.id));return[...r,...i.filter(n=>!o.has(n.id))]}async recreateCachedNewSession(t,i){try{const s=f(this.getState()),r=await this.api.startSession(t.cwd,s);un(r,s),mn(this.sessionCacheKey(t.id),this.sessionCacheKey(r.id)),fn(t.id,s);const o=xr(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(!Zi(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(xu(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,qe(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&ts(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();if(i.selectedWorkspace?.path!==t.cwd||i.sessions.some(r=>r.id===t.id))return;const s=f(i);if(this.hasPendingStartFor(t.cwd,s)){this.suppressedCreatedSessions.set(t.id,{session:t,machineId:s});return}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"&&!dt(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...og(i,t.sessionId,t.messageCount),...s?{sessionActivities:Vs(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(ng(t))return}if(t.type==="status.update"){this.queueStatusUpdate(t.status);return}if(t.type==="activity.update"){this.queueActivityUpdate(t.activity);return}if(ag(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:Qt},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 Vs(e,t){return Xe(e,t)}function Xe(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Pn(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 Cn(e,t,i){if(t===i||!(t in e))return e;const s=e[t];return s===void 0?e:{...Xe(e,t),[i]:s}}function Xf(e,t,i){const s=[];let r=!1;for(const o of e){if(o.id===t){r||(s.push(i),r=!0);continue}o.id!==i.id&&s.push(o)}return r?s:[i,...s]}function gt(e){return e!==void 0&&"clientPendingStart"in e&&e.clientPendingStart===!0}function Gs(e,t=0){return{sessionId:e,phase:"active",label:"Creating session",detail:t>0?`${String(t)} queued ${t===1?"message":"messages"} will send when the backend session is ready`:"Waiting for the backend session to be ready",at:new Date().toISOString()}}function Yf(e,t,i=0){const s=i>0?` · ${String(i)} queued ${i===1?"message":"messages"} kept below`:"";return{sessionId:e,phase:"error",label:"Session creation failed",detail:`${t}${s}`,at:new Date().toISOString()}}function eg(e){return e.type==="prompt"?{kind:e.streamingBehavior==="steer"?"steer":"followUp",text:tg(e.text,e.attachments)}:{kind:"followUp",text:e.text}}function tg(e,t){const i=ig(t);return i===void 0?e:e.trim()===""?i:`${e}
25
25
 
26
- 永久删除只适用于已归档会话,且无法撤销。`}function Hf(e){return`请更新并重启 ${e??"此机器"} 上的 Pi-Web 后再清理会话。`}function fn(e,t){const i=e.trim();if(i==="")return`${t}必须设置。`;const s=Number(i);return!Number.isInteger(s)||s<0?`${t}必须是非负整数天数。`:s}const qf="management";function vl(e){return Kf(Vf())===qf}function Kf(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function Vf(){return typeof window>"u"?void 0:window.location.search}const zr="themes:classic",Gf="themes:pi-web-dark",Jf={themeId:Gf,auto:!0},bl="pi-web-app-theme",Qf=["--pi-bg","--pi-surface","--pi-surface-hover","--pi-terminal-bg","--pi-terminal-text","--pi-border","--pi-border-muted","--pi-text","--pi-text-secondary","--pi-text-bright","--pi-muted","--pi-dim","--pi-accent","--pi-accent-border","--pi-selection-bg","--pi-success","--pi-success-border","--pi-success-bg","--pi-success-surface","--pi-success-ring","--pi-warning","--pi-warning-border","--pi-warning-surface","--pi-danger","--pi-purple","--pi-purple-border","--pi-purple-surface","--pi-overlay","--pi-shadow-soft","--pi-shadow","--pi-shadow-strong","--pi-bg-overlay-soft","--pi-bg-overlay","--pi-success-bg-overlay","--pi-terminal-selection"],Zf=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Xf(){try{const e=window.localStorage.getItem(bl);return e===null?void 0:sg(e)}catch{return}}function Yf(e){try{window.localStorage.setItem(bl,JSON.stringify(e))}catch{}}function eg(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of Qf){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function tg(e){const t=ig(e.themes,e.fallbackThemeId??zr),i=e.themes.find(n=>n.id===e.preference.themeId)??t;if(i===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};const s=wl(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const r=e.prefersLight?s.light:s.dark,o=e.themes.find(n=>n.id===r)??i;return{selectedTheme:i,activeTheme:o,selectedThemePair:s,fallbackTheme:t}}function ig(e,t=zr){return e.find(i=>i.id===t)??e[0]}function wl(e,t){return e.find(i=>i.light===t||i.dark===t)}function sg(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return rg(i)?i:void 0}catch{return}}function rg(e){if(!og(e))return!1;const t=e.themeId,i=e.auto;return ng(t)&&typeof i=="boolean"}function og(e){return typeof e=="object"&&e!==null}function ng(e){return typeof e=="string"&&Zf.test(e)}const ag="workspace.delete",lg="pi.operation",cg="target.workspaceId";function dg(e){return{...e===void 0?{}:{projectId:e},metadata:{[lg]:ag}}}function pg(e){const t={};for(const i of e){const s=sr(i);if(s===void 0)continue;const r=t[s];(r===void 0||i.createdAt.localeCompare(r.createdAt)>=0)&&(t[s]=i)}return t}function hg(e){return Object.entries(e).filter(([,t])=>zi(t)).map(([t])=>t)}function yl(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&zi(i)}function sr(e){return e.metadata[cg]}function zi(e){return e.status==="queued"||e.status==="running"}function gn(){return[{id:"actions.show",title:"显示操作",description:"打开命令面板",shortcut:"mod+k",group:"通用",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"聚焦提示词输入框",description:"将键盘焦点移动到消息编辑器",shortcut:"mod+g c",group:"通用",enabled:e=>e.state.selectedSession!==void 0,run:e=>{e.focusPrompt()}},{id:"machine.add",title:"添加机器",description:"注册另一个可从当前网关访问的 PI WEB 运行时",group:"机器",run:e=>e.addMachine()},{id:"machine.refresh",title:"刷新所选机器",description:"检查所选 PI WEB 运行时是否在线",group:"机器",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"打开所选机器的 PI WEB",description:"在新标签页中直接打开所选远程 PI WEB",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"移除所选机器",description:"从当前网关移除所选远程机器",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{id:"project.add",title:"添加项目",group:"项目",run:e=>e.addProject()},{id:"auth.login",title:"配置提供商认证",description:"运行 /login,但不将认证绑定到某个会话",group:"通用",run:e=>e.configureAuth()},{id:"auth.logout",title:"移除提供商认证",description:"针对已保存的 pi 凭据运行 /logout",group:"通用",run:e=>e.logoutAuth()},{id:"theme.select",title:"选择主题",description:"选择 PI WEB 颜色主题",group:"偏好设置",run:e=>{e.openThemePicker()}},{id:"settings.open",title:"打开设置",description:"管理 PI WEB 配置和键盘快捷键",shortcut:"mod+,",group:"偏好设置",run:e=>{e.piWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"完整重载页面",description:"重新加载 PI WEB 浏览器页面",group:"通用",run:e=>{e.reloadPage()}},{id:"view.chat",title:"转到聊天",shortcut:"mod+1",group:"导航",run:e=>{e.focusPrompt()}},{id:"view.files",title:"转到文件",shortcut:"mod+2",group:"导航",enabled:jt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:mn,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:jt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:jt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:mn,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:jt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"删除工作区",description:"移除所选 Git worktree",group:"工作区",enabled:ug,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:jt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:fg,run:e=>e.archiveSession()},{id:"session.reload",title:"重新加载会话",description:"从磁盘重新读取所选会话,以获取其他进程写入的条目",group:"会话",enabled:mg,disabledReason:xl,run:e=>e.reloadSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:gg,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&tt(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function jt(e){return e.state.selectedWorkspace!==void 0}function mn(e){return e.state.selectedWorkspace?.isGitRepo===!0}function ug(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!yl(e.state,t)}function fg(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!Y(t)}function gg(e){return Y(e.state.selectedSession)}function mg(e){const t=e.state.selectedSession;return t===void 0||t.archived===!0||Y(t)||xl(e)!==void 0?!1:!tt(e.state.status,e.state.activity)}function xl(e){const t=e.state.selectedSession;if(!(t===void 0||t.archived===!0||Y(t))&&!tt(e.state.status,e.state.activity))return vg(e.state,_e.sessionsReload,"reload sessions")}function vg(e,t,i){const s=e.machineRuntimes[f(e)];if(!(s?.ok===!0&&qe(s,t)))return`Update and restart Pi-Web on ${e.selectedMachine?.name??"this machine"} to ${i}.`}const bg="modulepreload",wg=function(e){return"/"+e},vn={},Ur=function(t,i,s){let r=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");r=c(i.map(p=>{if(p=wg(p),p in vn)return;vn[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const g=document.createElement("link");if(g.rel=u?"stylesheet":bg,u||(g.as="script"),g.crossOrigin="",g.href=p,a&&g.setAttribute("nonce",a),document.head.appendChild(g),u)return new Promise((y,P)=>{g.addEventListener("load",y),g.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function o(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return r.then(n=>{for(const a of n||[])a.status==="rejected"&&o(a.reason);return t().catch(o)})};function yg(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:Pi(e)}function Pi(e){switch(e){case"navigation":return be`
26
+ ${i}`}function ig(e){if(e===void 0||e.length===0)return;const t=e.map(n=>n.name?.trim()).filter(n=>n!==void 0&&n!==""),i=e.length,s=`${String(i)} ${i===1?"attachment":"attachments"}`;if(t.length===0)return`[${s} queued]`;const r=t.slice(0,3).join(", "),o=t.length>3?`, +${String(t.length-3)} more`:"";return`[${s} queued: ${r}${o}]`}function Rn(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 In(e){return e.filter(sg).map(t=>t.value)}function An(e){return e.map(t=>`${t.sessionId}: ${t.error}`)}function Mn(e,t){return t.flatMap((i,s)=>rg(i)?[`${e[s]?.id??"unknown"}: ${zi(i.reason)}`]:[])}async function Tn(e,t,i){const s=e.map((d,p)=>({item:d,index:p})),r=[];let o=0;async function n(){for(;o<s.length;){const d=s[o];if(d===void 0)return;o+=1;try{r[d.index]={status:"fulfilled",value:await i(d.item)}}catch(p){r[d.index]={status:"rejected",reason:p}}}}const a=Math.min(Math.max(1,t),s.length);return await Promise.all(Array.from({length:a},()=>n())),r}function sg(e){return e.status==="fulfilled"}function rg(e){return e.status==="rejected"}function zi(e){return e instanceof Error?e.message:String(e)}function og(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 ng(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 ag(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function lg(e){if(!(e instanceof Error))return!1;const t=e.message.toLowerCase();return t.includes("session not found")||t.includes("未找到会话")}class cg{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 dg="pi-web:workspace-selection:v1";class pg{constructor(t=yi()){this.workspaceIdsByProject=new $s(dg,oo,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function hg(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 ug{constructor(t,i,s,r,o=new cg,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=r,this.workspaceSelection=o,this.api=n.api??K}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,..._i()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(zs(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,..._i()});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=hg(r,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(zs(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:zs(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,..._i()});try{const r=Ml(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=gg(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 fg(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function gg(e){return e.find(t=>t.isMain)??e[0]}const mg="pi-web:machine-navigation:v1";class vg{constructor(t=yi()){this.snapshotsByMachine=new $s(mg,wg,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?Wn(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,Wn(t))}forget(t){this.snapshotsByMachine.delete(t)}}function bg(e){return{machineId:e,surface:{}}}function En(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??Al,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 Dn(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 Wn(e){return{...e,surface:{...e.surface}}}function wg(e){if(!Kl(e))return;const t=Ye(e,"machineId");if(t===void 0)return;const i=Hl(Ye(e,"tool")),s=Sg(Ye(e,"view"));return{machineId:t,projectId:Ye(e,"projectId"),workspaceId:Ye(e,"workspaceId"),sessionId:Ye(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:yg(e.surface)}}function yg(e){return Kl(e)?{selectedFilePath:Ye(e,"selectedFilePath"),selectedDiffPath:Ye(e,"selectedDiffPath"),selectedTerminalId:Ye(e,"selectedTerminalId")}:{}}function Sg(e){return e==="navigation"||e==="chat"?e:Hl(e)}function Hl(e){return xg(e)?e:void 0}function xg(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Ye(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Kl(e){return typeof e=="object"&&e!==null}const kg="pi-web:terminal-selection:v1";class $g{constructor(t=yi()){this.terminalIdsByCwd=new $s(kg,oo,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 dk(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 pk(e){return e.find(t=>!t.exited)??e[0]}const Vl=1200,Pg=["mod","alt","shift"];class Cg{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const r=Ql(t);if(r===void 0)return!1;const o=no(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,r],o))return!0;if(this.clearPending(),!gi(r))return!1}else if(!gi(r))return!1;return this.handleSequence([r],o)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(o=>Og(o.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(o=>ao(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},Vl)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function no(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Rg(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($r)[0];u!==void 0&&o.set(u.key,u)}const n=[...o.values()].sort(Mg),a=new Map,d=new Map;for(const p of s){const u=o.get(p.key);if(u===void 0)continue;const h=Tg(u,n)??u;d.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=d.get(p),h=u===p,g=u===void 0||h?void 0:Ln(u),S=h?[...a.get(p)??[]].sort($r).map(Ln):[];return{...p,active:h,shadows:S,...g===void 0?{}:{shadowedBy:g}}}).sort((p,u)=>p.order-u.order)}function Qs(e){return Jl(e,{requireFirstChordActivator:!0})}function Gl(e){const t=Jl(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function Ni(e){return Gl(e).map(t=>t.split("+").map(Xl).join("+")).join(" ")}function Ql(e){if(e.isComposing)return;const t=Wg(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 gi(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Rg(e,t,i){const s=Ig(e.id,t);if(s===null)return;const r=s??e.shortcut;if(r===void 0||r==="")return;const o=Gl(r),n=o[0];if(!(n===void 0||!gi(n)))return{action:e,shortcut:o.join(" "),source:s===void 0?"default":"custom",tokens:o,key:Ag(o),order:i}}function Ig(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Ag(e){return e.join("\0")}function Ln(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function $r(e,t){return On(e.source)-On(t.source)||Fn(e.action.id,t.action.id)||Fn(e.action.title,t.action.title)||e.order-t.order}function Mg(e,t){return e.tokens.length-t.tokens.length||$r(e,t)}function Tg(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&ao(e.tokens,i.tokens))}function On(e){switch(e){case"custom":return 0;case"default":return 1}}function Fn(e,t){return e<t?-1:e>t?1:0}function Jl(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=Eg(n);if(!a.ok)return a;if(o===0&&t.requireFirstChordActivator&&!gi(a.token))return{ok:!1,message:"快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。"};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Eg(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=Dg(o);if(n!==void 0){if(i.has(n))return{ok:!1,message:`快捷键包含重复的 ${Xl(n)} 修饰键。`};i.add(n);continue}const a=Zl(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:[...Pg.filter(o=>i.has(o)),s].join("+")}}function Dg(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 Zl(e){const t=Lg(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 Wg(e){if(e===" ")return"space";const t=e.toLowerCase();return Zl(t)}function Lg(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 Xl(e){return e==="mod"?_n()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?_n()?"⌥":"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 Og(e,t){return e.length===t.length&&ao(e,t)}function ao(e,t){return t.every((i,s)=>e[s]===i)}function _n(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const Fg={archiveIdleEnabled:!0,archiveIdleDays:"30",deleteArchivedEnabled:!1,deleteArchivedDays:"90"};function ni(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:"请至少启用一项清理操作。"};const t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){const i=Bn(e.archiveIdleDays,"归档空闲会话天数");if(typeof i=="string")return{ok:!1,error:i};t.archiveIdleDays=i}if(e.deleteArchivedEnabled){const i=Bn(e.deleteArchivedDays,"删除已归档会话天数");if(typeof i=="string")return{ok:!1,error:i};t.deleteArchivedDays=i}return{ok:!0,request:t}}function Ut(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null})}function jn(e){if(!e.canCleanup||e.loading===!0||e.running===!0||e.preview===void 0)return!1;const t=ni(e.draft);return!t.ok||Ut(t.request)!==Ut(e.previewRequest)?!1:qi(e.preview)}function qi(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function Yl(e,t){const i=e.projects.map(r=>r.cwd);if(t===void 0)return i;const s=new Set(t);return i.filter(r=>s.has(r))}function Un(e,t){const i=new Set(Yl(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 _g(e,t){return t(jg(e))}function jg(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("并")}?
27
+
28
+ 永久删除只适用于已归档会话,且无法撤销。`}function Ug(e){return`请更新并重启 ${e??"此机器"} 上的 Pi-Web 后再清理会话。`}function Bn(e,t){const i=e.trim();if(i==="")return`${t}必须设置。`;const s=Number(i);return!Number.isInteger(s)||s<0?`${t}必须是非负整数天数。`:s}const Bg="management";function ec(e){return zg(Ng())===Bg}function zg(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function Ng(){return typeof window>"u"?void 0:window.location.search}const lo="themes:classic",qg="themes:pi-web-dark",Hg={themeId:qg,auto:!0},tc="pi-web-app-theme",Kg=["--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"],Vg=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Gg(){try{const e=window.localStorage.getItem(tc);return e===null?void 0:Yg(e)}catch{return}}function Qg(e){try{window.localStorage.setItem(tc,JSON.stringify(e))}catch{}}function Jg(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of Kg){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function Zg(e){const t=Xg(e.themes,e.fallbackThemeId??lo),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=ic(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 Xg(e,t=lo){return e.find(i=>i.id===t)??e[0]}function ic(e,t){return e.find(i=>i.light===t||i.dark===t)}function Yg(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return em(i)?i:void 0}catch{return}}function em(e){if(!tm(e))return!1;const t=e.themeId,i=e.auto;return im(t)&&typeof i=="boolean"}function tm(e){return typeof e=="object"&&e!==null}function im(e){return typeof e=="string"&&Vg.test(e)}const sm="workspace.delete",rm="pi.operation",om="target.workspaceId";function nm(e){return{...e===void 0?{}:{projectId:e},metadata:{[rm]:sm}}}function am(e){const t={};for(const i of e){const s=Pr(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 lm(e){return Object.entries(e).filter(([,t])=>as(t)).map(([t])=>t)}function sc(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&as(i)}function Pr(e){return e.metadata[om]}function as(e){return e.status==="queued"||e.status==="running"}function zn(){return[{id:"actions.show",title:"显示操作",description:"打开命令面板",shortcut:"mod+k",group:"通用",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"聚焦提示词输入框",description:"将键盘焦点移动到消息编辑器",shortcut:"mod+g c",group:"通用",enabled:e=>e.state.selectedSession!==void 0,run:e=>{e.focusPrompt()}},{id:"machine.add",title:"添加机器",description:"注册另一个可从当前网关访问的 PI WEB 运行时",group:"机器",run:e=>e.addMachine()},{id:"machine.refresh",title:"刷新所选机器",description:"检查所选 PI WEB 运行时是否在线",group:"机器",run:e=>e.refreshSelectedMachine()},{id:"machine.open",title:"打开所选机器的 PI WEB",description:"在新标签页中直接打开所选远程 PI WEB",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote"&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:"machine.remove",title:"移除所选机器",description:"从当前网关移除所选远程机器",group:"机器",enabled:e=>e.state.selectedMachine?.kind==="remote",run:e=>e.removeSelectedMachine()},{id:"project.add",title:"添加项目",group:"项目",run:e=>e.addProject()},{id:"auth.login",title:"配置提供商认证",description:"运行 /login,但不将认证绑定到某个会话",group:"通用",run:e=>e.configureAuth()},{id:"auth.logout",title:"移除提供商认证",description:"针对已保存的 pi 凭据运行 /logout",group:"通用",run:e=>e.logoutAuth()},{id:"theme.select",title:"选择主题",description:"选择 PI WEB 颜色主题",group:"偏好设置",run:e=>{e.openThemePicker()}},{id:"settings.open",title:"打开设置",description:"管理 PI WEB 配置和键盘快捷键",shortcut:"mod+,",group:"偏好设置",run:e=>{e.piWebUnstable?.openSettings?.()}},{id:"app.reload-page",title:"完整重载页面",description:"重新加载 PI WEB 浏览器页面",group:"通用",run:e=>{e.reloadPage()}},{id:"view.chat",title:"转到聊天",shortcut:"mod+1",group:"导航",run:e=>{e.focusPrompt()}},{id:"view.files",title:"转到文件",shortcut:"mod+2",group:"导航",enabled:Jt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:Nn,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:Jt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:Jt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:Nn,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:Jt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"删除工作区",description:"移除所选 Git worktree",group:"工作区",enabled:cm,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:Jt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:dm,run:e=>e.archiveSession()},{id:"session.reload",title:"重新加载会话",description:"关闭并从会话文件重新打开所选会话;如需重载 Pi 运行时资源,请在提示词中使用 /reload",group:"会话",enabled:hm,disabledReason:rc,run:e=>e.reloadSession()},{id:"session.delete",title:"删除新会话",description:"删除所选的临时新会话",group:"会话",enabled:pm,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&dt(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function Jt(e){return e.state.selectedWorkspace!==void 0}function Nn(e){return e.state.selectedWorkspace?.isGitRepo===!0}function cm(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!sc(e.state,t)}function dm(e){return He(e.state.selectedSession,e.state.status,Ps(e.state))}function pm(e){return fi(e.state.selectedSession,e.state.status,Ps(e.state))}function hm(e){return!He(e.state.selectedSession,e.state.status,Ps(e.state))||rc(e)!==void 0?!1:!dt(e.state.status,e.state.activity)}function rc(e){if(He(e.state.selectedSession,e.state.status,Ps(e.state))&&!dt(e.state.status,e.state.activity))return um(e.state,we.sessionsReload,"reload sessions from disk")}function Ps(e){return Nl(e.machineRuntimes[f(e)])}function um(e,t,i){const s=e.machineRuntimes[f(e)];if(!(s?.ok===!0&&Pe(s,t)))return`Update and restart Pi-Web on ${e.selectedMachine?.name??"this machine"} to ${i}.`}const fm="modulepreload",gm=function(e){return"/"+e},qn={},co=function(t,i,s){let r=Promise.resolve();if(i&&i.length>0){let d=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=d(i.map(p=>{if(p=gm(p),p in qn)return;qn[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":fm,u||(g.as="script"),g.crossOrigin="",g.href=p,a&&g.setAttribute("nonce",a),document.head.appendChild(g),u)return new Promise((S,P)=>{g.addEventListener("load",S),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 mm(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:Hi(e)}function Hi(e){switch(e){case"navigation":return $e`
27
29
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
28
30
  <circle cx="6" cy="7" r="1.5"></circle>
29
31
  <path d="M10 7h8"></path>
@@ -32,17 +34,17 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
32
34
  <circle cx="6" cy="17" r="1.5"></circle>
33
35
  <path d="M10 17h8"></path>
34
36
  </svg>
35
- `;case"chat":return be`
37
+ `;case"chat":return $e`
36
38
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
37
39
  <path d="M7 5h10a3 3 0 0 1 3 3v5a3 3 0 0 1-3 3h-6l-5 4v-4H7a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3Z"></path>
38
40
  <path d="M8 9h8"></path>
39
41
  <path d="M8 13h5"></path>
40
42
  </svg>
41
- `;case"files":return be`
43
+ `;case"files":return $e`
42
44
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
43
45
  <path d="M3 7a2 2 0 0 1 2-2h4l2 2.5h8a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"></path>
44
46
  </svg>
45
- `;case"git":return be`
47
+ `;case"git":return $e`
46
48
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
47
49
  <circle cx="6" cy="6" r="2"></circle>
48
50
  <circle cx="18" cy="6" r="2"></circle>
@@ -51,13 +53,13 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
51
53
  <path d="M6 8v2a6 6 0 0 0 6 6"></path>
52
54
  <path d="M18 8v2a6 6 0 0 1-6 6"></path>
53
55
  </svg>
54
- `;case"terminal":return be`
56
+ `;case"terminal":return $e`
55
57
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
56
58
  <rect x="3" y="5" width="18" height="14" rx="2"></rect>
57
59
  <path d="m7 10 3 3-3 3"></path>
58
60
  <path d="M12 16h5"></path>
59
61
  </svg>
60
- `}}const xg=10*1024*1024,Sg="10 MB",kg=D`
62
+ `}}const vm=10*1024*1024,bm="10 MB",wm=D`
61
63
  :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
64
  header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
63
65
  .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
@@ -112,7 +114,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
112
114
  .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
115
  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
116
  p { margin: 10px; }
115
- `,$g=D`
117
+ `,ym=D`
116
118
  :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
117
119
  footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
118
120
  footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
@@ -163,7 +165,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
163
165
  button { padding: 5px 7px; }
164
166
  .icon-button { width: 34px; height: 34px; }
165
167
  }
166
- `;var Pg=Object.defineProperty,Cg=Object.getOwnPropertyDescriptor,Ge=(e,t,i,s)=>{for(var r=s>1?void 0:s?Cg(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Pg(t,i,r),r};let Me=class extends R{constructor(){super(...arguments),this.destinationFolder="",this.overwrite=!1,this.createDirs=!0,this.formError="",this.dragActive=!1,this.dragDepth=0,this.openFilePicker=()=>{this.uploadInput?.click()},this.handleFileInputChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0,i=kn(t?.files);t!==void 0&&(t.value=""),i.length>0&&this.openUploadReview(i)},this.handleDragEnter=e=>{di(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{di(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect="copy"),this.dragActive=!0)},this.handleDragLeave=e=>{di(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!di(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;const t=kn(e.dataTransfer?.files),i=this.context;t.length>0&&i!==void 0&&Mg(i,t)},this.handleDestinationInput=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.destinationFolder=t?.value??"",this.formError=""},this.handleCreateDirsChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.createDirs=t?.checked??!0},this.handleOverwriteChange=e=>{const t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.overwrite=t?.checked??!1},this.handleDialogKeyDown=e=>{e.key==="Escape"&&(e.preventDefault(),this.closeUploadDialog())}}willUpdate(e){if(!e.has("context"))return;const t=e.get("context");t!==void 0&&this.context!==void 0&&yn(t)!==yn(this.context)&&this.resetPendingUpload()}render(){const e=this.context;if(e===void 0)return l`<p class="muted">文件不可用。</p>`;const t=e.selectedFilePath,i=bn(e.fileTree,e.expandedDirs,t),s=Tg(t,i),r=t!==void 0&&t!=="";return l`
168
+ `;var Sm=Object.defineProperty,xm=Object.getOwnPropertyDescriptor,it=(e,t,i,s)=>{for(var r=s>1?void 0:s?xm(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&&Sm(t,i,r),r};let _e=class extends I{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=Jn(t?.files);t!==void 0&&(t.value=""),i.length>0&&this.openUploadReview(i)},this.handleDragEnter=e=>{Ii(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{Ii(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect="copy"),this.dragActive=!0)},this.handleDragLeave=e=>{Ii(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!Ii(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;const t=Jn(e.dataTransfer?.files),i=this.context;t.length>0&&i!==void 0&&Rm(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&&Vn(t)!==Vn(this.context)&&this.resetPendingUpload()}render(){const e=this.context;if(e===void 0)return l`<p class="muted">文件不可用。</p>`;const t=e.selectedFilePath,i=Hn(e.fileTree,e.expandedDirs,t),s=Cm(t,i),r=t!==void 0&&t!=="";return l`
167
169
  <section
168
170
  class=${this.dragActive?"files-panel dragging":"files-panel"}
169
171
  @dragenter=${this.handleDragEnter}
@@ -207,22 +209,22 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
207
209
  <span>${t.name}</span>
208
210
  </button>
209
211
  ${r?s.map(n=>this.renderTreeEntry(e,n,i+1)):null}
210
- `}selectTreeEntry(e,t){if(t.type==="directory"){e.onSelectDirectory(t.path),e.onExpandDir(t.path);return}e.onSelectFile(t.path)}renderFileViewer(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">请选择文件。</p>`:bn(e.fileTree,e.expandedDirs,e.selectedFilePath)==="directory"?l`<p class="muted">已选择文件夹:${e.selectedFilePath}</p>`:t===void 0?l`<p class="muted">正在加载 ${e.selectedFilePath}…</p>`:t.mediaType==="image"?this.renderImageViewer(e,t):t.binary?l`<p class="muted">二进制文件:${t.path} · ${Pt(t.size)}</p>`:(zg(),l`
212
+ `}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>`:Hn(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} · ${Ft(t.size)}</p>`:(Om(),l`
211
213
  <div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"文本"}${t.truncated?" · 已截断":""}</small></div>
212
214
  <code-viewer .content=${t.content} .language=${t.language}></code-viewer>
213
- `)}renderImageViewer(e,t){const i=`${t.mimeType??"image"} · ${Pt(t.size)}`;if(t.size>xg)return l`
215
+ `)}renderImageViewer(e,t){const i=`${t.mimeType??"image"} · ${Ft(t.size)}`;if(t.size>vm)return l`
214
216
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
215
- <p class="muted">图片过大,无法预览:${Pt(t.size)} · 限制 ${Sg}</p>
216
- `;const s=Ep(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
217
+ <p class="muted">图片过大,无法预览:${Ft(t.size)} · 限制 ${bm}</p>
218
+ `;const s=Ph(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
217
219
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
218
220
  <div class="image-preview">
219
221
  <img src=${s} alt=${t.path} decoding="async" />
220
222
  </div>
221
- `}renderUploadProgress(e){const t=Ig(e.state.workspaceUploadBatches,{projectId:e.workspace.projectId,workspaceId:e.workspace.id,machineId:e.machine.id});return t.length===0?null:l`
223
+ `}renderUploadProgress(e){const t=km(e.state.workspaceUploadBatches,{projectId:e.workspace.projectId,workspaceId:e.workspace.id,machineId:e.machine.id});return t.length===0?null:l`
222
224
  <section class="upload-progress" aria-label="工作区上传">
223
225
  <div class="upload-progress-header">
224
226
  <strong>上传</strong>
225
- <small>${Wg(t)}</small>
227
+ <small>${Mm(t)}</small>
226
228
  </div>
227
229
  ${t.map(i=>this.renderUploadBatch(e,i))}
228
230
  </section>
@@ -230,12 +232,12 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
230
232
  <article class=${`upload-batch ${t.status}`}>
231
233
  <div class="upload-batch-heading">
232
234
  <div>
233
- <strong>${Og(t)}</strong>
235
+ <strong>${Tm(t)}</strong>
234
236
  <small>${t.destinationFolder===""?"工作区根目录":t.destinationFolder}</small>
235
237
  </div>
236
- <span>${_g(t)}</span>
238
+ <span>${Em(t)}</span>
237
239
  </div>
238
- <progress max="1" .value=${Lg(t)}></progress>
240
+ <progress max="1" .value=${Dm(t)}></progress>
239
241
  <div class="upload-file-list">
240
242
  ${t.files.map(i=>this.renderUploadFile(i))}
241
243
  </div>
@@ -243,13 +245,13 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
243
245
  ${t.status==="uploading"?l`<button @click=${()=>{e.onCancelWorkspaceUpload(t.id)}}>取消</button>`:l`<button @click=${()=>{e.onClearWorkspaceUpload(t.id)}}>关闭</button>`}
244
246
  </div>
245
247
  </article>
246
- `}renderUploadFile(e){const t=Fg(e);return l`
248
+ `}renderUploadFile(e){const t=Lm(e);return l`
247
249
  <div class=${`upload-file ${e.status}`}>
248
250
  <div class="upload-file-main">
249
251
  <span>${e.name}</span>
250
252
  <small>${t}</small>
251
253
  </div>
252
- <span class="upload-file-status">${jg(e)}</span>
254
+ <span class="upload-file-status">${Wm(e)}</span>
253
255
  </div>
254
256
  `}renderUploadDialog(e,t){const i=t.files.length;return l`
255
257
  <div class="dialog-backdrop" @mousedown=${()=>{this.closeUploadDialog()}}>
@@ -282,7 +284,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
282
284
  ${t.files.map(s=>l`
283
285
  <div class="review-file">
284
286
  <span>${s.name}</span>
285
- <small>${Pt(s.size)}</small>
287
+ <small>${Ft(s.size)}</small>
286
288
  </div>
287
289
  `)}
288
290
  </section>
@@ -294,7 +296,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
294
296
  </form>
295
297
  </section>
296
298
  </div>
297
- `}promptCreateFile(e,t){const i=xn("新建文件路径",wn(e.selectedFilePath,t,"new-file.txt"));i!==void 0&&e.onCreateFile(i)}promptCreateDirectory(e,t){const i=xn("新建文件夹路径",wn(e.selectedFilePath,t,"new-folder"));i!==void 0&&e.onCreateDirectory(i)}confirmDeleteSelectedPath(e){const t=e.selectedFilePath;t===void 0||t===""||window.confirm(`删除 ${t}?此操作无法撤销。`)&&e.onDeleteSelectedPath()}openUploadReview(e){const t=this.context,i=Ag(t?.workspaceUploadDefaultFolder??"");this.pendingUpload={files:e},this.destinationFolder=i.destinationFolder,this.overwrite=i.overwrite,this.createDirs=i.createDirs,this.formError=""}submitUploadReview(e,t,i){e.preventDefault();const s=Rg(i.files,this.destinationFolder);if(s!==void 0){this.formError=s;return}t.onStartWorkspaceUpload(i.files,{destinationFolder:this.destinationFolder,createDirs:this.createDirs,overwrite:this.overwrite,selectUploadedFile:!0})!==void 0&&this.closeUploadDialog()}closeUploadDialog(){this.pendingUpload=void 0,this.formError=""}resetPendingUpload(){this.closeUploadDialog(),this.dragDepth=0,this.dragActive=!1}};Me.styles=[kg,D`
299
+ `}promptCreateFile(e,t){const i=Gn("新建文件路径",Kn(e.selectedFilePath,t,"new-file.txt"));i!==void 0&&e.onCreateFile(i)}promptCreateDirectory(e,t){const i=Gn("新建文件夹路径",Kn(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=Pm(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=$m(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}};_e.styles=[wm,D`
298
300
  :host { flex: 1 1 auto; }
299
301
  .files-panel { position: relative; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
300
302
  .toolbar-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
@@ -342,7 +344,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
342
344
  .review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
343
345
  .dialog-error { border: 1px solid var(--pi-danger); border-radius: 8px; background: color-mix(in srgb, var(--pi-danger) 10%, transparent); color: var(--pi-danger); padding: 9px; line-height: 1.35; overflow-wrap: anywhere; }
344
346
  footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
345
- `];Ge([d({attribute:!1})],Me.prototype,"context",2);Ge([B("#workspace-upload-input")],Me.prototype,"uploadInput",2);Ge([w()],Me.prototype,"pendingUpload",2);Ge([w()],Me.prototype,"destinationFolder",2);Ge([w()],Me.prototype,"overwrite",2);Ge([w()],Me.prototype,"createDirs",2);Ge([w()],Me.prototype,"formError",2);Ge([w()],Me.prototype,"dragActive",2);Me=Ge([W("workspace-files-panel")],Me);function Ig(e,t){return Object.values(e).filter(i=>i.projectId===t.projectId&&i.workspaceId===t.workspaceId&&i.machineId===t.machineId).sort((i,s)=>s.startedAt.localeCompare(i.startedAt))}function Rg(e,t){if(e.length===0)return"请至少选择一个要上传的文件。";for(const i of e)try{Rr(t,i.name)}catch(s){return s instanceof Error?s.message:String(s)}}function Ag(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function bn(e,t,i){if(i!==void 0)return Eg(e,t,i)?.type}function Tg(e,t){return e!==void 0&&e!==""&&t==="file"}function wn(e,t,i){if(e===void 0||e==="")return i;if(t==="directory")return Sn(e,i);const s=Dg(e);return s===""?i:Sn(s,i)}function Mg(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function yn(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function xn(e,t){const i=window.prompt(e,t);if(i===null)return;const s=i.trim();return s===""?void 0:s}function Eg(e,t,i){const s=e.find(r=>r.path===i);if(s!==void 0)return s;for(const r of Object.values(t)){const o=r.find(n=>n.path===i);if(o!==void 0)return o}}function Dg(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function Sn(e,t){return e===""?t:`${e.replace(/\/+$/u,"")}/${t.replace(/^\/+/u,"")}`}function kn(e){return e==null?[]:Array.from(e)}function di(e){return Array.from(e.dataTransfer?.types??[]).includes("Files")}function Wg(e){const t=e.filter(i=>i.status==="uploading").length;return t===0?`${String(e.length)} 个最近`:`${String(t)} 个上传中`}function Og(e){const t=String(e.files.length);switch(e.status){case"completed":return`已上传 ${t} 个文件`;case"error":return`${t} 个文件上传失败`;case"cancelled":return`已取消 ${t} 个文件的上传`;case"uploading":return`正在上传 ${t} 个文件`}}function _g(e){switch(e.status){case"completed":return"完成";case"error":return"失败";case"cancelled":return"已取消";case"uploading":return Sl(e.percent)}}function Lg(e){return e.status==="uploading"?e.percent:1}function jg(e){switch(e.status){case"pending":return"待处理";case"uploading":return Sl(e.percent);case"completed":return"完成";case"error":return"错误";case"cancelled":return"已取消"}}function Fg(e){return e.error!==void 0?e.error:e.response!==void 0?`已写入 ${e.response.path}`:`${e.path} · ${Pt(e.loaded)} / ${Pt(e.total)}`}function Sl(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function zg(){Ur(()=>import("./CodeViewer-CGV4uBeZ.js"),__vite__mapDeps([0,1,2,3]))}function Pt(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${Cs(t)} KB`;const i=t/1024;return i<1024?`${Cs(i)} MB`:`${Cs(i/1024)} GB`}function Cs(e){return e>=10?String(Math.round(e)):e.toFixed(1)}function $n(){return[{id:"workspace.files",title:"文件",icon:Pi("files"),order:10,render:Ug},{id:"workspace.git",title:"Git",icon:Pi("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:Ng},{id:"workspace.terminal",title:"终端",icon:Pi("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Bg}]}function Ug(e){return l`<workspace-files-panel .context=${e}></workspace-files-panel>`}function Bg(e){return Vg(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Ng(e){const t=e.gitStatus;return l`
347
+ `];it([c({attribute:!1})],_e.prototype,"context",2);it([q("#workspace-upload-input")],_e.prototype,"uploadInput",2);it([v()],_e.prototype,"pendingUpload",2);it([v()],_e.prototype,"destinationFolder",2);it([v()],_e.prototype,"overwrite",2);it([v()],_e.prototype,"createDirs",2);it([v()],_e.prototype,"formError",2);it([v()],_e.prototype,"dragActive",2);_e=it([W("workspace-files-panel")],_e);function km(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 $m(e,t){if(e.length===0)return"请至少选择一个要上传的文件。";for(const i of e)try{Zr(t,i.name)}catch(s){return s instanceof Error?s.message:String(s)}}function Pm(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function Hn(e,t,i){if(i!==void 0)return Im(e,t,i)?.type}function Cm(e,t){return e!==void 0&&e!==""&&t==="file"}function Kn(e,t,i){if(e===void 0||e==="")return i;if(t==="directory")return Qn(e,i);const s=Am(e);return s===""?i:Qn(s,i)}function Rm(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function Vn(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Gn(e,t){const i=window.prompt(e,t);if(i===null)return;const s=i.trim();return s===""?void 0:s}function Im(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 Am(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}function Qn(e,t){return e===""?t:`${e.replace(/\/+$/u,"")}/${t.replace(/^\/+/u,"")}`}function Jn(e){return e==null?[]:Array.from(e)}function Ii(e){return Array.from(e.dataTransfer?.types??[]).includes("Files")}function Mm(e){const t=e.filter(i=>i.status==="uploading").length;return t===0?`${String(e.length)} 个最近`:`${String(t)} 个上传中`}function Tm(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 Em(e){switch(e.status){case"completed":return"完成";case"error":return"失败";case"cancelled":return"已取消";case"uploading":return oc(e.percent)}}function Dm(e){return e.status==="uploading"?e.percent:1}function Wm(e){switch(e.status){case"pending":return"待处理";case"uploading":return oc(e.percent);case"completed":return"完成";case"error":return"错误";case"cancelled":return"已取消"}}function Lm(e){return e.error!==void 0?e.error:e.response!==void 0?`已写入 ${e.response.path}`:`${e.path} · ${Ft(e.loaded)} / ${Ft(e.total)}`}function oc(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function Om(){co(()=>import("./CodeViewer-DssF-c9D.js"),__vite__mapDeps([0,1,2,3]))}function Ft(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`${Js(t)} KB`;const i=t/1024;return i<1024?`${Js(i)} MB`:`${Js(i/1024)} GB`}function Js(e){return e>=10?String(Math.round(e)):e.toFixed(1)}function Zn(){return[{id:"workspace.files",title:"文件",icon:Hi("files"),order:10,render:Fm},{id:"workspace.git",title:"Git",icon:Hi("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:jm},{id:"workspace.terminal",title:"终端",icon:Hi("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:_m}]}function Fm(e){return l`<workspace-files-panel .context=${e}></workspace-files-panel>`}function _m(e){return Nm(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function jm(e){const t=e.gitStatus;return l`
346
348
  <section class="toolbar">
347
349
  <strong>Git</strong>
348
350
  ${e.gitStale?l`<span class="stale">过期</span>`:null}
@@ -351,29 +353,29 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
351
353
  <section class="split">
352
354
  <div class="list">
353
355
  ${t===void 0?l`<p class="muted">尚未加载状态。</p>`:t.isGitRepo?l`
354
- <p class="summary">${Gg(t)}</p>
356
+ <p class="summary">${qm(t)}</p>
355
357
  ${t.files.length===0?l`<p class="muted">没有变更。</p>`:t.files.map(i=>l`
356
358
  <button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
357
- <span>${Jg(i.index,i.workingTree)}</span>
359
+ <span>${Hm(i.index,i.workingTree)}</span>
358
360
  <span>${i.path}</span>
359
361
  </button>
360
362
  `)}
361
363
  `:l`<p class="muted">不是 Git 仓库。</p>`}
362
364
  </div>
363
365
  <div class="viewer">
364
- ${Hg(e)}
366
+ ${Um(e)}
365
367
  </div>
366
368
  </section>
367
- `}function Hg(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return l`<p class="muted">请选择一个已变更文件。</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return l`<p class="muted">正在加载 diff…</p>`;const s=[i,t].filter(r=>r.diff!=="");return s.length===0?l`<p class="muted">没有 staged 或 unstaged diff。</p>`:l`
369
+ `}function Um(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return l`<p class="muted">请选择一个已变更文件。</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return l`<p class="muted">正在加载 diff…</p>`;const s=[i,t].filter(r=>r.diff!=="");return s.length===0?l`<p class="muted">没有 staged 或 unstaged diff。</p>`:l`
368
370
  <div class=${s.length===1?"diffs single":"diffs"}>
369
- ${s.map(r=>qg(r))}
371
+ ${s.map(r=>Bm(r))}
370
372
  </div>
371
- `}function qg(e){return Kg(),l`
373
+ `}function Bm(e){return zm(),l`
372
374
  <section class="diff-section">
373
375
  <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"已暂存":"未暂存"}${e.truncated?" · 已截断":""}</small></div>
374
376
  <unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
375
377
  </section>
376
- `}function Kg(){Ur(()=>import("./UnifiedDiffViewer-BSzsWx-m.js"),__vite__mapDeps([4,1,2]))}function Vg(){Ur(()=>import("./TerminalPanel-CeJN9p9P.js"),__vite__mapDeps([5,6,7,1,2]))}function Gg(e){const t=e.branch??"分离 HEAD",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function Jg(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}const Qg={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!vl();return{contributions:{actions:e?gn():gn().filter(t=>t.id!=="view.terminal"),workspacePanels:e?$n():$n().filter(t=>t.id!=="workspace.terminal")}}}},Zg={"--pi-bg":"#0d1117","--pi-surface":"#161b22","--pi-surface-hover":"#21262d","--pi-terminal-bg":"#05070a","--pi-terminal-text":"#e6edf3","--pi-border":"#30363d","--pi-border-muted":"#21262d","--pi-text":"#e6edf3","--pi-text-secondary":"#c9d1d9","--pi-text-bright":"#f0f6fc","--pi-muted":"#8b949e","--pi-dim":"#6e7681","--pi-accent":"#58a6ff","--pi-accent-border":"#2f81f7","--pi-selection-bg":"#0d2847","--pi-success":"#3fb950","--pi-success-border":"#238636","--pi-success-bg":"#0f1b12","--pi-success-surface":"#0f2a16","--pi-success-ring":"#3fb95055","--pi-warning":"#d29922","--pi-warning-border":"#6e5200","--pi-warning-surface":"#1f1a10","--pi-danger":"#ff7b72","--pi-purple":"#d2a8ff","--pi-purple-border":"#a371f7","--pi-purple-surface":"#21132f","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#0d1117dd","--pi-bg-overlay":"#0d1117e6","--pi-success-bg-overlay":"#0f1b12ee","--pi-terminal-selection":"#264f78"},Xg={"--pi-bg":"#070912","--pi-surface":"#101527","--pi-surface-hover":"#151b31","--pi-terminal-bg":"#050710","--pi-terminal-text":"#f7f4ff","--pi-border":"#26304f","--pi-border-muted":"#26304f","--pi-text":"#f7f4ff","--pi-text-secondary":"#aaa4bd","--pi-text-bright":"#ffffff","--pi-muted":"#aaa4bd","--pi-dim":"#817a99","--pi-accent":"#7c3cff","--pi-accent-border":"#5a47b0","--pi-selection-bg":"#1d2547","--pi-success":"#00f0d8","--pi-success-border":"#00f0d8","--pi-success-bg":"#071e22","--pi-success-surface":"#092d31","--pi-success-ring":"#00f0d855","--pi-warning":"#ffb000","--pi-warning-border":"#ffb000","--pi-warning-surface":"#16140d","--pi-danger":"#ff4f7b","--pi-purple":"#b7a2ff","--pi-purple-border":"#7c3cff","--pi-purple-surface":"#181026","--pi-overlay":"#0008","--pi-shadow-soft":"#0006","--pi-shadow":"#0008","--pi-shadow-strong":"#000b","--pi-bg-overlay-soft":"#070912dd","--pi-bg-overlay":"#070912e6","--pi-success-bg-overlay":"#071e22ee","--pi-terminal-selection":"#3d4a78"},Yg={"--pi-bg":"#f7f1e6","--pi-surface":"#fff9ee","--pi-surface-hover":"#f0e6d6","--pi-terminal-bg":"#15131b","--pi-terminal-text":"#fff9ee","--pi-border":"#c9bca8","--pi-border-muted":"#d8cdbc","--pi-text":"#15131b","--pi-text-secondary":"#15131b","--pi-text-bright":"#15131b","--pi-muted":"#5f586a","--pi-dim":"#766f7e","--pi-accent":"#6430d8","--pi-accent-border":"#6430d8","--pi-selection-bg":"#eadff8","--pi-success":"#008c82","--pi-success-border":"#008c82","--pi-success-bg":"#e1f4ef","--pi-success-surface":"#d7f0ec","--pi-success-ring":"#008c8255","--pi-warning":"#b05f00","--pi-warning-border":"#b05f00","--pi-warning-surface":"#fff2d2","--pi-danger":"#b51d49","--pi-purple":"#6430d8","--pi-purple-border":"#6430d8","--pi-purple-surface":"#eadff8","--pi-overlay":"#15131b66","--pi-shadow-soft":"#15131b22","--pi-shadow":"#15131b33","--pi-shadow-strong":"#15131b44","--pi-bg-overlay-soft":"#f7f1e6dd","--pi-bg-overlay":"#f7f1e6e6","--pi-success-bg-overlay":"#e1f4efee","--pi-terminal-selection":"#8d7b64"},em={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:Xg},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Yg},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Zg}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},tm=/^[a-z][a-z0-9.-]*$/u;function im(e){return tm.test(e)}const sm="machine.";function rm(e,t){if(e==="")throw new Error("Machine id is required");if(!im(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${sm}${om(e)}.${t}`}function om(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function Pn(e="/pi-web-plugins/manifest.json",t={}){const i=await nm(e);if(i===void 0)return[];const s=[];for(const r of i.plugins)if(t.shouldLoadPlugin?.(r)!==!1)try{const o=new URL(r.module,new URL(e,window.location.href)).toString(),n=await import(o),a=cm(n,o);s.push({id:t.machineId===void 0?r.id:rm(t.machineId,r.id),plugin:a,machineSpecific:r.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:r.id}})}catch(o){console.warn(`Failed to load PI WEB plugin ${r.module}`,o)}return s}async function nm(e){const t=await fetch(e,{cache:"no-store"});if(t.status!==404){if(!t.ok)throw new Error(`Failed to load plugin manifest: ${t.statusText}`);return am(await t.json())}}function am(e){if(!Ui(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!Ui(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module,machineSpecific:lm(t.machineSpecific)}})}}function lm(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function cm(e,t){if(!Ui(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!dm(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function dm(e){return Ui(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function Ui(e){return typeof e=="object"&&e!==null}const pm=/^[a-z][a-z0-9.-]*$/u,hm=/^[a-z][a-z0-9.-]*$/u,kl=new WeakMap,$l=new WeakMap;class um{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;this.validatePluginId(i);const r=this.parseMachineSpecific(i,t.machineSpecific);if(this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(this.isRemoteDuplicateHiddenByGateway(t.sourcePluginId,t.machineId,r))return;this.pluginIds.add(i);const o=s.apiVersion;if(o!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(o)}`);const a=s.activate({apiVersion:1,pluginId:i,html:l,svg:be}).contributions;for(const c of a.actions??[])this.actions.push(this.qualifyAction(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,c,t.machineId,t.sourcePluginId));for(const c of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,c,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const c of a.themes??[])this.themes.push(this.qualifyTheme(i,c));for(const c of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,c));this.gatewayPluginIds.add(i),r&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&r&&vm(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=wm(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const r=fm(t,s.pluginId),o=s.enabled?.(r),n=o===!1?s.disabledReason?.(r):void 0,a={id:s.id,pluginId:s.pluginId,localId:s.localId,...s.machineId===void 0?{}:{machineId:s.machineId},title:s.title,run:()=>s.run(r)};return s.description!==void 0&&(a.description=s.description),s.shortcut!==void 0&&(a.shortcut=s.shortcut),s.group!==void 0&&(a.group=s.group),o!==void 0&&(a.enabled=o),n!==void 0&&n!==""&&(a.disabledReason=n),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,r){const o=this.qualify(t,i.id);return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(t,i,s,r){const o=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,r)&&(a?.(Is(c,t))??!0),...n===void 0?{}:{badge:c=>this.isContributionActive(t,s,c.machine.id,r)?n(Is(c,t)):void 0},render:c=>i.render(Is(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,r){const o=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:o,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>this.isContributionActive(t,s,c.machine.id,r)&&(n?.(c)??!0),items:c=>this.isContributionActive(t,s,c.machine.id,r)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}isContributionActive(t,i,s,r){return i===void 0?!this.isGatewayPluginHiddenForMachine(t,s):i===s&&!this.isRemotePluginHiddenByGateway(r,i)}isRemoteDuplicateHiddenByGateway(t,i,s){return t!==void 0&&i!==void 0&&this.gatewayPluginIds.has(t)&&!this.gatewayMachineSpecificPluginIds.has(t)&&!s}isRemotePluginHiddenByGateway(t,i){return t===void 0||this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0?!1:this.gatewayPluginIds.has(t)}isGatewayPluginHiddenForMachine(t,i){return i!=="local"&&(this.gatewayMachineSpecificPluginIds.has(t)||this.remoteMachineSpecificPluginIds.get(t)?.has(i)===!0)}validatePluginId(t){if(!pm.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!hm.test(t))throw new Error(`Invalid contribution id: ${t}`)}parseMachineSpecific(t,i){if(i===void 0)return!1;if(typeof i!="boolean")throw new Error(`Invalid plugin machineSpecific value for ${t}: ${bm(i)}`);return i}}function fm(e,t){return kl.get(e)?.(t)??e}function Is(e,t){return $l.get(e)?.(t)??e}function gm(e,t){return kl.set(e,t),e}function mm(e,t){return $l.set(e,t),e}function vm(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function bm(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"||typeof e=="symbol"||typeof e=="function"||e===null||e===void 0)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function wm(e){return e.state.selectedMachine?.id??"local"}const ym=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function xm(){return typeof window>"u"||!("matchMedia"in window)?[]:ym.map(e=>window.matchMedia(e))}function Cn(e,t=Sm()){return e.some(i=>i.matches)||km(t)}function Sm(){return typeof navigator>"u"?void 0:navigator}function km(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const $m=250;class Pm{constructor(t=Cm()){this.scheduler=t}repair(t){if(!t){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},$m)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);const t=this.scheduler.documentElement;t!==void 0&&(t.scrollTop=0);const i=this.scheduler.body;i!==void 0&&(i.scrollTop=0)}}function Cm(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>"u"?void 0:document.documentElement},get body(){return typeof document>"u"?void 0:document.body}}}const Im="(max-width: 760px)",Rm="(max-width: 1180px)";class Am{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onStackedWorkspaceMediaChange=s=>{this.isStackedWorkspaceLayout!==s.matches&&(this.isStackedWorkspaceLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=Cn(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Tm(),this.stackedWorkspaceMedia=i.stackedWorkspaceMedia??Mm(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??xm(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Pm,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=Cn(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.addEventListener("change",this.onStackedWorkspaceMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.removeEventListener("change",this.onStackedWorkspaceMediaChange);for(const t of this.pwaDisplayModeMedia)t.removeEventListener("change",this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.normalizedMainView(void 0,!1)}normalizedMainView(t,i){return Em(t,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:i})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Tm(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Im)}function Mm(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Rm)}function Em(e,t){const i=e??(t.isMobileNavigationLayout?"navigation":"chat");return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||i==="navigation"||i==="chat"?i:"chat"}const Bi=["machines","projects","workspaces","sessions"];function Dm(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function Br(e,t){if(e!=="none")return e??Dm(t)}function Wm(e,t){return t.isMobileLayout?Br(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Om(e,t,i){return Br(e,i.state)===t?"none":t}function _m(e,t,i){return i?t:e}function Lm(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),zm(i)}function jm(e){return Bi[Bi.indexOf(e)+1]}class Fm{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return Br(this.expanded,this.getState())}isCollapsed(t){return Wm(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Om(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Lm(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(_m(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=jm(t);i!==void 0&&this.expand(i)}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}setCollapsedSections(t){Um(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function zm(e){const t=new Set(e);return Bi.filter(i=>t.has(i))}function Um(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class Bm{constructor(t){this.host=t,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,t.addController(this)}hostConnected(){}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(t){return["shell",Pl(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Pl(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const rr="pi-web:panel-sizes:v1",Nm={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Hm{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??Nr(),this.panelSizes=Gm(this.storage)}hostConnected(){}constraints(t){return ri(t)}panelWidth(t,i){return we(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const r=we(t,i);this.storedPanelWidth(t)!==r&&(this.panelSizes=Zm(this.panelSizes,t,r),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Xm(this.panelSizes,t),i.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(t={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){Jm(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${Rn(we("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${Rn(we("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function ri(e){return Nm[e]}function qm(e,t,i){return e==="navigation"?i-t:t-i}function Km(e,t,i,s,r=ri(e)){return we(e,t+qm(e,i,s),r)}function Vm(e,t,i,s={}){const r=s.constraints??ri(e);if(i==="Home")return r.minWidth;if(i==="End")return r.maxWidth;const o=s.largeStep===!0?r.largeKeyboardStep:r.keyboardStep,n=Ym(e,i,o);if(n!==void 0)return we(e,t+n,r)}function we(e,t,i=ri(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Gm(e=Nr()){try{const t=e?.getItem(rr);if(t==null||t==="")return{};const i=JSON.parse(t);return Qm(i)}catch{return{}}}function Jm(e,t=Nr()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(rr);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=we("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=we("workspace",e.workspacePanelWidth)),t.setItem(rr,JSON.stringify(i))}catch{}}function Qm(e){if(!ev(e)||e.version!==1)return{};const t={},i=In(e.navigationPanelWidth),s=In(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=we("navigation",i)),s!==void 0&&(t.workspacePanelWidth=we("workspace",s)),t}function In(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Zm(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Xm(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Ym(e,t,i){if(e==="navigation")return t==="ArrowRight"?i:t==="ArrowLeft"?-i:void 0;if(t==="ArrowLeft")return i;if(t==="ArrowRight")return-i}function Rn(e){return`${String(Math.round(e))}px`}function Nr(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ev(e){return typeof e=="object"&&e!==null}function An(){const e=new URLSearchParams(window.location.search);return{machineId:e.get("machine")??void 0,projectId:e.get("project")??void 0,workspaceId:e.get("workspace")??void 0,sessionId:e.get("session")??void 0,tool:tv(e.get("tool")),view:iv(e.get("view"))}}function Rs(e,t){const i=new URL(window.location.href);i.searchParams.delete("machine"),i.searchParams.delete("project"),i.searchParams.delete("workspace"),i.searchParams.delete("session"),i.searchParams.delete("tool"),i.searchParams.delete("view"),e.machineId!==void 0&&e.machineId!==""&&e.machineId!=="local"&&i.searchParams.set("machine",e.machineId),e.projectId!==void 0&&e.projectId!==""&&i.searchParams.set("project",e.projectId),e.workspaceId!==void 0&&e.workspaceId!==""&&i.searchParams.set("workspace",e.workspaceId),e.sessionId!==void 0&&e.sessionId!==""&&i.searchParams.set("session",e.sessionId),e.tool!==void 0&&i.searchParams.set("tool",e.tool),e.view!==void 0&&i.searchParams.set("view",e.view);const s=`${i.pathname}${i.search}${i.hash}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function tv(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Cl(e)?e:void 0}function iv(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Cl(e)?e:void 0}function Cl(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Tn(){return sv(new URLSearchParams(window.location.search).get("settings"))}function As(e,t){const i=new URL(window.location.href);e===void 0?i.searchParams.delete("settings"):i.searchParams.set("settings",e);const s=`${i.pathname}${i.search}${i.hash}`,r=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==r&&window.history.pushState({},"",i)}function sv(e){if(e==="general")return"general";if(e==="sessiond"||e==="sessions")return"sessiond";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function rv(e,t){return t===void 0?e:e.map(i=>nv(i,t))}function ov(e,t){const i=new Set(jr(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return rv(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?Il(s):s)}function nv(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?Il(e):{...e,shortcut:i}}function Il(e){const t={...e};return delete t.shortcut,t}function av(e,t){const i=t.api??$t,s=t.pollIntervalMs??1e3,r=t.setTimeout??cv(),o=t.clearTimeout??dv();return{async runCommand(n){const a=await i.runTerminalCommand(e,n);return n.open===!0&&t.openTerminal(n.workspace,{terminalId:a.terminalId}),{run:a,completed:lv(a,i,s,r,o)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function lv(e,t,i,s,r){return Mn(e)?Promise.resolve(e):new Promise((o,n)=>{let a,c=!1;const p=g=>{c||(c=!0,a!==void 0&&r(a),o(g))},u=g=>{c||(c=!0,a!==void 0&&r(a),n(g instanceof Error?g:new Error(String(g))))},h=()=>{t.getCommandRun(e.id).then(g=>{if(g!==void 0&&Mn(g)){p(g);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function Mn(e){return e.status==="succeeded"||e.status==="failed"}function cv(){return(e,t)=>globalThis.setTimeout(e,t)}function dv(){return e=>{globalThis.clearTimeout(e)}}function pv(e,t){return t[e.path]}function hv(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function uv(e,t,i){return Al(fv(e,t,i))}function Rl(e){return Al(Object.values(e??{}))}function Al(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function fv(e,t,i){const s=new Set(t.filter(o=>o.projectId===e.id).map(o=>o.path)),r=new Map;for(const o of s){const n=i[o];n!==void 0&&r.set(n.cwd,n)}for(const o of Object.values(i))(o.cwd===e.path||o.cwd.startsWith(`${e.path}/`))&&r.set(o.cwd,o);return[...r.values()]}function Tl(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function ss(e,t="活跃"){const i=Tl(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const pi=0,gv=120;function Ml(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?El():mv(e),r=window.innerWidth,o=window.innerHeight,n=Math.max(0,s.left),a=Math.min(r,s.right),c=Math.max(0,s.top),p=Math.min(o,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-pi,g=i.top-c-pi;return[...h<gv&&g>h?[`bottom: ${wt(o-i.top+pi)};`,`max-height: ${wt(Math.max(0,g))};`]:[`top: ${wt(i.bottom+pi)};`,`max-height: ${wt(Math.max(0,h))};`],`right: ${wt(Math.max(0,r-u))};`,`max-width: ${wt(Math.max(0,u-n))};`].join(" ")}function mv(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():El()}function El(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function wt(e){return`${String(Math.round(e))}px`}class rs{constructor(t){this.host=t,this.menuStyle="",this.onDocumentClick=i=>{i.composedPath().includes(this.host)||this.close()},t.addController(this)}hostConnected(){document.addEventListener("click",this.onDocumentClick)}hostDisconnected(){document.removeEventListener("click",this.onDocumentClick)}isOpen(t){return this.openId===t}toggle(t,i){if(this.openId===t){this.close();return}this.menuStyle=Ml(i,{constrainTo:"viewport"}),this.openId=t,this.host.requestUpdate()}close(){this.openId===void 0&&this.menuStyle===""||(this.openId=void 0,this.menuStyle="",this.host.requestUpdate())}closeIfOpenIdMissing(t){this.openId!==void 0&&!t(this.openId)&&this.close()}closeIf(t){t&&this.close()}closeForEscape(t,i){return t.key!=="Escape"||this.openId!==i?!1:(t.preventDefault(),t.stopPropagation(),this.close(),!0)}}const vv=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Dl(e){return e.composedPath().some(t=>bv(t,vv))}function bv(e,t){if(typeof Element<"u"&&e instanceof Element)return e.matches(t);if(!("matches"in e))return!1;const{matches:i}=e;return typeof i=="function"&&i.call(e,t)===!0}function os(e,t){Dl(e)||t()}function ns(e,t){return Dl(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?nt(e,()=>{En(e.currentTarget,-1)}):e.key==="ArrowDown"?nt(e,()=>{En(e.currentTarget,1)}):e.key==="Home"?nt(e,()=>{Dn(e.currentTarget,0)}):e.key==="End"?nt(e,()=>{Dn(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?nt(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?nt(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?nt(e,t.cancel):!1}function as(e,t={}){const i=e.querySelector(".action-row.selected")??e.querySelector(".action-row")??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return i==null?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}function nt(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function En(e,t){const i=Ol(e),s=_l(e);if(s===void 0||i.length===0)return;const r=i.indexOf(s);r<0||Wl(i,r+t)}function Dn(e,t){const i=Ol(e);i.length!==0&&Wl(i,t<0?i.length-1:t)}function Wl(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function Ol(e){const t=_l(e)?.getRootNode();return t===void 0||!wv(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function wv(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function _l(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const ls=D`
378
+ `}function zm(){co(()=>import("./UnifiedDiffViewer-D_OLq3Q4.js"),__vite__mapDeps([4,1,2]))}function Nm(){co(()=>import("./TerminalPanel-8Or6pbwb.js"),__vite__mapDeps([5,6,7,1,2]))}function qm(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 Hm(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}const Km={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!ec();return{contributions:{actions:e?zn():zn().filter(t=>t.id!=="view.terminal"),workspacePanels:e?Zn():Zn().filter(t=>t.id!=="workspace.terminal")}}}},Vm={"--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"},Gm={"--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"},Qm={"--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"},Jm={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:Gm},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Qm},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Vm}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},Zm=/^[a-z][a-z0-9.-]*$/u;function Xm(e){return Zm.test(e)}const Ym="machine.";function ev(e,t){if(e==="")throw new Error("Machine id is required");if(!Xm(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Ym}${tv(e)}.${t}`}function tv(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function Xn(e="/pi-web-plugins/manifest.json",t={}){const i=await iv(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=ov(n,o);s.push({id:t.machineId===void 0?r.id:ev(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 iv(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 sv(await t.json())}}function sv(e){if(!ls(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!ls(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:rv(t.machineSpecific)}})}}function rv(e){if(e===void 0)return!1;if(typeof e!="boolean")throw new Error("Invalid plugin manifest entry");return e}function ov(e,t){if(!ls(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!nv(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function nv(e){return ls(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function ls(e){return typeof e=="object"&&e!==null}const av=/^[a-z][a-z0-9.-]*$/u,lv=/^[a-z][a-z0-9.-]*$/u,nc=new WeakMap,ac=new WeakMap;class cv{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:$e}).contributions;for(const d of a.actions??[])this.actions.push(this.qualifyAction(i,d,t.machineId,t.sourcePluginId));for(const d of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,d,t.machineId,t.sourcePluginId));for(const d of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,d,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const d of a.themes??[])this.themes.push(this.qualifyTheme(i,d));for(const d of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,d));this.gatewayPluginIds.add(i),r&&this.gatewayMachineSpecificPluginIds.add(i)}else t.sourcePluginId!==void 0&&r&&uv(this.remoteMachineSpecificPluginIds,t.sourcePluginId,t.machineId)}shouldLoadRemotePlugin(t,i=!1){return!this.gatewayPluginIds.has(t)||this.gatewayMachineSpecificPluginIds.has(t)||i}getActions(t){const i=gv(t);return this.actions.filter(s=>this.isContributionActive(s.pluginId,s.machineId,i,s.sourcePluginId)).map(s=>{const r=dv(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:d=>this.isContributionActive(t,s,d.machine.id,r)&&(a?.(Zs(d,t))??!0),...n===void 0?{}:{badge:d=>this.isContributionActive(t,s,d.machine.id,r)?n(Zs(d,t)):void 0},render:d=>i.render(Zs(d,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:d=>this.isContributionActive(t,s,d.machine.id,r)&&(n?.(d)??!0),items:d=>this.isContributionActive(t,s,d.machine.id,r)?a(d):[]}}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(!av.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!lv.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}: ${fv(i)}`);return i}}function dv(e,t){return nc.get(e)?.(t)??e}function Zs(e,t){return ac.get(e)?.(t)??e}function pv(e,t){return nc.set(e,t),e}function hv(e,t){return ac.set(e,t),e}function uv(e,t,i){const s=e.get(t);s===void 0?e.set(t,new Set([i])):s.add(i)}function fv(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 gv(e){return e.state.selectedMachine?.id??"local"}const mv=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function vv(){return typeof window>"u"||!("matchMedia"in window)?[]:mv.map(e=>window.matchMedia(e))}function Yn(e,t=bv()){return e.some(i=>i.matches)||wv(t)}function bv(){return typeof navigator>"u"?void 0:navigator}function wv(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const yv=250;class Sv{constructor(t=xv()){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()},yv)}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 xv(){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 kv="(max-width: 760px)",$v="(max-width: 1180px)";class Pv{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=Yn(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Cv(),this.stackedWorkspaceMedia=i.stackedWorkspaceMedia??Rv(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??vv(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Sv,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=Yn(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 Iv(t,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:i})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Cv(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(kv)}function Rv(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia($v)}function Iv(e,t){const i=e??(t.isMobileNavigationLayout?"navigation":"chat");return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||i==="navigation"||i==="chat"?i:"chat"}const cs=["machines","projects","workspaces","sessions"];function Av(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function po(e,t){if(e!=="none")return e??Av(t)}function Mv(e,t){return t.isMobileLayout?po(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Tv(e,t,i){return po(e,i.state)===t?"none":t}function Ev(e,t,i){return i?t:e}function Dv(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Ov(i)}function Wv(e){return cs[cs.indexOf(e)+1]}class Lv{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return po(this.expanded,this.getState())}isCollapsed(t){return Mv(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(Tv(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Dv(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(Ev(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=Wv(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){Fv(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Ov(e){const t=new Set(e);return cs.filter(i=>t.has(i))}function Fv(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class _v{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",lc(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function lc(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const Cr="pi-web:panel-sizes:v1",jv={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Uv{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??ho(),this.panelSizes=qv(this.storage)}hostConnected(){}constraints(t){return Si(t)}panelWidth(t,i){return Ce(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const r=Ce(t,i);this.storedPanelWidth(t)!==r&&(this.panelSizes=Vv(this.panelSizes,t,r),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Gv(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(){Hv(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${ta(Ce("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${ta(Ce("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Si(e){return jv[e]}function Bv(e,t,i){return e==="navigation"?i-t:t-i}function zv(e,t,i,s,r=Si(e)){return Ce(e,t+Bv(e,i,s),r)}function Nv(e,t,i,s={}){const r=s.constraints??Si(e);if(i==="Home")return r.minWidth;if(i==="End")return r.maxWidth;const o=s.largeStep===!0?r.largeKeyboardStep:r.keyboardStep,n=Qv(e,i,o);if(n!==void 0)return Ce(e,t+n,r)}function Ce(e,t,i=Si(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function qv(e=ho()){try{const t=e?.getItem(Cr);if(t==null||t==="")return{};const i=JSON.parse(t);return Kv(i)}catch{return{}}}function Hv(e,t=ho()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Cr);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=Ce("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=Ce("workspace",e.workspacePanelWidth)),t.setItem(Cr,JSON.stringify(i))}catch{}}function Kv(e){if(!Jv(e)||e.version!==1)return{};const t={},i=ea(e.navigationPanelWidth),s=ea(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=Ce("navigation",i)),s!==void 0&&(t.workspacePanelWidth=Ce("workspace",s)),t}function ea(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Vv(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Gv(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Qv(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 ta(e){return`${String(Math.round(e))}px`}function ho(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Jv(e){return typeof e=="object"&&e!==null}function ia(){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:Zv(e.get("tool")),view:Xv(e.get("view"))}}function Xs(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 Zv(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":cc(e)?e:void 0}function Xv(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":cc(e)?e:void 0}function cc(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function sa(){return Yv(new URLSearchParams(window.location.search).get("settings"))}function Ys(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 Yv(e){if(e==="general")return"general";if(e==="sessiond"||e==="sessions")return"sessiond";if(e==="packages"||e==="pi-packages")return"packages";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function eb(e,t){return t===void 0?e:e.map(i=>ib(i,t))}function tb(e,t){const i=new Set(no(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return eb(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?dc(s):s)}function ib(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?dc(e):{...e,shortcut:i}}function dc(e){const t={...e};return delete t.shortcut,t}function sb(e,t){const i=t.api??Ot,s=t.pollIntervalMs??1e3,r=t.setTimeout??ob(),o=t.clearTimeout??nb();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:rb(a,i,s,r,o)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function rb(e,t,i,s,r){return ra(e)?Promise.resolve(e):new Promise((o,n)=>{let a,d=!1;const p=g=>{d||(d=!0,a!==void 0&&r(a),o(g))},u=g=>{d||(d=!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&&ra(g)){p(g);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function ra(e){return e.status==="succeeded"||e.status==="failed"}function ob(){return(e,t)=>globalThis.setTimeout(e,t)}function nb(){return e=>{globalThis.clearTimeout(e)}}function ab(e,t){return t[e.path]}function lb(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function cb(e,t,i){return hc(db(e,t,i))}function pc(e){return hc(Object.values(e??{}))}function hc(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function db(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 uc(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Cs(e,t="活跃"){const i=uc(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const Ai=0,pb=120;function fc(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?gc():hb(e),r=window.innerWidth,o=window.innerHeight,n=Math.max(0,s.left),a=Math.min(r,s.right),d=Math.max(0,s.top),p=Math.min(o,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Ai,g=i.top-d-Ai;return[...h<pb&&g>h?[`bottom: ${Mt(o-i.top+Ai)};`,`max-height: ${Mt(Math.max(0,g))};`]:[`top: ${Mt(i.bottom+Ai)};`,`max-height: ${Mt(Math.max(0,h))};`],`right: ${Mt(Math.max(0,r-u))};`,`max-width: ${Mt(Math.max(0,u-n))};`].join(" ")}function hb(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():gc()}function gc(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function Mt(e){return`${String(Math.round(e))}px`}class Rs{constructor(t){this.host=t,this.menuStyle="",this.onDocumentClick=i=>{i.composedPath().includes(this.host)||this.close()},t.addController(this)}hostConnected(){document.addEventListener("click",this.onDocumentClick)}hostDisconnected(){document.removeEventListener("click",this.onDocumentClick)}isOpen(t){return this.openId===t}toggle(t,i){if(this.openId===t){this.close();return}this.menuStyle=fc(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 ub=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function mc(e){return e.composedPath().some(t=>fb(t,ub))}function fb(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 Is(e,t){mc(e)||t()}function As(e,t){return mc(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?mt(e,()=>{oa(e.currentTarget,-1)}):e.key==="ArrowDown"?mt(e,()=>{oa(e.currentTarget,1)}):e.key==="Home"?mt(e,()=>{na(e.currentTarget,0)}):e.key==="End"?mt(e,()=>{na(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?mt(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?mt(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?mt(e,t.cancel):!1}function Ms(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 mt(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function oa(e,t){const i=bc(e),s=wc(e);if(s===void 0||i.length===0)return;const r=i.indexOf(s);r<0||vc(i,r+t)}function na(e,t){const i=bc(e);i.length!==0&&vc(i,t<0?i.length-1:t)}function vc(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function bc(e){const t=wc(e)?.getRootNode();return t===void 0||!gb(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function gb(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function wc(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const Ts=D`
377
379
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
378
380
  :host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
379
381
  section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
@@ -434,7 +436,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
434
436
  .workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
435
437
  .workspace-detail-row .workspace-label-base, .workspace-detail-row .workspace-label-item, .workspace-detail-row .workspace-label-render { overflow: visible; text-overflow: clip; overflow-wrap: anywhere; white-space: normal; }
436
438
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
437
- `;var yv=Object.defineProperty,xv=Object.getOwnPropertyDescriptor,Pe=(e,t,i,s)=>{for(var r=s>1?void 0:s?xv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&yv(t,i,r),r};let le=class extends R{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menu=new rs(this)}updated(e){e.has("machines")&&this.menu.closeIfOpenIdMissing(t=>this.machines.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,as(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
439
+ `;var mb=Object.defineProperty,vb=Object.getOwnPropertyDescriptor,Ee=(e,t,i,s)=>{for(var r=s>1?void 0:s?vb(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&mb(t,i,r),r};let ue=class extends I{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menu=new Rs(this)}updated(e){e.has("machines")&&this.menu.closeIfOpenIdMissing(t=>this.machines.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,Ms(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
438
440
  <section>
439
441
  <h2>${this.renderHeading()}</h2>
440
442
  ${this.collapsed?null:l`
@@ -443,12 +445,12 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
443
445
  </div>
444
446
  `}
445
447
  </section>
446
- `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=Ll(e)&&this.onRemove!==void 0;return l`
448
+ `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=yc(e)&&this.onRemove!==void 0;return l`
447
449
  <div
448
450
  class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
449
451
  tabindex="0"
450
452
  title=${e.baseUrl??e.name}
451
- @click=${r=>{os(r,()=>this.onSelect?.(e))}}
453
+ @click=${r=>{Is(r,()=>this.onSelect?.(e))}}
452
454
  @keydown=${r=>{this.handleMachineKeydown(r,e)}}
453
455
  >
454
456
  <div class="action-main">
@@ -456,7 +458,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
456
458
  </div>
457
459
  ${s?this.renderMachineMenu(e):null}
458
460
  </div>
459
- `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=Rl(this.activities[e.id]);return ss(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.menu.isOpen(e.id),i=Sv(e.id);return l`
461
+ `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=pc(this.activities[e.id]);return Cs(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.menu.isOpen(e.id),i=bb(e.id);return l`
460
462
  <div class="action-menu">
461
463
  <button
462
464
  class="action-menu-toggle"
@@ -472,13 +474,13 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
472
474
  </div>
473
475
  `:null}
474
476
  </div>
475
- `}renderHeading(){if(!this.collapsible)return"机器";const e=this.selected?.name??"未选择机器",t=this.selected?.baseUrl??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 机器</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}removeMachine(e){this.menu.close(),this.onRemove?.(e)}handleMachineKeydown(e,t){this.menu.closeForEscape(e,t.id)||ns(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};le.styles=[ls,D`
477
+ `}renderHeading(){if(!this.collapsible)return"机器";const e=this.selected?.name??"未选择机器",t=this.selected?.baseUrl??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 机器</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}removeMachine(e){this.menu.close(),this.onRemove?.(e)}handleMachineKeydown(e,t){this.menu.closeForEscape(e,t.id)||As(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};ue.styles=[Ts,D`
476
478
  .machine-row.no-actions .action-main { border-radius: 8px; }
477
479
  .machine-primary { display: flex; align-items: baseline; gap: 6px; }
478
480
  .machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
479
481
  .machine-menu-panel button.danger { color: var(--pi-danger); }
480
482
  .machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
481
- `];Pe([d({attribute:!1})],le.prototype,"machines",2);Pe([d({attribute:!1})],le.prototype,"selected",2);Pe([d({attribute:!1})],le.prototype,"statuses",2);Pe([d({attribute:!1})],le.prototype,"activities",2);Pe([d({type:Boolean,reflect:!0})],le.prototype,"collapsible",2);Pe([d({type:Boolean,reflect:!0})],le.prototype,"collapsed",2);Pe([d({attribute:!1})],le.prototype,"onSelect",2);Pe([d({attribute:!1})],le.prototype,"onRemove",2);Pe([d({attribute:!1})],le.prototype,"onToggleCollapsed",2);Pe([d({attribute:!1})],le.prototype,"onFocusNextSection",2);Pe([d({attribute:!1})],le.prototype,"onCancelKeyboardNavigation",2);le=Pe([W("machine-list")],le);function Ll(e){return e.kind==="remote"}function Sv(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var kv=Object.defineProperty,$v=Object.getOwnPropertyDescriptor,ge=(e,t,i,s)=>{for(var r=s>1?void 0:s?$v(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&kv(t,i,r),r};let se=class extends R{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menu=new rs(this)}updated(e){e.has("projects")&&this.menu.closeIfOpenIdMissing(t=>this.projects.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,as(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
483
+ `];Ee([c({attribute:!1})],ue.prototype,"machines",2);Ee([c({attribute:!1})],ue.prototype,"selected",2);Ee([c({attribute:!1})],ue.prototype,"statuses",2);Ee([c({attribute:!1})],ue.prototype,"activities",2);Ee([c({type:Boolean,reflect:!0})],ue.prototype,"collapsible",2);Ee([c({type:Boolean,reflect:!0})],ue.prototype,"collapsed",2);Ee([c({attribute:!1})],ue.prototype,"onSelect",2);Ee([c({attribute:!1})],ue.prototype,"onRemove",2);Ee([c({attribute:!1})],ue.prototype,"onToggleCollapsed",2);Ee([c({attribute:!1})],ue.prototype,"onFocusNextSection",2);Ee([c({attribute:!1})],ue.prototype,"onCancelKeyboardNavigation",2);ue=Ee([W("machine-list")],ue);function yc(e){return e.kind==="remote"}function bb(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var wb=Object.defineProperty,yb=Object.getOwnPropertyDescriptor,Se=(e,t,i,s)=>{for(var r=s>1?void 0:s?yb(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&&wb(t,i,r),r};let le=class extends I{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menu=new Rs(this)}updated(e){e.has("projects")&&this.menu.closeIfOpenIdMissing(t=>this.projects.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,Ms(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
482
484
  <section>
483
485
  <h2>${this.renderHeading()}</h2>
484
486
  ${this.collapsed?null:l`
@@ -493,7 +495,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
493
495
  class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
494
496
  tabindex="0"
495
497
  title=${e.path}
496
- @click=${t=>{os(t,()=>this.onSelect?.(e))}}
498
+ @click=${t=>{Is(t,()=>this.onSelect?.(e))}}
497
499
  @keydown=${t=>{this.handleProjectKeydown(t,e)}}
498
500
  >
499
501
  <div class="action-main">
@@ -513,19 +515,19 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
513
515
  </div>
514
516
  `}
515
517
  </section>
516
- `}handleProjectKeydown(e,t){ns(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return"项目";const e=this.selected?.name??"未选择项目",t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 项目</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=uv(e,this.workspacesByProjectId[e.id]??[],this.activities);return ss(t,t==="terminal"?"项目终端活跃":"项目活跃")}close(e){this.menu.close(),confirm(`关闭 ${e.name}?
518
+ `}handleProjectKeydown(e,t){As(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=cb(e,this.workspacesByProjectId[e.id]??[],this.activities);return Cs(t,t==="terminal"?"项目终端活跃":"项目活跃")}close(e){this.menu.close(),confirm(`关闭 ${e.name}?
517
519
 
518
- 这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};se.styles=ls;ge([d({attribute:!1})],se.prototype,"projects",2);ge([d({attribute:!1})],se.prototype,"selected",2);ge([d({attribute:!1})],se.prototype,"activities",2);ge([d({attribute:!1})],se.prototype,"workspacesByProjectId",2);ge([d({type:Boolean,reflect:!0})],se.prototype,"collapsible",2);ge([d({type:Boolean,reflect:!0})],se.prototype,"collapsed",2);ge([d({attribute:!1})],se.prototype,"onSelect",2);ge([d({attribute:!1})],se.prototype,"onClose",2);ge([d({attribute:!1})],se.prototype,"onToggleCollapsed",2);ge([d({attribute:!1})],se.prototype,"onFocusPreviousSection",2);ge([d({attribute:!1})],se.prototype,"onFocusNextSection",2);ge([d({attribute:!1})],se.prototype,"onCancelKeyboardNavigation",2);se=ge([W("project-list")],se);function Wn(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Pv(t)}`)}function Pv(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&Cv(e.href)){const t=e.target??"_blank",i=t==="_blank"?"noopener noreferrer":void 0;return l`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${i??void 0}>${e.text}</a>`}return l`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function Cv(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var Iv=Object.defineProperty,Rv=Object.getOwnPropertyDescriptor,he=(e,t,i,s)=>{for(var r=s>1?void 0:s?Rv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Iv(t,i,r),r};let te=class extends R{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menu=new rs(this)}updated(e){e.has("workspaces")&&this.menu.closeIfOpenIdMissing(t=>this.workspaces.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,as(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
520
+ 这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};le.styles=Ts;Se([c({attribute:!1})],le.prototype,"projects",2);Se([c({attribute:!1})],le.prototype,"selected",2);Se([c({attribute:!1})],le.prototype,"activities",2);Se([c({attribute:!1})],le.prototype,"workspacesByProjectId",2);Se([c({type:Boolean,reflect:!0})],le.prototype,"collapsible",2);Se([c({type:Boolean,reflect:!0})],le.prototype,"collapsed",2);Se([c({attribute:!1})],le.prototype,"onSelect",2);Se([c({attribute:!1})],le.prototype,"onClose",2);Se([c({attribute:!1})],le.prototype,"onToggleCollapsed",2);Se([c({attribute:!1})],le.prototype,"onFocusPreviousSection",2);Se([c({attribute:!1})],le.prototype,"onFocusNextSection",2);Se([c({attribute:!1})],le.prototype,"onCancelKeyboardNavigation",2);le=Se([W("project-list")],le);function aa(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Sb(t)}`)}function Sb(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&xb(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 xb(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var kb=Object.defineProperty,$b=Object.getOwnPropertyDescriptor,me=(e,t,i,s)=>{for(var r=s>1?void 0:s?$b(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&kb(t,i,r),r};let oe=class extends I{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menu=new Rs(this)}updated(e){e.has("workspaces")&&this.menu.closeIfOpenIdMissing(t=>this.workspaces.some(i=>i.id===t)),e.has("collapsed")&&this.menu.closeIf(this.collapsed),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Ms(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
519
521
  <section>
520
522
  <h2>${this.renderHeading()}</h2>
521
523
  ${this.collapsed?null:l`
522
524
  <div class="list-body">
523
- ${this.workspaces.map(e=>{const t=Av(e),i=this.workspaceLabelItems(e);return l`
525
+ ${this.workspaces.map(e=>{const t=Pb(e),i=this.workspaceLabelItems(e);return l`
524
526
  <div
525
527
  class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
526
528
  tabindex="0"
527
529
  title=${t}
528
- @click=${s=>{os(s,()=>this.onSelect?.(e))}}
530
+ @click=${s=>{Is(s,()=>this.onSelect?.(e))}}
529
531
  @keydown=${s=>{this.handleWorkspaceKeydown(s,e)}}
530
532
  >
531
533
  <div class="action-main">
@@ -537,18 +539,18 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
537
539
  </div>
538
540
  `}
539
541
  </section>
540
- `}renderHeading(){if(!this.collapsible)return"工作区";const e=this.selected===void 0?"未选择工作区":`${this.selected.label}${this.selected.isMain?" · 主工作区":""} · ${this.selected.path}`,t=this.selected?.path??e;return l`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 工作区</span>${this.collapsed?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=hv(pv(e,this.activities));return ss(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return l`
542
+ `}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=lb(ab(e,this.activities));return Cs(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return l`
541
543
  <span class="workspace-primary">
542
544
  <span class="workspace-primary-label">${e}</span>
543
545
  ${this.isDeleting(i)?l`<span class="workspace-status">正在删除…</span>`:null}
544
546
  </span>
545
547
  ${t.length===0?null:l`
546
548
  <small class="workspace-secondary">
547
- <span class="workspace-label">${Wn(t)}</span>
549
+ <span class="workspace-label">${aa(t)}</span>
548
550
  </small>
549
551
  `}
550
552
  ${this.renderActivity(i)}
551
- `}renderWorkspaceMenu(e,t,i){const s=this.menu.isOpen(i.id),r=Mv(i.id);return l`
553
+ `}renderWorkspaceMenu(e,t,i){const s=this.menu.isOpen(i.id),r=Rb(i.id);return l`
552
554
  <div class="action-menu">
553
555
  <button
554
556
  class="action-menu-toggle"
@@ -565,7 +567,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
565
567
  </div>
566
568
  `:null}
567
569
  </div>
568
- `}renderWorkspaceActions(e){if(!Tv(e))return;const t=this.isDeleting(e);return l`
570
+ `}renderWorkspaceActions(e){if(!Cb(e))return;const t=this.isDeleting(e);return l`
569
571
  <div class="workspace-menu-actions">
570
572
  <button class="danger" title=${t?"正在删除工作区":"删除工作区"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"正在删除…":"删除工作区"}</button>
571
573
  </div>
@@ -582,16 +584,17 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
582
584
  ${t.length===0?null:l`
583
585
  <div class="workspace-detail-row">
584
586
  <dt>详情</dt>
585
- <dd><span class="workspace-label">${Wn(t)}</span></dd>
587
+ <dd><span class="workspace-label">${aa(t)}</span></dd>
586
588
  </div>
587
589
  `}
588
590
  </dl>
589
- `}delete(e){this.isDeleting(e)||(this.menu.close(),this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}handleWorkspaceKeydown(e,t){this.menu.closeForEscape(e,t.id)||ns(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};te.styles=ls;he([d({attribute:!1})],te.prototype,"workspaces",2);he([d({attribute:!1})],te.prototype,"selected",2);he([d({type:Boolean,reflect:!0})],te.prototype,"collapsible",2);he([d({type:Boolean,reflect:!0})],te.prototype,"collapsed",2);he([d({attribute:!1})],te.prototype,"workspaceLabelItems",2);he([d({attribute:!1})],te.prototype,"activities",2);he([d({attribute:!1})],te.prototype,"deletingWorkspaceIds",2);he([d({attribute:!1})],te.prototype,"onSelect",2);he([d({attribute:!1})],te.prototype,"onDelete",2);he([d({attribute:!1})],te.prototype,"onToggleCollapsed",2);he([d({attribute:!1})],te.prototype,"onFocusPreviousSection",2);he([d({attribute:!1})],te.prototype,"onFocusNextSection",2);he([d({attribute:!1})],te.prototype,"onCancelKeyboardNavigation",2);te=he([W("workspace-list")],te);function Av(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function Tv(e){return e.isGitWorktree&&!e.isMain}function Mv(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Ev=Object.defineProperty,Dv=Object.getOwnPropertyDescriptor,M=(e,t,i,s)=>{for(var r=s>1?void 0:s?Dv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ev(t,i,r),r};function Ft(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let A=class extends R{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.cleanupUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。",this.collapsible=!1,this.collapsed=!1,this.menu=new rs(this),this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set}updated(e){e.has("sessions")&&(this.menu.closeIfOpenIdMissing(i=>this.sessions.some(s=>s.id===i)),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.menu.closeIf(this.collapsed);const t=e.get("selected");if(e.has("selected")&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(e.has("selected")||e.has("sessions")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,as(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=_v(this.sessions),t=new Set(e.map(o=>o.session.id)),i=e.map(o=>o.session).filter(o=>zt(o)==="current"),s=jl(this.sessions.filter(o=>o.archived===!0&&!t.has(o.id))),r=Wv(this.sessions);return l`
591
+ `}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)||As(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"})}};oe.styles=Ts;me([c({attribute:!1})],oe.prototype,"workspaces",2);me([c({attribute:!1})],oe.prototype,"selected",2);me([c({type:Boolean,reflect:!0})],oe.prototype,"collapsible",2);me([c({type:Boolean,reflect:!0})],oe.prototype,"collapsed",2);me([c({attribute:!1})],oe.prototype,"workspaceLabelItems",2);me([c({attribute:!1})],oe.prototype,"activities",2);me([c({attribute:!1})],oe.prototype,"deletingWorkspaceIds",2);me([c({attribute:!1})],oe.prototype,"onSelect",2);me([c({attribute:!1})],oe.prototype,"onDelete",2);me([c({attribute:!1})],oe.prototype,"onToggleCollapsed",2);me([c({attribute:!1})],oe.prototype,"onFocusPreviousSection",2);me([c({attribute:!1})],oe.prototype,"onFocusNextSection",2);me([c({attribute:!1})],oe.prototype,"onCancelKeyboardNavigation",2);oe=me([W("workspace-list")],oe);function Pb(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function Cb(e){return e.isGitWorktree&&!e.isMain}function Rb(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}function Sc(e){return e.slice(-8)}var Ib=Object.defineProperty,Ab=Object.getOwnPropertyDescriptor,M=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ab(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ib(t,i,r),r};function Zt(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:Sc(e.id)}let A=class extends I{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.startingCount=0,this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.cleanupUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。",this.collapsible=!1,this.collapsed=!1,this.menu=new Rs(this),this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set}updated(e){e.has("sessions")&&(this.menu.closeIfOpenIdMissing(i=>this.sessions.some(s=>s.id===i)),this.sessions.some(i=>i.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has("collapsed")&&this.menu.closeIf(this.collapsed);const t=e.get("selected");if(e.has("selected")&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(e.has("selected")||e.has("sessions")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Ms(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=Eb(this.sessions),t=new Set(e.map(o=>o.session.id)),i=e.map(o=>o.session).filter(o=>Xt(o)==="current"),s=xc(this.sessions.filter(o=>o.archived===!0&&!t.has(o.id))),r=Mb(this.sessions);return l`
590
592
  <section>
591
593
  ${this.renderHeading(e.length+s.length,i)}
592
594
  ${this.collapsed?null:l`
593
595
  <div class="list-body">
594
596
  ${this.renderCurrentSelectionToolbar(i)}
597
+ ${this.startingCount>0?this.renderStartingSession():null}
595
598
  ${e.map(o=>this.renderSession(o,r.get(o.session.id)??0,"current"))}
596
599
  ${s.length>0?l`
597
600
  ${this.renderArchivedHeading(s.map(o=>o.session))}
@@ -608,23 +611,30 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
608
611
  会话
609
612
  ${this.renderCurrentSelectionButton(t)}
610
613
  ${this.renderCleanupButton()}
611
- <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button>
614
+ ${this.renderStartButton()}
612
615
  </h2>
613
- `;const i=this.selected===void 0?"未选择会话":Ft(this.selected),s=this.selected?.path??i;return l`
616
+ `;const i=this.selected===void 0?"未选择会话":Zt(this.selected),s=this.selected?.path??i;return l`
614
617
  <h2>
615
618
  <button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?"▸":"▾"} 会话</span>${this.collapsed?l`<small class="section-selected" dir="auto" title=${s}>${i}</small>`:null}</span></button>
616
619
  ${this.renderCurrentSelectionButton(t)}
617
620
  <small class="section-count">${e}</small>
618
621
  ${this.renderCleanupButton()}
619
- <button ?disabled=${!this.canStart} @click=${r=>{r.stopPropagation(),this.onStart?.()}}>+</button>
622
+ ${this.renderStartButton()}
620
623
  </h2>
621
- `}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`
624
+ `}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>`}renderStartButton(){const e=this.startingCount>0?"Start another session":"Start a new session";return l`<button class="start-session-button" title=${e} aria-label=${e} ?disabled=${!this.canStart} @click=${t=>{t.stopPropagation(),this.onStart?.()}}>+</button>`}renderStartingSession(){const e=this.startingCount!==1;return l`
625
+ <div class="pending-session-row starting-session" role="status" aria-live="polite">
626
+ <div class="action-main">
627
+ <span class="action-name"><span class="activity-indicator sending" aria-hidden="true"></span>${e?`Starting ${String(this.startingCount)} sessions…`:"Starting session…"}</span>
628
+ <small>Waiting for ${e?"new sessions":"the new session"} to be created</small>
629
+ </div>
630
+ </div>
631
+ `}renderArchivedHeading(e){const t=this.selectionScopes.has("archived");return l`
622
632
  <h2 class="subheading">
623
633
  <button class="section-toggle" aria-expanded=${String(this.archivedExpanded)} @click=${()=>{this.toggleArchived()}}><span>${this.archivedExpanded?"▾":"▸"} 已归档</span></button>
624
634
  ${this.archivedExpanded?l`<button class="bulk-select-entry ${t?"selected":""}" title=${t?"关闭已归档会话选择":"选择已归档会话"} aria-label=${t?"关闭已归档会话选择":"选择已归档会话"} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${()=>{this.toggleSelection("archived",e)}}>☑</button>`:null}
625
635
  <small class="section-count">${e.length}</small>
626
636
  </h2>
627
- `}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("current"))return null;const t=this.selectedSessions("current"),i=t.filter(o=>!Y(o)),s=e.length>0&&e.every(o=>this.selectedSessionIds.has(o.id)),r=e.filter(o=>this.selectedSessionIds.has(o.id)).length;return l`
637
+ `}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has("current"))return null;const t=this.selectedSessions("current"),i=t.filter(o=>He(o,this.statuses[o.id],this.sessionPersistenceOptions())),s=e.length>0&&e.every(o=>this.selectedSessionIds.has(o.id)),r=e.filter(o=>this.selectedSessionIds.has(o.id)).length;return l`
628
638
  <div class="bulk-row selecting">
629
639
  <button ?disabled=${e.length===0} @click=${()=>{this.toggleVisibleSelection(e,!s)}}>${s?"清除可见":"选择可见"}</button>
630
640
  <small>${t.length} 已选${r!==t.length?l` · ${r} 可见`:null}</small>
@@ -641,41 +651,44 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
641
651
  <button @click=${()=>{this.closeSelection("archived")}}>完成</button>
642
652
  ${this.canDeleteArchived?null:l`<small class="capability-hint">${this.archivedDeleteUnavailableMessage}</small>`}
643
653
  </div>
644
- `}renderSession(e,t,i){const{session:s}=e,r=Math.min(e.depth,2),o=zt(s)===i,n=this.selectionScopes.has(i),a=n&&o,c=a&&this.selectedSessionIds.has(s.id);return l`
654
+ `}renderSession(e,t,i){const{session:s}=e,r=Math.min(e.depth,2),o=Xt(s)===i,n=this.selectionScopes.has(i),a=n&&o,d=a&&this.selectedSessionIds.has(s.id),p=this.statuses[s.id],u=this.activities[s.id],h=this.sessionPersistenceOptions(),g=He(s,p,h),S=fi(s,p,h),P=g&&this.canReload;return l`
645
655
  <div
646
- class="action-row ${this.selected?.id===s.id?"selected":""} ${c?"bulk-selected":""} ${s.archived===!0?"archived":""} ${n?"selecting":""}"
656
+ class="action-row ${this.selected?.id===s.id?"selected":""} ${d?"bulk-selected":""} ${s.archived===!0?"archived":""} ${n?"selecting":""}"
647
657
  style=${`--depth:${String(r)}`}
648
658
  tabindex="0"
649
659
  title=${s.path}
650
- @click=${p=>{os(p,()=>{this.activateSessionRow(s,i)})}}
651
- @keydown=${p=>{this.handleSessionKeydown(p,s,i)}}
660
+ @click=${C=>{Is(C,()=>{this.activateSessionRow(s,i)})}}
661
+ @keydown=${C=>{this.handleSessionKeydown(C,s,i)}}
652
662
  >
653
663
  <div class="action-main ${n?"selecting":""}">
654
- ${a?l`<input class="session-checkbox" type="checkbox" aria-label=${`选择 ${Ft(s)}`} .checked=${c} @click=${p=>{p.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
655
- <span class="action-name" dir="auto">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${Ft(s)}${e.depth>2?l` <span class="badge">深度 ${e.depth}</span>`:null}${e.hasMissingParent?l` <span class="badge">父会话不可用</span>`:null}</span><small>${this.renderSessionMetaPrefix(s)}${String(s.messageCount)} 条消息</small>
664
+ ${a?l`<input class="session-checkbox" type="checkbox" aria-label=${`选择 ${Zt(s)}`} .checked=${d} @click=${C=>{C.stopPropagation()}} @change=${()=>{this.toggleSelected(s.id)}}>`:null}
665
+ <span class="action-name" dir="auto">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${Zt(s)}${e.depth>2?l` <span class="badge">深度 ${e.depth}</span>`:null}${e.hasMissingParent?l` <span class="badge">父会话不可用</span>`:null}</span><small>${this.renderSessionMetaPrefix(s,p,u)}${String(s.messageCount)} 条消息</small>
656
666
  ${this.renderActivity(s)}
657
667
  </div>
658
668
  <div class="action-menu">
659
- <button class="action-menu-toggle" title="会话操作" @click=${p=>{p.stopPropagation(),this.menu.toggle(s.id,p.currentTarget)}}>⋯</button>
669
+ <button class="action-menu-toggle" title="会话操作" @click=${C=>{C.stopPropagation(),this.menu.toggle(s.id,C.currentTarget)}}>⋯</button>
660
670
  ${this.menu.isOpen(s.id)?l`
661
671
  <div class="action-menu-panel" style=${this.menu.menuStyle}>
662
- ${Y(s)?l`<button title="删除浏览器缓存的新会话" @click=${()=>{this.menu.close(),this.onDelete?.(s)}}>删除</button>`:s.archived===!0?l`
672
+ ${s.archived===!0?l`
663
673
  <button title="恢复会话" @click=${()=>{this.menu.close(),this.onRestore?.(s)}}>恢复</button>
664
674
  <button class="danger" title=${this.canDeleteArchived?"永久删除已归档会话":this.archivedDeleteUnavailableMessage} ?disabled=${!this.canDeleteArchived} @click=${()=>{this.menu.close(),this.confirmDeleteArchived(s)}}>删除已归档会话</button>
665
- `:l`
666
- ${this.canReload?l`<button title=${tt(this.statuses[s.id],this.activities[s.id])?"当前会话活动结束后才能重新加载":"从磁盘重新加载会话"} ?disabled=${tt(this.statuses[s.id],this.activities[s.id])} @click=${()=>{this.menu.close(),this.onReload?.(s)}}>重新加载</button>`:null}
675
+ `:S?l`<button title="删除临时新会话" @click=${()=>{this.menu.close(),this.onDelete?.(s)}}>删除</button>`:l`
676
+ ${g?l`
677
+ <button title="归档会话" @click=${()=>{this.menu.close(),this.onArchive?.(s)}}>归档</button>
678
+ ${t>0?l`<button title="归档此会话及其后代会话" @click=${()=>{this.menu.close(),this.confirmArchiveWithDescendants(s,t)}}>连同后代归档(${t})</button>`:null}
679
+ `:null}
667
680
  ${s.parentSessionPath!==void 0?l`<button title="从父会话分离" @click=${()=>{this.menu.close(),this.onDetachParent?.(s)}}>从父会话分离</button>`:null}
668
- <button title="归档会话" @click=${()=>{this.menu.close(),this.onArchive?.(s)}}>归档</button>
669
- ${t>0?l`<button title="归档此会话及其后代会话" @click=${()=>{this.menu.close(),this.confirmArchiveWithDescendants(s,t)}}>连同后代归档(${t})</button>`:null}
681
+ ${P?l`<button title=${dt(this.statuses[s.id],this.activities[s.id])?"当前会话活动结束后才能从磁盘重新加载":"从磁盘重新加载会话,不刷新 Pi 运行时资源"} ?disabled=${dt(this.statuses[s.id],this.activities[s.id])} @click=${()=>{this.menu.close(),this.onReload?.(s)}}>从磁盘重新加载</button>`:null}
670
682
  `}
671
683
  </div>
672
684
  `:null}
673
685
  </div>
674
686
  </div>
675
- `}handleSessionKeydown(e,t,i){ns(e,{activate:()=>{this.activateSessionRow(t,i)},previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}activateSessionRow(e,t){if(this.selectionScopes.has(t)&&zt(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){confirm(`归档“${Ft(e)}”及其 ${String(t)} 个后代会话?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`永久删除已归档会话“${Ft(e)}”?此操作无法撤销。`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");e.length!==0&&confirm(`永久删除 ${String(e.length)} 个所选已归档会话?此操作无法撤销。`)&&(this.selectedSessionIds=Ts(this.selectedSessionIds,e.map(t=>t.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>!Y(t));this.selectedSessionIds=Ts(this.selectedSessionIds,e.map(t=>t.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){if(this.selectionScopes.has(e)){this.closeSelection(e);return}this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);const i=t.length===1?t[0]:void 0;i!==void 0&&(this.selectedSessionIds=new Set([...this.selectedSessionIds,i.id]))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){const t=this.sessions.filter(i=>zt(i)===e).map(i=>i.id);this.selectedSessionIds=Ts(this.selectedSessionIds,t)}toggleSelected(e){const t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}toggleVisibleSelection(e,t){const i=new Set(this.selectedSessionIds);for(const s of e)t?i.add(s.id):i.delete(s.id);this.selectedSessionIds=i}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&zt(t)===e)}pruneSelectedSessionIds(){const e=new Set(this.sessions.map(i=>i.id)),t=new Set([...this.selectedSessionIds].filter(i=>e.has(i)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has("archived")&&!this.sessions.some(i=>i.archived===!0)&&this.closeSelection("archived"),this.selectionScopes.has("current")&&!this.sessions.some(i=>i.archived!==!0)&&this.closeSelection("current")}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.menu.close(),this.selectionScopes.has("archived")&&this.closeSelection("archived"),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return Y(e)?"新建 · ":e.archived===!0?"只读 · ":""}renderActivity(e){const t=Ov(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return ss(t,t==="sending"?"正在发送消息":"会话活跃")}};A.styles=[ls,D`
687
+ `}handleSessionKeydown(e,t,i){As(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)&&Xt(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){confirm(`归档“${Zt(e)}”及其 ${String(t)} 个后代会话?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`永久删除已归档会话“${Zt(e)}”?此操作无法撤销。`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;const e=this.selectedSessions("archived");e.length!==0&&confirm(`永久删除 ${String(e.length)} 个所选已归档会话?此操作无法撤销。`)&&(this.selectedSessionIds=er(this.selectedSessionIds,e.map(t=>t.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){const e=this.selectedSessions("current").filter(t=>He(t,this.statuses[t.id],this.sessionPersistenceOptions()));this.selectedSessionIds=er(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=>Xt(i)===e).map(i=>i.id);this.selectedSessionIds=er(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)&&Xt(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,t,i){return fi(e,t,this.sessionPersistenceOptions())?i?.phase==="active"?"创建中 · ":i?.phase==="error"?"错误 · ":"新建 · ":e.archived===!0?"只读 · ":""}sessionPersistenceOptions(){return{authoritative:this.authoritativeSessionPersistence}}renderActivity(e){const t=Tb(e,this.statuses[e.id],this.activities[e.id],this.sending[e.id]===!0);return Cs(t,t==="sending"?"正在发送消息":"会话活跃")}};A.styles=[Ts,D`
676
688
  h2 { min-height: 30px; }
677
689
  h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
678
690
  .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; }
691
+ .start-session-button { box-sizing: border-box; flex: 0 0 auto; display: inline-grid; place-items: center; min-width: 30px; height: 30px; padding: 0 9px; }
679
692
  .cleanup-entry { flex: 0 0 auto; padding: 5px 7px; font-size: 12px; text-transform: none; }
680
693
  .bulk-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin: 0 0 6px; }
681
694
  .bulk-row button { padding: 5px 7px; font-size: 12px; }
@@ -686,9 +699,13 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
686
699
  button.danger, .action-menu-panel button.danger { color: var(--pi-danger); }
687
700
  button.danger:hover, .action-menu-panel button.danger:hover { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
688
701
  .action-row.bulk-selected .action-main { border-color: var(--pi-accent); box-shadow: inset 3px 0 0 var(--pi-accent); }
702
+ .pending-session-row { position: relative; display: grid; grid-template-columns: minmax(0, 1fr); margin: 6px 0; cursor: default; }
703
+ .pending-session-row.starting-session .action-main { border-radius: 8px; border-style: dashed; color: var(--pi-muted); }
704
+ .pending-session-row.starting-session .action-name { display: flex; align-items: center; gap: 6px; max-height: none; -webkit-line-clamp: 1; }
705
+ .pending-session-row.starting-session .activity-indicator { flex: 0 0 auto; margin: 0; }
689
706
  .action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
690
707
  .session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
691
- `];M([d({attribute:!1})],A.prototype,"sessions",2);M([d({attribute:!1})],A.prototype,"statuses",2);M([d({attribute:!1})],A.prototype,"activities",2);M([d({attribute:!1})],A.prototype,"sending",2);M([d({attribute:!1})],A.prototype,"selected",2);M([d({type:Boolean})],A.prototype,"canStart",2);M([d({type:Boolean})],A.prototype,"canDeleteArchived",2);M([d({type:Boolean})],A.prototype,"canReload",2);M([d({type:Boolean})],A.prototype,"canCleanup",2);M([d({type:String})],A.prototype,"archivedDeleteUnavailableMessage",2);M([d({type:String})],A.prototype,"cleanupUnavailableMessage",2);M([d({type:Boolean,reflect:!0})],A.prototype,"collapsible",2);M([d({type:Boolean,reflect:!0})],A.prototype,"collapsed",2);M([d({attribute:!1})],A.prototype,"onSelect",2);M([d({attribute:!1})],A.prototype,"onStart",2);M([d({attribute:!1})],A.prototype,"onToggleCollapsed",2);M([d({attribute:!1})],A.prototype,"onArchivedCollapsed",2);M([d({attribute:!1})],A.prototype,"onFocusPreviousSection",2);M([d({attribute:!1})],A.prototype,"onFocusNextSection",2);M([d({attribute:!1})],A.prototype,"onCancelKeyboardNavigation",2);M([d({attribute:!1})],A.prototype,"onArchive",2);M([d({attribute:!1})],A.prototype,"onArchiveWithDescendants",2);M([d({attribute:!1})],A.prototype,"onArchiveMany",2);M([d({attribute:!1})],A.prototype,"onRestore",2);M([d({attribute:!1})],A.prototype,"onDelete",2);M([d({attribute:!1})],A.prototype,"onDeleteArchived",2);M([d({attribute:!1})],A.prototype,"onDeleteArchivedMany",2);M([d({attribute:!1})],A.prototype,"onDetachParent",2);M([d({attribute:!1})],A.prototype,"onReload",2);M([d({attribute:!1})],A.prototype,"onCleanup",2);M([w()],A.prototype,"archivedExpanded",2);M([w()],A.prototype,"selectionScopes",2);M([w()],A.prototype,"selectedSessionIds",2);A=M([W("session-list")],A);function zt(e){return e.archived===!0?"archived":"current"}function Ts(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function Wv(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const r=t.get(s.parentSessionPath)??[];r.push(s),t.set(s.parentSessionPath,r)}const i=(s,r)=>{if(r.has(s.path))return 0;const o=new Set(r);o.add(s.path);let n=0;for(const a of t.get(s.path)??[])o.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,o));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function Ov(e,t,i,s){if(!(Y(e)||e.archived===!0))return s?"sending":tt(t,i)?"session":void 0}function _v(e){const t=new Map(e.map(s=>[s.path,s])),i=new Set;for(const s of e){if(s.archived===!0)continue;i.add(s.id);let r=s.parentSessionPath;const o=new Set([s.path]);for(;r!==void 0&&!o.has(r);){o.add(r);const n=t.get(r);if(n===void 0)break;i.add(n.id),r=n.parentSessionPath}}return jl(e.filter(s=>i.has(s.id)))}function jl(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,c=a===void 0?void 0:t.get(a);if(c===void 0){s.push(n);continue}const p=i.get(c.path)??[];p.push(n),i.set(c.path,p)}const r=[],o=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;r.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])o(h,a+1,u)};for(const n of s)o(n,0,new Set);return r}var Lv=Object.defineProperty,jv=Object.getOwnPropertyDescriptor,ne=(e,t,i,s)=>{for(var r=s>1?void 0:s?jv(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Lv(t,i,r),r};let Q=class extends R{constructor(){super(...arguments),this.canCleanup=!0,this.unavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。",this.loading=!1,this.running=!1,this.error="",this.draft={...Uf},this.formError=""}willUpdate(e){e.has("preview")&&(this.selectedProjectCwds=this.preview?.projects.map(t=>t.cwd))}render(){const e=qt(this.draft),t=this.selectedPreview(),i=hn({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),s=i?"运行清理":t!==void 0&&!$i(t)?"至少选择一个项目才能运行清理":"运行清理前请先预览";return l`
708
+ `];M([c({attribute:!1})],A.prototype,"sessions",2);M([c({attribute:!1})],A.prototype,"statuses",2);M([c({attribute:!1})],A.prototype,"activities",2);M([c({attribute:!1})],A.prototype,"sending",2);M([c({attribute:!1})],A.prototype,"selected",2);M([c({type:Number})],A.prototype,"startingCount",2);M([c({type:Boolean})],A.prototype,"canStart",2);M([c({type:Boolean})],A.prototype,"canDeleteArchived",2);M([c({type:Boolean})],A.prototype,"canReload",2);M([c({type:Boolean})],A.prototype,"canCleanup",2);M([c({type:Boolean})],A.prototype,"authoritativeSessionPersistence",2);M([c({type:String})],A.prototype,"archivedDeleteUnavailableMessage",2);M([c({type:String})],A.prototype,"cleanupUnavailableMessage",2);M([c({type:Boolean,reflect:!0})],A.prototype,"collapsible",2);M([c({type:Boolean,reflect:!0})],A.prototype,"collapsed",2);M([c({attribute:!1})],A.prototype,"onSelect",2);M([c({attribute:!1})],A.prototype,"onStart",2);M([c({attribute:!1})],A.prototype,"onToggleCollapsed",2);M([c({attribute:!1})],A.prototype,"onArchivedCollapsed",2);M([c({attribute:!1})],A.prototype,"onFocusPreviousSection",2);M([c({attribute:!1})],A.prototype,"onFocusNextSection",2);M([c({attribute:!1})],A.prototype,"onCancelKeyboardNavigation",2);M([c({attribute:!1})],A.prototype,"onArchive",2);M([c({attribute:!1})],A.prototype,"onArchiveWithDescendants",2);M([c({attribute:!1})],A.prototype,"onArchiveMany",2);M([c({attribute:!1})],A.prototype,"onRestore",2);M([c({attribute:!1})],A.prototype,"onDelete",2);M([c({attribute:!1})],A.prototype,"onDeleteArchived",2);M([c({attribute:!1})],A.prototype,"onDeleteArchivedMany",2);M([c({attribute:!1})],A.prototype,"onDetachParent",2);M([c({attribute:!1})],A.prototype,"onReload",2);M([c({attribute:!1})],A.prototype,"onCleanup",2);M([v()],A.prototype,"archivedExpanded",2);M([v()],A.prototype,"selectionScopes",2);M([v()],A.prototype,"selectedSessionIds",2);A=M([W("session-list")],A);function Xt(e){return e.archived===!0?"archived":"current"}function er(e,t){const i=new Set(t);return new Set([...e].filter(s=>!i.has(s)))}function Mb(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 Tb(e,t,i,s){if(!(Zi(e)||e.archived===!0))return s?"sending":dt(t,i)?"session":void 0}function Eb(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 xc(e.filter(s=>i.has(s.id)))}function xc(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,d=a===void 0?void 0:t.get(a);if(d===void 0){s.push(n);continue}const p=i.get(d.path)??[];p.push(n),i.set(d.path,p)}const r=[],o=(n,a,d)=>{if(d.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(d);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 Db=Object.defineProperty,Wb=Object.getOwnPropertyDescriptor,pe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Wb(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&&Db(t,i,r),r};let te=class extends I{constructor(){super(...arguments),this.canCleanup=!0,this.unavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。",this.loading=!1,this.running=!1,this.error="",this.draft={...Fg},this.formError=""}willUpdate(e){e.has("preview")&&(this.selectedProjectCwds=this.preview?.projects.map(t=>t.cwd))}render(){const e=ni(this.draft),t=this.selectedPreview(),i=jn({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),s=i?"运行清理":t!==void 0&&!qi(t)?"至少选择一个项目才能运行清理":"运行清理前请先预览";return l`
692
709
  <div class="backdrop" @mousedown=${()=>{this.onClose?.()}}>
693
710
  <section role="dialog" aria-modal="true" aria-label="清理会话" @mousedown=${r=>{r.stopPropagation()}} @keydown=${r=>{this.handleKeyDown(r)}}>
694
711
  <header>
@@ -712,25 +729,25 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
712
729
  </footer>
713
730
  </section>
714
731
  </div>
715
- `}renderForm(e){const t=this.loading||this.running,i=qt(this.draft),s=this.preview!==void 0&&i.ok&&Rt(i.request)!==Rt(this.previewRequest)&&$i(this.preview);return l`
732
+ `}renderForm(e){const t=this.loading||this.running,i=ni(this.draft),s=this.preview!==void 0&&i.ok&&Ut(i.request)!==Ut(this.previewRequest)&&qi(this.preview);return l`
716
733
  <fieldset ?disabled=${t}>
717
734
  <label class="toggle-row">
718
- <input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${r=>{this.updateDraft({archiveIdleEnabled:Ms(r)})}}>
735
+ <input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${r=>{this.updateDraft({archiveIdleEnabled:tr(r)})}}>
719
736
  <span>归档空闲超过</span>
720
- <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${r=>{this.updateDraft({archiveIdleDays:On(r)})}}>
737
+ <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:la(r)})}}>
721
738
  <span>天的未归档会话</span>
722
739
  </label>
723
740
  <label class="toggle-row delete-row">
724
- <input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${r=>{this.updateDraft({deleteArchivedEnabled:Ms(r)})}}>
741
+ <input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${r=>{this.updateDraft({deleteArchivedEnabled:tr(r)})}}>
725
742
  <span>删除已归档超过</span>
726
- <input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${r=>{this.updateDraft({deleteArchivedDays:On(r)})}}>
743
+ <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:la(r)})}}>
727
744
  <span>天的已归档会话</span>
728
745
  </label>
729
746
  </fieldset>
730
747
  <p class="warning"><strong>删除是永久操作。</strong>清理只会删除已经归档的会话。</p>
731
748
  ${e===""?null:l`<div class="dialog-error" role="alert">${e}</div>`}
732
749
  ${s?l`<div class="hint" role="status">阈值已更改。运行清理前请重新预览。</div>`:null}
733
- `}renderUnavailable(){return l`<div class="unavailable" role="status">${this.unavailableMessage}</div>`}renderMessage(){const e=this.formError||this.error;return e===""?null:l`<div class="dialog-error" role="alert">${e}</div>`}renderPreview(e){const t=this.selectedProjectCwdsForPreview(),i=new Set(t),s=un(e,t);return l`
750
+ `}renderUnavailable(){return l`<div class="unavailable" role="status">${this.unavailableMessage}</div>`}renderMessage(){const e=this.formError||this.error;return e===""?null:l`<div class="dialog-error" role="alert">${e}</div>`}renderPreview(e){const t=this.selectedProjectCwdsForPreview(),i=new Set(t),s=Un(e,t);return l`
734
751
  <section class="preview" aria-label="清理预览">
735
752
  <h2>预览</h2>
736
753
  ${e.projects.length===0?l`<p class="empty">没有会话匹配这些阈值。</p>`:l`
@@ -760,7 +777,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
760
777
  ${t.length===0?l`<p class="hint" role="status">至少选择一个项目才能运行清理。</p>`:null}
761
778
  `}renderProjectRow(e,t){return l`
762
779
  <tr class=${t?"":"unselected"}>
763
- <td class="select-cell"><input type="checkbox" aria-label=${`清理 ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${i=>{this.setProjectSelected(e.cwd,Ms(i))}}></td>
780
+ <td class="select-cell"><input type="checkbox" aria-label=${`清理 ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${i=>{this.setProjectSelected(e.cwd,tr(i))}}></td>
764
781
  <th title=${e.cwd} dir="auto">${e.cwd}</th>
765
782
  <td>${e.archiveCount}</td>
766
783
  <td>${e.deleteCount}</td>
@@ -770,7 +787,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
770
787
  <h2>清理完成</h2>
771
788
  <p>已归档 ${e.archivedSessionIds.length} 个会话;已永久删除 ${e.deletedSessionIds.length} 个已归档会话。</p>
772
789
  </section>
773
- `}updateDraft(e){this.draft={...this.draft,...e},this.formError=""}selectedPreview(){return this.preview===void 0?void 0:un(this.preview,this.selectedProjectCwdsForPreview())}selectedProjectCwdsForPreview(){return this.preview===void 0?[]:ml(this.preview,this.selectedProjectCwds)}selectAllProjects(){this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd)??[],this.formError=""}deselectAllProjects(){this.selectedProjectCwds=[],this.formError=""}setProjectSelected(e,t){const i=this.preview;if(i===void 0)return;const s=new Set(this.selectedProjectCwdsForPreview());t?s.add(e):s.delete(e),this.selectedProjectCwds=i.projects.map(r=>r.cwd).filter(r=>s.has(r)),this.formError=""}previewCleanup(){const e=qt(this.draft);if(!e.ok){this.formError=e.error;return}this.formError="",this.onPreview?.(e.request)}runCleanup(){const e=qt(this.draft);if(!e.ok){this.formError=e.error;return}const t=this.selectedPreview(),i=this.selectedProjectCwdsForPreview();if(!hn({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest})){this.formError=t!==void 0&&!$i(t)?"至少选择一个项目才能运行清理。":"运行清理前请先预览。";return}t===void 0||!Bf(t,s=>confirm(s))||(this.formError="",this.onRun?.({...e.request,projectCwds:i}))}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};Q.styles=D`
790
+ `}updateDraft(e){this.draft={...this.draft,...e},this.formError=""}selectedPreview(){return this.preview===void 0?void 0:Un(this.preview,this.selectedProjectCwdsForPreview())}selectedProjectCwdsForPreview(){return this.preview===void 0?[]:Yl(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=ni(this.draft);if(!e.ok){this.formError=e.error;return}this.formError="",this.onPreview?.(e.request)}runCleanup(){const e=ni(this.draft);if(!e.ok){this.formError=e.error;return}const t=this.selectedPreview(),i=this.selectedProjectCwdsForPreview();if(!jn({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest})){this.formError=t!==void 0&&!qi(t)?"至少选择一个项目才能运行清理。":"运行清理前请先预览。";return}t===void 0||!_g(t,s=>confirm(s))||(this.formError="",this.onRun?.({...e.request,projectCwds:i}))}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};te.styles=D`
774
791
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
775
792
  .backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
776
793
  section[role="dialog"] { width: min(760px, 100%); max-height: min(760px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr) auto; border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -820,7 +837,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
820
837
  table { min-width: 560px; }
821
838
  thead th:first-child, td.select-cell { width: 58px; }
822
839
  }
823
- `;ne([d({type:Boolean})],Q.prototype,"canCleanup",2);ne([d({type:String})],Q.prototype,"unavailableMessage",2);ne([d({attribute:!1})],Q.prototype,"preview",2);ne([d({attribute:!1})],Q.prototype,"previewRequest",2);ne([d({attribute:!1})],Q.prototype,"result",2);ne([d({type:Boolean})],Q.prototype,"loading",2);ne([d({type:Boolean})],Q.prototype,"running",2);ne([d({type:String})],Q.prototype,"error",2);ne([d({attribute:!1})],Q.prototype,"onPreview",2);ne([d({attribute:!1})],Q.prototype,"onRun",2);ne([d({attribute:!1})],Q.prototype,"onClose",2);ne([w()],Q.prototype,"draft",2);ne([w()],Q.prototype,"formError",2);ne([w()],Q.prototype,"selectedProjectCwds",2);Q=ne([W("session-cleanup-dialog")],Q);function Ms(e){return e.target instanceof HTMLInputElement?e.target.checked:!1}function On(e){return e.target instanceof HTMLInputElement?e.target.value:""}const Hr={CHILD:2,ELEMENT:6},qr=e=>(...t)=>({_$litDirective$:e,values:t});let Kr=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,i,s){this._$Ct=t,this._$AM=i,this._$Ci=s}_$AS(t,i){return this.update(t,i)}update(t,i){return this.render(...i)}};const{I:Fv}=Hc,_n=e=>e,Ln=()=>document.createComment(""),Ut=(e,t,i)=>{const s=e._$AA.parentNode,r=t===void 0?e._$AB:t._$AA;if(i===void 0){const o=s.insertBefore(Ln(),r),n=s.insertBefore(Ln(),r);i=new Fv(o,n,e,e.options)}else{const o=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let c;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(c=e._$AU)!==n._$AU&&i._$AP(c)}if(o!==r||a){let c=i._$AA;for(;c!==o;){const p=_n(c).nextSibling;_n(s).insertBefore(c,r),c=p}}}return i},at=(e,t,i=e)=>(e._$AI(t,i),e),zv={},Uv=(e,t=zv)=>e._$AH=t,Bv=e=>e._$AH,Es=e=>{e._$AR(),e._$AA.remove()};const jn=(e,t,i)=>{const s=new Map;for(let r=t;r<=i;r++)s.set(e[r],r);return s},Nv=qr(class extends Kr{constructor(e){if(super(e),e.type!==Hr.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let s;i===void 0?i=t:t!==void 0&&(s=t);const r=[],o=[];let n=0;for(const a of e)r[n]=s?s(a,n):n,o[n]=i(a,n),n++;return{values:o,keys:r}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const r=Bv(e),{values:o,keys:n}=this.dt(t,i,s);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],c=[];let p,u,h=0,g=r.length-1,y=0,P=o.length-1;for(;h<=g&&y<=P;)if(r[h]===null)h++;else if(r[g]===null)g--;else if(a[h]===n[y])c[y]=at(r[h],o[y]),h++,y++;else if(a[g]===n[P])c[P]=at(r[g],o[P]),g--,P--;else if(a[h]===n[P])c[P]=at(r[h],o[P]),Ut(e,c[P+1],r[h]),h++,P--;else if(a[g]===n[y])c[y]=at(r[g],o[y]),Ut(e,r[h],r[g]),g--,y++;else if(p===void 0&&(p=jn(n,y,P),u=jn(a,h,g)),p.has(a[h]))if(p.has(a[g])){const I=u.get(n[y]),G=I!==void 0?r[I]:null;if(G===null){const Ze=Ut(e,r[h]);at(Ze,o[y]),c[y]=Ze}else c[y]=at(G,o[y]),Ut(e,r[h],G),r[I]=null;y++}else Es(r[g]),g--;else Es(r[h]),h++;for(;y<=P;){const I=Ut(e,c[P+1]);at(I,o[y]),c[y++]=I}for(;h<=g;){const I=r[h++];I!==null&&Es(I)}return this.ut=n,Uv(e,c),et}}),Hv="pi-web:chat-groups:",qv={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(Fn(e));return t===null||t===""?void 0:Vv(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(Fn(e),JSON.stringify(t))}catch{}}};class Kv{constructor(t=qv){this.storage=t,this.sessionId="",this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(t){if(this.sessionId===t)return;this.sessionId=t;const i=t===""?void 0:this.storage.read(t);this.openGroupKeys=new Set(i?.open??[]),this.closedDefaultOpenGroupKeys=new Set(i?.closedDefaultOpen??[])}isOpen(t,i){return i?!this.closedDefaultOpenGroupKeys.has(t):this.openGroupKeys.has(t)}applyToggle(t,i,s){const r=this.isOpen(t,s),o=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(o.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?o.add(t):o.delete(t)),(s?!n.has(t):o.has(t))===r&&zn(o,this.openGroupKeys)&&zn(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=o,this.closedDefaultOpenGroupKeys=n,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==""&&this.storage.write(this.sessionId,this.snapshot())}}function Fn(e){return`${Hv}${e}`}function Vv(e){if(Array.isArray(e))return{open:Ds(e),closedDefaultOpen:[]};if(Gv(e))return{open:Array.isArray(e.open)?Ds(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Ds(e.closedDefaultOpen):[]}}function Ds(e){return e.filter(t=>typeof t=="string")}function zn(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Gv(e){return typeof e=="object"&&e!==null}function Jv(e,t=0){const i=[];let s=[],r=0;const o=(a,c)=>{s.length||(r=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:r,endIndex:r+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(y=>Un(a,y)),u=a.parts.filter(y=>!Un(a,y)),h=t+c,g={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&o({role:a.role,parts:u,...g},h),p.length){n();const y=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:y,parts:p,...g},index:h})}}),n(),i}function Qv(e){if(e.every(s=>s.source==="compaction"))return`${String(e.length)} 条历史压缩摘要`;if(e.every(s=>s.source==="branch_summary"))return`${String(e.length)} 条分支摘要`;const t=e.reduce((s,r)=>(s[r.role]=(s[r.role]??0)+1,s),{}),i=Object.entries(t).map(([s,r])=>`${String(r)} ${Zv(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Zv(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Un(e,t){return e.source==="compaction"||e.source==="branch_summary"?!1:t.type==="skillInvocation"||t.type==="skillRead"?!0:t.type==="text"&&(e.role==="user"||e.role==="assistant"||e.role==="system"||e.role==="bash")}const Xv=30;function Yv(e,t){const i=tb(rb(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function eb(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=ib(s,t.markerOffset);return}e.scrollTop=sb(e.scrollHeight,t.distanceFromBottom)}function tb(e){let t,i=Number.NEGATIVE_INFINITY,s,r=Number.POSITIVE_INFINITY;for(const o of e)o.offset<=0&&o.offset>=i?(t=o,i=o.offset):o.offset>0&&o.offset<r&&(s=o,r=o.offset);return t??s}function ib(e,t){return e-t}function sb(e,t){return Math.max(0,e-t)}function rb(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const r=s.dataset.markerId;return r===void 0?[]:[{id:r,offset:s.getBoundingClientRect().top-i}]})}const ob=600,nb=1;function ab(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:lb(e)||cb(e)}function lb(e){return e.scrollTop<(e.topThreshold??Math.max(ob,e.clientHeight))}function cb(e){return e.scrollHeight<=e.clientHeight+nb}const db="pi-web:chat-scroll:",pb=180,hb=48,ub=2,fb={getItem(e){return typeof localStorage>"u"?null:localStorage.getItem(e)},setItem(e,t){typeof localStorage>"u"||localStorage.setItem(e,t)},removeItem(e){typeof localStorage>"u"||localStorage.removeItem(e)}},gb={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class mb{constructor(t=fb,i=gb){this.storage=t,this.scheduler=i}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(t,i,s=pb){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,r=ub){if(t===""||i===void 0||!Os(i))return"skipped";try{if(zl(i,r)){const a={mode:"bottom"};return this.storage.setItem(Ws(t),JSON.stringify(a)),"saved"}const o=wb(i,s);if(o===void 0)return"skipped";const n=bb(i,o);return this.storage.setItem(Ws(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,r){const o=this.readPosition(t);return o===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(o,i,s,r)}restoreExplicitPosition(t,i,s,r){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!Os(i))return{status:"skipped"};const o=yb(s,t.anchorId);if(o===void 0)return r?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=o.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(Ws(t));if(i===null||i==="")return;const s=JSON.parse(i);return vb(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!Os(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function Ws(e){return`${db}${e}`}function vb(e){return typeof e!="object"||e===null||!("mode"in e)?!1:e.mode==="bottom"?!0:e.mode==="anchor"&&"anchorId"in e&&typeof e.anchorId=="string"&&e.anchorId!==""&&"offset"in e&&typeof e.offset=="number"}function Os(e){return e.clientHeight>0&&e.scrollHeight>0}function Fl(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function zl(e,t=hb){return Fl(e)<t}function bb(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:Vr(t)??"",offset:t.getBoundingClientRect().top-i}}function wb(e,t){const i=e.getBoundingClientRect();let s,r=Number.NEGATIVE_INFINITY,o,n=Number.POSITIVE_INFINITY;for(const a of t){if(Vr(a)===void 0)continue;const c=a.getBoundingClientRect();if(c.bottom<=c.top||c.bottom<i.top||c.top>i.bottom)continue;const p=c.top-i.top;p<=0&&p>=r?(s=a,r=p):p>0&&p<n&&(o=a,n=p)}return s??o}function Bn(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const r=s.getBoundingClientRect();return r.bottom>=i.top&&r.top<=i.bottom})}function yb(e,t){return e.find(i=>Vr(i)===t)}function Vr(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}async function Gr(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}const xb=D`
840
+ `;pe([c({type:Boolean})],te.prototype,"canCleanup",2);pe([c({type:String})],te.prototype,"unavailableMessage",2);pe([c({attribute:!1})],te.prototype,"preview",2);pe([c({attribute:!1})],te.prototype,"previewRequest",2);pe([c({attribute:!1})],te.prototype,"result",2);pe([c({type:Boolean})],te.prototype,"loading",2);pe([c({type:Boolean})],te.prototype,"running",2);pe([c({type:String})],te.prototype,"error",2);pe([c({attribute:!1})],te.prototype,"onPreview",2);pe([c({attribute:!1})],te.prototype,"onRun",2);pe([c({attribute:!1})],te.prototype,"onClose",2);pe([v()],te.prototype,"draft",2);pe([v()],te.prototype,"formError",2);pe([v()],te.prototype,"selectedProjectCwds",2);te=pe([W("session-cleanup-dialog")],te);function tr(e){return e.target instanceof HTMLInputElement?e.target.checked:!1}function la(e){return e.target instanceof HTMLInputElement?e.target.value:""}const uo={CHILD:2,ELEMENT:6},fo=e=>(...t)=>({_$litDirective$:e,values:t});let go=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:Lb}=Wd,ca=e=>e,da=()=>document.createComment(""),Yt=(e,t,i)=>{const s=e._$AA.parentNode,r=t===void 0?e._$AB:t._$AA;if(i===void 0){const o=s.insertBefore(da(),r),n=s.insertBefore(da(),r);i=new Lb(o,n,e,e.options)}else{const o=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let d;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(d=e._$AU)!==n._$AU&&i._$AP(d)}if(o!==r||a){let d=i._$AA;for(;d!==o;){const p=ca(d).nextSibling;ca(s).insertBefore(d,r),d=p}}}return i},vt=(e,t,i=e)=>(e._$AI(t,i),e),Ob={},Fb=(e,t=Ob)=>e._$AH=t,_b=e=>e._$AH,ir=e=>{e._$AR(),e._$AA.remove()};const pa=(e,t,i)=>{const s=new Map;for(let r=t;r<=i;r++)s.set(e[r],r);return s},jb=fo(class extends go{constructor(e){if(super(e),e.type!==uo.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=_b(e),{values:o,keys:n}=this.dt(t,i,s);if(!Array.isArray(r))return this.ut=n,o;const a=this.ut??=[],d=[];let p,u,h=0,g=r.length-1,S=0,P=o.length-1;for(;h<=g&&S<=P;)if(r[h]===null)h++;else if(r[g]===null)g--;else if(a[h]===n[S])d[S]=vt(r[h],o[S]),h++,S++;else if(a[g]===n[P])d[P]=vt(r[g],o[P]),g--,P--;else if(a[h]===n[P])d[P]=vt(r[h],o[P]),Yt(e,d[P+1],r[h]),h++,P--;else if(a[g]===n[S])d[S]=vt(r[g],o[S]),Yt(e,r[h],r[g]),g--,S++;else if(p===void 0&&(p=pa(n,S,P),u=pa(a,h,g)),p.has(a[h]))if(p.has(a[g])){const C=u.get(n[S]),X=C!==void 0?r[C]:null;if(X===null){const ot=Yt(e,r[h]);vt(ot,o[S]),d[S]=ot}else d[S]=vt(X,o[S]),Yt(e,r[h],X),r[C]=null;S++}else ir(r[g]),g--;else ir(r[h]),h++;for(;S<=P;){const C=Yt(e,d[P+1]);vt(C,o[S]),d[S++]=C}for(;h<=g;){const C=r[h++];C!==null&&ir(C)}return this.ut=n,Fb(e,d),ct}}),Ub="pi-web:chat-groups:",Bb={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(ha(e));return t===null||t===""?void 0:Nb(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(ha(e),JSON.stringify(t))}catch{}}};class zb{constructor(t=Bb){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&&ua(o,this.openGroupKeys)&&ua(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 ha(e){return`${Ub}${e}`}function Nb(e){if(Array.isArray(e))return{open:sr(e),closedDefaultOpen:[]};if(qb(e))return{open:Array.isArray(e.open)?sr(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?sr(e.closedDefaultOpen):[]}}function sr(e){return e.filter(t=>typeof t=="string")}function ua(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function qb(e){return typeof e=="object"&&e!==null}function Hb(e,t=0){const i=[];let s=[],r=0;const o=(a,d)=>{s.length||(r=d),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:r,endIndex:r+s.length-1}),s=[])};return e.forEach((a,d)=>{const p=a.parts.filter(S=>fa(a,S)),u=a.parts.filter(S=>!fa(a,S)),h=t+d,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 S=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:S,parts:p,...g},index:h})}}),n(),i}function Kb(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)} ${Vb(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Vb(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function fa(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")}async function mo(e,t=Gb()){if(!t.isSecureContext)return t.fallbackWriteText(e);if(t.writeText!==void 0)try{return await t.writeText(e),!0}catch{return t.fallbackWriteText(e)}return t.fallbackWriteText(e)}function Gb(){const e=i=>Jb(i),t=Qb();return t===void 0?{isSecureContext:ga(),fallbackWriteText:e}:{isSecureContext:ga(),writeText:t,fallbackWriteText:e}}function ga(){return typeof window<"u"&&window.isSecureContext}function Qb(){if(!(typeof navigator>"u"||!("clipboard"in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function Jb(e){if(typeof document>"u")return!1;const t=document.activeElement,i=document.getSelection(),s=i===null?[]:Zb(i),r=document.createElement("textarea");r.value=e,r.readOnly=!0,r.setAttribute("aria-hidden","true"),r.style.position="fixed",r.style.top="0",r.style.left="-9999px",r.style.width="1px",r.style.height="1px",r.style.padding="0",r.style.border="0",r.style.opacity="0",r.style.pointerEvents="none",document.body.append(r),r.focus(),r.select(),r.setSelectionRange(0,r.value.length);try{return document.execCommand("copy")}catch{return!1}finally{r.remove(),Xb(i,s),Yb(t)}}function Zb(e){const t=[];for(let i=0;i<e.rangeCount;i+=1)t.push(e.getRangeAt(i));return t}function Xb(e,t){if(e!==null)try{e.removeAllRanges();for(const i of t)e.addRange(i)}catch{}}function Yb(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}const ew=30;function tw(e,t){const i=sw(nw(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function iw(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=rw(s,t.markerOffset);return}e.scrollTop=ow(e.scrollHeight,t.distanceFromBottom)}function sw(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 rw(e,t){return e-t}function ow(e,t){return Math.max(0,e-t)}function nw(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 aw=600,lw=1;function cw(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:dw(e)||pw(e)}function dw(e){return e.scrollTop<(e.topThreshold??Math.max(aw,e.clientHeight))}function pw(e){return e.scrollHeight<=e.clientHeight+lw}const hw="pi-web:chat-scroll:",uw=180,fw=48,gw=2,mw={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)}},vw={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class bw{constructor(t=mw,i=vw){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=uw){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,r=gw){if(t===""||i===void 0||!or(i))return"skipped";try{if($c(i,r)){const a={mode:"bottom"};return this.storage.setItem(rr(t),JSON.stringify(a)),"saved"}const o=Sw(i,s);if(o===void 0)return"skipped";const n=yw(i,o);return this.storage.setItem(rr(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||!or(i))return{status:"skipped"};const o=xw(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(rr(t));if(i===null||i==="")return;const s=JSON.parse(i);return ww(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!or(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function rr(e){return`${hw}${e}`}function ww(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 or(e){return e.clientHeight>0&&e.scrollHeight>0}function kc(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function $c(e,t=fw){return kc(e)<t}function yw(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:vo(t)??"",offset:t.getBoundingClientRect().top-i}}function Sw(e,t){const i=e.getBoundingClientRect();let s,r=Number.NEGATIVE_INFINITY,o,n=Number.POSITIVE_INFINITY;for(const a of t){if(vo(a)===void 0)continue;const d=a.getBoundingClientRect();if(d.bottom<=d.top||d.bottom<i.top||d.top>i.bottom)continue;const p=d.top-i.top;p<=0&&p>=r?(s=a,r=p):p>0&&p<n&&(o=a,n=p)}return s??o}function ma(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const r=s.getBoundingClientRect();return r.bottom>=i.top&&r.top<=i.bottom})}function xw(e,t){return e.find(i=>vo(i)===t)}function vo(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}const kw=D`
824
841
  :host { position: relative; z-index: 0; display: flex; flex: 1 1 0; flex-direction: column; min-height: 0; max-height: 100%; overflow: hidden; contain: size layout; color: var(--pi-text); font: 14px system-ui, sans-serif; }
825
842
  .chat-wrap { position: relative; flex: 1 1 0; min-height: 0; max-height: 100%; overflow: hidden; }
826
843
  .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
@@ -909,7 +926,7 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
909
926
  pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
910
927
  .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
911
928
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
912
- `;var Sb=Object.defineProperty,kb=Object.getOwnPropertyDescriptor,Jr=(e,t,i,s)=>{for(var r=s>1?void 0:s?kb(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Sb(t,i,r),r};let Yt=class extends R{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=Nn(this.positionPercent),t=Nn(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return l`
929
+ `;var $w=Object.defineProperty,Pw=Object.getOwnPropertyDescriptor,bo=(e,t,i,s)=>{for(var r=s>1?void 0:s?Pw(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&&$w(t,i,r),r};let mi=class extends I{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=va(this.positionPercent),t=va(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return l`
913
930
  <div
914
931
  class="meter"
915
932
  style=${`--position:${e.toFixed(2)}%;`}
@@ -925,60 +942,60 @@ ${h}`;await this.api.prompt(a,g,i,p)}else await this.api.prompt(a,t,i,p,s);this.
925
942
  <div class="marker"></div>
926
943
  </div>
927
944
  </div>
928
- `}};Yt.styles=D`
945
+ `}};mi.styles=D`
929
946
  :host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
930
947
  :host(:hover), :host(:focus-within) { opacity: .92; }
931
948
  .meter { height: 100%; }
932
949
  .track { position: relative; height: 4px; margin-top: 4px; border-radius: 999px; background: color-mix(in srgb, var(--pi-border-muted) 34%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--pi-bg) 55%, transparent); }
933
950
  .progress { position: absolute; left: 0; width: var(--position); top: 0; bottom: 0; border-radius: 999px; background: color-mix(in srgb, var(--pi-accent) 42%, var(--pi-border-muted)); }
934
951
  .marker { position: absolute; left: var(--position); top: 50%; width: 10px; height: 10px; border: 2px solid var(--pi-bg); border-radius: 50%; background: var(--pi-accent); box-shadow: 0 2px 8px var(--pi-shadow); transform: translate(-50%, -50%); }
935
- `;Jr([d({type:Number})],Yt.prototype,"positionPercent",2);Jr([d({type:Number})],Yt.prototype,"loadedPercent",2);Yt=Jr([W("conversation-meter")],Yt);function Nn(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class or extends Kr{constructor(t){if(super(t),this.it=U,t.type!==Hr.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===U||t==null)return this._t=void 0,this.it=t;if(t===et)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const i=[t];return i.raw=i,this._t={_$litType$:this.constructor.resultType,strings:i,values:[]}}}or.directiveName="unsafeHTML",or.resultType=1;const $b=qr(or);function Qr(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var gt=Qr();function Ul(e){gt=e}var lt={exec:()=>null};function yt(e){let t=[];return i=>{let s=Math.max(0,Math.min(3,i-1)),r=t[s];return r||(r=e(s),t[s]=r),r}}function T(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(r,o)=>{let n=typeof o=="string"?o:o.source;return n=n.replace(ee.caret,"$1"),i=i.replace(r,n),s},getRegex:()=>new RegExp(i,t)};return s}var Pb=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),ee={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:yt(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:yt(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:yt(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:yt(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:yt(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:yt(e=>new RegExp(`^ {0,${e}}>`))},Cb=/^(?:[ \t]*(?:\n|$))+/,Ib=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Rb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,oi=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ab=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Zr=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Bl=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Nl=T(Bl).replace(/bull/g,Zr).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Tb=T(Bl).replace(/bull/g,Zr).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Xr=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Mb=/^[^\n]+/,Yr=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Eb=T(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Yr).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Db=T(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Zr).getRegex(),cs="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",eo=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Wb=T("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",eo).replace("tag",cs).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Hl=T(Xr).replace("hr",oi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",cs).getRegex(),Ob=T(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Hl).getRegex(),to={blockquote:Ob,code:Ib,def:Eb,fences:Rb,heading:Ab,hr:oi,html:Wb,lheading:Nl,list:Db,newline:Cb,paragraph:Hl,table:lt,text:Mb},Hn=T("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",oi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",cs).getRegex(),_b={...to,lheading:Tb,table:Hn,paragraph:T(Xr).replace("hr",oi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Hn).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",cs).getRegex()},Lb={...to,html:T(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",eo).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:lt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:T(Xr).replace("hr",oi).replace("heading",` *#{1,6} *[^
936
- ]`).replace("lheading",Nl).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},jb=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Fb=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ql=/^( {2,}|\\)\n(?!\s*$)/,zb=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Et=/[\p{P}\p{S}]/u,ds=/[\s\p{P}\p{S}]/u,io=/[^\s\p{P}\p{S}]/u,Ub=T(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ds).getRegex(),Kl=/(?!~)[\p{P}\p{S}]/u,Bb=/(?!~)[\s\p{P}\p{S}]/u,Nb=/(?:[^\s\p{P}\p{S}]|~)/u,Hb=T(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Pb?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Vl=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,qb=T(Vl,"u").replace(/punct/g,Et).getRegex(),Kb=T(Vl,"u").replace(/punct/g,Kl).getRegex(),Gl="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Vb=T(Gl,"gu").replace(/notPunctSpace/g,io).replace(/punctSpace/g,ds).replace(/punct/g,Et).getRegex(),Gb=T(Gl,"gu").replace(/notPunctSpace/g,Nb).replace(/punctSpace/g,Bb).replace(/punct/g,Kl).getRegex(),Jb=T("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,io).replace(/punctSpace/g,ds).replace(/punct/g,Et).getRegex(),Qb=T(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Et).getRegex(),Zb="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Xb=T(Zb,"gu").replace(/notPunctSpace/g,io).replace(/punctSpace/g,ds).replace(/punct/g,Et).getRegex(),Yb=T(/\\(punct)/,"gu").replace(/punct/g,Et).getRegex(),ew=T(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),tw=T(eo).replace("(?:-->|$)","-->").getRegex(),iw=T("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",tw).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ni=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,sw=T(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Ni).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Jl=T(/^!?\[(label)\]\[(ref)\]/).replace("label",Ni).replace("ref",Yr).getRegex(),Ql=T(/^!?\[(ref)\](?:\[\])?/).replace("ref",Yr).getRegex(),rw=T("reflink|nolink(?!\\()","g").replace("reflink",Jl).replace("nolink",Ql).getRegex(),qn=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,so={_backpedal:lt,anyPunctuation:Yb,autolink:ew,blockSkip:Hb,br:ql,code:Fb,del:lt,delLDelim:lt,delRDelim:lt,emStrongLDelim:qb,emStrongRDelimAst:Vb,emStrongRDelimUnd:Jb,escape:jb,link:sw,nolink:Ql,punctuation:Ub,reflink:Jl,reflinkSearch:rw,tag:iw,text:zb,url:lt},ow={...so,link:T(/^!?\[(label)\]\((.*?)\)/).replace("label",Ni).getRegex(),reflink:T(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Ni).getRegex()},nr={...so,emStrongRDelimAst:Gb,emStrongLDelim:Kb,delLDelim:Qb,delRDelim:Xb,url:T(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",qn).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:T(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",qn).getRegex()},nw={...nr,br:T(ql).replace("{2,}","*").getRegex(),text:T(nr.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},hi={normal:to,gfm:_b,pedantic:Lb},Bt={normal:so,gfm:nr,breaks:nw,pedantic:ow},aw={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Kn=e=>aw[e];function Oe(e,t){if(t){if(ee.escapeTest.test(e))return e.replace(ee.escapeReplace,Kn)}else if(ee.escapeTestNoEncode.test(e))return e.replace(ee.escapeReplaceNoEncode,Kn);return e}function Vn(e){try{e=encodeURI(e).replace(ee.percentDecode,"%")}catch{return null}return e}function Gn(e,t){let i=e.replace(ee.findPipe,(o,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(ee.splitPipe),r=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;r<s.length;r++)s[r]=s[r].trim().replace(ee.slashPipe,"|");return s}function Xe(e,t,i){let s=e.length;if(s===0)return"";let r=0;for(;r<s&&e.charAt(s-r-1)===t;)r++;return e.slice(0,s-r)}function Jn(e){let t=e.split(`
937
- `),i=t.length-1;for(;i>=0&&ee.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
938
- `)}function lw(e,t){if(e.indexOf(t[1])===-1)return-1;let i=0;for(let s=0;s<e.length;s++)if(e[s]==="\\")s++;else if(e[s]===t[0])i++;else if(e[s]===t[1]&&(i--,i<0))return s;return i>0?-2:-1}function cw(e,t=0){let i=t,s="";for(let r of e)if(r===" "){let o=4-i%4;s+=" ".repeat(o),i+=o}else s+=r,i++;return s}function Qn(e,t,i,s,r){let o=t.href,n=t.title||null,a=e[1].replace(r.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:o,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function dw(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(`
952
+ `;bo([c({type:Number})],mi.prototype,"positionPercent",2);bo([c({type:Number})],mi.prototype,"loadedPercent",2);mi=bo([W("conversation-meter")],mi);function va(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class Rr extends go{constructor(t){if(super(t),this.it=B,t.type!==uo.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===B||t==null)return this._t=void 0,this.it=t;if(t===ct)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:[]}}}Rr.directiveName="unsafeHTML",Rr.resultType=1;const Cw=fo(Rr);function wo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ct=wo();function Pc(e){Ct=e}var bt={exec:()=>null};function Tt(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 E(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(re.caret,"$1"),i=i.replace(r,n),s},getRegex:()=>new RegExp(i,t)};return s}var Rw=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),re={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:Tt(e=>new RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Tt(e=>new RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Tt(e=>new RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Tt(e=>new RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Tt(e=>new RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Tt(e=>new RegExp(`^ {0,${e}}>`))},Iw=/^(?:[ \t]*(?:\n|$))+/,Aw=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Mw=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,xi=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Tw=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,yo=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Cc=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Rc=E(Cc).replace(/bull/g,yo).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Ew=E(Cc).replace(/bull/g,yo).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),So=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Dw=/^[^\n]+/,xo=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Ww=E(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",xo).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Lw=E(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,yo).getRegex(),Es="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",ko=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ow=E("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",ko).replace("tag",Es).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ic=E(So).replace("hr",xi).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",Es).getRegex(),Fw=E(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Ic).getRegex(),$o={blockquote:Fw,code:Aw,def:Ww,fences:Mw,heading:Tw,hr:xi,html:Ow,lheading:Rc,list:Lw,newline:Iw,paragraph:Ic,table:bt,text:Dw},ba=E("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",xi).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",Es).getRegex(),_w={...$o,lheading:Ew,table:ba,paragraph:E(So).replace("hr",xi).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ba).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",Es).getRegex()},jw={...$o,html:E(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ko).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:bt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:E(So).replace("hr",xi).replace("heading",` *#{1,6} *[^
953
+ ]`).replace("lheading",Rc).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Uw=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Bw=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ac=/^( {2,}|\\)\n(?!\s*$)/,zw=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,qt=/[\p{P}\p{S}]/u,Ds=/[\s\p{P}\p{S}]/u,Po=/[^\s\p{P}\p{S}]/u,Nw=E(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ds).getRegex(),Mc=/(?!~)[\p{P}\p{S}]/u,qw=/(?!~)[\s\p{P}\p{S}]/u,Hw=/(?:[^\s\p{P}\p{S}]|~)/u,Kw=E(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Rw?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Tc=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Vw=E(Tc,"u").replace(/punct/g,qt).getRegex(),Gw=E(Tc,"u").replace(/punct/g,Mc).getRegex(),Ec="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Qw=E(Ec,"gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Ds).replace(/punct/g,qt).getRegex(),Jw=E(Ec,"gu").replace(/notPunctSpace/g,Hw).replace(/punctSpace/g,qw).replace(/punct/g,Mc).getRegex(),Zw=E("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Ds).replace(/punct/g,qt).getRegex(),Xw=E(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,qt).getRegex(),Yw="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",ey=E(Yw,"gu").replace(/notPunctSpace/g,Po).replace(/punctSpace/g,Ds).replace(/punct/g,qt).getRegex(),ty=E(/\\(punct)/,"gu").replace(/punct/g,qt).getRegex(),iy=E(/^<(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(),sy=E(ko).replace("(?:-->|$)","-->").getRegex(),ry=E("^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",sy).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ds=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,oy=E(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",ds).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Dc=E(/^!?\[(label)\]\[(ref)\]/).replace("label",ds).replace("ref",xo).getRegex(),Wc=E(/^!?\[(ref)\](?:\[\])?/).replace("ref",xo).getRegex(),ny=E("reflink|nolink(?!\\()","g").replace("reflink",Dc).replace("nolink",Wc).getRegex(),wa=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Co={_backpedal:bt,anyPunctuation:ty,autolink:iy,blockSkip:Kw,br:Ac,code:Bw,del:bt,delLDelim:bt,delRDelim:bt,emStrongLDelim:Vw,emStrongRDelimAst:Qw,emStrongRDelimUnd:Zw,escape:Uw,link:oy,nolink:Wc,punctuation:Nw,reflink:Dc,reflinkSearch:ny,tag:ry,text:zw,url:bt},ay={...Co,link:E(/^!?\[(label)\]\((.*?)\)/).replace("label",ds).getRegex(),reflink:E(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ds).getRegex()},Ir={...Co,emStrongRDelimAst:Jw,emStrongLDelim:Gw,delLDelim:Xw,delRDelim:ey,url:E(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",wa).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:E(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",wa).getRegex()},ly={...Ir,br:E(Ac).replace("{2,}","*").getRegex(),text:E(Ir.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Mi={normal:$o,gfm:_w,pedantic:jw},ei={normal:Co,gfm:Ir,breaks:ly,pedantic:ay},cy={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},ya=e=>cy[e];function ze(e,t){if(t){if(re.escapeTest.test(e))return e.replace(re.escapeReplace,ya)}else if(re.escapeTestNoEncode.test(e))return e.replace(re.escapeReplaceNoEncode,ya);return e}function Sa(e){try{e=encodeURI(e).replace(re.percentDecode,"%")}catch{return null}return e}function xa(e,t){let i=e.replace(re.findPipe,(o,n,a)=>{let d=!1,p=n;for(;--p>=0&&a[p]==="\\";)d=!d;return d?"|":" |"}),s=i.split(re.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(re.slashPipe,"|");return s}function nt(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 ka(e){let t=e.split(`
954
+ `),i=t.length-1;for(;i>=0&&re.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
955
+ `)}function dy(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 py(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 $a(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 d={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:o,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,d}function hy(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(`
939
956
  `).map(o=>{let n=o.match(i.other.beginningSpace);if(n===null)return o;let[a]=n;return a.length>=r.length?o.slice(r.length):o}).join(`
940
- `)}var Hi=class{options;rules;lexer;constructor(e){this.options=e||gt}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let i=this.options.pedantic?t[0]:Jn(t[0]),s=i.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:i,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let i=t[0],s=dw(i,t[3]||"",this.rules);return{type:"code",raw:i,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let i=t[2].trim();if(this.rules.other.endingHash.test(i)){let s=Xe(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Xe(t[0],`
941
- `),depth:t[1].length,text:i,tokens:this.lexer.inline(i)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Xe(t[0],`
942
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Xe(t[0],`
957
+ `)}var ps=class{options;rules;lexer;constructor(e){this.options=e||Ct}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]:ka(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=hy(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=nt(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:nt(t[0],`
958
+ `),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:nt(t[0],`
959
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=nt(t[0],`
943
960
  `).split(`
944
- `),s="",r="",o=[];for(;i.length>0;){let n=!1,a=[],c;for(c=0;c<i.length;c++)if(this.rules.other.blockquoteStart.test(i[c]))a.push(i[c]),n=!0;else if(!n)a.push(i[c]);else break;i=i.slice(c);let p=a.join(`
961
+ `),s="",r="",o=[];for(;i.length>0;){let n=!1,a=[],d;for(d=0;d<i.length;d++)if(this.rules.other.blockquoteStart.test(i[d]))a.push(i[d]),n=!0;else if(!n)a.push(i[d]);else break;i=i.slice(d);let p=a.join(`
945
962
  `),u=p.replace(this.rules.other.blockquoteSetextReplace,`
946
963
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
947
964
  ${p}`:p,r=r?`${r}
948
- ${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,o,!0),this.lexer.state.top=h,i.length===0)break;let g=o.at(-1);if(g?.type==="code")break;if(g?.type==="blockquote"){let y=g,P=y.raw+`
965
+ ${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 S=g,P=S.raw+`
949
966
  `+i.join(`
950
- `),I=this.blockquote(P);o[o.length-1]=I,s=s.substring(0,s.length-y.raw.length)+I.raw,r=r.substring(0,r.length-y.text.length)+I.text;break}else if(g?.type==="list"){let y=g,P=y.raw+`
967
+ `),C=this.blockquote(P);o[o.length-1]=C,s=s.substring(0,s.length-S.raw.length)+C.raw,r=r.substring(0,r.length-S.text.length)+C.text;break}else if(g?.type==="list"){let S=g,P=S.raw+`
951
968
  `+i.join(`
952
- `),I=this.list(P);o[o.length-1]=I,s=s.substring(0,s.length-g.raw.length)+I.raw,r=r.substring(0,r.length-y.raw.length)+I.raw,i=P.substring(o.at(-1).raw.length).split(`
953
- `);continue}}return{type:"blockquote",raw:s,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,r={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let o=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=cw(t[2].split(`
969
+ `),C=this.list(P);o[o.length-1]=C,s=s.substring(0,s.length-g.raw.length)+C.raw,r=r.substring(0,r.length-S.raw.length)+C.raw,i=P.substring(o.at(-1).raw.length).split(`
970
+ `);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 d=!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=py(t[2].split(`
954
971
  `,1)[0],t[1].length),g=e.split(`
955
- `,1)[0],y=!h.trim(),P=0;if(this.options.pedantic?(P=2,u=h.trimStart()):y?P=t[1].length+1:(P=h.search(this.rules.other.nonSpaceChar),P=P>4?1:P,u=h.slice(P),P+=t[1].length),y&&this.rules.other.blankLine.test(g)&&(p+=g+`
956
- `,e=e.substring(g.length+1),c=!0),!c){let I=this.rules.other.nextBulletRegex(P),G=this.rules.other.hrRegex(P),Ze=this.rules.other.fencesBeginRegex(P),ao=this.rules.other.headingBeginRegex(P),pc=this.rules.other.htmlBeginRegex(P),hc=this.rules.other.blockquoteBeginRegex(P);for(;e;){let ms=e.split(`
957
- `,1)[0],Dt;if(g=ms,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),Dt=g):Dt=g.replace(this.rules.other.tabCharGlobal," "),Ze.test(g)||ao.test(g)||pc.test(g)||hc.test(g)||I.test(g)||G.test(g))break;if(Dt.search(this.rules.other.nonSpaceChar)>=P||!g.trim())u+=`
958
- `+Dt.slice(P);else{if(y||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||Ze.test(h)||ao.test(h)||G.test(h))break;u+=`
959
- `+g}y=!g.trim(),p+=ms+`
960
- `,e=e.substring(ms.length+1),h=Dt.slice(P)}}r.loose||(n?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),r.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),r.raw+=p}let a=r.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let c of r.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let p=c.tokens[0];if(c.task&&(p?.type==="text"||p?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=h.checked,r.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=h.raw+c.tokens[0].raw,c.tokens[0].text=h.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(h)):c.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):c.tokens.unshift(h)}}else c.task&&(c.task=!1);if(!r.loose){let u=c.tokens.filter(g=>g.type==="space"),h=u.length>0&&u.some(g=>this.rules.other.anyLine.test(g.raw));r.loose=h}}if(r.loose)for(let c of r.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Jn(t[0]);return{type:"html",block:!0,raw:i,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:i}}}def(e){let t=this.rules.block.def.exec(e);if(t){let i=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:Xe(t[0],`
961
- `),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Gn(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
962
- `):[],o={type:"table",raw:Xe(t[0],`
963
- `),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?o.align.push("right"):this.rules.other.tableAlignCenter.test(n)?o.align.push("center"):this.rules.other.tableAlignLeft.test(n)?o.align.push("left"):o.align.push(null);for(let n=0;n<i.length;n++)o.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:o.align[n]});for(let n of r)o.rows.push(Gn(n,o.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:Xe(t[0],`
972
+ `,1)[0],S=!h.trim(),P=0;if(this.options.pedantic?(P=2,u=h.trimStart()):S?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),S&&this.rules.other.blankLine.test(g)&&(p+=g+`
973
+ `,e=e.substring(g.length+1),d=!0),!d){let C=this.rules.other.nextBulletRegex(P),X=this.rules.other.hrRegex(P),ot=this.rules.other.fencesBeginRegex(P),To=this.rules.other.headingBeginRegex(P),td=this.rules.other.htmlBeginRegex(P),id=this.rules.other.blockquoteBeginRegex(P);for(;e;){let Fs=e.split(`
974
+ `,1)[0],Ht;if(g=Fs,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting," "),Ht=g):Ht=g.replace(this.rules.other.tabCharGlobal," "),ot.test(g)||To.test(g)||td.test(g)||id.test(g)||C.test(g)||X.test(g))break;if(Ht.search(this.rules.other.nonSpaceChar)>=P||!g.trim())u+=`
975
+ `+Ht.slice(P);else{if(S||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ot.test(h)||To.test(h)||X.test(h))break;u+=`
976
+ `+g}S=!g.trim(),p+=Fs+`
977
+ `,e=e.substring(Fs.length+1),h=Ht.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 d of r.items){this.lexer.state.top=!1,d.tokens=this.lexer.blockTokens(d.text,[]);let p=d.tokens[0];if(d.task&&(p?.type==="text"||p?.type==="paragraph")){d.text=d.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(d.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};d.checked=h.checked,r.loose?d.tokens[0]&&["paragraph","text"].includes(d.tokens[0].type)&&"tokens"in d.tokens[0]&&d.tokens[0].tokens?(d.tokens[0].raw=h.raw+d.tokens[0].raw,d.tokens[0].text=h.raw+d.tokens[0].text,d.tokens[0].tokens.unshift(h)):d.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):d.tokens.unshift(h)}}else d.task&&(d.task=!1);if(!r.loose){let u=d.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 d of r.items){d.loose=!0;for(let p of d.tokens)p.type==="text"&&(p.type="paragraph")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=ka(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:nt(t[0],`
978
+ `),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=xa(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
979
+ `):[],o={type:"table",raw:nt(t[0],`
980
+ `),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(xa(n,o.header.length).map((a,d)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[d]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:nt(t[0],`
964
981
  `),depth:t[2].charAt(0)==="="?1:2,text:i,tokens:this.lexer.inline(i)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let i=t[1].charAt(t[1].length-1)===`
965
- `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let o=Xe(i.slice(0,-1),"\\");if((i.length-o.length)%2===0)return}else{let o=lw(t[2],"()");if(o===-2)return;if(o>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],r="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(s);o&&(s=o[1],r=o[3])}else r=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(i)?s=s.slice(1):s=s.slice(1,-1)),Qn(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:r&&r.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let s=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),r=t[s.toLowerCase()];if(!r){let o=i[0].charAt(0);return{type:"text",raw:o,text:o}}return Qn(i,r,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&i.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!i||this.rules.inline.punctuation.exec(i))){let r=[...s[0]].length-1,o,n,a=r,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+r);(s=p.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(n=[...o].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&r%3&&!((r+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let u=[...s[0]][0].length,h=e.slice(0,r+s.index+u+n);if(Math.min(r,n)%2){let y=h.slice(1,-1);return{type:"em",raw:h,text:y,tokens:this.lexer.inlineTokens(y)}}let g=h.slice(2,-2);return{type:"strong",raw:h,text:g,tokens:this.lexer.inlineTokens(g)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(i),r=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&r&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!i||this.rules.inline.punctuation.exec(i))){let r=[...s[0]].length-1,o,n,a=r,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+r);(s=c.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(n=[...o].length,n!==r))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,u=e.slice(0,r+s.index+p+n),h=u.slice(r,-r);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,s;return t[2]==="@"?(i=t[1],s="mailto:"+i):(i=t[1],s=i),{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:i}}}},Ae=class ar{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||gt,this.options.tokenizer=this.options.tokenizer||new Hi,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let i={other:ee,block:hi.normal,inline:Bt.normal};this.options.pedantic?(i.block=hi.pedantic,i.inline=Bt.pedantic):this.options.gfm&&(i.block=hi.gfm,this.options.breaks?i.inline=Bt.breaks:i.inline=Bt.gfm),this.tokenizer.rules=i}static get rules(){return{block:hi,inline:Bt}}static lex(t,i){return new ar(i).lex(t)}static lexInline(t,i){return new ar(i).inlineTokens(t)}lex(t){t=t.replace(ee.carriageReturn,`
966
- `),this.blockTokens(t,this.tokens);for(let i=0;i<this.inlineQueue.length;i++){let s=this.inlineQueue[i];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,i=[],s=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(ee.tabCharGlobal," ").replace(ee.spaceLine,""));let r=1/0;for(;t;){if(t.length<r)r=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},t,i))?(t=t.substring(o.raw.length),i.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let a=i.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
982
+ `?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=nt(i.slice(0,-1),"\\");if((i.length-o.length)%2===0)return}else{let o=dy(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)),$a(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 $a(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,d=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)){d+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+d);let u=[...s[0]][0].length,h=e.slice(0,r+s.index+u+n);if(Math.min(r,n)%2){let S=h.slice(1,-1);return{type:"em",raw:h,text:S,tokens:this.lexer.inlineTokens(S)}}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,d=this.rules.inline.delRDelim;for(d.lastIndex=0,t=t.slice(-1*e.length+r);(s=d.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}}}},Oe=class Ar{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ct,this.options.tokenizer=this.options.tokenizer||new ps,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:re,block:Mi.normal,inline:ei.normal};this.options.pedantic?(i.block=Mi.pedantic,i.inline=ei.pedantic):this.options.gfm&&(i.block=Mi.gfm,this.options.breaks?i.inline=ei.breaks:i.inline=ei.gfm),this.tokenizer.rules=i}static get rules(){return{block:Mi,inline:ei}}static lex(t,i){return new Ar(i).lex(t)}static lexInline(t,i){return new Ar(i).inlineTokens(t)}lex(t){t=t.replace(re.carriageReturn,`
983
+ `),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(re.tabCharGlobal," ").replace(re.spaceLine,""));let r=1/0;for(;t;){if(t.length<r)r=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},t,i))?(t=t.substring(o.raw.length),i.push(o),!0):!1))continue;if(o=this.tokenizer.space(t)){t=t.substring(o.raw.length);let a=i.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
967
984
  `:i.push(o);continue}if(o=this.tokenizer.code(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
968
985
  `)?"":`
969
986
  `)+o.raw,a.text+=`
970
987
  `+o.text,this.inlineQueue.at(-1).src=a.text):i.push(o);continue}if(o=this.tokenizer.fences(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.heading(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.hr(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.blockquote(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.list(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.html(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.def(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
971
988
  `)?"":`
972
989
  `)+o.raw,a.text+=`
973
- `+o.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},i.push(o));continue}if(o=this.tokenizer.table(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.lheading(t)){t=t.substring(o.raw.length),i.push(o);continue}let n=t;if(this.options.extensions?.startBlock){let a=1/0,c=t.slice(1),p;this.options.extensions.startBlock.forEach(u=>{p=u.call({lexer:this},c),typeof p=="number"&&p>=0&&(a=Math.min(a,p))}),a<1/0&&a>=0&&(n=t.substring(0,a+1))}if(this.state.top&&(o=this.tokenizer.paragraph(n))){let a=i.at(-1);s&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
990
+ `+o.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},i.push(o));continue}if(o=this.tokenizer.table(t)){t=t.substring(o.raw.length),i.push(o);continue}if(o=this.tokenizer.lheading(t)){t=t.substring(o.raw.length),i.push(o);continue}let n=t;if(this.options.extensions?.startBlock){let a=1/0,d=t.slice(1),p;this.options.extensions.startBlock.forEach(u=>{p=u.call({lexer:this},d),typeof p=="number"&&p>=0&&(a=Math.min(a,p))}),a<1/0&&a>=0&&(n=t.substring(0,a+1))}if(this.state.top&&(o=this.tokenizer.paragraph(n))){let a=i.at(-1);s&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
974
991
  `)?"":`
975
992
  `)+o.raw,a.text+=`
976
993
  `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o),s=n.length!==t.length,t=t.substring(o.raw.length);continue}if(o=this.tokenizer.text(t)){t=t.substring(o.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
977
994
  `)?"":`
978
995
  `)+o.raw,a.text+=`
979
- `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,r=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)o=r[2]?r[2].length:0,s=s.slice(0,r.index+o)+"["+"a".repeat(r[0].length-o-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",c=1/0;for(;t;){if(t.length<c)c=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let u=t;if(this.options.extensions?.startInline){let h=1/0,g=t.slice(1),y;this.options.extensions.startInline.forEach(P=>{y=P.call({lexer:this},g),typeof y=="number"&&y>=0&&(h=Math.min(h,y))}),h<1/0&&h>=0&&(u=t.substring(0,h+1))}if(p=this.tokenizer.inlineText(u)){t=t.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),n=!0;let h=i.at(-1);h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},qi=class{options;parser;constructor(e){this.options=e||gt}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(ee.notSpaceStart)?.[0],r=e.replace(ee.endingNewline,"")+`
980
- `;return s?'<pre><code class="language-'+Oe(s)+'">'+(i?r:Oe(r,!0))+`</code></pre>
981
- `:"<pre><code>"+(i?r:Oe(r,!0))+`</code></pre>
996
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(o);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,r=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)o=r[2]?r[2].length:0,s=s.slice(0,r.index+o)+"["+"a".repeat(r[0].length-o-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",d=1/0;for(;t;){if(t.length<d)d=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let u=t;if(this.options.extensions?.startInline){let h=1/0,g=t.slice(1),S;this.options.extensions.startInline.forEach(P=>{S=P.call({lexer:this},g),typeof S=="number"&&S>=0&&(h=Math.min(h,S))}),h<1/0&&h>=0&&(u=t.substring(0,h+1))}if(p=this.tokenizer.inlineText(u)){t=t.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),n=!0;let h=i.at(-1);h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},hs=class{options;parser;constructor(e){this.options=e||Ct}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(re.notSpaceStart)?.[0],r=e.replace(re.endingNewline,"")+`
997
+ `;return s?'<pre><code class="language-'+ze(s)+'">'+(i?r:ze(r,!0))+`</code></pre>
998
+ `:"<pre><code>"+(i?r:ze(r,!0))+`</code></pre>
982
999
  `}blockquote({tokens:e}){return`<blockquote>
983
1000
  ${this.parser.parse(e)}</blockquote>
984
1001
  `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
@@ -994,8 +1011,8 @@ ${this.parser.parse(e)}</blockquote>
994
1011
  `}tablerow({text:e}){return`<tr>
995
1012
  ${e}</tr>
996
1013
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
997
- `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Oe(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:i}){let s=this.parser.parseInline(i),r=Vn(e);if(r===null)return s;e=r;let o='<a href="'+e+'"';return t&&(o+=' title="'+Oe(t)+'"'),o+=">"+s+"</a>",o}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let r=Vn(e);if(r===null)return Oe(i);e=r;let o=`<img src="${e}" alt="${Oe(i)}"`;return t&&(o+=` title="${Oe(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Oe(e.text)}},ro=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Te=class lr{options;renderer;textRenderer;constructor(t){this.options=t||gt,this.options.renderer=this.options.renderer||new qi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new ro}static parse(t,i){return new lr(i).parse(t)}static parseInline(t,i){return new lr(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let r=t[s];if(this.options.extensions?.renderers?.[r.type]){let n=r,a=this.options.extensions.renderers[n.type].call({parser:this},n);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(n.type)){i+=a||"";continue}}let o=r;switch(o.type){case"space":{i+=this.renderer.space(o);break}case"hr":{i+=this.renderer.hr(o);break}case"heading":{i+=this.renderer.heading(o);break}case"code":{i+=this.renderer.code(o);break}case"table":{i+=this.renderer.table(o);break}case"blockquote":{i+=this.renderer.blockquote(o);break}case"list":{i+=this.renderer.list(o);break}case"checkbox":{i+=this.renderer.checkbox(o);break}case"html":{i+=this.renderer.html(o);break}case"def":{i+=this.renderer.def(o);break}case"paragraph":{i+=this.renderer.paragraph(o);break}case"text":{i+=this.renderer.text(o);break}default:{let n='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(n),"";throw new Error(n)}}}return i}parseInline(t,i=this.renderer){this.renderer.parser=this;let s="";for(let r=0;r<t.length;r++){let o=t[r];if(this.options.extensions?.renderers?.[o.type]){let a=this.options.extensions.renderers[o.type].call({parser:this},o);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){s+=a||"";continue}}let n=o;switch(n.type){case"escape":{s+=i.text(n);break}case"html":{s+=i.html(n);break}case"link":{s+=i.link(n);break}case"image":{s+=i.image(n);break}case"checkbox":{s+=i.checkbox(n);break}case"strong":{s+=i.strong(n);break}case"em":{s+=i.em(n);break}case"codespan":{s+=i.codespan(n);break}case"br":{s+=i.br(n);break}case"del":{s+=i.del(n);break}case"text":{s+=i.text(n);break}default:{let a='Token with "'+n.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return s}},Kt=class{options;block;constructor(e){this.options=e||gt}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Ae.lex:Ae.lexInline}provideParser(e=this.block){return e?Te.parse:Te.parseInline}},pw=class{defaults=Qr();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Te;Renderer=qi;TextRenderer=ro;Lexer=Ae;Tokenizer=Hi;Hooks=Kt;constructor(...e){this.use(...e)}walkTokens(e,t){let i=[];for(let s of e)switch(i=i.concat(t.call(this,s)),s.type){case"table":{let r=s;for(let o of r.header)i=i.concat(this.walkTokens(o.tokens,t));for(let o of r.rows)for(let n of o)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let r=s;i=i.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let n=r[o].flat(1/0);i=i.concat(this.walkTokens(n,t))}):r.tokens&&(i=i.concat(this.walkTokens(r.tokens,t)))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let s={...i};if(s.async=this.defaults.async||s.async||!1,i.extensions&&(i.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...n){let a=r.renderer.apply(this,n);return a===!1&&(a=o.apply(this,n)),a}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),i.renderer){let r=this.defaults.renderer||new qi(this.defaults);for(let o in i.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let n=o,a=i.renderer[n],c=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u||""}}s.renderer=r}if(i.tokenizer){let r=this.defaults.tokenizer||new Hi(this.defaults);for(let o in i.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let n=o,a=i.tokenizer[n],c=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u}}s.tokenizer=r}if(i.hooks){let r=this.defaults.hooks||new Kt;for(let o in i.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let n=o,a=i.hooks[n],c=r[n];Kt.passThroughHooks.has(o)?r[n]=p=>{if(this.defaults.async&&Kt.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await a.call(r,p);return c.call(r,h)})();let u=a.call(r,p);return c.call(r,u)}:r[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(r,p);return h===!1&&(h=await c.apply(r,p)),h})();let u=a.apply(r,p);return u===!1&&(u=c.apply(r,p)),u}}s.hooks=r}if(i.walkTokens){let r=this.defaults.walkTokens,o=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(o.call(this,n)),r&&(a=a.concat(r.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ae.lex(e,t??this.defaults)}parser(e,t){return Te.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},r={...this.defaults,...s},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&s.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return o(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let n=r.hooks?await r.hooks.preprocess(t):t,a=await(r.hooks?await r.hooks.provideLexer(e):e?Ae.lex:Ae.lexInline)(n,r),c=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(c,r.walkTokens));let p=await(r.hooks?await r.hooks.provideParser(e):e?Te.parse:Te.parseInline)(c,r);return r.hooks?await r.hooks.postprocess(p):p})().catch(o);try{r.hooks&&(t=r.hooks.preprocess(t));let n=(r.hooks?r.hooks.provideLexer(e):e?Ae.lex:Ae.lexInline)(t,r);r.hooks&&(n=r.hooks.processAllTokens(n)),r.walkTokens&&this.walkTokens(n,r.walkTokens);let a=(r.hooks?r.hooks.provideParser(e):e?Te.parse:Te.parseInline)(n,r);return r.hooks&&(a=r.hooks.postprocess(a)),a}catch(n){return o(n)}}}onError(e,t){return i=>{if(i.message+=`
998
- Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Oe(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},ut=new pw;function O(e,t){return ut.parse(e,t)}O.options=O.setOptions=function(e){return ut.setOptions(e),O.defaults=ut.defaults,Ul(O.defaults),O};O.getDefaults=Qr;O.defaults=gt;O.use=function(...e){return ut.use(...e),O.defaults=ut.defaults,Ul(O.defaults),O};O.walkTokens=function(e,t){return ut.walkTokens(e,t)};O.parseInline=ut.parseInline;O.Parser=Te;O.parser=Te.parse;O.Renderer=qi;O.TextRenderer=ro;O.Lexer=Ae;O.lexer=Ae.lex;O.Tokenizer=Hi;O.Hooks=Kt;O.parse=O;O.options;O.setOptions;O.use;O.walkTokens;O.parseInline;Te.parse;Ae.lex;const Zl=new O.Renderer;Zl.html=({text:e})=>fw(e);const hw=300,Nt=new Map;function uw(e){const t=Nt.get(e);if(t!==void 0)return t;const i=O.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:Zl}),s=gw(i);if(Nt.set(e,s),Nt.size>hw){const r=Nt.keys().next().value;r!==void 0&&Nt.delete(r)}return s}function fw(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function gw(e){const t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("script, style, iframe, object, embed").forEach(i=>{i.remove()}),t.content.querySelectorAll("*").forEach(i=>{for(const s of[...i.attributes]){const r=s.name.toLowerCase();r.startsWith("on")&&i.removeAttribute(s.name),(r==="href"||r==="src")&&!mw(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function mw(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var vw=Object.defineProperty,bw=Object.getOwnPropertyDescriptor,Xl=(e,t,i,s)=>{for(var r=s>1?void 0:s?bw(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&vw(t,i,r),r};const ww=D`
1014
+ `}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>${ze(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=Sa(e);if(r===null)return s;e=r;let o='<a href="'+e+'"';return t&&(o+=' title="'+ze(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=Sa(e);if(r===null)return ze(i);e=r;let o=`<img src="${e}" alt="${ze(i)}"`;return t&&(o+=` title="${ze(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:ze(e.text)}},Ro=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Fe=class Mr{options;renderer;textRenderer;constructor(t){this.options=t||Ct,this.options.renderer=this.options.renderer||new hs,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ro}static parse(t,i){return new Mr(i).parse(t)}static parseInline(t,i){return new Mr(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}},ai=class{options;block;constructor(e){this.options=e||Ct}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?Oe.lex:Oe.lexInline}provideParser(e=this.block){return e?Fe.parse:Fe.parseInline}},uy=class{defaults=wo();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Fe;Renderer=hs;TextRenderer=Ro;Lexer=Oe;Tokenizer=ps;Hooks=ai;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 hs(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],d=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=d.apply(r,p)),u||""}}s.renderer=r}if(i.tokenizer){let r=this.defaults.tokenizer||new ps(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],d=r[n];r[n]=(...p)=>{let u=a.apply(r,p);return u===!1&&(u=d.apply(r,p)),u}}s.tokenizer=r}if(i.hooks){let r=this.defaults.hooks||new ai;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],d=r[n];ai.passThroughHooks.has(o)?r[n]=p=>{if(this.defaults.async&&ai.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await a.call(r,p);return d.call(r,h)})();let u=a.call(r,p);return d.call(r,u)}:r[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(r,p);return h===!1&&(h=await d.apply(r,p)),h})();let u=a.apply(r,p);return u===!1&&(u=d.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 Oe.lex(e,t??this.defaults)}parser(e,t){return Fe.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?Oe.lex:Oe.lexInline)(n,r),d=r.hooks?await r.hooks.processAllTokens(a):a;r.walkTokens&&await Promise.all(this.walkTokens(d,r.walkTokens));let p=await(r.hooks?await r.hooks.provideParser(e):e?Fe.parse:Fe.parseInline)(d,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?Oe.lex:Oe.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?Fe.parse:Fe.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+=`
1015
+ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+ze(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},$t=new uy;function O(e,t){return $t.parse(e,t)}O.options=O.setOptions=function(e){return $t.setOptions(e),O.defaults=$t.defaults,Pc(O.defaults),O};O.getDefaults=wo;O.defaults=Ct;O.use=function(...e){return $t.use(...e),O.defaults=$t.defaults,Pc(O.defaults),O};O.walkTokens=function(e,t){return $t.walkTokens(e,t)};O.parseInline=$t.parseInline;O.Parser=Fe;O.parser=Fe.parse;O.Renderer=hs;O.TextRenderer=Ro;O.Lexer=Oe;O.lexer=Oe.lex;O.Tokenizer=ps;O.Hooks=ai;O.parse=O;O.options;O.setOptions;O.use;O.walkTokens;O.parseInline;Fe.parse;Oe.lex;const Lc=new O.Renderer;Lc.html=({text:e})=>my(e);const fy=300,ti=new Map;function gy(e){const t=ti.get(e);if(t!==void 0)return t;const i=O.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:Lc}),s=vy(i);if(ti.set(e,s),ti.size>fy){const r=ti.keys().next().value;r!==void 0&&ti.delete(r)}return s}function my(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function vy(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")&&!by(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function by(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var wy=Object.defineProperty,yy=Object.getOwnPropertyDescriptor,Oc=(e,t,i,s)=>{for(var r=s>1?void 0:s?yy(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};const Sy=D`
999
1016
  :host { display: block; }
1000
1017
  .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
1001
1018
  p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
@@ -1020,60 +1037,71 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1020
1037
  table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
1021
1038
  th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
1022
1039
  th { background: var(--pi-surface); }
1023
- `;let Ki=class extends R{constructor(){super(...arguments),this.text="",this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;const t=e.target.closest(".code-copy-button");if(!(t instanceof HTMLButtonElement))return;const i=t.closest(".code-block-wrapper");if(!(i instanceof HTMLElement))return;const s=i.querySelector("pre code");s instanceof HTMLElement&&this.copyCode(s.textContent,t)}}render(){return l`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${$b(uw(this.text))}</div>`}updated(){this.enhanceCodeBlocks()}enhanceCodeBlocks(){this.renderRoot.querySelectorAll("pre").forEach(e=>{if(!(e instanceof HTMLPreElement)||e.parentElement?.classList.contains("code-block-wrapper")===!0||!(e.querySelector("code")instanceof HTMLElement))return;const i=document.createElement("div");i.className="code-block-wrapper";const s=document.createElement("button");s.type="button",s.className="code-copy-button",s.title="复制代码块",s.setAttribute("aria-label","复制代码块");const r=document.createElement("span");r.setAttribute("aria-hidden","true"),r.textContent="⧉",s.append(r),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await Gr(e);this.setCopyButtonState(t,i?"copied":"failed"),window.setTimeout(()=>{this.setCopyButtonState(t,"idle")},1200)}setCopyButtonState(e,t){const i=e.querySelector("span");i!==null&&(i.textContent=t==="copied"?"✓":"⧉");const s=t==="copied"?"已复制代码块":t==="failed"?"复制代码块失败":"复制代码块";e.title=s,e.setAttribute("aria-label",s)}};Ki.styles=ww;Xl([d()],Ki.prototype,"text",2);Ki=Xl([W("formatted-text")],Ki);var yw=Object.defineProperty,xw=Object.getOwnPropertyDescriptor,ni=(e,t,i,s)=>{for(var r=s>1?void 0:s?xw(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&yw(t,i,r),r};const Zn=180;let ft=class extends R{constructor(){super(...arguments),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){const e=this.execution;if(e===void 0)return null;const t=e.toolName==="edit",i=Sw(e.args),s=kw(e.details),r=e.preview,o=s??r?.diff,n=o===void 0?void 0:$w(o),a=s!==void 0&&r?.diff!==void 0&&s!==r.diff,c=e.status==="error"?e.resultText:r?.error,p=o===void 0?e.resultText:void 0;return l`
1040
+ `;let us=class extends I{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}>${Cw(gy(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 mo(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)}};us.styles=Sy;Oc([c()],us.prototype,"text",2);us=Oc([W("formatted-text")],us);var xy=Object.defineProperty,ky=Object.getOwnPropertyDescriptor,ki=(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&&xy(t,i,r),r};const Pa=180;let Pt=class extends I{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=Py(e.args),i=Cy(e.details),s=e.preview,r=i??s?.diff,o=r===void 0?void 0:Ry(r),n=i!==void 0&&s?.diff!==void 0&&i!==s.diff,a=e.status==="error"?e.resultText:s?.error,d=r===void 0?e.resultText:void 0,p=$y(e,t);return l`
1024
1041
  <section class=${`tool-card ${e.status}`}>
1025
1042
  <div class="tool-header">
1026
1043
  <div class="tool-title">
1027
- <span class="status-icon" aria-hidden="true">${Cw(e.status)}</span>
1044
+ <span class="status-icon" aria-hidden="true">${Ay(e.status)}</span>
1028
1045
  <strong>${e.toolName}</strong>
1029
- ${i===void 0?l`<span class="summary">${e.summary}</span>`:l`<span class="path">${i}</span>`}
1046
+ ${this.renderHeaderTarget(p)}
1030
1047
  </div>
1031
1048
  <div class="tool-meta">
1032
- ${Xn(e)===void 0?null:l`<span>${Xn(e)}</span>`}
1033
- ${n===void 0?null:l`<span class="diff-stats"><b class="added">+${n.added}</b><span>/</span><b class="removed">-${n.removed}</b></span>`}
1034
- <span class="status-label">${Iw(e.status)}</span>
1049
+ ${Ca(e)===void 0?null:l`<span>${Ca(e)}</span>`}
1050
+ ${o===void 0?null:l`<span class="diff-stats"><b class="added">+${o.added}</b><span>/</span><b class="removed">-${o.removed}</b></span>`}
1051
+ <span class="status-label">${My(e.status)}</span>
1035
1052
  </div>
1036
1053
  </div>
1037
1054
 
1038
- ${a?l`<p class="notice">实际应用的 diff 与预览不同。</p>`:null}
1039
- ${c===void 0||c===""?null:l`<pre class="error-text">${c}</pre>`}
1040
- ${o===void 0?this.renderTextBody(p,e.status==="error"):this.renderDiffBody(o,s===void 0?"预览 diff":"已应用 diff")}
1041
- ${!t&&o===void 0&&(p===void 0||p==="")?l`<p class="muted">${e.summary}</p>`:null}
1055
+ ${n?l`<p class="notice">实际应用的 diff 与预览不同。</p>`:null}
1056
+ ${a===void 0||a===""?null:l`<pre class="error-text">${a}</pre>`}
1057
+ ${r===void 0?this.renderTextBody(d,e.status==="error",p):this.renderDiffBody(r,i===void 0?"预览 diff":"已应用 diff",p)}
1042
1058
  </section>
1043
- `}renderTextBody(e,t){return e===void 0||e===""?null:l`
1059
+ `}renderHeaderTarget(e){if(e===void 0)return null;const t=e.label==="File"?"path":"summary";return l`<span class=${t} title=${e.text} aria-label=${`${e.label}: ${e.text}`}>${e.text}</span>`}renderExpandedTarget(e){return e===void 0?null:l`
1060
+ <div class="detail-target">
1061
+ <span class="detail-label">${e.label}</span>
1062
+ <pre class="detail-target-value">${e.text}</pre>
1063
+ </div>
1064
+ `}renderTextBody(e,t,i){return(e===void 0||e==="")&&i===void 0?null:l`
1044
1065
  <details class="text-body" ?open=${t}>
1045
- <summary>结果</summary>
1046
- <pre>${e}</pre>
1066
+ <summary>详情</summary>
1067
+ ${this.renderExpandedTarget(i)}
1068
+ ${e===void 0||e===""?null:l`
1069
+ <div class="detail-result">
1070
+ <span class="detail-label">结果</span>
1071
+ <pre>${e}</pre>
1072
+ </div>
1073
+ `}
1047
1074
  </details>
1048
- `}renderDiffBody(e,t){const i=e.split(`
1049
- `),s=!this.showFullDiff&&i.length>Zn,r=s?i.slice(0,Zn):i;return l`
1050
- <details class="diff-details" ?open=${this.diffOpen} @toggle=${o=>{this.onDiffToggle(o)}}>
1075
+ `}renderDiffBody(e,t,i){const s=e.split(`
1076
+ `),r=!this.showFullDiff&&s.length>Pa,o=r?s.slice(0,Pa):s;return l`
1077
+ <details class="diff-details" ?open=${this.diffOpen} @toggle=${n=>{this.onDiffToggle(n)}}>
1051
1078
  <summary>
1052
1079
  <span>${t}</span>
1053
- <small>${String(i.length)} 行</small>
1080
+ <small>${String(s.length)} 行</small>
1054
1081
  </summary>
1082
+ ${this.renderExpandedTarget(i)}
1055
1083
  <div class="diff-toolbar">
1056
- <span>${s?`显示 ${String(r.length)} / ${String(i.length)} 行`:"完整 diff"}</span>
1084
+ <span>${r?`显示 ${String(o.length)} / ${String(s.length)} 行`:"完整 diff"}</span>
1057
1085
  <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"已复制":"复制 diff"}</button>
1058
1086
  </div>
1059
- <pre class="diff" aria-label=${t}><code class="diff-content">${r.map(o=>l`<span class=${Pw(o)}>${o}</span>`)}</code></pre>
1060
- ${s?l`
1087
+ <pre class="diff" aria-label=${t}><code class="diff-content">${o.map(n=>l`<span class=${Iy(n)}>${n}</span>`)}</code></pre>
1088
+ ${r?l`
1061
1089
  <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
1062
- 显示全部 ${String(i.length)} 行 diff
1090
+ 显示全部 ${String(s.length)} 行 diff
1063
1091
  </button>
1064
1092
  `:null}
1065
1093
  </details>
1066
- `}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){const t=await Gr(e);this.copied=t,t&&window.setTimeout(()=>{this.copied=!1},1200)}};ft.styles=D`
1094
+ `}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await mo(e)){this.copied=!1;return}this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}};Pt.styles=D`
1067
1095
  :host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
1068
1096
  .tool-card { display: grid; gap: 8px; width: 100%; max-width: 100%; min-width: 0; box-sizing: border-box; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 9px; color: var(--pi-text); }
1069
1097
  .tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
1070
1098
  .tool-card.success { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
1071
1099
  .tool-card.error { border-color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); }
1072
1100
  .tool-header { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; min-width: 0; }
1073
- .tool-title { display: inline-flex; align-items: baseline; gap: 7px; min-width: 0; }
1101
+ .tool-title { flex: 1 1 auto; display: inline-flex; align-items: baseline; gap: 7px; min-width: 0; }
1074
1102
  .status-icon { flex: 0 0 auto; color: var(--pi-muted); }
1075
- strong { color: var(--pi-text); }
1076
- .path, .summary { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--pi-accent); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1103
+ strong { flex: 0 0 auto; color: var(--pi-text); }
1104
+ .path, .summary { display: block; flex: 1 1 auto; min-width: 0; max-width: 100%; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; white-space: pre; color: var(--pi-accent); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; direction: ltr; text-align: left; unicode-bidi: isolate; }
1077
1105
  .summary { color: var(--pi-muted); font-family: inherit; }
1078
1106
  .tool-meta { flex: 0 0 auto; display: inline-flex; align-items: baseline; gap: 8px; color: var(--pi-muted); font-size: 12px; }
1079
1107
  .diff-stats { display: inline-flex; gap: 3px; }
@@ -1084,7 +1112,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1084
1112
  .muted { margin: 0; color: var(--pi-muted); }
1085
1113
  .error-text { margin: 0; border: 1px solid var(--pi-danger); border-radius: 7px; background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); color: var(--pi-danger); padding: 8px; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
1086
1114
  .text-body { border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
1087
- .text-body pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: var(--pi-text); }
1115
+ .detail-target, .detail-result { display: grid; gap: 4px; margin-top: 8px; min-width: 0; }
1116
+ .detail-label { color: var(--pi-muted); font-size: 12px; text-transform: uppercase; letter-spacing: .04em; }
1117
+ .text-body pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: var(--pi-text); }
1118
+ .detail-result pre { box-sizing: border-box; max-width: 100%; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; border: 1px solid var(--pi-border-muted); border-radius: 7px; background: var(--pi-bg); padding: 8px; white-space: pre; overflow-wrap: normal; direction: ltr; text-align: left; unicode-bidi: isolate; }
1119
+ .detail-target-value { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; color: var(--pi-accent); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; direction: ltr; text-align: left; unicode-bidi: isolate; }
1088
1120
  .diff-details { min-width: 0; max-width: 100%; border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
1089
1121
  .diff-details > summary { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; min-width: 0; color: var(--pi-muted); cursor: pointer; }
1090
1122
  .diff-details > summary span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -1103,19 +1135,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1103
1135
  .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
1104
1136
  .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
1105
1137
  .show-more { justify-self: start; }
1106
- `;ni([d({attribute:!1})],ft.prototype,"execution",2);ni([w()],ft.prototype,"showFullDiff",2);ni([w()],ft.prototype,"copied",2);ni([w()],ft.prototype,"diffOpen",2);ft=ni([W("tool-execution-view")],ft);function Sw(e){return cr(e,"path")??cr(e,"file_path")}function Xn(e){if(e.toolName!=="edit")return;const t=Ci(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof Ci(e.args,"oldText")=="string"&&typeof Ci(e.args,"newText")=="string")return"1 处编辑"}function kw(e){return cr(e,"diff")}function $w(e){let t=0,i=0;for(const s of e.split(`
1107
- `))Yl(s)?t++:ec(s)&&i++;return{added:t,removed:i}}function Pw(e){return Yl(e)?"added":ec(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function Yl(e){return e.startsWith("+")&&!e.startsWith("+++")}function ec(e){return e.startsWith("-")&&!e.startsWith("---")}function Cw(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function Iw(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function Rw(e){return typeof e=="object"&&e!==null}function Ci(e,t){return Rw(e)?e[t]:void 0}function cr(e,t){const i=Ci(e,t);return typeof i=="string"?i:void 0}var Aw=Object.defineProperty,Tw=Object.getOwnPropertyDescriptor,H=(e,t,i,s)=>{for(var r=s>1?void 0:s?Tw(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Aw(t,i,r),r};const Mw=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Ew=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),_s=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"],Dw={active:"活跃","agent running":"助手运行中","bash complete":"Shell 已完成","bash failed":"Shell 失败","compaction complete":"压缩已完成","compaction failed":"压缩失败",compacting:"正在压缩","duplicate queued message ignored":"已忽略重复排队消息",error:"错误",idle:"空闲","message complete":"消息已完成","message queued":"消息已排队","message queued during compaction":"压缩期间消息已排队","message started":"消息已开始","prompt accepted":"提示已接受",queued:"已排队","receiving response":"正在接收回复","running bash":"Shell 运行中","running tool":"工具运行中","steering queued":"引导已排队",stopped:"已停止","tool complete":"工具已完成","tool failed":"工具失败","turn complete":"回合已完成"};function Yn(){return _s[Math.floor(Math.random()*_s.length)]??_s[0]}function ea(e){return Ii(e,0,100)}function Ii(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let z=class extends R{constructor(){super(...arguments),this.messages=[],this.sessionId="",this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isReceivingPartialStream=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.disclosures=new Kv,this.scrollController=new mb,this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onPageHide=()=>{this.saveScrollPosition()}}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.onViewportResize),window.addEventListener("pagehide",this.onPageHide),window.visualViewport?.addEventListener("resize",this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),window.removeEventListener("resize",this.onViewportResize),window.removeEventListener("pagehide",this.onPageHide),window.visualViewport?.removeEventListener("resize",this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!="string"||e===""||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has("sessionId")&&(this.savePreviousSessionScrollPosition(e.get("sessionId")),this.prepareSessionUiState()),(e.has("isReceivingPartialStream")||e.has("sessionId")&&this.isReceivingPartialStream)&&this.syncPartialStreamNoticeBody(),e.has("messages")&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){const t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),t!==void 0&&this.restorePrependScrollAnchor(t)}updated(e){e.has("loadingMore")&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has("hasMore")&&!this.hasMore&&(this.loadMoreRequested=!1),e.has("sessionId")&&this.restoreScrollPosition(),!e.has("sessionId")&&e.has("messages")&&this.pinnedToBottom&&this.scrollToBottom(),(e.has("messages")||e.has("messageStart")||e.has("messageTotal")||e.has("hasMore")||e.has("loadingMore"))&&this.scheduleConversationRailUpdate(),(e.has("messages")||e.has("messageStart")||e.has("hasMore")||e.has("loadingMore"))&&this.continuePendingScrollRestore(),(e.has("messages")||e.has("hasMore")||e.has("loadingMore"))&&this.requestLoadMoreIfNeeded()}render(){const e=this.groupedMessages();return l`
1138
+ `;ki([c({attribute:!1})],Pt.prototype,"execution",2);ki([v()],Pt.prototype,"showFullDiff",2);ki([v()],Pt.prototype,"copied",2);ki([v()],Pt.prototype,"diffOpen",2);Pt=ki([W("tool-execution-view")],Pt);function $y(e,t){if(t!==void 0&&t!=="")return{label:"File",text:t};const i=fs(e.args,"command");if(i!==void 0&&i!=="")return{label:"Command",text:i};if(e.summary!=="")return{label:"Input",text:e.summary}}function Py(e){return fs(e,"path")??fs(e,"file_path")}function Ca(e){if(e.toolName!=="edit")return;const t=Ki(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof Ki(e.args,"oldText")=="string"&&typeof Ki(e.args,"newText")=="string")return"1 处编辑"}function Cy(e){return fs(e,"diff")}function Ry(e){let t=0,i=0;for(const s of e.split(`
1139
+ `))Fc(s)?t++:_c(s)&&i++;return{added:t,removed:i}}function Iy(e){return Fc(e)?"added":_c(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function Fc(e){return e.startsWith("+")&&!e.startsWith("+++")}function _c(e){return e.startsWith("-")&&!e.startsWith("---")}function Ay(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function My(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function Ty(e){return typeof e=="object"&&e!==null}function Ki(e,t){return Ty(e)?e[t]:void 0}function fs(e,t){const i=Ki(e,t);return typeof i=="string"?i:void 0}var Ey=Object.defineProperty,Dy=Object.getOwnPropertyDescriptor,H=(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};const Wy=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Ly=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),nr=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"],Oy={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 Ra(){return nr[Math.floor(Math.random()*nr.length)]??nr[0]}function Ia(e){return Vi(e,0,100)}function Vi(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}function Fy(e,t){return[e.length===0?void 0:{heading:"等待会话启动",detail:"后端会话准备好后将自动发送",messages:e},t.length===0?void 0:{heading:"排队消息",detail:`${String(t.length)} 条待处理 · 停止会清空队列`,messages:t}].filter(i=>i!==void 0)}let N=class extends I{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.clientQueuedMessages=[],this.pinnedToBottom=!0,this.disclosures=new zb,this.scrollController=new bw,this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onPageHide=()=>{this.saveScrollPosition()}}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.onViewportResize),window.addEventListener("pagehide",this.onPageHide),window.visualViewport?.addEventListener("resize",this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),window.removeEventListener("resize",this.onViewportResize),window.removeEventListener("pagehide",this.onPageHide),window.visualViewport?.removeEventListener("resize",this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!="string"||e===""||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has("sessionId")&&(this.savePreviousSessionScrollPosition(e.get("sessionId")),this.prepareSessionUiState()),(e.has("isReceivingPartialStream")||e.has("sessionId")&&this.isReceivingPartialStream)&&this.syncPartialStreamNoticeBody(),e.has("messages")&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){const t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),t!==void 0&&this.restorePrependScrollAnchor(t)}updated(e){e.has("loadingMore")&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has("hasMore")&&!this.hasMore&&(this.loadMoreRequested=!1),e.has("sessionId")&&this.restoreScrollPosition(),!e.has("sessionId")&&e.has("messages")&&this.pinnedToBottom&&this.scrollToBottom(),(e.has("messages")||e.has("messageStart")||e.has("messageTotal")||e.has("hasMore")||e.has("loadingMore"))&&this.scheduleConversationRailUpdate(),(e.has("messages")||e.has("messageStart")||e.has("hasMore")||e.has("loadingMore"))&&this.continuePendingScrollRestore(),(e.has("messages")||e.has("hasMore")||e.has("loadingMore"))&&this.requestLoadMoreIfNeeded()}render(){const e=this.groupedMessages();return l`
1108
1140
  <div class="chat-wrap">
1109
1141
  ${this.renderConversationRail()}
1110
1142
  <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
1111
1143
  ${this.renderHistoryBoundary()}
1112
- ${Nv(e,t=>t.kind==="message"?this.messageAnchorKey(t.index):this.groupRenderKey(t.startIndex),(t,i)=>t.kind==="message"?this.renderMessage(t.message,t.index):this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,i)))}
1144
+ ${jb(e,t=>t.kind==="message"?this.messageAnchorKey(t.index):this.groupRenderKey(t.startIndex),(t,i)=>t.kind==="message"?this.renderMessage(t.message,t.index):this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,i)))}
1113
1145
  ${this.renderQueuedMessages()}
1114
1146
  ${this.renderSessionActivity()}
1115
1147
  </div>
1116
1148
  ${this.renderActivityDock()}
1117
1149
  </div>
1118
- `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Jv(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){if(this.isSendingPrompt)return l`
1150
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Hb(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){if(this.isSendingPrompt)return l`
1119
1151
  <div class="activity-dock active" aria-live="polite">
1120
1152
  <span class="dot"></span>
1121
1153
  <span class="activity-text">正在发送你的消息…</span>
@@ -1125,13 +1157,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1125
1157
  <span class="dot"></span>
1126
1158
  <span class="activity-text">${this.activityText(e)}</span>
1127
1159
  </div>
1128
- `}renderQueuedMessages(){const e=this.status?.queuedMessages??[];return e.length===0?null:l`
1160
+ `}renderQueuedMessages(){const e=this.status?.queuedMessages??[];return l`${Fy(this.clientQueuedMessages,e).map(t=>this.renderQueuedMessageList(t))}`}renderQueuedMessageList(e){return l`
1129
1161
  <aside class="queued-messages" aria-live="polite">
1130
1162
  <div class="queued-header">
1131
- <strong>排队消息</strong>
1132
- <small>${e.length} 条待处理 · 停止会清空队列</small>
1163
+ <strong>${e.heading}</strong>
1164
+ <small>${e.detail}</small>
1133
1165
  </div>
1134
- ${e.map((t,i)=>l`
1166
+ ${e.messages.map((t,i)=>l`
1135
1167
  <div class="queued-message">
1136
1168
  <span class="queued-kind">${t.kind==="steer"?"引导":"跟进"} ${String(i+1)}</span>
1137
1169
  ${t.imageCount!==void 0&&t.imageCount>0?l`<small>含 ${t.imageCount} 张图片</small>`:null}
@@ -1150,7 +1182,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1150
1182
  <span>助手正在总结早前上下文。压缩完成前,新提示会排队等待。</span>
1151
1183
  ${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} 条消息已排队</small>`:null}
1152
1184
  </aside>
1153
- `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Yn():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Yn(),this.partialStreamNoticeBody}activityState(){const e=this.status;return e===void 0?this.activity?.label:e.isCompacting?"compacting":e.isBashRunning?"bash":e.isStreaming?"running":e.pendingMessageCount>0?"queued":"idle"}activityText(e){const t=this.activity;if(t===void 0||e!=="idle"&&t.phase==="idle")return Ls(e);const i=Ls(t.label);return t.detail!==void 0&&t.detail!==""?`${i}: ${t.detail}`:i}renderConversationRail(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.conversationDisplayTotal(),t=this.conversationPositionPercent(e),i=this.hasMore?ea(this.messages.length/e*100):100;return l`<conversation-meter .positionPercent=${t} .loadedPercent=${i}></conversation-meter>`}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;const t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,i=Ii(this.currentConversationIndex??t,0,e-1);return ea(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?l`
1185
+ `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Ra():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Ra(),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 ar(e);const i=ar(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?Ia(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=Vi(this.currentConversationIndex??t,0,e-1);return Ia(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?l`
1154
1186
  <div class="history-boundary">
1155
1187
  <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>加载更早的消息</button>
1156
1188
  <span>向上滚动加载更早的消息</span>
@@ -1167,12 +1199,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1167
1199
  <details class=${s?"msg event-group live":"msg event-group"} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${o} @toggle=${n=>{this.onGroupToggle(r,n,s)}}>
1168
1200
  <summary>
1169
1201
  <b class="label">${s?"实时事件":"事件"}</b>
1170
- <span>${Qv(e)}</span>
1202
+ <span>${Kb(e)}</span>
1171
1203
  </summary>
1172
1204
  <div class="group-body">
1173
- ${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
1174
- <section class=${c?"group-msg tool-execution-shell":`group-msg ${n.role}`} data-index=${t+a} data-scroll-anchor-id=${this.eventAnchorKey(t+a)}>
1175
- ${c?null:this.renderMessageHeader(n,`${String(t)}:${String(a)}`)}
1205
+ ${e.map((n,a)=>{const d=this.isToolExecutionOnlyMessage(n);return l`
1206
+ <section class=${d?"group-msg tool-execution-shell":`group-msg ${n.role}`} data-index=${t+a} data-scroll-anchor-id=${this.eventAnchorKey(t+a)}>
1207
+ ${d?null:this.renderMessageHeader(n,`${String(t)}:${String(a)}`)}
1176
1208
  ${n.parts.map(p=>this.renderPart(p,n))}
1177
1209
  </section>
1178
1210
  `})}
@@ -1180,7 +1212,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1180
1212
  </details>
1181
1213
  `}renderScrollMarker(e){return l`<span class="scroll-marker" data-marker-id=${e} aria-hidden="true"></span>`}renderMessageHeader(e,t){const i=this.messageMetaLabel(e),s=this.expandedMetaKey===t;return l`
1182
1214
  <div class="msg-header">
1183
- <b class="label">${ta(e.role)}</b>
1215
+ <b class="label">${Aa(e.role)}</b>
1184
1216
  <div class="msg-header-trailing">
1185
1217
  ${this.renderMessageActions(e,t)}
1186
1218
  <span class=${s?"msg-meta expanded":"msg-meta"} role="button" tabindex="0" title=${i.full} aria-label=${i.full} aria-expanded=${String(s)} @click=${()=>{this.expandedMetaKey=s?void 0:t}} @keydown=${r=>{this.onMetaKeydown(r,t,s)}}>${i.short}</span>
@@ -1188,13 +1220,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1188
1220
  </div>
1189
1221
  `}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return l`
1190
1222
  <div class="msg-actions" aria-label="消息操作">
1191
- <button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${ta(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
1223
+ <button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${Aa(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
1192
1224
  <span aria-hidden="true">${i?"✓":"⧉"}</span>
1193
1225
  </button>
1194
1226
  </div>
1195
1227
  `}onMetaKeydown(e,t,i){e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),this.expandedMetaKey=i?void 0:t)}isCopyableMessage(e){return(e.role==="user"||e.role==="assistant")&&this.messageCopyText(e)!==""}messageCopyText(e){const t=this.messageCopyTextCache.get(e);if(t!==void 0)return t;const i=e.parts.filter(s=>s.type==="text").map(s=>s.text.trim()).filter(s=>s!=="").join(`
1196
1228
 
1197
- `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await Gr(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const c={short:"无信息",full:"没有可用的 Pi 消息元数据"};return this.messageMetaCache.set(e,c),c}const r=i===void 0?void 0:this.formatTimestamp(i),o=[r?.short,s].filter(c=>c!==void 0&&c!==""),n=[r?.full,s===void 0?void 0:`模型:${s}`].filter(c=>c!==void 0&&c!==""),a={short:o.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:Mw.format(t),full:Ew.format(t)}}modelLabel(e){const t=e.meta?.model;if(t===void 0)return;const i=t.responseId??t.id;return i===void 0||i===""?t.provider:t.provider!==void 0&&t.provider!==""?`${t.provider}/${i}`:i}renderPart(e,t){return e.type==="text"&&t?.role==="bash"?l`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?l`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="image"?l`<figure class="part chat-image"><img src=${`data:${e.mimeType};base64,${e.data}`} alt="用户上传的图片" loading="lazy"></figure>`:e.type==="thinking"?l`<details class="part"><summary>思考</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
1229
+ `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await mo(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 d={short:"无信息",full:"没有可用的 Pi 消息元数据"};return this.messageMetaCache.set(e,d),d}const r=i===void 0?void 0:this.formatTimestamp(i),o=[r?.short,s].filter(d=>d!==void 0&&d!==""),n=[r?.full,s===void 0?void 0:`模型:${s}`].filter(d=>d!==void 0&&d!==""),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:Wy.format(t),full:Ly.format(t)}}modelLabel(e){const t=e.meta?.model;if(t===void 0)return;const i=t.responseId??t.id;return i===void 0||i===""?t.provider:t.provider!==void 0&&t.provider!==""?`${t.provider}/${i}`:i}renderPart(e,t){return e.type==="text"&&t?.role==="bash"?l`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?l`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="image"?l`<figure class="part chat-image"><img src=${`data:${e.mimeType};base64,${e.data}`} alt="用户上传的图片" loading="lazy"></figure>`:e.type==="thinking"?l`<details class="part"><summary>思考</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
1198
1230
  <details class="part skill-invocation">
1199
1231
  <summary><b>[技能]</b> ${e.name}</summary>
1200
1232
  <small>${e.location}</small>
@@ -1210,31 +1242,31 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1210
1242
  <summary>${e.isError?"✖":"✓"} ${e.toolName} 结果</summary>
1211
1243
  <formatted-text .text=${e.text}></formatted-text>
1212
1244
  </details>
1213
- `:null}onGroupToggle(e,t,i){const s=t.currentTarget;s instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,s.open,i)&&this.requestUpdate()}onScroll(){this.requestLoadMoreIfNeeded(),this.updatePinnedToBottomFromScroll(),this.scheduleConversationRailUpdate(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(e){e.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(e){this.touchStartY=e.touches[0]?.clientY}onTouchMove(e){const t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){const e=this.chat;if(!e)return;const t=this.didChatHeightChange(),i=this.pinnedToBottom,s=e.scrollTop<this.lastScrollTop;if(t&&i){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:s?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){const e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){const t=e.get("messageStart");return typeof t=="number"&&this.messageStart<t}requestLoadMoreIfNeeded(){this.loadMoreCheckFrame===void 0&&(this.loadMoreCheckFrame=requestAnimationFrame(()=>{if(this.loadMoreCheckFrame=void 0,this.suppressLoadMoreRequests)return;const e=this.chat;e&&ab({hasMore:this.hasMore,loadingMore:this.loadingMore||this.loadMoreRequested,canRequest:this.onLoadMore!==void 0,scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})&&this.requestLoadMore()}))}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}isNearBottom(){const e=this.chat;return e?zl(e):!0}isAtBottom(){const e=this.chat;return e?Fl(e)<2:!0}canScrollUp(){const e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;const e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){const e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){const e=this.pendingScrollRestoreSessionId,t=this.pendingScrollRestorePosition;e===void 0||t===void 0||e!==this.sessionId||this.restoreScrollFrame!==void 0||(this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const i=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,i)})}))}handleScrollRestoreResult(e,t){if(this.syncScrollMetrics(),t.status!=="missing"){this.updatePinnedToBottomAfterRestore(t.status),(t.status==="restored"||t.status==="bottom")&&this.cancelPrependRestore(),this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0;return}this.pinnedToBottom=!1,this.pendingScrollRestoreSessionId=e,this.pendingScrollRestorePosition=t.position;const i=this.chat;i===void 0||!this.hasMore||this.loadingMore||(i.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore&&!this.isReceivingPartialStream}updatePinnedToBottomAfterRestore(e){e==="bottom"?this.pinnedToBottom=!0:e==="restored"&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){const e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){const e=this.chat;if(e)return Yv(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;const t=this.prependRestoreToken+1;this.prependRestoreToken=t;let i=0;const s=()=>{const r=this.chat;if(!(!r||t!==this.prependRestoreToken)){if(eb(r,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=r.scrollTop,i+=1,i<Xv){requestAnimationFrame(s);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};s()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){const e=this.sessionId;this.scrollController.scheduleSave(e,t=>{this.sessionId===t&&this.saveScrollPosition(t)})}scheduleConversationRailUpdate(){this.conversationRailFrame===void 0&&(this.conversationRailFrame=requestAnimationFrame(()=>{this.conversationRailFrame=void 0,this.updateConversationRailPosition()}))}updateConversationRailPosition(){if(!this.messages.length||this.messageTotal<=0){this.currentConversationIndex=void 0;return}const e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),i=Number(t?.dataset.index);if(Number.isFinite(i)){this.currentConversationIndex=Ii(i,0,Math.max(0,e-1));return}this.currentConversationIndex=Ii(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(".scroll-marker"))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}firstVisibleArticle(){const e=this.chat;if(e===void 0)return;const t=Array.from(this.renderRoot.querySelectorAll("article.msg"));return Bn(e,t)??Bn(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll("[data-scroll-anchor-id]"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,i){return i?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return`m:${String(e)}`}groupRenderKey(e){return`g:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}eventAnchorKey(e){return`e:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}};z.styles=xb;H([d({attribute:!1})],z.prototype,"messages",2);H([d()],z.prototype,"sessionId",2);H([d({type:Number})],z.prototype,"messageStart",2);H([d({type:Number})],z.prototype,"messageEnd",2);H([d({type:Number})],z.prototype,"messageTotal",2);H([d({type:Boolean})],z.prototype,"hasMore",2);H([d({type:Boolean})],z.prototype,"loadingMore",2);H([d({type:Boolean})],z.prototype,"isReceivingPartialStream",2);H([d({type:Boolean})],z.prototype,"isSendingPrompt",2);H([d({type:Boolean})],z.prototype,"isCompacting",2);H([d({type:Number})],z.prototype,"pendingMessageCount",2);H([d({attribute:!1})],z.prototype,"status",2);H([d({attribute:!1})],z.prototype,"activity",2);H([d({attribute:!1})],z.prototype,"onLoadMore",2);H([B(".chat")],z.prototype,"chat",2);H([w()],z.prototype,"pinnedToBottom",2);H([w()],z.prototype,"expandedMetaKey",2);H([w()],z.prototype,"copiedMessageKey",2);H([w()],z.prototype,"currentConversationIndex",2);H([w()],z.prototype,"loadMoreRequested",2);z=H([W("chat-view")],z);function ta(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Ls(e){return e==="bash"?"Shell 运行中":e==="running"?"运行中":Dw[e]??e}const Ww=["image/jpeg","image/png","image/gif","image/webp"],Ow=new Set(Ww);function oo(e){return typeof e=="string"&&Ow.has(e)}function _w(e){switch(e){case"image/jpeg":return"jpg";case"image/png":return"png";case"image/gif":return"gif";case"image/webp":return"webp";default:return"bin"}}const Lw="application/octet-stream",jw="读取附件失败。";async function Fw(e,t){const i=[];let s;for(const r of e)try{const o=await t(r);i.push(Uw(r,o))}catch{s=jw}return{attachments:i,...s===void 0?{}:{error:s}}}function dr(e){return e.kind==="image"&&oo(e.mimeType)}function pr(e){return e.every(t=>dr(t))}function zw(e,t){return pr(t)?e:"folder"}function Uw(e,t){return oo(e.type)?{kind:"image",name:ia(e),mimeType:e.type,data:t,size:e.size}:{kind:"file",name:ia(e),mimeType:Bw(e),data:t,size:e.size}}function Bw(e){const t=e.type.trim();return t===""?Lw:t}function ia(e){return e.name!==""?e.name:oo(e.type)?`pasted-image.${_w(e.type)}`:"pasted-file.bin"}const tc="pi-web:attachment-delivery";function ic(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Nw(e=ic()){try{return e?.getItem(tc)==="folder"?"folder":"inline"}catch{return"inline"}}function Hw(e,t=ic()){try{t?.setItem(tc,e)}catch{}}const qw="(pointer: coarse), (max-width: 760px)",sc="pi-web.promptEnterPreference";function ps(){return typeof window<"u"&&"matchMedia"in window?window.matchMedia(qw):void 0}function Kw(e){return e==="send"||e==="newline"?e:"auto"}function hs(e=rc()){if(e===void 0)return"auto";try{return Kw(e.getItem(sc))}catch{return"auto"}}function Vw(e,t=rc()){if(t!==void 0)try{t.setItem(sc,e)}catch{}}function Gw(e=ps(),t=hs()){return t==="send"?!0:t==="newline"?!1:e?.matches!==!0}function Jw(e,t,i=ps()){return e?i?.matches===!0?t:!0:!1}function Qw(e,t=ps(),i=hs()){const s=Gw(t,i);return e?!s:s}function rc(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function Zw(){return be`
1245
+ `: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&&cw({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?$c(e):!0}isAtBottom(){const e=this.chat;return e?kc(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 tw(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(iw(r,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=r.scrollTop,i+=1,i<ew){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=Vi(i,0,Math.max(0,e-1));return}this.currentConversationIndex=Vi(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 ma(e,t)??ma(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)}`}};N.styles=kw;H([c({attribute:!1})],N.prototype,"messages",2);H([c()],N.prototype,"sessionId",2);H([c({type:Number})],N.prototype,"messageStart",2);H([c({type:Number})],N.prototype,"messageEnd",2);H([c({type:Number})],N.prototype,"messageTotal",2);H([c({type:Boolean})],N.prototype,"hasMore",2);H([c({type:Boolean})],N.prototype,"loadingMore",2);H([c({type:Boolean})],N.prototype,"isReceivingPartialStream",2);H([c({type:Boolean})],N.prototype,"isSendingPrompt",2);H([c({type:Boolean})],N.prototype,"isCompacting",2);H([c({type:Number})],N.prototype,"pendingMessageCount",2);H([c({attribute:!1})],N.prototype,"clientQueuedMessages",2);H([c({attribute:!1})],N.prototype,"status",2);H([c({attribute:!1})],N.prototype,"activity",2);H([c({attribute:!1})],N.prototype,"onLoadMore",2);H([q(".chat")],N.prototype,"chat",2);H([v()],N.prototype,"pinnedToBottom",2);H([v()],N.prototype,"expandedMetaKey",2);H([v()],N.prototype,"copiedMessageKey",2);H([v()],N.prototype,"currentConversationIndex",2);H([v()],N.prototype,"loadMoreRequested",2);N=H([W("chat-view")],N);function Aa(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function ar(e){return e==="bash"?"Shell 运行中":e==="running"?"运行中":Oy[e]??e}const _y=["image/jpeg","image/png","image/gif","image/webp"],jy=new Set(_y);function Io(e){return typeof e=="string"&&jy.has(e)}function Uy(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 By="application/octet-stream",zy="读取附件失败。";async function Ny(e,t){const i=[];let s;for(const r of e)try{const o=await t(r);i.push(Hy(r,o))}catch{s=zy}return{attachments:i,...s===void 0?{}:{error:s}}}function Tr(e){return e.kind==="image"&&Io(e.mimeType)}function Er(e){return e.every(t=>Tr(t))}function qy(e,t){return Er(t)?e:"folder"}function Hy(e,t){return Io(e.type)?{kind:"image",name:Ma(e),mimeType:e.type,data:t,size:e.size}:{kind:"file",name:Ma(e),mimeType:Ky(e),data:t,size:e.size}}function Ky(e){const t=e.type.trim();return t===""?By:t}function Ma(e){return e.name!==""?e.name:Io(e.type)?`pasted-image.${Uy(e.type)}`:"pasted-file.bin"}const jc="pi-web:attachment-delivery";function Uc(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Vy(e=Uc()){try{return e?.getItem(jc)==="folder"?"folder":"inline"}catch{return"inline"}}function Gy(e,t=Uc()){try{t?.setItem(jc,e)}catch{}}const Qy="(pointer: coarse), (max-width: 760px)",Bc="pi-web.promptEnterPreference";function Ws(){return typeof window<"u"&&"matchMedia"in window?window.matchMedia(Qy):void 0}function Jy(e){return e==="send"||e==="newline"?e:"auto"}function Ls(e=zc()){if(e===void 0)return"auto";try{return Jy(e.getItem(Bc))}catch{return"auto"}}function Zy(e,t=zc()){if(t!==void 0)try{t.setItem(Bc,e)}catch{}}function Xy(e=Ws(),t=Ls()){return t==="send"?!0:t==="newline"?!1:e?.matches!==!0}function Yy(e,t,i=Ws()){return e?i?.matches===!0?t:!0:!1}function e0(e,t=Ws(),i=Ls()){const s=Xy(t,i);return e?!s:s}function zc(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function t0(){return $e`
1214
1246
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1215
1247
  <path d="M20 11.5 12.5 19a4 4 0 0 1-5.66-5.66l7.07-7.07a2.5 2.5 0 0 1 3.54 3.54l-7.07 7.07a1 1 0 0 1-1.42-1.42l6.37-6.36"></path>
1216
1248
  </svg>
1217
- `}function oc(){return be`
1249
+ `}function Nc(){return $e`
1218
1250
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1219
1251
  <path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
1220
1252
  <path d="M21 3 11.5 12.5"></path>
1221
1253
  </svg>
1222
- `}function Xw(){return be`
1254
+ `}function i0(){return $e`
1223
1255
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1224
1256
  <path d="M4 7h11"></path>
1225
1257
  <path d="M4 12h7"></path>
1226
1258
  <path d="M4 17h7"></path>
1227
1259
  <path d="m15 14 5 3-5 3z"></path>
1228
1260
  </svg>
1229
- `}function Yw(){return oc()}function ey(){return be`
1261
+ `}function s0(){return Nc()}function r0(){return $e`
1230
1262
  <svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1231
1263
  <rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
1232
1264
  </svg>
1233
- `}function ty(e){const t=Math.max(e.total,1),i=t>1?1.2:0,s=3,n=(21-s-i*(t-1))/t,a=Array.from({length:t},(c,p)=>{const u=s+p*(n+i),h=4+(p+1)/t*12,g=20-h,y=p<e.filled;return be`<rect class=${y?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${g} width=${n} height=${h} rx="1"></rect>`});return be`
1265
+ `}function o0(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},(d,p)=>{const u=s+p*(n+i),h=4+(p+1)/t*12,g=20-h,S=p<e.filled;return $e`<rect class=${S?"gauge-bar gauge-bar-active":"gauge-bar"} x=${u} y=${g} width=${n} height=${h} rx="1"></rect>`});return $e`
1234
1266
  <svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1235
1267
  ${a}
1236
1268
  </svg>
1237
- `}const iy=["off","minimal","low","medium","high","xhigh"];function hr(e){return e===void 0||e===""?"off":e}function sy(e,t){const i=t.length>=2?t:iy,s=i.length-1,r=hr(e),o=i.indexOf(r),n=o<=0?0:Math.min(o,s);return{total:s,filled:n}}class ry extends Kr{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===Hr.ELEMENT}update(t,[i,s]){if(!this.isElementPart)throw new Error("scrollWhenSelected must be used on an element");if(i&&(!this.wasSelected||s!==this.previousKey)){const r="element"in t?t.element:void 0;requestAnimationFrame(()=>{r instanceof HTMLElement&&r.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const no=qr(ry);var oy=Object.defineProperty,ny=Object.getOwnPropertyDescriptor,us=(e,t,i,s)=>{for(var r=s>1?void 0:s?ny(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&oy(t,i,r),r};const ay=D`
1269
+ `}const n0=["off","minimal","low","medium","high","xhigh"];function Dr(e){return e===void 0||e===""?"off":e}function a0(e,t){const i=t.length>=2?t:n0,s=i.length-1,r=Dr(e),o=i.indexOf(r),n=o<=0?0:Math.min(o,s);return{total:s,filled:n}}class l0 extends go{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===uo.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 Ao=fo(l0);var c0=Object.defineProperty,d0=Object.getOwnPropertyDescriptor,Os=(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};const p0=D`
1238
1270
  :host { display: block; }
1239
1271
  .menu { position: absolute; left: 0; right: 0; bottom: calc(100% + 6px); z-index: 10; max-height: 260px; overflow: auto; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 10px 30px var(--pi-shadow); }
1240
1272
  button { display: grid; grid-template-columns: minmax(120px, 1fr) auto; gap: 4px 10px; width: 100%; border: 0; border-bottom: 1px solid var(--pi-border); border-radius: 0; background: transparent; color: var(--pi-text); padding: 8px 10px; text-align: left; cursor: pointer; }
@@ -1242,22 +1274,22 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1242
1274
  button.selected, button:hover { background: var(--pi-selection-bg); }
1243
1275
  span { color: var(--pi-muted); font-size: 12px; }
1244
1276
  small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1245
- `;let At=class extends R{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
1277
+ `;let Bt=class extends I{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
1246
1278
  <div class="menu">
1247
1279
  ${this.items.map((e,t)=>l`
1248
- <button class=${t===this.selectedIndex?"selected":""} ${no(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1280
+ <button class=${t===this.selectedIndex?"selected":""} ${Ao(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1249
1281
  <strong>${e.insertText}</strong>
1250
1282
  <span>${e.detail}</span>
1251
1283
  ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1252
1284
  </button>
1253
1285
  `)}
1254
1286
  </div>
1255
- `:null}};At.styles=ay;us([d({attribute:!1})],At.prototype,"items",2);us([d({type:Number})],At.prototype,"selectedIndex",2);us([d({attribute:!1})],At.prototype,"onPick",2);At=us([W("autocomplete-menu")],At);var ly=Object.defineProperty,cy=Object.getOwnPropertyDescriptor,F=(e,t,i,s)=>{for(var r=s>1?void 0:s?cy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&ly(t,i,r),r};let L=class extends R{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft="",this.currentInputMode={kind:"normal"},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=Nw(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new lo,this.readOnlyCompartment=new lo,this.mobilePromptEnterMedia=ps(),this.explicitShiftKeyActive=!1}willUpdate(e){if(!e.has("sessionId")&&!e.has("machineId"))return;const t=e.has("sessionId")?e.get("sessionId"):this.sessionId,i=e.has("machineId")?e.get("machineId"):this.machineId,s=ui(i,t);s!==void 0&&Oi(s,this.draft);const r=ui(this.machineId,this.sessionId);this.draft=r!==void 0?Qa(r):"",this.currentInputMode=Fi(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has("status")&&e.size===1?!dy(e.get("status"),this.status):!0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=this.currentInputMode.kind==="shell"?this.currentInputMode:void 0,t=e!==void 0,i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return l`
1287
+ `:null}};Bt.styles=p0;Os([c({attribute:!1})],Bt.prototype,"items",2);Os([c({type:Number})],Bt.prototype,"selectedIndex",2);Os([c({attribute:!1})],Bt.prototype,"onPick",2);Bt=Os([W("autocomplete-menu")],Bt);var h0=Object.defineProperty,u0=Object.getOwnPropertyDescriptor,z=(e,t,i,s)=>{for(var r=s>1?void 0:s?u0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&h0(t,i,r),r};let U=class extends I{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=Vy(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new Eo,this.readOnlyCompartment=new Eo,this.mobilePromptEnterMedia=Ws(),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=Ti(i,t);s!==void 0&&ts(s,this.draft);const r=Ti(this.machineId,this.sessionId);this.draft=r!==void 0?Tl(r):"",this.currentInputMode=ns(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has("status")&&e.size===1?!f0(e.get("status"),this.status):!0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=this.currentInputMode.kind==="shell"?this.currentInputMode:void 0,t=e!==void 0,i=this.canSteer||this.isCompacting,s=this.disabled||this.sending;return l`
1256
1288
  <footer class=${t?"shell-mode":""} @paste=${r=>{this.handlePaste(r)}} @dragover=${r=>{this.handleDragOver(r)}} @drop=${r=>{this.handleDrop(r)}}>
1257
1289
  <div class="editor-wrap">
1258
1290
  <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="给 pi 发送消息" aria-disabled=${this.disabled?"true":"false"}></div>
1259
1291
  <input class="attachment-input" type="file" multiple hidden @change=${r=>{this.handleFileInput(r)}} />
1260
- <button class="editor-attach icon-button" ?disabled=${s} title="附加文件" aria-label="附加文件" @click=${()=>{this.attachmentInput?.click()}}>${Zw()}</button>
1292
+ <button class="editor-attach icon-button" ?disabled=${s} title="附加文件" aria-label="附加文件" @click=${()=>{this.attachmentInput?.click()}}>${t0()}</button>
1261
1293
  ${t?l`<div class="mode-hint">Shell 命令${e.excludeFromContext?" · 已排除上下文":""}</div>`:null}
1262
1294
  ${this.isCompacting&&!t?l`<div class="mode-hint">正在压缩历史 · 消息将排队发送</div>`:null}
1263
1295
  ${this.renderAttachments()}
@@ -1265,20 +1297,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1265
1297
  </div>
1266
1298
  <div class="actions">
1267
1299
  ${this.renderCompactStatus()}
1268
- <button class="icon-button send-button" ?disabled=${s} title=${i?"当前活动结束后排队发送":"发送"} aria-label=${i?"排队发送":"发送"} @click=${()=>{this.send("followUp")}}>${i?Xw():oc()}</button>
1269
- ${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send("steer")}}>${Yw()}</button>`:null}
1270
- <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} aria-label="停止" @click=${()=>this.onStop?.()}>${ey()}</button>
1300
+ <button class="icon-button send-button" ?disabled=${s} title=${i?"当前活动结束后排队发送":"发送"} aria-label=${i?"排队发送":"发送"} @click=${()=>{this.send("followUp")}}>${i?i0():Nc()}</button>
1301
+ ${this.canSteer&&!this.isCompacting?l`<button class="icon-button steer-button" ?disabled=${s} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send("steer")}}>${s0()}</button>`:null}
1302
+ <button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} aria-label="停止" @click=${()=>this.onStop?.()}>${r0()}</button>
1271
1303
  </div>
1272
1304
  </footer>
1273
1305
  `}focusInput(){this.editor?.focus()}get view(){return this.editor}renderCompactStatus(){const e=this.status;if(e===void 0)return null;const t=e.model?.id??"无模型",i=e.model?.provider!==void 0&&e.model.provider!==""?`${e.model.provider}/`:"";return l`
1274
1306
  <div class="compact-status" aria-label="会话状态">
1275
1307
  <button class="select-model" title="选择模型" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
1276
- <button class="select-thinking icon-button" title=${`思考级别:${hr(e.thinkingLevel)}`} aria-label=${`思考级别:${hr(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${ty(sy(e.thinkingLevel,this.availableThinkingLevels))}</button>
1308
+ <button class="select-thinking icon-button" title=${`思考级别:${Dr(e.thinkingLevel)}`} aria-label=${`思考级别:${Dr(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${o0(a0(e.thinkingLevel,this.availableThinkingLevels))}</button>
1277
1309
  </div>
1278
- `}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;const e=pr(this.attachments),t=this.effectiveAttachmentDelivery();return l`
1310
+ `}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;const e=Er(this.attachments),t=this.effectiveAttachmentDelivery();return l`
1279
1311
  <div class="attachments" aria-label="待发送附件">
1280
1312
  ${this.attachments.map(i=>l`
1281
- <div class=${`attachment-chip ${dr(i)?"attachment-chip-image":"attachment-chip-file"}`} title=${i.name}>
1313
+ <div class=${`attachment-chip ${Tr(i)?"attachment-chip-image":"attachment-chip-file"}`} title=${i.name}>
1282
1314
  ${this.renderAttachmentPreview(i)}
1283
1315
  <button type="button" class="attachment-remove" title="移除附件" aria-label=${`移除 ${i.name}`} @click=${()=>{this.removeAttachment(i.id)}}>×</button>
1284
1316
  </div>
@@ -1293,10 +1325,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1293
1325
  `:null}
1294
1326
  ${this.attachmentError!==void 0?l`<div class="attachment-error">${this.attachmentError}</div>`:null}
1295
1327
  </div>
1296
- `}renderAttachmentPreview(e){return dr(e)?l`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:l`
1297
- <div class="attachment-file-preview" aria-hidden="true">${gy(e.name)}</div>
1328
+ `}renderAttachmentPreview(e){return Tr(e)?l`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:l`
1329
+ <div class="attachment-file-preview" aria-hidden="true">${w0(e.name)}</div>
1298
1330
  <span class="attachment-file-name">${e.name}</span>
1299
- `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;const t=e.target.value==="folder"?"folder":"inline";if(t==="inline"&&!pr(this.attachments)){e.target.value="folder";return}this.attachmentDelivery=t,Hw(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=sa(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&uy(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){const t=sa(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;const t=Array.from(e.target.files);e.target.value="",await this.addAttachmentFiles(t)}async addAttachmentFiles(e){this.attachmentError=void 0;const{attachments:t,error:i}=await Fw(e,my);t.length>0&&(this.attachments=[...this.attachments,...t.map(s=>({id:`attachment-${String(++this.attachmentSeq)}`,...s}))]),i!==void 0&&(this.attachmentError=i)}currentAttachments(){return this.attachments.map(e=>fy(e))}effectiveAttachmentDelivery(){return zw(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new rt({parent:this.editorHost,state:vs.create({doc:this.draft,extensions:[uc(),kc(),fc(),gc.of(" "),mc(vc,{fallback:!0}),rt.lineWrapping,rt.contentAttributes.of(e=>wy(e.state.sliceDoc(0,e.state.selection.main.head))),rt.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),bc("给 pi 发送消息... 使用 / 输入命令,@ 输入已跟踪文件,@ 空格显示所有文件"),this.editableCompartment.of(rt.editable.of(!this.disabled)),this.readOnlyCompartment.of(vs.readOnly.of(this.disabled)),rt.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),wc.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>co.shift?.(e)??!1},{key:"Backspace",run:e=>$c(e)},...yc,...xc])]})}))}syncEditorDoc(){const e=this.editor;if(!e)return;const t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:po.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(rt.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(vs.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=ui(this.machineId,this.sessionId);t!==void 0&&Oi(t,this.draft);const i=Fi(this.draft);Bu(i,this.currentInputMode)||(this.currentInputMode=i),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""&&this.cwd!==void 0&&this.cwd!==""){const i=await N.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(py);if(t!==this.requestVersion)return;this.completions=i.filter(s=>s.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(s=>({kind:"command",replaceFrom:e.from,replaceTo:e.to,insertText:`/${s.name}`,detail:s.source,...s.description===void 0?{}:{description:s.description}}))}else if(e.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const i=await N.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(hy);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const r=sl(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:r,detail:s.kind,...s.path.endsWith("/")&&r.endsWith('"')?{cursorOffset:r.length-1}:{}}})}}currentTrigger(){return il(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key==="Shift")return this.explicitShiftKeyActive=!0,!1;if(e.key!=="Enter")return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;const i=Jw(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,i)}handleEditorKeyUp(e){return e.key==="Shift"&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(!t&&this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return Qw(t,this.mobilePromptEnterMedia,hs())?(this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0):Pc(e)||Sc(e)}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):co.run?.(e)??!1}pick(e){const t=this.editor;if(!t)return;const i=e.kind==="file"&&(e.insertText.endsWith("/")||e.cursorOffset!==void 0)?"":" ",s=e.replaceFrom+(e.cursorOffset??e.insertText.length)+i.length,r=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:r,insert:`${e.insertText}${i}`},selection:po.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;const t=this.draft.trim(),i=this.attachments;if(t===""&&i.length===0)return;const s=this.canSteer||this.isCompacting?e:void 0,r=i.length>0?this.currentAttachments():void 0,o=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,s,r,r===void 0?void 0:o)}resetComposer(){this.draft="",this.currentInputMode={kind:"normal"};const e=ui(this.machineId,this.sessionId);e!==void 0&&Or(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}};L.styles=$g;F([d({type:Boolean})],L.prototype,"disabled",2);F([d()],L.prototype,"sessionId",2);F([d()],L.prototype,"cwd",2);F([d()],L.prototype,"machineId",2);F([d()],L.prototype,"projectId",2);F([d()],L.prototype,"workspaceId",2);F([d({type:Boolean})],L.prototype,"workspaceScopedFileSuggestions",2);F([d({type:Boolean})],L.prototype,"canSteer",2);F([d({type:Boolean})],L.prototype,"isCompacting",2);F([d({type:Boolean})],L.prototype,"canStop",2);F([d({attribute:!1})],L.prototype,"status",2);F([d({type:Boolean})],L.prototype,"sending",2);F([d({attribute:!1})],L.prototype,"onSend",2);F([d({attribute:!1})],L.prototype,"onStop",2);F([d({attribute:!1})],L.prototype,"onSelectModel",2);F([d({attribute:!1})],L.prototype,"onSelectThinking",2);F([d({attribute:!1})],L.prototype,"availableThinkingLevels",2);F([B(".markdown-editor")],L.prototype,"editorHost",2);F([B(".attachment-input")],L.prototype,"attachmentInput",2);F([w()],L.prototype,"currentInputMode",2);F([w()],L.prototype,"completions",2);F([w()],L.prototype,"selectedIndex",2);F([w()],L.prototype,"attachments",2);F([w()],L.prototype,"attachmentDelivery",2);F([w()],L.prototype,"attachmentError",2);L=F([W("prompt-editor")],L);function dy(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel}function ui(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return Ga(e,t)}function py(){return[]}function hy(){return[]}function sa(e){return e===null?[]:Array.from(e.files)}function uy(e){const t=Array.from(e.items);return t.length>0?t.some(i=>i.kind==="file"):Array.from(e.types).includes("Files")}function fy(e){return e.kind==="image"?{kind:"image",mimeType:e.mimeType,data:e.data,name:e.name}:{kind:"file",mimeType:e.mimeType,data:e.data,name:e.name}}function gy(e){const t=e.trim(),i=t.lastIndexOf(".");return i>=0&&i<t.length-1?t.slice(i+1,i+5).toUpperCase():"FILE"}function my(e){return new Promise((t,i)=>{const s=new FileReader;s.onerror=()=>{i(s.error??new Error("读取文件失败"))},s.onload=()=>{const r=s.result;if(typeof r!="string"){i(new Error("文件读取结果异常"));return}const o=r.indexOf(",");t(o===-1?r:r.slice(o+1))},s.readAsDataURL(e)})}const vy={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true",dir:"auto"},by={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",dir:"auto"};function wy(e){return Fi(e).kind==="normal"?vy:by}function fi(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:"0"}function yy(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var xy=Object.defineProperty,Sy=Object.getOwnPropertyDescriptor,nc=(e,t,i,s)=>{for(var r=s>1?void 0:s?Sy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&xy(t,i,r),r};const ky=D`
1331
+ `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;const t=e.target.value==="folder"?"folder":"inline";if(t==="inline"&&!Er(this.attachments)){e.target.value="folder";return}this.attachmentDelivery=t,Gy(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){const t=Ta(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&v0(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){const t=Ta(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 Ny(e,y0);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=>b0(e))}effectiveAttachmentDelivery(){return qy(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new ut({parent:this.editorHost,state:_s.create({doc:this.draft,extensions:[sd(),ud(),rd(),od.of(" "),nd(ad,{fallback:!0}),ut.lineWrapping,ut.contentAttributes.of(e=>k0(e.state.sliceDoc(0,e.state.selection.main.head))),ut.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),ld("给 pi 发送消息... 使用 / 输入命令,@ 输入已跟踪文件,@ 空格显示所有文件"),this.editableCompartment.of(ut.editable.of(!this.disabled)),this.readOnlyCompartment.of(_s.readOnly.of(this.disabled)),ut.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),cd.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=>Do.shift?.(e)??!1},{key:"Backspace",run:e=>fd(e)},...dd,...pd])]})}))}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:Wo.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(ut.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(_s.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Ti(this.machineId,this.sessionId);t!==void 0&&ts(t,this.draft);const i=ns(this.draft);Lf(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 K.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(g0);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 K.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(m0);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const r=_l(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 Fl(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=Yy(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 e0(t,this.mobilePromptEnterMedia,Ls())?(this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0):gd(e)||hd(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):Do.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:Wo.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=Ti(this.machineId,this.sessionId);e!==void 0&&is(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}};U.styles=ym;z([c({type:Boolean})],U.prototype,"disabled",2);z([c()],U.prototype,"sessionId",2);z([c()],U.prototype,"cwd",2);z([c()],U.prototype,"machineId",2);z([c()],U.prototype,"projectId",2);z([c()],U.prototype,"workspaceId",2);z([c({type:Boolean})],U.prototype,"workspaceScopedFileSuggestions",2);z([c({type:Boolean})],U.prototype,"canSteer",2);z([c({type:Boolean})],U.prototype,"isCompacting",2);z([c({type:Boolean})],U.prototype,"canStop",2);z([c({attribute:!1})],U.prototype,"status",2);z([c({type:Boolean})],U.prototype,"sending",2);z([c({attribute:!1})],U.prototype,"onSend",2);z([c({attribute:!1})],U.prototype,"onStop",2);z([c({attribute:!1})],U.prototype,"onSelectModel",2);z([c({attribute:!1})],U.prototype,"onSelectThinking",2);z([c({attribute:!1})],U.prototype,"availableThinkingLevels",2);z([q(".markdown-editor")],U.prototype,"editorHost",2);z([q(".attachment-input")],U.prototype,"attachmentInput",2);z([v()],U.prototype,"currentInputMode",2);z([v()],U.prototype,"completions",2);z([v()],U.prototype,"selectedIndex",2);z([v()],U.prototype,"attachments",2);z([v()],U.prototype,"attachmentDelivery",2);z([v()],U.prototype,"attachmentError",2);U=z([W("prompt-editor")],U);function f0(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 Ti(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return oi(e,t)}function g0(){return[]}function m0(){return[]}function Ta(e){return e===null?[]:Array.from(e.files)}function v0(e){const t=Array.from(e.items);return t.length>0?t.some(i=>i.kind==="file"):Array.from(e.types).includes("Files")}function b0(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 w0(e){const t=e.trim(),i=t.lastIndexOf(".");return i>=0&&i<t.length-1?t.slice(i+1,i+5).toUpperCase():"FILE"}function y0(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 S0={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true",dir:"auto"},x0={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",dir:"auto"};function k0(e){return ns(e).kind==="normal"?S0:x0}function Ei(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:"0"}function $0(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var P0=Object.defineProperty,C0=Object.getOwnPropertyDescriptor,qc=(e,t,i,s)=>{for(var r=s>1?void 0:s?C0(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};const R0=D`
1300
1332
  :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
1301
1333
  .bar { display: flex; justify-content: flex-end; gap: 12px; align-items: center; min-width: 0; padding: 7px 12px; border-top: 1px solid var(--pi-border); background: var(--pi-bg); white-space: nowrap; overflow: hidden; }
1302
1334
  span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
@@ -1306,15 +1338,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1306
1338
  .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
1307
1339
  .muted { color: var(--pi-dim); }
1308
1340
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
1309
- `;let Vi=class extends R{render(){const e=this.status;if(e===void 0)return l`<div class="bar muted">暂无会话状态</div>`;const t=e.contextUsage,i=t?t.percent==null?`上下文 ${fi(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${fi(t.contextWindow)}`:"上下文未知",s=e.tokens;return l`
1341
+ `;let gs=class extends I{render(){const e=this.status;if(e===void 0)return l`<div class="bar muted">暂无会话状态</div>`;const t=e.contextUsage,i=t?t.percent==null?`上下文 ${Ei(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Ei(t.contextWindow)}`:"上下文未知",s=e.tokens;return l`
1310
1342
  <div class="bar">
1311
- <span>↑${fi(s.input)}</span>
1312
- <span>↓${fi(s.output)}</span>
1343
+ <span>↑${Ei(s.input)}</span>
1344
+ <span>↓${Ei(s.output)}</span>
1313
1345
  <span class="context">${i}</span>
1314
- <span>${yy(e.cost)}</span>
1346
+ <span>${$0(e.cost)}</span>
1315
1347
  ${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} 条排队</span>`:null}
1316
1348
  </div>
1317
- `}};Vi.styles=ky;nc([d({attribute:!1})],Vi.prototype,"status",2);Vi=nc([W("status-bar")],Vi);const ac=D`
1349
+ `}};gs.styles=R0;qc([c({attribute:!1})],gs.prototype,"status",2);gs=qc([W("status-bar")],gs);const Hc=D`
1318
1350
  :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1319
1351
  .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
1320
1352
  section { width: min(720px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -1328,7 +1360,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1328
1360
  .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
1329
1361
  small { display: block; margin-top: 4px; color: var(--pi-muted); }
1330
1362
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
1331
- `;var $y=Object.defineProperty,Py=Object.getOwnPropertyDescriptor,Je=(e,t,i,s)=>{for(var r=s>1?void 0:s?Py(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&$y(t,i,r),r};let Ee=class extends R{constructor(){super(...arguments),this.title="选择",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
1363
+ `;var I0=Object.defineProperty,A0=Object.getOwnPropertyDescriptor,st=(e,t,i,s)=>{for(var r=s>1?void 0:s?A0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&I0(t,i,r),r};let je=class extends I{constructor(){super(...arguments),this.title="选择",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
1332
1364
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1333
1365
  <section @mousedown=${t=>{t.stopPropagation()}}>
1334
1366
  <header>
@@ -1338,7 +1370,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1338
1370
  ${this.searchable?l`<input placeholder="搜索" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
1339
1371
  <div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
1340
1372
  ${e.map((t,i)=>l`
1341
- <button class=${i===this.selectedIndex?"selected":""} ${no(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1373
+ <button class=${i===this.selectedIndex?"selected":""} ${Ao(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1342
1374
  <span>${t.label}</span>
1343
1375
  ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1344
1376
  </button>
@@ -1347,7 +1379,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1347
1379
  </div>
1348
1380
  </section>
1349
1381
  </div>
1350
- `}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const e=this.filteredOptions().findIndex(t=>t.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){const e=this.query.trim().toLowerCase();return e===""?this.options:this.options.filter(t=>`${t.label} ${t.description??""} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredOptions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i&&this.onPick?.(i.value)}}};Ee.styles=ac;Je([d()],Ee.prototype,"title",2);Je([d({type:Boolean})],Ee.prototype,"searchable",2);Je([d({attribute:!1})],Ee.prototype,"options",2);Je([d({attribute:!1})],Ee.prototype,"selectedValue",2);Je([d({attribute:!1})],Ee.prototype,"onPick",2);Je([d({attribute:!1})],Ee.prototype,"onCancel",2);Je([w()],Ee.prototype,"selectedIndex",2);Je([w()],Ee.prototype,"query",2);Ee=Je([W("command-picker")],Ee);var Cy=Object.defineProperty,Iy=Object.getOwnPropertyDescriptor,mt=(e,t,i,s)=>{for(var r=s>1?void 0:s?Iy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Cy(t,i,r),r};const Ry=D`
1382
+ `}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)}}};je.styles=Hc;st([c()],je.prototype,"title",2);st([c({type:Boolean})],je.prototype,"searchable",2);st([c({attribute:!1})],je.prototype,"options",2);st([c({attribute:!1})],je.prototype,"selectedValue",2);st([c({attribute:!1})],je.prototype,"onPick",2);st([c({attribute:!1})],je.prototype,"onCancel",2);st([v()],je.prototype,"selectedIndex",2);st([v()],je.prototype,"query",2);je=st([W("command-picker")],je);var M0=Object.defineProperty,T0=Object.getOwnPropertyDescriptor,Rt=(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&&M0(t,i,r),r};const E0=D`
1351
1383
  :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1352
1384
  .backdrop { --palette-top: min(12dvh, 90px); --palette-bottom: max(20px, env(safe-area-inset-bottom)); display: grid; align-items: start; justify-items: center; width: 100%; height: 100dvh; background: var(--pi-overlay); padding: var(--palette-top) 20px var(--palette-bottom); box-sizing: border-box; overflow: hidden; }
1353
1385
  section { width: min(720px, 100%); max-height: min(640px, calc(100dvh - var(--palette-top) - var(--palette-bottom))); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -1365,7 +1397,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1365
1397
  .group { grid-column: 1 / -1; font-size: 12px; }
1366
1398
  kbd { align-self: center; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 2px 6px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
1367
1399
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
1368
- `;let Ke=class extends R{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
1400
+ `;let et=class extends I{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
1369
1401
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1370
1402
  <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1371
1403
  <header>
@@ -1378,20 +1410,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1378
1410
  </header>
1379
1411
  <div class="options">
1380
1412
  ${e.length===0?l`<div class="empty">未找到操作。</div>`:e.map((t,i)=>l`
1381
- <button class=${`${i===this.selectedIndex?"selected":""} ${t.enabled===!1?"disabled":""}`} ?disabled=${t.enabled===!1} title=${t.disabledReason??t.title} ${no(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1413
+ <button class=${`${i===this.selectedIndex?"selected":""} ${t.enabled===!1?"disabled":""}`} ?disabled=${t.enabled===!1} title=${t.disabledReason??t.title} ${Ao(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1382
1414
  <span class="main">
1383
1415
  <strong>${t.title}</strong>
1384
1416
  ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1385
1417
  ${t.enabled===!1&&t.disabledReason!==void 0?l`<small class="disabled-reason">${t.disabledReason}</small>`:null}
1386
1418
  </span>
1387
- ${t.shortcut!==void 0?l`<kbd>${ki(t.shortcut)}</kbd>`:null}
1419
+ ${t.shortcut!==void 0?l`<kbd>${Ni(t.shortcut)}</kbd>`:null}
1388
1420
  ${t.group!==void 0&&t.group!==""?l`<small class="group">${t.group}</small>`:null}
1389
1421
  </button>
1390
1422
  `)}
1391
1423
  </div>
1392
1424
  </section>
1393
1425
  </div>
1394
- `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return Ay(this.actions,this.queryText)}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){e.enabled!==!1&&this.onRun?.(e)}};Ke.styles=Ry;mt([d({attribute:!1})],Ke.prototype,"actions",2);mt([d({attribute:!1})],Ke.prototype,"onRun",2);mt([d({attribute:!1})],Ke.prototype,"onCancel",2);mt([B("input")],Ke.prototype,"input",2);mt([w()],Ke.prototype,"queryText",2);mt([w()],Ke.prototype,"selectedIndex",2);Ke=mt([W("action-palette")],Ke);function Ay(e,t){const i=t.trim().toLowerCase();return e.filter(s=>s.enabled!==!1||s.disabledReason!==void 0).filter(s=>i===""?!0:[s.title,s.description??"",s.disabledReason??"",s.group??"",s.shortcut??""].join(" ").toLowerCase().includes(i))}var Ty=Object.defineProperty,My=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var r=s>1?void 0:s?My(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Ty(t,i,r),r};let ce=class extends R{render(){const e=this.state;return e===void 0?null:l`
1426
+ `}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 D0(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)}};et.styles=E0;Rt([c({attribute:!1})],et.prototype,"actions",2);Rt([c({attribute:!1})],et.prototype,"onRun",2);Rt([c({attribute:!1})],et.prototype,"onCancel",2);Rt([q("input")],et.prototype,"input",2);Rt([v()],et.prototype,"queryText",2);Rt([v()],et.prototype,"selectedIndex",2);et=Rt([W("action-palette")],et);function D0(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 W0=Object.defineProperty,L0=Object.getOwnPropertyDescriptor,De=(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&&W0(t,i,r),r};let fe=class extends I{render(){const e=this.state;return e===void 0?null:l`
1395
1427
  <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
1396
1428
  <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1397
1429
  <header>
@@ -1414,11 +1446,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1414
1446
  <div class="actions"><button @click=${()=>{this.cancel()}}>取消</button><button class="primary" ?disabled=${e.saving===!0} @click=${()=>{this.onSaveApiKey?.()}}>${e.saving===!0?"正在保存…":"保存 API key"}</button></div>
1415
1447
  </div>
1416
1448
  `;case"oauth":return this.renderOAuth(e);case"logout":return l`<div class="options">${e.providers.length===0?l`<div class="empty">没有已保存的凭据。环境变量和 models.json 设置不会变化。</div>`:e.providers.map(t=>l`
1417
- <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${ra(t.authType)}</small></button>
1449
+ <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Ea(t.authType)}</small></button>
1418
1450
  `)}</div>`}}renderProviderButton(e){return l`
1419
1451
  <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
1420
- <span>${e.name}${e.status.source!==void 0?l` <em>${Dy(e)}</em>`:null}</span>
1421
- <small>${e.id} · ${ra(e.authType)}</small>
1452
+ <span>${e.name}${e.status.source!==void 0?l` <em>${F0(e)}</em>`:null}</span>
1453
+ <small>${e.id} · ${Ea(e.authType)}</small>
1422
1454
  </button>
1423
1455
  `}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
1424
1456
  <div class="form">
@@ -1438,10 +1470,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1438
1470
  <div class="inline-options">${s.options.map(r=>l`<button @click=${()=>{this.onOAuthRespond?.(r.value)}}>${r.label}</button>`)}</div>
1439
1471
  `:null}
1440
1472
  ${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
1441
- ${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??Wy(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
1473
+ ${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??_0(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
1442
1474
  ${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button></div>`:null}
1443
1475
  </div>
1444
- `}focusInputIfNeeded(){const e=Ey(this.state);if(e===void 0){this.lastFocusedInputKey=void 0;return}e!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=e,this.input?.focus())}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.cancel();return}if(e.key!=="Enter")return;const t=this.state;t?.step==="apiKey"?(e.preventDefault(),this.onSaveApiKey?.()):t?.step==="oauth"&&t.flow.prompt!==void 0&&(e.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step==="oauth"?this.onOAuthCancel?.():this.onCancel?.()}};ce.styles=[ac,D`
1476
+ `}focusInputIfNeeded(){const e=O0(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?.()}};fe.styles=[Hc,D`
1445
1477
  .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
1446
1478
  .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
1447
1479
  .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
@@ -1456,7 +1488,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1456
1488
  .progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
1457
1489
  .inline-options { display: grid; gap: 8px; }
1458
1490
  em { color: var(--pi-success); font-style: normal; font-size: 12px; }
1459
- `];Ce([d({attribute:!1})],ce.prototype,"state",2);Ce([d({attribute:!1})],ce.prototype,"onChooseMethod",2);Ce([d({attribute:!1})],ce.prototype,"onSelectProvider",2);Ce([d({attribute:!1})],ce.prototype,"onApiKeyInput",2);Ce([d({attribute:!1})],ce.prototype,"onSaveApiKey",2);Ce([d({attribute:!1})],ce.prototype,"onLogoutProvider",2);Ce([d({attribute:!1})],ce.prototype,"onOAuthInput",2);Ce([d({attribute:!1})],ce.prototype,"onOAuthRespond",2);Ce([d({attribute:!1})],ce.prototype,"onOAuthCancel",2);Ce([d({attribute:!1})],ce.prototype,"onCancel",2);Ce([B("input")],ce.prototype,"input",2);ce=Ce([W("auth-dialog")],ce);function ra(e){return e==="oauth"?"订阅":"API key"}function Ey(e){if(e?.step==="apiKey")return`api-key:${e.provider.authType}:${e.provider.id}`;if(e?.step==="oauth"&&e.flow.prompt!==void 0)return`oauth:${e.flow.flowId}:${e.flow.prompt.requestId}`}function Dy(e){if(e.status.source===void 0)return"";switch(e.status.source){case"stored":return"✓ 已配置";case"environment":return`✓ 环境变量${e.status.label===void 0?"":`: ${e.status.label}`}`;case"runtime":return"✓ 运行时";case"fallback":return"✓ 自定义 key";case"models_json_key":return"✓ models.json key";case"models_json_command":return"✓ models.json command";default:return""}}function Wy(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var Oy=Object.defineProperty,_y=Object.getOwnPropertyDescriptor,ze=(e,t,i,s)=>{for(var r=s>1?void 0:s?_y(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Oy(t,i,r),r};let xe=class extends R{constructor(){super(...arguments),this.mode="login",this.loading=!1,this.error="",this.currentPassword="",this.password="",this.confirmPassword="",this.localError=""}render(){return l`
1491
+ `];De([c({attribute:!1})],fe.prototype,"state",2);De([c({attribute:!1})],fe.prototype,"onChooseMethod",2);De([c({attribute:!1})],fe.prototype,"onSelectProvider",2);De([c({attribute:!1})],fe.prototype,"onApiKeyInput",2);De([c({attribute:!1})],fe.prototype,"onSaveApiKey",2);De([c({attribute:!1})],fe.prototype,"onLogoutProvider",2);De([c({attribute:!1})],fe.prototype,"onOAuthInput",2);De([c({attribute:!1})],fe.prototype,"onOAuthRespond",2);De([c({attribute:!1})],fe.prototype,"onOAuthCancel",2);De([c({attribute:!1})],fe.prototype,"onCancel",2);De([q("input")],fe.prototype,"input",2);fe=De([W("auth-dialog")],fe);function Ea(e){return e==="oauth"?"订阅":"API key"}function O0(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 F0(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 _0(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var j0=Object.defineProperty,U0=Object.getOwnPropertyDescriptor,Ge=(e,t,i,s)=>{for(var r=s>1?void 0:s?U0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&j0(t,i,r),r};let Ie=class extends I{constructor(){super(...arguments),this.mode="login",this.loading=!1,this.error="",this.currentPassword="",this.password="",this.confirmPassword="",this.localError=""}render(){return l`
1460
1492
  <div class="backdrop">
1461
1493
  <section role="dialog" aria-modal="true" aria-label=${this.dialogTitle()} @keydown=${e=>{this.handleKeyDown(e)}}>
1462
1494
  <header>
@@ -1470,17 +1502,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1470
1502
  ${this.mode==="change"?l`
1471
1503
  <label>
1472
1504
  <span>当前密码</span>
1473
- <input type="password" .value=${this.currentPassword} autocomplete="current-password" @input=${e=>{this.currentPassword=js(e),this.localError=""}}>
1505
+ <input type="password" .value=${this.currentPassword} autocomplete="current-password" @input=${e=>{this.currentPassword=lr(e),this.localError=""}}>
1474
1506
  </label>
1475
1507
  `:null}
1476
1508
  <label>
1477
1509
  <span>${this.mode==="login"?"密码":"新密码"}</span>
1478
- <input type="password" .value=${this.password} autocomplete=${this.mode==="login"?"current-password":"new-password"} @input=${e=>{this.password=js(e),this.localError=""}}>
1510
+ <input type="password" .value=${this.password} autocomplete=${this.mode==="login"?"current-password":"new-password"} @input=${e=>{this.password=lr(e),this.localError=""}}>
1479
1511
  </label>
1480
1512
  ${this.mode!=="login"?l`
1481
1513
  <label>
1482
1514
  <span>确认密码</span>
1483
- <input type="password" .value=${this.confirmPassword} autocomplete="new-password" @input=${e=>{this.confirmPassword=js(e),this.localError=""}}>
1515
+ <input type="password" .value=${this.confirmPassword} autocomplete="new-password" @input=${e=>{this.confirmPassword=lr(e),this.localError=""}}>
1484
1516
  </label>
1485
1517
  `:null}
1486
1518
  ${this.message()===""?null:l`<p class="message">${this.message()}</p>`}
@@ -1491,7 +1523,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1491
1523
  </form>
1492
1524
  </section>
1493
1525
  </div>
1494
- `}dialogTitle(){return this.mode==="setup"?"设置进入密码":this.mode==="change"?"修改进入密码":"输入进入密码"}submitLabel(){return this.mode==="setup"?"设置并进入":this.mode==="change"?"保存密码":"进入"}message(){return this.localError||this.error}async submit(e){e.preventDefault();const t={currentPassword:this.currentPassword,password:this.password,confirmPassword:this.confirmPassword},i=Ly(this.mode,t);if(i!==void 0){this.localError=i;return}this.localError="",await this.onSubmit?.(t)}handleKeyDown(e){e.key!=="Escape"||this.mode!=="change"||(e.preventDefault(),e.stopPropagation(),this.onCancel?.())}};xe.styles=D`
1526
+ `}dialogTitle(){return this.mode==="setup"?"设置进入密码":this.mode==="change"?"修改进入密码":"输入进入密码"}submitLabel(){return this.mode==="setup"?"设置并进入":this.mode==="change"?"保存密码":"进入"}message(){return this.localError||this.error}async submit(e){e.preventDefault();const t={currentPassword:this.currentPassword,password:this.password,confirmPassword:this.confirmPassword},i=B0(this.mode,t);if(i!==void 0){this.localError=i;return}this.localError="",await this.onSubmit?.(t)}handleKeyDown(e){e.key!=="Escape"||this.mode!=="change"||(e.preventDefault(),e.stopPropagation(),this.onCancel?.())}};Ie.styles=D`
1495
1527
  :host { position: fixed; inset: 0; z-index: 40; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1496
1528
  .backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-bg); }
1497
1529
  section { width: min(420px, 100%); border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-surface); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -1505,11 +1537,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1505
1537
  input:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
1506
1538
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 8px 10px; font: inherit; cursor: pointer; }
1507
1539
  button:disabled { opacity: .6; cursor: default; }
1508
- .primary { border-color: var(--pi-accent); background: var(--pi-accent); color: var(--pi-accent-contrast); }
1540
+ .primary { border-color: var(--pi-accent); background: var(--pi-accent); color: #fff; }
1509
1541
  .close-button { width: 34px; height: 34px; display: grid; place-items: center; border: 0; background: transparent; color: var(--pi-muted); padding: 0; font-size: 24px; }
1510
1542
  .message { margin: 0; border: 1px solid var(--pi-danger-border); border-radius: 8px; background: var(--pi-danger-surface); color: var(--pi-danger); padding: 10px; }
1511
1543
  footer { display: flex; justify-content: flex-end; gap: 8px; }
1512
- `;ze([d()],xe.prototype,"mode",2);ze([d({type:Boolean})],xe.prototype,"loading",2);ze([d()],xe.prototype,"error",2);ze([d({attribute:!1})],xe.prototype,"onSubmit",2);ze([d({attribute:!1})],xe.prototype,"onCancel",2);ze([w()],xe.prototype,"currentPassword",2);ze([w()],xe.prototype,"password",2);ze([w()],xe.prototype,"confirmPassword",2);ze([w()],xe.prototype,"localError",2);xe=ze([W("normal-auth-dialog")],xe);function Ly(e,t){if(e==="change"&&(t.currentPassword??"")==="")return"请输入当前密码。";if(t.password==="")return"请输入密码。";if(e!=="login"&&t.password!==(t.confirmPassword??""))return"两次输入的密码不一致。"}function js(e){return e.target instanceof HTMLInputElement?e.target.value:""}var jy=Object.defineProperty,Fy=Object.getOwnPropertyDescriptor,Ue=(e,t,i,s)=>{for(var r=s>1?void 0:s?Fy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&jy(t,i,r),r};let Se=class extends R{constructor(){super(...arguments),this.machineId="local",this.path="",this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}firstUpdated(){this.pathInput?.focus()}async loadSuggestions(){const e=++this.requestId;this.loading=!0;try{const t=await N.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==""&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="Enter")e.preventDefault(),this.submit();else if(e.key==="ArrowDown")e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key==="ArrowUp")e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key==="Tab"){const t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return l`
1544
+ `;Ge([c()],Ie.prototype,"mode",2);Ge([c({type:Boolean})],Ie.prototype,"loading",2);Ge([c()],Ie.prototype,"error",2);Ge([c({attribute:!1})],Ie.prototype,"onSubmit",2);Ge([c({attribute:!1})],Ie.prototype,"onCancel",2);Ge([v()],Ie.prototype,"currentPassword",2);Ge([v()],Ie.prototype,"password",2);Ge([v()],Ie.prototype,"confirmPassword",2);Ge([v()],Ie.prototype,"localError",2);Ie=Ge([W("normal-auth-dialog")],Ie);function B0(e,t){if(e==="change"&&(t.currentPassword??"")==="")return"请输入当前密码。";if(t.password==="")return"请输入密码。";if(e!=="login"&&t.password!==(t.confirmPassword??""))return"两次输入的密码不一致。"}function lr(e){return e.target instanceof HTMLInputElement?e.target.value:""}var z0=Object.defineProperty,N0=Object.getOwnPropertyDescriptor,Qe=(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&&z0(t,i,r),r};let Ae=class extends I{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 K.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`
1513
1545
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1514
1546
  <section @click=${e=>{e.stopPropagation()}}>
1515
1547
  <header>
@@ -1541,7 +1573,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1541
1573
  </footer>
1542
1574
  </section>
1543
1575
  </div>
1544
- `}};Se.styles=D`
1576
+ `}};Ae.styles=D`
1545
1577
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1546
1578
  .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1547
1579
  section { width: min(720px, calc(100vw - 40px)); max-height: min(700px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -1559,7 +1591,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1559
1591
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1560
1592
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1561
1593
  button:disabled { opacity: .5; cursor: not-allowed; }
1562
- `;Ue([d({attribute:!1})],Se.prototype,"onSubmit",2);Ue([d({attribute:!1})],Se.prototype,"onCancel",2);Ue([d()],Se.prototype,"machineId",2);Ue([w()],Se.prototype,"path",2);Ue([w()],Se.prototype,"createMissing",2);Ue([w()],Se.prototype,"suggestions",2);Ue([w()],Se.prototype,"selected",2);Ue([w()],Se.prototype,"loading",2);Ue([B("input")],Se.prototype,"pathInput",2);Se=Ue([W("project-dialog")],Se);var zy=Object.defineProperty,Uy=Object.getOwnPropertyDescriptor,Be=(e,t,i,s)=>{for(var r=s>1?void 0:s?Uy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&zy(t,i,r),r};let ke=class extends R{constructor(){super(...arguments),this.error="",this.url="",this.name="",this.token="",this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=""}firstUpdated(){this.urlInput?.focus()}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;const t=e.target.value,i=By(t);(!this.nameEdited||this.name.trim()===""||this.name===this.previousSuggestedName)&&(this.name=i),this.previousSuggestedName=i,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.onCancel?.();return}e.key==="Enter"&&e.target instanceof HTMLInputElement&&e.target.name==="baseUrl"&&Fs(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){const e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){const e=this.url.trim(),t=this.name.trim();if(e===""||t===""||Fs(e)!==void 0)return;const i=this.token.trim();return{name:t,baseUrl:e,...i===""?{}:{token:i}}}render(){const e=this.url.trim()!=="",t=e?Fs(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1594
+ `;Qe([c({attribute:!1})],Ae.prototype,"onSubmit",2);Qe([c({attribute:!1})],Ae.prototype,"onCancel",2);Qe([c()],Ae.prototype,"machineId",2);Qe([v()],Ae.prototype,"path",2);Qe([v()],Ae.prototype,"createMissing",2);Qe([v()],Ae.prototype,"suggestions",2);Qe([v()],Ae.prototype,"selected",2);Qe([v()],Ae.prototype,"loading",2);Qe([q("input")],Ae.prototype,"pathInput",2);Ae=Qe([W("project-dialog")],Ae);var q0=Object.defineProperty,H0=Object.getOwnPropertyDescriptor,Je=(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&&q0(t,i,r),r};let Me=class extends I{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=K0(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"&&cr(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===""||cr(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?cr(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1563
1595
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1564
1596
  <section @click=${s=>{s.stopPropagation()}}>
1565
1597
  <form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
@@ -1594,7 +1626,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1594
1626
  </form>
1595
1627
  </section>
1596
1628
  </div>
1597
- `}};ke.styles=D`
1629
+ `}};Me.styles=D`
1598
1630
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
1599
1631
  .backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
1600
1632
  section { width: min(560px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
@@ -1614,204 +1646,410 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1614
1646
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1615
1647
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1616
1648
  button:disabled { opacity: .5; cursor: not-allowed; }
1617
- `;Be([d({attribute:!1})],ke.prototype,"onSubmit",2);Be([d({attribute:!1})],ke.prototype,"onCancel",2);Be([d()],ke.prototype,"error",2);Be([w()],ke.prototype,"url",2);Be([w()],ke.prototype,"name",2);Be([w()],ke.prototype,"token",2);Be([w()],ke.prototype,"submitting",2);Be([B("input[name='baseUrl']")],ke.prototype,"urlInput",2);Be([B("input[name='name']")],ke.prototype,"nameInput",2);ke=Be([W("machine-dialog")],ke);function By(e){const t=e.trim();if(t==="")return"";const i=oa(t)??oa(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):Ny(t)}function Fs(e){const t=e.trim();if(t==="")return"必须填写远程 PI WEB URL。";let i;try{i=new URL(t)}catch{return"请输入包含 http:// 或 https:// 的有效 URL。"}if(i.protocol!=="http:"&&i.protocol!=="https:")return"请使用 http:// 或 https:// URL。";if(i.username!==""||i.password!=="")return"机器 URL 中不要包含凭据。";if(i.search!==""||i.hash!=="")return"不要包含查询字符串或片段。"}function oa(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function Ny(e){const t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,""),s=t.slice(t.lastIndexOf("@")+1).split(/[/?#]/u)[0]??"";return s.startsWith("[")&&s.includes("]")?s.slice(1,s.indexOf("]")):s.replace(/:\d+$/u,"")}function Hy(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:"",allowedPathsText:""}}function qy(e){return{host:e.host??"",port:e.port===void 0?"":String(e.port),allowedHostsMode:e.allowedHosts===!0?"all":"list",allowedHostsText:Array.isArray(e.allowedHosts)?e.allowedHosts.join(`
1618
- `):"",allowedPathsText:e.pathAccess?.allowedPaths?.join(`
1619
- `)??""}}function Ky(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins},...t.normalAuth===void 0?{}:{normalAuth:t.normalAuth},...t.uploads===void 0?{}:{uploads:t.uploads},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes},...t.spawnSessions===void 0?{}:{spawnSessions:t.spawnSessions},...t.subsessions===void 0?{}:{subsessions:t.subsessions}},s=e.host.trim(),r=e.port.trim();if(s!==""&&(i.host=s),r!==""){const n=Number(r);if(!Number.isInteger(n)||n<1||n>65535)throw new Error("端口必须是 1 到 65535 之间的整数。");i.port=n}i.allowedHosts=e.allowedHostsMode==="all"?!0:Vy(e.allowedHostsText);const o=Gy(e.allowedPathsText);return o.length>0&&(i.pathAccess={allowedPaths:o}),i}function Vy(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}function Gy(e){const t=e.split(`
1620
- `).map(s=>s.trim()).filter(s=>s!==""),i=t.find(s=>!Jy(s));if(i!==void 0)throw new Error(`Allowed external paths must be absolute paths or start with ~: ${i}`);return t}function Jy(e){return e==="~"||e.startsWith("~/")||e.startsWith("~\\")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:[\\/]/u.test(e)}function fs(e,t){return e!==""?l`<div class="message error-message">${e}</div>`:t!==""?l`<div class="message success-message">${t}</div>`:null}const gs=D`
1621
- :host { display: block; }
1622
- .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1623
- .section-heading > div { display: grid; gap: 6px; min-width: 0; }
1624
- h2, h3, p { margin: 0; }
1625
- h2 { font-size: 17px; line-height: 1.25; }
1626
- h3 { font-size: 13px; line-height: 1.3; }
1627
- p { color: var(--pi-muted); line-height: 1.45; }
1628
- button, input, select, textarea { font: inherit; }
1629
- button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1630
- button:disabled, input:disabled { opacity: .55; cursor: not-allowed; }
1631
- .primary { border-color: var(--pi-accent); background: var(--pi-selection-bg); color: var(--pi-text-bright); }
1632
- .secondary { flex: 0 0 auto; }
1633
- .message, .loading-card, .config-path-card, .effective-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1634
- .message { margin-bottom: 12px; }
1635
- .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1636
- .success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1637
- .loading-card, .config-path-card { color: var(--pi-muted); }
1638
- .config-path-card { display: grid; gap: 5px; margin-bottom: 14px; }
1639
- .field { display: grid; gap: 7px; }
1640
- .field small { color: var(--pi-muted); }
1641
- .field-heading { display: flex; align-items: center; gap: 8px; }
1642
- .config-path-card span, .field-heading, dt { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
1643
- code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1644
- .override-badge { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); background: var(--pi-warning-surface); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: none; }
1645
- .effective-card { display: grid; gap: 10px; }
1646
- .effective-card dl { display: grid; gap: 8px; margin: 0; }
1647
- .effective-card dl > div { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 12px; align-items: baseline; }
1648
- dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
1649
- .muted { color: var(--pi-muted); }
1649
+ `;Je([c({attribute:!1})],Me.prototype,"onSubmit",2);Je([c({attribute:!1})],Me.prototype,"onCancel",2);Je([c()],Me.prototype,"error",2);Je([v()],Me.prototype,"url",2);Je([v()],Me.prototype,"name",2);Je([v()],Me.prototype,"token",2);Je([v()],Me.prototype,"submitting",2);Je([q("input[name='baseUrl']")],Me.prototype,"urlInput",2);Je([q("input[name='name']")],Me.prototype,"nameInput",2);Me=Je([W("machine-dialog")],Me);function K0(e){const t=e.trim();if(t==="")return"";const i=Da(t)??Da(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):V0(t)}function cr(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 Da(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function V0(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,"")}var G0=Object.defineProperty,Q0=Object.getOwnPropertyDescriptor,ht=(e,t,i,s)=>{for(var r=s>1?void 0:s?Q0(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};const J0={availability:"error",error:"error",success:"success",security:"warning",warning:"warning",info:"info"};function Z0(e){return e.tone??J0[e.type]}let Ve=class extends I{constructor(){super(...arguments),this.heading="",this.description="",this.actionLabel="",this.actionTitle="",this.actionDisabled=!1,this.notices=[]}render(){return l`
1650
+ <section class="panel" aria-label=${this.heading||"Settings panel"}>
1651
+ <header class="section-heading">
1652
+ <div class="heading-copy">
1653
+ ${this.heading===""?B:l`<h2>${this.heading}</h2>`}
1654
+ <div class="description"><slot name="description">${this.description}</slot></div>
1655
+ </div>
1656
+ <div class="heading-actions"><slot name="actions">${this.renderDefaultAction()}</slot></div>
1657
+ </header>
1658
+ ${this.renderNoticeStack()}
1659
+ <div class="content"><slot></slot></div>
1660
+ </section>
1661
+ `}renderDefaultAction(){return this.actionLabel===""?B:l`
1662
+ <button
1663
+ class="secondary"
1664
+ title=${this.actionTitle||this.actionLabel}
1665
+ ?disabled=${this.actionDisabled}
1666
+ @click=${()=>{this.onAction?.()}}
1667
+ >${this.actionLabel}</button>
1668
+ `}renderNoticeStack(){return this.notices.length===0?B:l`
1669
+ <div class="notice-stack" aria-label="Settings notices">
1670
+ ${this.notices.map(e=>this.renderNotice(e))}
1671
+ </div>
1672
+ `}renderNotice(e){const t=Z0(e),i=e.role??X0(t),s=e.title;return l`
1673
+ <article class=${`notice ${t}`} role=${i}>
1674
+ ${s===void 0||s===""?B:l`<strong class="notice-title">${s}</strong>`}
1675
+ <div class="notice-content">${e.content}</div>
1676
+ </article>
1677
+ `}};Ve.styles=D`
1678
+ :host { display: block; }
1679
+ .panel { display: block; }
1680
+ .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1681
+ .heading-copy { display: grid; gap: 6px; min-width: 0; }
1682
+ .heading-actions { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; }
1683
+ h2 { margin: 0; font-size: 17px; line-height: 1.25; }
1684
+ .description { color: var(--pi-muted); line-height: 1.45; }
1685
+ .description ::slotted(*) { margin: 0; }
1686
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; font: inherit; cursor: pointer; }
1687
+ button:disabled { opacity: .55; cursor: not-allowed; }
1688
+ .secondary { flex: 0 0 auto; }
1689
+ .notice-stack { display: grid; gap: 12px; margin-bottom: 14px; }
1690
+ .notice { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; line-height: 1.45; }
1691
+ .notice.error { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1692
+ .notice.success { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
1693
+ .notice.warning { border-color: var(--pi-warning-border); color: var(--pi-text); background: var(--pi-warning-surface); }
1694
+ .notice.info { color: var(--pi-muted); }
1695
+ .notice-title { display: block; margin-bottom: 4px; color: inherit; }
1696
+ .notice-content { min-width: 0; }
1697
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1698
+ .content { display: grid; gap: 14px; min-width: 0; }
1699
+ .content ::slotted(*) { min-width: 0; }
1650
1700
 
1651
- @media (max-width: 760px) {
1652
- .section-heading { display: grid; gap: 12px; }
1653
- .section-heading .secondary { justify-self: start; }
1654
- .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1655
- }
1656
- `;var Qy=Object.defineProperty,Zy=Object.getOwnPropertyDescriptor,Ne=(e,t,i,s)=>{for(var r=s>1?void 0:s?Zy(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Qy(t,i,r),r};let $e=class extends R{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=Hy(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=qy(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
1657
- <div class="section-heading">
1658
- <div>
1659
- <h2>通用配置</h2>
1660
- <p>更新 PI WEB 正在使用的 JSON 配置文件。Host 和端口会立即保存,但需要重启 Web 服务后,运行中的服务器才会绑定到新地址。</p>
1701
+ @media (max-width: 760px) {
1702
+ .section-heading { display: grid; gap: 12px; }
1703
+ .heading-actions { justify-self: start; }
1704
+ }
1705
+ `;ht([c()],Ve.prototype,"heading",2);ht([c({attribute:!1})],Ve.prototype,"description",2);ht([c()],Ve.prototype,"actionLabel",2);ht([c()],Ve.prototype,"actionTitle",2);ht([c({type:Boolean})],Ve.prototype,"actionDisabled",2);ht([c({attribute:!1})],Ve.prototype,"notices",2);ht([c({attribute:!1})],Ve.prototype,"onAction",2);Ve=ht([W("settings-panel-frame")],Ve);function X0(e){switch(e){case"error":return"alert";case"success":return"status";case"warning":case"info":return"note"}}function Y0(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function eS(){return{allowedPathsText:"",uploadDefaultFolder:""}}function tS(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(`
1706
+ `):""}}function iS(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
1707
+ `)??"",uploadDefaultFolder:e.uploads?.defaultFolder??""}}function sS(e,t={}){const i=oS(t),s=e.host.trim(),r=e.port.trim();if(s!==""&&(i.host=s),r!==""){const o=Number(r);if(!Number.isInteger(o)||o<1||o>65535)throw new Error("端口必须是 1 到 65535 之间的整数。");i.port=o}return i.allowedHosts=e.allowedHostsMode==="all"?!0:nS(e.allowedHostsText),i}function rS(e){const t=aS(e.allowedPathsText),i=lS(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:i===""?{}:{defaultFolder:i}}}function oS(e){return{...e.shortcuts===void 0?{}:{shortcuts:e.shortcuts},...e.plugins===void 0?{}:{plugins:e.plugins},...e.normalAuth===void 0?{}:{normalAuth:e.normalAuth},...e.pathAccess===void 0?{}:{pathAccess:e.pathAccess},...e.uploads===void 0?{}:{uploads:e.uploads},...e.maxUploadBytes===void 0?{}:{maxUploadBytes:e.maxUploadBytes},...e.spawnSessions===void 0?{}:{spawnSessions:e.spawnSessions},...e.subsessions===void 0?{}:{subsessions:e.subsessions}}}function nS(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}function aS(e){const t=e.split(`
1708
+ `).map(s=>s.trim()).filter(s=>s!==""),i=t.find(s=>!cS(s));if(i!==void 0)throw new Error(`Allowed external paths must be absolute paths or start with ~: ${i}`);return t}function lS(e){const t=e.trim();if(t==="")return"";if(dS(t))throw new Error("Upload default folder must be workspace-relative.");const i=t.split(/[\\/]+/u).filter(s=>s!==""&&s!==".");if(i.length===0)return"";if(i.some(s=>s===".."))throw new Error("Upload default folder must not contain path traversal.");return i.join("/")}function cS(e){return e==="~"||e.startsWith("~/")||e.startsWith("~\\")||e.startsWith("/")||e.startsWith("\\")||/^[A-Za-z]:[\\/]/u.test(e)}function dS(e){const t=e.replace(/\\/g,"/");return t.startsWith("/")||/^[A-Za-z]:\//u.test(t)}var pS=Object.defineProperty,hS=Object.getOwnPropertyDescriptor,Z=(e,t,i,s)=>{for(var r=s>1?void 0:s?hS(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&&pS(t,i,r),r};function uS(e){return l`网关服务器字段用于编辑当前本地网关;文件访问和上传默认值用于编辑 ${e}。`}let G=class extends I{constructor(){super(...arguments),this.loading=!1,this.machineLoading=!1,this.saving=!1,this.error="",this.machineError="",this.savedMessage="",this.targetLabel="selected machine",this.gatewayDraft=Y0(),this.machineDraft=eS(),this.gatewayLocalError="",this.machineLocalError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.gatewayDraft=tS(this.configResponse.config),this.gatewayLocalError=""),e.has("machineConfigResponse")&&this.machineConfigResponse!==void 0&&(this.machineDraft=iS(this.machineConfigResponse.config),this.machineLocalError="")}render(){return l`
1709
+ <settings-panel-frame
1710
+ heading="通用配置"
1711
+ .description=${uS(this.targetLabel)}
1712
+ actionLabel="重新加载"
1713
+ .actionDisabled=${this.loading||this.machineLoading}
1714
+ .notices=${this.panelNotices()}
1715
+ .onAction=${()=>{this.reloadAll()}}
1716
+ >
1717
+ <div class="settings-sections">
1718
+ ${this.renderGatewayServerSettings()}
1719
+ ${this.renderSelectedMachineAccessSettings()}
1661
1720
  </div>
1662
- <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>重新加载</button>
1663
- </div>
1664
- ${this.renderMessages()}
1665
- ${e===void 0&&this.loading?l`<div class="loading-card">正在加载配置…</div>`:l`
1666
- <div class="config-path-card">
1667
- <span>配置文件</span>
1668
- <code>${e?.path??"未知"}</code>
1669
- <small>${e?.exists===!0?"已有文件":"保存时会创建此文件"}</small>
1721
+ </settings-panel-frame>
1722
+ `}renderGatewayServerSettings(){const e=this.configResponse;return l`
1723
+ <section class="settings-card" aria-label="网关服务器设置">
1724
+ <div class="card-heading">
1725
+ <h3>网关服务器</h3>
1726
+ <p>Host、端口和允许的 host 会保存到网关配置中。地址变更后必须重启 Web 服务,运行中的服务器才会绑定到新地址。</p>
1670
1727
  </div>
1671
- <form class="config-form" @submit=${t=>{this.saveConfig(t)}}>
1672
- <label class="field">
1673
- <span class="field-heading">
1674
- <span>Host</span>
1675
- ${this.renderOverrideBadge("host")}
1676
- </span>
1677
- <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:na(t)})}}>
1678
- <small>Web 服务器应绑定的地址。留空则使用 PI WEB 默认值。</small>
1679
- </label>
1728
+ ${e===void 0&&this.loading?l`<div class="loading-card">正在加载网关配置…</div>`:l`
1729
+ <div class="config-path-card">
1730
+ <span>网关配置文件</span>
1731
+ <code>${e?.path??"未知"}</code>
1732
+ <small>${e?.exists===!0?"已有文件":"保存时会创建此文件"}</small>
1733
+ </div>
1734
+ <form class="config-form" @submit=${t=>{this.saveGatewayConfig(t)}}>
1735
+ <label class="field">
1736
+ <span class="field-heading">
1737
+ <span>Host</span>
1738
+ ${this.renderOverrideBadge("host")}
1739
+ </span>
1740
+ <input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateGatewayDraft({host:dr(t)})}}>
1741
+ <small>Web 服务器应绑定的地址。留空则使用 PI WEB 默认值。</small>
1742
+ </label>
1680
1743
 
1681
- <label class="field">
1682
- <span class="field-heading">
1683
- <span>Port</span>
1684
- ${this.renderOverrideBadge("port")}
1685
- </span>
1686
- <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:na(t)})}}>
1687
- <small>TCP 端口,范围 1 到 65535。留空则使用 PI WEB 默认值。</small>
1688
- </label>
1744
+ <label class="field">
1745
+ <span class="field-heading">
1746
+ <span>Port</span>
1747
+ ${this.renderOverrideBadge("port")}
1748
+ </span>
1749
+ <input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateGatewayDraft({port:dr(t)})}}>
1750
+ <small>TCP 端口,范围 1 到 65535。留空则使用 PI WEB 默认值。</small>
1751
+ </label>
1689
1752
 
1690
- <div class="field">
1691
- <span class="field-heading">
1692
- <span>允许的 hosts</span>
1693
- ${this.renderOverrideBadge("allowedHosts")}
1694
- </span>
1695
- <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:e0(t)==="all"?"all":"list"})}}>
1696
- <option value="list">仅允许列出的 hosts</option>
1697
- <option value="all">允许所有 host</option>
1698
- </select>
1699
- <textarea .value=${this.draft.allowedHostsText} ?disabled=${this.draft.allowedHostsMode==="all"} rows="4" placeholder="example.local&#10;192.168.1.20" spellcheck="false" @input=${t=>{this.updateDraft({allowedHostsText:aa(t)})}}></textarea>
1700
- <small>每行输入一个 host,或选择“允许所有 host”写入 <code>true</code>。</small>
1753
+ <div class="field">
1754
+ <span class="field-heading">
1755
+ <span>允许的 hosts</span>
1756
+ ${this.renderOverrideBadge("allowedHosts")}
1757
+ </span>
1758
+ <select .value=${this.gatewayDraft.allowedHostsMode} @change=${t=>{this.updateGatewayDraft({allowedHostsMode:mS(t)==="all"?"all":"list"})}}>
1759
+ <option value="list">仅允许列出的 hosts</option>
1760
+ <option value="all">允许所有 host</option>
1761
+ </select>
1762
+ <textarea .value=${this.gatewayDraft.allowedHostsText} ?disabled=${this.gatewayDraft.allowedHostsMode==="all"} rows="4" placeholder="example.local&#10;192.168.1.20" spellcheck="false" @input=${t=>{this.updateGatewayDraft({allowedHostsText:Wa(t)})}}></textarea>
1763
+ <small>每行输入一个 host,或选择“允许所有 host”写入 <code>true</code>。</small>
1764
+ </div>
1765
+
1766
+ ${this.renderGatewayEffectiveConfig()}
1767
+
1768
+ <footer class="form-actions">
1769
+ <button class="primary" ?disabled=${this.loading||this.saving}>${this.saving?"正在保存…":"保存网关服务器配置"}</button>
1770
+ </footer>
1771
+ </form>
1772
+ `}
1773
+ </section>
1774
+ `}renderSelectedMachineAccessSettings(){const e=this.machineConfigResponse;return l`
1775
+ <section class="settings-card" aria-label="所选机器的文件访问和上传设置">
1776
+ <div class="card-heading">
1777
+ <h3>所选机器的文件访问和上传</h3>
1778
+ <p>外部文件系统根目录和上传默认值会保存到 ${this.targetLabel}。</p>
1779
+ </div>
1780
+ ${this.renderMachineMessages()}
1781
+ ${e===void 0?l`<div class="loading-card">${this.machineLoading?"正在加载所选机器的文件访问配置…":"所选机器的文件访问配置不可用。保存文件/上传设置前请重新加载。"}</div>`:l`
1782
+ <div class="config-path-card">
1783
+ <span>所选机器配置文件</span>
1784
+ <code>${e.path}</code>
1785
+ <small>${e.exists?"已有文件":"保存时会创建此文件"}</small>
1701
1786
  </div>
1787
+ <form class="config-form" @submit=${t=>{this.saveMachineAccessConfig(t)}}>
1788
+ <label class="field">
1789
+ <span class="field-heading">
1790
+ <span>外部文件系统根目录</span>
1791
+ </span>
1792
+ <textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${t=>{this.updateMachineDraft({allowedPathsText:Wa(t)})}}></textarea>
1793
+ <small>${this.targetLabel} 上允许用于绝对路径 <code>@</code> 补全和工作区外文件读取的目录。每行输入一个绝对路径、Windows 绝对路径或以 <code>~</code> 开头的路径。留空则默认禁止外部路径。</small>
1794
+ </label>
1702
1795
 
1703
- <label class="field">
1704
- <span class="field-heading">
1705
- <span>External filesystem roots</span>
1706
- </span>
1707
- <textarea .value=${this.draft.allowedPathsText} rows="4" placeholder="~/SDKs&#10;/opt/reference" spellcheck="false" @input=${t=>{this.updateDraft({allowedPathsText:aa(t)})}}></textarea>
1708
- <small>Global allowlist for absolute <code>@</code> completions and file explorer reads outside a workspace. Enter one absolute path, Windows absolute path, or <code>~</code>-prefixed path per line. Leave empty to deny external paths by default.</small>
1709
- </label>
1796
+ <label class="field">
1797
+ <span class="field-heading">
1798
+ <span>默认上传文件夹</span>
1799
+ </span>
1800
+ <input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${di} autocomplete="off" spellcheck="false" @input=${t=>{this.updateMachineDraft({uploadDefaultFolder:dr(t)})}}>
1801
+ <small>${this.targetLabel} 上手动上传文件使用的工作区相对目录。留空则使用 PI WEB 默认值 <code>${di}</code>。</small>
1802
+ </label>
1710
1803
 
1711
- ${this.renderEffectiveConfig()}
1804
+ ${this.renderMachineEffectiveConfig()}
1712
1805
 
1713
- <footer class="form-actions">
1714
- <button class="primary" ?disabled=${this.loading||this.saving}>${this.saving?"正在保存…":"保存配置"}</button>
1715
- </footer>
1716
- </form>
1717
- `}
1718
- `}renderMessages(){const e=this.localError||this.error;return fs(e,this.savedMessage)}renderOverrideBadge(e){return this.configResponse?.envOverrides[e]!==!0?null:l`<span class="override-badge">环境变量覆盖</span>`}renderEffectiveConfig(){const e=this.configResponse?.effectiveConfig??{};return l`
1806
+ <footer class="form-actions">
1807
+ <button class="primary" ?disabled=${this.machineLoading||this.saving}>${this.saving?"正在保存…":"保存文件/上传配置"}</button>
1808
+ </footer>
1809
+ </form>
1810
+ `}
1811
+ </section>
1812
+ `}panelNotices(){const e=[],t=this.gatewayLocalError||this.error;return t!==""&&e.push({type:"error",title:"网关服务器",content:t}),this.savedMessage!==""&&e.push({type:"success",content:this.savedMessage}),e}renderMachineMessages(){const e=this.machineLocalError||this.machineError;return e===""?null:l`<div class="message error-message">${e}</div>`}renderOverrideBadge(e){return this.configResponse?.envOverrides[e]!==!0?null:l`<span class="override-badge">环境变量覆盖</span>`}renderGatewayEffectiveConfig(){const e=this.configResponse?.effectiveConfig??{};return l`
1719
1813
  <section class="effective-card" aria-label="最终生效配置摘要">
1720
- <h3>环境变量覆盖后的生效配置</h3>
1814
+ <h3>环境变量覆盖后的网关生效配置</h3>
1721
1815
  <dl>
1722
1816
  <div><dt>Host</dt><dd>${e.host??l`<span class="muted">默认 127.0.0.1</span>`}</dd></div>
1723
1817
  <div><dt>端口</dt><dd>${e.port??l`<span class="muted">默认 8504</span>`}</dd></div>
1724
- <div><dt>允许的 hosts</dt><dd>${Xy(e.allowedHosts)}</dd></div>
1725
- <div><dt>外部根目录</dt><dd>${Yy(e.pathAccess?.allowedPaths)}</dd></div>
1818
+ <div><dt>允许的 hosts</dt><dd>${fS(e.allowedHosts)}</dd></div>
1819
+ </dl>
1820
+ </section>
1821
+ `}renderMachineEffectiveConfig(){const e=this.machineConfigResponse?.effectiveConfig??{};return l`
1822
+ <section class="effective-card" aria-label="所选机器最终生效的文件访问和上传摘要">
1823
+ <h3>所选机器的生效配置</h3>
1824
+ <dl>
1825
+ <div><dt>外部根目录</dt><dd>${gS(e.pathAccess?.allowedPaths)}</dd></div>
1826
+ <div><dt>上传文件夹</dt><dd>${e.uploads?.defaultFolder??l`<span class="muted">默认 ${di}</span>`}</dd></div>
1726
1827
  </dl>
1727
1828
  </section>
1728
- `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(Ky(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=t0(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};$e.styles=[gs,D`
1829
+ `}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError="";try{await this.onSave?.(sS(this.gatewayDraft,this.configResponse?.config??{}))}catch(t){this.gatewayLocalError=La(t)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError="";try{await this.onSaveMachineConfig?.(rS(this.machineDraft))}catch(t){this.machineLocalError=La(t)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=""}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=""}};G.styles=D`
1830
+ :host { display: block; }
1831
+ .card-heading { display: grid; gap: 6px; min-width: 0; }
1832
+ h3, p { margin: 0; }
1833
+ h3 { font-size: 13px; line-height: 1.3; }
1834
+ p { color: var(--pi-muted); line-height: 1.45; }
1835
+ button, input, select, textarea { font: inherit; }
1836
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1837
+ button:disabled { opacity: .55; cursor: not-allowed; }
1838
+ .settings-sections { display: grid; gap: 14px; }
1839
+ .settings-card, .message, .loading-card, .config-path-card, .effective-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1840
+ .settings-card { display: grid; gap: 14px; }
1841
+ .message { margin-bottom: 12px; }
1842
+ .settings-card .message { margin-bottom: 0; }
1843
+ .error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
1844
+ .loading-card { color: var(--pi-muted); }
1845
+ .config-path-card { display: grid; gap: 5px; }
1846
+ .config-path-card span, .field-heading, dt { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
1847
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1848
+ .config-path-card small, .field small { color: var(--pi-muted); }
1729
1849
  .config-form { display: grid; gap: 14px; }
1730
1850
  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); }
1731
1851
  input:focus, select:focus, textarea:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
1732
1852
  textarea { resize: vertical; min-height: 94px; font-family: var(--pi-control-monospace-font-family, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); }
1733
1853
  textarea:disabled { opacity: .55; }
1734
1854
  .form-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 2px; }
1735
- `];Ne([d({attribute:!1})],$e.prototype,"configResponse",2);Ne([d({type:Boolean})],$e.prototype,"loading",2);Ne([d({type:Boolean})],$e.prototype,"saving",2);Ne([d()],$e.prototype,"error",2);Ne([d()],$e.prototype,"savedMessage",2);Ne([d({attribute:!1})],$e.prototype,"onReload",2);Ne([d({attribute:!1})],$e.prototype,"onSave",2);Ne([w()],$e.prototype,"draft",2);Ne([w()],$e.prototype,"localError",2);$e=Ne([W("settings-general-panel")],$e);function Xy(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?l`<span class="muted">未列出</span>`:e.join(", "):l`<span class="muted">未设置</span>`}function Yy(e){return e===void 0||e.length===0?l`<span class="muted">已禁止外部路径</span>`:e.join(", ")}function na(e){return e.target instanceof HTMLInputElement?e.target.value:""}function e0(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function aa(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function t0(e){return e instanceof Error?e.message:String(e)}var i0=Object.defineProperty,s0=Object.getOwnPropertyDescriptor,st=(e,t,i,s)=>{for(var r=s>1?void 0:s?s0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&i0(t,i,r),r};let Fe=class extends R{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,i=e?.effectiveConfig.spawnSessions!==!1,s=e?.envOverrides.subsessions===!0,r=e?.effectiveConfig.subsessions===!0&&i;return l`
1736
- <div class="section-heading">
1737
- <div>
1738
- <h2>会话守护进程</h2>
1739
- <p>这些设置会影响长生命周期的会话运行时。更改会立即保存到配置文件,但只有在会话守护进程重启后才会生效。</p>
1740
- </div>
1741
- <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>重新加载</button>
1742
- </div>
1743
- ${this.renderMessages()}
1744
- <div class="restart-note" role="note">需要重启:更改这些设置后,运行 <code>pi-web restart</code>,或重启会话守护进程服务。</div>
1745
- ${e===void 0&&this.loading?l`<div class="loading-card">正在加载配置...</div>`:l`
1746
- <div class="config-path-card">
1747
- <span>配置文件</span>
1748
- <code>${e?.path??"未知"}</code>
1749
- </div>
1750
- <div class="field">
1751
- <span class="field-heading">
1752
- <span>允许代理启动会话</span>
1753
- ${t?l`<span class="override-badge">环境变量覆盖</span>`:null}
1754
- </span>
1755
- <label class="toggle">
1756
- <input
1757
- type="checkbox"
1758
- .checked=${i}
1759
- ?disabled=${this.loading||this.saving||t}
1760
- @change=${o=>{this.toggleSpawnSessions(o)}}
1761
- >
1762
- <span>启用 <code>spawn_session</code> 工具</span>
1763
- </label>
1764
- <small>启用后,LLM 可以启动新会话,但会被限制在同一个已注册项目的工作区(包括任意 worktree)内,因此每个派生会话都会显示在这里。默认启用。</small>
1765
- </div>
1766
- <div class="field">
1767
- <span class="field-heading">
1768
- <span>允许代理启动受跟踪的子会话</span>
1769
- <span class="beta-badge">beta</span>
1770
- ${s?l`<span class="override-badge">环境变量覆盖</span>`:null}
1771
- </span>
1772
- <label class="toggle">
1773
- <input
1774
- type="checkbox"
1775
- .checked=${r}
1776
- ?disabled=${this.loading||this.saving||s||!i}
1777
- @change=${o=>{this.toggleSubsessions(o)}}
1778
- >
1779
- <span>启用 <code>spawn_subsession</code> 工具</span>
1780
- </label>
1781
- <small>Beta:代理可以启动自己持续关联的子会话(<code>spawn_subsession</code>、<code>list_subsessions</code>、<code>check_subsession</code>、<code>read_subsession</code>),并在子会话完成时收到通知。需要先启用“允许代理启动会话”。默认关闭。</small>
1782
- </div>
1783
- <section class="effective-card" aria-label="最终生效配置摘要">
1784
- <h3>环境变量覆盖后的生效配置</h3>
1785
- <dl>
1786
- <div><dt>派生会话</dt><dd>${i?"已启用":l`<span class="muted">已禁用</span>`}</dd></div>
1787
- <div><dt>子会话</dt><dd>${r?"已启用":l`<span class="muted">已禁用</span>`}</dd></div>
1788
- </dl>
1789
- </section>
1790
- `}
1791
- `}renderMessages(){return fs(this.error,this.savedMessage)}async toggleSpawnSessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,spawnSessions:t})}async toggleSubsessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked,i=this.configResponse?.config??{};await this.onSave?.({...i,subsessions:t})}};Fe.styles=[gs,D`
1792
- .restart-note { margin-bottom: 14px; border: 1px solid var(--pi-warning-border); border-radius: 10px; background: var(--pi-warning-surface); color: var(--pi-warning); padding: 12px; line-height: 1.45; }
1793
- .field { margin-bottom: 14px; }
1794
- .field small { line-height: 1.45; }
1855
+ .primary { border-color: var(--pi-accent); background: var(--pi-selection-bg); color: var(--pi-text-bright); }
1856
+
1857
+ @media (max-width: 760px) {
1858
+ .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1859
+ }
1860
+ `;Z([c({attribute:!1})],G.prototype,"configResponse",2);Z([c({attribute:!1})],G.prototype,"machineConfigResponse",2);Z([c({type:Boolean})],G.prototype,"loading",2);Z([c({type:Boolean})],G.prototype,"machineLoading",2);Z([c({type:Boolean})],G.prototype,"saving",2);Z([c()],G.prototype,"error",2);Z([c()],G.prototype,"machineError",2);Z([c()],G.prototype,"savedMessage",2);Z([c()],G.prototype,"targetLabel",2);Z([c({attribute:!1})],G.prototype,"onReload",2);Z([c({attribute:!1})],G.prototype,"onReloadMachine",2);Z([c({attribute:!1})],G.prototype,"onSave",2);Z([c({attribute:!1})],G.prototype,"onSaveMachineConfig",2);Z([v()],G.prototype,"gatewayDraft",2);Z([v()],G.prototype,"machineDraft",2);Z([v()],G.prototype,"gatewayLocalError",2);Z([v()],G.prototype,"machineLocalError",2);G=Z([W("settings-general-panel")],G);function fS(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?l`<span class="muted">未列出</span>`:e.join(", "):l`<span class="muted">未设置</span>`}function gS(e){return e===void 0||e.length===0?l`<span class="muted">已禁止外部路径</span>`:e.join(", ")}function dr(e){return e.target instanceof HTMLInputElement?e.target.value:""}function mS(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function Wa(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function La(e){return e instanceof Error?e.message:String(e)}function vS(e){return{spawnSessions:e}}function bS(e){return{subsessions:e}}function wS(e,t){return{...e,config:{...e.config,...t.config},effectiveConfig:{...e.effectiveConfig,...t.effectiveConfig},envOverrides:{...e.envOverrides,spawnSessions:t.envOverrides.spawnSessions,subsessions:t.envOverrides.subsessions}}}var yS=Object.defineProperty,SS=Object.getOwnPropertyDescriptor,rt=(e,t,i,s)=>{for(var r=s>1?void 0:s?SS(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&&yS(t,i,r),r};let Ue=class extends I{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.targetLabel="local (local gateway)"}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`
1861
+ <settings-panel-frame
1862
+ heading="会话守护进程"
1863
+ .description=${xS(this.targetLabel)}
1864
+ actionLabel="重新加载"
1865
+ .actionDisabled=${this.loading}
1866
+ .notices=${this.panelNotices(e)}
1867
+ .onAction=${this.onReload}
1868
+ >
1869
+ ${e===void 0?this.renderUnavailableConfigState():l`
1870
+ <div class="config-path-card">
1871
+ <span>配置文件</span>
1872
+ <code>${e.path}</code>
1873
+ </div>
1874
+ <div class="field">
1875
+ <span class="field-heading">
1876
+ <span>允许代理启动会话</span>
1877
+ ${t?l`<span class="override-badge">环境变量覆盖</span>`:null}
1878
+ </span>
1879
+ <label class="toggle">
1880
+ <input
1881
+ type="checkbox"
1882
+ .checked=${i}
1883
+ ?disabled=${this.loading||this.saving||t}
1884
+ @change=${o=>{this.toggleSpawnSessions(o)}}
1885
+ >
1886
+ <span>启用 <code>spawn_session</code> 工具</span>
1887
+ </label>
1888
+ <small>启用后,LLM 可以启动新会话,但会被限制在同一个已注册项目的工作区(包括任意 worktree)内,因此每个派生会话都会显示在这里。默认启用。</small>
1889
+ </div>
1890
+ <div class="field">
1891
+ <span class="field-heading">
1892
+ <span>允许代理启动受跟踪的子会话</span>
1893
+ <span class="beta-badge">beta</span>
1894
+ ${s?l`<span class="override-badge">环境变量覆盖</span>`:null}
1895
+ </span>
1896
+ <label class="toggle">
1897
+ <input
1898
+ type="checkbox"
1899
+ .checked=${r}
1900
+ ?disabled=${this.loading||this.saving||s||!i}
1901
+ @change=${o=>{this.toggleSubsessions(o)}}
1902
+ >
1903
+ <span>启用 <code>spawn_subsession</code> 工具</span>
1904
+ </label>
1905
+ <small>Beta:代理可以启动自己持续关联的子会话(<code>spawn_subsession</code>、<code>list_subsessions</code>、<code>check_subsession</code>、<code>read_subsession</code>),并在子会话完成时收到通知。需要先启用“允许代理启动会话”。默认关闭。</small>
1906
+ </div>
1907
+ <section class="effective-card" aria-label="最终生效配置摘要">
1908
+ <h3>环境变量覆盖后的生效配置</h3>
1909
+ <dl>
1910
+ <div><dt>派生会话</dt><dd>${i?"已启用":l`<span class="muted">已禁用</span>`}</dd></div>
1911
+ <div><dt>子会话</dt><dd>${r?"已启用":l`<span class="muted">已禁用</span>`}</dd></div>
1912
+ </dl>
1913
+ </section>
1914
+ `}
1915
+ </settings-panel-frame>
1916
+ `}panelNotices(e){const t=[];return this.error!==""&&t.push({type:"error",content:this.error}),this.savedMessage!==""&&t.push({type:"success",content:this.savedMessage}),e!==void 0&&t.push({type:"warning",title:`${this.targetLabel} 需要重启`,content:l`更改这些设置后,请在该机器上运行 <code>pi-web restart</code>,或重启其会话守护进程服务。`}),t}renderUnavailableConfigState(){return l`<div class="loading-card">${this.loading?"正在加载配置…":"配置不可用,请重新加载。"}</div>`}async toggleSpawnSessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(vS(t))}async toggleSubsessions(e){const t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(bS(t))}};Ue.styles=D`
1917
+ :host { display: block; }
1918
+ h3 { margin: 0; font-size: 13px; line-height: 1.3; }
1919
+ button, input { font: inherit; }
1920
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1921
+ button:disabled { opacity: .55; cursor: not-allowed; }
1922
+ .loading-card, .config-path-card, .effective-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1923
+ .loading-card { color: var(--pi-muted); }
1924
+ .config-path-card { display: grid; gap: 5px; }
1925
+ .config-path-card span, .field-heading, dt { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
1926
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1927
+ .field { display: grid; gap: 7px; }
1928
+ .field small { color: var(--pi-muted); line-height: 1.45; }
1929
+ .field-heading { display: flex; align-items: center; gap: 8px; }
1795
1930
  .toggle { display: flex; align-items: center; gap: 9px; cursor: pointer; }
1796
1931
  .toggle input { width: 16px; height: 16px; }
1797
1932
  .toggle input:disabled { cursor: not-allowed; }
1798
1933
  .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; }
1799
- `];st([d({attribute:!1})],Fe.prototype,"configResponse",2);st([d({type:Boolean})],Fe.prototype,"loading",2);st([d({type:Boolean})],Fe.prototype,"saving",2);st([d()],Fe.prototype,"error",2);st([d()],Fe.prototype,"savedMessage",2);st([d({attribute:!1})],Fe.prototype,"onReload",2);st([d({attribute:!1})],Fe.prototype,"onSave",2);Fe=st([W("settings-sessiond-panel")],Fe);var r0=Object.defineProperty,o0=Object.getOwnPropertyDescriptor,Qe=(e,t,i,s)=>{for(var r=s>1?void 0:s?o0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&r0(t,i,r),r};let De=class extends R{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
1800
- <div class="section-heading">
1801
- <div>
1802
- <h2>插件</h2>
1803
- <p>启用或禁用已发现的 PI WEB 插件。更改会在重新加载浏览器标签页后生效;当前页面已加载的插件代码不会被卸载。</p>
1934
+ .effective-card { display: grid; gap: 10px; }
1935
+ .effective-card dl { display: grid; gap: 8px; margin: 0; }
1936
+ .effective-card dl > div { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 12px; align-items: baseline; }
1937
+ dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
1938
+ .muted { color: var(--pi-muted); }
1939
+
1940
+ @media (max-width: 760px) {
1941
+ .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1942
+ }
1943
+ `;rt([c({attribute:!1})],Ue.prototype,"configResponse",2);rt([c({type:Boolean})],Ue.prototype,"loading",2);rt([c({type:Boolean})],Ue.prototype,"saving",2);rt([c()],Ue.prototype,"error",2);rt([c()],Ue.prototype,"savedMessage",2);rt([c()],Ue.prototype,"targetLabel",2);rt([c({attribute:!1})],Ue.prototype,"onReload",2);rt([c({attribute:!1})],Ue.prototype,"onSave",2);Ue=rt([W("settings-sessiond-panel")],Ue);function xS(e){return`这些设置会影响 ${e} 上长生命周期的会话运行时。更改会立即保存,但只有在该机器的会话守护进程重启后才会生效。`}function Kc(e){return{id:"local",name:"local",kind:"local"}}function xt(e){return e.kind==="local"?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function Oa(e,t){return e.kind==="local"?{state:"supported"}:t?.ok!==!0?{state:"unknown"}:Pe(t,we.piPackagesManage)?{state:"supported"}:{state:"unsupported",message:Vc(e)}}function Fa(e){return`${e.state}:${e.message??""}`}function Mo(e){return e?.state==="unsupported"}function Vc(e){return`Pi package management is not available on ${e.name}. Update and restart Pi-Web on that machine, then try again.`}function kS(e){return e.kind==="local"}function Gc(e){return e.trim()}function $S(e){if(Gc(e)==="")return"Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path."}function PS(e){return e.scope==="project"?"Project scope":"User scope"}function CS(e){return e.filtered?"Filtered by current Pi package settings":"Available in this PI WEB process"}function RS(e){return e.installedPath??"Installed path not reported by Pi"}function Qc(e){return e.scope==="user"}function IS(e){if(!Qc(e))return"Project-scope Pi packages are listed for visibility, but PI WEB only updates user-scope Pi packages safely from this view."}function AS(e){return e.length>0&&e.every(Qc)}function MS(e){if(e.length===0)return"No Pi packages are configured yet.";if(!AS(e))return"Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually."}function Di(e,t,i){return e?.kind!==t?!1:i===void 0||e.source===i}function TS(e,t=Kc()){const i=e==="install"?"installed":e==="remove"?"removed":"updated",s=t.kind==="local"?"":` on ${t.name}`,r=t.kind==="local"?"each idle PI WEB session":`each idle PI WEB session on ${t.name}`,o=t.kind==="local"?"PI WEB browser plugin changes":`PI WEB browser plugin changes served by ${t.name}`;return`Pi package ${i}${s}. Type /reload in ${r} to rediscover Pi runtime resources: extensions, skills, prompt templates, themes, and context/system prompt files. Reload the browser page separately for ${o}.`}function Jc(e,t){const i=e.trim();return t.kind!=="remote"?i:ES(i)?Vc(t):i==="Remote machine timeout"?`Timed out while contacting ${t.name} for Pi package management. The package operation may still be running remotely; reload the package list before retrying.`:i==="Remote machine unavailable"?`Could not reach ${t.name} for Pi package management. Check the machine connection and try again.`:i}function ES(e){return e==="Not Found"||/route\s+(GET|POST):?\/api\/pi-packages\b.*not found/iu.test(e)||/cannot\s+(GET|POST)\s+.*\/api\/pi-packages\b/iu.test(e)}var DS=Object.defineProperty,WS=Object.getOwnPropertyDescriptor,ve=(e,t,i,s)=>{for(var r=s>1?void 0:s?WS(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&&DS(t,i,r),r};let ne=class extends I{constructor(){super(...arguments),this.loading=!1,this.error="",this.operationMessage="",this.installSource="",this.validationMessage=""}render(){const e=this.packagesResponse?.packages??[],t=this.packageTarget,i=xt(t),s=this.packageManagementUnavailable,r=this.packagesResponse!==void 0&&!s;return l`
1944
+ <settings-panel-frame
1945
+ heading="Pi packages"
1946
+ .description=${LS(i)}
1947
+ actionLabel="Reload"
1948
+ actionTitle=${s?this.packageManagementUnavailableMessage(i):`Reload Pi packages from ${i}`}
1949
+ .actionDisabled=${this.loading||this.isOperating||s}
1950
+ .notices=${this.panelNotices(i,r)}
1951
+ .onAction=${this.onReload}
1952
+ >
1953
+ ${this.renderPanelContent(e,t,i)}
1954
+ </settings-panel-frame>
1955
+ `}panelNotices(e,t){const i=[];return this.packageManagementUnavailable?i.push({type:"availability",content:this.packageManagementUnavailableMessage(e)}):this.error!==""&&i.push({type:"error",content:this.error}),this.operationMessage!==""&&i.push({type:"success",content:this.operationMessage}),t&&i.push({type:"security",content:l`<strong>Trusted code warning:</strong> Pi packages and PI WEB plugins can run with your user permissions. Install packages and enable plugins only from sources you trust.`}),i}renderPanelContent(e,t,i){return this.packageManagementUnavailable?null:this.packagesResponse===void 0?l`<div class="loading-card">${this.loading?`Loading Pi packages from ${i}…`:`Pi package list unavailable for ${i}. Use Reload to try again.`}</div>`:l`
1956
+ ${this.renderInstallForm(i)}
1957
+ ${this.renderPackageList(e,t)}
1958
+ `}renderInstallForm(e){return l`
1959
+ <form class="install-card" @submit=${t=>{this.installPackage(t)}}>
1960
+ <label for="package-source">Pi package source</label>
1961
+ <div class="install-row">
1962
+ <input id="package-source" .value=${this.installSource} ?disabled=${this.isOperating} placeholder="npm:@scope/package, git URL, or local path" @input=${t=>{this.updateInstallSource(t)}}>
1963
+ <button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${Di(this.operation,"install")?"Installing…":"Install"}</button>
1804
1964
  </div>
1805
- <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>重新加载</button>
1965
+ ${this.validationMessage===""?null:l`<div class="field-error">${this.validationMessage}</div>`}
1966
+ <small>Installs run on ${e} and use Pi's default package location, equivalent to <code>pi install &lt;source&gt;</code>. PI WEB does not ask you to choose an install location.</small>
1967
+ </form>
1968
+ `}renderPackageList(e,t){const i=xt(t),r=this.packageManagementUnavailable?this.packageManagementUnavailableMessage(i):MS(e),o=r!==void 0&&e.length>0;return l`
1969
+ <section class="package-section" aria-label="Configured Pi packages">
1970
+ <div class="package-toolbar">
1971
+ <div>
1972
+ <h3>Configured Pi packages</h3>
1973
+ <p>This list comes from Pi's package manager settings on ${i}.</p>
1974
+ </div>
1975
+ <button class="secondary" title=${r??"Update all user-scope Pi packages"} ?disabled=${this.isOperating||r!==void 0} @click=${()=>{this.updatePackage()}}>
1976
+ ${Di(this.operation,"update-all")?"Updating…":"Update all"}
1977
+ </button>
1978
+ </div>
1979
+ ${o?l`<div class="action-note">${r}</div>`:null}
1980
+ ${this.loading&&e.length>0?l`<div class="action-note">Refreshing Pi packages from ${i}…</div>`:null}
1981
+ ${this.renderPackageListContent(e,i)}
1982
+ </section>
1983
+ `}renderPackageListContent(e,t){return this.loading&&e.length===0?l`<div class="loading-card">Loading Pi packages from ${t}…</div>`:e.length===0?l`<div class="loading-card">No Pi packages configured in Pi settings on ${t} yet.</div>`:l`
1984
+ <div class="package-list">
1985
+ ${e.map(i=>this.renderPackage(i))}
1806
1986
  </div>
1807
- ${this.renderMessages()}
1808
- <div class="plugin-note">配置键:<code>plugins</code>。除非条目将 <code>enabled</code> 设置为 <code>false</code>,插件默认启用。</div>
1809
- ${this.loading&&e.length===0?l`<div class="loading-card">正在加载插件…</div>`:e.length===0?l`<div class="loading-card">未发现外部或内置插件。</div>`:l`
1810
- <div class="plugin-list">
1811
- ${e.map(t=>this.renderPlugin(t))}
1987
+ `}renderPackage(e){const t=xt(this.packageTarget),i=this.packageManagementUnavailable,s=i?this.packageManagementUnavailableMessage(t):IS(e),r=i?this.packageManagementUnavailableMessage(t):"Remove this Pi package",o=Di(this.operation,"update",e.source),n=Di(this.operation,"remove",e.source);return l`
1988
+ <article class=${`package-card${e.filtered?" filtered":""}`}>
1989
+ <div class="package-main">
1990
+ <strong>${e.source}</strong>
1991
+ <small>${PS(e)} · ${CS(e)}</small>
1992
+ <small>Installed path: <code>${RS(e)}</code></small>
1993
+ ${s===void 0?null:l`<small class="action-note">${s}</small>`}
1812
1994
  </div>
1813
- `}
1814
- `}renderMessages(){return fs(this.error,this.savedMessage===""?"":`${this.savedMessage} 重新加载浏览器标签页以应用插件更改。`)}renderPlugin(e){const t=this.configResponse?.config.plugins?.[e.id],i=t?.enabled===!1?"配置已禁用":t?.enabled===!0?"配置已启用":"默认启用";return l`
1995
+ <div class="package-actions">
1996
+ <button class="secondary" title=${s??"Update this Pi package"} ?disabled=${this.isOperating||s!==void 0} @click=${()=>{this.updatePackage(e.source)}}>${o?"Updating…":"Update"}</button>
1997
+ <button class="danger" title=${r} ?disabled=${this.isOperating||i} @click=${()=>{this.removePackage(e)}}>${n?"Removing…":"Remove"}</button>
1998
+ </div>
1999
+ </article>
2000
+ `}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:"",this.validationMessage=""}async installPackage(e){e.preventDefault();const t=$S(this.installSource);if(t!==void 0){this.validationMessage=t;return}const i=Gc(this.installSource);try{await this.onInstallPackage?.(i),this.installSource="",this.validationMessage=""}catch{}}async removePackage(e){try{await this.onRemovePackage?.(e.source,e.scope)}catch{}}async updatePackage(e){try{await this.onUpdatePackage?.(e)}catch{}}get packageTarget(){return this.targetMachine??Kc()}get packageManagementUnavailable(){return Mo(this.managementSupport)}packageManagementUnavailableMessage(e){return this.managementSupport?.message??`Pi package management is not available on ${e}.`}get isOperating(){return this.operation!==void 0}};ne.styles=D`
2001
+ :host { display: block; }
2002
+ .package-toolbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
2003
+ .package-toolbar > div, .package-main { display: grid; gap: 6px; min-width: 0; }
2004
+ h3, p { margin: 0; }
2005
+ h3 { font-size: 15px; line-height: 1.25; }
2006
+ p, small { color: var(--pi-muted); line-height: 1.45; }
2007
+ button, input { font: inherit; }
2008
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2009
+ button:disabled, input:disabled { opacity: .55; cursor: not-allowed; }
2010
+ input { box-sizing: border-box; width: 100%; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 8px 9px; }
2011
+ label { font-weight: 700; }
2012
+ .secondary { flex: 0 0 auto; }
2013
+ .danger { border-color: color-mix(in srgb, var(--pi-danger) 55%, var(--pi-border)); color: var(--pi-danger); }
2014
+ .loading-card, .install-card, .package-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
2015
+ .field-error { color: var(--pi-danger); font-size: 12px; }
2016
+ .install-card { display: grid; gap: 8px; }
2017
+ .install-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; align-items: center; }
2018
+ .package-section { display: block; }
2019
+ .loading-card, .action-note { color: var(--pi-muted); }
2020
+ .action-note { margin-bottom: 10px; font-size: 12px; }
2021
+ .package-list { display: grid; gap: 10px; }
2022
+ .package-card { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px; align-items: center; }
2023
+ .package-card.filtered { opacity: .82; }
2024
+ .package-main strong, .package-main small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
2025
+ .package-actions { display: flex; align-items: center; gap: 8px; }
2026
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
2027
+
2028
+ @media (max-width: 760px) {
2029
+ .package-toolbar { display: grid; gap: 12px; }
2030
+ .package-toolbar .secondary { justify-self: start; }
2031
+ .install-row, .package-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
2032
+ .package-actions { justify-self: start; flex-wrap: wrap; }
2033
+ .package-main strong, .package-main small { white-space: normal; }
2034
+ }
2035
+ `;ve([c({attribute:!1})],ne.prototype,"packagesResponse",2);ve([c({type:Boolean})],ne.prototype,"loading",2);ve([c({attribute:!1})],ne.prototype,"operation",2);ve([c({attribute:!1})],ne.prototype,"targetMachine",2);ve([c({attribute:!1})],ne.prototype,"managementSupport",2);ve([c()],ne.prototype,"error",2);ve([c()],ne.prototype,"operationMessage",2);ve([c({attribute:!1})],ne.prototype,"onReload",2);ve([c({attribute:!1})],ne.prototype,"onInstallPackage",2);ve([c({attribute:!1})],ne.prototype,"onRemovePackage",2);ve([c({attribute:!1})],ne.prototype,"onUpdatePackage",2);ve([v()],ne.prototype,"installSource",2);ve([v()],ne.prototype,"validationMessage",2);ne=ve([W("settings-packages-panel")],ne);function LS(e){return l`Managing Pi packages on <strong>${e}</strong>. Install, remove, and update packages managed by Pi on the selected machine. Pi packages can provide extensions, skills, prompt templates, themes, context/system prompt files, and PI WEB browser plugins.`}var OS=Object.defineProperty,FS=Object.getOwnPropertyDescriptor,Ze=(e,t,i,s)=>{for(var r=s>1?void 0:s?FS(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&&OS(t,i,r),r};let Te=class extends I{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.targetLabel="local (local gateway)"}render(){const e=this.pluginsResponse?.plugins??[],t=this.pluginsResponse!==void 0;return l`
2036
+ <settings-panel-frame
2037
+ heading="PI WEB 插件"
2038
+ .description=${_S(this.targetLabel)}
2039
+ actionLabel="重新加载"
2040
+ actionTitle=${`从 ${this.targetLabel} 重新加载 PI WEB 插件`}
2041
+ .actionDisabled=${this.loading}
2042
+ .notices=${this.panelNotices(e.length>0)}
2043
+ .onAction=${this.onReload}
2044
+ >
2045
+ ${this.renderPanelContent(e,t)}
2046
+ </settings-panel-frame>
2047
+ `}panelNotices(e){const t=[];return this.error!==""&&t.push({type:"error",content:this.error}),this.shouldShowConfigUnavailableNotice(e)&&t.push({type:"availability",content:"配置不可用。更改插件启用状态前请重新加载。"}),this.savedMessage!==""&&t.push({type:"success",content:`${this.savedMessage} 重新加载浏览器标签页以应用插件更改。`}),e&&t.push({type:"security",content:l`<strong>受信代码警告:</strong>PI WEB 插件和 Pi 包可使用你的用户权限运行。请仅启用可信来源的插件。`}),t}shouldShowConfigUnavailableNotice(e){return e&&this.configResponse===void 0&&!this.loading&&this.error===""}renderPanelContent(e,t){return t?e.length===0?l`<div class="loading-card">在 ${this.targetLabel} 上未发现 PI WEB 浏览器插件。</div>`:l`
2048
+ <div class="plugin-note">${this.targetLabel} 上的配置键:<code>plugins</code>。除非条目将 <code>enabled</code> 设为 <code>false</code>,插件默认启用。</div>
2049
+ <div class="plugin-list">
2050
+ ${e.map(i=>this.renderPlugin(i))}
2051
+ </div>
2052
+ `:l`<div class="loading-card">${this.loading?"正在加载 PI WEB 插件…":`${this.targetLabel} 的 PI WEB 插件列表不可用,请重新加载。`}</div>`}renderPlugin(e){const t=this.configResponse?.config.plugins?.[e.id],i=t?.enabled===!1?"配置已禁用":t?.enabled===!0?"配置已启用":"默认启用";return l`
1815
2053
  <article class=${`plugin-card${e.enabled?"":" disabled"}`}>
1816
2054
  <div class="plugin-main">
1817
2055
  <strong>${e.id}</strong>
@@ -1819,14 +2057,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1819
2057
  <small>${i}</small>
1820
2058
  </div>
1821
2059
  <label class="toggle">
1822
- <input type="checkbox" .checked=${e.enabled} ?disabled=${this.saving} @change=${s=>{this.togglePlugin(e,s)}}>
2060
+ <input type="checkbox" .checked=${e.enabled} ?disabled=${this.saving||this.configResponse===void 0} @change=${s=>{this.togglePlugin(e,s)}}>
1823
2061
  <span>${e.enabled?"已启用":"已禁用"}</span>
1824
2062
  </label>
1825
2063
  </article>
1826
- `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};De.styles=[gs,D`
1827
- .plugin-note, .plugin-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
1828
- .plugin-note { color: var(--pi-muted); }
1829
- .plugin-note { margin-bottom: 14px; }
2064
+ `}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};Te.styles=D`
2065
+ :host { display: block; }
2066
+ input { font: inherit; }
2067
+ input:disabled { opacity: .55; cursor: not-allowed; }
2068
+ .loading-card, .plugin-note, .plugin-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
2069
+ .loading-card, .plugin-note { color: var(--pi-muted); }
2070
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
1830
2071
  .plugin-list { display: grid; gap: 10px; }
1831
2072
  .plugin-card { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px; align-items: center; }
1832
2073
  .plugin-card.disabled { opacity: .75; }
@@ -1840,40 +2081,41 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1840
2081
  .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
1841
2082
  .toggle { justify-self: start; }
1842
2083
  }
1843
- `];Qe([d({attribute:!1})],De.prototype,"pluginsResponse",2);Qe([d({attribute:!1})],De.prototype,"configResponse",2);Qe([d({type:Boolean})],De.prototype,"loading",2);Qe([d({type:Boolean})],De.prototype,"saving",2);Qe([d()],De.prototype,"error",2);Qe([d()],De.prototype,"savedMessage",2);Qe([d({attribute:!1})],De.prototype,"onReload",2);Qe([d({attribute:!1})],De.prototype,"onTogglePlugin",2);De=Qe([W("settings-plugins-panel")],De);var n0=Object.defineProperty,a0=Object.getOwnPropertyDescriptor,me=(e,t,i,s)=>{for(var r=s>1?void 0:s?a0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&n0(t,i,r),r};const la={capture:!0},l0=[{value:"auto",label:"Auto/default",description:"Desktop-like Enter sends; mobile, coarse pointer, or narrow screens insert a new line."},{value:"send",label:"Enter sends message",description:"Enter sends the chat message; Shift+Enter adds a new line when supported."},{value:"newline",label:"Enter inserts new line",description:"Enter adds a line break; Shift+Enter sends the chat message when supported."}];let re=class extends R{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.promptEnterPreference=hs(),this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{const t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key==="Escape"){this.stopRecording();return}const i=hl(e);if(i===void 0){this.localError="Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.";return}if(t.tokens.length===0&&!Xt(i)){this.localError="Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.";return}const s=[...t.tokens,i];this.localError="",this.drafts={[t.actionId]:s.join(" ")},this.recording={actionId:t.actionId,tokens:s},this.armRecordingTimer()}}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.drafts={},this.localError="",this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){const e=h0(this.actions),t=this.shortcutResolutions();return l`
1844
- <div class="section-heading">
1845
- <div>
1846
- <h2>键盘快捷键</h2>
1847
- <p>按操作编辑应用快捷键。输入 <code>mod+k</code> 或 <code>mod+g p</code> 这类快捷键,也可以从键盘录制、设为无或恢复默认。快捷键冲突时,自定义快捷键优先于默认值;同级按 action id 排序,较短快捷键会遮蔽相同前缀的较长序列。</p>
1848
- </div>
1849
- <button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>Reload</button>
1850
- </div>
1851
- ${this.renderMessages()}
1852
- ${this.renderPromptEnterPreferenceCard()}
1853
- ${this.configResponse===void 0&&this.loading?l`<div class="loading-card">正在加载快捷键…</div>`:l`
1854
- <div class="config-path-card">
1855
- <span>配置文件</span>
1856
- <code>${this.configResponse?.path??"未知"}</code>
1857
- <small>快捷键覆盖项保存在 <code>shortcuts</code> 下。值为 <code>null</code> 时会禁用该操作快捷键。</small>
1858
- </div>
1859
- ${e.length===0?l`<div class="loading-card">没有已注册操作。</div>`:e.map(i=>l`
1860
- <section class="shortcut-group">
1861
- <h3>${i.name}</h3>
1862
- <div class="shortcut-list">
1863
- ${i.actions.map(s=>this.renderShortcutRow(s,t.get(s.id)))}
1864
- </div>
1865
- </section>
1866
- `)}
1867
- `}
1868
- `}renderMessages(){const e=this.localError||this.error;return fs(e,this.savedMessage)}renderPromptEnterPreferenceCard(){return l`
2084
+ `;Ze([c({attribute:!1})],Te.prototype,"pluginsResponse",2);Ze([c({attribute:!1})],Te.prototype,"configResponse",2);Ze([c({type:Boolean})],Te.prototype,"loading",2);Ze([c({type:Boolean})],Te.prototype,"saving",2);Ze([c()],Te.prototype,"error",2);Ze([c()],Te.prototype,"savedMessage",2);Ze([c()],Te.prototype,"targetLabel",2);Ze([c({attribute:!1})],Te.prototype,"onReload",2);Ze([c({attribute:!1})],Te.prototype,"onTogglePlugin",2);Te=Ze([W("settings-plugins-panel")],Te);function _S(e){return l`启用或禁用 <strong>${e}</strong> 上发现的 PI WEB 浏览器插件。这与安装 Pi 包相互独立;请重新加载浏览器标签页以应用插件运行时更改。`}var jS=Object.defineProperty,US=Object.getOwnPropertyDescriptor,xe=(e,t,i,s)=>{for(var r=s>1?void 0:s?US(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&&jS(t,i,r),r};const _a={capture:!0},BS=[{value:"auto",label:"自动/默认",description:"桌面环境按 Enter 发送;移动设备、粗略指针或窄屏环境按 Enter 换行。"},{value:"send",label:"Enter 发送消息",description:"Enter 发送聊天消息;支持时 Shift+Enter 插入新行。"},{value:"newline",label:"Enter 插入新行",description:"Enter 插入换行;支持时 Shift+Enter 发送聊天消息。"}];function zS(){return l`按操作编辑应用快捷键。输入 <code>mod+k</code> 或 <code>mod+g p</code> 这类快捷键,也可以从键盘录制、设为无或恢复默认。快捷键冲突时,自定义快捷键优先于默认值;同级按 action id 排序,较短快捷键会遮蔽相同前缀的较长序列。`}let ce=class extends I{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.promptEnterPreference=Ls(),this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{const t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key==="Escape"){this.stopRecording();return}const i=Ql(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&&!gi(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=KS(this.actions),t=this.shortcutResolutions();return l`
2085
+ <settings-panel-frame
2086
+ heading="键盘快捷键"
2087
+ .description=${zS()}
2088
+ actionLabel="重新加载"
2089
+ .actionDisabled=${this.loading}
2090
+ .notices=${this.panelNotices()}
2091
+ .onAction=${this.onReload}
2092
+ >
2093
+ ${this.renderPromptEnterPreferenceCard()}
2094
+ ${this.configResponse===void 0&&this.loading?l`<div class="loading-card">正在加载快捷键…</div>`:l`
2095
+ <div class="config-path-card">
2096
+ <span>配置文件</span>
2097
+ <code>${this.configResponse?.path??"未知"}</code>
2098
+ <small>快捷键覆盖项保存在 <code>shortcuts</code> 下。值为 <code>null</code> 时会禁用该操作快捷键。</small>
2099
+ </div>
2100
+ ${e.length===0?l`<div class="loading-card">没有已注册操作。</div>`:e.map(i=>l`
2101
+ <section class="shortcut-group">
2102
+ <h3>${i.name}</h3>
2103
+ <div class="shortcut-list">
2104
+ ${i.actions.map(s=>this.renderShortcutRow(s,t.get(s.id)))}
2105
+ </div>
2106
+ </section>
2107
+ `)}
2108
+ `}
2109
+ </settings-panel-frame>
2110
+ `}panelNotices(){const e=[],t=this.localError||this.error;return t!==""&&e.push({type:"error",content:t}),this.savedMessage!==""&&e.push({type:"success",content:this.savedMessage}),e}renderPromptEnterPreferenceCard(){return l`
1869
2111
  <section class="prompt-enter-card" aria-labelledby="prompt-enter-preference-title">
1870
2112
  <div class="prompt-enter-copy">
1871
- <span class="card-eyebrow">Chat composer</span>
1872
- <h3 id="prompt-enter-preference-title">Enter key behavior</h3>
1873
- <p>Choose what Enter does in this browser. Shift+Enter does the opposite when supported; automatic touch-keyboard capitalization is ignored to avoid accidental sends.</p>
2113
+ <span class="card-eyebrow">聊天输入框</span>
2114
+ <h3 id="prompt-enter-preference-title">Enter 键行为</h3>
2115
+ <p>选择当前浏览器中 Enter 键的行为。支持时 Shift+Enter 执行相反操作;为避免误发送,会忽略触摸键盘的自动大写状态。</p>
1874
2116
  </div>
1875
- <div class="prompt-enter-options" role="radiogroup" aria-label="Enter and Shift Enter behavior in the chat composer">
1876
- ${l0.map(e=>l`
2117
+ <div class="prompt-enter-options" role="radiogroup" aria-label="聊天输入框中的 Enter 和 Shift Enter 行为">
2118
+ ${BS.map(e=>l`
1877
2119
  <label class="prompt-enter-option">
1878
2120
  <input
1879
2121
  type="radio"
@@ -1890,19 +2132,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1890
2132
  `)}
1891
2133
  </div>
1892
2134
  </section>
1893
- `}updatePromptEnterPreference(e){this.promptEnterPreference=e,Vw(e)}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=Gi(e.id,i),r=m0(e,i),o=this.shortcutInputText(e),n=o.trim()===""?void 0:Ps(o),a=n?.ok===!0?n.shortcut:g0(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&o.trim()!==""?"custom":r,h=this.recordingHint(e.id),g=p0(t);return l`
1894
- <article class=${c0(t)}>
2135
+ `}updatePromptEnterPreference(e){this.promptEnterPreference=e,Zy(e)}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=ms(e.id,i),r=JS(e,i),o=this.shortcutInputText(e),n=o.trim()===""?void 0:Qs(o),a=n?.ok===!0?n.shortcut:QS(e,i),d=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&o.trim()!==""?"custom":r,h=this.recordingHint(e.id),g=HS(t);return l`
2136
+ <article class=${NS(t)}>
1895
2137
  <div class="shortcut-main">
1896
2138
  <strong>${e.title}</strong>
1897
2139
  ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1898
2140
  <small class="shortcut-id">${e.id}</small>
1899
- <small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${ki(e.shortcut)}</kbd>`:"No default shortcut"}</small>
2141
+ <small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${Ni(e.shortcut)}</kbd>`:"No default shortcut"}</small>
1900
2142
  </div>
1901
2143
  <div class="shortcut-editor">
1902
2144
  <div class="shortcut-status">
1903
- ${a!==void 0&&a!==""?l`<kbd>${ki(a)}</kbd>`:l`<span class="unassigned">${r==="disabled"?"已禁用":"未分配"}</span>`}
1904
- <small class=${u}>${v0(u)}${p?" · 未保存":""}</small>
1905
- ${g===void 0?null:l`<small class=${d0(t)}>${g}</small>`}
2145
+ ${a!==void 0&&a!==""?l`<kbd>${Ni(a)}</kbd>`:l`<span class="unassigned">${r==="disabled"?"已禁用":"未分配"}</span>`}
2146
+ <small class=${u}>${ZS(u)}${p?" · 未保存":""}</small>
2147
+ ${g===void 0?null:l`<small class=${qS(t)}>${g}</small>`}
1906
2148
  </div>
1907
2149
  <label class="shortcut-input-label">
1908
2150
  <span>快捷键</span>
@@ -1915,7 +2157,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1915
2157
  autocapitalize="off"
1916
2158
  spellcheck="false"
1917
2159
  ?disabled=${this.saving}
1918
- @input=${y=>{this.updateDraft(e.id,b0(y))}}
2160
+ @input=${S=>{this.updateDraft(e.id,XS(S))}}
1919
2161
  >
1920
2162
  </label>
1921
2163
  ${h!==""?l`<small class="recording-hint">${h}</small>`:null}
@@ -1923,12 +2165,24 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1923
2165
  <button class="primary" ?disabled=${this.loading||this.saving||!p||o.trim()===""} @click=${()=>{this.saveShortcut(e)}}>保存</button>
1924
2166
  <button ?disabled=${this.loading||this.saving} @click=${()=>{this.toggleRecording(e.id)}}>${this.recording?.actionId===e.id?"取消录制":"录制"}</button>
1925
2167
  <button ?disabled=${this.loading||this.saving||s===null} @click=${()=>{this.setShortcutNone(e.id)}}>无</button>
1926
- <button ?disabled=${this.loading||this.saving||!c} @click=${()=>{this.resetShortcut(e.id)}}>重置</button>
2168
+ <button ?disabled=${this.loading||this.saving||!d} @click=${()=>{this.resetShortcut(e.id)}}>重置</button>
1927
2169
  </div>
1928
2170
  </div>
1929
2171
  </article>
1930
- `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=Gi(e.id,this.configResponse?.config.shortcuts);return i===null?"":i??e.shortcut??""}recordingHint(e){const t=this.recording;return t?.actionId!==e?"":t.tokens.length===0?"Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.":`Recording: ${ki(t.tokens.join(" "))}. Press another key to add a sequence, or wait to finish.`}updateDraft(e,t){this.drafts={[e]:t},this.localError=""}async saveShortcut(e){this.stopRecording();const t=this.shortcutInputText(e).trim(),i=Ps(t);if(!i.ok){this.localError=i.message;return}this.localError="",await this.saveShortcutPreference(e.id,i.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError="",await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){const i={...this.configResponse?.config??{}},s=i.shortcuts??{},r=t===void 0?f0(s,e):{...s,[e]:t};Object.keys(r).length===0?delete i.shortcuts:i.shortcuts=r,await this.onSave?.(i)}shortcutResolutions(){return new Map(jr(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){const e={...this.configResponse?.config.shortcuts??{}};for(const[t,i]of Object.entries(this.drafts)){const s=i.trim();if(s==="")continue;const r=Ps(s);r.ok&&(e[t]=r.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError="",this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(const t of this.renderRoot.querySelectorAll(".shortcut-input"))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},dl)}stopRecording(){this.clearRecordingTimer(),this.removeRecordingListener(),this.recording=void 0}clearRecordingTimer(){this.recordingTimer!==void 0&&(window.clearTimeout(this.recordingTimer),this.recordingTimer=void 0)}ensureRecordingListener(){this.recordingListenerActive||(window.addEventListener("keydown",this.onRecordKeyDown,la),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,la),this.recordingListenerActive=!1)}};re.styles=[gs,D`
1931
- .prompt-enter-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; display: grid; grid-template-columns: minmax(0, .85fr) minmax(260px, 1fr); gap: 12px; align-items: start; margin-bottom: 14px; }
2172
+ `}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=ms(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: ${Ni(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=Qs(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?GS(s,e):{...s,[e]:t};Object.keys(r).length===0?delete i.shortcuts:i.shortcuts=r,await this.onSave?.(i)}shortcutResolutions(){return new Map(no(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){const e={...this.configResponse?.config.shortcuts??{}};for(const[t,i]of Object.entries(this.drafts)){const s=i.trim();if(s==="")continue;const r=Qs(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()},Vl)}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,_a),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,_a),this.recordingListenerActive=!1)}};ce.styles=D`
2173
+ :host { display: block; }
2174
+ h3, p { margin: 0; }
2175
+ h3 { font-size: 13px; line-height: 1.3; }
2176
+ p { color: var(--pi-muted); line-height: 1.45; }
2177
+ button, input { font: inherit; }
2178
+ button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2179
+ button:disabled, input:disabled { opacity: .55; cursor: not-allowed; }
2180
+ .primary { border-color: var(--pi-accent); background: var(--pi-selection-bg); color: var(--pi-text-bright); }
2181
+ .loading-card, .config-path-card, .prompt-enter-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
2182
+ .loading-card, .config-path-card { color: var(--pi-muted); }
2183
+ .config-path-card { display: grid; gap: 5px; }
2184
+ .config-path-card span, .card-eyebrow { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
2185
+ .prompt-enter-card { display: grid; grid-template-columns: minmax(0, .85fr) minmax(260px, 1fr); gap: 12px; align-items: start; }
1932
2186
  .prompt-enter-copy { display: grid; gap: 5px; min-width: 0; }
1933
2187
  .prompt-enter-copy p, .prompt-enter-option small { font-size: 12px; }
1934
2188
  .prompt-enter-options { display: grid; gap: 7px; }
@@ -1937,7 +2191,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1937
2191
  .prompt-enter-option input:focus { border-color: transparent; box-shadow: none; outline: 2px solid var(--pi-accent-border); outline-offset: 2px; }
1938
2192
  .prompt-enter-option span { display: grid; gap: 2px; }
1939
2193
  .prompt-enter-option small { color: var(--pi-muted); line-height: 1.35; }
1940
- .shortcut-group { margin: 0 0 16px; }
2194
+ code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
2195
+ .shortcut-group { margin: 0; }
1941
2196
  .shortcut-group h3 { margin: 0 0 8px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
1942
2197
  .shortcut-list { border: 1px solid var(--pi-border); border-radius: 10px; overflow: hidden; }
1943
2198
  .shortcut-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(360px, 48%); gap: 14px; align-items: start; padding: 12px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-surface); }
@@ -1970,7 +2225,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1970
2225
  .shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
1971
2226
  .shortcut-status, .shortcut-actions { justify-content: flex-start; }
1972
2227
  }
1973
- `];me([d({attribute:!1})],re.prototype,"actions",2);me([d({attribute:!1})],re.prototype,"configResponse",2);me([d({type:Boolean})],re.prototype,"loading",2);me([d({type:Boolean})],re.prototype,"saving",2);me([d()],re.prototype,"error",2);me([d()],re.prototype,"savedMessage",2);me([d({attribute:!1})],re.prototype,"onReload",2);me([d({attribute:!1})],re.prototype,"onSave",2);me([w()],re.prototype,"drafts",2);me([w()],re.prototype,"localError",2);me([w()],re.prototype,"promptEnterPreference",2);me([w()],re.prototype,"recording",2);re=me([W("settings-shortcuts-panel")],re);function c0(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function d0(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function p0(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??"another action"}`;const t=e.shadows.length;if(t===0)return;const i=e.shadows.slice(0,2).map(r=>r.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function h0(e){const t=new Map;for(const i of[...e].sort(u0)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function u0(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function Gi(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function f0(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function g0(e,t){const i=Gi(e.id,t);if(i!==null)return i??e.shortcut}function m0(e,t){const i=Gi(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function v0(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}function b0(e){return e.target instanceof HTMLInputElement?e.target.value:""}var w0=Object.defineProperty,y0=Object.getOwnPropertyDescriptor,Ie=(e,t,i,s)=>{for(var r=s>1?void 0:s?y0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&w0(t,i,r),r};let de=class extends R{constructor(){super(...arguments),this.section="general",this.actions=[],this.loading=!0,this.saving=!1,this.error="",this.savedMessage=""}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}render(){return l`
2228
+ `;xe([c({attribute:!1})],ce.prototype,"actions",2);xe([c({attribute:!1})],ce.prototype,"configResponse",2);xe([c({type:Boolean})],ce.prototype,"loading",2);xe([c({type:Boolean})],ce.prototype,"saving",2);xe([c()],ce.prototype,"error",2);xe([c()],ce.prototype,"savedMessage",2);xe([c({attribute:!1})],ce.prototype,"onReload",2);xe([c({attribute:!1})],ce.prototype,"onSave",2);xe([v()],ce.prototype,"drafts",2);xe([v()],ce.prototype,"localError",2);xe([v()],ce.prototype,"promptEnterPreference",2);xe([v()],ce.prototype,"recording",2);ce=xe([W("settings-shortcuts-panel")],ce);function NS(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function qS(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function HS(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 KS(e){const t=new Map;for(const i of[...e].sort(VS)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function VS(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function ms(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function GS(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function QS(e,t){const i=ms(e.id,t);if(i!==null)return i??e.shortcut}function JS(e,t){const i=ms(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function ZS(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}function XS(e){return e.target instanceof HTMLInputElement?e.target.value:""}async function YS(e){const[t,i]=await Promise.allSettled([e.loadConfig(),e.loadPlugins()]),s={error:""},r=[];return t.status==="fulfilled"?s.config=t.value:r.push(`config: ${Wr(t.reason)}`),i.status==="fulfilled"?s.plugins=i.value:r.push(`PI WEB plugins: ${Wr(i.reason)}`),r.length>0&&(s.error=`Failed to load settings: ${r.join("; ")}`),s}async function ex(e,t,i){if(Mo(i))return{error:i.message??`Pi package management is not available on ${xt(e)}.`,skipped:!0};try{return{packagesResponse:await t(e.id),error:""}}catch(s){return{error:`Failed to load Pi packages from ${xt(e)}: ${Jc(Wr(s),e)}`}}}function Wr(e){return e instanceof Error?e.message:String(e)}function tx(e,t){return{...e,config:ja(e.config,t.config),effectiveConfig:ja(e.effectiveConfig,t.effectiveConfig)}}function ja(e,t){return{...e,...t.pathAccess===void 0?{}:{pathAccess:t.pathAccess},...t.uploads===void 0?{}:{uploads:t.uploads},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes}}}function Ua(e){return e!==void 0?{id:e.id,name:e.name,kind:e.kind}:{id:"local",name:"local",kind:"local"}}function Y(e){return e.kind==="local"?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function Ba(e,t){return e.kind==="local"?{state:"supported"}:t?.ok!==!0?{state:"unknown"}:Pe(t,we.selectedMachineSettings)?{state:"supported"}:{state:"unsupported",message:Zc(e)}}function za(e){return`${e.state}:${e.message??""}`}function Et(e){return e?.state==="unsupported"}function Zc(e){return`Selected-machine settings are not available on ${e.name}. Update and restart PI WEB on that machine, then try again.`}function at(e,t){const i=e.trim();return t.kind!=="remote"?i:ix(i)?Zc(t):i==="Remote machine timeout"?`Timed out while contacting ${t.name} for selected-machine settings. The operation may still be running remotely; reload before retrying.`:i==="Remote machine unavailable"?`Could not reach ${t.name} for selected-machine settings. Check the machine connection and try again.`:i}function ix(e){return e==="Not Found"||/route\s+(GET|PUT):?\/api\/(config|plugins)\b.*not found/iu.test(e)||/cannot\s+(GET|PUT)\s+.*\/api\/(config|plugins)\b/iu.test(e)}function sx(e,t,i){const s=e.plugins??{},r=s[t]??{};return{plugins:{...s,[t]:{...r,enabled:i}}}}function rx(e,t){return{...e,config:Na(e.config,t.config),effectiveConfig:Na(e.effectiveConfig,t.effectiveConfig)}}function Na(e,t){return t.plugins===void 0?e:{...e,plugins:t.plugins}}var ox=Object.defineProperty,nx=Object.getOwnPropertyDescriptor,F=(e,t,i,s)=>{for(var r=s>1?void 0:s?nx(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&&ox(t,i,r),r};let L=class extends I{constructor(){super(...arguments),this.section="general",this.actions=[],this.loading=!0,this.accessLoading=!0,this.sessiondLoading=!0,this.pluginLoading=!0,this.packageLoading=!0,this.saving=!1,this.error="",this.accessError="",this.sessiondError="",this.pluginError="",this.packageError="",this.savedMessage="",this.packageMessage="",this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.loadSessiondConfigForTarget(),this.loadPluginsForTarget(),this.loadPackagesForTarget()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){const t=this.settingsTarget();if(e.has("machine")&&Ua(e.get("machine")).id!==t.id){this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t),this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t);return}e.has("machineRuntime")&&(this.selectedMachineSettingsSupportNeedsReload(e.get("machineRuntime"),t)&&(this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t)),this.packageManagementSupportNeedsReload(e.get("machineRuntime"),t)&&(this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t)))}render(){return l`
1974
2229
  <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
1975
2230
  <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB 设置" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
1976
2231
  <header class="settings-header">
@@ -1982,10 +2237,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1982
2237
  </header>
1983
2238
  <div class="settings-body">
1984
2239
  <nav class="settings-nav" aria-label="设置分区">
1985
- ${this.renderNavButton("general","通用","服务器配置")}
1986
- ${this.renderNavButton("sessiond","会话守护进程","运行时设置")}
1987
- ${this.renderNavButton("plugins","插件","启用和禁用")}
1988
- ${this.renderNavButton("shortcuts","键盘","快捷键")}
2240
+ ${this.renderNavButton("general","通用","网关与所选机器")}
2241
+ ${this.renderNavButton("sessiond","会话守护进程","所选机器")}
2242
+ ${this.renderNavButton("packages","Pi 包","所选机器")}
2243
+ ${this.renderNavButton("plugins","PI WEB 插件","所选机器")}
2244
+ ${this.renderNavButton("shortcuts","键盘","网关快捷键")}
1989
2245
  </nav>
1990
2246
  <main class="settings-content">
1991
2247
  ${this.renderActiveSection()}
@@ -1995,13 +2251,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1995
2251
  </div>
1996
2252
  `}renderActiveSection(){return this.section==="sessiond"?l`
1997
2253
  <settings-sessiond-panel
1998
- .configResponse=${this.configResponse}
1999
- .loading=${this.loading}
2254
+ .configResponse=${this.sessiondConfigResponse}
2255
+ .loading=${this.sessiondLoading}
2000
2256
  .saving=${this.saving}
2001
- .error=${this.error}
2257
+ .error=${this.sessiondError}
2002
2258
  .savedMessage=${this.savedMessage}
2003
- .onReload=${()=>this.loadConfig()}
2004
- .onSave=${e=>this.saveConfig(e)}
2259
+ .targetLabel=${Y(this.settingsTarget())}
2260
+ .onReload=${()=>this.loadSessiondConfigForTarget()}
2261
+ .onSave=${e=>this.saveSessiondConfig(e)}
2005
2262
  ></settings-sessiond-panel>
2006
2263
  `:this.section==="shortcuts"?l`
2007
2264
  <settings-shortcuts-panel
@@ -2014,33 +2271,54 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2014
2271
  .onReload=${()=>this.loadConfig()}
2015
2272
  .onSave=${e=>this.saveConfig(e)}
2016
2273
  ></settings-shortcuts-panel>
2274
+ `:this.section==="packages"?l`
2275
+ <settings-packages-panel
2276
+ .packagesResponse=${this.packagesResponse}
2277
+ .targetMachine=${this.packageTarget()}
2278
+ .managementSupport=${this.packageManagementSupport()}
2279
+ .loading=${this.packageLoading}
2280
+ .operation=${this.packageOperation}
2281
+ .error=${this.packageError}
2282
+ .operationMessage=${this.packageMessage}
2283
+ .onReload=${()=>this.loadPackagesForTarget()}
2284
+ .onInstallPackage=${e=>this.installPiPackage(e)}
2285
+ .onRemovePackage=${(e,t)=>this.removePiPackage(e,t)}
2286
+ .onUpdatePackage=${e=>this.updatePiPackage(e)}
2287
+ ></settings-packages-panel>
2017
2288
  `:this.section==="plugins"?l`
2018
2289
  <settings-plugins-panel
2019
- .configResponse=${this.configResponse}
2020
- .pluginsResponse=${this.pluginsResponse}
2021
- .loading=${this.loading}
2290
+ .configResponse=${this.selectedPluginConfigResponse}
2291
+ .pluginsResponse=${this.selectedPluginsResponse}
2292
+ .loading=${this.pluginLoading}
2022
2293
  .saving=${this.saving}
2023
- .error=${this.error}
2294
+ .error=${this.pluginError}
2024
2295
  .savedMessage=${this.savedMessage}
2025
- .onReload=${()=>this.loadConfig()}
2296
+ .targetLabel=${Y(this.settingsTarget())}
2297
+ .onReload=${()=>this.loadPluginsForTarget()}
2026
2298
  .onTogglePlugin=${(e,t)=>this.togglePlugin(e,t)}
2027
2299
  ></settings-plugins-panel>
2028
2300
  `:l`
2029
2301
  <settings-general-panel
2030
2302
  .configResponse=${this.configResponse}
2303
+ .machineConfigResponse=${this.accessConfigResponse}
2031
2304
  .loading=${this.loading}
2305
+ .machineLoading=${this.accessLoading}
2032
2306
  .saving=${this.saving}
2033
2307
  .error=${this.error}
2308
+ .machineError=${this.accessError}
2034
2309
  .savedMessage=${this.savedMessage}
2310
+ .targetLabel=${Y(this.settingsTarget())}
2035
2311
  .onReload=${()=>this.loadConfig()}
2312
+ .onReloadMachine=${()=>this.loadAccessConfigForTarget()}
2036
2313
  .onSave=${e=>this.saveConfig(e)}
2314
+ .onSaveMachineConfig=${e=>this.saveMachineAccessConfig(e)}
2037
2315
  ></settings-general-panel>
2038
2316
  `}renderNavButton(e,t,i){const s=this.section===e;return l`
2039
2317
  <button class=${s?"selected":""} aria-current=${s?"page":"false"} @click=${()=>{this.navigate(e)}}>
2040
2318
  <strong>${t}</strong>
2041
2319
  <small>${i}</small>
2042
2320
  </button>
2043
- `}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([Mi.config(),Qs.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`加载设置失败:${zs(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},r=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...r,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await Mi.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(t){this.error=`保存配置失败:${zs(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await Qs.plugins()}catch(e){this.error=`刷新插件失败:${zs(e)}`}}showSavedMessage(){this.savedMessage="配置已保存。",this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage==="配置已保存。"&&(this.savedMessage=""),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};de.styles=D`
2321
+ `}navigate(e){this.onNavigate?.(e)}async loadConfig(){const e=++this.loadRequestSeq;this.loading=!0,this.error="";try{const t=await YS({loadConfig:()=>Ne.config(),loadPlugins:()=>si.plugins()});if(!this.isCurrentLoad(e))return;t.config!==void 0&&(this.configResponse=t.config),t.plugins!==void 0&&(this.pluginsResponse=t.plugins),this.error=t.error}finally{this.isCurrentLoad(e)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){const t=++this.accessLoadRequestSeq,i=this.selectedMachineSettingsSupport(e);if(Et(i)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=i.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.accessLoading=!0,this.accessError="";try{const s=await Ne.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=s}catch(s){this.isCurrentAccessLoad(t,e)&&(this.accessError=`Failed to load file access/upload config from ${Y(e)}: ${at(Le(s),e)}`)}finally{this.isCurrentAccessLoad(t,e)&&(this.accessLoading=!1)}}async loadSessiondConfigForTarget(e=this.settingsTarget()){const t=++this.sessiondLoadRequestSeq,i=this.selectedMachineSettingsSupport(e);if(Et(i)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=i.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.sessiondLoading=!0,this.sessiondError="";try{const s=await Ne.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=s}catch(s){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`Failed to load session-daemon config from ${Y(e)}: ${at(Le(s),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){const t=++this.pluginLoadRequestSeq,i=this.selectedMachineSettingsSupport(e);if(Et(i)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=i.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.pluginLoading=!0,this.pluginError="";try{const[s,r]=await Promise.allSettled([Ne.config(e.id),si.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;const o=[];s.status==="fulfilled"?this.selectedPluginConfigResponse=s.value:o.push(`config: ${at(Le(s.reason),e)}`),r.status==="fulfilled"?this.selectedPluginsResponse=r.value:o.push(`PI WEB plugins: ${at(Le(r.reason),e)}`),this.pluginError=o.length===0?"":`Failed to load PI WEB plugin settings from ${Y(e)}: ${o.join("; ")}`}finally{this.isCurrentPluginLoad(t,e)&&(this.pluginLoading=!1)}}async loadPackagesForTarget(e=this.packageTarget()){const t=++this.packageLoadRequestSeq;this.packageLoading=!0,this.packageError="",this.packageMessage="";try{const i=await ex(e,s=>ri.packages(s),this.packageManagementSupport(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=i.packagesResponse,this.packageError=i.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;const i=this.settingsTarget(),s=this.selectedMachineSettingsSupport(i);if(Et(s)){this.pluginError=s.message??`Selected-machine settings are not available on ${Y(i)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${Y(i)}. Reload before changing plugin enablement.`;return}const r=sx(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError="",this.savedMessage="";try{const o=await Ne.saveConfig(r,i.id);if(!this.isCurrentSettingsTarget(i))return;this.selectedPluginConfigResponse=o,i.kind==="local"&&this.configResponse!==void 0&&(this.configResponse=rx(this.configResponse,o),this.onConfigSaved?.(this.configResponse.effectiveConfig));const n=await this.refreshPluginsForTarget(i);if(!this.isCurrentSettingsTarget(i))return;n!==void 0&&(this.pluginError=n),this.showSavedMessage()}catch(o){this.isCurrentSettingsTarget(i)&&(this.pluginError=`Failed to save PI WEB plugin config on ${Y(i)}: ${at(Le(o),i)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await Ne.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(t){this.error=`保存配置失败:${Le(t)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;const t=this.settingsTarget(),i=this.selectedMachineSettingsSupport(t);if(Et(i)){this.accessError=i.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.accessError="",this.savedMessage="";try{const s=await Ne.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=s,t.kind==="local"&&this.configResponse!==void 0&&(this.configResponse=tx(this.configResponse,s),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(s){this.isCurrentSettingsTarget(t)&&(this.accessError=`Failed to save file access/upload config on ${Y(t)}: ${at(Le(s),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;const t=this.settingsTarget(),i=this.selectedMachineSettingsSupport(t);if(Et(i)){this.sessiondError=i.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.sessiondError="",this.savedMessage="";try{const s=await Ne.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=s,t.kind==="local"&&this.configResponse!==void 0&&(this.configResponse=wS(this.configResponse,s)),this.showSavedMessage()}catch(s){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${Y(t)}: ${at(Le(s),t)}`)}finally{this.saving=!1}}async installPiPackage(e){const t=this.packageTarget();await this.runPiPackageMutation({kind:"install",source:e},"install Pi package",t,()=>ri.install(e,t.id))}async removePiPackage(e,t){const i=this.packageTarget();await this.runPiPackageMutation({kind:"remove",source:e},"remove Pi package",i,()=>ri.remove(e,t,i.id))}async updatePiPackage(e){const t=this.packageTarget();await this.runPiPackageMutation(e===void 0?{kind:"update-all"}:{kind:"update",source:e},"update Pi packages",t,()=>ri.update(e,t.id))}async runPiPackageMutation(e,t,i,s){const r=this.packageManagementSupport(i);if(Mo(r))throw this.packageError=r.message??`Pi package management is not available on ${xt(i)}.`,new Error(this.packageError);if(this.saving)throw new Error("A settings operation is already running.");const o=++this.packageMutationSeq;this.packageLoadRequestSeq+=1,this.packageLoading=!1,this.saving=!0,this.packageOperation=e,this.packageError="",this.packageMessage="";try{const n=await s();if(!this.isCurrentPackageMutation(o,i))return;this.packagesResponse={packages:n.packages};const a=kS(i)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(o,i))return;a!==void 0&&(this.packageError=a),this.packageMessage=TS(n.action,i)}catch(n){throw this.isCurrentPackageMutation(o,i)&&(this.packageError=`Failed to ${t} on ${xt(i)}: ${Jc(Le(n),i)}`),n}finally{this.packageMutationSeq===o&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await si.plugins();return}catch(e){return`刷新网关 PI WEB 插件失败:${Le(e)}`}}async refreshPluginsForTarget(e){try{const t=await si.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEB plugins from ${Y(e)}: ${at(Le(t),e)}`}}settingsTarget(){return Ua(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return Ba(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){const i=Ba(t,e),s=this.selectedMachineSettingsSupport(t);return za(i)!==za(s)}packageManagementSupport(e=this.packageTarget()){return Oa(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){const i=Oa(t,e),s=this.packageManagementSupport(t);return Fa(i)===Fa(s)?!1:i.state==="unsupported"||s.state==="unsupported"}isCurrentLoad(e){return e===this.loadRequestSeq}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError="",this.accessConfigResponse=void 0,this.savedMessage=""}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError="",this.sessiondConfigResponse=void 0,this.savedMessage=""}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError="",this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=""}resetPackageStateForTargetChange(){const e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage="",this.packageError="",this.packagesResponse=void 0,e&&(this.saving=!1)}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?.())}};L.styles=D`
2044
2322
  :host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
2045
2323
  .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; }
2046
2324
  .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; }
@@ -2067,7 +2345,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2067
2345
  .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
2068
2346
  .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
2069
2347
  }
2070
- `;Ie([d({attribute:!1})],de.prototype,"section",2);Ie([d({attribute:!1})],de.prototype,"actions",2);Ie([d({attribute:!1})],de.prototype,"onNavigate",2);Ie([d({attribute:!1})],de.prototype,"onClose",2);Ie([d({attribute:!1})],de.prototype,"onConfigSaved",2);Ie([w()],de.prototype,"configResponse",2);Ie([w()],de.prototype,"pluginsResponse",2);Ie([w()],de.prototype,"loading",2);Ie([w()],de.prototype,"saving",2);Ie([w()],de.prototype,"error",2);Ie([w()],de.prototype,"savedMessage",2);de=Ie([W("settings-dialog")],de);function zs(e){return e instanceof Error?e.message:String(e)}var x0=Object.defineProperty,S0=Object.getOwnPropertyDescriptor,We=(e,t,i,s)=>{for(var r=s>1?void 0:s?S0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&x0(t,i,r),r};const k0=D`
2348
+ `;F([c({attribute:!1})],L.prototype,"section",2);F([c({attribute:!1})],L.prototype,"actions",2);F([c({attribute:!1})],L.prototype,"machine",2);F([c({attribute:!1})],L.prototype,"machineRuntime",2);F([c({attribute:!1})],L.prototype,"onNavigate",2);F([c({attribute:!1})],L.prototype,"onClose",2);F([c({attribute:!1})],L.prototype,"onConfigSaved",2);F([v()],L.prototype,"configResponse",2);F([v()],L.prototype,"accessConfigResponse",2);F([v()],L.prototype,"sessiondConfigResponse",2);F([v()],L.prototype,"pluginsResponse",2);F([v()],L.prototype,"selectedPluginConfigResponse",2);F([v()],L.prototype,"selectedPluginsResponse",2);F([v()],L.prototype,"packagesResponse",2);F([v()],L.prototype,"loading",2);F([v()],L.prototype,"accessLoading",2);F([v()],L.prototype,"sessiondLoading",2);F([v()],L.prototype,"pluginLoading",2);F([v()],L.prototype,"packageLoading",2);F([v()],L.prototype,"saving",2);F([v()],L.prototype,"packageOperation",2);F([v()],L.prototype,"error",2);F([v()],L.prototype,"accessError",2);F([v()],L.prototype,"sessiondError",2);F([v()],L.prototype,"pluginError",2);F([v()],L.prototype,"packageError",2);F([v()],L.prototype,"savedMessage",2);F([v()],L.prototype,"packageMessage",2);L=F([W("settings-dialog")],L);function Le(e){return e instanceof Error?e.message:String(e)}var ax=Object.defineProperty,lx=Object.getOwnPropertyDescriptor,Be=(e,t,i,s)=>{for(var r=s>1?void 0:s?lx(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&&ax(t,i,r),r};const cx=D`
2071
2349
  :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; }
2072
2350
  header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
2073
2351
  .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
@@ -2126,7 +2404,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2126
2404
  .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); }
2127
2405
  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; }
2128
2406
  p { margin: 10px; }
2129
- `;let fe=class extends R{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>{},this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:"选择工作区",body:"选择工作区来查看文件、Git 或终端。"});const t=this.panelContext;if(t===void 0)return this.renderEmptyState({title:"工作区工具不可用",body:"请尝试重新选择工作区。"});const i=this.panels,s=i.find(r=>r.id===this.tool)??i[0];return l`
2407
+ `;let ye=class extends I{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>{},this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:"选择工作区",body:"选择工作区来查看文件、Git 或终端。"});const t=this.panelContext;if(t===void 0)return this.renderEmptyState({title:"工作区工具不可用",body:"请尝试重新选择工作区。"});const i=this.panels,s=i.find(r=>r.id===this.tool)??i[0];return l`
2130
2408
  ${this.hideToolTabs?null:l`
2131
2409
  <header>
2132
2410
  <div class=${this.workspaceHeaderFrameClass()}>
@@ -2156,32 +2434,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2156
2434
  <h2>${e.title}</h2>
2157
2435
  ${e.body===void 0?null:l`<p>${e.body}</p>`}
2158
2436
  </section>
2159
- `}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?" can-scroll-left":""}${this.workspaceHeaderCanScrollRight?" can-scroll-right":""}`}observeWorkspaceHeaderStrip(){const e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){const e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==i&&(this.workspaceHeaderCanScrollLeft=i),this.workspaceHeaderCanScrollRight!==s&&(this.workspaceHeaderCanScrollRight=s)}workspaceHeaderStripElement(){const e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}};fe.styles=k0;We([d({attribute:!1})],fe.prototype,"workspace",2);We([d({attribute:!1})],fe.prototype,"panelContext",2);We([d({attribute:!1})],fe.prototype,"emptyState",2);We([d()],fe.prototype,"tool",2);We([d({attribute:!1})],fe.prototype,"panels",2);We([d({type:Boolean})],fe.prototype,"hideToolTabs",2);We([d({attribute:!1})],fe.prototype,"onSelectTool",2);We([B(".workspace-header-strip")],fe.prototype,"workspaceHeaderStrip",2);We([w()],fe.prototype,"workspaceHeaderCanScrollLeft",2);We([w()],fe.prototype,"workspaceHeaderCanScrollRight",2);fe=We([W("workspace-panel")],fe);var $0=Object.defineProperty,P0=Object.getOwnPropertyDescriptor,Re=(e,t,i,s)=>{for(var r=s>1?void 0:s?P0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&$0(t,i,r),r};let pe=class extends R{constructor(){super(...arguments),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){const e=C0(this.machines),t=I0(this.machine),i=A0(this.project),s=M0(this.workspace),r=D0(this.session);return l`
2437
+ `}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}};ye.styles=cx;Be([c({attribute:!1})],ye.prototype,"workspace",2);Be([c({attribute:!1})],ye.prototype,"panelContext",2);Be([c({attribute:!1})],ye.prototype,"emptyState",2);Be([c()],ye.prototype,"tool",2);Be([c({attribute:!1})],ye.prototype,"panels",2);Be([c({type:Boolean})],ye.prototype,"hideToolTabs",2);Be([c({attribute:!1})],ye.prototype,"onSelectTool",2);Be([q(".workspace-header-strip")],ye.prototype,"workspaceHeaderStrip",2);Be([v()],ye.prototype,"workspaceHeaderCanScrollLeft",2);Be([v()],ye.prototype,"workspaceHeaderCanScrollRight",2);ye=Be([W("workspace-panel")],ye);var dx=Object.defineProperty,px=Object.getOwnPropertyDescriptor,We=(e,t,i,s)=>{for(var r=s>1?void 0:s?px(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&&dx(t,i,r),r};let ge=class extends I{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=hx(this.machines),t=ux(this.machine),i=gx(this.project),s=vx(this.workspace),r=wx(this.session);return l`
2160
2438
  <nav class=${this.contextBarClass()} aria-label="当前位置">
2161
2439
  <span class="context-bar-label">位置</span>
2162
2440
  <ol class="context-items" @scroll=${this.onContextScroll}>
2163
2441
  ${e?l`
2164
2442
  <li class="context-item">
2165
- <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${R0(this.machine)} aria-label=${`机器:${t}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
2443
+ <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${fx(this.machine)} aria-label=${`机器:${t}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
2166
2444
  <span class="context-kind">机器</span>
2167
2445
  <span class="context-value">${t}</span>
2168
2446
  </button>
2169
2447
  </li>
2170
2448
  `:null}
2171
2449
  <li class="context-item">
2172
- <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${T0(this.project)} aria-label=${`项目:${i}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
2450
+ <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${mx(this.project)} aria-label=${`项目:${i}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
2173
2451
  <span class="context-kind">项目</span>
2174
2452
  <span class="context-value">${i}</span>
2175
2453
  </button>
2176
2454
  </li>
2177
2455
  <li class="context-item">
2178
- <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${E0(this.workspace)} aria-label=${`工作区:${s}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
2456
+ <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${bx(this.workspace)} aria-label=${`工作区:${s}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
2179
2457
  <span class="context-kind">工作区</span>
2180
2458
  <span class="context-value">${s}</span>
2181
2459
  </button>
2182
2460
  </li>
2183
2461
  <li class="context-item">
2184
- <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${W0(this.session)} aria-label=${`会话:${r}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
2462
+ <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${yx(this.session)} aria-label=${`会话:${r}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
2185
2463
  <span class="context-kind">会话</span>
2186
2464
  <span class="context-value">${r}</span>
2187
2465
  </button>
@@ -2195,7 +2473,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2195
2473
  <path d="M13 2 4 14h7l-1 8 10-13h-7V2Z"></path>
2196
2474
  </svg>
2197
2475
  </button>
2198
- `}contextBarClass(){const e=["context-bar"];return this.hasContextActions()&&e.push("has-context-actions"),this.refreshControl!==void 0&&this.onShowActions!==void 0&&e.push("has-context-actions-double"),this.canScrollLeft&&e.push("can-scroll-left"),this.canScrollRight&&e.push("can-scroll-right"),e.join(" ")}hasContextActions(){return this.refreshControl!==void 0||this.onShowActions!==void 0}observeContextItems(){const e=this.contextItemsElement();this.observedContextItems!==e&&(this.contextItemsResizeObserver?.disconnect(),this.observedContextItems=e,this.contextItemsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.contextItemsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.contextItemsResizeObserver.observe(e)))}updateScrollState(){const e=this.contextItemsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}contextItemsElement(){const e=this.contextItems;return e instanceof HTMLElement?e:void 0}};pe.styles=D`
2476
+ `}contextBarClass(){const e=["context-bar"];return this.hasContextActions()&&e.push("has-context-actions"),this.refreshControl!==void 0&&this.onShowActions!==void 0&&e.push("has-context-actions-double"),this.canScrollLeft&&e.push("can-scroll-left"),this.canScrollRight&&e.push("can-scroll-right"),e.join(" ")}hasContextActions(){return this.refreshControl!==void 0||this.onShowActions!==void 0}observeContextItems(){const e=this.contextItemsElement();this.observedContextItems!==e&&(this.contextItemsResizeObserver?.disconnect(),this.observedContextItems=e,this.contextItemsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.contextItemsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.contextItemsResizeObserver.observe(e)))}updateScrollState(){const e=this.contextItemsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}contextItemsElement(){const e=this.contextItems;return e instanceof HTMLElement?e:void 0}};ge.styles=D`
2199
2477
  /* Keep the refresh menu in this shadow tree above the following mobile tab strip. */
2200
2478
  :host { position: relative; z-index: 20; flex: 0 0 auto; min-width: 0; }
2201
2479
  .context-bar { position: relative; flex: 0 0 auto; min-width: 0; display: flex; align-items: center; gap: 0; padding: 6px 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
@@ -2221,7 +2499,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2221
2499
  .context-kind { display: none; }
2222
2500
  .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
2223
2501
  button { cursor: pointer; }
2224
- `;Re([d({attribute:!1})],pe.prototype,"machines",2);Re([d({attribute:!1})],pe.prototype,"machine",2);Re([d({attribute:!1})],pe.prototype,"project",2);Re([d({attribute:!1})],pe.prototype,"workspace",2);Re([d({attribute:!1})],pe.prototype,"session",2);Re([d({attribute:!1})],pe.prototype,"refreshControl",2);Re([d({attribute:!1})],pe.prototype,"onOpenSection",2);Re([d({attribute:!1})],pe.prototype,"onShowActions",2);Re([B(".context-items")],pe.prototype,"contextItems",2);Re([w()],pe.prototype,"canScrollLeft",2);Re([w()],pe.prototype,"canScrollRight",2);pe=Re([W("app-context-bar")],pe);function C0(e){return e.length>1}function I0(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function R0(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function A0(e){return e?.name??"未选择项目"}function T0(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function M0(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function E0(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function D0(e){const t=e?.name?.trim(),i=e?.firstMessage.trim();return t!==void 0&&t!==""?t:i!==void 0&&i!==""?i:e?.id.slice(0,8)??"未选择会话"}function W0(e){return e===void 0?"未选择会话":e.path}var O0=Object.defineProperty,_0=Object.getOwnPropertyDescriptor,vt=(e,t,i,s)=>{for(var r=s>1?void 0:s?_0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&O0(t,i,r),r};let Ve=class extends R{constructor(){super(...arguments),this.tabs=[],this.selectedView="chat",this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){const e=this.fallbackLabels();return l`
2502
+ `;We([c({attribute:!1})],ge.prototype,"machines",2);We([c({attribute:!1})],ge.prototype,"machine",2);We([c({attribute:!1})],ge.prototype,"project",2);We([c({attribute:!1})],ge.prototype,"workspace",2);We([c({attribute:!1})],ge.prototype,"session",2);We([c({attribute:!1})],ge.prototype,"refreshControl",2);We([c({attribute:!1})],ge.prototype,"onOpenSection",2);We([c({attribute:!1})],ge.prototype,"onShowActions",2);We([q(".context-items")],ge.prototype,"contextItems",2);We([v()],ge.prototype,"canScrollLeft",2);We([v()],ge.prototype,"canScrollRight",2);ge=We([W("app-context-bar")],ge);function hx(e){return e.length>1}function ux(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function fx(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function gx(e){return e?.name??"未选择项目"}function mx(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function vx(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function bx(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function wx(e){const t=e?.name?.trim(),i=e?.firstMessage.trim();return t!==void 0&&t!==""?t:i!==void 0&&i!==""?i:e===void 0?"未选择会话":Sc(e.id)}function yx(e){return e===void 0?"未选择会话":e.path}var Sx=Object.defineProperty,xx=Object.getOwnPropertyDescriptor,It=(e,t,i,s)=>{for(var r=s>1?void 0:s?xx(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&&Sx(t,i,r),r};let tt=class extends I{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`
2225
2503
  <div class=${this.frameClass()}>
2226
2504
  <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
2227
2505
  ${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
@@ -2233,7 +2511,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2233
2511
  `})}
2234
2512
  </div>
2235
2513
  </div>
2236
- `}frameClass(){return`mobile-tabs-frame${this.canScrollLeft?" can-scroll-left":""}${this.canScrollRight?" can-scroll-right":""}`}tabClass(e){return[...e.className===void 0?[]:[e.className],...this.selectedView===e.id?["selected"]:[]].join(" ")}tabAriaLabel(e){if(typeof e.badge!="string"&&typeof e.badge!="number")return e.label;const t=String(e.badge).trim();return t===""?e.label:`${e.label}, ${t}`}isEmptyBadge(e){return e===void 0||e===""}renderTabMark(e,t){return e.icon===void 0?l`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:yg(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const r=this.initialsLabel(s.label);t.set(r,(t.get(r)??0)+1)}const i=new Map;for(const s of e){const r=this.initialsLabel(s.label);i.set(s.id,(t.get(r)??0)>1?this.fullFallbackLabel(s.label):r)}return i}initialsLabel(e){const i=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(s=>Array.from(s)[0]??"").join("").toLocaleUpperCase();return i===""?"?":i}fullFallbackLabel(e){const t=e.trim();return t===""?"?":t}observeMobileTabs(){const e=this.mobileTabsElement();this.observedMobileTabs!==e&&(this.mobileTabsResizeObserver?.disconnect(),this.observedMobileTabs=e,this.mobileTabsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.mobileTabsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.mobileTabsResizeObserver.observe(e)))}updateScrollState(){const e=this.mobileTabsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}mobileTabsElement(){const e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}};Ve.styles=D`
2514
+ `}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>`:mm(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}};tt.styles=D`
2237
2515
  :host { flex: 0 0 auto; min-width: 0; }
2238
2516
  .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); }
2239
2517
  .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; }
@@ -2259,12 +2537,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2259
2537
  .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; }
2260
2538
  .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
2261
2539
  }
2262
- `;vt([d({attribute:!1})],Ve.prototype,"tabs",2);vt([d({attribute:!1})],Ve.prototype,"selectedView",2);vt([d({attribute:!1})],Ve.prototype,"onSelect",2);vt([B(".mobile-tabs")],Ve.prototype,"mobileTabs",2);vt([w()],Ve.prototype,"canScrollLeft",2);vt([w()],Ve.prototype,"canScrollRight",2);Ve=vt([W("app-mobile-main-tabs")],Ve);var L0=Object.defineProperty,j0=Object.getOwnPropertyDescriptor,ve=(e,t,i,s)=>{for(var r=s>1?void 0:s?j0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&L0(t,i,r),r};let oe=class extends R{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.open=!1,this.menuStyle="",this.actionMenuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has("machines")&&this.openActionsMachineId!==void 0&&!this.machines.some(t=>t.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){const e=this.switcherButton();return e===null?!1:await this.openMenuAndFocusOption(e)}render(){const e=this.selectedMachine();if(e===void 0)return null;const t=Us(e,this.statuses),i=e.name;return l`
2540
+ `;It([c({attribute:!1})],tt.prototype,"tabs",2);It([c({attribute:!1})],tt.prototype,"selectedView",2);It([c({attribute:!1})],tt.prototype,"onSelect",2);It([q(".mobile-tabs")],tt.prototype,"mobileTabs",2);It([v()],tt.prototype,"canScrollLeft",2);It([v()],tt.prototype,"canScrollRight",2);tt=It([W("app-mobile-main-tabs")],tt);var kx=Object.defineProperty,$x=Object.getOwnPropertyDescriptor,ke=(e,t,i,s)=>{for(var r=s>1?void 0:s?$x(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&&kx(t,i,r),r};let de=class extends I{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=pr(e,this.statuses),i=e.name;return l`
2263
2541
  <div class="machine-switcher">
2264
2542
  <button
2265
2543
  type="button"
2266
2544
  class="machine-switcher-button"
2267
- title=${da(e)}
2545
+ title=${Ha(e)}
2268
2546
  aria-label=${`Machine: ${i}. Switch machine.`}
2269
2547
  aria-expanded=${String(this.open)}
2270
2548
  @click=${s=>{this.toggleMenu(s.currentTarget)}}
@@ -2275,7 +2553,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2275
2553
  <span class="machine-switcher-kicker">Machine</span>
2276
2554
  <span class="machine-switcher-label">${i}</span>
2277
2555
  </span>
2278
- <span class=${`machine-status ${t}`}>${ca(t)}</span>
2556
+ <span class=${`machine-status ${t}`}>${qa(t)}</span>
2279
2557
  <span class="machine-chevron" aria-hidden="true">▾</span>
2280
2558
  </button>
2281
2559
  ${this.open?l`
@@ -2284,18 +2562,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2284
2562
  </div>
2285
2563
  `:null}
2286
2564
  </div>
2287
- `}renderMachineOption(e){const t=this.selected?.id===e.id,i=Us(e,this.statuses),s=Ll(e)&&this.onRemove!==void 0,r=this.openActionsMachineId===e.id;return l`
2565
+ `}renderMachineOption(e){const t=this.selected?.id===e.id,i=pr(e,this.statuses),s=yc(e)&&this.onRemove!==void 0,r=this.openActionsMachineId===e.id;return l`
2288
2566
  <div class=${`machine-option ${t?"selected":""} ${s?"":"no-actions"}`}>
2289
2567
  <button
2290
2568
  type="button"
2291
2569
  class="machine-option-main"
2292
- title=${da(e)}
2570
+ title=${Ha(e)}
2293
2571
  data-machine-id=${e.id}
2294
2572
  @click=${()=>{this.select(e)}}
2295
2573
  @keydown=${o=>{this.handleMachineOptionKeydown(o)}}
2296
2574
  >
2297
2575
  <span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
2298
- <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${ca(i)}</small>
2576
+ <small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${qa(i)}</small>
2299
2577
  </button>
2300
2578
  ${s?l`
2301
2579
  <div class="machine-option-actions">
@@ -2315,7 +2593,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2315
2593
  </div>
2316
2594
  `:null}
2317
2595
  </div>
2318
- `}renderActivity(e){const t=Us(e,this.statuses);if(t==="offline"||t==="error")return;const i=Rl(this.activities[e.id]);return Tl(i,i==="terminal"?"Machine terminal active":"Machine active")}selectedMachine(){return this.selected??this.machines.find(e=>e.id==="local")??this.machines[0]}switcherButton(){return this.renderRoot.querySelector(".machine-switcher-button")}handleSwitcherButtonKeydown(e){if(e.key==="ArrowDown"||e.key==="ArrowUp"){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key==="Escape"&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key==="ArrowUp"){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key==="ArrowDown"){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key==="Home"){this.focusIndexedMachineOption(0,e);return}if(e.key==="End"){this.focusIndexedMachineOption(-1,e);return}if(e.key==="ArrowRight"&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key==="ArrowLeft"||e.key==="Escape")&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=pa(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){const e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=pa(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){const e=this.renderRoot.querySelector(".machine-option.selected .machine-option-main"),t=this.machineOptionButtons()[0],i=e??t;return i===void 0?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}focusRelativeMachineOption(e,t,i){i.preventDefault(),i.stopPropagation();const s=this.machineOptionButtons();if(s.length===0||!(e instanceof HTMLElement))return;const r=s.indexOf(e);r<0||this.focusMachineOptionAt(r+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){const t=this.machineOptionButtons(),i=t[Math.min(Math.max(e,0),t.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(".machine-option-main"))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=Ml(t,{constrainTo:"viewport"}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}};oe.styles=D`
2596
+ `}renderActivity(e){const t=pr(e,this.statuses);if(t==="offline"||t==="error")return;const i=pc(this.activities[e.id]);return uc(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=Ka(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=Ka(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=fc(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)}};de.styles=D`
2319
2597
  :host { min-width: 0; display: block; }
2320
2598
  .machine-switcher { min-width: 0; }
2321
2599
  .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; }
@@ -2348,10 +2626,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2348
2626
  .machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
2349
2627
  .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); }
2350
2628
  @keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
2351
- `;ve([d({attribute:!1})],oe.prototype,"machines",2);ve([d({attribute:!1})],oe.prototype,"selected",2);ve([d({attribute:!1})],oe.prototype,"statuses",2);ve([d({attribute:!1})],oe.prototype,"activities",2);ve([d({attribute:!1})],oe.prototype,"onSelect",2);ve([d({attribute:!1})],oe.prototype,"onRemove",2);ve([d({attribute:!1})],oe.prototype,"onFocusNextSection",2);ve([d({attribute:!1})],oe.prototype,"onCancelKeyboardNavigation",2);ve([w()],oe.prototype,"open",2);ve([w()],oe.prototype,"menuStyle",2);ve([w()],oe.prototype,"openActionsMachineId",2);ve([w()],oe.prototype,"actionMenuStyle",2);oe=ve([W("machine-switcher")],oe);function Us(e,t){return t[e.id]?.status??e.status??"unknown"}function ca(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function da(e){return e.baseUrl??e.name}function pa(e){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const t=e.getBoundingClientRect(),i=8,s=Math.min(280,Math.max(0,window.innerWidth-i*2)),r=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),o=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${gi(t.bottom)};`,`left: ${gi(r)};`,`width: ${gi(s)};`,`max-height: ${gi(o)};`].join(" ")}function gi(e){return`${String(Math.round(e))}px`}var F0=Object.defineProperty,z0=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var r=s>1?void 0:s?z0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&F0(t,i,r),r};let S=class extends R{constructor(){super(...arguments),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canCleanupSessions=!1,this.archivedDeleteUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再删除已归档会话。",this.cleanupUnavailableMessage="请更新并重启此机器上的 Pi-Web 后再清理会话。"}async focusSection(e){switch(await this.updateComplete,e){case"machines":return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case"projects":return await this.focusNavigableSection(this.projectList);case"workspaces":return await this.focusNavigableSection(this.workspaceList);case"sessions":return await this.focusNavigableSection(this.sessionList)}}render(){return l`
2629
+ `;ke([c({attribute:!1})],de.prototype,"machines",2);ke([c({attribute:!1})],de.prototype,"selected",2);ke([c({attribute:!1})],de.prototype,"statuses",2);ke([c({attribute:!1})],de.prototype,"activities",2);ke([c({attribute:!1})],de.prototype,"onSelect",2);ke([c({attribute:!1})],de.prototype,"onRemove",2);ke([c({attribute:!1})],de.prototype,"onFocusNextSection",2);ke([c({attribute:!1})],de.prototype,"onCancelKeyboardNavigation",2);ke([v()],de.prototype,"open",2);ke([v()],de.prototype,"menuStyle",2);ke([v()],de.prototype,"openActionsMachineId",2);ke([v()],de.prototype,"actionMenuStyle",2);de=ke([W("machine-switcher")],de);function pr(e,t){return t[e.id]?.status??e.status??"unknown"}function qa(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function Ha(e){return e.baseUrl??e.name}function Ka(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: ${Wi(t.bottom)};`,`left: ${Wi(r)};`,`width: ${Wi(s)};`,`max-height: ${Wi(o)};`].join(" ")}function Wi(e){return`${String(Math.round(e))}px`}var Px=Object.defineProperty,Cx=Object.getOwnPropertyDescriptor,k=(e,t,i,s)=>{for(var r=s>1?void 0:s?Cx(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&&Px(t,i,r),r};let x=class extends I{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.startingSessionCount=0,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canCleanupSessions=!1,this.authoritativeSessionPersistence=!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`
2352
2630
  <header>
2353
2631
  <strong>PI WEB</strong>
2354
- ${Ji(this.machines)?l`
2632
+ ${vs(this.machines)?l`
2355
2633
  <machine-switcher
2356
2634
  .machines=${this.machines}
2357
2635
  .selected=${this.selectedMachine}
@@ -2368,7 +2646,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2368
2646
  <button title="显示操作" aria-label="显示操作" @click=${()=>{this.onShowActions?.()}}>操作</button>
2369
2647
  </div>
2370
2648
  </header>
2371
- ${this.compact&&Ji(this.machines)?l`
2649
+ ${this.compact&&vs(this.machines)?l`
2372
2650
  <machine-list
2373
2651
  .machines=${this.machines}
2374
2652
  .selected=${this.selectedMachine}
@@ -2418,10 +2696,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2418
2696
  .activities=${this.sessionActivities}
2419
2697
  .sending=${this.sendingPrompts}
2420
2698
  .selected=${this.selectedSession}
2699
+ .startingCount=${this.startingSessionCount}
2421
2700
  .canStart=${this.canStartSession}
2422
2701
  .canDeleteArchived=${this.canDeleteArchivedSessions}
2423
2702
  .canReload=${this.canReloadSessions}
2424
2703
  .canCleanup=${this.canCleanupSessions}
2704
+ .authoritativeSessionPersistence=${this.authoritativeSessionPersistence}
2425
2705
  .archivedDeleteUnavailableMessage=${this.archivedDeleteUnavailableMessage}
2426
2706
  .cleanupUnavailableMessage=${this.cleanupUnavailableMessage}
2427
2707
  .collapsible=${this.collapsible}
@@ -2444,7 +2724,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2444
2724
  .onFocusNextSection=${()=>{this.focusNextFrom("sessions")}}
2445
2725
  .onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
2446
2726
  ></session-list>
2447
- `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=U0(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(B0(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};S.styles=D`
2727
+ `}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=Rx(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Ix(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};x.styles=D`
2448
2728
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
2449
2729
  :host([compact]) { flex: 1 1 auto; }
2450
2730
  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); }
@@ -2467,7 +2747,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2467
2747
  :host([compact]) workspace-list[collapsed],
2468
2748
  :host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
2469
2749
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2470
- `;k([d({attribute:!1})],S.prototype,"machines",2);k([d({attribute:!1})],S.prototype,"selectedMachine",2);k([d({attribute:!1})],S.prototype,"machineStatuses",2);k([d({attribute:!1})],S.prototype,"machineActivities",2);k([d({attribute:!1})],S.prototype,"projects",2);k([d({attribute:!1})],S.prototype,"selectedProject",2);k([d({attribute:!1})],S.prototype,"workspaces",2);k([d({attribute:!1})],S.prototype,"selectedWorkspace",2);k([d({attribute:!1})],S.prototype,"sessions",2);k([d({attribute:!1})],S.prototype,"selectedSession",2);k([d({attribute:!1})],S.prototype,"workspaceActivities",2);k([d({attribute:!1})],S.prototype,"sessionActivities",2);k([d({attribute:!1})],S.prototype,"sessionStatuses",2);k([d({attribute:!1})],S.prototype,"sendingPrompts",2);k([d({attribute:!1})],S.prototype,"workspacesByProjectId",2);k([d({attribute:!1})],S.prototype,"deletingWorkspaceIds",2);k([d({attribute:!1})],S.prototype,"workspaceLabelItems",2);k([d({attribute:!1})],S.prototype,"refreshControl",2);k([d({type:Boolean,reflect:!0})],S.prototype,"collapsible",2);k([d({type:Boolean,reflect:!0})],S.prototype,"compact",2);k([d({type:Boolean})],S.prototype,"machinesCollapsed",2);k([d({type:Boolean})],S.prototype,"projectsCollapsed",2);k([d({type:Boolean})],S.prototype,"workspacesCollapsed",2);k([d({type:Boolean})],S.prototype,"sessionsCollapsed",2);k([d({type:Boolean})],S.prototype,"canStartSession",2);k([d({type:Boolean})],S.prototype,"canDeleteArchivedSessions",2);k([d({type:Boolean})],S.prototype,"canReloadSessions",2);k([d({type:Boolean})],S.prototype,"canCleanupSessions",2);k([d({type:String})],S.prototype,"archivedDeleteUnavailableMessage",2);k([d({type:String})],S.prototype,"cleanupUnavailableMessage",2);k([d({attribute:!1})],S.prototype,"onShowActions",2);k([d({attribute:!1})],S.prototype,"onToggleMachines",2);k([d({attribute:!1})],S.prototype,"onToggleProjects",2);k([d({attribute:!1})],S.prototype,"onToggleWorkspaces",2);k([d({attribute:!1})],S.prototype,"onToggleSessions",2);k([d({attribute:!1})],S.prototype,"onSelectProject",2);k([d({attribute:!1})],S.prototype,"onCloseProject",2);k([d({attribute:!1})],S.prototype,"onSelectWorkspace",2);k([d({attribute:!1})],S.prototype,"onDeleteWorkspace",2);k([d({attribute:!1})],S.prototype,"onStartSession",2);k([d({attribute:!1})],S.prototype,"onSelectSession",2);k([d({attribute:!1})],S.prototype,"onArchiveSession",2);k([d({attribute:!1})],S.prototype,"onArchiveSessionWithDescendants",2);k([d({attribute:!1})],S.prototype,"onArchiveSessions",2);k([d({attribute:!1})],S.prototype,"onRestoreSession",2);k([d({attribute:!1})],S.prototype,"onDeleteCachedNewSession",2);k([d({attribute:!1})],S.prototype,"onDeleteArchivedSession",2);k([d({attribute:!1})],S.prototype,"onDeleteArchivedSessions",2);k([d({attribute:!1})],S.prototype,"onDetachParentSession",2);k([d({attribute:!1})],S.prototype,"onReloadSession",2);k([d({attribute:!1})],S.prototype,"onCleanupSessions",2);k([d({attribute:!1})],S.prototype,"onArchivedCollapsed",2);k([d({attribute:!1})],S.prototype,"onSelectMachine",2);k([d({attribute:!1})],S.prototype,"onRemoveMachine",2);k([d({attribute:!1})],S.prototype,"onFocusNavigationTarget",2);k([d({attribute:!1})],S.prototype,"onCancelKeyboardNavigation",2);k([B("machine-list")],S.prototype,"machineList",2);k([B("machine-switcher")],S.prototype,"machineSwitcher",2);k([B("project-list")],S.prototype,"projectList",2);k([B("workspace-list")],S.prototype,"workspaceList",2);k([B("session-list")],S.prototype,"sessionList",2);S=k([W("app-navigation-panel")],S);function Ji(e){return e.length>1}function U0(e,t){const i=lc(t);return i[i.indexOf(e)-1]}function B0(e,t){const i=lc(t);return i[i.indexOf(e)+1]??"chat"}function lc(e){return Bi.filter(t=>t!=="machines"||Ji(e))}var N0=Object.defineProperty,H0=Object.getOwnPropertyDescriptor,ie=(e,t,i,s)=>{for(var r=s>1?void 0:s?H0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&N0(t,i,r),r};const q0=new Set(["ArrowLeft","ArrowRight","Home","End"]),K0=420,V0=4;let V=class extends R{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.resizable=!1,this.controls="",this.resizeLabel="调整面板宽度",this.expandLabel="展开面板",this.collapseLabel="折叠面板",this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
2750
+ `;k([c({attribute:!1})],x.prototype,"machines",2);k([c({attribute:!1})],x.prototype,"selectedMachine",2);k([c({attribute:!1})],x.prototype,"machineStatuses",2);k([c({attribute:!1})],x.prototype,"machineActivities",2);k([c({attribute:!1})],x.prototype,"projects",2);k([c({attribute:!1})],x.prototype,"selectedProject",2);k([c({attribute:!1})],x.prototype,"workspaces",2);k([c({attribute:!1})],x.prototype,"selectedWorkspace",2);k([c({attribute:!1})],x.prototype,"sessions",2);k([c({attribute:!1})],x.prototype,"selectedSession",2);k([c({attribute:!1})],x.prototype,"workspaceActivities",2);k([c({attribute:!1})],x.prototype,"sessionActivities",2);k([c({attribute:!1})],x.prototype,"sessionStatuses",2);k([c({attribute:!1})],x.prototype,"sendingPrompts",2);k([c({attribute:!1})],x.prototype,"workspacesByProjectId",2);k([c({attribute:!1})],x.prototype,"deletingWorkspaceIds",2);k([c({attribute:!1})],x.prototype,"workspaceLabelItems",2);k([c({attribute:!1})],x.prototype,"refreshControl",2);k([c({type:Boolean,reflect:!0})],x.prototype,"collapsible",2);k([c({type:Boolean,reflect:!0})],x.prototype,"compact",2);k([c({type:Boolean})],x.prototype,"machinesCollapsed",2);k([c({type:Boolean})],x.prototype,"projectsCollapsed",2);k([c({type:Boolean})],x.prototype,"workspacesCollapsed",2);k([c({type:Boolean})],x.prototype,"sessionsCollapsed",2);k([c({type:Number})],x.prototype,"startingSessionCount",2);k([c({type:Boolean})],x.prototype,"canStartSession",2);k([c({type:Boolean})],x.prototype,"canDeleteArchivedSessions",2);k([c({type:Boolean})],x.prototype,"canReloadSessions",2);k([c({type:Boolean})],x.prototype,"canCleanupSessions",2);k([c({type:Boolean})],x.prototype,"authoritativeSessionPersistence",2);k([c({type:String})],x.prototype,"archivedDeleteUnavailableMessage",2);k([c({type:String})],x.prototype,"cleanupUnavailableMessage",2);k([c({attribute:!1})],x.prototype,"onShowActions",2);k([c({attribute:!1})],x.prototype,"onToggleMachines",2);k([c({attribute:!1})],x.prototype,"onToggleProjects",2);k([c({attribute:!1})],x.prototype,"onToggleWorkspaces",2);k([c({attribute:!1})],x.prototype,"onToggleSessions",2);k([c({attribute:!1})],x.prototype,"onSelectProject",2);k([c({attribute:!1})],x.prototype,"onCloseProject",2);k([c({attribute:!1})],x.prototype,"onSelectWorkspace",2);k([c({attribute:!1})],x.prototype,"onDeleteWorkspace",2);k([c({attribute:!1})],x.prototype,"onStartSession",2);k([c({attribute:!1})],x.prototype,"onSelectSession",2);k([c({attribute:!1})],x.prototype,"onArchiveSession",2);k([c({attribute:!1})],x.prototype,"onArchiveSessionWithDescendants",2);k([c({attribute:!1})],x.prototype,"onArchiveSessions",2);k([c({attribute:!1})],x.prototype,"onRestoreSession",2);k([c({attribute:!1})],x.prototype,"onDeleteCachedNewSession",2);k([c({attribute:!1})],x.prototype,"onDeleteArchivedSession",2);k([c({attribute:!1})],x.prototype,"onDeleteArchivedSessions",2);k([c({attribute:!1})],x.prototype,"onDetachParentSession",2);k([c({attribute:!1})],x.prototype,"onReloadSession",2);k([c({attribute:!1})],x.prototype,"onCleanupSessions",2);k([c({attribute:!1})],x.prototype,"onArchivedCollapsed",2);k([c({attribute:!1})],x.prototype,"onSelectMachine",2);k([c({attribute:!1})],x.prototype,"onRemoveMachine",2);k([c({attribute:!1})],x.prototype,"onFocusNavigationTarget",2);k([c({attribute:!1})],x.prototype,"onCancelKeyboardNavigation",2);k([q("machine-list")],x.prototype,"machineList",2);k([q("machine-switcher")],x.prototype,"machineSwitcher",2);k([q("project-list")],x.prototype,"projectList",2);k([q("workspace-list")],x.prototype,"workspaceList",2);k([q("session-list")],x.prototype,"sessionList",2);x=k([W("app-navigation-panel")],x);function vs(e){return e.length>1}function Rx(e,t){const i=Xc(t);return i[i.indexOf(e)-1]}function Ix(e,t){const i=Xc(t);return i[i.indexOf(e)+1]??"chat"}function Xc(e){return cs.filter(t=>t!=="machines"||vs(e))}var Ax=Object.defineProperty,Mx=Object.getOwnPropertyDescriptor,ae=(e,t,i,s)=>{for(var r=s>1?void 0:s?Mx(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&&Ax(t,i,r),r};const Tx=new Set(["ArrowLeft","ArrowRight","Home","End"]),Ex=420,Dx=4;let J=class extends I{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`
2471
2751
  ${this.renderResizeHandle()}
2472
2752
  <button
2473
2753
  type="button"
@@ -2478,7 +2758,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2478
2758
  aria-expanded=${String(!this.collapsed)}
2479
2759
  @click=${()=>{this.onToggle?.()}}
2480
2760
  >${this.renderIcon()}</button>
2481
- `}renderResizeHandle(){if(!this.resizable)return U;const e=this.resizeConstraints();return l`
2761
+ `}renderResizeHandle(){if(!this.resizable)return B;const e=this.resizeConstraints();return l`
2482
2762
  <div
2483
2763
  class="resize-handle"
2484
2764
  role="separator"
@@ -2497,7 +2777,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2497
2777
  @dblclick=${t=>{this.onResizeDoubleClick(t)}}
2498
2778
  @keydown=${t=>{this.onResizeKeyDown(t)}}
2499
2779
  ></div>
2500
- `}resizeAriaValueNow(){return this.panelWidth===void 0?U:String(Math.round(this.panelWidth))}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return l`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${t}/></svg>`}iconDirection(){return this.side==="navigation"?this.collapsed?"right":"left":this.collapsed?"left":"right"}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=this.resizeStartWidth();i!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:i,handle:t,moved:!1},this.toggleAttribute("resizing",!0))}onResizePointerMove(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=V0)&&(t.moved=!0,this.commitPanelWidth(Km(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!q0.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=Vm(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});i!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(i),this.onResizeEnd?.())}registerTapForReset(){const e=Date.now();if(e-this.lastTapAt<=K0){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){const e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return we(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(we(this.side,e,this.resizeConstraints()))}finishActiveResize(){const e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute("resizing",!1),this.onResizeEnd?.()}}resizeConstraints(){const e=ri(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};V.styles=D`
2780
+ `}resizeAriaValueNow(){return this.panelWidth===void 0?B: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)<=Dx)&&(t.moved=!0,this.commitPanelWidth(zv(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||!Tx.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=Nv(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<=Ex){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 Ce(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(Ce(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=Si(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};J.styles=D`
2501
2781
  :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; }
2502
2782
  :host([side="navigation"]) { grid-column: 2; }
2503
2783
  :host([side="workspace"]) { grid-column: 4; }
@@ -2516,7 +2796,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2516
2796
  @media (max-width: 760px) {
2517
2797
  :host([side="navigation"]) { display: none; }
2518
2798
  }
2519
- `;ie([d({reflect:!0})],V.prototype,"side",2);ie([d({type:Boolean,reflect:!0})],V.prototype,"collapsed",2);ie([d({type:Boolean})],V.prototype,"resizable",2);ie([d({type:Number})],V.prototype,"panelWidth",2);ie([d({type:Number})],V.prototype,"minWidth",2);ie([d({type:Number})],V.prototype,"maxWidth",2);ie([d()],V.prototype,"controls",2);ie([d()],V.prototype,"resizeLabel",2);ie([d()],V.prototype,"expandLabel",2);ie([d()],V.prototype,"collapseLabel",2);ie([d({attribute:!1})],V.prototype,"onToggle",2);ie([d({attribute:!1})],V.prototype,"onResizeStart",2);ie([d({attribute:!1})],V.prototype,"onResize",2);ie([d({attribute:!1})],V.prototype,"onResizeEnd",2);ie([d({attribute:!1})],V.prototype,"onReset",2);V=ie([W("app-panel-edge-control")],V);var G0=Object.defineProperty,J0=Object.getOwnPropertyDescriptor,cc=(e,t,i,s)=>{for(var r=s>1?void 0:s?J0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&G0(t,i,r),r};let Qi=class extends R{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="完整重载页面";return l`
2799
+ `;ae([c({reflect:!0})],J.prototype,"side",2);ae([c({type:Boolean,reflect:!0})],J.prototype,"collapsed",2);ae([c({type:Boolean})],J.prototype,"resizable",2);ae([c({type:Number})],J.prototype,"panelWidth",2);ae([c({type:Number})],J.prototype,"minWidth",2);ae([c({type:Number})],J.prototype,"maxWidth",2);ae([c()],J.prototype,"controls",2);ae([c()],J.prototype,"resizeLabel",2);ae([c()],J.prototype,"expandLabel",2);ae([c()],J.prototype,"collapseLabel",2);ae([c({attribute:!1})],J.prototype,"onToggle",2);ae([c({attribute:!1})],J.prototype,"onResizeStart",2);ae([c({attribute:!1})],J.prototype,"onResize",2);ae([c({attribute:!1})],J.prototype,"onResizeEnd",2);ae([c({attribute:!1})],J.prototype,"onReset",2);J=ae([W("app-panel-edge-control")],J);var Wx=Object.defineProperty,Lx=Object.getOwnPropertyDescriptor,Yc=(e,t,i,s)=>{for(var r=s>1?void 0:s?Lx(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&&Wx(t,i,r),r};let bs=class extends I{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="完整重载页面";return l`
2520
2800
  <button
2521
2801
  class="app-refresh-button"
2522
2802
  title=${e}
@@ -2530,12 +2810,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2530
2810
  <path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
2531
2811
  <path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
2532
2812
  </svg>
2533
- `}};Qi.styles=D`
2813
+ `}};bs.styles=D`
2534
2814
  :host { position: relative; z-index: 1; display: flex; align-items: center; pointer-events: auto; -webkit-touch-callout: none; -webkit-user-select: none; user-select: none; }
2535
2815
  :host, :host * { -webkit-user-select: none; user-select: none; }
2536
2816
  .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; }
2537
2817
  .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
2538
- `;cc([d({attribute:!1})],Qi.prototype,"onReload",2);Qi=cc([W("app-refresh-control")],Qi);var Q0=Object.defineProperty,Z0=Object.getOwnPropertyDescriptor,Z=(e,t,i,s)=>{for(var r=s>1?void 0:s?Z0(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Q0(t,i,r),r};const X0=D`
2818
+ `;Yc([c({attribute:!1})],bs.prototype,"onReload",2);bs=Yc([W("app-refresh-control")],bs);var Ox=Object.defineProperty,Fx=Object.getOwnPropertyDescriptor,ie=(e,t,i,s)=>{for(var r=s>1?void 0:s?Fx(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&&Ox(t,i,r),r};const _x=D`
2539
2819
  /* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
2540
2820
  :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; }
2541
2821
  :host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
@@ -2634,7 +2914,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2634
2914
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
2635
2915
  .empty { margin: auto; color: var(--pi-muted); }
2636
2916
  .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
2637
- `,Y0=900*1e3,ex=750,ur=[1e3,3e3,8e3,15e3,3e4],ha={capture:!0},Bs="auto:on",ua="auto:off",mi="theme:",Ns=ei("core:workspace.files"),Hs=ei("core:workspace.git"),vi=ei("core:workspace.terminal"),tx=320,ix=2,sx="(min-width: 1181px)";let K=class extends R{constructor(){super(...arguments),this.state=lh(),this.apiScope=ox(),this.sessions=new of(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Xu,{socket:new rl(this.apiScope)}),this.activity=new ch(()=>this.state,e=>{this.setState(e)}),this.auth=new hh(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new vf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new gf),this.projects=new Ch(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Ph(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new yh(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new $h(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Tf,this.realtime=new Qo(this.apiScope),this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new xf,this.terminalSelection=new Rf,this.appShell=new Am(this),this.panelCollapse=new Bm(this),this.panelResize=new Hm(this),this.navigationSections=new Fm(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=rx(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Xf()??Jf,this.activeThemeId=zr,this.isRefreshingApp=!1,this.settingsSection=Tn(),this.normalAuthLoading=!0,this.normalAuthError="",this.shortcutConfig={},this.workspaceUploadDefaultFolder=Wo(void 0),this.appStartupStarted=!1,this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.previousStackedWorkspaceLayout=this.appShell.isStackedWorkspaceLayout,this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,i,s)=>{this.sendPrompt(e,t,i,s)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode),this.normalizeMainViewForLayoutChange()}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,ha),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.initializeNormalAuth()}startAuthenticatedApp(){this.appStartupStarted||(this.appStartupStarted=!0,this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},Y0),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()}))}async initializeNormalAuth(){if(this.apiScope==="management"){this.normalAuthStatus={configured:!0,authenticated:!0},this.normalAuthLoading=!1,this.startAuthenticatedApp();return}this.normalAuthLoading=!0,this.normalAuthError="";try{const e=await St.status();this.normalAuthStatus=e,e.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=`检查普通模式密码失败:${Ht(e)}`}finally{this.normalAuthLoading=!1}}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,ha),this.systemLightThemeMedia?.removeEventListener("change",this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!lx(this.state,e))return;const t=this.state;this.state={...this.state,...e},this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),nx(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=An();await this.machines.loadMachines(e.machineId);const t=this.routeForSelectedMachine(e),i=this.state.machineStatuses[t.machineId??"local"];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,i)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}schedulePiWebStatusRefresh(e=ex){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.refreshPiWebStatus()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshPiWebStatus(){const e=f(this.state);try{const t=await za.piWebStatus(e);f(this.state)===e&&this.setState({piWebStatus:t})}catch(t){f(this.state)===e&&this.setState({piWebStatus:void 0}),console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}async refreshWorkspaceActivity(e=f(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){const e=this.state.machines.length===0?[f(this.state)]:this.state.machines.filter(t=>dc(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await Mi.config()).effectiveConfig)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=Wo(e)}async submitNormalAuth(e){const t=this.normalAuthDialogMode??this.normalAuthGateMode();if(!(t===void 0||this.normalAuthLoading)){this.normalAuthLoading=!0,this.normalAuthError="";try{t==="setup"?await St.setup(e.password):t==="change"?await St.changePassword(e.currentPassword??"",e.password):await St.login(e.password);const i=await St.status();this.normalAuthStatus=i,this.normalAuthDialogMode=void 0,i.authenticated&&this.startAuthenticatedApp()}catch(i){this.normalAuthError=Ht(i)}finally{this.normalAuthLoading=!1}}}normalAuthGateMode(){if(this.apiScope!=="management"&&this.normalAuthStatus?.authenticated!==!0)return this.normalAuthStatus?.configured===!0?"login":"setup"}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(An(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const r=f(this.state),o=e.projectId===void 0||e.projectId===""?ma():i,n=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=o.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const a=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await a,!this.isCurrentRouteRestore(n))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:this.appShell.normalizedMainView(s??e.view,e.sessionId!==void 0),selectedFilePath:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const c=this.state.projects.find(p=>p.id===e.projectId);if(!c){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(c,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(n))return;this.setState({selectedFilePath:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),f(this.state)!==r&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?ma():{selectedFilePath:xs(Ns,"file"),selectedDiffPath:xs(Hs,"diff"),selectedTerminalId:xs(vi,"terminal")}}routeForSelectedMachine(e){const t=this.state.selectedMachine?.id??"local";return(e.machineId??"local")===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){Rs(e,{replace:!0}),ue(Ns,"file",void 0,{replace:!0}),ue(Hs,"diff",void 0,{replace:!0}),ue(vi,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.kind!=="remote"||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===""?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=dx(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;const e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{const t=e.machineId??"local",i=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==""){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=ur.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){const i=e.machineId??"local",s=this.state.machines.find(a=>a.id===i)?.name??this.state.selectedMachine?.name??"Remote machine",o=this.state.machineStatuses[i]?.error??(this.state.error===""?void 0:this.state.error),n=t.exhausted===!0?`${s} is still unavailable.`:`${s} is unavailable; reconnecting…`;this.setState({error:`${n}${o===void 0?"":` ${o}`}`})}pendingRemoteRouteRestoreStillCurrent(e){const t=e.machineId??"local";return t!=="local"&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(i=>i.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(r=>r.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await qs(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}normalizeMainViewForLayoutChange(){const e=this.previousStackedWorkspaceLayout,t=this.appShell.isStackedWorkspaceLayout;if(this.previousStackedWorkspaceLayout=t,e||!t)return;const i=this.appShell.normalizedMainView(this.state.mainView,this.state.selectedSession!==void 0);i!==this.state.mainView&&(this.setState({mainView:i}),this.updateUrl({replace:!0}))}updateUrl(e){this.rememberCurrentMachineNavigation(),Rs({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView==="navigation"?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(on(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(on(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Rs(nn(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){ue(Ns,"file",e.selectedFilePath,{replace:!0}),ue(Hs,"diff",e.selectedDiffPath,{replace:!0}),ue(vi,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??Sf(e.id);if(await this.restoreRouteFor(nn(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==""}openWorkspaceTool(e){e==="core:workspace.terminal"&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool("core:workspace.terminal")}terminalCommandRunsForOrigin(e,t=f(this.state)){const i=va(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const r=av(e,{api:{runTerminalCommand:(o,n)=>$t.runTerminalCommand(o,n,t),listCommandRuns:o=>$t.listCommandRuns(o,t),getCommandRun:o=>$t.getCommandRun(o,t)},openTerminal:(o,n)=>{this.openRuntimeTerminal(t,o,n)}});return this.terminalCommandRunRuntimes.set(i,r),r}async openRuntimeTerminal(e,t,i){if((f(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:"core:workspace.terminal",view:"core:workspace.terminal"},!1,{selectedTerminalId:i?.terminalId},"core:workspace.terminal"),f(this.state)!==e)){this.setState({error:"Machine not found for terminal command run"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){ue(vi,"terminal",e,t)}terminalWorkspaceKey(e){return`${f(this.state)}:${e.path}`}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e="general"){this.settingsSection=e,As(e)}closeSettings(){this.settingsSection=void 0,As(void 0)}navigateSettings(e){this.settingsSection=e,As(e)}restoreSettingsRoute(){this.settingsSection=Tn()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();const i=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:i}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(i,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}connectRealtime(){this.realtime.connect(e=>{this.handleRealtimeEvent(e)},()=>{const e=this.state.selectedWorkspace;e!==void 0&&this.refreshActiveTerminals(e),this.refreshWorkspaceActivity()},f(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new Qo(this.apiScope);i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=f(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>ax(t,this.state.machineStatuses[t.id])).map(t=>t.id))}handleMachineActivityEvent(e,t){t.type==="workspace.activity"&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e){e.type==="workspace.activity"?this.activity.applyWorkspaceActivity(e.activity):cx(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const t=this.state.selectedWorkspace;t===void 0||(e.type==="terminal.closed"?e.cwd:e.terminal.cwd)!==t.path||(e.type==="terminal.created"&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type==="terminal.closed"?e.terminalId:e.terminal.id),e.type==="terminal.closed"&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){const t=f(this.state);try{const i=await $t.terminals(e.projectId,e.id,t);if(f(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=ga(e),s=ga(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??"local")===(t.selectedMachine?.id??"local"))return;(this.pendingRemoteRouteRestore?.machineId??"local")!==(t.selectedMachine?.id??"local")&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine()}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return l`
2917
+ `,jx=900*1e3,Ux=750,Lr=[1e3,3e3,8e3,15e3,3e4],Va={capture:!0},hr="auto:on",Ga="auto:off",Li="theme:",ur=vi("core:workspace.files"),fr=vi("core:workspace.git"),Oi=vi("core:workspace.terminal"),Bx=320,zx=2,Nx="(min-width: 1181px)";let Q=class extends I{constructor(){super(...arguments),this.state=iu(),this.apiScope=Hx(),this.sessions=new Zf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Hf,{socket:new jl(this.apiScope)}),this.activity=new su(()=>this.state,e=>{this.setState(e)}),this.auth=new nu(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new ug(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new pg),this.projects=new yu(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new wu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new fu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new bu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Cg,this.realtime=new kn(this.apiScope),this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new vg,this.terminalSelection=new $g,this.appShell=new Pv(this),this.panelCollapse=new _v(this),this.panelResize=new Uv(this),this.navigationSections=new Lv(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=qx(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Gg()??Hg,this.activeThemeId=lo,this.isRefreshingApp=!1,this.settingsSection=sa(),this.normalAuthLoading=!0,this.normalAuthError="",this.shortcutConfig={},this.workspaceUploadDefaultFolder=on(void 0),this.appStartupStarted=!1,this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.schedulePiWebStatusRefresh(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.retryPendingRemoteRouteRestoreSoon())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.previousStackedWorkspaceLayout=this.appShell.isStackedWorkspaceLayout,this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,i,s)=>{this.sendPrompt(e,t,i,s)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode),this.normalizeMainViewForLayoutChange()}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,Va),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.initializeNormalAuth()}startAuthenticatedApp(){this.appStartupStarted||(this.appStartupStarted=!0,this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},jx),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()}))}async initializeNormalAuth(){if(this.apiScope==="management"){this.normalAuthStatus={configured:!0,authenticated:!0},this.normalAuthLoading=!1,this.startAuthenticatedApp();return}this.normalAuthLoading=!0,this.normalAuthError="";try{const e=await Wt.status();this.normalAuthStatus=e,e.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=`检查普通模式密码失败:${ii(e)}`}finally{this.normalAuthLoading=!1}}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,Va),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(!Gx(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),Kx(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=ia();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=Ux){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 kl.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=>ed(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 Ne.config()).effectiveConfig)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=on(e)}async submitNormalAuth(e){const t=this.normalAuthDialogMode??this.normalAuthGateMode();if(!(t===void 0||this.normalAuthLoading)){this.normalAuthLoading=!0,this.normalAuthError="";try{t==="setup"?await Wt.setup(e.password):t==="change"?await Wt.changePassword(e.currentPassword??"",e.password):await Wt.login(e.password);const i=await Wt.status();this.normalAuthStatus=i,this.normalAuthDialogMode=void 0,i.authenticated&&this.startAuthenticatedApp()}catch(i){this.normalAuthError=ii(i)}finally{this.normalAuthLoading=!1}}}normalAuthGateMode(){if(this.apiScope!=="management"&&this.normalAuthStatus?.authenticated!==!0)return this.normalAuthStatus?.configured===!0?"login":"setup"}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(ia(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const r=f(this.state),o=e.projectId===void 0||e.projectId===""?Za():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 d=this.state.projects.find(p=>p.id===e.projectId);if(!d){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(d,{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===""?Za():{selectedFilePath:Ns(ur,"file"),selectedDiffPath:Ns(fr,"diff"),selectedTerminalId:Ns(Oi,"terminal")}}routeForSelectedMachine(e){const t=this.state.selectedMachine?.id??"local";return(e.machineId??"local")===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){Xs(e,{replace:!0}),be(ur,"file",void 0,{replace:!0}),be(fr,"diff",void 0,{replace:!0}),be(Oi,"terminal",void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??"local"]){const i=e.machineId??"local",s=this.state.selectedMachine;return i==="local"||s?.id!==i||s.kind!=="remote"||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===""?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=Jx(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>=Lr.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 gr(),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(),Xs({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView==="navigation"?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(En(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(En(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Xs(Dn(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){be(ur,"file",e.selectedFilePath,{replace:!0}),be(fr,"diff",e.selectedDiffPath,{replace:!0}),be(Oi,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??bg(e.id);if(await this.restoreRouteFor(Dn(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=Xa(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const r=sb(e,{api:{runTerminalCommand:(o,n)=>Ot.runTerminalCommand(o,n,t),listCommandRuns:o=>Ot.listCommandRuns(o,t),getCommandRun:o=>Ot.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){be(Oi,"terminal",e,t)}terminalWorkspaceKey(e){return`${f(this.state)}:${e.path}`}selectMainView(e){if(e!=="navigation"&&e!=="chat"){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e="general"){this.settingsSection=e,Ys(e)}closeSettings(){this.settingsSection=void 0,Ys(void 0)}navigateSettings(e){this.settingsSection=e,Ys(e)}restoreSettingsRoute(){this.settingsSection=sa()}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 kn(this.apiScope);i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=f(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>Vx(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):Qx(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 Ot.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=Ja(e),s=Ja(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`
2638
2918
  <workspace-panel
2639
2919
  id="workspace-panel"
2640
2920
  .workspace=${e}
@@ -2680,7 +2960,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2680
2960
  .onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
2681
2961
  .onReset=${()=>{this.resetResizablePanel("workspace")}}
2682
2962
  ></app-panel-edge-control>
2683
- `}startPanelResize(e){return e==="navigation"?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){const t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){const i=this.getBoundingClientRect().width||(typeof window>"u"?0:window.innerWidth);if(i<=0)return t.maxWidth;const s=this.oppositeResizablePanelWidth(e),r=Math.floor(i-s-ix-tx);return Math.max(t.minWidth,Math.min(t.maxWidth,r))}oppositeResizablePanelWidth(e){const t=e==="navigation"?"workspace":"navigation";return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e==="navigation"?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>"u"||!("matchMedia"in window)?!0:window.matchMedia(sx).matches}measuredPanelWidth(e){const i=(e==="navigation"?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return i===void 0||i<=0?void 0:i}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&qe(e,_e.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&qe(e,_e.sessionsReload)}canCleanupSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&qe(e,_e.sessionsCleanup)}supportsWorkspaceFileSuggestions(e=f(this.state)){if(e==="local")return!0;const t=this.state.machineRuntimes[e];return t?.ok===!0&&qe(t,_e.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`请更新并重启 ${this.state.selectedMachine?.name??"此机器"} 上的 Pi-Web 后再删除已归档会话。`}sessionCleanupUnavailableMessage(){return Hf(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[f(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:""}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}const t=f(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:"",preview:void 0,previewRequest:void 0,result:void 0};try{const i=await Zs.cleanupPreview(e,t);if(f(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:i,previewRequest:e,result:void 0,loading:!1,error:""}}catch(i){f(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`预览清理失败:${Ht(i)}`})}}async runSessionCleanup(e){const t=this.sessionCleanupDialog;if(t?.preview===void 0||Rt(t.previewRequest)!==Rt(e)){this.sessionCleanupDialog={...t??{},error:"运行清理前请先预览。"};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}const i=f(this.state);this.sessionCleanupDialog={...t,running:!0,error:""};try{const s=await Zs.cleanup(e,i);if(f(this.state)!==i)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:s,previewRequest:e,result:s,running:!1,error:""},await this.sessions.applySessionCleanupResult(s,i)}catch(s){f(this.state)===i&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`运行清理失败:${Ht(s)}`})}}renderNavigationPanel(){return l`
2963
+ `}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-zx-Bx);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(Nx).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||Pe(e,we.sessionsDeleteArchived)}canReloadSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&Pe(e,we.sessionsReload)}canCleanupSessions(){const e=this.selectedMachineRuntime();return e?.ok===!0&&Pe(e,we.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return zl(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=f(this.state)){if(e==="local")return!0;const t=this.state.machineRuntimes[e];return t?.ok===!0&&Pe(t,we.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`请更新并重启 ${this.state.selectedMachine?.name??"此机器"} 上的 Pi-Web 后再删除已归档会话。`}sessionCleanupUnavailableMessage(){return Ug(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 yr.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:`预览清理失败:${ii(i)}`})}}async runSessionCleanup(e){const t=this.sessionCleanupDialog;if(t?.preview===void 0||Ut(t.previewRequest)!==Ut(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 yr.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:`运行清理失败:${ii(s)}`})}}renderNavigationPanel(){return l`
2684
2964
  <app-navigation-panel
2685
2965
  .machines=${this.state.machines}
2686
2966
  .selectedMachine=${this.state.selectedMachine}
@@ -2696,16 +2976,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2696
2976
  .workspacesByProjectId=${this.state.workspacesByProjectId}
2697
2977
  .workspaces=${this.state.workspaces}
2698
2978
  .selectedWorkspace=${this.state.selectedWorkspace}
2699
- .deletingWorkspaceIds=${hg(this.state.workspaceDeletionRuns)}
2979
+ .deletingWorkspaceIds=${lm(this.state.workspaceDeletionRuns)}
2700
2980
  .sessions=${this.state.sessions}
2701
2981
  .sessionStatuses=${this.state.sessionStatuses}
2702
2982
  .sessionActivities=${this.state.sessionActivities}
2703
2983
  .sendingPrompts=${this.state.sendingPrompts}
2704
2984
  .selectedSession=${this.state.selectedSession}
2985
+ .startingSessionCount=${this.state.startingSessionCount}
2705
2986
  .canStartSession=${!!this.state.selectedWorkspace}
2706
2987
  .canDeleteArchivedSessions=${this.canDeleteArchivedSessions()}
2707
2988
  .canReloadSessions=${this.canReloadSessions()}
2708
2989
  .canCleanupSessions=${this.canCleanupSessions()}
2990
+ .authoritativeSessionPersistence=${this.hasAuthoritativeSessionPersistence()}
2709
2991
  .archivedDeleteUnavailableMessage=${this.archivedDeleteUnavailableMessage()}
2710
2992
  .cleanupUnavailableMessage=${this.sessionCleanupUnavailableMessage()}
2711
2993
  .collapsible=${!0}
@@ -2724,7 +3006,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2724
3006
  .onSelectWorkspace=${e=>this.selectNavigationItem("workspaces","sessions",()=>this.workspaces.selectWorkspace(e))}
2725
3007
  .onDeleteWorkspace=${e=>{this.deleteWorkspace(e)}}
2726
3008
  .onArchivedCollapsed=${()=>{this.sessions.clearSelectionAfterArchivedCollapse()}}
2727
- .onStartSession=${()=>this.selectNavigationItem("sessions","chat",()=>this.sessions.startSession())}
3009
+ .onStartSession=${()=>this.startSessionFromNavigation()}
2728
3010
  .onSelectSession=${e=>this.selectNavigationItem("sessions","chat",()=>this.sessions.selectSession(e))}
2729
3011
  .onArchiveSession=${e=>this.sessions.archiveSession(e)}
2730
3012
  .onArchiveSessionWithDescendants=${e=>this.sessions.archiveSessionWithDescendants(e)}
@@ -2739,14 +3021,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
2739
3021
  .onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
2740
3022
  .onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
2741
3023
  ></app-navigation-panel>
2742
- `}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){const s=++this.navigationSelectionSeq,r=()=>s===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()},r),r()&&await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!Ji(this.state.machines)){await this.focusNavigationSection("projects");return}this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView("navigation"),this.navigationSections.expand(e),await this.updateComplete,await qs(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await qs(),this.promptEditor?.focusInput()}visibleWorkspacePanels(){const e=this.state.selectedWorkspace;if(e===void 0)return[];const t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(i=>i.visible?.(t)??!0)}workspacePanelEmptyState(){const e=this.state.selectedProject;return this.state.isLoadingProjects?{title:"正在加载项目…",body:"正在查找你已添加到 PI WEB 的项目。"}:e===void 0?this.state.projects.length===0?{title:"还没有项目",body:"使用“操作 → 添加项目”添加文件夹。选择工作区后,工作区工具会显示在这里。"}:{title:"选择项目",body:"从侧边栏选择一个项目,然后选择工作区来查看文件、Git 或终端。"}:this.state.isLoadingWorkspaces?{title:"正在加载工作区…",body:`正在为 ${e.name} 准备工作区工具。`}:this.state.workspaces.length===0?{title:"未找到工作区",body:`${e.name} 没有可用工作区。请尝试重新选择该项目,或重新添加它。`}:{title:"选择工作区",body:`选择 ${e.name} 中的工作区,以查看文件、Git 或终端。`}}sessionEmptyMessage(){return this.state.isLoadingProjects?"正在加载项目…":this.state.selectedWorkspace!==void 0?"选择或启动会话。":this.state.selectedProject!==void 0?"选择工作区以启动会话。":this.state.projects.length===0?"添加项目以启动会话。":"选择项目和工作区以开始会话。"}mobilePanelBadge(e){const t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case"core:workspace.files":return"files";case"core:workspace.git":return"git";case"core:workspace.terminal":return"terminal";default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){const t=fa(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:i=>kt.workspaceFile(e.projectId,e.id,i,t),writeFile:async(i,s,r)=>{const o=await kt.writeWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o},deleteFile:async i=>{const s=await kt.deleteWorkspaceFile(e.projectId,e.id,i,t);return this.files.refreshFiles(),s},moveFile:async(i,s,r)=>{const o=await kt.moveWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=fa(this.state),i=t.id,s=r=>{const o=this.terminalCommandRunsForOrigin(r,i);return mm({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),prompt:this.createPromptEditor(),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>o.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:o},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:Gp(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onCreateFile:n=>{this.files.createFile(n)},onCreateDirectory:n=>{this.files.createDirectory(n)},onMoveSelectedPath:n=>{this.files.moveSelectedPath(n)},onDeleteSelectedPath:()=>{this.files.deleteSelectedPath()},onDownloadSelectedFile:()=>{this.files.downloadSelectedFile()},onExpandDir:n=>{this.files.expandDir(n)},onSelectDirectory:n=>{this.files.selectDirectory(n)},onSelectFile:n=>{this.files.selectFile(n)},onStartWorkspaceUpload:(n,a)=>this.files.startWorkspaceUpload(n,a),onCancelWorkspaceUpload:n=>{this.files.cancelWorkspaceUpload(n)},onClearWorkspaceUpload:n=>{this.files.clearWorkspaceUpload(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return ov(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.normalAuthActions(),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}normalAuthActions(){return this.apiScope==="management"?[]:[{id:"app.normal-auth.change-password",title:"修改普通模式密码",description:"更改进入普通模式所需的本地密码",group:"偏好设置",enabled:this.normalAuthStatus?.authenticated===!0,run:()=>{this.normalAuthDialogMode="change",this.normalAuthError=""}}]}sessionActions(){return[{id:"app.sessions.cleanup",title:"清理会话",description:"预览并手动清理所选机器上的空闲或已归档会话",group:"Sessions",...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"重置导航面板宽度",description:"将导航面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"重置工作区面板宽度",description:"将工作区面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"重置面板宽度",description:"将所有侧边面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"聚焦机器",description:"将键盘焦点移到机器选择器",shortcut:"mod+g m",group:"导航",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"聚焦项目",description:"将键盘焦点移到项目列表",shortcut:"mod+g p",group:"导航",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"聚焦工作区",description:"将键盘焦点移到工作区列表",shortcut:"mod+g w",group:"导航",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"聚焦会话",description:"将键盘焦点移到会话列表",shortcut:"mod+g s",group:"导航",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>Pn())}async loadPluginsForSelectedMachine(){const e=this.state.selectedMachine;e?.kind==="remote"&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!=="remote"||this.loadedMachinePluginIds.has(e.id))return;const t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;const i=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>Pn(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:s=>this.plugins.shouldLoadRemotePlugin(s.id,s.machineSpecific)})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(r){console.warn(`Failed to register PI WEB plugin ${s.id}`,r)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPromptEditor(){return{insertText:e=>{const t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();const i=t.state.selection.main;t.dispatch({changes:{from:i.from,to:i.to,insert:e},selection:{anchor:i.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??"",getSelection:()=>{const e=this.promptEditor?.view;if(!e)return null;const t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){const e=t=>gm({state:this.state,prompt:this.createPromptEditor(),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!bf(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(yl(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
3024
+ `}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 startSessionFromNavigation(){const e=++this.navigationSelectionSeq,t=()=>e===this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection("sessions"),await this.startSessionAndOpenChat(t)}async startSessionAndOpenChat(e=()=>!0){this.sessions.startSession().catch(t=>{e()&&this.setState({error:String(t)})}),e()&&await this.focusChatComposer()}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!vs(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 gr(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await gr(),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=Qa(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=>Lt.workspaceFile(e.projectId,e.id,i,t),writeFile:async(i,s,r)=>{const o=await Lt.writeWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o},deleteFile:async i=>{const s=await Lt.deleteWorkspaceFile(e.projectId,e.id,i,t);return this.files.refreshFiles(),s},moveFile:async(i,s,r)=>{const o=await Lt.moveWorkspaceFile(e.projectId,e.id,i,s,r,t);return this.files.refreshFiles(),o}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=Qa(this.state),i=t.id,s=r=>{const o=this.terminalCommandRunsForOrigin(r,i);return hv({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:zh(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 tb(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.normalAuthActions(),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}normalAuthActions(){return this.apiScope==="management"?[]:[{id:"app.normal-auth.change-password",title:"修改普通模式密码",description:"更改进入普通模式所需的本地密码",group:"偏好设置",enabled:this.normalAuthStatus?.authenticated===!0,run:()=>{this.normalAuthDialogMode="change",this.normalAuthError=""}}]}sessionActions(){return[{id:"app.sessions.cleanup",title:"清理会话",description:"预览并手动清理所选机器上的空闲或已归档会话",group:"Sessions",...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"重置导航面板宽度",description:"将导航面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"重置工作区面板宽度",description:"将工作区面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"重置面板宽度",description:"将所有侧边面板恢复为默认宽度",group:"视图",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"聚焦机器",description:"将键盘焦点移到机器选择器",shortcut:"mod+g m",group:"导航",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"聚焦项目",description:"将键盘焦点移到项目列表",shortcut:"mod+g p",group:"导航",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"聚焦工作区",description:"将键盘焦点移到工作区列表",shortcut:"mod+g w",group:"导航",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"聚焦会话",description:"将键盘焦点移到会话列表",shortcut:"mod+g s",group:"导航",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>Xn())}async loadPluginsForSelectedMachine(){const e=this.state.selectedMachine;e?.kind==="remote"&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!=="remote"||this.loadedMachinePluginIds.has(e.id))return;const t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;const i=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>Xn(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:s=>this.plugins.shouldLoadRemotePlugin(s.id,s.machineSpecific)})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(r){console.warn(`Failed to register PI WEB plugin ${s.id}`,r)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPromptEditor(){return{insertText:e=>{const t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();const i=t.state.selection.main;t.dispatch({changes:{from:i.from,to:i.to,insert:e},selection:{anchor:i.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??"",getSelection:()=>{const e=this.promptEditor?.view;if(!e)return null;const t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){const e=t=>pv({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.startSessionAndOpenChat()),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(!fg(e)){this.setState({error:"Only secondary Git worktrees can be deleted"});return}if(sc(this.state,e))return;const t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?
2743
3025
 
2744
3026
  This will run git worktree remove and delete:
2745
3027
  ${e.path}
2746
3028
 
2747
- The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=await kt.deleteWorkspace(e.projectId,e.id,s);if(f(this.state)!==s)return;this.recordWorkspaceDeletionRun(r,s);const o=await this.workspaceForCommandRun(r);if(f(this.state)!==s)return;o!==void 0&&this.openRuntimeTerminal(s,o,{terminalId:r.terminalId})}catch(r){f(this.state)===s&&this.setState({error:`启动工作区删除失败:${Ht(r)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(i=>i.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(f(this.state)!==t)return;const i=sr(e);i!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[i]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;const e=f(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{const i=await this.terminalCommandRunsForOrigin("core",e).listCommandRuns(dg(t.id));if(f(this.state)!==e)return;const s=pg(i);this.setState({workspaceDeletionRuns:s});for(const r of Object.values(s))zi(r)||await this.handleCompletedWorkspaceDeletionRun(r,e)}catch(i){console.warn("Failed to refresh workspace deletion runs",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(zi);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=f(this.state)){if(f(this.state)!==t)return;const i=va(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=sr(e);if(s!==void 0){if(this.handledWorkspaceDeletionRunIds.add(i),e.status==="succeeded"){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,s),f(this.state)!==t)return;this.setState({workspaceDeletionRuns:px(this.state.workspaceDeletionRuns,s)}),this.updateWorkspaceDeletionPolling();return}e.status==="failed"&&(this.setState({error:"工作区删除失败。请查看终端输出。"}),this.updateWorkspaceDeletionPolling())}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:""})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind==="local"||!window.confirm(`移除 ${e.name}?
3029
+ The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=await Lt.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:`启动工作区删除失败:${ii(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=Pr(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(nm(t.id));if(f(this.state)!==e)return;const s=am(i);this.setState({workspaceDeletionRuns:s});for(const r of Object.values(s))as(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(as);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=Xa(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Pr(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:Zx(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}?
2748
3030
 
2749
- 这只会从当前 PI WEB 网关移除它。`))return;const t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();const i=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(s=>s.id===e.id)||this.machineNavigation.forget(e.id),t&&i!==void 0&&await this.selectMachineWithMemory(i,{rememberCurrent:!1})}openSelectedMachine(){const e=this.state.selectedMachine;e?.kind!=="remote"||e.baseUrl===void 0||window.open(e.baseUrl,"_blank","noopener,noreferrer")}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{const i=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`操作失败:${i}`})})}async openModelDialog(){const e=await this.sessions.listModels(),t=this.state.status?.model?.provider,i=this.state.status?.model?.id;this.setState({modelDialog:{title:"选择模型",...t!==void 0&&i!==void 0?{selectedValue:`${t}/${i}`}:{},options:e.map(s=>{const r=s.provider??"",o=s.id??"",n=r===t&&o===i;return{value:`${r}/${o}`,label:`${o}${n?" ✓ 当前":""}`,description:r}})}})}async pickModel(e){this.setState({modelDialog:void 0});const t=e.indexOf("/");t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){const e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?ua:Bs;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${mi}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开启":"关闭"}`,description:this.autoThemeDescription(t)},...e.map(r=>({value:`${mi}${r.id}`,label:this.themeOptionLabel(r,i),description:this.themeOptionDescription(r)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===Bs||e===ua){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===Bs},this.applyPreferredTheme(!0);return}if(!e.startsWith(mi))return;const t=e.slice(mi.length),i=this.plugins.getThemes().find(s=>s.id===t);i!==void 0&&(this.themePreference={themeId:i.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){const t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,eg(t),e&&Yf(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return tg({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return wl(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?"当所选主题有配对主题时,跟随系统明暗偏好。":e.selectedThemePair===void 0?"已开启,但所选主题没有明暗配对,因此会保持当前主题。":`已开启 · ${e.selectedThemePair.name} 跟随系统${this.systemPrefersLight()?"浅色":"深色"}偏好。`}themeOptionLabel(e,t){const i=[...e.id===t?["已选择"]:[],...e.id===this.activeThemeId&&e.id!==t?["生效中"]:[]];return i.length===0?e.name:`${e.name} ✓ ${i.join(" · ")}`}themeOptionDescription(e){const t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push("自动配对"),e.description!==void 0&&t.push(e.description),t.join(" · ")}async openThinkingDialog(){const e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??"off";this.setState({thinkingDialog:{title:"选择思考级别",selectedValue:t,options:e.map(i=>{const s=hx(i);return{value:i,label:`${i}${i===t?" ✓ 当前":""}`,...s===void 0?{}:{description:s}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==""&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t,i,s){!(i!==void 0&&i.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,i,s)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
3031
+ 这只会从当前 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?Ga:hr;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${Li}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开启":"关闭"}`,description:this.autoThemeDescription(t)},...e.map(r=>({value:`${Li}${r.id}`,label:this.themeOptionLabel(r,i),description:this.themeOptionDescription(r)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===hr||e===Ga){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===hr},this.applyPreferredTheme(!0);return}if(!e.startsWith(Li))return;const t=e.slice(Li.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,Jg(t),e&&Qg(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Zg({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return ic(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=Xx(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`
2750
3032
  <app-context-bar
2751
3033
  .machines=${this.state.machines}
2752
3034
  .machine=${this.state.selectedMachine}
@@ -2767,13 +3049,13 @@ The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=a
2767
3049
  <div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints("navigation"),workspace:this.resizablePanelConstraints("workspace")})}>
2768
3050
  <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
2769
3051
  ${this.renderNavigationPanelEdgeControl()}
2770
- <main class=${Pl(e.mainView)}>
3052
+ <main class=${lc(e.mainView)}>
2771
3053
  ${this.renderContextBar()}
2772
3054
  ${this.renderMobileMainTabs()}
2773
3055
  ${e.error?l`<div class="error">${e.error}</div>`:null}
2774
3056
  <div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
2775
3057
  ${e.selectedSession?l`
2776
- <chat-view .sessionId=${e.selectedSession.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isReceivingPartialStream=${e.isReceivingPartialStream} .isSendingPrompt=${e.sendingPrompts[e.selectedSession.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .status=${e.status} .activity=${e.activity} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
3058
+ <chat-view .sessionId=${e.selectedSession.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isReceivingPartialStream=${e.isReceivingPartialStream} .isSendingPrompt=${e.sendingPrompts[e.selectedSession.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .clientQueuedMessages=${e.clientQueuedSessionMessages[e.selectedSession.id]??[]} .status=${e.status} .activity=${e.activity} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
2777
3059
  <prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${f(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${e.status} .availableThinkingLevels=${e.availableThinkingLevels} .sending=${e.sendingPrompts[e.selectedSession.id]===!0} .onSend=${this.handleSendPrompt} .onStop=${this.handleStopActiveWork} .onSelectModel=${this.handleSelectModel} .onSelectThinking=${this.handleSelectThinking}></prompt-editor>
2778
3060
  <status-bar .status=${e.status}></status-bar>
2779
3061
  ${e.commandDialog!==void 0?l`<command-picker .title=${e.commandDialog.title} .options=${e.commandDialog.options} .onPick=${i=>this.sessions.respondToCommand(e.commandDialog?.requestId??"",i)} .onCancel=${()=>{this.sessions.cancelCommand()}}></command-picker>`:null}
@@ -2789,7 +3071,7 @@ The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=a
2789
3071
  ${e.machineDialogOpen?l`<machine-dialog .error=${e.error} .onSubmit=${i=>this.submitMachineDialog(i)} .onCancel=${()=>{this.setState({machineDialogOpen:!1})}}></machine-dialog>`:null}
2790
3072
  ${this.sessionCleanupDialog!==void 0?l`<session-cleanup-dialog .canCleanup=${this.canCleanupSessions()} .unavailableMessage=${this.sessionCleanupUnavailableMessage()} .preview=${this.sessionCleanupDialog.preview} .previewRequest=${this.sessionCleanupDialog.previewRequest} .result=${this.sessionCleanupDialog.result} .loading=${this.sessionCleanupDialog.loading===!0} .running=${this.sessionCleanupDialog.running===!0} .error=${this.sessionCleanupDialog.error??""} .onPreview=${i=>{this.previewSessionCleanup(i)}} .onRun=${i=>{this.runSessionCleanup(i)}} .onClose=${()=>{this.closeSessionCleanupDialog()}}></session-cleanup-dialog>`:null}
2791
3073
  ${e.themeDialog!==void 0?l`<command-picker title=${e.themeDialog.title} .options=${e.themeDialog.options} .selectedValue=${e.themeDialog.selectedValue} .onPick=${i=>{this.pickTheme(i)}} .onCancel=${()=>{this.setState({themeDialog:void 0})}}></command-picker>`:null}
2792
- ${this.settingsSection!==void 0?l`<settings-dialog .section=${this.settingsSection} .actions=${this.getDefaultActions()} .onNavigate=${i=>{this.navigateSettings(i)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${i=>{this.applyClientConfig(i)}}></settings-dialog>`:null}
3074
+ ${this.settingsSection!==void 0?l`<settings-dialog .section=${this.settingsSection} .machine=${e.selectedMachine} .machineRuntime=${this.selectedMachineRuntime()} .actions=${this.getDefaultActions()} .onNavigate=${i=>{this.navigateSettings(i)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${i=>{this.applyClientConfig(i)}}></settings-dialog>`:null}
2793
3075
  ${this.normalAuthDialogMode==="change"?this.renderNormalAuthDialog("change"):null}
2794
3076
  </div>
2795
3077
  `}renderNormalAuthDialog(e){return l`
@@ -2800,4 +3082,4 @@ The Git branch will not be deleted.`))return;const s=f(this.state);try{const r=a
2800
3082
  .onSubmit=${t=>{this.submitNormalAuth(t)}}
2801
3083
  .onCancel=${()=>{this.normalAuthDialogMode=void 0,this.normalAuthError=""}}
2802
3084
  ></normal-auth-dialog>
2803
- `}};K.styles=X0;Z([w()],K.prototype,"state",2);Z([B("chat-view")],K.prototype,"chatView",2);Z([B("prompt-editor")],K.prototype,"promptEditor",2);Z([B("app-navigation-panel")],K.prototype,"navigationPanel",2);Z([B("#navigation-panel")],K.prototype,"navigationPanelFrame",2);Z([B("#workspace-panel")],K.prototype,"workspacePanelFrame",2);Z([w()],K.prototype,"activeThemeId",2);Z([w()],K.prototype,"isRefreshingApp",2);Z([w()],K.prototype,"sessionCleanupDialog",2);Z([w()],K.prototype,"settingsSection",2);Z([w()],K.prototype,"normalAuthStatus",2);Z([w()],K.prototype,"normalAuthLoading",2);Z([w()],K.prototype,"normalAuthError",2);Z([w()],K.prototype,"normalAuthDialogMode",2);Z([w()],K.prototype,"shortcutConfig",2);Z([w()],K.prototype,"workspaceUploadDefaultFolder",2);K=Z([W("pi-web-app")],K);function rx(){const e=new um;return e.register({id:"core",plugin:Qg}),e.register({id:"themes",plugin:em}),e}function ox(){const e=vl()?"management":"normal";return Zc(e),e}function fa(e){const t=e.selectedMachine;return t!==void 0?{id:t.id,name:t.name,kind:t.kind}:{id:"local",name:"local",kind:"local"}}function nx(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function ax(e,t){return dc(e,t)}function dc(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function lx(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function ga(e){return tt(e.status,e.activity)}function cx(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function ma(){return{}}function va(e,t){return JSON.stringify([e,t])}function dx(e){const t=Math.min(e,ur.length-1);return ur[t]??3e4}function Ht(e){return e instanceof Error?e.message:String(e)}function px(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function qs(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function hx(e){switch(e){case"off":return"不使用推理";case"minimal":return"极简推理(约 1k tokens)";case"low":return"轻量推理(约 2k tokens)";case"medium":return"中等推理(约 8k tokens)";case"high":return"深度推理(约 16k tokens)";case"xhigh":return"最大推理(约 32k tokens)";default:return}}export{D as a,l as b,$t as c,Px as d,kx as e,B as f,R as i,d as n,w as r,$x as s,W as t};
3085
+ `}};Q.styles=_x;ie([v()],Q.prototype,"state",2);ie([q("chat-view")],Q.prototype,"chatView",2);ie([q("prompt-editor")],Q.prototype,"promptEditor",2);ie([q("app-navigation-panel")],Q.prototype,"navigationPanel",2);ie([q("#navigation-panel")],Q.prototype,"navigationPanelFrame",2);ie([q("#workspace-panel")],Q.prototype,"workspacePanelFrame",2);ie([v()],Q.prototype,"activeThemeId",2);ie([v()],Q.prototype,"isRefreshingApp",2);ie([v()],Q.prototype,"sessionCleanupDialog",2);ie([v()],Q.prototype,"settingsSection",2);ie([v()],Q.prototype,"normalAuthStatus",2);ie([v()],Q.prototype,"normalAuthLoading",2);ie([v()],Q.prototype,"normalAuthError",2);ie([v()],Q.prototype,"normalAuthDialogMode",2);ie([v()],Q.prototype,"shortcutConfig",2);ie([v()],Q.prototype,"workspaceUploadDefaultFolder",2);Q=ie([W("pi-web-app")],Q);function qx(){const e=new cv;return e.register({id:"core",plugin:Km}),e.register({id:"themes",plugin:Jm}),e}function Hx(){const e=ec()?"management":"normal";return Bd(e),e}function Qa(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 Kx(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function Vx(e,t){return ed(e,t)}function ed(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function Gx(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function Ja(e){return dt(e.status,e.activity)}function Qx(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function Za(){return{}}function Xa(e,t){return JSON.stringify([e,t])}function Jx(e){const t=Math.min(e,Lr.length-1);return Lr[t]??3e4}function ii(e){return e instanceof Error?e.message:String(e)}function Zx(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function gr(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function Xx(e){switch(e){case"off":return"不使用推理";case"minimal":return"极简推理(约 1k tokens)";case"low":return"轻量推理(约 2k tokens)";case"medium":return"中等推理(约 8k tokens)";case"high":return"深度推理(约 16k tokens)";case"xhigh":return"最大推理(约 32k tokens)";default:return}}export{D as a,l as b,Ot as c,pk as d,ck as e,q as f,I as i,c as n,v as r,dk as s,W as t};