@chainingintention/pi-web-cn 1.202606.3 → 1.202606.5

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 (59) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +364 -364
  3. package/dist/cli.js +32 -32
  4. package/dist/client/assets/{CodeViewer-B4nxYc0g.js → CodeViewer-DRxmEzh1.js} +1 -1
  5. package/dist/client/assets/{TerminalPanel-htr2dU1I.js → TerminalPanel-BcGKwlLZ.js} +1 -1
  6. package/dist/client/assets/{index-BjUH4a8R.js → index-BZE2v69K.js} +149 -141
  7. package/dist/client/favicon.svg +11 -11
  8. package/dist/client/index.html +17 -17
  9. package/dist/client/manifest.webmanifest +24 -24
  10. package/dist/config.js +72 -0
  11. package/dist/config.js.map +1 -1
  12. package/dist/pi-web-plugins/info/package.json +9 -9
  13. package/dist/pi-web-plugins/info/pi-web-plugin.js +14 -14
  14. package/dist/pi-web-plugins/updates/package.json +9 -9
  15. package/dist/pi-web-plugins/updates/pi-web-plugin.js +75 -75
  16. package/dist/pi-web-plugins/workspace-tasks/config.js +1 -1
  17. package/dist/pi-web-plugins/workspace-tasks/package.json +9 -9
  18. package/dist/pi-web-plugins/workspace-tasks/pi-web-plugin.js +10 -10
  19. package/dist/pi-web-plugins/workspace-tasks/taskRunner.js +1 -1
  20. package/dist/pi-web-plugins/workspace-tasks/tasksPanelElement.js +58 -58
  21. package/dist/pi-web-plugins/workspace-tasks/workspaceTasksClient.js +1 -1
  22. package/dist/server/app.js +48 -17
  23. package/dist/server/app.js.map +1 -1
  24. package/dist/server/configRoutes.js +77 -0
  25. package/dist/server/configRoutes.js.map +1 -1
  26. package/dist/server/gitRoutes.js +16 -3
  27. package/dist/server/gitRoutes.js.map +1 -1
  28. package/dist/server/managementEmbed.js +205 -0
  29. package/dist/server/managementEmbed.js.map +1 -0
  30. package/dist/server/sessiond/sessionProxyRoutes.js +66 -8
  31. package/dist/server/sessiond/sessionProxyRoutes.js.map +1 -1
  32. package/dist/server/sessions/managementPermissionSystem.js +94 -0
  33. package/dist/server/sessions/managementPermissionSystem.js.map +1 -0
  34. package/dist/server/sessions/managementSandbox.js +156 -0
  35. package/dist/server/sessions/managementSandbox.js.map +1 -0
  36. package/dist/server/sessions/piSessionService.js +320 -26
  37. package/dist/server/sessions/piSessionService.js.map +1 -1
  38. package/dist/server/sessions/sessionRoutes.js +9 -4
  39. package/dist/server/sessions/sessionRoutes.js.map +1 -1
  40. package/dist/server/terminalProxyRoutes.js +54 -8
  41. package/dist/server/terminalProxyRoutes.js.map +1 -1
  42. package/dist/server/terminals/terminalRoutes.js +12 -3
  43. package/dist/server/terminals/terminalRoutes.js.map +1 -1
  44. package/dist/server/terminals/terminalService.js +48 -4
  45. package/dist/server/terminals/terminalService.js.map +1 -1
  46. package/dist/server/workspaceExplorerRoutes.js +17 -4
  47. package/dist/server/workspaceExplorerRoutes.js.map +1 -1
  48. package/dist/server/workspaces/pathSafety.js +9 -2
  49. package/dist/server/workspaces/pathSafety.js.map +1 -1
  50. package/dist/sessiond/sessionDaemonClient.js +12 -12
  51. package/dist/sessiond/sessionDaemonClient.js.map +1 -1
  52. package/dist/shared/apiTypes.d.ts +18 -0
  53. package/docs/assets/favicon.svg +11 -11
  54. package/docs/plugins.md +762 -762
  55. package/extensions/pi-web.ts +133 -133
  56. package/install.sh +5 -5
  57. package/package.json +127 -127
  58. package/plugin-api/unstable.d.ts +1 -1
  59. package/plugin-api.d.ts +1 -1
@@ -1,23 +1,23 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-B4nxYc0g.js","assets/vendor-editor-core-B4Sq6exx.js","assets/vendor-editor-languages-DznYbTkJ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-htr2dU1I.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
- import{Q as _s,w as Ge,J as yi,R as yn,S as xn,G as Sn,U as kn,V as $n,A as Pn,W as Tn,X as Cn,Y as In,Z as Os,x as Ls,_ as Mn}from"./vendor-editor-core-B4Sq6exx.js";import{m as An,i as Rn,d as En}from"./vendor-editor-languages-DznYbTkJ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const n of o.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=i(r);fetch(r.href,o)}})();const Bt=globalThis,es=Bt.ShadowRoot&&(Bt.ShadyCSS===void 0||Bt.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,ts=Symbol(),Ws=new WeakMap;let eo=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==ts)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(es&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=Ws.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&Ws.set(i,t))}return t}toString(){return this.cssText}};const Dn=e=>new eo(typeof e=="string"?e:e+"",void 0,ts),E=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,r,o)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+e[o+1],e[0]);return new eo(i,e,ts)},_n=(e,t)=>{if(es)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),r=Bt.litNonce;r!==void 0&&s.setAttribute("nonce",r),s.textContent=i.cssText,e.appendChild(s)}},js=es?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return Dn(i)})(e):e;const{is:On,defineProperty:Ln,getOwnPropertyDescriptor:Wn,getOwnPropertyNames:jn,getOwnPropertySymbols:Nn,getPrototypeOf:Bn}=Object,ci=globalThis,Ns=ci.trustedTypes,Fn=Ns?Ns.emptyScript:"",zn=ci.reactiveElementPolyfillSupport,mt=(e,t)=>e,Kt={toAttribute(e,t){switch(t){case Boolean:e=e?Fn: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}},is=(e,t)=>!On(e,t),Bs={attribute:!0,type:String,converter:Kt,reflect:!1,useDefault:!1,hasChanged:is};Symbol.metadata??=Symbol("metadata"),ci.litPropertyMetadata??=new WeakMap;let Ze=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=Bs){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&&Ln(this.prototype,t,r)}}static getPropertyDescriptor(t,i,s){const{get:r,set:o}=Wn(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)??Bs}static _$Ei(){if(this.hasOwnProperty(mt("elementProperties")))return;const t=Bn(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(mt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(mt("properties"))){const i=this.properties,s=[...jn(i),...Nn(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(js(r))}else t!==void 0&&i.push(js(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 _n(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:Kt).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:Kt;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??is)(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){}};Ze.elementStyles=[],Ze.shadowRootOptions={mode:"open"},Ze[mt("elementProperties")]=new Map,Ze[mt("finalized")]=new Map,zn?.({ReactiveElement:Ze}),(ci.reactiveElementVersions??=[]).push("2.1.2");const ss=globalThis,Fs=e=>e,Gt=ss.trustedTypes,zs=Gt?Gt.createPolicy("lit-html",{createHTML:e=>e}):void 0,to="$lit$",Ae=`lit$${Math.random().toFixed(9).slice(2)}$`,io="?"+Ae,Un=`<${io}>`,je=document,vt=()=>je.createComment(""),bt=e=>e===null||typeof e!="object"&&typeof e!="function",rs=Array.isArray,Hn=e=>rs(e)||typeof e?.[Symbol.iterator]=="function",xi=`[
3
- \f\r]`,at=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Us=/-->/g,Hs=/>/g,De=RegExp(`>|${xi}(?:([^\\s"'>=/]+)(${xi}*=${xi}*(?:[^
4
- \f\r"'\`<>=]|("|')|))|$)`,"g"),qs=/'/g,Vs=/"/g,so=/^(?:script|style|textarea|title)$/i,ro=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=ro(1),Xe=ro(2),Re=Symbol.for("lit-noChange"),j=Symbol.for("lit-nothing"),Ks=new WeakMap,Le=je.createTreeWalker(je,129);function oo(e,t){if(!rs(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return zs!==void 0?zs.createHTML(t):t}const qn=(e,t)=>{const i=e.length-1,s=[];let r,o=t===2?"<svg>":t===3?"<math>":"",n=at;for(let a=0;a<i;a++){const c=e[a];let p,f,h=-1,u=0;for(;u<c.length&&(n.lastIndex=u,f=n.exec(c),f!==null);)u=n.lastIndex,n===at?f[1]==="!--"?n=Us:f[1]!==void 0?n=Hs:f[2]!==void 0?(so.test(f[2])&&(r=RegExp("</"+f[2],"g")),n=De):f[3]!==void 0&&(n=De):n===De?f[0]===">"?(n=r??at,h=-1):f[1]===void 0?h=-2:(h=n.lastIndex-f[2].length,p=f[1],n=f[3]===void 0?De:f[3]==='"'?Vs:qs):n===Vs||n===qs?n=De:n===Us||n===Hs?n=at:(n=De,r=void 0);const v=n===De&&e[a+1].startsWith("/>")?" ":"";o+=n===at?c+Un:h>=0?(s.push(p),c.slice(0,h)+to+c.slice(h)+Ae+v):c+Ae+(h===-2?a:v)}return[oo(e,o+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class wt{constructor({strings:t,_$litType$:i},s){let r;this.parts=[];let o=0,n=0;const a=t.length-1,c=this.parts,[p,f]=qn(t,i);if(this.el=wt.createElement(p,s),Le.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(r=Le.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const h of r.getAttributeNames())if(h.endsWith(to)){const u=f[n++],v=r.getAttribute(h).split(Ae),S=/([.?@])?(.*)/.exec(u);c.push({type:1,index:o,name:S[2],strings:v,ctor:S[1]==="."?Kn:S[1]==="?"?Gn:S[1]==="@"?Jn:di}),r.removeAttribute(h)}else h.startsWith(Ae)&&(c.push({type:6,index:o}),r.removeAttribute(h));if(so.test(r.tagName)){const h=r.textContent.split(Ae),u=h.length-1;if(u>0){r.textContent=Gt?Gt.emptyScript:"";for(let v=0;v<u;v++)r.append(h[v],vt()),Le.nextNode(),c.push({type:2,index:++o});r.append(h[u],vt())}}}else if(r.nodeType===8)if(r.data===io)c.push({type:2,index:o});else{let h=-1;for(;(h=r.data.indexOf(Ae,h+1))!==-1;)c.push({type:7,index:o}),h+=Ae.length-1}o++}}static createElement(t,i){const s=je.createElement("template");return s.innerHTML=t,s}}function et(e,t,i=e,s){if(t===Re)return t;let r=s!==void 0?i._$Co?.[s]:i._$Cl;const o=bt(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=et(e,r._$AS(e,t.values),r,s)),t}class Vn{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??je).importNode(i,!0);Le.currentNode=r;let o=Le.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new it(o,o.nextSibling,this,t):c.type===1?p=new c.ctor(o,c.name,c.strings,this,t):c.type===6&&(p=new Qn(o,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(o=Le.nextNode(),n++)}return Le.currentNode=je,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 it{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,r){this.type=2,this._$AH=j,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=et(this,t,i),bt(t)?t===j||t==null||t===""?(this._$AH!==j&&this._$AR(),this._$AH=j):t!==this._$AH&&t!==Re&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Hn(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!==j&&bt(this._$AH)?this._$AA.nextSibling.data=t:this.T(je.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,r=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=wt.createElement(oo(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(i);else{const o=new Vn(r,this),n=o.u(this.options);o.p(i),this.T(n),this._$AH=o}}_$AC(t){let i=Ks.get(t.strings);return i===void 0&&Ks.set(t.strings,i=new wt(t)),i}k(t){rs(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 it(this.O(vt()),this.O(vt()),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=Fs(t).nextSibling;Fs(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let di=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,r,o){this.type=1,this._$AH=j,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=j}_$AI(t,i=this,s,r){const o=this.strings;let n=!1;if(o===void 0)t=et(this,t,i,0),n=!bt(t)||t!==this._$AH&&t!==Re,n&&(this._$AH=t);else{const a=t;let c,p;for(t=o[0],c=0;c<o.length-1;c++)p=et(this,a[s+c],i,c),p===Re&&(p=this._$AH[c]),n||=!bt(p)||p!==this._$AH[c],p===j?t=j:t!==j&&(t+=(p??"")+o[c+1]),this._$AH[c]=p}n&&!r&&this.j(t)}j(t){t===j?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Kn=class extends di{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===j?void 0:t}},Gn=class extends di{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==j)}},Jn=class extends di{constructor(t,i,s,r,o){super(t,i,s,r,o),this.type=5}_$AI(t,i=this){if((t=et(this,t,i,0)??j)===Re)return;const s=this._$AH,r=t===j&&s!==j||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,o=t!==j&&(s===j||r);r&&this.element.removeEventListener(this.name,this,s),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}};class Qn{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){et(this,t)}}const Zn={I:it},Xn=ss.litHtmlPolyfillSupport;Xn?.(wt,it),(ss.litHtmlVersions??=[]).push("3.3.2");const Yn=(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 it(t.insertBefore(vt(),o),o,void 0,i??{})}return r._$AI(e),r};const os=globalThis;let I=class extends Ze{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=Yn(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Re}};I._$litElement$=!0,I.finalized=!0,os.litElementHydrateSupport?.({LitElement:I});const ea=os.litElementPolyfillSupport;ea?.({LitElement:I});(os.litElementVersions??=[]).push("4.2.2");const A=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const ta={attribute:!0,type:String,converter:Kt,reflect:!1,hasChanged:is},ia=(e=ta,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"?ia(e,t,i):((s,r,o)=>{const n=r.hasOwnProperty(o);return r.constructor.createProperty(o,s),n?Object.getOwnPropertyDescriptor(r,o):void 0})(e,t,i)}function x(e){return d({...e,state:!0,attribute:!1})}const sa=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function re(e,t){return(i,s,r)=>{const o=n=>n.renderRoot?.querySelector(e)??null;return sa(i,s,{get(){return o(this)}})}}async function y(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const r=await fetch(e,{...i,headers:s});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(ra(n)??r.statusText)}const o=await r.json();return t(o)}function ra(e){if(oa(e))return typeof e.error=="string"?e.error:void 0}function oa(e){return typeof e=="object"&&e!==null}function gt(e){return typeof e=="object"&&e!==null}function w(e){if(!gt(e))throw new Error("Expected object response");return e}function g(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function k(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 Y(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function R(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function W(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function na(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function aa(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function la(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=w(e);return{messages:na(t.messages),start:Y(t,"start"),total:Y(t,"total")}}function ca(e){const t=w(e);return W(no)(t.machines)}function no(e){const t=w(e),i=pa(t,"kind"),s=k(t,"baseUrl"),r=ao(t,"status"),o=k(t,"statusMessage");return{id:g(t,"id"),name:g(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:g(t,"createdAt"),updatedAt:g(t,"updatedAt"),...r===void 0?{}:{status:r},...o===void 0?{}:{statusMessage:o}}}function da(e){const t=w(e),i=ao(t,"status"),s=k(t,"error");return{machineId:g(t,"machineId"),ok:R(t,"ok"),checkedAt:g(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:Jt(t.web)},...t.sessiond===void 0?{}:{sessiond:Jt(t.sessiond)},...s===void 0?{}:{error:s}}}function pa(e,t){const i=g(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function ao(e,t){const i=k(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 Gs(e){const t=w(e);return{id:g(t,"id"),name:g(t,"name"),path:g(t,"path"),createdAt:g(t,"createdAt")}}function ha(e){const t=w(e),i=k(t,"branch");return{id:g(t,"id"),projectId:g(t,"projectId"),path:g(t,"path"),label:g(t,"label"),...i===void 0?{}:{branch:i},isMain:R(t,"isMain"),isGitRepo:R(t,"isGitRepo"),isGitWorktree:R(t,"isGitWorktree")}}function Fi(e){const t=w(e),i=k(t,"name"),s=k(t,"parentSessionPath"),r=k(t,"archivedAt");return{id:g(t,"id"),path:g(t,"path"),cwd:g(t,"cwd"),...i===void 0?{}:{name:i},created:g(t,"created"),modified:g(t,"modified"),messageCount:Y(t,"messageCount"),firstMessage:g(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...r===void 0?{}:{archivedAt:r}}}function lt(e){const t=w(e);return{sessionId:g(t,"sessionId"),isStreaming:R(t,"isStreaming"),isCompacting:R(t,"isCompacting"),isBashRunning:R(t,"isBashRunning"),pendingMessageCount:Y(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:W(ua)(t.queuedMessages),...b("messageCount",be(t,"messageCount")),tokens:fa(t.tokens),cost:Y(t,"cost"),...ma(t.model),...Ia(t.contextUsage),...b("thinkingLevel",k(t,"thinkingLevel"))}}function ua(e){const t=w(e),i=g(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:g(t,"text")}}function fa(e){const t=w(e);return{input:Y(t,"input"),output:Y(t,"output"),cacheRead:Y(t,"cacheRead"),cacheWrite:Y(t,"cacheWrite"),total:Y(t,"total")}}function lo(e){const t=w(e);return{...b("provider",k(t,"provider")),...b("id",k(t,"id")),...b("name",k(t,"name")),...b("contextWindow",be(t,"contextWindow")),...b("reasoning",t.reasoning)}}function ma(e){return e===void 0?{}:{model:lo(e)}}function ga(e){const t=w(e);return{models:W(lo)(t.models)}}function va(e){if(e!=="off"&&e!=="minimal"&&e!=="low"&&e!=="medium"&&e!=="high"&&e!=="xhigh")throw new Error("Invalid thinking level");return e}function ba(e){const t=w(e);return{levels:W(va)(t.levels)}}function wa(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function ya(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 xa(e){const t=w(e),i=t.source===void 0?void 0:ya(t.source);return{configured:R(t,"configured"),...b("source",i),...b("label",k(t,"label"))}}function Sa(e){const t=w(e);return{id:g(t,"id"),name:g(t,"name"),authType:wa(t.authType),status:xa(t.status)}}function ka(e){const t=w(e);return{providers:W(Sa)(t.providers)}}function Rt(e){const t=w(e);return{flowId:g(t,"flowId"),providerId:g(t,"providerId"),providerName:g(t,"providerName"),status:$a(t.status),progress:W(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...b("error",k(t,"error")),...b("auth",Pa(t.auth)),...b("prompt",Ta(t.prompt)),...b("select",Ca(t.select))}}function $a(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Pa(e){if(e===void 0)return;const t=w(e);return{url:g(t,"url"),...b("instructions",k(t,"instructions"))}}function Ta(e){if(e===void 0)return;const t=w(e),i=g(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:g(t,"requestId"),message:g(t,"message"),kind:i,...b("placeholder",k(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function Ca(e){if(e===void 0)return;const t=w(e);return{requestId:g(t,"requestId"),message:g(t,"message"),options:W(po)(t.options)}}function Ia(e){if(e===void 0)return{};const t=w(e);return{contextUsage:{tokens:er(t,"tokens"),contextWindow:Y(t,"contextWindow"),percent:er(t,"percent")}}}function Ma(e){const t=w(e),i=g(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:g(t,"name"),source:i,...b("description",k(t,"description"))}}function co(e){const t=w(e),i=g(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:g(t,"path"),kind:i}}function Aa(e){const t=w(e);return{path:g(t,"path"),entries:W(Ra)(t.entries),scannedAt:g(t,"scannedAt"),truncated:R(t,"truncated")}}function Ra(e){const t=w(e),i=g(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:g(t,"name"),path:g(t,"path"),type:i,...b("size",be(t,"size")),...b("modifiedAt",k(t,"modifiedAt"))}}function Ea(e){const t=w(e),i=g(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:g(t,"path"),...b("language",k(t,"language")),...b("mediaType",Da(t.mediaType)),...b("mimeType",k(t,"mimeType")),encoding:i,size:Y(t,"size"),modifiedAt:g(t,"modifiedAt"),content:g(t,"content"),truncated:R(t,"truncated"),binary:R(t,"binary")}}function Da(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function _a(e){const t=w(e);return{isGitRepo:R(t,"isGitRepo"),hash:g(t,"hash"),...b("branch",k(t,"branch")),...b("upstream",k(t,"upstream")),...b("ahead",be(t,"ahead")),...b("behind",be(t,"behind")),files:W(Oa)(t.files)}}function Oa(e){const t=w(e);return{path:g(t,"path"),...b("oldPath",k(t,"oldPath")),index:Js(t.index),workingTree:Js(t.workingTree)}}function Js(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 La(e){const t=w(e);return{...b("path",k(t,"path")),staged:R(t,"staged"),hash:g(t,"hash"),diff:g(t,"diff"),truncated:R(t,"truncated")}}function Si(e){const t=w(e);return{id:g(t,"id"),cwd:g(t,"cwd"),name:g(t,"name"),createdAt:g(t,"createdAt"),exited:R(t,"exited"),...b("exitCode",be(t,"exitCode")),...b("commandRunId",k(t,"commandRunId"))}}function Ft(e){const t=w(e);return{id:g(t,"id"),origin:g(t,"origin"),projectId:g(t,"projectId"),workspaceId:g(t,"workspaceId"),terminalId:g(t,"terminalId"),title:g(t,"title"),command:g(t,"command"),status:Wa(t.status),...b("exitCode",be(t,"exitCode")),createdAt:g(t,"createdAt"),...b("startedAt",k(t,"startedAt")),...b("completedAt",k(t,"completedAt")),metadata:ja(t.metadata,"metadata")}}function Wa(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function ja(e,t){const i=w(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 Na(e){const t=w(e);return{cwd:g(t,"cwd"),hasSessionActivity:R(t,"hasSessionActivity"),hasTerminalActivity:R(t,"hasTerminalActivity"),updatedAt:g(t,"updatedAt")}}function Ba(e){const t=w(e);return{workspaces:W(Na)(t.workspaces),generatedAt:g(t,"generatedAt")}}function Qs(e){const t=w(e);return{path:g(t,"path"),exists:R(t,"exists"),config:Zs(t.config),effectiveConfig:Zs(t.effectiveConfig),envOverrides:Ha(t.envOverrides)}}function Zs(e){const t=w(e);return{...b("host",k(t,"host")),...b("port",be(t,"port")),...b("allowedHosts",Fa(t.allowedHosts)),...b("shortcuts",za(t.shortcuts)),...b("plugins",Ua(t.plugins))}}function Fa(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 za(e){if(e!==void 0){if(!gt(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 Ua(e){if(e!==void 0){if(!gt(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!gt(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&&(!gt(r)||Array.isArray(r)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Ha(e){const t=w(e);return{host:R(t,"host"),port:R(t,"port"),allowedHosts:R(t,"allowedHosts")}}function qa(e){const t=w(e);return{plugins:W(Va)(t.plugins)}}function Va(e){const t=w(e);return{id:g(t,"id"),module:g(t,"module"),source:g(t,"source"),scope:Ka(t.scope),enabled:R(t,"enabled")}}function Ka(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function Ga(e){const t=w(e);return{packageName:g(t,"packageName"),generatedAt:g(t,"generatedAt"),components:Ja(t.components),release:Za(t.release),commands:Xa(t.commands),messages:W(Ya)(t.messages)}}function Ja(e){const t=w(e);return{web:Jt(t.web),sessiond:Jt(t.sessiond)}}function Jt(e){const t=w(e);return{component:el(t.component),label:g(t,"label"),...b("runtimeVersion",k(t,"runtimeVersion")),...b("installedVersion",k(t,"installedVersion")),stale:R(t,"stale"),available:R(t,"available"),...b("installation",Qa(t.installation)),...b("error",k(t,"error"))}}function Qa(e){if(e===void 0)return;const t=w(e),i=g(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",k(t,"path")),...b("source",k(t,"source")),...s===void 0?{}:{scope:s},...b("npmRoot",k(t,"npmRoot"))}}function Za(e){const t=w(e);return{packageName:g(t,"packageName"),...b("latestVersion",k(t,"latestVersion")),updateAvailable:R(t,"updateAvailable"),...b("checkedAt",k(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...b("error",k(t,"error"))}}function Xa(e){const t=w(e);return{...b("update",k(t,"update")),...b("restart",k(t,"restart")),...b("restartWeb",k(t,"restartWeb")),...b("restartSessiond",k(t,"restartSessiond")),...b("status",k(t,"status"))}}function Ya(e){const t=w(e);return{id:g(t,"id"),severity:tl(t.severity),title:g(t,"title"),body:g(t,"body"),...b("command",k(t,"command"))}}function el(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function tl(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Xs(e){const t=w(e),i=g(t,"type");if(i==="unsupported")return{type:i,message:g(t,"message")};if(i==="select")return{type:i,requestId:g(t,"requestId"),title:g(t,"title"),options:W(po)(t.options)};if(i==="done")return{type:i,...b("message",k(t,"message")),...il(t.session),...b("promptDraft",k(t,"promptDraft"))};throw new Error("Invalid command result type")}function po(e){const t=w(e);return{value:g(t,"value"),label:g(t,"label"),...b("description",k(t,"description"))}}function il(e){return e===void 0?{}:{session:Fi(e)}}function Et(e){if(w(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function ho(e){if(w(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function sl(e){if(w(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function rl(e){if(w(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Ys(e){const t=w(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:aa(t.sessionIds,"sessionIds"),s=be(t,"archivedCount"),r=be(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...r===void 0?{}:{skippedAlreadyArchivedCount:r}}}function ol(e){if(w(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function nl(e){if(w(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function be(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 er(e,t){const i=e[t];if(i===null)return null;if(typeof i!="number")throw new Error(`Expected number|null field: ${t}`);return i}function b(e,t){return t===void 0?{}:{[e]:t}}function al(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 ll(e,t,i="local"){const s=new URLSearchParams;t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const r=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${e}/messages${r?`?${r}`:""}`}function cl(e,t,i,s){const r=new URLSearchParams;return r.set("path",i),s?.modifiedAt!==void 0&&r.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${r.toString()}`}const $=(e="local")=>`/api/machines/${encodeURIComponent(e)}`,uo={piWebStatus:()=>y("/api/pi-web/status",Ga)},dl={machines:()=>y("/api/machines",ca),addMachine:e=>y("/api/machines",no,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>y(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>y(`/api/machines/${encodeURIComponent(e)}/health`,da)},Qt={config:()=>y("/api/config",Qs),saveConfig:e=>y("/api/config",Qs,{method:"PUT",body:JSON.stringify({config:e})})},zi={plugins:()=>y("/api/plugins",qa)},fo={workspaceActivity:(e="local")=>y(`${$(e)}/activity`,Ba)},pl={projects:(e="local")=>y(`${$(e)}/projects`,W(Gs)),addProject:(e,t,i,s="local")=>y(`${$(s)}/projects`,Gs,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>y(`${$(t)}/projects/${encodeURIComponent(e)}`,ho,{method:"DELETE"}),projectDirectories:(e,t="local")=>y(`${$(t)}/project-directories?q=${encodeURIComponent(e)}`,W(co))},mo={workspaces:(e,t="local")=>y(`${$(t)}/projects/${e}/workspaces`,W(ha)),workspaceTree:(e,t,i="",s="local")=>y(`${$(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Aa),workspaceFile:(e,t,i,s="local")=>y(`${$(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Ea)},hl={sessions:(e,t="local")=>y(`${$(t)}/sessions?cwd=${encodeURIComponent(e)}`,W(Fi)),startSession:(e,t="local")=>y(`${$(t)}/sessions`,Fi,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>y(ll(e,t,i),la),status:(e,t="local")=>y(`${$(t)}/sessions/${e}/status`,lt),models:(e,t="local")=>y(`${$(t)}/sessions/${e}/models`,ga),setModel:(e,t,i,s="local")=>y(`${$(s)}/sessions/${e}/model`,lt,{method:"POST",body:JSON.stringify({provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>y(`${$(i)}/sessions/${e}/model/cycle`,lt,{method:"POST",body:JSON.stringify({direction:t})}),thinkingLevels:(e,t="local")=>y(`${$(t)}/sessions/${e}/thinking-levels`,ba),setThinkingLevel:(e,t,i="local")=>y(`${$(i)}/sessions/${e}/thinking-level`,lt,{method:"POST",body:JSON.stringify({level:t})}),cycleThinkingLevel:(e,t="local")=>y(`${$(t)}/sessions/${e}/thinking-level/cycle`,lt,{method:"POST"}),commands:(e,t="local")=>y(`${$(t)}/sessions/${e}/commands`,W(Ma)),prompt:(e,t,i,s="local")=>y(`${$(s)}/sessions/${e}/prompt`,Et,{method:"POST",body:JSON.stringify(i===void 0?{text:t}:{text:t,streamingBehavior:i})}),shell:(e,t,i="local")=>y(`${$(i)}/sessions/${e}/shell`,Et,{method:"POST",body:JSON.stringify({text:t})}),runCommand:(e,t,i="local")=>y(`${$(i)}/sessions/${e}/commands/run`,Xs,{method:"POST",body:JSON.stringify({text:t})}),respondToCommand:(e,t,i,s="local")=>y(`${$(s)}/sessions/${e}/commands/respond`,Xs,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),abort:(e,t="local")=>y(`${$(t)}/sessions/${e}/abort`,sl,{method:"POST"}),stop:(e,t="local")=>y(`${$(t)}/sessions/${e}/stop`,rl,{method:"POST"}),archive:(e,t="local")=>y(`${$(t)}/sessions/${e}/archive`,Ys,{method:"POST"}),archiveWithDescendants:(e,t="local")=>y(`${$(t)}/sessions/${e}/archive-tree`,Ys,{method:"POST"}),restore:(e,t="local")=>y(`${$(t)}/sessions/${e}/restore`,ol,{method:"POST"}),detachParent:(e,t="local")=>y(`${$(t)}/sessions/${e}/detach-parent`,nl,{method:"POST"}),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 y(`${$(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,ka)},saveApiKey:(e,t,i="local")=>y(`${$(i)}/auth/api-key`,Et,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>y(`${$(t)}/auth/logout`,Et,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>y(`${$(t)}/auth/oauth`,Rt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>y(`${$(t)}/auth/oauth/${encodeURIComponent(e)}`,Rt),respondOAuthFlow:(e,t,i,s="local")=>y(`${$(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Rt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>y(`${$(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Rt,{method:"POST"})},Ye={terminals:(e,t,i="local")=>y(`${$(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,W(Si)),startTerminal:(e,t,i,s="local")=>y(`${$(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Si,{method:"POST",body:JSON.stringify(i??{})}),closeTerminal:(e,t,i,s="local")=>y(`${$(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,ho,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>y(`${$(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Si,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>y(`${$(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Ft,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>y(`${$(t)}/terminal-command-runs${fl(e)}`,W(Ft)),getCommandRun:(e,t="local")=>ul(e,t),cancelCommandRun:(e,t="local")=>y(`${$(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Ft,{method:"POST"})};async function ul(e,t){const i=await fetch(`${$(t)}/terminal-command-runs/${encodeURIComponent(e)}`);if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(ml(s)??i.statusText)}return Ft(await i.json())}}function fl(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 ml(e){if(!gl(e))return;const t=e.error;return typeof t=="string"?t:void 0}function gl(e){return typeof e=="object"&&e!==null}const vl={files:(e,t,i={})=>{const s=new URLSearchParams({cwd:e,q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),y(`${$(i.machineId)}/files?${s.toString()}`,W(co))}},bl={gitStatus:(e,t,i="local")=>y(`${$(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,_a),gitDiff:(e,t,i,s="local")=>y(al(s,e,t,i),La)},_={...uo,...dl,...Qt,...zi,...fo,...pl,...mo,...hl,...Ye,...vl,...bl};function wl(e,t="local"){return new WebSocket(`${as()}${ns(t)}/sessions/${e}/events`)}function hg(e,t,i,s,r="local"){const o=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(`${as()}${ns(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${o}`)}function yl(e="local"){return new WebSocket(`${as()}${ns(e)}/events`)}function ns(e){return`/api/machines/${encodeURIComponent(e)}`}function as(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function zt(){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 xl(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function pi(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function go(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const vo="local";function ki(e,t){return`${e}:${t}`}function bo(e,t){return`${e}:${t}`}function m(e){return e.selectedMachine?.id??vo}class Sl{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??fo}async refresh(t=m(this.getState())){this.applyMachineActivitySnapshot(t,kl(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=m(this.getState())){const s=this.getState(),r=m(s)===i,o=s.machineActivities[i]??(r?s.workspaceActivities:{}),n=$l(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},...m(s)===t?{workspaceActivities:i}:{}})}}function kl(e){const t={};for(const i of e.workspaces)go(i)&&(t[i.cwd]=i);return t}function $l(e,t){const i={...e};return go(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class Pl{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=r.api??_,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=Tl(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:m(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,m(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:m(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,m(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,m(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,m(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:m(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,m(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,m(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.sessionId();if(t!==void 0)try{this.applyStatus(await this.api.status(t,m(this.getState())))}catch{}}sessionId(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t.id}}function Tl(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 St(e){return e.replaceAll(":",".")}function Cl(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 $i(e,t){const i=Cl(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function pe(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));Il(r,s)}function Il(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}const tr=St("core:workspace.files");class Ml{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=m(this.getState()),r=await _.workspaceTree(t.id,i.id,"",s),o={...this.getState().expandedDirs};await Promise.all(Object.keys(o).map(async n=>{o[n]=(await _.workspaceTree(t.id,i.id,n,s)).entries})),this.setState({fileTree:r.entries,expandedDirs:o,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:Rl(this.getState().expandedDirs,t)});return}try{const r=await _.workspaceTree(i.id,s.id,t,m(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"}),pe(tr,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}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 _.workspaceFile(i.id,s.id,t,m(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:r,error:""})}catch(r){if(this.getState().selectedFilePath!==t)return;if(Al(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),pe(tr,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}}function Al(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function Rl(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}const ir=St("core:workspace.git");class El{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 _.gitStatus(t.id,i.id,m(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}),pe(ir,"diff",void 0,{replace:!0})))}catch(s){this.setState({error:String(s)})}}async selectDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),pe(ir,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[r,o]=await Promise.all([_.gitDiff(i.id,s.id,{path:t},m(this.getState())),_.gitDiff(i.id,s.id,{path:t,staged:!0},m(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 Dl{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 _.machines(),s=await this.selectInitialMachine(i,t),r=new Set(i.map(o=>o.id));this.setState({machines:i,selectedMachine:s,machineActivities:_l(this.getState().machineActivities,r)}),this.refreshMachineHealthFor(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:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...zt()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id))}async addMachine(t){this.setState({error:""});try{const i=await _.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 _.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:sr(this.getState().machineStatuses,t.id),machineActivities:sr(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 _.health(t);this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(n=>n.id===(i??"local"));if(s?.kind!=="remote")return s??this.localMachine(t);const r=await this.safeRemoteHealth(s);if(r.ok)return s;const o=this.localMachine(t);return this.setState({error:`${s.name} is offline; showing ${o?.name??"another machine"} instead.`,machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r}}),o??s}async safeRemoteHealth(t){try{return await _.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=>_.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}})}}function sr(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function _l(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class Ol{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=m(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await _.projects(t);if(m(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){m(this.getState())===t&&this.setState({error:String(i)})}finally{m(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await _.addProject(t.trim(),void 0,i,m(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 _.closeProject(t,m(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 Ui="pi-web:cached-new-sessions:v1",Ll="browserCachedNew",st="local";function kt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function rr(e,t=st,i=kt()){if(e.messageCount!==0||e.archived===!0)return;const s=ls(i).filter(r=>r.id!==e.id||r.machineId!==t);cs([Hi(e,t),...s],i)}function Hi(e,t=st){return{...e,browserCachedNew:!0,machineId:t}}function or(e,t=st,i=kt()){const s=ls(i).filter(r=>r.id!==e||r.machineId!==t);cs(s,i)}function Wl(e,t,i=st,s=kt()){const r=new Set(t.map(c=>c.id)),o=ls(s),n=o.filter(c=>c.machineId!==i||!r.has(c.id));return n.length!==o.length&&cs(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function ke(e){return e===void 0?!1:Bl(e)&&e.browserCachedNew===!0}function jl(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:st},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function ls(e=kt()){try{const t=e?.getItem(Ui);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>Nl(s)):[]}catch{return[]}}function cs(e,t=kt()){try{e.length===0?t?.removeItem(Ui):t?.setItem(Ui,JSON.stringify(e))}catch{}}function Nl(e){if(!Fl(e))return[];const t=Je(e,"id"),i=Je(e,"path"),s=Je(e,"cwd"),r=Je(e,"created"),o=Je(e,"modified"),n=Je(e,"firstMessage"),a=zl(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=Pi(e,"name"),p=Pi(e,"parentSessionPath"),f=Pi(e,"machineId")??st;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:f,browserCachedNew:!0}]}function Bl(e){return Ll in e}function Fl(e){return typeof e=="object"&&e!==null}function Je(e,t){const i=e[t];return typeof i=="string"?i:void 0}function Pi(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function zl(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Ul(e){return rc(e.flatMap(ds)).filter(t=>t.parts.length>0)}function ve(e,t){return{role:e,parts:[{type:"text",text:t}]}}function Dt(e,t){const i=Ql(t);return i===void 0?e:{...e,meta:i}}function Hl(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,ve(t,i)]}function ql(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 ds(e){if(Vl(e))return[e];if(D(e,"role")==="bashExecution")return[Dt(Yl(e),e)];const t=ec(D(e,"role")),i=tc(ee(e,"content"),e),s=t==="user"?Kl(i):void 0;if(s!==void 0)return s.map(a=>Dt(a,e));const r=Jl(e);if(t==="tool")return[Dt({role:t,parts:i,...r===void 0?{}:{source:r}},e)];const o=i.filter(a=>a.type!=="empty"),n=t==="assistant"&&o.length>0&&o.every(a=>a.type==="skillRead")?"skill":t;return o.length>0?[Dt({role:n,parts:o,...r===void 0?{}:{source:r}},e)]:[]}function Vl(e){const t=D(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(ee(e,"parts"))}function Kl(e){if(e.length!==1||e[0]?.type!=="text")return;const t=Gl(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 Gl(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 Jl(e){const t=D(e,"source");if(t==="compaction"||t==="branch_summary")return t}function Ql(e){const t=Zl(ee(e,"timestamp")),i=Xl(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function Zl(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 Xl(e){if(D(e,"role")!=="assistant")return;const t=D(e,"provider"),i=D(e,"model"),s=D(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function Yl(e){const t=D(e,"command")??"",i=Ut(e,"excludeFromContext")===!0?["不加入上下文","",`$ ${t}`]:[`$ ${t}`],s=ee(e,"output");s!=null&&i.push("",Xt(s));const r=ee(e,"exitCode");r!=null&&i.push("",`exit ${Xt(r)}`),Ut(e,"cancelled")===!0&&i.push("","cancelled"),Ut(e,"truncated")===!0&&i.push("","output truncated");const o=D(e,"fullOutputPath");return o!==void 0&&o!==""&&i.push("",`完整输出:${o}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
- `)}]}}function ec(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function tc(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=D(i,"type"),r=D(i,"text");if(s==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(s==="thinking"){const o=D(i,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}if(s==="toolCall"){const o=D(i,"name")??"tool",n=ee(i,"arguments"),a=o==="read"?sc(D(n,"path")):void 0;if(a!==void 0)return[{type:"skillRead",...a}];const c=D(i,"id");return[{type:"toolCall",...c===void 0?{}:{toolCallId:c},toolName:o,summary:$t(n),...n===void 0?{}:{args:n}}]}return s==="image"?[{type:"text",text:"[image]"}]:nr(i)}).map(i=>i.type==="text"&&D(t,"role")==="toolResult"?ic(i.text,t):i):nr(e)}function ic(e,t){const i=D(t,"toolCallId"),s=ee(t,"content"),r=ee(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:D(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...r===void 0?{}:{details:r},isError:Ut(t,"isError")===!0}}function sc(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 rc(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=oc(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&&nc(t,c,a)){i.delete(a.toolCallId??"");continue}}r.push(a)}n()}return t}function oc(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 nc(e,t,i){const s=e[t.lineIndex],r=s?.parts[t.partIndex];if(s===void 0||r?.type!=="toolExecution")return!1;const o=Zt(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 Zt(e){const t=ee(e,"preview");if(!ps(t))return;const i=D(t,"diff"),s=D(t,"error"),r=lc(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 nr(e){return e==null?[]:typeof e=="object"?[{type:"text",text:$t(e)}]:[{type:"text",text:Xt(e)}]}function $t(e){if(!ps(e))return Xt(e);const t=D(e,"command");if(t!==void 0)return t;const i=D(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} 处编辑`:Object.entries(e).filter(([,o])=>o!=null).slice(0,3).map(([o,n])=>`${o}: ${ac(n)}`).join(" · ")}function ac(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)} 项`:typeof e=="object"&&e!==null?"object":""}function ps(e){return typeof e=="object"&&e!==null}function ee(e,t){return ps(e)?e[t]:void 0}function D(e,t){const i=ee(e,t);return typeof i=="string"?i:void 0}function Ut(e,t){const i=ee(e,t);return typeof i=="boolean"?i:void 0}function lc(e,t){const i=ee(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function Xt(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const cc="pi-web:prompt-draft:";function Yt(e){return`${cc}${e}`}function hi(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function wo(e,t=hi()){try{return t?.getItem(Yt(e))??""}catch{return""}}function ei(e,t,i=hi()){try{t?i?.setItem(Yt(e),t):i?.removeItem(Yt(e))}catch{}}function hs(e,t=hi()){try{t?.removeItem(Yt(e))}catch{}}function dc(e,t,i=hi()){const s=wo(e,i);s!==""&&(ei(t,s,i),hs(e,i))}function pc(e,t){return ve("bash",`${t===!0?`不加入上下文
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-DRxmEzh1.js","assets/vendor-editor-core-B4Sq6exx.js","assets/vendor-editor-languages-DznYbTkJ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-BcGKwlLZ.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
2
+ import{Q as Os,w as Ge,J as yi,R as Tn,S as Cn,G as In,U as Mn,V as An,A as Rn,W as En,X as Dn,Y as _n,Z as Ls,x as Ws,_ as On}from"./vendor-editor-core-B4Sq6exx.js";import{m as Ln,i as Wn,d as jn}from"./vendor-editor-languages-DznYbTkJ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))s(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const n of o.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function s(r){if(r.ep)return;r.ep=!0;const o=i(r);fetch(r.href,o)}})();const Bt=globalThis,es=Bt.ShadowRoot&&(Bt.ShadyCSS===void 0||Bt.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,ts=Symbol(),js=new WeakMap;let so=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==ts)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(es&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=js.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&js.set(i,t))}return t}toString(){return this.cssText}};const Nn=e=>new so(typeof e=="string"?e:e+"",void 0,ts),E=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,r,o)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+e[o+1],e[0]);return new so(i,e,ts)},Bn=(e,t)=>{if(es)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),r=Bt.litNonce;r!==void 0&&s.setAttribute("nonce",r),s.textContent=i.cssText,e.appendChild(s)}},Ns=es?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return Nn(i)})(e):e;const{is:Fn,defineProperty:zn,getOwnPropertyDescriptor:Un,getOwnPropertyNames:Hn,getOwnPropertySymbols:qn,getPrototypeOf:Vn}=Object,ci=globalThis,Bs=ci.trustedTypes,Kn=Bs?Bs.emptyScript:"",Gn=ci.reactiveElementPolyfillSupport,mt=(e,t)=>e,Kt={toAttribute(e,t){switch(t){case Boolean:e=e?Kn: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}},is=(e,t)=>!Fn(e,t),Fs={attribute:!0,type:String,converter:Kt,reflect:!1,useDefault:!1,hasChanged:is};Symbol.metadata??=Symbol("metadata"),ci.litPropertyMetadata??=new WeakMap;let Ze=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=Fs){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&&zn(this.prototype,t,r)}}static getPropertyDescriptor(t,i,s){const{get:r,set:o}=Un(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)??Fs}static _$Ei(){if(this.hasOwnProperty(mt("elementProperties")))return;const t=Vn(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(mt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(mt("properties"))){const i=this.properties,s=[...Hn(i),...qn(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(Ns(r))}else t!==void 0&&i.push(Ns(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 Bn(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:Kt).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:Kt;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??is)(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){}};Ze.elementStyles=[],Ze.shadowRootOptions={mode:"open"},Ze[mt("elementProperties")]=new Map,Ze[mt("finalized")]=new Map,Gn?.({ReactiveElement:Ze}),(ci.reactiveElementVersions??=[]).push("2.1.2");const ss=globalThis,zs=e=>e,Gt=ss.trustedTypes,Us=Gt?Gt.createPolicy("lit-html",{createHTML:e=>e}):void 0,ro="$lit$",Ae=`lit$${Math.random().toFixed(9).slice(2)}$`,oo="?"+Ae,Jn=`<${oo}>`,je=document,vt=()=>je.createComment(""),bt=e=>e===null||typeof e!="object"&&typeof e!="function",rs=Array.isArray,Qn=e=>rs(e)||typeof e?.[Symbol.iterator]=="function",xi=`[
3
+ \f\r]`,at=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Hs=/-->/g,qs=/>/g,De=RegExp(`>|${xi}(?:([^\\s"'>=/]+)(${xi}*=${xi}*(?:[^
4
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Vs=/'/g,Ks=/"/g,no=/^(?:script|style|textarea|title)$/i,ao=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=ao(1),Xe=ao(2),Re=Symbol.for("lit-noChange"),j=Symbol.for("lit-nothing"),Gs=new WeakMap,Le=je.createTreeWalker(je,129);function lo(e,t){if(!rs(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return Us!==void 0?Us.createHTML(t):t}const Zn=(e,t)=>{const i=e.length-1,s=[];let r,o=t===2?"<svg>":t===3?"<math>":"",n=at;for(let a=0;a<i;a++){const c=e[a];let p,f,h=-1,u=0;for(;u<c.length&&(n.lastIndex=u,f=n.exec(c),f!==null);)u=n.lastIndex,n===at?f[1]==="!--"?n=Hs:f[1]!==void 0?n=qs:f[2]!==void 0?(no.test(f[2])&&(r=RegExp("</"+f[2],"g")),n=De):f[3]!==void 0&&(n=De):n===De?f[0]===">"?(n=r??at,h=-1):f[1]===void 0?h=-2:(h=n.lastIndex-f[2].length,p=f[1],n=f[3]===void 0?De:f[3]==='"'?Ks:Vs):n===Ks||n===Vs?n=De:n===Hs||n===qs?n=at:(n=De,r=void 0);const v=n===De&&e[a+1].startsWith("/>")?" ":"";o+=n===at?c+Jn:h>=0?(s.push(p),c.slice(0,h)+ro+c.slice(h)+Ae+v):c+Ae+(h===-2?a:v)}return[lo(e,o+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class wt{constructor({strings:t,_$litType$:i},s){let r;this.parts=[];let o=0,n=0;const a=t.length-1,c=this.parts,[p,f]=Zn(t,i);if(this.el=wt.createElement(p,s),Le.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(r=Le.nextNode())!==null&&c.length<a;){if(r.nodeType===1){if(r.hasAttributes())for(const h of r.getAttributeNames())if(h.endsWith(ro)){const u=f[n++],v=r.getAttribute(h).split(Ae),S=/([.?@])?(.*)/.exec(u);c.push({type:1,index:o,name:S[2],strings:v,ctor:S[1]==="."?Yn:S[1]==="?"?ea:S[1]==="@"?ta:di}),r.removeAttribute(h)}else h.startsWith(Ae)&&(c.push({type:6,index:o}),r.removeAttribute(h));if(no.test(r.tagName)){const h=r.textContent.split(Ae),u=h.length-1;if(u>0){r.textContent=Gt?Gt.emptyScript:"";for(let v=0;v<u;v++)r.append(h[v],vt()),Le.nextNode(),c.push({type:2,index:++o});r.append(h[u],vt())}}}else if(r.nodeType===8)if(r.data===oo)c.push({type:2,index:o});else{let h=-1;for(;(h=r.data.indexOf(Ae,h+1))!==-1;)c.push({type:7,index:o}),h+=Ae.length-1}o++}}static createElement(t,i){const s=je.createElement("template");return s.innerHTML=t,s}}function et(e,t,i=e,s){if(t===Re)return t;let r=s!==void 0?i._$Co?.[s]:i._$Cl;const o=bt(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=et(e,r._$AS(e,t.values),r,s)),t}class Xn{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??je).importNode(i,!0);Le.currentNode=r;let o=Le.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new it(o,o.nextSibling,this,t):c.type===1?p=new c.ctor(o,c.name,c.strings,this,t):c.type===6&&(p=new ia(o,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(o=Le.nextNode(),n++)}return Le.currentNode=je,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 it{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,r){this.type=2,this._$AH=j,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=et(this,t,i),bt(t)?t===j||t==null||t===""?(this._$AH!==j&&this._$AR(),this._$AH=j):t!==this._$AH&&t!==Re&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Qn(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!==j&&bt(this._$AH)?this._$AA.nextSibling.data=t:this.T(je.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,r=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=wt.createElement(lo(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===r)this._$AH.p(i);else{const o=new Xn(r,this),n=o.u(this.options);o.p(i),this.T(n),this._$AH=o}}_$AC(t){let i=Gs.get(t.strings);return i===void 0&&Gs.set(t.strings,i=new wt(t)),i}k(t){rs(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 it(this.O(vt()),this.O(vt()),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=zs(t).nextSibling;zs(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let di=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,r,o){this.type=1,this._$AH=j,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=j}_$AI(t,i=this,s,r){const o=this.strings;let n=!1;if(o===void 0)t=et(this,t,i,0),n=!bt(t)||t!==this._$AH&&t!==Re,n&&(this._$AH=t);else{const a=t;let c,p;for(t=o[0],c=0;c<o.length-1;c++)p=et(this,a[s+c],i,c),p===Re&&(p=this._$AH[c]),n||=!bt(p)||p!==this._$AH[c],p===j?t=j:t!==j&&(t+=(p??"")+o[c+1]),this._$AH[c]=p}n&&!r&&this.j(t)}j(t){t===j?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Yn=class extends di{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===j?void 0:t}},ea=class extends di{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==j)}},ta=class extends di{constructor(t,i,s,r,o){super(t,i,s,r,o),this.type=5}_$AI(t,i=this){if((t=et(this,t,i,0)??j)===Re)return;const s=this._$AH,r=t===j&&s!==j||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,o=t!==j&&(s===j||r);r&&this.element.removeEventListener(this.name,this,s),o&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}};class ia{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){et(this,t)}}const sa={I:it},ra=ss.litHtmlPolyfillSupport;ra?.(wt,it),(ss.litHtmlVersions??=[]).push("3.3.2");const oa=(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 it(t.insertBefore(vt(),o),o,void 0,i??{})}return r._$AI(e),r};const os=globalThis;let I=class extends Ze{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=oa(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Re}};I._$litElement$=!0,I.finalized=!0,os.litElementHydrateSupport?.({LitElement:I});const na=os.litElementPolyfillSupport;na?.({LitElement:I});(os.litElementVersions??=[]).push("4.2.2");const A=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const aa={attribute:!0,type:String,converter:Kt,reflect:!1,hasChanged:is},la=(e=aa,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"?la(e,t,i):((s,r,o)=>{const n=r.hasOwnProperty(o);return r.constructor.createProperty(o,s),n?Object.getOwnPropertyDescriptor(r,o):void 0})(e,t,i)}function x(e){return d({...e,state:!0,attribute:!1})}const ca=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function re(e,t){return(i,s,r)=>{const o=n=>n.renderRoot?.querySelector(e)??null;return ca(i,s,{get(){return o(this)}})}}function co(e,t=ho()){if(t===void 0)return e;const i=po(t);if(i===void 0)return e;const s=new URL(e,t.origin);return s.searchParams.set("embed",i.embed),s.searchParams.set("token",i.token),`${s.pathname}${s.search}${s.hash}`}function ns(e,t=ho()){if(t===void 0)return e;const i=po(t);if(i===void 0)return e;const s=new URL(e);return s.searchParams.set("embed",i.embed),s.searchParams.set("token",i.token),s.toString()}function po(e){const t=e.searchParams.get("embed"),i=e.searchParams.get("token")?.trim();if(!(t!=="management"||i===void 0||i===""))return{embed:t,token:i}}function ho(){if(typeof globalThis.location>"u")return;const e=globalThis.location;if(typeof e.href=="string"&&e.href!=="")return new URL(e.href);const t=typeof e.protocol=="string"&&e.protocol!==""?e.protocol:"http:",i=typeof e.host=="string"&&e.host!==""?e.host:"localhost",s=typeof e.search=="string"?e.search:"";return new URL(`${t}//${i}/${s}`)}async function y(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const r=await fetch(co(e),{...i,headers:s});if(!r.ok){const n=await r.json().catch(()=>({}));throw new Error(da(n)??r.statusText)}const o=await r.json();return t(o)}function da(e){if(pa(e))return typeof e.error=="string"?e.error:void 0}function pa(e){return typeof e=="object"&&e!==null}function gt(e){return typeof e=="object"&&e!==null}function w(e){if(!gt(e))throw new Error("Expected object response");return e}function g(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function k(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 Y(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function R(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function W(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function ha(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function ua(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function fa(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=w(e);return{messages:ha(t.messages),start:Y(t,"start"),total:Y(t,"total")}}function ma(e){const t=w(e);return W(uo)(t.machines)}function uo(e){const t=w(e),i=va(t,"kind"),s=k(t,"baseUrl"),r=fo(t,"status"),o=k(t,"statusMessage");return{id:g(t,"id"),name:g(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:g(t,"createdAt"),updatedAt:g(t,"updatedAt"),...r===void 0?{}:{status:r},...o===void 0?{}:{statusMessage:o}}}function ga(e){const t=w(e),i=fo(t,"status"),s=k(t,"error");return{machineId:g(t,"machineId"),ok:R(t,"ok"),checkedAt:g(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:Jt(t.web)},...t.sessiond===void 0?{}:{sessiond:Jt(t.sessiond)},...s===void 0?{}:{error:s}}}function va(e,t){const i=g(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function fo(e,t){const i=k(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 Js(e){const t=w(e);return{id:g(t,"id"),name:g(t,"name"),path:g(t,"path"),createdAt:g(t,"createdAt")}}function ba(e){const t=w(e),i=k(t,"branch");return{id:g(t,"id"),projectId:g(t,"projectId"),path:g(t,"path"),label:g(t,"label"),...i===void 0?{}:{branch:i},isMain:R(t,"isMain"),isGitRepo:R(t,"isGitRepo"),isGitWorktree:R(t,"isGitWorktree")}}function Fi(e){const t=w(e),i=k(t,"name"),s=k(t,"parentSessionPath"),r=k(t,"archivedAt");return{id:g(t,"id"),path:g(t,"path"),cwd:g(t,"cwd"),...i===void 0?{}:{name:i},created:g(t,"created"),modified:g(t,"modified"),messageCount:Y(t,"messageCount"),firstMessage:g(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...r===void 0?{}:{archivedAt:r}}}function lt(e){const t=w(e);return{sessionId:g(t,"sessionId"),isStreaming:R(t,"isStreaming"),isCompacting:R(t,"isCompacting"),isBashRunning:R(t,"isBashRunning"),pendingMessageCount:Y(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:W(wa)(t.queuedMessages),...b("messageCount",be(t,"messageCount")),tokens:ya(t.tokens),cost:Y(t,"cost"),...xa(t.model),..._a(t.contextUsage),...b("thinkingLevel",k(t,"thinkingLevel"))}}function wa(e){const t=w(e),i=g(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:g(t,"text")}}function ya(e){const t=w(e);return{input:Y(t,"input"),output:Y(t,"output"),cacheRead:Y(t,"cacheRead"),cacheWrite:Y(t,"cacheWrite"),total:Y(t,"total")}}function mo(e){const t=w(e);return{...b("provider",k(t,"provider")),...b("id",k(t,"id")),...b("name",k(t,"name")),...b("contextWindow",be(t,"contextWindow")),...b("reasoning",t.reasoning)}}function xa(e){return e===void 0?{}:{model:mo(e)}}function Sa(e){const t=w(e);return{models:W(mo)(t.models)}}function ka(e){if(e!=="off"&&e!=="minimal"&&e!=="low"&&e!=="medium"&&e!=="high"&&e!=="xhigh")throw new Error("Invalid thinking level");return e}function $a(e){const t=w(e);return{levels:W(ka)(t.levels)}}function Pa(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function Ta(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 Ca(e){const t=w(e),i=t.source===void 0?void 0:Ta(t.source);return{configured:R(t,"configured"),...b("source",i),...b("label",k(t,"label"))}}function Ia(e){const t=w(e);return{id:g(t,"id"),name:g(t,"name"),authType:Pa(t.authType),status:Ca(t.status)}}function Ma(e){const t=w(e);return{providers:W(Ia)(t.providers)}}function Rt(e){const t=w(e);return{flowId:g(t,"flowId"),providerId:g(t,"providerId"),providerName:g(t,"providerName"),status:Aa(t.status),progress:W(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...b("error",k(t,"error")),...b("auth",Ra(t.auth)),...b("prompt",Ea(t.prompt)),...b("select",Da(t.select))}}function Aa(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Ra(e){if(e===void 0)return;const t=w(e);return{url:g(t,"url"),...b("instructions",k(t,"instructions"))}}function Ea(e){if(e===void 0)return;const t=w(e),i=g(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:g(t,"requestId"),message:g(t,"message"),kind:i,...b("placeholder",k(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function Da(e){if(e===void 0)return;const t=w(e);return{requestId:g(t,"requestId"),message:g(t,"message"),options:W(vo)(t.options)}}function _a(e){if(e===void 0)return{};const t=w(e);return{contextUsage:{tokens:tr(t,"tokens"),contextWindow:Y(t,"contextWindow"),percent:tr(t,"percent")}}}function Oa(e){const t=w(e),i=g(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:g(t,"name"),source:i,...b("description",k(t,"description"))}}function go(e){const t=w(e),i=g(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:g(t,"path"),kind:i}}function La(e){const t=w(e);return{path:g(t,"path"),entries:W(Wa)(t.entries),scannedAt:g(t,"scannedAt"),truncated:R(t,"truncated")}}function Wa(e){const t=w(e),i=g(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:g(t,"name"),path:g(t,"path"),type:i,...b("size",be(t,"size")),...b("modifiedAt",k(t,"modifiedAt"))}}function ja(e){const t=w(e),i=g(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:g(t,"path"),...b("language",k(t,"language")),...b("mediaType",Na(t.mediaType)),...b("mimeType",k(t,"mimeType")),encoding:i,size:Y(t,"size"),modifiedAt:g(t,"modifiedAt"),content:g(t,"content"),truncated:R(t,"truncated"),binary:R(t,"binary")}}function Na(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function Ba(e){const t=w(e);return{isGitRepo:R(t,"isGitRepo"),hash:g(t,"hash"),...b("branch",k(t,"branch")),...b("upstream",k(t,"upstream")),...b("ahead",be(t,"ahead")),...b("behind",be(t,"behind")),files:W(Fa)(t.files)}}function Fa(e){const t=w(e);return{path:g(t,"path"),...b("oldPath",k(t,"oldPath")),index:Qs(t.index),workingTree:Qs(t.workingTree)}}function Qs(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 za(e){const t=w(e);return{...b("path",k(t,"path")),staged:R(t,"staged"),hash:g(t,"hash"),diff:g(t,"diff"),truncated:R(t,"truncated")}}function Si(e){const t=w(e);return{id:g(t,"id"),cwd:g(t,"cwd"),name:g(t,"name"),createdAt:g(t,"createdAt"),exited:R(t,"exited"),...b("exitCode",be(t,"exitCode")),...b("commandRunId",k(t,"commandRunId"))}}function Ft(e){const t=w(e);return{id:g(t,"id"),origin:g(t,"origin"),projectId:g(t,"projectId"),workspaceId:g(t,"workspaceId"),terminalId:g(t,"terminalId"),title:g(t,"title"),command:g(t,"command"),status:Ua(t.status),...b("exitCode",be(t,"exitCode")),createdAt:g(t,"createdAt"),...b("startedAt",k(t,"startedAt")),...b("completedAt",k(t,"completedAt")),metadata:Ha(t.metadata,"metadata")}}function Ua(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function Ha(e,t){const i=w(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 qa(e){const t=w(e);return{cwd:g(t,"cwd"),hasSessionActivity:R(t,"hasSessionActivity"),hasTerminalActivity:R(t,"hasTerminalActivity"),updatedAt:g(t,"updatedAt")}}function Va(e){const t=w(e);return{workspaces:W(qa)(t.workspaces),generatedAt:g(t,"generatedAt")}}function Zs(e){const t=w(e);return{path:g(t,"path"),exists:R(t,"exists"),config:Xs(t.config),effectiveConfig:Xs(t.effectiveConfig),envOverrides:Qa(t.envOverrides)}}function Xs(e){const t=w(e);return{...b("host",k(t,"host")),...b("port",be(t,"port")),...b("allowedHosts",Ka(t.allowedHosts)),...b("shortcuts",Ga(t.shortcuts)),...b("plugins",Ja(t.plugins))}}function Ka(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 Ga(e){if(e!==void 0){if(!gt(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 Ja(e){if(e!==void 0){if(!gt(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!gt(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&&(!gt(r)||Array.isArray(r)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Qa(e){const t=w(e);return{host:R(t,"host"),port:R(t,"port"),allowedHosts:R(t,"allowedHosts")}}function Za(e){const t=w(e);return{plugins:W(Xa)(t.plugins)}}function Xa(e){const t=w(e);return{id:g(t,"id"),module:g(t,"module"),source:g(t,"source"),scope:Ya(t.scope),enabled:R(t,"enabled")}}function Ya(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function el(e){const t=w(e);return{packageName:g(t,"packageName"),generatedAt:g(t,"generatedAt"),components:tl(t.components),release:sl(t.release),commands:rl(t.commands),messages:W(ol)(t.messages)}}function tl(e){const t=w(e);return{web:Jt(t.web),sessiond:Jt(t.sessiond)}}function Jt(e){const t=w(e);return{component:nl(t.component),label:g(t,"label"),...b("runtimeVersion",k(t,"runtimeVersion")),...b("installedVersion",k(t,"installedVersion")),stale:R(t,"stale"),available:R(t,"available"),...b("installation",il(t.installation)),...b("error",k(t,"error"))}}function il(e){if(e===void 0)return;const t=w(e),i=g(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",k(t,"path")),...b("source",k(t,"source")),...s===void 0?{}:{scope:s},...b("npmRoot",k(t,"npmRoot"))}}function sl(e){const t=w(e);return{packageName:g(t,"packageName"),...b("latestVersion",k(t,"latestVersion")),updateAvailable:R(t,"updateAvailable"),...b("checkedAt",k(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...b("error",k(t,"error"))}}function rl(e){const t=w(e);return{...b("update",k(t,"update")),...b("restart",k(t,"restart")),...b("restartWeb",k(t,"restartWeb")),...b("restartSessiond",k(t,"restartSessiond")),...b("status",k(t,"status"))}}function ol(e){const t=w(e);return{id:g(t,"id"),severity:al(t.severity),title:g(t,"title"),body:g(t,"body"),...b("command",k(t,"command"))}}function nl(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function al(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Ys(e){const t=w(e),i=g(t,"type");if(i==="unsupported")return{type:i,message:g(t,"message")};if(i==="select")return{type:i,requestId:g(t,"requestId"),title:g(t,"title"),options:W(vo)(t.options)};if(i==="done")return{type:i,...b("message",k(t,"message")),...ll(t.session),...b("promptDraft",k(t,"promptDraft"))};throw new Error("Invalid command result type")}function vo(e){const t=w(e);return{value:g(t,"value"),label:g(t,"label"),...b("description",k(t,"description"))}}function ll(e){return e===void 0?{}:{session:Fi(e)}}function Et(e){if(w(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function bo(e){if(w(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function cl(e){if(w(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function dl(e){if(w(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function er(e){const t=w(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:ua(t.sessionIds,"sessionIds"),s=be(t,"archivedCount"),r=be(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...r===void 0?{}:{skippedAlreadyArchivedCount:r}}}function pl(e){if(w(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function hl(e){if(w(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function be(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 tr(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 b(e,t){return t===void 0?{}:{[e]:t}}function ul(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 fl(e,t,i="local"){const s=new URLSearchParams;t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const r=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${e}/messages${r?`?${r}`:""}`}function ml(e,t,i,s){const r=new URLSearchParams;return r.set("path",i),s?.modifiedAt!==void 0&&r.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${r.toString()}`}const $=(e="local")=>`/api/machines/${encodeURIComponent(e)}`,wo={piWebStatus:()=>y("/api/pi-web/status",el)},gl={machines:()=>y("/api/machines",ma),addMachine:e=>y("/api/machines",uo,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>y(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>y(`/api/machines/${encodeURIComponent(e)}/health`,ga)},Qt={config:()=>y("/api/config",Zs),saveConfig:e=>y("/api/config",Zs,{method:"PUT",body:JSON.stringify({config:e})})},zi={plugins:()=>y("/api/plugins",Za)},yo={workspaceActivity:(e="local")=>y(`${$(e)}/activity`,Va)},vl={projects:(e="local")=>y(`${$(e)}/projects`,W(Js)),addProject:(e,t,i,s="local")=>y(`${$(s)}/projects`,Js,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>y(`${$(t)}/projects/${encodeURIComponent(e)}`,bo,{method:"DELETE"}),projectDirectories:(e,t="local")=>y(`${$(t)}/project-directories?q=${encodeURIComponent(e)}`,W(go))},xo={workspaces:(e,t="local")=>y(`${$(t)}/projects/${e}/workspaces`,W(ba)),workspaceTree:(e,t,i="",s="local")=>y(`${$(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,La),workspaceFile:(e,t,i,s="local")=>y(`${$(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,ja)},bl={sessions:(e,t="local")=>y(`${$(t)}/sessions?cwd=${encodeURIComponent(e)}`,W(Fi)),startSession:(e,t="local")=>y(`${$(t)}/sessions`,Fi,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>y(fl(e,t,i),fa),status:(e,t="local")=>y(`${$(t)}/sessions/${e}/status`,lt),models:(e,t="local")=>y(`${$(t)}/sessions/${e}/models`,Sa),setModel:(e,t,i,s="local")=>y(`${$(s)}/sessions/${e}/model`,lt,{method:"POST",body:JSON.stringify({provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>y(`${$(i)}/sessions/${e}/model/cycle`,lt,{method:"POST",body:JSON.stringify({direction:t})}),thinkingLevels:(e,t="local")=>y(`${$(t)}/sessions/${e}/thinking-levels`,$a),setThinkingLevel:(e,t,i="local")=>y(`${$(i)}/sessions/${e}/thinking-level`,lt,{method:"POST",body:JSON.stringify({level:t})}),cycleThinkingLevel:(e,t="local")=>y(`${$(t)}/sessions/${e}/thinking-level/cycle`,lt,{method:"POST"}),commands:(e,t="local")=>y(`${$(t)}/sessions/${e}/commands`,W(Oa)),prompt:(e,t,i,s="local")=>y(`${$(s)}/sessions/${e}/prompt`,Et,{method:"POST",body:JSON.stringify(i===void 0?{text:t}:{text:t,streamingBehavior:i})}),shell:(e,t,i="local")=>y(`${$(i)}/sessions/${e}/shell`,Et,{method:"POST",body:JSON.stringify({text:t})}),runCommand:(e,t,i="local")=>y(`${$(i)}/sessions/${e}/commands/run`,Ys,{method:"POST",body:JSON.stringify({text:t})}),respondToCommand:(e,t,i,s="local")=>y(`${$(s)}/sessions/${e}/commands/respond`,Ys,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),abort:(e,t="local")=>y(`${$(t)}/sessions/${e}/abort`,cl,{method:"POST"}),stop:(e,t="local")=>y(`${$(t)}/sessions/${e}/stop`,dl,{method:"POST"}),archive:(e,t="local")=>y(`${$(t)}/sessions/${e}/archive`,er,{method:"POST"}),archiveWithDescendants:(e,t="local")=>y(`${$(t)}/sessions/${e}/archive-tree`,er,{method:"POST"}),restore:(e,t="local")=>y(`${$(t)}/sessions/${e}/restore`,pl,{method:"POST"}),detachParent:(e,t="local")=>y(`${$(t)}/sessions/${e}/detach-parent`,hl,{method:"POST"}),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 y(`${$(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Ma)},saveApiKey:(e,t,i="local")=>y(`${$(i)}/auth/api-key`,Et,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>y(`${$(t)}/auth/logout`,Et,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>y(`${$(t)}/auth/oauth`,Rt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>y(`${$(t)}/auth/oauth/${encodeURIComponent(e)}`,Rt),respondOAuthFlow:(e,t,i,s="local")=>y(`${$(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,Rt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>y(`${$(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,Rt,{method:"POST"})},Ye={terminals:(e,t,i="local")=>y(`${$(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,W(Si)),startTerminal:(e,t,i,s="local")=>y(`${$(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Si,{method:"POST",body:JSON.stringify(i??{})}),closeTerminal:(e,t,i,s="local")=>y(`${$(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,bo,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>y(`${$(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Si,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>y(`${$(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Ft,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>y(`${$(t)}/terminal-command-runs${yl(e)}`,W(Ft)),getCommandRun:(e,t="local")=>wl(e,t),cancelCommandRun:(e,t="local")=>y(`${$(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Ft,{method:"POST"})};async function wl(e,t){const i=await fetch(co(`${$(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(xl(s)??i.statusText)}return Ft(await i.json())}}function yl(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 xl(e){if(!Sl(e))return;const t=e.error;return typeof t=="string"?t:void 0}function Sl(e){return typeof e=="object"&&e!==null}const kl={files:(e,t,i={})=>{const s=new URLSearchParams({cwd:e,q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),y(`${$(i.machineId)}/files?${s.toString()}`,W(go))}},$l={gitStatus:(e,t,i="local")=>y(`${$(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Ba),gitDiff:(e,t,i,s="local")=>y(ul(s,e,t,i),za)},_={...wo,...gl,...Qt,...zi,...yo,...vl,...xo,...bl,...Ye,...kl,...$l};function Pl(e,t="local"){return new WebSocket(ns(`${ls()}${as(t)}/sessions/${e}/events`))}function yg(e,t,i,s,r="local"){const o=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(ns(`${ls()}${as(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${o}`))}function Tl(e="local"){return new WebSocket(ns(`${ls()}${as(e)}/events`))}function as(e){return`/api/machines/${encodeURIComponent(e)}`}function ls(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function zt(){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 Cl(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function pi(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function So(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const ko="local";function ki(e,t){return`${e}:${t}`}function $o(e,t){return`${e}:${t}`}function m(e){return e.selectedMachine?.id??ko}class Il{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??yo}async refresh(t=m(this.getState())){this.applyMachineActivitySnapshot(t,Ml(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=m(this.getState())){const s=this.getState(),r=m(s)===i,o=s.machineActivities[i]??(r?s.workspaceActivities:{}),n=Al(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},...m(s)===t?{workspaceActivities:i}:{}})}}function Ml(e){const t={};for(const i of e.workspaces)So(i)&&(t[i.cwd]=i);return t}function Al(e,t){const i={...e};return So(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class Rl{constructor(t,i,s,r={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=r.api??_,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=El(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:m(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,m(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:m(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,m(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,m(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,m(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:m(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,m(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,m(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.sessionId();if(t!==void 0)try{this.applyStatus(await this.api.status(t,m(this.getState())))}catch{}}sessionId(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t.id}}function El(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 St(e){return e.replaceAll(":",".")}function Dl(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 $i(e,t){const i=Dl(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function pe(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));_l(r,s)}function _l(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}const ir=St("core:workspace.files");class Ol{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=m(this.getState()),r=await _.workspaceTree(t.id,i.id,"",s),o={...this.getState().expandedDirs};await Promise.all(Object.keys(o).map(async n=>{o[n]=(await _.workspaceTree(t.id,i.id,n,s)).entries})),this.setState({fileTree:r.entries,expandedDirs:o,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:Wl(this.getState().expandedDirs,t)});return}try{const r=await _.workspaceTree(i.id,s.id,t,m(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"}),pe(ir,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}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 _.workspaceFile(i.id,s.id,t,m(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:r,error:""})}catch(r){if(this.getState().selectedFilePath!==t)return;if(Ll(r)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),pe(ir,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(r)})}}}}function Ll(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function Wl(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}const sr=St("core:workspace.git");class jl{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 _.gitStatus(t.id,i.id,m(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}),pe(sr,"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"}),pe(sr,"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([_.gitDiff(i.id,s.id,{path:t},m(this.getState())),_.gitDiff(i.id,s.id,{path:t,staged:!0},m(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 Nl{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 _.machines(),s=await this.selectInitialMachine(i,t),r=new Set(i.map(o=>o.id));this.setState({machines:i,selectedMachine:s,machineActivities:Bl(this.getState().machineActivities,r)}),this.refreshMachineHealthFor(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:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...zt()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id))}async addMachine(t){this.setState({error:""});try{const i=await _.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 _.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:rr(this.getState().machineStatuses,t.id),machineActivities:rr(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 _.health(t);this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(n=>n.id===(i??"local"));if(s?.kind!=="remote")return s??this.localMachine(t);const r=await this.safeRemoteHealth(s);if(r.ok)return s;const o=this.localMachine(t);return this.setState({error:`${s.name} is offline; showing ${o?.name??"another machine"} instead.`,machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r}}),o??s}async safeRemoteHealth(t){try{return await _.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=>_.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}})}}function rr(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Bl(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class Fl{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=m(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await _.projects(t);if(m(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){m(this.getState())===t&&this.setState({error:String(i)})}finally{m(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await _.addProject(t.trim(),void 0,i,m(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 _.closeProject(t,m(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 Ui="pi-web:cached-new-sessions:v1",zl="browserCachedNew",st="local";function kt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function or(e,t=st,i=kt()){if(e.messageCount!==0||e.archived===!0)return;const s=cs(i).filter(r=>r.id!==e.id||r.machineId!==t);ds([Hi(e,t),...s],i)}function Hi(e,t=st){return{...e,browserCachedNew:!0,machineId:t}}function nr(e,t=st,i=kt()){const s=cs(i).filter(r=>r.id!==e||r.machineId!==t);ds(s,i)}function Ul(e,t,i=st,s=kt()){const r=new Set(t.map(c=>c.id)),o=cs(s),n=o.filter(c=>c.machineId!==i||!r.has(c.id));return n.length!==o.length&&ds(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function ke(e){return e===void 0?!1:Vl(e)&&e.browserCachedNew===!0}function Hl(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:st},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function cs(e=kt()){try{const t=e?.getItem(Ui);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>ql(s)):[]}catch{return[]}}function ds(e,t=kt()){try{e.length===0?t?.removeItem(Ui):t?.setItem(Ui,JSON.stringify(e))}catch{}}function ql(e){if(!Kl(e))return[];const t=Je(e,"id"),i=Je(e,"path"),s=Je(e,"cwd"),r=Je(e,"created"),o=Je(e,"modified"),n=Je(e,"firstMessage"),a=Gl(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=Pi(e,"name"),p=Pi(e,"parentSessionPath"),f=Pi(e,"machineId")??st;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:f,browserCachedNew:!0}]}function Vl(e){return zl in e}function Kl(e){return typeof e=="object"&&e!==null}function Je(e,t){const i=e[t];return typeof i=="string"?i:void 0}function Pi(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Gl(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Jl(e){return dc(e.flatMap(ps)).filter(t=>t.parts.length>0)}function ve(e,t){return{role:e,parts:[{type:"text",text:t}]}}function Dt(e,t){const i=ic(t);return i===void 0?e:{...e,meta:i}}function Ql(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,ve(t,i)]}function Zl(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 ps(e){if(Xl(e))return[e];if(D(e,"role")==="bashExecution")return[Dt(oc(e),e)];const t=nc(D(e,"role")),i=ac(ee(e,"content"),e),s=t==="user"?Yl(i):void 0;if(s!==void 0)return s.map(a=>Dt(a,e));const r=tc(e);if(t==="tool")return[Dt({role:t,parts:i,...r===void 0?{}:{source:r}},e)];const o=i.filter(a=>a.type!=="empty"),n=t==="assistant"&&o.length>0&&o.every(a=>a.type==="skillRead")?"skill":t;return o.length>0?[Dt({role:n,parts:o,...r===void 0?{}:{source:r}},e)]:[]}function Xl(e){const t=D(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(ee(e,"parts"))}function Yl(e){if(e.length!==1||e[0]?.type!=="text")return;const t=ec(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 ec(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 tc(e){const t=D(e,"source");if(t==="compaction"||t==="branch_summary")return t}function ic(e){const t=sc(ee(e,"timestamp")),i=rc(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function sc(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 rc(e){if(D(e,"role")!=="assistant")return;const t=D(e,"provider"),i=D(e,"model"),s=D(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function oc(e){const t=D(e,"command")??"",i=Ut(e,"excludeFromContext")===!0?["不加入上下文","",`$ ${t}`]:[`$ ${t}`],s=ee(e,"output");s!=null&&i.push("",Xt(s));const r=ee(e,"exitCode");r!=null&&i.push("",`exit ${Xt(r)}`),Ut(e,"cancelled")===!0&&i.push("","cancelled"),Ut(e,"truncated")===!0&&i.push("","output truncated");const o=D(e,"fullOutputPath");return o!==void 0&&o!==""&&i.push("",`完整输出:${o}`),{role:"bash",parts:[{type:"text",text:i.join(`
5
+ `)}]}}function nc(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function ac(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=D(i,"type"),r=D(i,"text");if(s==="text")return r!==void 0&&r!==""?[{type:"text",text:r}]:[];if(s==="thinking"){const o=D(i,"thinking")??r;return o!==void 0&&o!==""?[{type:"thinking",text:o}]:[]}if(s==="toolCall"){const o=D(i,"name")??"tool",n=ee(i,"arguments"),a=o==="read"?cc(D(n,"path")):void 0;if(a!==void 0)return[{type:"skillRead",...a}];const c=D(i,"id");return[{type:"toolCall",...c===void 0?{}:{toolCallId:c},toolName:o,summary:$t(n),...n===void 0?{}:{args:n}}]}return s==="image"?[{type:"text",text:"[image]"}]:ar(i)}).map(i=>i.type==="text"&&D(t,"role")==="toolResult"?lc(i.text,t):i):ar(e)}function lc(e,t){const i=D(t,"toolCallId"),s=ee(t,"content"),r=ee(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:D(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...r===void 0?{}:{details:r},isError:Ut(t,"isError")===!0}}function cc(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 dc(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=pc(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&&hc(t,c,a)){i.delete(a.toolCallId??"");continue}}r.push(a)}n()}return t}function pc(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 hc(e,t,i){const s=e[t.lineIndex],r=s?.parts[t.partIndex];if(s===void 0||r?.type!=="toolExecution")return!1;const o=Zt(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 Zt(e){const t=ee(e,"preview");if(!hs(t))return;const i=D(t,"diff"),s=D(t,"error"),r=fc(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 ar(e){return e==null?[]:typeof e=="object"?[{type:"text",text:$t(e)}]:[{type:"text",text:Xt(e)}]}function $t(e){if(!hs(e))return Xt(e);const t=D(e,"command");if(t!==void 0)return t;const i=D(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} 处编辑`:Object.entries(e).filter(([,o])=>o!=null).slice(0,3).map(([o,n])=>`${o}: ${uc(n)}`).join(" · ")}function uc(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)} 项`:typeof e=="object"&&e!==null?"object":""}function hs(e){return typeof e=="object"&&e!==null}function ee(e,t){return hs(e)?e[t]:void 0}function D(e,t){const i=ee(e,t);return typeof i=="string"?i:void 0}function Ut(e,t){const i=ee(e,t);return typeof i=="boolean"?i:void 0}function fc(e,t){const i=ee(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function Xt(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const mc="pi-web:prompt-draft:";function Yt(e){return`${mc}${e}`}function hi(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function Po(e,t=hi()){try{return t?.getItem(Yt(e))??""}catch{return""}}function ei(e,t,i=hi()){try{t?i?.setItem(Yt(e),t):i?.removeItem(Yt(e))}catch{}}function us(e,t=hi()){try{t?.removeItem(Yt(e))}catch{}}function gc(e,t,i=hi()){const s=Po(e,i);s!==""&&(ei(t,s,i),us(e,i))}function vc(e,t){return ve("bash",`${t===!0?`不加入上下文
6
6
 
7
- `:""}$ ${e}`)}function hc(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,ve("bash",t)];const r=fc(s.text)?"":`
7
+ `:""}$ ${e}`)}function bc(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,ve("bash",t)];const r=yc(s.text)?"":`
8
8
 
9
- `;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+r+t}]}]}function uc(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 wc(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 fc(e){const t=e.lastIndexOf(`
14
+ `)}`}]}]}function yc(e){const t=e.lastIndexOf(`
15
15
 
16
- `),i=e.lastIndexOf("$ ");return t>i}function mc(e,t){if(t.type==="message.append")return Pc(e,t.message);if(t.type==="assistant.delta")return Hl(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return ql(e,t.text);if(t.type==="tool.start")return wc(e,t);if(t.type==="tool.update")return xo(e,t.toolCallId,i=>yc(i,t));if(t.type==="tool.end")return yo(e,t.toolCallId,t.toolName,$t(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,pc(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return hc(e,t.chunk);if(t.type==="shell.end")return uc(e,t);if(t.type==="command.output")return[...e,ve(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,ve("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:gc(e,t.message)}function gc(e,t){const i=xc(t);if(i!==void 0)return yo(e,i.toolCallId,i.toolName,$t(i.content),i.text,i.isError,i.content,i.details);const s=ds(t)[0];if(s===void 0)return;const r=s.role==="assistant"?vc(s):s;if(r.parts.length===0)return e;const o=Sc(e,r);if(o>=0)return[...e.slice(0,o),r,...e.slice(o+1)];const n=e.at(-1);return n?.role!==r.role?[...e,r]:r.role==="assistant"||$c(n,r)?[...e.slice(0,-1),r]:[...e,r]}function vc(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function bc(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 wc(e,t){const i=t.toolName==="read"?bc(We(t.args,"path")):void 0;if(i!==void 0)return Tc(e,{role:"skill",parts:[{type:"skillRead",...i}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||$t(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function yc(e,t){const i=Zt(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 yo(e,t,i,s,r,o,n,a){const c=xo(e,t,h=>{const u=Zt(a)??h.preview;return{...h,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...u===void 0?{}:{preview:u}}});if(c!==e)return c;const p=Zt(a),f={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:[f]}]}function xo(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 xc(e){if(We(e,"role")!=="toolResult")return;const t=We(e,"toolCallId"),i=ii(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:We(e,"toolName")??"tool",text:So(i),isError:Ic(e,"isError")===!0,content:i,details:ii(e,"details")}}function So(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(So).filter(t=>t!=="").join(`
17
- `);if(typeof e=="object"&&e!==null){const t=We(e,"text")??We(e,"content")??We(e,"output");if(t!==void 0)return t}return""}function Sc(e,t){const i=ti(t);if(i.length===0)return-1;for(let s=e.length-1;s>=0;s--){const r=e[s];if(r?.role!=="skill")continue;const o=ti(r);if(ko(o,i))return s}return-1}function ti(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function ko(e,t){return e.length===t.length&&e.every((i,s)=>kc(i,t[s]))}function kc(e,t){return t===void 0?!1:ar(e.path)===ar(t.path)||e.name===t.name}function ar(e){return e.replace(/\\/g,"/")}function $c(e,t){return lr(e)===lr(t)}function lr(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
16
+ `),i=e.lastIndexOf("$ ");return t>i}function xc(e,t){if(t.type==="message.append")return Rc(e,t.message);if(t.type==="assistant.delta")return Ql(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return Zl(e,t.text);if(t.type==="tool.start")return Pc(e,t);if(t.type==="tool.update")return Co(e,t.toolCallId,i=>Tc(i,t));if(t.type==="tool.end")return To(e,t.toolCallId,t.toolName,$t(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,vc(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return bc(e,t.chunk);if(t.type==="shell.end")return wc(e,t);if(t.type==="command.output")return[...e,ve(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,ve("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:Sc(e,t.message)}function Sc(e,t){const i=Cc(t);if(i!==void 0)return To(e,i.toolCallId,i.toolName,$t(i.content),i.text,i.isError,i.content,i.details);const s=ps(t)[0];if(s===void 0)return;const r=s.role==="assistant"?kc(s):s;if(r.parts.length===0)return e;const o=Ic(e,r);if(o>=0)return[...e.slice(0,o),r,...e.slice(o+1)];const n=e.at(-1);return n?.role!==r.role?[...e,r]:r.role==="assistant"||Ac(n,r)?[...e.slice(0,-1),r]:[...e,r]}function kc(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function $c(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 Pc(e,t){const i=t.toolName==="read"?$c(We(t.args,"path")):void 0;if(i!==void 0)return Ec(e,{role:"skill",parts:[{type:"skillRead",...i}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||$t(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function Tc(e,t){const i=Zt(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 To(e,t,i,s,r,o,n,a){const c=Co(e,t,h=>{const u=Zt(a)??h.preview;return{...h,status:o?"error":"success",resultText:r,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...u===void 0?{}:{preview:u}}});if(c!==e)return c;const p=Zt(a),f={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:[f]}]}function Co(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 Cc(e){if(We(e,"role")!=="toolResult")return;const t=We(e,"toolCallId"),i=ii(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:We(e,"toolName")??"tool",text:Io(i),isError:_c(e,"isError")===!0,content:i,details:ii(e,"details")}}function Io(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Io).filter(t=>t!=="").join(`
17
+ `);if(typeof e=="object"&&e!==null){const t=We(e,"text")??We(e,"content")??We(e,"output");if(t!==void 0)return t}return""}function Ic(e,t){const i=ti(t);if(i.length===0)return-1;for(let s=e.length-1;s>=0;s--){const r=e[s];if(r?.role!=="skill")continue;const o=ti(r);if(Mo(o,i))return s}return-1}function ti(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function Mo(e,t){return e.length===t.length&&e.every((i,s)=>Mc(i,t[s]))}function Mc(e,t){return t===void 0?!1:lr(e.path)===lr(t.path)||e.name===t.name}function lr(e){return e.replace(/\\/g,"/")}function Ac(e,t){return cr(e)===cr(t)}function cr(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
18
18
 
19
- `)}function Pc(e,t){const i=ds(t);return i.length===0?e:[...e,...i]}function Tc(e,t){const i=e.at(-1);return t.role==="skill"&&ko(ti(i),ti(t))?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Cc(e){return typeof e=="object"&&e!==null}function ii(e,t){return Cc(e)?e[t]:void 0}function We(e,t){const i=ii(e,t);return typeof i=="string"?i:void 0}function Ic(e,t){const i=ii(e,t);return typeof i=="boolean"?i:void 0}const Mc="pi-web:chat-history:v2:",Ac=1800*1e3;function Rc(e){try{const t=sessionStorage.getItem(qi(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!Lc(i))return;if(Date.now()-i.savedAt>Ac){sessionStorage.removeItem(qi(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function Ec(e,t){try{sessionStorage.setItem(qi(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Dc(e,t){if(e===void 0||!Vi(e))return t;if(!Vi(t))return e;if(_c(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 cr(r,i,e),cr(r,i,t),Oc(r)?t:{start:i,total:Math.max(e.total,t.total),messages:r}}function _c(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Oc(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function cr(e,t,i){i.messages.forEach((s,r)=>{e[i.start-t+r]=s})}function qi(e){return`${Mc}${e}`}function Lc(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"&&Vi({messages:t,start:i,total:s})}function Vi(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(Wc)}function Wc(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 jc={read:Rc,write:Ec};class Nc{constructor(t=jc){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return dr(this.rawHistoryPage(t))}mergeHistory(t,i){const s=Dc(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),dr(s)}applyLiveEvent(t,i){return mc(t,i)}rawHistoryPage(t){const i=this.rawHistoryPages.get(t)??this.cache.read(t);return i!==void 0&&this.rawHistoryPages.set(t,i),i}}function dr(e){const t=e?.start??0;return{messages:Ul(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function us(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:$o(e).startsWith("/")?{kind:"command"}:Fc(e)?{kind:"file"}:{kind:"normal"}}function Bc(e){return us(e).kind==="shell"}function $o(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
20
- `))+1;return e.slice(t)}function Fc(e){const t=$o(e);if(t.startsWith("@")||t.startsWith("!@"))return!0;const i=e.length-t.length;if(e.slice(0,i).endsWith("@ "))return!0;const s=e.lastIndexOf('"');if(s===-1)return!1;const r=e.slice(0,s);return r.endsWith("@")||r.endsWith("@ ")||r.endsWith("!@")}class zc{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,r="local"){this.close(),this.machineId=r,this.sessionId=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),To(this.socket),this.socket=void 0,this.sessionId=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.sessionId===void 0||this.sessionId===""||!this.shouldReconnect)return;const t=wl(this.sessionId,this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Po(t);Uc(i)&&this.onEvent?.(i)}}class pr{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),To(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=yl(this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Po(t);qc(i)&&this.onEvent?.(i)}}function Uc(e){const t=fs(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","pi.event"].includes(t)}function Hc(e){const t=fs(e);return t==="status.update"||t==="activity.update"||t==="session.name"}function qc(e){const t=fs(e);return Hc(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function fs(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Po(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 To(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()}}class Vc{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)}}function Kc(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return Jc(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 Gc(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function Jc(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function Qc(e,t,i){return Co(e,[t],i)}function Co(e,t,i){const s=new Set(t);return e.map(r=>s.has(r.id)?{...r,archived:!0,archivedAt:i}:r)}function Zc(e,t,i){return Io(e,t,[i])}function Io(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 ct=100;class Xc{constructor(t,i,s,r=new Vc,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=o.socket??new zc,this.api=o.api??_,this.transcripts=o.transcripts??new Nc}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0})}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();Gc(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=m(this.getState()),s=await this.api.startSession(t.path,i);rr(s,i);const r=Hi(s,i);this.setState({sessions:[r,...this.getState().sessions]}),await this.selectSession(r)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return Kc(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const r=this.sessionCacheKey(t.id),o=this.transcripts.cachedView(r);this.setState({selectedSession:t,...o,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const h=await this.api.messages(t.id,{limit:ct},m(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const u=this.transcripts.mergeHistory(r,h);this.setState({...u,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t.id,h=>n.push(h),()=>{this.refreshSelectedSession(t.id)},m(this.getState()));const[a,c]=await Promise.all([this.api.messages(t.id,{limit:ct},m(this.getState())),this.api.status(t.id,m(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(r,a),f=c.isStreaming;this.catchupStreamSessionId=f?t.id:void 0,this.setState({...p,isLoadingEarlierMessages:!1,isReceivingPartialStream:f,status:c,activity:this.getState().sessionActivities[t.id]}),this.applyStatus(c);for(const h of n)this.applyEvent(h);this.socket.setHandler(h=>{this.applyEvent(h)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(ke(t)&&sd(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.id,{before:t.messagePageStart,limit:ct},m(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){if(t.trim().startsWith("/"))return this.runCommand(t);if(Bc(t))return this.runShell(t);const r=this.getState().selectedSession;if(!(!r||r.archived===!0))try{await this.api.prompt(r.id,t,i,m(this.getState())),this.markCachedNewSessionPersisted(r)}catch(o){this.setState({error:String(o)})}}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,ve("user",t)]});try{await this.api.shell(i.id,t,m(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,ve("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,ve("user",t)]});try{this.applyCommandResult(await this.api.runCommand(i.id,t,m(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,ve("system",String(s))],error:String(s)})}}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s.id,t,i,m(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(ke(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t.id,m(this.getState()));const i=this.getState(),s=Qc(i.sessions,t.id,new Date().toISOString()),r=Zc(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||ke(t)))try{const i=await this.api.archiveWithDescendants(t.id,m(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],r=this.getState(),o=Co(r.sessions,s,new Date().toISOString()),n=Io(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 deleteCachedNewSession(t=this.getState().selectedSession){if(!ke(t))return;this.api.stop(t.id,m(this.getState())).catch(()=>{}),or(t.id,m(this.getState())),hs(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.id,m(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 detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t.id,m(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.id,m(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.id,t,i,m(this.getState())))}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.id,t,m(this.getState())))}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.id,m(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i.id,t,m(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.id,m(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t.id,m(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingTranscriptEvents();const[s,r]=await Promise.all([this.api.messages(t,{limit:ct},m(this.getState())),this.api.status(t,m(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],isReceivingPartialStream:r.isStreaming}),this.applyStatus(r)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}sessionCacheKey(t){return bo(m(this.getState()),t)}workspaceSelectionKey(t){return`${m(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=m(this.getState()),r=await this.api.startSession(t.cwd,s);rr(r,s),dc(this.sessionCacheKey(t.id),this.sessionCacheKey(r.id)),or(t.id,s);const o=Hi(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(!ke(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(jl(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,ve(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&ei(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)}}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"&&!pi(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...ed(i,t.sessionId,t.messageCount),...s?{sessionActivities:Yc(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),this.catchupStreamSessionId===t.sessionId&&!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(td(t))return}if(id(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}finishStreamCatchup(t){this.catchupStreamSessionId===t&&(this.catchupStreamSessionId=void 0,this.getState().selectedSession?.id===t&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=await this.api.messages(t,{limit:ct},m(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),i))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function Yc(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function ed(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 td(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 id(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function sd(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class rd{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)}}function od(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 nd{constructor(t,i,s,r,o=new rd,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=r,this.workspaceSelection=o,this.api=n.api??_}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...zt()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(ki(m(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=m(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...zt()});try{const r=await this.api.workspaces(t.id,s);if(m(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=od(r,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(ki(s,t.id))});o?await this.selectWorkspace(o,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){m(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(r),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=m(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:ki(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...zt()});try{const r=Wl(t.path,await this.api.sessions(t.path,s),s);if(m(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){m(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,m(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=ld(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 ad(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function ld(e){return e.find(t=>t.isMain)??e[0]}class cd{constructor(){this.snapshotsByMachine=new Map}latest(t){const i=this.snapshotsByMachine.get(t);return i===void 0?void 0:fr(i)}remember(t){this.snapshotsByMachine.set(t.machineId,fr(t))}forget(t){this.snapshotsByMachine.delete(t)}}function dd(e){return{machineId:e,surface:{}}}function hr(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??vo,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,tool:e.workspaceTool,view:e.mainView,surface:{selectedFilePath:t?e.selectedFilePath:void 0,selectedDiffPath:t?e.selectedDiffPath:void 0,selectedTerminalId:t?e.selectedTerminalId:void 0}}}function ur(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view==="navigation"?void 0:e.view}}function fr(e){return{...e,surface:{...e.surface}}}class pd{constructor(){this.terminalIdsByCwd=new Map}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 ug(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 fg(e){return e.find(t=>!t.exited)??e[0]}const hd=1200;class ud{constructor(){this.pendingTokens=[]}handle(t,i){const s=fd(t);if(s===void 0||!mr(s))return!1;const r=i.filter(c=>c.shortcut!==void 0&&c.enabled!==!1).map(c=>({action:c,tokens:Ao(c.shortcut??"")})).filter(c=>c.tokens.length>0),o=this.pendingTokens.length>0&&!mr(s)?[...this.pendingTokens,s]:[s],n=r.find(c=>gd(c.tokens,o));return n!==void 0?(this.clearPending(),n.action.run(),!0):r.some(c=>Ro(c.tokens,o))?(this.setPending(o),!0):(this.clearPending(),!1)}reset(){this.clearPending()}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=window.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},hd)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(window.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Mo(e){return Ao(e).map(t=>t.split("+").map(i=>i==="mod"?gr()?"⌘":"Ctrl":i==="shift"?"Shift":i==="alt"?gr()?"⌥":"Alt":i==="ctrl"?"Ctrl":i==="enter"?"Enter":i==="escape"?"Esc":i==="."?".":i.length===1?i.toUpperCase():`${i.charAt(0).toUpperCase()}${i.slice(1)}`).join("+")).join(" ")}function fd(e){if(e.isComposing)return;const t=md(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 Ao(e){return e.trim().toLowerCase().split(/\s+/u).filter(t=>t!=="").map(t=>t.split("+").filter(i=>i!=="").join("+"))}function md(e){if(e===" ")return"space";if(e.length===1)return e.toLowerCase();const t=e.toLowerCase();if(["enter","escape","tab","arrowup","arrowdown","arrowleft","arrowright","backspace","delete"].includes(t))return t}function gd(e,t){return e.length===t.length&&Ro(e,t)}function Ro(e,t){return t.every((i,s)=>e[s]===i)}function mr(e){return e.includes("+")}function gr(){return navigator.userAgent.toLowerCase().includes("mac")}const ms="themes:classic",vd="themes:pi-web-dark",bd={themeId:vd,auto:!0},Eo="pi-web-app-theme",wd=["--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"],yd=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function xd(){try{const e=window.localStorage.getItem(Eo);return e===null?void 0:Td(e)}catch{return}}function Sd(e){try{window.localStorage.setItem(Eo,JSON.stringify(e))}catch{}}function kd(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of wd){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function $d(e){const t=Pd(e.themes,e.fallbackThemeId??ms),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=Do(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 Pd(e,t=ms){return e.find(i=>i.id===t)??e[0]}function Do(e,t){return e.find(i=>i.light===t||i.dark===t)}function Td(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return Cd(i)?i:void 0}catch{return}}function Cd(e){if(!Id(e))return!1;const t=e.themeId,i=e.auto;return Md(t)&&typeof i=="boolean"}function Id(e){return typeof e=="object"&&e!==null}function Md(e){return typeof e=="string"&&yd.test(e)}const _o="workspace.delete",Oo="pi.operation",Lo="target.workspaceId",Ad="target.workspacePath";function Rd(e){return{[Oo]:_o,[Lo]:e.id,[Ad]:e.path}}function Ed(e){return{...e===void 0?{}:{projectId:e},metadata:{[Oo]:_o}}}function Dd(e){const t={};for(const i of e){const s=Ki(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 _d(e){return Object.entries(e).filter(([,t])=>si(t)).map(([t])=>t)}function Wo(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&si(i)}function Ki(e){return e.metadata[Lo]}function si(e){return e.status==="queued"||e.status==="running"}function Od(){return[{id:"actions.show",title:"显示操作",description:"打开命令面板",shortcut:"mod+k",group:"通用",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"聚焦提示词输入框",description:"将键盘焦点移动到消息编辑器",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.refresh-data",title:"刷新应用数据",description:"刷新会话、状态、活动和当前工作区界面,不重新加载页面",group:"通用",run:e=>e.refreshAppData()},{id:"app.reload-page",title:"完整重载页面",description:"重新加载 PI WEB 浏览器页面",group:"通用",run:e=>{e.reloadPage()}},{id:"view.chat",title:"转到聊天",shortcut:"mod+1",group:"导航",run:e=>{e.selectMainView("chat")}},{id:"view.files",title:"转到文件",shortcut:"mod+2",group:"导航",enabled:dt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:vr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:dt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:dt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:vr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:dt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"删除工作区",description:"移除所选 Git worktree",group:"工作区",enabled:Ld,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:dt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:Wd,run:e=>e.archiveSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:jd,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&pi(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function dt(e){return e.state.selectedWorkspace!==void 0}function vr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Ld(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!Wo(e.state,t)}function Wd(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!ke(t)}function jd(e){return ke(e.state.selectedSession)}const Nd="modulepreload",Bd=function(e){return"/"+e},br={},jo=function(t,i,s){let r=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(f=>Promise.resolve(f).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=Bd(p),p in br)return;br[p]=!0;const f=p.endsWith(".css"),h=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const u=document.createElement("link");if(u.rel=f?"stylesheet":Nd,f||(u.as="script"),u.crossOrigin="",u.href=p,a&&u.setAttribute("nonce",a),document.head.appendChild(u),f)return new Promise((v,S)=>{u.addEventListener("load",v),u.addEventListener("error",()=>S(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)})},Fd=10*1024*1024,zd="10 MB";function Ud(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:Ht(e)}function Ht(e){switch(e){case"navigation":return Xe`
19
+ `)}function Rc(e,t){const i=ps(t);return i.length===0?e:[...e,...i]}function Ec(e,t){const i=e.at(-1);return t.role==="skill"&&Mo(ti(i),ti(t))?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Dc(e){return typeof e=="object"&&e!==null}function ii(e,t){return Dc(e)?e[t]:void 0}function We(e,t){const i=ii(e,t);return typeof i=="string"?i:void 0}function _c(e,t){const i=ii(e,t);return typeof i=="boolean"?i:void 0}const Oc="pi-web:chat-history:v2:",Lc=1800*1e3;function Wc(e){try{const t=sessionStorage.getItem(qi(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!zc(i))return;if(Date.now()-i.savedAt>Lc){sessionStorage.removeItem(qi(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function jc(e,t){try{sessionStorage.setItem(qi(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Nc(e,t){if(e===void 0||!Vi(e))return t;if(!Vi(t))return e;if(Bc(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 dr(r,i,e),dr(r,i,t),Fc(r)?t:{start:i,total:Math.max(e.total,t.total),messages:r}}function Bc(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Fc(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function dr(e,t,i){i.messages.forEach((s,r)=>{e[i.start-t+r]=s})}function qi(e){return`${Oc}${e}`}function zc(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"&&Vi({messages:t,start:i,total:s})}function Vi(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(Uc)}function Uc(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 Hc={read:Wc,write:jc};class qc{constructor(t=Hc){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return pr(this.rawHistoryPage(t))}mergeHistory(t,i){const s=Nc(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),pr(s)}applyLiveEvent(t,i){return xc(t,i)}rawHistoryPage(t){const i=this.rawHistoryPages.get(t)??this.cache.read(t);return i!==void 0&&this.rawHistoryPages.set(t,i),i}}function pr(e){const t=e?.start??0;return{messages:Jl(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function fs(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:Ao(e).startsWith("/")?{kind:"command"}:Kc(e)?{kind:"file"}:{kind:"normal"}}function Vc(e){return fs(e).kind==="shell"}function Ao(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
20
+ `))+1;return e.slice(t)}function Kc(e){const t=Ao(e);if(t.startsWith("@")||t.startsWith("!@"))return!0;const i=e.length-t.length;if(e.slice(0,i).endsWith("@ "))return!0;const s=e.lastIndexOf('"');if(s===-1)return!1;const r=e.slice(0,s);return r.endsWith("@")||r.endsWith("@ ")||r.endsWith("!@")}class Gc{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,r="local"){this.close(),this.machineId=r,this.sessionId=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),Eo(this.socket),this.socket=void 0,this.sessionId=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.sessionId===void 0||this.sessionId===""||!this.shouldReconnect)return;const t=Pl(this.sessionId,this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Ro(t);Jc(i)&&this.onEvent?.(i)}}class hr{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Eo(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Tl(this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await Ro(t);Zc(i)&&this.onEvent?.(i)}}function Jc(e){const t=ms(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","pi.event"].includes(t)}function Qc(e){const t=ms(e);return t==="status.update"||t==="activity.update"||t==="session.name"}function Zc(e){const t=ms(e);return Qc(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function ms(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function Ro(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 Eo(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()}}class Xc{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)}}function Yc(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return td(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 ed(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function td(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function id(e,t,i){return Do(e,[t],i)}function Do(e,t,i){const s=new Set(t);return e.map(r=>s.has(r.id)?{...r,archived:!0,archivedAt:i}:r)}function sd(e,t,i){return _o(e,t,[i])}function _o(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 ct=100;class rd{constructor(t,i,s,r=new Xc,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=r,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=o.socket??new Gc,this.api=o.api??_,this.transcripts=o.transcripts??new qc}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0})}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();ed(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=m(this.getState()),s=await this.api.startSession(t.path,i);or(s,i);const r=Hi(s,i);this.setState({sessions:[r,...this.getState().sessions]}),await this.selectSession(r)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return Yc(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const r=this.sessionCacheKey(t.id),o=this.transcripts.cachedView(r);this.setState({selectedSession:t,...o,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const h=await this.api.messages(t.id,{limit:ct},m(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const u=this.transcripts.mergeHistory(r,h);this.setState({...u,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t.id,h=>n.push(h),()=>{this.refreshSelectedSession(t.id)},m(this.getState()));const[a,c]=await Promise.all([this.api.messages(t.id,{limit:ct},m(this.getState())),this.api.status(t.id,m(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(r,a),f=c.isStreaming;this.catchupStreamSessionId=f?t.id:void 0,this.setState({...p,isLoadingEarlierMessages:!1,isReceivingPartialStream:f,status:c,activity:this.getState().sessionActivities[t.id]}),this.applyStatus(c);for(const h of n)this.applyEvent(h);this.socket.setHandler(h=>{this.applyEvent(h)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(ke(t)&&cd(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.id,{before:t.messagePageStart,limit:ct},m(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){if(t.trim().startsWith("/"))return this.runCommand(t);if(Vc(t))return this.runShell(t);const r=this.getState().selectedSession;if(!(!r||r.archived===!0))try{await this.api.prompt(r.id,t,i,m(this.getState())),this.markCachedNewSessionPersisted(r)}catch(o){this.setState({error:String(o)})}}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,ve("user",t)]});try{await this.api.shell(i.id,t,m(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,ve("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,ve("user",t)]});try{this.applyCommandResult(await this.api.runCommand(i.id,t,m(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,ve("system",String(s))],error:String(s)})}}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s.id,t,i,m(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(ke(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t.id,m(this.getState()));const i=this.getState(),s=id(i.sessions,t.id,new Date().toISOString()),r=sd(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||ke(t)))try{const i=await this.api.archiveWithDescendants(t.id,m(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],r=this.getState(),o=Do(r.sessions,s,new Date().toISOString()),n=_o(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 deleteCachedNewSession(t=this.getState().selectedSession){if(!ke(t))return;this.api.stop(t.id,m(this.getState())).catch(()=>{}),nr(t.id,m(this.getState())),us(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.id,m(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 detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t.id,m(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.id,m(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.id,t,i,m(this.getState())))}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.id,t,m(this.getState())))}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.id,m(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i.id,t,m(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.id,m(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t.id,m(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingTranscriptEvents();const[s,r]=await Promise.all([this.api.messages(t,{limit:ct},m(this.getState())),this.api.status(t,m(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],isReceivingPartialStream:r.isStreaming}),this.applyStatus(r)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}sessionCacheKey(t){return $o(m(this.getState()),t)}workspaceSelectionKey(t){return`${m(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=m(this.getState()),r=await this.api.startSession(t.cwd,s);or(r,s),gc(this.sessionCacheKey(t.id),this.sessionCacheKey(r.id)),nr(t.id,s);const o=Hi(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(!ke(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Hl(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,ve(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&ei(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)}}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"&&!pi(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...nd(i,t.sessionId,t.messageCount),...s?{sessionActivities:od(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),this.catchupStreamSessionId===t.sessionId&&!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(ad(t))return}if(ld(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}finishStreamCatchup(t){this.catchupStreamSessionId===t&&(this.catchupStreamSessionId=void 0,this.getState().selectedSession?.id===t&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=await this.api.messages(t,{limit:ct},m(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),i))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function od(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function nd(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 ad(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 ld(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function cd(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class dd{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)}}function pd(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 hd{constructor(t,i,s,r,o=new dd,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=r,this.workspaceSelection=o,this.api=n.api??_}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...zt()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(ki(m(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=m(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...zt()});try{const r=await this.api.workspaces(t.id,s);if(m(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=pd(r,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(ki(s,t.id))});o?await this.selectWorkspace(o,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(r){m(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(r),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=m(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:ki(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...zt()});try{const r=Ul(t.path,await this.api.sessions(t.path,s),s);if(m(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){m(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,m(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=fd(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 ud(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function fd(e){return e.find(t=>t.isMain)??e[0]}class md{constructor(){this.snapshotsByMachine=new Map}latest(t){const i=this.snapshotsByMachine.get(t);return i===void 0?void 0:mr(i)}remember(t){this.snapshotsByMachine.set(t.machineId,mr(t))}forget(t){this.snapshotsByMachine.delete(t)}}function gd(e){return{machineId:e,surface:{}}}function ur(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??ko,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 fr(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view==="navigation"?void 0:e.view}}function mr(e){return{...e,surface:{...e.surface}}}class vd{constructor(){this.terminalIdsByCwd=new Map}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 xg(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 Sg(e){return e.find(t=>!t.exited)??e[0]}const bd=1200;class wd{constructor(){this.pendingTokens=[]}handle(t,i){const s=yd(t);if(s===void 0||!gr(s))return!1;const r=i.filter(c=>c.shortcut!==void 0&&c.enabled!==!1).map(c=>({action:c,tokens:Lo(c.shortcut??"")})).filter(c=>c.tokens.length>0),o=this.pendingTokens.length>0&&!gr(s)?[...this.pendingTokens,s]:[s],n=r.find(c=>Sd(c.tokens,o));return n!==void 0?(this.clearPending(),n.action.run(),!0):r.some(c=>Wo(c.tokens,o))?(this.setPending(o),!0):(this.clearPending(),!1)}reset(){this.clearPending()}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=window.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},bd)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(window.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Oo(e){return Lo(e).map(t=>t.split("+").map(i=>i==="mod"?vr()?"⌘":"Ctrl":i==="shift"?"Shift":i==="alt"?vr()?"⌥":"Alt":i==="ctrl"?"Ctrl":i==="enter"?"Enter":i==="escape"?"Esc":i==="."?".":i.length===1?i.toUpperCase():`${i.charAt(0).toUpperCase()}${i.slice(1)}`).join("+")).join(" ")}function yd(e){if(e.isComposing)return;const t=xd(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 Lo(e){return e.trim().toLowerCase().split(/\s+/u).filter(t=>t!=="").map(t=>t.split("+").filter(i=>i!=="").join("+"))}function xd(e){if(e===" ")return"space";if(e.length===1)return e.toLowerCase();const t=e.toLowerCase();if(["enter","escape","tab","arrowup","arrowdown","arrowleft","arrowright","backspace","delete"].includes(t))return t}function Sd(e,t){return e.length===t.length&&Wo(e,t)}function Wo(e,t){return t.every((i,s)=>e[s]===i)}function gr(e){return e.includes("+")}function vr(){return navigator.userAgent.toLowerCase().includes("mac")}const gs="themes:classic",kd="themes:pi-web-dark",$d={themeId:kd,auto:!0},jo="pi-web-app-theme",Pd=["--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"],Td=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Cd(){try{const e=window.localStorage.getItem(jo);return e===null?void 0:Ed(e)}catch{return}}function Id(e){try{window.localStorage.setItem(jo,JSON.stringify(e))}catch{}}function Md(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of Pd){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function Ad(e){const t=Rd(e.themes,e.fallbackThemeId??gs),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=No(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 Rd(e,t=gs){return e.find(i=>i.id===t)??e[0]}function No(e,t){return e.find(i=>i.light===t||i.dark===t)}function Ed(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return Dd(i)?i:void 0}catch{return}}function Dd(e){if(!_d(e))return!1;const t=e.themeId,i=e.auto;return Od(t)&&typeof i=="boolean"}function _d(e){return typeof e=="object"&&e!==null}function Od(e){return typeof e=="string"&&Td.test(e)}const Ld="management";function Wd(e){return jd(Nd())===Ld}function jd(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function Nd(){return typeof window>"u"?void 0:window.location.search}const Bo="workspace.delete",Fo="pi.operation",zo="target.workspaceId",Bd="target.workspacePath";function Fd(e){return{[Fo]:Bo,[zo]:e.id,[Bd]:e.path}}function zd(e){return{...e===void 0?{}:{projectId:e},metadata:{[Fo]:Bo}}}function Ud(e){const t={};for(const i of e){const s=Ki(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 Hd(e){return Object.entries(e).filter(([,t])=>si(t)).map(([t])=>t)}function Uo(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&si(i)}function Ki(e){return e.metadata[zo]}function si(e){return e.status==="queued"||e.status==="running"}function br(){return[{id:"actions.show",title:"显示操作",description:"打开命令面板",shortcut:"mod+k",group:"通用",run:e=>{e.openActionPalette()}},{id:"prompt.focus",title:"聚焦提示词输入框",description:"将键盘焦点移动到消息编辑器",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.refresh-data",title:"刷新应用数据",description:"刷新会话、状态、活动和当前工作区界面,不重新加载页面",group:"通用",run:e=>e.refreshAppData()},{id:"app.reload-page",title:"完整重载页面",description:"重新加载 PI WEB 浏览器页面",group:"通用",run:e=>{e.reloadPage()}},{id:"view.chat",title:"转到聊天",shortcut:"mod+1",group:"导航",run:e=>{e.selectMainView("chat")}},{id:"view.files",title:"转到文件",shortcut:"mod+2",group:"导航",enabled:dt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:wr,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:dt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:dt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:wr,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:dt,run:e=>e.state.workspaceTool==="core:workspace.git"&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:"workspace.delete",title:"删除工作区",description:"移除所选 Git worktree",group:"工作区",enabled:qd,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:dt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:Vd,run:e=>e.archiveSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:Kd,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&pi(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function dt(e){return e.state.selectedWorkspace!==void 0}function wr(e){return e.state.selectedWorkspace?.isGitRepo===!0}function qd(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!Uo(e.state,t)}function Vd(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!ke(t)}function Kd(e){return ke(e.state.selectedSession)}const Gd="modulepreload",Jd=function(e){return"/"+e},yr={},Ho=function(t,i,s){let r=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(f=>Promise.resolve(f).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=Jd(p),p in yr)return;yr[p]=!0;const f=p.endsWith(".css"),h=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const u=document.createElement("link");if(u.rel=f?"stylesheet":Gd,f||(u.as="script"),u.crossOrigin="",u.href=p,a&&u.setAttribute("nonce",a),document.head.appendChild(u),f)return new Promise((v,S)=>{u.addEventListener("load",v),u.addEventListener("error",()=>S(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)})},Qd=10*1024*1024,Zd="10 MB";function Xd(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:Ht(e)}function Ht(e){switch(e){case"navigation":return Xe`
21
21
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
22
22
  <circle cx="6" cy="7" r="1.5"></circle>
23
23
  <path d="M10 7h8"></path>
@@ -51,7 +51,7 @@ ${r.join(`
51
51
  <path d="m7 10 3 3-3 3"></path>
52
52
  <path d="M12 16h5"></path>
53
53
  </svg>
54
- `}}function Hd(){return[{id:"workspace.files",title:"文件",icon:Ht("files"),order:10,render:qd},{id:"workspace.git",title:"Git",icon:Ht("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:Qd},{id:"workspace.terminal",title:"终端",icon:Ht("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Jd}]}function qd(e){return l`
54
+ `}}function xr(){return[{id:"workspace.files",title:"文件",icon:Ht("files"),order:10,render:Yd},{id:"workspace.git",title:"Git",icon:Ht("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:rp},{id:"workspace.terminal",title:"终端",icon:Ht("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:sp}]}function Yd(e){return l`
55
55
  <section class="toolbar">
56
56
  <strong>文件</strong>
57
57
  ${e.fileTreeStale?l`<span class="stale">过期</span>`:null}
@@ -59,30 +59,30 @@ ${r.join(`
59
59
  </section>
60
60
  <section class="split">
61
61
  <div class="list tree">
62
- ${e.fileTree.length===0?l`<p class="muted">尚未加载文件。</p>`:e.fileTree.map(t=>No(e,t,0))}
62
+ ${e.fileTree.length===0?l`<p class="muted">尚未加载文件。</p>`:e.fileTree.map(t=>qo(e,t,0))}
63
63
  </div>
64
64
  <div class="viewer">
65
- ${Kd(e)}
65
+ ${tp(e)}
66
66
  </div>
67
67
  </section>
68
- `}function No(e,t,i){const s=e.expandedDirs[t.path],r=s!==void 0,o=t.type!=="directory"&&e.selectedFilePath===t.path;return l`
69
- <button class=${o?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{Vd(e,t)}}>
68
+ `}function qo(e,t,i){const s=e.expandedDirs[t.path],r=s!==void 0,o=t.type!=="directory"&&e.selectedFilePath===t.path;return l`
69
+ <button class=${o?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{ep(e,t)}}>
70
70
  <span>${t.type==="directory"?r?"▾":"▸":"·"}</span>
71
71
  <span>${t.name}</span>
72
72
  </button>
73
- ${r?s.map(n=>No(e,n,i+1)):null}
74
- `}function Vd(e,t){t.type==="directory"?e.onExpandDir(t.path):e.onSelectFile(t.path)}function Kd(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">请选择文件。</p>`:t===void 0?l`<p class="muted">正在加载 ${e.selectedFilePath}…</p>`:t.mediaType==="image"?Gd(e,t):t.binary?l`<p class="muted">二进制文件:${t.path} · ${Gi(t.size)}</p>`:(Bo(),l`
73
+ ${r?s.map(n=>qo(e,n,i+1)):null}
74
+ `}function ep(e,t){t.type==="directory"?e.onExpandDir(t.path):e.onSelectFile(t.path)}function tp(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">请选择文件。</p>`:t===void 0?l`<p class="muted">正在加载 ${e.selectedFilePath}…</p>`:t.mediaType==="image"?ip(e,t):t.binary?l`<p class="muted">二进制文件:${t.path} · ${Gi(t.size)}</p>`:(Vo(),l`
75
75
  <div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"文本"}${t.truncated?" · 已截断":""}</small></div>
76
76
  <code-viewer .content=${t.content} .language=${t.language}></code-viewer>
77
- `)}function Gd(e,t){const i=`${t.mimeType??"image"} · ${Gi(t.size)}`;if(t.size>Fd)return l`
77
+ `)}function ip(e,t){const i=`${t.mimeType??"image"} · ${Gi(t.size)}`;if(t.size>Qd)return l`
78
78
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
79
- <p class="muted">图片过大,无法预览:${Gi(t.size)} · 限制 ${zd}</p>
80
- `;const s=cl(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
79
+ <p class="muted">图片过大,无法预览:${Gi(t.size)} · 限制 ${Zd}</p>
80
+ `;const s=ml(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
81
81
  <div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
82
82
  <div class="image-preview">
83
83
  <img src=${s} alt=${t.path} decoding="async" />
84
84
  </div>
85
- `}function Jd(e){return Yd(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Qd(e){const t=e.gitStatus;return l`
85
+ `}function sp(e){return ap(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function rp(e){const t=e.gitStatus;return l`
86
86
  <section class="toolbar">
87
87
  <strong>Git</strong>
88
88
  ${e.gitStale?l`<span class="stale">过期</span>`:null}
@@ -91,29 +91,29 @@ ${r.join(`
91
91
  <section class="split">
92
92
  <div class="list">
93
93
  ${t===void 0?l`<p class="muted">尚未加载状态。</p>`:t.isGitRepo?l`
94
- <p class="summary">${ep(t)}</p>
94
+ <p class="summary">${lp(t)}</p>
95
95
  ${t.files.length===0?l`<p class="muted">没有变更。</p>`:t.files.map(i=>l`
96
96
  <button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
97
- <span>${tp(i.index,i.workingTree)}</span>
97
+ <span>${cp(i.index,i.workingTree)}</span>
98
98
  <span>${i.path}</span>
99
99
  </button>
100
100
  `)}
101
101
  `:l`<p class="muted">不是 Git 仓库。</p>`}
102
102
  </div>
103
103
  <div class="viewer">
104
- ${Zd(e)}
104
+ ${op(e)}
105
105
  </div>
106
106
  </section>
107
- `}function Zd(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`
107
+ `}function op(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`
108
108
  <div class=${s.length===1?"diffs single":"diffs"}>
109
- ${s.map(r=>Xd(r))}
109
+ ${s.map(r=>np(r))}
110
110
  </div>
111
- `}function Xd(e){return Bo(),l`
111
+ `}function np(e){return Vo(),l`
112
112
  <section class="diff-section">
113
113
  <div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"已暂存":"未暂存"}${e.truncated?" · 已截断":""}</small></div>
114
114
  <code-viewer .content=${e.diff} .language=${"diff"}></code-viewer>
115
115
  </section>
116
- `}function Bo(){jo(()=>import("./CodeViewer-B4nxYc0g.js"),__vite__mapDeps([0,1,2,3]))}function Yd(){jo(()=>import("./TerminalPanel-htr2dU1I.js"),__vite__mapDeps([4,5,6,1,2]))}function ep(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 tp(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function Gi(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`${Ti(t)} KB`;const i=t/1024;return i<1024?`${Ti(i)} MB`:`${Ti(i/1024)} GB`}function Ti(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const ip={apiVersion:1,name:"PI WEB 核心",activate:()=>({contributions:{actions:Od(),workspacePanels:Hd()}})},sp={"--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"},rp={"--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":"#3d4a78","--pi-selection-bg":"#151b31","--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"},op={"--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"},np={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:rp},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:op},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:sp}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})};async function ap(e="/pi-web-plugins/manifest.json"){const t=await lp(e);if(t===void 0)return[];const i=[];for(const s of t.plugins)try{const r=new URL(s.module,new URL(e,window.location.href)).toString(),o=await import(r),n=dp(o,r);i.push({id:s.id,plugin:n})}catch(r){console.warn(`Failed to load PI WEB plugin ${s.module}`,r)}return i}async function lp(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 cp(await t.json())}}function cp(e){if(!ri(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!ri(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}})}}function dp(e,t){if(!ri(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!pp(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function pp(e){return ri(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function ri(e){return typeof e=="object"&&e!==null}const hp=/^[a-z][a-z0-9.-]*$/u,up=/^[a-z][a-z0-9.-]*$/u,Fo=new WeakMap,zo=new WeakMap;class fp{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;if(this.validatePluginId(i),this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);this.pluginIds.add(i);const r=s.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(r)}`);const n=s.activate({apiVersion:1,pluginId:i,html:l,svg:Xe}).contributions;for(const a of n.actions??[])this.actions.push(this.qualifyAction(i,a));for(const a of n.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,a));for(const a of n.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,a));for(const a of n.themes??[])this.themes.push(this.qualifyTheme(i,a));for(const a of n.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,a))}getActions(t){return this.actions.map(i=>{const s=mp(t,i.pluginId),r=i.enabled?.(s),o={id:i.id,pluginId:i.pluginId,localId:i.localId,title:i.title,run:()=>i.run(s)};return i.description!==void 0&&(o.description=i.description),i.shortcut!==void 0&&(o.shortcut=i.shortcut),i.group!==void 0&&(o.group=i.group),r!==void 0&&(o.enabled=r),o})}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,i){const s={machine:bp(t),state:t,workspace:i};return[...this.workspaceLabels].sort((r,o)=>(r.order??1e3)-(o.order??1e3)||r.id.localeCompare(o.id)).flatMap(r=>r.visible?.(s)===!1?[]:r.items(s))}qualifyAction(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyWorkspacePanel(t,i){const s=this.qualify(t,i.id),r=i.badge,o=i.visible;return{...i,id:s,pluginId:t,localId:i.id,...o===void 0?{}:{visible:n=>o(Ci(n,t))},...r===void 0?{}:{badge:n=>r(Ci(n,t))},render:n=>i.render(Ci(n,t))}}qualifyWorkspaceLabelContribution(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}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}`}validatePluginId(t){if(!hp.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!up.test(t))throw new Error(`Invalid contribution id: ${t}`)}}function mp(e,t){return Fo.get(e)?.(t)??e}function Ci(e,t){return zo.get(e)?.(t)??e}function gp(e,t){return Fo.set(e,t),e}function vp(e,t){return zo.set(e,t),e}function bp(e){const t=e.selectedMachine;return t!==void 0?{id:t.id,name:t.name,kind:t.kind}:{id:"local",name:"local",kind:"local"}}const wp=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function yp(){return typeof window>"u"||!("matchMedia"in window)?[]:wp.map(e=>window.matchMedia(e))}function wr(e,t=xp()){return e.some(i=>i.matches)||Sp(t)}function xp(){return typeof navigator>"u"?void 0:navigator}function Sp(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const kp=250;class $p{constructor(t=Pp()){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()},kp)}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 Pp(){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 Tp="(max-width: 760px)";class Cp{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=wr(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Ip(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??yp(),this.viewportPositionRepairer=i.viewportPositionRepairer??new $p,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=wr(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.removeEventListener("change",this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?"navigation":"chat"}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Ip(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(Tp)}function Mp(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function gs(e,t){if(e!=="none")return e??Mp(t)}function Ap(e,t){return t.isMobileLayout&&gs(t.expanded,t.state)!==e}function Rp(e,t,i){return i.isMobileLayout?gs(e,i.state)===t?"none":t:e}function Ep(e,t,i){return i?t:e}class Dp{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,t.addController(this)}hostConnected(){}expandedSection(){return gs(this.expanded,this.getState())}isCollapsed(t){return Ap(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState()})}toggle(t){this.setExpanded(Rp(this.expanded,t,{isMobileLayout:this.isMobileLayout(),state:this.getState()}))}expand(t){this.setExpanded(Ep(this.expanded,t,this.isMobileLayout()))}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}}class _p{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()}shellClass(t){return["shell",Uo(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Uo(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}function yr(){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:Op(e.get("tool")),view:Lp(e.get("view"))}}function Ii(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 Op(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Ho(e)?e:void 0}function Lp(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Ho(e)?e:void 0}function Ho(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function xr(){return Wp(new URLSearchParams(window.location.search).get("settings"))}function Mi(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 Wp(e){if(e==="general")return"general";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function jp(e,t){return t===void 0?e:e.map(i=>Np(i,t))}function Np(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?Bp(e):{...e,shortcut:i}}function Bp(e){const t={...e};return delete t.shortcut,t}function Fp(e,t){const i=t.api??Ye,s=t.pollIntervalMs??1e3,r=t.setTimeout??Up(),o=t.clearTimeout??Hp();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:zp(a,i,s,r,o)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function zp(e,t,i,s,r){return Sr(e)?Promise.resolve(e):new Promise((o,n)=>{let a,c=!1;const p=u=>{c||(c=!0,a!==void 0&&r(a),o(u))},f=u=>{c||(c=!0,a!==void 0&&r(a),n(u instanceof Error?u:new Error(String(u))))},h=()=>{t.getCommandRun(e.id).then(u=>{if(u!==void 0&&Sr(u)){p(u);return}a=s(h,i)}).catch(f)};a=s(h,i)})}function Sr(e){return e.status==="succeeded"||e.status==="failed"}function Up(){return(e,t)=>globalThis.setTimeout(e,t)}function Hp(){return e=>{globalThis.clearTimeout(e)}}function qp(e,t){return t[e.path]}function Vp(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function Kp(e,t,i){return Vo(Gp(e,t,i))}function qo(e){return Vo(Object.values(e??{}))}function Vo(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function Gp(e,t,i){const s=new Set(t.filter(o=>o.projectId===e.id).map(o=>o.path)),r=new Map;for(const o of s){const n=i[o];n!==void 0&&r.set(n.cwd,n)}for(const o of Object.values(i))(o.cwd===e.path||o.cwd.startsWith(`${e.path}/`))&&r.set(o.cwd,o);return[...r.values()]}const _t=0,Jp=120;function Pt(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?Ko():Qp(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),f=Math.min(i.right,a),h=p-i.bottom-_t,u=i.top-c-_t;return[...h<Jp&&u>h?[`bottom: ${Qe(o-i.top+_t)};`,`max-height: ${Qe(Math.max(0,u))};`]:[`top: ${Qe(i.bottom+_t)};`,`max-height: ${Qe(Math.max(0,h))};`],`right: ${Qe(Math.max(0,r-f))};`,`max-width: ${Qe(Math.max(0,f-n))};`].join(" ")}function Qp(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Ko()}function Ko(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function Qe(e){return`${String(Math.round(e))}px`}function Tt(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}const Zp=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Go(e){return e.composedPath().some(t=>Xp(t,Zp))}function Xp(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 ui(e,t){Go(e)||t()}function fi(e,t){e.key!=="Enter"&&e.key!==" "||Go(e)||(e.preventDefault(),t())}const Yp=E`
116
+ `}function Vo(){Ho(()=>import("./CodeViewer-DRxmEzh1.js"),__vite__mapDeps([0,1,2,3]))}function ap(){Ho(()=>import("./TerminalPanel-BcGKwlLZ.js"),__vite__mapDeps([4,5,6,1,2]))}function lp(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 cp(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function Gi(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`${Ti(t)} KB`;const i=t/1024;return i<1024?`${Ti(i)} MB`:`${Ti(i/1024)} GB`}function Ti(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const dp={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!Wd();return{contributions:{actions:e?br():br().filter(t=>t.id!=="view.terminal"),workspacePanels:e?xr():xr().filter(t=>t.id!=="workspace.terminal")}}}},pp={"--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"},hp={"--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":"#3d4a78","--pi-selection-bg":"#151b31","--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"},up={"--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"},fp={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:hp},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:up},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:pp}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})};async function mp(e="/pi-web-plugins/manifest.json"){const t=await gp(e);if(t===void 0)return[];const i=[];for(const s of t.plugins)try{const r=new URL(s.module,new URL(e,window.location.href)).toString(),o=await import(r),n=bp(o,r);i.push({id:s.id,plugin:n})}catch(r){console.warn(`Failed to load PI WEB plugin ${s.module}`,r)}return i}async function gp(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 vp(await t.json())}}function vp(e){if(!ri(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!ri(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}})}}function bp(e,t){if(!ri(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!wp(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function wp(e){return ri(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function ri(e){return typeof e=="object"&&e!==null}const yp=/^[a-z][a-z0-9.-]*$/u,xp=/^[a-z][a-z0-9.-]*$/u,Ko=new WeakMap,Go=new WeakMap;class Sp{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;if(this.validatePluginId(i),this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);this.pluginIds.add(i);const r=s.apiVersion;if(r!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(r)}`);const n=s.activate({apiVersion:1,pluginId:i,html:l,svg:Xe}).contributions;for(const a of n.actions??[])this.actions.push(this.qualifyAction(i,a));for(const a of n.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,a));for(const a of n.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,a));for(const a of n.themes??[])this.themes.push(this.qualifyTheme(i,a));for(const a of n.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,a))}getActions(t){return this.actions.map(i=>{const s=kp(t,i.pluginId),r=i.enabled?.(s),o={id:i.id,pluginId:i.pluginId,localId:i.localId,title:i.title,run:()=>i.run(s)};return i.description!==void 0&&(o.description=i.description),i.shortcut!==void 0&&(o.shortcut=i.shortcut),i.group!==void 0&&(o.group=i.group),r!==void 0&&(o.enabled=r),o})}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,i){const s={machine:Tp(t),state:t,workspace:i};return[...this.workspaceLabels].sort((r,o)=>(r.order??1e3)-(o.order??1e3)||r.id.localeCompare(o.id)).flatMap(r=>r.visible?.(s)===!1?[]:r.items(s))}qualifyAction(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyWorkspacePanel(t,i){const s=this.qualify(t,i.id),r=i.badge,o=i.visible;return{...i,id:s,pluginId:t,localId:i.id,...o===void 0?{}:{visible:n=>o(Ci(n,t))},...r===void 0?{}:{badge:n=>r(Ci(n,t))},render:n=>i.render(Ci(n,t))}}qualifyWorkspaceLabelContribution(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}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}`}validatePluginId(t){if(!yp.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!xp.test(t))throw new Error(`Invalid contribution id: ${t}`)}}function kp(e,t){return Ko.get(e)?.(t)??e}function Ci(e,t){return Go.get(e)?.(t)??e}function $p(e,t){return Ko.set(e,t),e}function Pp(e,t){return Go.set(e,t),e}function Tp(e){const t=e.selectedMachine;return t!==void 0?{id:t.id,name:t.name,kind:t.kind}:{id:"local",name:"local",kind:"local"}}const Cp=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function Ip(){return typeof window>"u"||!("matchMedia"in window)?[]:Cp.map(e=>window.matchMedia(e))}function Sr(e,t=Mp()){return e.some(i=>i.matches)||Ap(t)}function Mp(){return typeof navigator>"u"?void 0:navigator}function Ap(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const Rp=250;class Ep{constructor(t=Dp()){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()},Rp)}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 Dp(){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 _p="(max-width: 760px)";class Op{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=Sr(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??Lp(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??Ip(),this.viewportPositionRepairer=i.viewportPositionRepairer??new Ep,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=Sr(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.removeEventListener("change",this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?"navigation":"chat"}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function Lp(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(_p)}function Wp(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function vs(e,t){if(e!=="none")return e??Wp(t)}function jp(e,t){return t.isMobileLayout&&vs(t.expanded,t.state)!==e}function Np(e,t,i){return i.isMobileLayout?vs(e,i.state)===t?"none":t:e}function Bp(e,t,i){return i?t:e}class Fp{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,t.addController(this)}hostConnected(){}expandedSection(){return vs(this.expanded,this.getState())}isCollapsed(t){return jp(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState()})}toggle(t){this.setExpanded(Np(this.expanded,t,{isMobileLayout:this.isMobileLayout(),state:this.getState()}))}expand(t){this.setExpanded(Bp(this.expanded,t,this.isMobileLayout()))}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}}class zp{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()}shellClass(t){return["shell",Jo(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function Jo(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}function kr(){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:Up(e.get("tool")),view:Hp(e.get("view"))}}function Ii(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 Up(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Qo(e)?e:void 0}function Hp(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Qo(e)?e:void 0}function Qo(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function $r(){return qp(new URLSearchParams(window.location.search).get("settings"))}function Mi(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 qp(e){if(e==="general")return"general";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function Vp(e,t){return t===void 0?e:e.map(i=>Kp(i,t))}function Kp(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?Gp(e):{...e,shortcut:i}}function Gp(e){const t={...e};return delete t.shortcut,t}function Jp(e,t){const i=t.api??Ye,s=t.pollIntervalMs??1e3,r=t.setTimeout??Zp(),o=t.clearTimeout??Xp();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:Qp(a,i,s,r,o)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function Qp(e,t,i,s,r){return Pr(e)?Promise.resolve(e):new Promise((o,n)=>{let a,c=!1;const p=u=>{c||(c=!0,a!==void 0&&r(a),o(u))},f=u=>{c||(c=!0,a!==void 0&&r(a),n(u instanceof Error?u:new Error(String(u))))},h=()=>{t.getCommandRun(e.id).then(u=>{if(u!==void 0&&Pr(u)){p(u);return}a=s(h,i)}).catch(f)};a=s(h,i)})}function Pr(e){return e.status==="succeeded"||e.status==="failed"}function Zp(){return(e,t)=>globalThis.setTimeout(e,t)}function Xp(){return e=>{globalThis.clearTimeout(e)}}function Yp(e,t){return t[e.path]}function eh(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function th(e,t,i){return Xo(ih(e,t,i))}function Zo(e){return Xo(Object.values(e??{}))}function Xo(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function ih(e,t,i){const s=new Set(t.filter(o=>o.projectId===e.id).map(o=>o.path)),r=new Map;for(const o of s){const n=i[o];n!==void 0&&r.set(n.cwd,n)}for(const o of Object.values(i))(o.cwd===e.path||o.cwd.startsWith(`${e.path}/`))&&r.set(o.cwd,o);return[...r.values()]}const _t=0,sh=120;function Pt(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?Yo():rh(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),f=Math.min(i.right,a),h=p-i.bottom-_t,u=i.top-c-_t;return[...h<sh&&u>h?[`bottom: ${Qe(o-i.top+_t)};`,`max-height: ${Qe(Math.max(0,u))};`]:[`top: ${Qe(i.bottom+_t)};`,`max-height: ${Qe(Math.max(0,h))};`],`right: ${Qe(Math.max(0,r-f))};`,`max-width: ${Qe(Math.max(0,f-n))};`].join(" ")}function rh(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Yo()}function Yo(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function Qe(e){return`${String(Math.round(e))}px`}function Tt(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}const oh=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function en(e){return e.composedPath().some(t=>nh(t,oh))}function nh(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 ui(e,t){en(e)||t()}function fi(e,t){e.key!=="Enter"&&e.key!==" "||en(e)||(e.preventDefault(),t())}const ah=E`
117
117
  /* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
118
118
  :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; }
119
119
  :host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
@@ -220,7 +220,7 @@ ${r.join(`
220
220
  .empty { margin: auto; color: var(--pi-muted); }
221
221
  .error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
222
222
  @keyframes app-refresh-spin { to { transform: rotate(360deg); } }
223
- `,eh=E`
223
+ `,lh=E`
224
224
  :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; }
225
225
  header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
226
226
  .workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
@@ -284,6 +284,9 @@ ${r.join(`
284
284
  section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
285
285
  h2 { flex: 0 0 auto; display: flex; justify-content: space-between; align-items: center; gap: 8px; margin: 0 0 8px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
286
286
  .list-body { flex: 1 1 auto; min-height: 0; overflow: auto; }
287
+ .empty-list { box-sizing: border-box; display: grid; gap: 4px; margin: 6px 0; border: 1px dashed var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-muted); padding: 10px; line-height: 1.35; }
288
+ .empty-list strong { color: var(--pi-text); font-size: 13px; }
289
+ .empty-list small { white-space: normal; overflow: visible; text-overflow: clip; }
287
290
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
288
291
  section > button { display: block; width: 100%; text-align: left; margin: 6px 0; }
289
292
  .subheading { margin-top: 14px; }
@@ -336,7 +339,7 @@ ${r.join(`
336
339
  .workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
337
340
  .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; }
338
341
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
339
- `,th=E`
342
+ `,ch=E`
340
343
  :host { position: relative; z-index: 0; display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
341
344
  .chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
342
345
  .chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
@@ -420,7 +423,7 @@ ${r.join(`
420
423
  pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
421
424
  .shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
422
425
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
423
- `,ih=E`
426
+ `,dh=E`
424
427
  :host { display: block; }
425
428
  .formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
426
429
  p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
@@ -445,7 +448,7 @@ ${r.join(`
445
448
  table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
446
449
  th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
447
450
  th { background: var(--pi-surface); }
448
- `,sh=E`
451
+ `,ph=E`
449
452
  :host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
450
453
  .bar { display: flex; 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; }
451
454
  span { overflow: hidden; text-overflow: ellipsis; }
@@ -461,7 +464,7 @@ ${r.join(`
461
464
  .activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
462
465
  .muted { color: var(--pi-dim); }
463
466
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
464
- `,rh=E`
467
+ `,hh=E`
465
468
  :host { display: block; }
466
469
  .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); }
467
470
  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; }
@@ -469,7 +472,7 @@ ${r.join(`
469
472
  button.selected, button:hover { background: var(--pi-selection-bg); }
470
473
  span { color: var(--pi-muted); font-size: 12px; }
471
474
  small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
472
- `,Jo=E`
475
+ `,tn=E`
473
476
  :host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
474
477
  .backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
475
478
  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; }
@@ -483,7 +486,7 @@ ${r.join(`
483
486
  .options button.selected, .options button:hover { background: var(--pi-selection-bg); }
484
487
  small { display: block; margin-top: 4px; color: var(--pi-muted); }
485
488
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
486
- `,oh=E`
489
+ `,uh=E`
487
490
  :host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
488
491
  .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; }
489
492
  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; }
@@ -501,7 +504,7 @@ ${r.join(`
501
504
  .group { grid-column: 1 / -1; font-size: 12px; }
502
505
  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; }
503
506
  .empty { padding: 24px; color: var(--pi-muted); text-align: center; }
504
- `,nh=E`
507
+ `,fh=E`
505
508
  :host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
506
509
  footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
507
510
  footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
@@ -535,7 +538,7 @@ ${r.join(`
535
538
  .select-thinking { max-width: 70px; }
536
539
  button { padding: 5px 7px; }
537
540
  }
538
- `;var ah=Object.defineProperty,lh=Object.getOwnPropertyDescriptor,oe=(e,t,i,s)=>{for(var r=s>1?void 0:s?lh(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&&ah(t,i,r),r};let V=class extends I{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.openMenuMachineId!==void 0&&!this.machines.some(t=>t.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuMachineId=void 0)}render(){return l`
541
+ `;var mh=Object.defineProperty,gh=Object.getOwnPropertyDescriptor,oe=(e,t,i,s)=>{for(var r=s>1?void 0:s?gh(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&&mh(t,i,r),r};let V=class extends I{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.openMenuMachineId!==void 0&&!this.machines.some(t=>t.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuMachineId=void 0)}render(){return l`
539
542
  <section>
540
543
  <h2>${this.renderHeading()}</h2>
541
544
  ${this.collapsed?null:l`
@@ -544,7 +547,7 @@ ${r.join(`
544
547
  </div>
545
548
  `}
546
549
  </section>
547
- `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=ch(e)&&this.onRemove!==void 0;return l`
550
+ `}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=vh(e)&&this.onRemove!==void 0;return l`
548
551
  <div
549
552
  class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
550
553
  tabindex="0"
@@ -557,7 +560,7 @@ ${r.join(`
557
560
  </div>
558
561
  ${s?this.renderMachineMenu(e):null}
559
562
  </div>
560
- `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=qo(this.activities[e.id]);return Tt(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.openMenuMachineId===e.id,i=dh(e.id);return l`
563
+ `}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=Zo(this.activities[e.id]);return Tt(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.openMenuMachineId===e.id,i=bh(e.id);return l`
561
564
  <div class="action-menu">
562
565
  <button
563
566
  class="action-menu-toggle"
@@ -580,12 +583,17 @@ ${r.join(`
580
583
  .machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
581
584
  .machine-menu-panel button.danger { color: var(--pi-danger); }
582
585
  .machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
583
- `];oe([d({attribute:!1})],V.prototype,"machines",2);oe([d({attribute:!1})],V.prototype,"selected",2);oe([d({attribute:!1})],V.prototype,"statuses",2);oe([d({attribute:!1})],V.prototype,"activities",2);oe([d({type:Boolean,reflect:!0})],V.prototype,"collapsible",2);oe([d({type:Boolean,reflect:!0})],V.prototype,"collapsed",2);oe([d({attribute:!1})],V.prototype,"onSelect",2);oe([d({attribute:!1})],V.prototype,"onRemove",2);oe([d({attribute:!1})],V.prototype,"onToggleCollapsed",2);oe([x()],V.prototype,"openMenuMachineId",2);oe([x()],V.prototype,"menuStyle",2);V=oe([A("machine-list")],V);function ch(e){return e.kind==="remote"}function dh(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var ph=Object.defineProperty,hh=Object.getOwnPropertyDescriptor,ne=(e,t,i,s)=>{for(var r=s>1?void 0:s?hh(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&&ph(t,i,r),r};let K=class extends I{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("projects")&&this.openMenuProjectId!==void 0&&!this.projects.some(t=>t.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuProjectId=void 0)}render(){return l`
586
+ `];oe([d({attribute:!1})],V.prototype,"machines",2);oe([d({attribute:!1})],V.prototype,"selected",2);oe([d({attribute:!1})],V.prototype,"statuses",2);oe([d({attribute:!1})],V.prototype,"activities",2);oe([d({type:Boolean,reflect:!0})],V.prototype,"collapsible",2);oe([d({type:Boolean,reflect:!0})],V.prototype,"collapsed",2);oe([d({attribute:!1})],V.prototype,"onSelect",2);oe([d({attribute:!1})],V.prototype,"onRemove",2);oe([d({attribute:!1})],V.prototype,"onToggleCollapsed",2);oe([x()],V.prototype,"openMenuMachineId",2);oe([x()],V.prototype,"menuStyle",2);V=oe([A("machine-list")],V);function vh(e){return e.kind==="remote"}function bh(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var wh=Object.defineProperty,yh=Object.getOwnPropertyDescriptor,ne=(e,t,i,s)=>{for(var r=s>1?void 0:s?yh(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&&wh(t,i,r),r};let K=class extends I{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("projects")&&this.openMenuProjectId!==void 0&&!this.projects.some(t=>t.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuProjectId=void 0)}render(){return l`
584
587
  <section>
585
588
  <h2>${this.renderHeading()}</h2>
586
589
  ${this.collapsed?null:l`
587
590
  <div class="list-body">
588
- ${this.projects.map(e=>l`
591
+ ${this.projects.length===0?l`
592
+ <div class="empty-list" role="status">
593
+ <strong>暂无可访问项目</strong>
594
+ <small>请先在 AI 平台手动创建项目,然后刷新此页面。</small>
595
+ </div>
596
+ `:this.projects.map(e=>l`
589
597
  <div
590
598
  class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
591
599
  tabindex="0"
@@ -609,19 +617,19 @@ ${r.join(`
609
617
  </div>
610
618
  `}
611
619
  </section>
612
- `}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><small class="section-selected" title=${t}>${e}</small></span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=Kp(e,this.workspacesByProjectId[e.id]??[],this.activities);return Tt(t,t==="terminal"?"项目终端活跃":"项目活跃")??""}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=Pt(t),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`关闭 ${e.name}?
620
+ `}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><small class="section-selected" title=${t}>${e}</small></span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=th(e,this.workspacesByProjectId[e.id]??[],this.activities);return Tt(t,t==="terminal"?"项目终端活跃":"项目活跃")??""}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=Pt(t),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`关闭 ${e.name}?
613
621
 
614
- 这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};K.styles=mi;ne([d({attribute:!1})],K.prototype,"projects",2);ne([d({attribute:!1})],K.prototype,"selected",2);ne([d({attribute:!1})],K.prototype,"activities",2);ne([d({attribute:!1})],K.prototype,"workspacesByProjectId",2);ne([d({type:Boolean,reflect:!0})],K.prototype,"collapsible",2);ne([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);ne([d({attribute:!1})],K.prototype,"onSelect",2);ne([d({attribute:!1})],K.prototype,"onClose",2);ne([d({attribute:!1})],K.prototype,"onToggleCollapsed",2);ne([x()],K.prototype,"openMenuProjectId",2);ne([x()],K.prototype,"menuStyle",2);K=ne([A("project-list")],K);function Qo(e,t=[],i){return l`
622
+ 这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};K.styles=mi;ne([d({attribute:!1})],K.prototype,"projects",2);ne([d({attribute:!1})],K.prototype,"selected",2);ne([d({attribute:!1})],K.prototype,"activities",2);ne([d({attribute:!1})],K.prototype,"workspacesByProjectId",2);ne([d({type:Boolean,reflect:!0})],K.prototype,"collapsible",2);ne([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);ne([d({attribute:!1})],K.prototype,"onSelect",2);ne([d({attribute:!1})],K.prototype,"onClose",2);ne([d({attribute:!1})],K.prototype,"onToggleCollapsed",2);ne([x()],K.prototype,"openMenuProjectId",2);ne([x()],K.prototype,"menuStyle",2);K=ne([A("project-list")],K);function sn(e,t=[],i){return l`
615
623
  <span class="workspace-label">
616
624
  <span class="workspace-label-base" title=${i??e}>${e}</span>
617
- ${uh(t)}
625
+ ${xh(t)}
618
626
  </span>
619
- `}function uh(e=[]){return e.map(t=>l`<span class="workspace-label-separator">·</span>${Zo(t)}`)}function kr(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${Zo(t)}`)}function Zo(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&fh(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 fh(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var mh=Object.defineProperty,gh=Object.getOwnPropertyDescriptor,X=(e,t,i,s)=>{for(var r=s>1?void 0:s?gh(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&&mh(t,i,r),r};let q=class extends I{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuWorkspaceId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("workspaces")&&this.openMenuWorkspaceId!==void 0&&!this.workspaces.some(t=>t.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuWorkspaceId=void 0),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}render(){return l`
627
+ `}function xh(e=[]){return e.map(t=>l`<span class="workspace-label-separator">·</span>${rn(t)}`)}function Tr(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${rn(t)}`)}function rn(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&Sh(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 Sh(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var kh=Object.defineProperty,$h=Object.getOwnPropertyDescriptor,X=(e,t,i,s)=>{for(var r=s>1?void 0:s?$h(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&&kh(t,i,r),r};let q=class extends I{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuWorkspaceId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("workspaces")&&this.openMenuWorkspaceId!==void 0&&!this.workspaces.some(t=>t.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuWorkspaceId=void 0),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}render(){return l`
620
628
  <section>
621
629
  <h2>${this.renderHeading()}</h2>
622
630
  ${this.collapsed?null:l`
623
631
  <div class="list-body">
624
- ${this.workspaces.map(e=>{const t=vh(e),i=this.workspaceLabelItems(e);return l`
632
+ ${this.workspaces.map(e=>{const t=Ph(e),i=this.workspaceLabelItems(e);return l`
625
633
  <div
626
634
  class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
627
635
  tabindex="0"
@@ -638,7 +646,7 @@ ${r.join(`
638
646
  </div>
639
647
  `}
640
648
  </section>
641
- `}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><small class="section-selected" title=${t}>${e}</small></span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=Vp(qp(e,this.activities));return Tt(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return l`
649
+ `}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><small class="section-selected" title=${t}>${e}</small></span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=eh(Yp(e,this.activities));return Tt(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return l`
642
650
  <span class="workspace-primary">
643
651
  ${this.renderActivity(i)}
644
652
  <span class="workspace-primary-label">${e}</span>
@@ -646,10 +654,10 @@ ${r.join(`
646
654
  </span>
647
655
  ${t.length===0?null:l`
648
656
  <small class="workspace-secondary">
649
- <span class="workspace-label">${kr(t)}</span>
657
+ <span class="workspace-label">${Tr(t)}</span>
650
658
  </small>
651
659
  `}
652
- `}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,r=wh(i.id);return l`
660
+ `}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,r=Ch(i.id);return l`
653
661
  <div class="action-menu">
654
662
  <button
655
663
  class="action-menu-toggle"
@@ -666,7 +674,7 @@ ${r.join(`
666
674
  </div>
667
675
  `:null}
668
676
  </div>
669
- `}renderWorkspaceActions(e){if(!bh(e))return;const t=this.isDeleting(e);return l`
677
+ `}renderWorkspaceActions(e){if(!Th(e))return;const t=this.isDeleting(e);return l`
670
678
  <div class="workspace-menu-actions">
671
679
  <button class="danger" title=${t?"正在删除工作区":"删除工作区"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"正在删除…":"删除工作区"}</button>
672
680
  </div>
@@ -683,11 +691,11 @@ ${r.join(`
683
691
  ${t.length===0?null:l`
684
692
  <div class="workspace-detail-row">
685
693
  <dt>详情</dt>
686
- <dd><span class="workspace-label">${kr(t)}</span></dd>
694
+ <dd><span class="workspace-label">${Tr(t)}</span></dd>
687
695
  </div>
688
696
  `}
689
697
  </dl>
690
- `}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=Pt(t),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key==="Escape"&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}fi(e,()=>this.onSelect?.(t))}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};q.styles=mi;X([d({attribute:!1})],q.prototype,"workspaces",2);X([d({attribute:!1})],q.prototype,"selected",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsible",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsed",2);X([d({attribute:!1})],q.prototype,"workspaceLabelItems",2);X([d({attribute:!1})],q.prototype,"activities",2);X([d({attribute:!1})],q.prototype,"deletingWorkspaceIds",2);X([d({attribute:!1})],q.prototype,"onSelect",2);X([d({attribute:!1})],q.prototype,"onDelete",2);X([d({attribute:!1})],q.prototype,"onToggleCollapsed",2);X([x()],q.prototype,"openMenuWorkspaceId",2);X([x()],q.prototype,"menuStyle",2);q=X([A("workspace-list")],q);function vh(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function bh(e){return e.isGitWorktree&&!e.isMain}function wh(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var yh=Object.defineProperty,xh=Object.getOwnPropertyDescriptor,N=(e,t,i,s)=>{for(var r=s>1?void 0:s?xh(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&&yh(t,i,r),r};function Ai(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let O=class extends I{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.canStart=!1,this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.archivedExpanded=!1,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("sessions")&&this.openMenuSessionId!==void 0&&!this.sessions.some(i=>i.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuSessionId=void 0),e.has("sessions")&&!this.sessions.some(i=>i.archived===!0)&&(this.archivedExpanded=!1);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()}render(){const e=kh(this.sessions),t=new Set(e.map(r=>r.session.id)),i=Xo(this.sessions.filter(r=>r.archived===!0&&!t.has(r.id))),s=Sh(this.sessions);return l`
698
+ `}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=Pt(t),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key==="Escape"&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}fi(e,()=>this.onSelect?.(t))}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}};q.styles=mi;X([d({attribute:!1})],q.prototype,"workspaces",2);X([d({attribute:!1})],q.prototype,"selected",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsible",2);X([d({type:Boolean,reflect:!0})],q.prototype,"collapsed",2);X([d({attribute:!1})],q.prototype,"workspaceLabelItems",2);X([d({attribute:!1})],q.prototype,"activities",2);X([d({attribute:!1})],q.prototype,"deletingWorkspaceIds",2);X([d({attribute:!1})],q.prototype,"onSelect",2);X([d({attribute:!1})],q.prototype,"onDelete",2);X([d({attribute:!1})],q.prototype,"onToggleCollapsed",2);X([x()],q.prototype,"openMenuWorkspaceId",2);X([x()],q.prototype,"menuStyle",2);q=X([A("workspace-list")],q);function Ph(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function Th(e){return e.isGitWorktree&&!e.isMain}function Ch(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Ih=Object.defineProperty,Mh=Object.getOwnPropertyDescriptor,N=(e,t,i,s)=>{for(var r=s>1?void 0:s?Mh(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&&Ih(t,i,r),r};function Ai(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let O=class extends I{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.canStart=!1,this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.archivedExpanded=!1,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("sessions")&&this.openMenuSessionId!==void 0&&!this.sessions.some(i=>i.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuSessionId=void 0),e.has("sessions")&&!this.sessions.some(i=>i.archived===!0)&&(this.archivedExpanded=!1);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()}render(){const e=Rh(this.sessions),t=new Set(e.map(r=>r.session.id)),i=on(this.sessions.filter(r=>r.archived===!0&&!t.has(r.id))),s=Ah(this.sessions);return l`
691
699
  <section>
692
700
  ${this.renderHeading(e.length+i.length)}
693
701
  ${this.collapsed?null:l`
@@ -730,7 +738,7 @@ ${r.join(`
730
738
  `:null}
731
739
  </div>
732
740
  </div>
733
- `}confirmArchiveWithDescendants(e,t){confirm(`归档“${Ai(e)}”及 ${String(t)} 个子会话?`)&&this.onArchiveWithDescendants?.(e)}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=Pt(t),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderStatus(e){return ke(e)?"新建 · ":e.archived===!0?"只读 · ":Tt(pi(this.statuses[e.id],this.activities[e.id])?"session":void 0,"会话活跃")??""}};O.styles=mi;N([d({attribute:!1})],O.prototype,"sessions",2);N([d({attribute:!1})],O.prototype,"statuses",2);N([d({attribute:!1})],O.prototype,"activities",2);N([d({attribute:!1})],O.prototype,"selected",2);N([d({type:Boolean})],O.prototype,"canStart",2);N([d({type:Boolean,reflect:!0})],O.prototype,"collapsible",2);N([d({type:Boolean,reflect:!0})],O.prototype,"collapsed",2);N([d({attribute:!1})],O.prototype,"onSelect",2);N([d({attribute:!1})],O.prototype,"onStart",2);N([d({attribute:!1})],O.prototype,"onToggleCollapsed",2);N([d({attribute:!1})],O.prototype,"onArchivedCollapsed",2);N([x()],O.prototype,"openMenuSessionId",2);N([x()],O.prototype,"menuStyle",2);N([x()],O.prototype,"archivedExpanded",2);N([d({attribute:!1})],O.prototype,"onArchive",2);N([d({attribute:!1})],O.prototype,"onArchiveWithDescendants",2);N([d({attribute:!1})],O.prototype,"onRestore",2);N([d({attribute:!1})],O.prototype,"onDelete",2);N([d({attribute:!1})],O.prototype,"onDetachParent",2);O=N([A("session-list")],O);function Sh(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 kh(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 Xo(e.filter(s=>i.has(s.id)))}function Xo(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 f=new Set(c);f.add(n.path);for(const h of i.get(n.path)??[])o(h,a+1,f)};for(const n of s)o(n,0,new Set);return r}const vs={CHILD:2,ELEMENT:6},bs=e=>(...t)=>({_$litDirective$:e,values:t});let ws=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:$h}=Zn,$r=e=>e,Pr=()=>document.createComment(""),pt=(e,t,i)=>{const s=e._$AA.parentNode,r=t===void 0?e._$AB:t._$AA;if(i===void 0){const o=s.insertBefore(Pr(),r),n=s.insertBefore(Pr(),r);i=new $h(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=$r(c).nextSibling;$r(s).insertBefore(c,r),c=p}}}return i},_e=(e,t,i=e)=>(e._$AI(t,i),e),Ph={},Th=(e,t=Ph)=>e._$AH=t,Ch=e=>e._$AH,Ri=e=>{e._$AR(),e._$AA.remove()};const Tr=(e,t,i)=>{const s=new Map;for(let r=t;r<=i;r++)s.set(e[r],r);return s},Ih=bs(class extends ws{constructor(e){if(super(e),e.type!==vs.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=Ch(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,f,h=0,u=r.length-1,v=0,S=o.length-1;for(;h<=u&&v<=S;)if(r[h]===null)h++;else if(r[u]===null)u--;else if(a[h]===n[v])c[v]=_e(r[h],o[v]),h++,v++;else if(a[u]===n[S])c[S]=_e(r[u],o[S]),u--,S--;else if(a[h]===n[S])c[S]=_e(r[h],o[S]),pt(e,c[S+1],r[h]),h++,S--;else if(a[u]===n[v])c[v]=_e(r[u],o[v]),pt(e,r[h],r[u]),u--,v++;else if(p===void 0&&(p=Tr(n,v,S),f=Tr(a,h,u)),p.has(a[h]))if(p.has(a[u])){const F=f.get(n[v]),Ke=F!==void 0?r[F]:null;if(Ke===null){const ot=pt(e,r[h]);_e(ot,o[v]),c[v]=ot}else c[v]=_e(Ke,o[v]),pt(e,r[h],Ke),r[F]=null;v++}else Ri(r[u]),u--;else Ri(r[h]),h++;for(;v<=S;){const F=pt(e,c[S+1]);_e(F,o[v]),c[v++]=F}for(;h<=u;){const F=r[h++];F!==null&&Ri(F)}return this.ut=n,Th(e,c),Re}}),Mh="pi-web:chat-groups:",Ah={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(Cr(e));return t===null||t===""?void 0:Eh(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(Cr(e),JSON.stringify(t))}catch{}}};class Rh{constructor(t=Ah){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&&Ir(o,this.openGroupKeys)&&Ir(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 Cr(e){return`${Mh}${e}`}function Eh(e){if(Array.isArray(e))return{open:Ei(e),closedDefaultOpen:[]};if(Dh(e))return{open:Array.isArray(e.open)?Ei(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Ei(e.closedDefaultOpen):[]}}function Ei(e){return e.filter(t=>typeof t=="string")}function Ir(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Dh(e){return typeof e=="object"&&e!==null}function _h(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(v=>Mr(a,v)),f=a.parts.filter(v=>!Mr(a,v)),h=t+c,u={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(f.length&&o({role:a.role,parts:f,...u},h),p.length){n();const v=p.every(S=>S.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:v,parts:p,...u},index:h})}}),n(),i}function Oh(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)} ${Lh(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Lh(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Mr(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 Wh=30;function jh(e,t){const i=Bh(Uh(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Nh(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Fh(s,t.markerOffset);return}e.scrollTop=zh(e.scrollHeight,t.distanceFromBottom)}function Bh(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 Fh(e,t){return e-t}function zh(e,t){return Math.max(0,e-t)}function Uh(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 Hh=600,qh=1;function Vh(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:Kh(e)||Gh(e)}function Kh(e){return e.scrollTop<(e.topThreshold??Math.max(Hh,e.clientHeight))}function Gh(e){return e.scrollHeight<=e.clientHeight+qh}const Jh="pi-web:chat-scroll:",Qh=180,Zh=48,Xh=2,Yh={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)}},eu={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class tu{constructor(t=Yh,i=eu){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=Qh){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,r=Xh){if(t===""||i===void 0||!_i(i))return"skipped";try{if(en(i,r)){const a={mode:"bottom"};return this.storage.setItem(Di(t),JSON.stringify(a)),"saved"}const o=ru(i,s);if(o===void 0)return"skipped";const n=su(i,o);return this.storage.setItem(Di(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||!_i(i))return{status:"skipped"};const o=ou(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(Di(t));if(i===null||i==="")return;const s=JSON.parse(i);return iu(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!_i(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function Di(e){return`${Jh}${e}`}function iu(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 _i(e){return e.clientHeight>0&&e.scrollHeight>0}function Yo(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function en(e,t=Zh){return Yo(e)<t}function su(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:ys(t)??"",offset:t.getBoundingClientRect().top-i}}function ru(e,t){const i=e.getBoundingClientRect();let s,r=Number.NEGATIVE_INFINITY,o,n=Number.POSITIVE_INFINITY;for(const a of t){if(ys(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 Ar(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const r=s.getBoundingClientRect();return r.bottom>=i.top&&r.top<=i.bottom})}function ou(e,t){return e.find(i=>ys(i)===t)}function ys(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var nu=Object.defineProperty,au=Object.getOwnPropertyDescriptor,xs=(e,t,i,s)=>{for(var r=s>1?void 0:s?au(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&&nu(t,i,r),r};let yt=class extends I{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=Rr(this.positionPercent),t=Rr(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return l`
741
+ `}confirmArchiveWithDescendants(e,t){confirm(`归档“${Ai(e)}”及 ${String(t)} 个子会话?`)&&this.onArchiveWithDescendants?.(e)}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=Pt(t),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderStatus(e){return ke(e)?"新建 · ":e.archived===!0?"只读 · ":Tt(pi(this.statuses[e.id],this.activities[e.id])?"session":void 0,"会话活跃")??""}};O.styles=mi;N([d({attribute:!1})],O.prototype,"sessions",2);N([d({attribute:!1})],O.prototype,"statuses",2);N([d({attribute:!1})],O.prototype,"activities",2);N([d({attribute:!1})],O.prototype,"selected",2);N([d({type:Boolean})],O.prototype,"canStart",2);N([d({type:Boolean,reflect:!0})],O.prototype,"collapsible",2);N([d({type:Boolean,reflect:!0})],O.prototype,"collapsed",2);N([d({attribute:!1})],O.prototype,"onSelect",2);N([d({attribute:!1})],O.prototype,"onStart",2);N([d({attribute:!1})],O.prototype,"onToggleCollapsed",2);N([d({attribute:!1})],O.prototype,"onArchivedCollapsed",2);N([x()],O.prototype,"openMenuSessionId",2);N([x()],O.prototype,"menuStyle",2);N([x()],O.prototype,"archivedExpanded",2);N([d({attribute:!1})],O.prototype,"onArchive",2);N([d({attribute:!1})],O.prototype,"onArchiveWithDescendants",2);N([d({attribute:!1})],O.prototype,"onRestore",2);N([d({attribute:!1})],O.prototype,"onDelete",2);N([d({attribute:!1})],O.prototype,"onDetachParent",2);O=N([A("session-list")],O);function Ah(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 Rh(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 on(e.filter(s=>i.has(s.id)))}function on(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 f=new Set(c);f.add(n.path);for(const h of i.get(n.path)??[])o(h,a+1,f)};for(const n of s)o(n,0,new Set);return r}const bs={CHILD:2,ELEMENT:6},ws=e=>(...t)=>({_$litDirective$:e,values:t});let ys=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:Eh}=sa,Cr=e=>e,Ir=()=>document.createComment(""),pt=(e,t,i)=>{const s=e._$AA.parentNode,r=t===void 0?e._$AB:t._$AA;if(i===void 0){const o=s.insertBefore(Ir(),r),n=s.insertBefore(Ir(),r);i=new Eh(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=Cr(c).nextSibling;Cr(s).insertBefore(c,r),c=p}}}return i},_e=(e,t,i=e)=>(e._$AI(t,i),e),Dh={},_h=(e,t=Dh)=>e._$AH=t,Oh=e=>e._$AH,Ri=e=>{e._$AR(),e._$AA.remove()};const Mr=(e,t,i)=>{const s=new Map;for(let r=t;r<=i;r++)s.set(e[r],r);return s},Lh=ws(class extends ys{constructor(e){if(super(e),e.type!==bs.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=Oh(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,f,h=0,u=r.length-1,v=0,S=o.length-1;for(;h<=u&&v<=S;)if(r[h]===null)h++;else if(r[u]===null)u--;else if(a[h]===n[v])c[v]=_e(r[h],o[v]),h++,v++;else if(a[u]===n[S])c[S]=_e(r[u],o[S]),u--,S--;else if(a[h]===n[S])c[S]=_e(r[h],o[S]),pt(e,c[S+1],r[h]),h++,S--;else if(a[u]===n[v])c[v]=_e(r[u],o[v]),pt(e,r[h],r[u]),u--,v++;else if(p===void 0&&(p=Mr(n,v,S),f=Mr(a,h,u)),p.has(a[h]))if(p.has(a[u])){const F=f.get(n[v]),Ke=F!==void 0?r[F]:null;if(Ke===null){const ot=pt(e,r[h]);_e(ot,o[v]),c[v]=ot}else c[v]=_e(Ke,o[v]),pt(e,r[h],Ke),r[F]=null;v++}else Ri(r[u]),u--;else Ri(r[h]),h++;for(;v<=S;){const F=pt(e,c[S+1]);_e(F,o[v]),c[v++]=F}for(;h<=u;){const F=r[h++];F!==null&&Ri(F)}return this.ut=n,_h(e,c),Re}}),Wh="pi-web:chat-groups:",jh={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(Ar(e));return t===null||t===""?void 0:Bh(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(Ar(e),JSON.stringify(t))}catch{}}};class Nh{constructor(t=jh){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&&Rr(o,this.openGroupKeys)&&Rr(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 Ar(e){return`${Wh}${e}`}function Bh(e){if(Array.isArray(e))return{open:Ei(e),closedDefaultOpen:[]};if(Fh(e))return{open:Array.isArray(e.open)?Ei(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Ei(e.closedDefaultOpen):[]}}function Ei(e){return e.filter(t=>typeof t=="string")}function Rr(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Fh(e){return typeof e=="object"&&e!==null}function zh(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(v=>Er(a,v)),f=a.parts.filter(v=>!Er(a,v)),h=t+c,u={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(f.length&&o({role:a.role,parts:f,...u},h),p.length){n();const v=p.every(S=>S.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:v,parts:p,...u},index:h})}}),n(),i}function Uh(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)} ${Hh(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Hh(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Er(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 qh=30;function Vh(e,t){const i=Gh(Zh(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function Kh(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Jh(s,t.markerOffset);return}e.scrollTop=Qh(e.scrollHeight,t.distanceFromBottom)}function Gh(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 Jh(e,t){return e-t}function Qh(e,t){return Math.max(0,e-t)}function Zh(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 Xh=600,Yh=1;function eu(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:tu(e)||iu(e)}function tu(e){return e.scrollTop<(e.topThreshold??Math.max(Xh,e.clientHeight))}function iu(e){return e.scrollHeight<=e.clientHeight+Yh}const su="pi-web:chat-scroll:",ru=180,ou=48,nu=2,au={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)}},lu={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class cu{constructor(t=au,i=lu){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=ru){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,r=nu){if(t===""||i===void 0||!_i(i))return"skipped";try{if(an(i,r)){const a={mode:"bottom"};return this.storage.setItem(Di(t),JSON.stringify(a)),"saved"}const o=hu(i,s);if(o===void 0)return"skipped";const n=pu(i,o);return this.storage.setItem(Di(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||!_i(i))return{status:"skipped"};const o=uu(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(Di(t));if(i===null||i==="")return;const s=JSON.parse(i);return du(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!_i(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function Di(e){return`${su}${e}`}function du(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 _i(e){return e.clientHeight>0&&e.scrollHeight>0}function nn(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function an(e,t=ou){return nn(e)<t}function pu(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:xs(t)??"",offset:t.getBoundingClientRect().top-i}}function hu(e,t){const i=e.getBoundingClientRect();let s,r=Number.NEGATIVE_INFINITY,o,n=Number.POSITIVE_INFINITY;for(const a of t){if(xs(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 Dr(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const r=s.getBoundingClientRect();return r.bottom>=i.top&&r.top<=i.bottom})}function uu(e,t){return e.find(i=>xs(i)===t)}function xs(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var fu=Object.defineProperty,mu=Object.getOwnPropertyDescriptor,Ss=(e,t,i,s)=>{for(var r=s>1?void 0:s?mu(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&&fu(t,i,r),r};let yt=class extends I{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=_r(this.positionPercent),t=_r(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return l`
734
742
  <div
735
743
  class="meter"
736
744
  style=${`--position:${e.toFixed(2)}%;`}
@@ -753,12 +761,12 @@ ${r.join(`
753
761
  .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); }
754
762
  .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)); }
755
763
  .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%); }
756
- `;xs([d({type:Number})],yt.prototype,"positionPercent",2);xs([d({type:Number})],yt.prototype,"loadedPercent",2);yt=xs([A("conversation-meter")],yt);function Rr(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class Ji extends ws{constructor(t){if(super(t),this.it=j,t.type!==vs.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===j||t==null)return this._t=void 0,this.it=t;if(t===Re)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:[]}}}Ji.directiveName="unsafeHTML",Ji.resultType=1;const lu=bs(Ji);function Ss(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ue=Ss();function tn(e){Ue=e}var Oe={exec:()=>null};function C(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(r,o)=>{let n=typeof o=="string"?o:o.source;return n=n.replace(H.caret,"$1"),i=i.replace(r,n),s},getRegex:()=>new RegExp(i,t)};return s}var cu=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),H={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},du=/^(?:[ \t]*(?:\n|$))+/,pu=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,hu=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ct=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,uu=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ks=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,sn=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,rn=C(sn).replace(/bull/g,ks).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(),fu=C(sn).replace(/bull/g,ks).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(),$s=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,mu=/^[^\n]+/,Ps=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,gu=C(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Ps).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),vu=C(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,ks).getRegex(),gi="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",Ts=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,bu=C("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Ts).replace("tag",gi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),on=C($s).replace("hr",Ct).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",gi).getRegex(),wu=C(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",on).getRegex(),Cs={blockquote:wu,code:pu,def:gu,fences:hu,heading:uu,hr:Ct,html:bu,lheading:rn,list:vu,newline:du,paragraph:on,table:Oe,text:mu},Er=C("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ct).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",gi).getRegex(),yu={...Cs,lheading:fu,table:Er,paragraph:C($s).replace("hr",Ct).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Er).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",gi).getRegex()},xu={...Cs,html:C(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Ts).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:Oe,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:C($s).replace("hr",Ct).replace("heading",` *#{1,6} *[^
757
- ]`).replace("lheading",rn).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Su=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,ku=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,nn=/^( {2,}|\\)\n(?!\s*$)/,$u=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,rt=/[\p{P}\p{S}]/u,vi=/[\s\p{P}\p{S}]/u,Is=/[^\s\p{P}\p{S}]/u,Pu=C(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,vi).getRegex(),an=/(?!~)[\p{P}\p{S}]/u,Tu=/(?!~)[\s\p{P}\p{S}]/u,Cu=/(?:[^\s\p{P}\p{S}]|~)/u,Iu=C(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",cu?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ln=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Mu=C(ln,"u").replace(/punct/g,rt).getRegex(),Au=C(ln,"u").replace(/punct/g,an).getRegex(),cn="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Ru=C(cn,"gu").replace(/notPunctSpace/g,Is).replace(/punctSpace/g,vi).replace(/punct/g,rt).getRegex(),Eu=C(cn,"gu").replace(/notPunctSpace/g,Cu).replace(/punctSpace/g,Tu).replace(/punct/g,an).getRegex(),Du=C("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Is).replace(/punctSpace/g,vi).replace(/punct/g,rt).getRegex(),_u=C(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,rt).getRegex(),Ou="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Lu=C(Ou,"gu").replace(/notPunctSpace/g,Is).replace(/punctSpace/g,vi).replace(/punct/g,rt).getRegex(),Wu=C(/\\(punct)/,"gu").replace(/punct/g,rt).getRegex(),ju=C(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Nu=C(Ts).replace("(?:-->|$)","-->").getRegex(),Bu=C("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Nu).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),oi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Fu=C(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",oi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),dn=C(/^!?\[(label)\]\[(ref)\]/).replace("label",oi).replace("ref",Ps).getRegex(),pn=C(/^!?\[(ref)\](?:\[\])?/).replace("ref",Ps).getRegex(),zu=C("reflink|nolink(?!\\()","g").replace("reflink",dn).replace("nolink",pn).getRegex(),Dr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ms={_backpedal:Oe,anyPunctuation:Wu,autolink:ju,blockSkip:Iu,br:nn,code:ku,del:Oe,delLDelim:Oe,delRDelim:Oe,emStrongLDelim:Mu,emStrongRDelimAst:Ru,emStrongRDelimUnd:Du,escape:Su,link:Fu,nolink:pn,punctuation:Pu,reflink:dn,reflinkSearch:zu,tag:Bu,text:$u,url:Oe},Uu={...Ms,link:C(/^!?\[(label)\]\((.*?)\)/).replace("label",oi).getRegex(),reflink:C(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",oi).getRegex()},Qi={...Ms,emStrongRDelimAst:Eu,emStrongLDelim:Au,delLDelim:_u,delRDelim:Lu,url:C(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Dr).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:C(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Dr).getRegex()},Hu={...Qi,br:C(nn).replace("{2,}","*").getRegex(),text:C(Qi.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ot={normal:Cs,gfm:yu,pedantic:xu},ht={normal:Ms,gfm:Qi,breaks:Hu,pedantic:Uu},qu={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},_r=e=>qu[e];function ge(e,t){if(t){if(H.escapeTest.test(e))return e.replace(H.escapeReplace,_r)}else if(H.escapeTestNoEncode.test(e))return e.replace(H.escapeReplaceNoEncode,_r);return e}function Or(e){try{e=encodeURI(e).replace(H.percentDecode,"%")}catch{return null}return e}function Lr(e,t){let i=e.replace(H.findPipe,(o,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(H.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(H.slashPipe,"|");return s}function Me(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 Wr(e){let t=e.split(`
764
+ `;Ss([d({type:Number})],yt.prototype,"positionPercent",2);Ss([d({type:Number})],yt.prototype,"loadedPercent",2);yt=Ss([A("conversation-meter")],yt);function _r(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class Ji extends ys{constructor(t){if(super(t),this.it=j,t.type!==bs.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===j||t==null)return this._t=void 0,this.it=t;if(t===Re)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:[]}}}Ji.directiveName="unsafeHTML",Ji.resultType=1;const gu=ws(Ji);function ks(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Ue=ks();function ln(e){Ue=e}var Oe={exec:()=>null};function C(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(r,o)=>{let n=typeof o=="string"?o:o.source;return n=n.replace(H.caret,"$1"),i=i.replace(r,n),s},getRegex:()=>new RegExp(i,t)};return s}var vu=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),H={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},bu=/^(?:[ \t]*(?:\n|$))+/,wu=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,yu=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ct=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,xu=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,$s=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,cn=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,dn=C(cn).replace(/bull/g,$s).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(),Su=C(cn).replace(/bull/g,$s).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(),Ps=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ku=/^[^\n]+/,Ts=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,$u=C(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Ts).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Pu=C(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,$s).getRegex(),gi="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",Cs=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Tu=C("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Cs).replace("tag",gi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),pn=C(Ps).replace("hr",Ct).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",gi).getRegex(),Cu=C(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",pn).getRegex(),Is={blockquote:Cu,code:wu,def:$u,fences:yu,heading:xu,hr:Ct,html:Tu,lheading:dn,list:Pu,newline:bu,paragraph:pn,table:Oe,text:ku},Or=C("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ct).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",gi).getRegex(),Iu={...Is,lheading:Su,table:Or,paragraph:C(Ps).replace("hr",Ct).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Or).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",gi).getRegex()},Mu={...Is,html:C(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Cs).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:Oe,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:C(Ps).replace("hr",Ct).replace("heading",` *#{1,6} *[^
765
+ ]`).replace("lheading",dn).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Au=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ru=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,hn=/^( {2,}|\\)\n(?!\s*$)/,Eu=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,rt=/[\p{P}\p{S}]/u,vi=/[\s\p{P}\p{S}]/u,Ms=/[^\s\p{P}\p{S}]/u,Du=C(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,vi).getRegex(),un=/(?!~)[\p{P}\p{S}]/u,_u=/(?!~)[\s\p{P}\p{S}]/u,Ou=/(?:[^\s\p{P}\p{S}]|~)/u,Lu=C(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",vu?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),fn=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Wu=C(fn,"u").replace(/punct/g,rt).getRegex(),ju=C(fn,"u").replace(/punct/g,un).getRegex(),mn="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Nu=C(mn,"gu").replace(/notPunctSpace/g,Ms).replace(/punctSpace/g,vi).replace(/punct/g,rt).getRegex(),Bu=C(mn,"gu").replace(/notPunctSpace/g,Ou).replace(/punctSpace/g,_u).replace(/punct/g,un).getRegex(),Fu=C("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ms).replace(/punctSpace/g,vi).replace(/punct/g,rt).getRegex(),zu=C(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,rt).getRegex(),Uu="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Hu=C(Uu,"gu").replace(/notPunctSpace/g,Ms).replace(/punctSpace/g,vi).replace(/punct/g,rt).getRegex(),qu=C(/\\(punct)/,"gu").replace(/punct/g,rt).getRegex(),Vu=C(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Ku=C(Cs).replace("(?:-->|$)","-->").getRegex(),Gu=C("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Ku).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),oi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Ju=C(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",oi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),gn=C(/^!?\[(label)\]\[(ref)\]/).replace("label",oi).replace("ref",Ts).getRegex(),vn=C(/^!?\[(ref)\](?:\[\])?/).replace("ref",Ts).getRegex(),Qu=C("reflink|nolink(?!\\()","g").replace("reflink",gn).replace("nolink",vn).getRegex(),Lr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,As={_backpedal:Oe,anyPunctuation:qu,autolink:Vu,blockSkip:Lu,br:hn,code:Ru,del:Oe,delLDelim:Oe,delRDelim:Oe,emStrongLDelim:Wu,emStrongRDelimAst:Nu,emStrongRDelimUnd:Fu,escape:Au,link:Ju,nolink:vn,punctuation:Du,reflink:gn,reflinkSearch:Qu,tag:Gu,text:Eu,url:Oe},Zu={...As,link:C(/^!?\[(label)\]\((.*?)\)/).replace("label",oi).getRegex(),reflink:C(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",oi).getRegex()},Qi={...As,emStrongRDelimAst:Bu,emStrongLDelim:ju,delLDelim:zu,delRDelim:Hu,url:C(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Lr).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:C(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Lr).getRegex()},Xu={...Qi,br:C(hn).replace("{2,}","*").getRegex(),text:C(Qi.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ot={normal:Is,gfm:Iu,pedantic:Mu},ht={normal:As,gfm:Qi,breaks:Xu,pedantic:Zu},Yu={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Wr=e=>Yu[e];function ge(e,t){if(t){if(H.escapeTest.test(e))return e.replace(H.escapeReplace,Wr)}else if(H.escapeTestNoEncode.test(e))return e.replace(H.escapeReplaceNoEncode,Wr);return e}function jr(e){try{e=encodeURI(e).replace(H.percentDecode,"%")}catch{return null}return e}function Nr(e,t){let i=e.replace(H.findPipe,(o,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(H.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(H.slashPipe,"|");return s}function Me(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 Br(e){let t=e.split(`
758
766
  `),i=t.length-1;for(;i>=0&&H.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
759
- `)}function Vu(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 Ku(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 jr(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 Gu(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(`
767
+ `)}function ef(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 tf(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 Fr(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 sf(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let r=s[1];return t.split(`
760
768
  `).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(`
761
- `)}var ni=class{options;rules;lexer;constructor(e){this.options=e||Ue}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]:Wr(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=Gu(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=Me(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Me(t[0],`
769
+ `)}var ni=class{options;rules;lexer;constructor(e){this.options=e||Ue}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]:Br(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=sf(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=Me(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Me(t[0],`
762
770
  `),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:Me(t[0],`
763
771
  `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Me(t[0],`
764
772
  `).split(`
@@ -771,19 +779,19 @@ ${f}`:f;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
771
779
  `),F=this.blockquote(S);o[o.length-1]=F,s=s.substring(0,s.length-v.raw.length)+F.raw,r=r.substring(0,r.length-v.text.length)+F.text;break}else if(u?.type==="list"){let v=u,S=v.raw+`
772
780
  `+i.join(`
773
781
  `),F=this.list(S);o[o.length-1]=F,s=s.substring(0,s.length-u.raw.length)+F.raw,r=r.substring(0,r.length-v.raw.length)+F.raw,i=S.substring(o.at(-1).raw.length).split(`
774
- `);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="",f="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=Ku(t[2].split(`
782
+ `);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="",f="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=tf(t[2].split(`
775
783
  `,1)[0],t[1].length),u=e.split(`
776
784
  `,1)[0],v=!h.trim(),S=0;if(this.options.pedantic?(S=2,f=h.trimStart()):v?S=t[1].length+1:(S=h.search(this.rules.other.nonSpaceChar),S=S>4?1:S,f=h.slice(S),S+=t[1].length),v&&this.rules.other.blankLine.test(u)&&(p+=u+`
777
- `,e=e.substring(u.length+1),c=!0),!c){let F=this.rules.other.nextBulletRegex(S),Ke=this.rules.other.hrRegex(S),ot=this.rules.other.fencesBeginRegex(S),Ds=this.rules.other.headingBeginRegex(S),bn=this.rules.other.htmlBeginRegex(S),wn=this.rules.other.blockquoteBeginRegex(S);for(;e;){let wi=e.split(`
778
- `,1)[0],nt;if(u=wi,this.options.pedantic?(u=u.replace(this.rules.other.listReplaceNesting," "),nt=u):nt=u.replace(this.rules.other.tabCharGlobal," "),ot.test(u)||Ds.test(u)||bn.test(u)||wn.test(u)||F.test(u)||Ke.test(u))break;if(nt.search(this.rules.other.nonSpaceChar)>=S||!u.trim())f+=`
779
- `+nt.slice(S);else{if(v||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ot.test(h)||Ds.test(h)||Ke.test(h))break;f+=`
785
+ `,e=e.substring(u.length+1),c=!0),!c){let F=this.rules.other.nextBulletRegex(S),Ke=this.rules.other.hrRegex(S),ot=this.rules.other.fencesBeginRegex(S),_s=this.rules.other.headingBeginRegex(S),$n=this.rules.other.htmlBeginRegex(S),Pn=this.rules.other.blockquoteBeginRegex(S);for(;e;){let wi=e.split(`
786
+ `,1)[0],nt;if(u=wi,this.options.pedantic?(u=u.replace(this.rules.other.listReplaceNesting," "),nt=u):nt=u.replace(this.rules.other.tabCharGlobal," "),ot.test(u)||_s.test(u)||$n.test(u)||Pn.test(u)||F.test(u)||Ke.test(u))break;if(nt.search(this.rules.other.nonSpaceChar)>=S||!u.trim())f+=`
787
+ `+nt.slice(S);else{if(v||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ot.test(h)||_s.test(h)||Ke.test(h))break;f+=`
780
788
  `+u}v=!u.trim(),p+=wi+`
781
- `,e=e.substring(wi.length+1),h=nt.slice(S)}}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(f),loose:!1,text:f,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 f=this.rules.other.listTaskCheckbox.exec(c.raw);if(f){let h={type:"checkbox",raw:f[0]+" ",checked:f[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 f=c.tokens.filter(u=>u.type==="space"),h=f.length>0&&f.some(u=>this.rules.other.anyLine.test(u.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=Wr(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:Me(t[0],`
782
- `),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=Lr(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
789
+ `,e=e.substring(wi.length+1),h=nt.slice(S)}}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(f),loose:!1,text:f,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 f=this.rules.other.listTaskCheckbox.exec(c.raw);if(f){let h={type:"checkbox",raw:f[0]+" ",checked:f[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 f=c.tokens.filter(u=>u.type==="space"),h=f.length>0&&f.some(u=>this.rules.other.anyLine.test(u.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=Br(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:Me(t[0],`
790
+ `),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=Nr(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
783
791
  `):[],o={type:"table",raw:Me(t[0],`
784
- `),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(Lr(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:Me(t[0],`
792
+ `),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(Nr(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:Me(t[0],`
785
793
  `),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)===`
786
- `?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=Me(i.slice(0,-1),"\\");if((i.length-o.length)%2===0)return}else{let o=Vu(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)),jr(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 jr(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 f=[...s[0]][0].length,h=e.slice(0,r+s.index+f+n);if(Math.min(r,n)%2){let v=h.slice(1,-1);return{type:"em",raw:h,text:v,tokens:this.lexer.inlineTokens(v)}}let u=h.slice(2,-2);return{type:"strong",raw:h,text:u,tokens:this.lexer.inlineTokens(u)}}}}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,f=e.slice(0,r+s.index+p+n),h=f.slice(r,-r);return{type:"del",raw:f,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}}}},he=class Zi{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ue,this.options.tokenizer=this.options.tokenizer||new ni,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:H,block:Ot.normal,inline:ht.normal};this.options.pedantic?(i.block=Ot.pedantic,i.inline=ht.pedantic):this.options.gfm&&(i.block=Ot.gfm,this.options.breaks?i.inline=ht.breaks:i.inline=ht.gfm),this.tokenizer.rules=i}static get rules(){return{block:Ot,inline:ht}}static lex(t,i){return new Zi(i).lex(t)}static lexInline(t,i){return new Zi(i).inlineTokens(t)}lex(t){t=t.replace(H.carriageReturn,`
794
+ `?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=Me(i.slice(0,-1),"\\");if((i.length-o.length)%2===0)return}else{let o=ef(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)),Fr(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 Fr(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 f=[...s[0]][0].length,h=e.slice(0,r+s.index+f+n);if(Math.min(r,n)%2){let v=h.slice(1,-1);return{type:"em",raw:h,text:v,tokens:this.lexer.inlineTokens(v)}}let u=h.slice(2,-2);return{type:"strong",raw:h,text:u,tokens:this.lexer.inlineTokens(u)}}}}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,f=e.slice(0,r+s.index+p+n),h=f.slice(r,-r);return{type:"del",raw:f,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}}}},he=class Zi{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Ue,this.options.tokenizer=this.options.tokenizer||new ni,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:H,block:Ot.normal,inline:ht.normal};this.options.pedantic?(i.block=Ot.pedantic,i.inline=ht.pedantic):this.options.gfm&&(i.block=Ot.gfm,this.options.breaks?i.inline=ht.breaks:i.inline=ht.gfm),this.tokenizer.rules=i}static get rules(){return{block:Ot,inline:ht}}static lex(t,i){return new Zi(i).lex(t)}static lexInline(t,i){return new Zi(i).inlineTokens(t)}lex(t){t=t.replace(H.carriageReturn,`
787
795
  `),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(H.tabCharGlobal," ").replace(H.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+=`
788
796
  `: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(`
789
797
  `)?"":`
@@ -815,19 +823,19 @@ ${this.parser.parse(e)}</blockquote>
815
823
  `}tablerow({text:e}){return`<tr>
816
824
  ${e}</tr>
817
825
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
818
- `}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>${ge(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=Or(e);if(r===null)return s;e=r;let o='<a href="'+e+'"';return t&&(o+=' title="'+ge(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=Or(e);if(r===null)return ge(i);e=r;let o=`<img src="${e}" alt="${ge(i)}"`;return t&&(o+=` title="${ge(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:ge(e.text)}},As=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}},ue=class Xi{options;renderer;textRenderer;constructor(t){this.options=t||Ue,this.options.renderer=this.options.renderer||new ai,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new As}static parse(t,i){return new Xi(i).parse(t)}static parseInline(t,i){return new Xi(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}},ft=class{options;block;constructor(e){this.options=e||Ue}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?he.lex:he.lexInline}provideParser(e=this.block){return e?ue.parse:ue.parseInline}},Ju=class{defaults=Ss();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=ue;Renderer=ai;TextRenderer=As;Lexer=he;Tokenizer=ni;Hooks=ft;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 ai(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 f=a.apply(r,p);return f===!1&&(f=c.apply(r,p)),f||""}}s.renderer=r}if(i.tokenizer){let r=this.defaults.tokenizer||new ni(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 f=a.apply(r,p);return f===!1&&(f=c.apply(r,p)),f}}s.tokenizer=r}if(i.hooks){let r=this.defaults.hooks||new ft;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];ft.passThroughHooks.has(o)?r[n]=p=>{if(this.defaults.async&&ft.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await a.call(r,p);return c.call(r,h)})();let f=a.call(r,p);return c.call(r,f)}: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 f=a.apply(r,p);return f===!1&&(f=c.apply(r,p)),f}}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 he.lex(e,t??this.defaults)}parser(e,t){return ue.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?he.lex:he.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?ue.parse:ue.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?he.lex:he.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?ue.parse:ue.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+=`
819
- Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+ge(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},Ne=new Ju;function M(e,t){return Ne.parse(e,t)}M.options=M.setOptions=function(e){return Ne.setOptions(e),M.defaults=Ne.defaults,tn(M.defaults),M};M.getDefaults=Ss;M.defaults=Ue;M.use=function(...e){return Ne.use(...e),M.defaults=Ne.defaults,tn(M.defaults),M};M.walkTokens=function(e,t){return Ne.walkTokens(e,t)};M.parseInline=Ne.parseInline;M.Parser=ue;M.parser=ue.parse;M.Renderer=ai;M.TextRenderer=As;M.Lexer=he;M.lexer=he.lex;M.Tokenizer=ni;M.Hooks=ft;M.parse=M;M.options;M.setOptions;M.use;M.walkTokens;M.parseInline;ue.parse;he.lex;const hn=new M.Renderer;hn.html=({text:e})=>Xu(e);const Qu=300,ut=new Map;function Zu(e){const t=ut.get(e);if(t!==void 0)return t;const i=M.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:hn}),s=Yu(i);if(ut.set(e,s),ut.size>Qu){const r=ut.keys().next().value;r!==void 0&&ut.delete(r)}return s}function Xu(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function Yu(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")&&!ef(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function ef(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var tf=Object.defineProperty,sf=Object.getOwnPropertyDescriptor,un=(e,t,i,s)=>{for(var r=s>1?void 0:s?sf(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&&tf(t,i,r),r};let li=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)},this.onFormattedCopy=e=>{e.clipboardData===null||!nf(rf(this))||(e.clipboardData.setData("text/plain",this.text),e.preventDefault(),e.stopPropagation())}}render(){return l`<div class="formatted" @click=${this.onFormattedClick} @copy=${this.onFormattedCopy}>${lu(Zu(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 af(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)}};li.styles=ih;un([d()],li.prototype,"text",2);li=un([A("formatted-text")],li);function rf(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&of(t)?t.getSelection():e.ownerDocument.getSelection()}function of(e){return"getSelection"in e&&typeof e.getSelection=="function"}function nf(e){return e!==null&&!e.isCollapsed&&e.toString()!==""}async function af(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var lf=Object.defineProperty,cf=Object.getOwnPropertyDescriptor,It=(e,t,i,s)=>{for(var r=s>1?void 0:s?cf(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&&lf(t,i,r),r};const Nr=180;let Be=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=e.toolName==="edit",i=df(e.args),s=pf(e.details),r=e.preview,o=s??r?.diff,n=o===void 0?void 0:hf(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`
826
+ `}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>${ge(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=jr(e);if(r===null)return s;e=r;let o='<a href="'+e+'"';return t&&(o+=' title="'+ge(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=jr(e);if(r===null)return ge(i);e=r;let o=`<img src="${e}" alt="${ge(i)}"`;return t&&(o+=` title="${ge(t)}"`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:ge(e.text)}},Rs=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}},ue=class Xi{options;renderer;textRenderer;constructor(t){this.options=t||Ue,this.options.renderer=this.options.renderer||new ai,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Rs}static parse(t,i){return new Xi(i).parse(t)}static parseInline(t,i){return new Xi(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}},ft=class{options;block;constructor(e){this.options=e||Ue}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?he.lex:he.lexInline}provideParser(e=this.block){return e?ue.parse:ue.parseInline}},rf=class{defaults=ks();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=ue;Renderer=ai;TextRenderer=Rs;Lexer=he;Tokenizer=ni;Hooks=ft;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 ai(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 f=a.apply(r,p);return f===!1&&(f=c.apply(r,p)),f||""}}s.renderer=r}if(i.tokenizer){let r=this.defaults.tokenizer||new ni(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 f=a.apply(r,p);return f===!1&&(f=c.apply(r,p)),f}}s.tokenizer=r}if(i.hooks){let r=this.defaults.hooks||new ft;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];ft.passThroughHooks.has(o)?r[n]=p=>{if(this.defaults.async&&ft.passThroughHooksRespectAsync.has(o))return(async()=>{let h=await a.call(r,p);return c.call(r,h)})();let f=a.call(r,p);return c.call(r,f)}: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 f=a.apply(r,p);return f===!1&&(f=c.apply(r,p)),f}}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 he.lex(e,t??this.defaults)}parser(e,t){return ue.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?he.lex:he.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?ue.parse:ue.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?he.lex:he.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?ue.parse:ue.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+=`
827
+ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+ge(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},Ne=new rf;function M(e,t){return Ne.parse(e,t)}M.options=M.setOptions=function(e){return Ne.setOptions(e),M.defaults=Ne.defaults,ln(M.defaults),M};M.getDefaults=ks;M.defaults=Ue;M.use=function(...e){return Ne.use(...e),M.defaults=Ne.defaults,ln(M.defaults),M};M.walkTokens=function(e,t){return Ne.walkTokens(e,t)};M.parseInline=Ne.parseInline;M.Parser=ue;M.parser=ue.parse;M.Renderer=ai;M.TextRenderer=Rs;M.Lexer=he;M.lexer=he.lex;M.Tokenizer=ni;M.Hooks=ft;M.parse=M;M.options;M.setOptions;M.use;M.walkTokens;M.parseInline;ue.parse;he.lex;const bn=new M.Renderer;bn.html=({text:e})=>af(e);const of=300,ut=new Map;function nf(e){const t=ut.get(e);if(t!==void 0)return t;const i=M.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:bn}),s=lf(i);if(ut.set(e,s),ut.size>of){const r=ut.keys().next().value;r!==void 0&&ut.delete(r)}return s}function af(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function lf(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")&&!cf(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function cf(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var df=Object.defineProperty,pf=Object.getOwnPropertyDescriptor,wn=(e,t,i,s)=>{for(var r=s>1?void 0:s?pf(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&&df(t,i,r),r};let li=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)},this.onFormattedCopy=e=>{e.clipboardData===null||!ff(hf(this))||(e.clipboardData.setData("text/plain",this.text),e.preventDefault(),e.stopPropagation())}}render(){return l`<div class="formatted" @click=${this.onFormattedClick} @copy=${this.onFormattedCopy}>${gu(nf(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 mf(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)}};li.styles=dh;wn([d()],li.prototype,"text",2);li=wn([A("formatted-text")],li);function hf(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&uf(t)?t.getSelection():e.ownerDocument.getSelection()}function uf(e){return"getSelection"in e&&typeof e.getSelection=="function"}function ff(e){return e!==null&&!e.isCollapsed&&e.toString()!==""}async function mf(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var gf=Object.defineProperty,vf=Object.getOwnPropertyDescriptor,It=(e,t,i,s)=>{for(var r=s>1?void 0:s?vf(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&&gf(t,i,r),r};const zr=180;let Be=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=e.toolName==="edit",i=bf(e.args),s=wf(e.details),r=e.preview,o=s??r?.diff,n=o===void 0?void 0:yf(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`
820
828
  <section class=${`tool-card ${e.status}`}>
821
829
  <div class="tool-header">
822
830
  <div class="tool-title">
823
- <span class="status-icon" aria-hidden="true">${ff(e.status)}</span>
831
+ <span class="status-icon" aria-hidden="true">${Sf(e.status)}</span>
824
832
  <strong>${e.toolName}</strong>
825
833
  ${i===void 0?l`<span class="summary">${e.summary}</span>`:l`<span class="path">${i}</span>`}
826
834
  </div>
827
835
  <div class="tool-meta">
828
- ${Br(e)===void 0?null:l`<span>${Br(e)}</span>`}
836
+ ${Ur(e)===void 0?null:l`<span>${Ur(e)}</span>`}
829
837
  ${n===void 0?null:l`<span class="diff-stats"><b class="added">+${n.added}</b><span>/</span><b class="removed">-${n.removed}</b></span>`}
830
- <span class="status-label">${mf(e.status)}</span>
838
+ <span class="status-label">${kf(e.status)}</span>
831
839
  </div>
832
840
  </div>
833
841
 
@@ -842,7 +850,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
842
850
  <pre>${e}</pre>
843
851
  </details>
844
852
  `}renderDiffBody(e,t){const i=e.split(`
845
- `),s=!this.showFullDiff&&i.length>Nr,r=s?i.slice(0,Nr):i;return l`
853
+ `),s=!this.showFullDiff&&i.length>zr,r=s?i.slice(0,zr):i;return l`
846
854
  <details class="diff-details" ?open=${this.diffOpen} @toggle=${o=>{this.onDiffToggle(o)}}>
847
855
  <summary>
848
856
  <span>${t}</span>
@@ -852,7 +860,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
852
860
  <span>${s?`显示 ${String(r.length)} / ${String(i.length)} 行`:"完整 diff"}</span>
853
861
  <button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"已复制":"复制 diff"}</button>
854
862
  </div>
855
- <pre class="diff" aria-label=${t}><code class="diff-content">${r.map(o=>l`<span class=${uf(o)}>${o}</span>`)}</code></pre>
863
+ <pre class="diff" aria-label=${t}><code class="diff-content">${r.map(o=>l`<span class=${xf(o)}>${o}</span>`)}</code></pre>
856
864
  ${s?l`
857
865
  <button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
858
866
  显示全部 ${String(i.length)} 行 diff
@@ -899,19 +907,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
899
907
  .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
900
908
  .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
901
909
  .show-more { justify-self: start; }
902
- `;It([d({attribute:!1})],Be.prototype,"execution",2);It([x()],Be.prototype,"showFullDiff",2);It([x()],Be.prototype,"copied",2);It([x()],Be.prototype,"diffOpen",2);Be=It([A("tool-execution-view")],Be);function df(e){return Yi(e,"path")??Yi(e,"file_path")}function Br(e){if(e.toolName!=="edit")return;const t=qt(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof qt(e.args,"oldText")=="string"&&typeof qt(e.args,"newText")=="string")return"1 处编辑"}function pf(e){return Yi(e,"diff")}function hf(e){let t=0,i=0;for(const s of e.split(`
903
- `))fn(s)?t++:mn(s)&&i++;return{added:t,removed:i}}function uf(e){return fn(e)?"added":mn(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function fn(e){return e.startsWith("+")&&!e.startsWith("+++")}function mn(e){return e.startsWith("-")&&!e.startsWith("---")}function ff(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function mf(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function gf(e){return typeof e=="object"&&e!==null}function qt(e,t){return gf(e)?e[t]:void 0}function Yi(e,t){const i=qt(e,t);return typeof i=="string"?i:void 0}var vf=Object.defineProperty,bf=Object.getOwnPropertyDescriptor,B=(e,t,i,s)=>{for(var r=s>1?void 0:s?bf(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&&vf(t,i,r),r};const wf=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),yf=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),Oi=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"];function Fr(){return Oi[Math.floor(Math.random()*Oi.length)]??Oi[0]}function zr(e){return Vt(e,0,100)}function Vt(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let L=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.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.disclosures=new Rh,this.scrollController=new tu,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`
910
+ `;It([d({attribute:!1})],Be.prototype,"execution",2);It([x()],Be.prototype,"showFullDiff",2);It([x()],Be.prototype,"copied",2);It([x()],Be.prototype,"diffOpen",2);Be=It([A("tool-execution-view")],Be);function bf(e){return Yi(e,"path")??Yi(e,"file_path")}function Ur(e){if(e.toolName!=="edit")return;const t=qt(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof qt(e.args,"oldText")=="string"&&typeof qt(e.args,"newText")=="string")return"1 处编辑"}function wf(e){return Yi(e,"diff")}function yf(e){let t=0,i=0;for(const s of e.split(`
911
+ `))yn(s)?t++:xn(s)&&i++;return{added:t,removed:i}}function xf(e){return yn(e)?"added":xn(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function yn(e){return e.startsWith("+")&&!e.startsWith("+++")}function xn(e){return e.startsWith("-")&&!e.startsWith("---")}function Sf(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function kf(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function $f(e){return typeof e=="object"&&e!==null}function qt(e,t){return $f(e)?e[t]:void 0}function Yi(e,t){const i=qt(e,t);return typeof i=="string"?i:void 0}var Pf=Object.defineProperty,Tf=Object.getOwnPropertyDescriptor,B=(e,t,i,s)=>{for(var r=s>1?void 0:s?Tf(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&&Pf(t,i,r),r};const Cf=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),If=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),Oi=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"];function Hr(){return Oi[Math.floor(Math.random()*Oi.length)]??Oi[0]}function qr(e){return Vt(e,0,100)}function Vt(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let L=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.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.disclosures=new Nh,this.scrollController=new cu,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`
904
912
  <div class="chat-wrap">
905
913
  ${this.renderConversationRail()}
906
914
  <div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
907
915
  ${this.renderHistoryBoundary()}
908
- ${Ih(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)))}
916
+ ${Lh(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)))}
909
917
  ${this.renderQueuedMessages()}
910
918
  ${this.renderSessionActivity()}
911
919
  </div>
912
920
  ${this.renderActivityDock()}
913
921
  </div>
914
- `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=_h(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){const e=this.activityState();if(e===void 0)return null;const t=e!=="idle"||this.activity?.phase==="active";return l`
922
+ `}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=zh(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){const e=this.activityState();if(e===void 0)return null;const t=e!=="idle"||this.activity?.phase==="active";return l`
915
923
  <div class=${t?"activity-dock active":"activity-dock"} aria-live="polite">
916
924
  <span class="dot"></span>
917
925
  <span class="activity-text">${this.activityText(e)}</span>
@@ -940,7 +948,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
940
948
  <span>助手正在总结早前上下文。压缩完成前,新提示会排队等待。</span>
941
949
  ${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} 条消息已排队</small>`:null}
942
950
  </aside>
943
- `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Fr():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Fr(),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;return t===void 0?e:e!=="idle"&&t.phase==="idle"?xf(e):t.detail!==void 0&&t.detail!==""?`${t.label}: ${t.detail}`:t.label}renderConversationRail(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.conversationDisplayTotal(),t=this.conversationPositionPercent(e),i=this.hasMore?zr(this.messages.length/e*100):100;return 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=Vt(this.currentConversationIndex??t,0,e-1);return zr(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?l`
951
+ `:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Hr():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Hr(),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;return t===void 0?e:e!=="idle"&&t.phase==="idle"?Mf(e):t.detail!==void 0&&t.detail!==""?`${t.label}: ${t.detail}`:t.label}renderConversationRail(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.conversationDisplayTotal(),t=this.conversationPositionPercent(e),i=this.hasMore?qr(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=Vt(this.currentConversationIndex??t,0,e-1);return qr(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?l`
944
952
  <div class="history-boundary">
945
953
  <button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>加载更早的消息</button>
946
954
  <span>向上滚动加载更早的消息</span>
@@ -957,7 +965,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
957
965
  <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)}}>
958
966
  <summary>
959
967
  <b class="label">${s?"实时事件":"事件"}</b>
960
- <span>${Oh(e)}</span>
968
+ <span>${Uh(e)}</span>
961
969
  </summary>
962
970
  <div class="group-body">
963
971
  ${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
@@ -970,7 +978,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
970
978
  </details>
971
979
  `}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`
972
980
  <div class="msg-header">
973
- <b class="label">${Ur(e.role)}</b>
981
+ <b class="label">${Vr(e.role)}</b>
974
982
  <div class="msg-header-trailing">
975
983
  ${this.renderMessageActions(e,t)}
976
984
  <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>
@@ -978,13 +986,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
978
986
  </div>
979
987
  `}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return l`
980
988
  <div class="msg-actions" aria-label="消息操作">
981
- <button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${Ur(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
989
+ <button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${Vr(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
982
990
  <span aria-hidden="true">${i?"✓":"⧉"}</span>
983
991
  </button>
984
992
  </div>
985
993
  `}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(`
986
994
 
987
- `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await this.writeClipboard(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const c={short:"无信息",full:"没有可用的 Pi 消息元数据"};return this.messageMetaCache.set(e,c),c}const 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:wf.format(t),full:yf.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==="thinking"?l`<details class="part"><summary>思考</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
995
+ `);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await this.writeClipboard(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const c={short:"无信息",full:"没有可用的 Pi 消息元数据"};return this.messageMetaCache.set(e,c),c}const 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:Cf.format(t),full:If.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==="thinking"?l`<details class="part"><summary>思考</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
988
996
  <details class="part skill-invocation">
989
997
  <summary><b>[技能]</b> ${e.name}</summary>
990
998
  <small>${e.location}</small>
@@ -1000,17 +1008,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1000
1008
  <summary>${e.isError?"✖":"✓"} ${e.toolName} 结果</summary>
1001
1009
  <formatted-text .text=${e.text}></formatted-text>
1002
1010
  </details>
1003
- `: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&&Vh({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?en(e):!0}isAtBottom(){const e=this.chat;return e?Yo(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 jh(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(Nh(r,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=r.scrollTop,i+=1,i<Wh){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=Vt(i,0,Math.max(0,e-1));return}this.currentConversationIndex=Vt(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 Ar(e,t)??Ar(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll("[data-scroll-anchor-id]"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,i){return i?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return`m:${String(e)}`}groupRenderKey(e){return`g:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}eventAnchorKey(e){return`e:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}};L.styles=th;B([d({attribute:!1})],L.prototype,"messages",2);B([d()],L.prototype,"sessionId",2);B([d({type:Number})],L.prototype,"messageStart",2);B([d({type:Number})],L.prototype,"messageEnd",2);B([d({type:Number})],L.prototype,"messageTotal",2);B([d({type:Boolean})],L.prototype,"hasMore",2);B([d({type:Boolean})],L.prototype,"loadingMore",2);B([d({type:Boolean})],L.prototype,"isReceivingPartialStream",2);B([d({type:Boolean})],L.prototype,"isCompacting",2);B([d({type:Number})],L.prototype,"pendingMessageCount",2);B([d({attribute:!1})],L.prototype,"status",2);B([d({attribute:!1})],L.prototype,"activity",2);B([d({attribute:!1})],L.prototype,"onLoadMore",2);B([re(".chat")],L.prototype,"chat",2);B([x()],L.prototype,"pinnedToBottom",2);B([x()],L.prototype,"expandedMetaKey",2);B([x()],L.prototype,"copiedMessageKey",2);B([x()],L.prototype,"currentConversationIndex",2);B([x()],L.prototype,"loadMoreRequested",2);L=B([A("chat-view")],L);function Ur(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function xf(e){return e==="compacting"?"正在压缩":e==="bash"?"Shell 运行中":e==="running"?"运行中":e==="queued"?"已排队":e==="idle"?"空闲":e}class Sf extends ws{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===vs.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 Rs=bs(Sf);var kf=Object.defineProperty,$f=Object.getOwnPropertyDescriptor,bi=(e,t,i,s)=>{for(var r=s>1?void 0:s?$f(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&&kf(t,i,r),r};let tt=class extends I{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
1011
+ `: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&&eu({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?an(e):!0}isAtBottom(){const e=this.chat;return e?nn(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 Vh(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(Kh(r,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=r.scrollTop,i+=1,i<qh){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=Vt(i,0,Math.max(0,e-1));return}this.currentConversationIndex=Vt(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 Dr(e,t)??Dr(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll("[data-scroll-anchor-id]"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,i){return i?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return`m:${String(e)}`}groupRenderKey(e){return`g:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}eventAnchorKey(e){return`e:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}};L.styles=ch;B([d({attribute:!1})],L.prototype,"messages",2);B([d()],L.prototype,"sessionId",2);B([d({type:Number})],L.prototype,"messageStart",2);B([d({type:Number})],L.prototype,"messageEnd",2);B([d({type:Number})],L.prototype,"messageTotal",2);B([d({type:Boolean})],L.prototype,"hasMore",2);B([d({type:Boolean})],L.prototype,"loadingMore",2);B([d({type:Boolean})],L.prototype,"isReceivingPartialStream",2);B([d({type:Boolean})],L.prototype,"isCompacting",2);B([d({type:Number})],L.prototype,"pendingMessageCount",2);B([d({attribute:!1})],L.prototype,"status",2);B([d({attribute:!1})],L.prototype,"activity",2);B([d({attribute:!1})],L.prototype,"onLoadMore",2);B([re(".chat")],L.prototype,"chat",2);B([x()],L.prototype,"pinnedToBottom",2);B([x()],L.prototype,"expandedMetaKey",2);B([x()],L.prototype,"copiedMessageKey",2);B([x()],L.prototype,"currentConversationIndex",2);B([x()],L.prototype,"loadMoreRequested",2);L=B([A("chat-view")],L);function Vr(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Mf(e){return e==="compacting"?"正在压缩":e==="bash"?"Shell 运行中":e==="running"?"运行中":e==="queued"?"已排队":e==="idle"?"空闲":e}class Af extends ys{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===bs.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 Es=ws(Af);var Rf=Object.defineProperty,Ef=Object.getOwnPropertyDescriptor,bi=(e,t,i,s)=>{for(var r=s>1?void 0:s?Ef(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&&Rf(t,i,r),r};let tt=class extends I{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
1004
1012
  <div class="menu">
1005
1013
  ${this.items.map((e,t)=>l`
1006
- <button class=${t===this.selectedIndex?"selected":""} ${Rs(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1014
+ <button class=${t===this.selectedIndex?"selected":""} ${Es(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
1007
1015
  <strong>${e.insertText}</strong>
1008
1016
  <span>${e.detail}</span>
1009
1017
  ${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
1010
1018
  </button>
1011
1019
  `)}
1012
1020
  </div>
1013
- `:null}};tt.styles=rh;bi([d({attribute:!1})],tt.prototype,"items",2);bi([d({type:Number})],tt.prototype,"selectedIndex",2);bi([d({attribute:!1})],tt.prototype,"onPick",2);tt=bi([A("autocomplete-menu")],tt);var Pf=Object.defineProperty,Tf=Object.getOwnPropertyDescriptor,U=(e,t,i,s)=>{for(var r=s>1?void 0:s?Tf(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&&Pf(t,i,r),r};let z=class extends I{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.draft="",this.completions=[],this.selectedIndex=0,this.requestVersion=0,this.editableCompartment=new _s,this.readOnlyCompartment=new _s}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=Lt(i,t);s!==void 0&&ei(s,this.draft);const r=Lt(this.machineId,this.sessionId);this.draft=r!==void 0?wo(r):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("draft")||e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=us(this.draft),t=e.kind==="shell",i=this.canSteer||this.isCompacting;return l`
1021
+ `:null}};tt.styles=hh;bi([d({attribute:!1})],tt.prototype,"items",2);bi([d({type:Number})],tt.prototype,"selectedIndex",2);bi([d({attribute:!1})],tt.prototype,"onPick",2);tt=bi([A("autocomplete-menu")],tt);var Df=Object.defineProperty,_f=Object.getOwnPropertyDescriptor,U=(e,t,i,s)=>{for(var r=s>1?void 0:s?_f(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&&Df(t,i,r),r};let z=class extends I{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.draft="",this.completions=[],this.selectedIndex=0,this.requestVersion=0,this.editableCompartment=new Os,this.readOnlyCompartment=new Os}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=Lt(i,t);s!==void 0&&ei(s,this.draft);const r=Lt(this.machineId,this.sessionId);this.draft=r!==void 0?Po(r):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("draft")||e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=fs(this.draft),t=e.kind==="shell",i=this.canSteer||this.isCompacting;return l`
1014
1022
  <footer class=${t?"shell-mode":""}>
1015
1023
  <div class="editor-wrap">
1016
1024
  <div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="给 pi 发送消息" aria-disabled=${this.disabled?"true":"false"}></div>
@@ -1028,20 +1036,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1028
1036
  `}focusInput(){this.editor?.focus()}renderCompactStatus(){const e=this.status;if(e===void 0)return null;const t=e.model?.id??"未选择模型",i=e.model?.provider!==void 0&&e.model.provider!==""?`${e.model.provider}/`:"";return l`
1029
1037
  <div class="compact-status" aria-label="会话状态">
1030
1038
  <button class="select-model" title="选择模型" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
1031
- <button class="select-thinking" title="选择思考级别" @click=${()=>this.onSelectThinking?.()}>思考 ${Af(e.thinkingLevel)}</button>
1039
+ <button class="select-thinking" title="选择思考级别" @click=${()=>this.onSelectThinking?.()}>思考 ${jf(e.thinkingLevel)}</button>
1032
1040
  </div>
1033
- `}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new Ge({parent:this.editorHost,state:yi.create({doc:this.draft,extensions:[yn(),An(),xn(),Sn.of(" "),kn(Mn,{fallback:!0}),Ge.lineWrapping,Ge.contentAttributes.of(e=>Df(e.state.sliceDoc(0,e.state.selection.main.head))),$n("给 pi 发送消息... 使用 / 输入命令,使用 @ 引用跟踪文件,使用 @ 空格查看全部文件"),this.editableCompartment.of(Ge.editable.of(!this.disabled)),this.readOnlyCompartment.of(yi.readOnly.of(this.disabled)),Ge.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Pn.of([{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Enter",run:()=>this.handleEditorEnter()},{key:"Shift-Enter",run:e=>Rn(e)||In(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>Os.shift?.(e)??!1},{key:"Backspace",run:e=>En(e)},...Tn,...Cn])]})}))}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:Ls.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(Ge.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(yi.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Lt(this.machineId,this.sessionId);t!==void 0&&ei(t,this.draft),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""){const i=await _.commands(this.sessionId,this.machineId).catch(If);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 _.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId}).catch(Mf);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const r=Cf(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(){const e=this.editor?.state.selection.main.head??this.draft.length,t=this.draft.slice(0,e),i=this.currentQuotedTrigger(t,e);if(i!==void 0)return i;const s=Math.max(t.lastIndexOf(" "),t.lastIndexOf(`
1034
- `))+1,r=t.slice(s);if(t.slice(0,s).endsWith("@ "))return{kind:"file",query:r,from:s-2,to:e,fileScope:"all",allPrefix:"@ "};if(r.startsWith("/")&&s===0)return{kind:"command",query:r.slice(1),from:s,to:e};if(r.startsWith("!@"))return{kind:"file",query:r.slice(2),from:s,to:e,fileScope:"all",allPrefix:"!@"};if(r.startsWith("@"))return{kind:"file",query:r.slice(1),from:s,to:e,fileScope:"tracked"}}currentQuotedTrigger(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}}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorEnter(){if(this.completions.length){const e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):Os.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:Ls.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){const t=this.draft.trim();if(t===""||this.disabled)return;this.draft="";const i=Lt(this.machineId,this.sessionId);i!==void 0&&hs(i),this.completions=[],this.onSend?.(t,this.canSteer||this.isCompacting?e:void 0)}};z.styles=nh;U([d({type:Boolean})],z.prototype,"disabled",2);U([d()],z.prototype,"sessionId",2);U([d()],z.prototype,"cwd",2);U([d()],z.prototype,"machineId",2);U([d({type:Boolean})],z.prototype,"canSteer",2);U([d({type:Boolean})],z.prototype,"isCompacting",2);U([d({type:Boolean})],z.prototype,"canStop",2);U([d({attribute:!1})],z.prototype,"status",2);U([d({attribute:!1})],z.prototype,"onSend",2);U([d({attribute:!1})],z.prototype,"onStop",2);U([d({attribute:!1})],z.prototype,"onSelectModel",2);U([d({attribute:!1})],z.prototype,"onSelectThinking",2);U([re(".markdown-editor")],z.prototype,"editorHost",2);U([x()],z.prototype,"draft",2);U([x()],z.prototype,"completions",2);U([x()],z.prototype,"selectedIndex",2);z=U([A("prompt-editor")],z);function Lt(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return bo(e,t)}function Cf(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function If(){return[]}function Mf(){return[]}function Af(e){return e===void 0||e==="off"?"关闭":e==="minimal"?"极简":e==="low"?"低":e==="medium"?"中":e==="high"?"高":e==="xhigh"?"超高":e}const Rf={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},Ef={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function Df(e){return us(e).kind==="normal"?Rf:Ef}function Wt(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 _f(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var Of=Object.defineProperty,Lf=Object.getOwnPropertyDescriptor,Mt=(e,t,i,s)=>{for(var r=s>1?void 0:s?Lf(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&&Of(t,i,r),r};let Fe=class extends I{constructor(){super(...arguments),this.workspaceLabelItems=[]}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?`上下文 ${Wt(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Wt(t.contextWindow)}`:"上下文未知",s=e.tokens;return l`
1041
+ `}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new Ge({parent:this.editorHost,state:yi.create({doc:this.draft,extensions:[Tn(),Ln(),Cn(),In.of(" "),Mn(On,{fallback:!0}),Ge.lineWrapping,Ge.contentAttributes.of(e=>Ff(e.state.sliceDoc(0,e.state.selection.main.head))),An("给 pi 发送消息... 使用 / 输入命令,使用 @ 引用跟踪文件,使用 @ 空格查看全部文件"),this.editableCompartment.of(Ge.editable.of(!this.disabled)),this.readOnlyCompartment.of(yi.readOnly.of(this.disabled)),Ge.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Rn.of([{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Enter",run:()=>this.handleEditorEnter()},{key:"Shift-Enter",run:e=>Wn(e)||_n(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>Ls.shift?.(e)??!1},{key:"Backspace",run:e=>jn(e)},...En,...Dn])]})}))}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:Ws.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(Ge.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(yi.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Lt(this.machineId,this.sessionId);t!==void 0&&ei(t,this.draft),this.refreshCompletions()}async refreshCompletions(){const e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind==="command"&&this.sessionId!==void 0&&this.sessionId!==""){const i=await _.commands(this.sessionId,this.machineId).catch(Lf);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 _.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId}).catch(Wf);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const r=Of(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(){const e=this.editor?.state.selection.main.head??this.draft.length,t=this.draft.slice(0,e),i=this.currentQuotedTrigger(t,e);if(i!==void 0)return i;const s=Math.max(t.lastIndexOf(" "),t.lastIndexOf(`
1042
+ `))+1,r=t.slice(s);if(t.slice(0,s).endsWith("@ "))return{kind:"file",query:r,from:s-2,to:e,fileScope:"all",allPrefix:"@ "};if(r.startsWith("/")&&s===0)return{kind:"command",query:r.slice(1),from:s,to:e};if(r.startsWith("!@"))return{kind:"file",query:r.slice(2),from:s,to:e,fileScope:"all",allPrefix:"!@"};if(r.startsWith("@"))return{kind:"file",query:r.slice(1),from:s,to:e,fileScope:"tracked"}}currentQuotedTrigger(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}}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorEnter(){if(this.completions.length){const e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):Ls.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:Ws.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){const t=this.draft.trim();if(t===""||this.disabled)return;this.draft="";const i=Lt(this.machineId,this.sessionId);i!==void 0&&us(i),this.completions=[],this.onSend?.(t,this.canSteer||this.isCompacting?e:void 0)}};z.styles=fh;U([d({type:Boolean})],z.prototype,"disabled",2);U([d()],z.prototype,"sessionId",2);U([d()],z.prototype,"cwd",2);U([d()],z.prototype,"machineId",2);U([d({type:Boolean})],z.prototype,"canSteer",2);U([d({type:Boolean})],z.prototype,"isCompacting",2);U([d({type:Boolean})],z.prototype,"canStop",2);U([d({attribute:!1})],z.prototype,"status",2);U([d({attribute:!1})],z.prototype,"onSend",2);U([d({attribute:!1})],z.prototype,"onStop",2);U([d({attribute:!1})],z.prototype,"onSelectModel",2);U([d({attribute:!1})],z.prototype,"onSelectThinking",2);U([re(".markdown-editor")],z.prototype,"editorHost",2);U([x()],z.prototype,"draft",2);U([x()],z.prototype,"completions",2);U([x()],z.prototype,"selectedIndex",2);z=U([A("prompt-editor")],z);function Lt(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return $o(e,t)}function Of(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Lf(){return[]}function Wf(){return[]}function jf(e){return e===void 0||e==="off"?"关闭":e==="minimal"?"极简":e==="low"?"低":e==="medium"?"中":e==="high"?"高":e==="xhigh"?"超高":e}const Nf={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},Bf={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function Ff(e){return fs(e).kind==="normal"?Nf:Bf}function Wt(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 zf(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var Uf=Object.defineProperty,Hf=Object.getOwnPropertyDescriptor,Mt=(e,t,i,s)=>{for(var r=s>1?void 0:s?Hf(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&&Uf(t,i,r),r};let Fe=class extends I{constructor(){super(...arguments),this.workspaceLabelItems=[]}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?`上下文 ${Wt(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Wt(t.contextWindow)}`:"上下文未知",s=e.tokens;return l`
1035
1043
  <div class="bar">
1036
1044
  <span>${this.machine?.name??"本机"}</span>
1037
- <span>${Qo(this.workspace?.label??"工作区",this.workspaceLabelItems,this.workspace?.path)}</span>
1045
+ <span>${sn(this.workspace?.label??"工作区",this.workspaceLabelItems,this.workspace?.path)}</span>
1038
1046
  <span>↑${Wt(s.input)}</span>
1039
1047
  <span>↓${Wt(s.output)}</span>
1040
1048
  <span>${i}</span>
1041
- <span>${_f(e.cost)}</span>
1049
+ <span>${zf(e.cost)}</span>
1042
1050
  ${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} 条排队</span>`:null}
1043
1051
  </div>
1044
- `}};Fe.styles=sh;Mt([d({attribute:!1})],Fe.prototype,"status",2);Mt([d({attribute:!1})],Fe.prototype,"machine",2);Mt([d({attribute:!1})],Fe.prototype,"workspace",2);Mt([d({attribute:!1})],Fe.prototype,"workspaceLabelItems",2);Fe=Mt([A("status-bar")],Fe);var Wf=Object.defineProperty,jf=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var r=s>1?void 0:s?jf(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&&Wf(t,i,r),r};let fe=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`
1052
+ `}};Fe.styles=ph;Mt([d({attribute:!1})],Fe.prototype,"status",2);Mt([d({attribute:!1})],Fe.prototype,"machine",2);Mt([d({attribute:!1})],Fe.prototype,"workspace",2);Mt([d({attribute:!1})],Fe.prototype,"workspaceLabelItems",2);Fe=Mt([A("status-bar")],Fe);var qf=Object.defineProperty,Vf=Object.getOwnPropertyDescriptor,Ce=(e,t,i,s)=>{for(var r=s>1?void 0:s?Vf(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&&qf(t,i,r),r};let fe=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`
1045
1053
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1046
1054
  <section @mousedown=${t=>{t.stopPropagation()}}>
1047
1055
  <header>
@@ -1051,7 +1059,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1051
1059
  ${this.searchable?l`<input placeholder="搜索" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
1052
1060
  <div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
1053
1061
  ${e.map((t,i)=>l`
1054
- <button class=${i===this.selectedIndex?"selected":""} ${Rs(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1062
+ <button class=${i===this.selectedIndex?"selected":""} ${Es(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
1055
1063
  <span>${t.label}</span>
1056
1064
  ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1057
1065
  </button>
@@ -1060,7 +1068,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1060
1068
  </div>
1061
1069
  </section>
1062
1070
  </div>
1063
- `}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)}}};fe.styles=Jo;Ce([d()],fe.prototype,"title",2);Ce([d({type:Boolean})],fe.prototype,"searchable",2);Ce([d({attribute:!1})],fe.prototype,"options",2);Ce([d({attribute:!1})],fe.prototype,"selectedValue",2);Ce([d({attribute:!1})],fe.prototype,"onPick",2);Ce([d({attribute:!1})],fe.prototype,"onCancel",2);Ce([x()],fe.prototype,"selectedIndex",2);Ce([x()],fe.prototype,"query",2);fe=Ce([A("command-picker")],fe);var Nf=Object.defineProperty,Bf=Object.getOwnPropertyDescriptor,He=(e,t,i,s)=>{for(var r=s>1?void 0:s?Bf(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&&Nf(t,i,r),r};let $e=class extends I{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
1071
+ `}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)}}};fe.styles=tn;Ce([d()],fe.prototype,"title",2);Ce([d({type:Boolean})],fe.prototype,"searchable",2);Ce([d({attribute:!1})],fe.prototype,"options",2);Ce([d({attribute:!1})],fe.prototype,"selectedValue",2);Ce([d({attribute:!1})],fe.prototype,"onPick",2);Ce([d({attribute:!1})],fe.prototype,"onCancel",2);Ce([x()],fe.prototype,"selectedIndex",2);Ce([x()],fe.prototype,"query",2);fe=Ce([A("command-picker")],fe);var Kf=Object.defineProperty,Gf=Object.getOwnPropertyDescriptor,He=(e,t,i,s)=>{for(var r=s>1?void 0:s?Gf(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&&Kf(t,i,r),r};let $e=class extends I{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
1064
1072
  <div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
1065
1073
  <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1066
1074
  <header>
@@ -1073,19 +1081,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1073
1081
  </header>
1074
1082
  <div class="options">
1075
1083
  ${e.length===0?l`<div class="empty">未找到操作。</div>`:e.map((t,i)=>l`
1076
- <button class=${i===this.selectedIndex?"selected":""} ${Rs(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1084
+ <button class=${i===this.selectedIndex?"selected":""} ${Es(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
1077
1085
  <span class="main">
1078
1086
  <strong>${t.title}</strong>
1079
1087
  ${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
1080
1088
  </span>
1081
- ${t.shortcut!==void 0?l`<kbd>${Mo(t.shortcut)}</kbd>`:null}
1089
+ ${t.shortcut!==void 0?l`<kbd>${Oo(t.shortcut)}</kbd>`:null}
1082
1090
  ${t.group!==void 0&&t.group!==""?l`<small class="group">${t.group}</small>`:null}
1083
1091
  </button>
1084
1092
  `)}
1085
1093
  </div>
1086
1094
  </section>
1087
1095
  </div>
1088
- `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){const e=this.queryText.trim().toLowerCase();return this.actions.filter(t=>t.enabled!==!1).filter(t=>e===""?!0:[t.title,t.description??"",t.group??"",t.shortcut??""].join(" ").toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){this.onRun?.(e)}};$e.styles=oh;He([d({attribute:!1})],$e.prototype,"actions",2);He([d({attribute:!1})],$e.prototype,"onRun",2);He([d({attribute:!1})],$e.prototype,"onCancel",2);He([re("input")],$e.prototype,"input",2);He([x()],$e.prototype,"queryText",2);He([x()],$e.prototype,"selectedIndex",2);$e=He([A("action-palette")],$e);var Ff=Object.defineProperty,zf=Object.getOwnPropertyDescriptor,ae=(e,t,i,s)=>{for(var r=s>1?void 0:s?zf(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&&Ff(t,i,r),r};let G=class extends I{render(){const e=this.state;return e===void 0?null:l`
1096
+ `}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){const e=this.queryText.trim().toLowerCase();return this.actions.filter(t=>t.enabled!==!1).filter(t=>e===""?!0:[t.title,t.description??"",t.group??"",t.shortcut??""].join(" ").toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){this.onRun?.(e)}};$e.styles=uh;He([d({attribute:!1})],$e.prototype,"actions",2);He([d({attribute:!1})],$e.prototype,"onRun",2);He([d({attribute:!1})],$e.prototype,"onCancel",2);He([re("input")],$e.prototype,"input",2);He([x()],$e.prototype,"queryText",2);He([x()],$e.prototype,"selectedIndex",2);$e=He([A("action-palette")],$e);var Jf=Object.defineProperty,Qf=Object.getOwnPropertyDescriptor,ae=(e,t,i,s)=>{for(var r=s>1?void 0:s?Qf(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&&Jf(t,i,r),r};let G=class extends I{render(){const e=this.state;return e===void 0?null:l`
1089
1097
  <div class="backdrop" @mousedown=${()=>{this.cancel()}}>
1090
1098
  <section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
1091
1099
  <header>
@@ -1108,11 +1116,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1108
1116
  <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>
1109
1117
  </div>
1110
1118
  `;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`
1111
- <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Hr(t.authType)}</small></button>
1119
+ <button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Kr(t.authType)}</small></button>
1112
1120
  `)}</div>`}}renderProviderButton(e){return l`
1113
1121
  <button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
1114
- <span>${e.name}${e.status.source!==void 0?l` <em>${Hf(e)}</em>`:null}</span>
1115
- <small>${e.id} · ${Hr(e.authType)}</small>
1122
+ <span>${e.name}${e.status.source!==void 0?l` <em>${Xf(e)}</em>`:null}</span>
1123
+ <small>${e.id} · ${Kr(e.authType)}</small>
1116
1124
  </button>
1117
1125
  `}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
1118
1126
  <div class="form">
@@ -1132,10 +1140,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1132
1140
  <div class="inline-options">${s.options.map(r=>l`<button @click=${()=>{this.onOAuthRespond?.(r.value)}}>${r.label}</button>`)}</div>
1133
1141
  `:null}
1134
1142
  ${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
1135
- ${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??qf(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
1143
+ ${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??Yf(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
1136
1144
  ${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button></div>`:null}
1137
1145
  </div>
1138
- `}focusInputIfNeeded(){const e=Uf(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?.()}};G.styles=[Jo,E`
1146
+ `}focusInputIfNeeded(){const e=Zf(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?.()}};G.styles=[tn,E`
1139
1147
  .form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
1140
1148
  .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
1141
1149
  .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
@@ -1150,7 +1158,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1150
1158
  .progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
1151
1159
  .inline-options { display: grid; gap: 8px; }
1152
1160
  em { color: var(--pi-success); font-style: normal; font-size: 12px; }
1153
- `];ae([d({attribute:!1})],G.prototype,"state",2);ae([d({attribute:!1})],G.prototype,"onChooseMethod",2);ae([d({attribute:!1})],G.prototype,"onSelectProvider",2);ae([d({attribute:!1})],G.prototype,"onApiKeyInput",2);ae([d({attribute:!1})],G.prototype,"onSaveApiKey",2);ae([d({attribute:!1})],G.prototype,"onLogoutProvider",2);ae([d({attribute:!1})],G.prototype,"onOAuthInput",2);ae([d({attribute:!1})],G.prototype,"onOAuthRespond",2);ae([d({attribute:!1})],G.prototype,"onOAuthCancel",2);ae([d({attribute:!1})],G.prototype,"onCancel",2);ae([re("input")],G.prototype,"input",2);G=ae([A("auth-dialog")],G);function Hr(e){return e==="oauth"?"订阅":"API key"}function Uf(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 Hf(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 qf(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var Vf=Object.defineProperty,Kf=Object.getOwnPropertyDescriptor,ye=(e,t,i,s)=>{for(var r=s>1?void 0:s?Kf(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&&Vf(t,i,r),r};let te=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 _.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`
1161
+ `];ae([d({attribute:!1})],G.prototype,"state",2);ae([d({attribute:!1})],G.prototype,"onChooseMethod",2);ae([d({attribute:!1})],G.prototype,"onSelectProvider",2);ae([d({attribute:!1})],G.prototype,"onApiKeyInput",2);ae([d({attribute:!1})],G.prototype,"onSaveApiKey",2);ae([d({attribute:!1})],G.prototype,"onLogoutProvider",2);ae([d({attribute:!1})],G.prototype,"onOAuthInput",2);ae([d({attribute:!1})],G.prototype,"onOAuthRespond",2);ae([d({attribute:!1})],G.prototype,"onOAuthCancel",2);ae([d({attribute:!1})],G.prototype,"onCancel",2);ae([re("input")],G.prototype,"input",2);G=ae([A("auth-dialog")],G);function Kr(e){return e==="oauth"?"订阅":"API key"}function Zf(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 Xf(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 Yf(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var em=Object.defineProperty,tm=Object.getOwnPropertyDescriptor,ye=(e,t,i,s)=>{for(var r=s>1?void 0:s?tm(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&&em(t,i,r),r};let te=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 _.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`
1154
1162
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1155
1163
  <section @click=${e=>{e.stopPropagation()}}>
1156
1164
  <header>
@@ -1200,7 +1208,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1200
1208
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1201
1209
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1202
1210
  button:disabled { opacity: .5; cursor: not-allowed; }
1203
- `;ye([d({attribute:!1})],te.prototype,"onSubmit",2);ye([d({attribute:!1})],te.prototype,"onCancel",2);ye([d()],te.prototype,"machineId",2);ye([x()],te.prototype,"path",2);ye([x()],te.prototype,"createMissing",2);ye([x()],te.prototype,"suggestions",2);ye([x()],te.prototype,"selected",2);ye([x()],te.prototype,"loading",2);ye([re("input")],te.prototype,"pathInput",2);te=ye([A("project-dialog")],te);var Gf=Object.defineProperty,Jf=Object.getOwnPropertyDescriptor,xe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Jf(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&&Gf(t,i,r),r};let ie=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=Qf(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"&&Li(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===""||Li(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?Li(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1211
+ `;ye([d({attribute:!1})],te.prototype,"onSubmit",2);ye([d({attribute:!1})],te.prototype,"onCancel",2);ye([d()],te.prototype,"machineId",2);ye([x()],te.prototype,"path",2);ye([x()],te.prototype,"createMissing",2);ye([x()],te.prototype,"suggestions",2);ye([x()],te.prototype,"selected",2);ye([x()],te.prototype,"loading",2);ye([re("input")],te.prototype,"pathInput",2);te=ye([A("project-dialog")],te);var im=Object.defineProperty,sm=Object.getOwnPropertyDescriptor,xe=(e,t,i,s)=>{for(var r=s>1?void 0:s?sm(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&&im(t,i,r),r};let ie=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=rm(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"&&Li(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===""||Li(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?Li(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
1204
1212
  <div class="backdrop" @click=${()=>this.onCancel?.()}>
1205
1213
  <section @click=${s=>{s.stopPropagation()}}>
1206
1214
  <form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
@@ -1255,8 +1263,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1255
1263
  header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
1256
1264
  .primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
1257
1265
  button:disabled { opacity: .5; cursor: not-allowed; }
1258
- `;xe([d({attribute:!1})],ie.prototype,"onSubmit",2);xe([d({attribute:!1})],ie.prototype,"onCancel",2);xe([d()],ie.prototype,"error",2);xe([x()],ie.prototype,"url",2);xe([x()],ie.prototype,"name",2);xe([x()],ie.prototype,"token",2);xe([x()],ie.prototype,"submitting",2);xe([re("input[name='baseUrl']")],ie.prototype,"urlInput",2);xe([re("input[name='name']")],ie.prototype,"nameInput",2);ie=xe([A("machine-dialog")],ie);function Qf(e){const t=e.trim();if(t==="")return"";const i=qr(t)??qr(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):Zf(t)}function Li(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 qr(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function Zf(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 Xf(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function Yf(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(`
1259
- `):""}}function em(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins}},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:tm(e.allowedHostsText),i}function tm(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}var im=Object.defineProperty,sm=Object.getOwnPropertyDescriptor,Se=(e,t,i,s)=>{for(var r=s>1?void 0:s?sm(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&&im(t,i,r),r};let se=class extends I{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=Xf(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=Yf(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
1266
+ `;xe([d({attribute:!1})],ie.prototype,"onSubmit",2);xe([d({attribute:!1})],ie.prototype,"onCancel",2);xe([d()],ie.prototype,"error",2);xe([x()],ie.prototype,"url",2);xe([x()],ie.prototype,"name",2);xe([x()],ie.prototype,"token",2);xe([x()],ie.prototype,"submitting",2);xe([re("input[name='baseUrl']")],ie.prototype,"urlInput",2);xe([re("input[name='name']")],ie.prototype,"nameInput",2);ie=xe([A("machine-dialog")],ie);function rm(e){const t=e.trim();if(t==="")return"";const i=Gr(t)??Gr(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):om(t)}function Li(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 Gr(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function om(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 nm(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function am(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(`
1267
+ `):""}}function lm(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins}},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:cm(e.allowedHostsText),i}function cm(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}var dm=Object.defineProperty,pm=Object.getOwnPropertyDescriptor,Se=(e,t,i,s)=>{for(var r=s>1?void 0:s?pm(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&&dm(t,i,r),r};let se=class extends I{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=nm(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=am(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
1260
1268
  <div class="section-heading">
1261
1269
  <div>
1262
1270
  <h2>通用配置</h2>
@@ -1277,7 +1285,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1277
1285
  <span>Host</span>
1278
1286
  ${this.renderOverrideBadge("host")}
1279
1287
  </span>
1280
- <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:Vr(t)})}}>
1288
+ <input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:Jr(t)})}}>
1281
1289
  <small>Web 服务器应绑定的地址。留空则使用 PI WEB 默认值。</small>
1282
1290
  </label>
1283
1291
 
@@ -1286,7 +1294,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1286
1294
  <span>Port</span>
1287
1295
  ${this.renderOverrideBadge("port")}
1288
1296
  </span>
1289
- <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:Vr(t)})}}>
1297
+ <input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:Jr(t)})}}>
1290
1298
  <small>TCP 端口,范围 1 到 65535。留空则使用 PI WEB 默认值。</small>
1291
1299
  </label>
1292
1300
 
@@ -1295,11 +1303,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1295
1303
  <span>允许的 hosts</span>
1296
1304
  ${this.renderOverrideBadge("allowedHosts")}
1297
1305
  </span>
1298
- <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:om(t)==="all"?"all":"list"})}}>
1306
+ <select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:um(t)==="all"?"all":"list"})}}>
1299
1307
  <option value="list">仅允许列出的 hosts</option>
1300
1308
  <option value="all">允许所有 host</option>
1301
1309
  </select>
1302
- <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:nm(t)})}}></textarea>
1310
+ <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:fm(t)})}}></textarea>
1303
1311
  <small>每行输入一个 host,或选择“允许所有 host”写入 <code>true</code>。</small>
1304
1312
  </div>
1305
1313
 
@@ -1316,10 +1324,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1316
1324
  <dl>
1317
1325
  <div><dt>Host</dt><dd>${e.host??l`<span class="muted">默认 127.0.0.1</span>`}</dd></div>
1318
1326
  <div><dt>端口</dt><dd>${e.port??l`<span class="muted">默认 8504</span>`}</dd></div>
1319
- <div><dt>允许的 hosts</dt><dd>${rm(e.allowedHosts)}</dd></div>
1327
+ <div><dt>允许的 hosts</dt><dd>${hm(e.allowedHosts)}</dd></div>
1320
1328
  </dl>
1321
1329
  </section>
1322
- `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(em(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=am(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};se.styles=E`
1330
+ `}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(lm(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=mm(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};se.styles=E`
1323
1331
  :host { display: block; }
1324
1332
  .section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
1325
1333
  .section-heading > div { display: grid; gap: 6px; min-width: 0; }
@@ -1361,7 +1369,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1361
1369
  .section-heading .secondary { justify-self: start; }
1362
1370
  .effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
1363
1371
  }
1364
- `;Se([d({attribute:!1})],se.prototype,"configResponse",2);Se([d({type:Boolean})],se.prototype,"loading",2);Se([d({type:Boolean})],se.prototype,"saving",2);Se([d()],se.prototype,"error",2);Se([d()],se.prototype,"savedMessage",2);Se([d({attribute:!1})],se.prototype,"onReload",2);Se([d({attribute:!1})],se.prototype,"onSave",2);Se([x()],se.prototype,"draft",2);Se([x()],se.prototype,"localError",2);se=Se([A("settings-general-panel")],se);function rm(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?l`<span class="muted">未列出</span>`:e.join(", "):l`<span class="muted">未设置</span>`}function Vr(e){return e.target instanceof HTMLInputElement?e.target.value:""}function om(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function nm(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function am(e){return e instanceof Error?e.message:String(e)}var lm=Object.defineProperty,cm=Object.getOwnPropertyDescriptor,Ie=(e,t,i,s)=>{for(var r=s>1?void 0:s?cm(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&&lm(t,i,r),r};let me=class extends I{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
1372
+ `;Se([d({attribute:!1})],se.prototype,"configResponse",2);Se([d({type:Boolean})],se.prototype,"loading",2);Se([d({type:Boolean})],se.prototype,"saving",2);Se([d()],se.prototype,"error",2);Se([d()],se.prototype,"savedMessage",2);Se([d({attribute:!1})],se.prototype,"onReload",2);Se([d({attribute:!1})],se.prototype,"onSave",2);Se([x()],se.prototype,"draft",2);Se([x()],se.prototype,"localError",2);se=Se([A("settings-general-panel")],se);function hm(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?l`<span class="muted">未列出</span>`:e.join(", "):l`<span class="muted">未设置</span>`}function Jr(e){return e.target instanceof HTMLInputElement?e.target.value:""}function um(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function fm(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function mm(e){return e instanceof Error?e.message:String(e)}var gm=Object.defineProperty,vm=Object.getOwnPropertyDescriptor,Ie=(e,t,i,s)=>{for(var r=s>1?void 0:s?vm(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&&gm(t,i,r),r};let me=class extends I{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
1365
1373
  <div class="section-heading">
1366
1374
  <div>
1367
1375
  <h2>插件</h2>
@@ -1421,7 +1429,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1421
1429
  .plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
1422
1430
  .toggle { justify-self: start; }
1423
1431
  }
1424
- `;Ie([d({attribute:!1})],me.prototype,"pluginsResponse",2);Ie([d({attribute:!1})],me.prototype,"configResponse",2);Ie([d({type:Boolean})],me.prototype,"loading",2);Ie([d({type:Boolean})],me.prototype,"saving",2);Ie([d()],me.prototype,"error",2);Ie([d()],me.prototype,"savedMessage",2);Ie([d({attribute:!1})],me.prototype,"onReload",2);Ie([d({attribute:!1})],me.prototype,"onTogglePlugin",2);me=Ie([A("settings-plugins-panel")],me);var dm=Object.defineProperty,pm=Object.getOwnPropertyDescriptor,Es=(e,t,i,s)=>{for(var r=s>1?void 0:s?pm(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&&dm(t,i,r),r};let xt=class extends I{constructor(){super(...arguments),this.actions=[]}render(){const e=hm(this.actions);return l`
1432
+ `;Ie([d({attribute:!1})],me.prototype,"pluginsResponse",2);Ie([d({attribute:!1})],me.prototype,"configResponse",2);Ie([d({type:Boolean})],me.prototype,"loading",2);Ie([d({type:Boolean})],me.prototype,"saving",2);Ie([d()],me.prototype,"error",2);Ie([d()],me.prototype,"savedMessage",2);Ie([d({attribute:!1})],me.prototype,"onReload",2);Ie([d({attribute:!1})],me.prototype,"onTogglePlugin",2);me=Ie([A("settings-plugins-panel")],me);var bm=Object.defineProperty,wm=Object.getOwnPropertyDescriptor,Ds=(e,t,i,s)=>{for(var r=s>1?void 0:s?wm(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&&bm(t,i,r),r};let xt=class extends I{constructor(){super(...arguments),this.actions=[]}render(){const e=ym(this.actions);return l`
1425
1433
  <div class="section-heading">
1426
1434
  <div>
1427
1435
  <h2>键盘快捷键</h2>
@@ -1437,7 +1445,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1437
1445
  </div>
1438
1446
  </section>
1439
1447
  `)}
1440
- `}renderShortcutRow(e){const t=this.configResponse?.config.shortcuts,i=gn(e.id,t),s=i===null?void 0:i??e.shortcut,r=fm(e,t);return l`
1448
+ `}renderShortcutRow(e){const t=this.configResponse?.config.shortcuts,i=Sn(e.id,t),s=i===null?void 0:i??e.shortcut,r=Sm(e,t);return l`
1441
1449
  <div class="shortcut-row">
1442
1450
  <div class="shortcut-main">
1443
1451
  <strong>${e.title}</strong>
@@ -1445,8 +1453,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1445
1453
  <small class="shortcut-id">${e.id}</small>
1446
1454
  </div>
1447
1455
  <div class="shortcut-value">
1448
- ${s!==void 0&&s!==""?l`<kbd>${Mo(s)}</kbd>`:l`<span class="unassigned">${r==="disabled"?"已禁用":"未分配"}</span>`}
1449
- <small class=${r}>${mm(r)}</small>
1456
+ ${s!==void 0&&s!==""?l`<kbd>${Oo(s)}</kbd>`:l`<span class="unassigned">${r==="disabled"?"已禁用":"未分配"}</span>`}
1457
+ <small class=${r}>${km(r)}</small>
1450
1458
  </div>
1451
1459
  </div>
1452
1460
  `}};xt.styles=E`
@@ -1483,7 +1491,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1483
1491
  .shortcut-value { justify-self: start; justify-items: start; }
1484
1492
  kbd, .unassigned { justify-self: start; }
1485
1493
  }
1486
- `;Es([d({attribute:!1})],xt.prototype,"actions",2);Es([d({attribute:!1})],xt.prototype,"configResponse",2);xt=Es([A("settings-shortcuts-panel")],xt);function hm(e){const t=new Map;for(const i of[...e].sort(um)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function um(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function gn(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function fm(e,t){const i=gn(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function mm(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}var gm=Object.defineProperty,vm=Object.getOwnPropertyDescriptor,le=(e,t,i,s)=>{for(var r=s>1?void 0:s?vm(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&&gm(t,i,r),r};let J=class extends I{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`
1494
+ `;Ds([d({attribute:!1})],xt.prototype,"actions",2);Ds([d({attribute:!1})],xt.prototype,"configResponse",2);xt=Ds([A("settings-shortcuts-panel")],xt);function ym(e){const t=new Map;for(const i of[...e].sort(xm)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function xm(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function Sn(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Sm(e,t){const i=Sn(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function km(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}var $m=Object.defineProperty,Pm=Object.getOwnPropertyDescriptor,le=(e,t,i,s)=>{for(var r=s>1?void 0:s?Pm(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&&$m(t,i,r),r};let J=class extends I{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`
1487
1495
  <div class="backdrop" @mousedown=${()=>this.onClose?.()}>
1488
1496
  <section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB 设置" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
1489
1497
  <header class="settings-header">
@@ -1558,7 +1566,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1558
1566
  .settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
1559
1567
  .settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
1560
1568
  }
1561
- `;le([d({attribute:!1})],J.prototype,"section",2);le([d({attribute:!1})],J.prototype,"actions",2);le([d({attribute:!1})],J.prototype,"onNavigate",2);le([d({attribute:!1})],J.prototype,"onClose",2);le([d({attribute:!1})],J.prototype,"onConfigSaved",2);le([x()],J.prototype,"configResponse",2);le([x()],J.prototype,"pluginsResponse",2);le([x()],J.prototype,"loading",2);le([x()],J.prototype,"saving",2);le([x()],J.prototype,"error",2);le([x()],J.prototype,"savedMessage",2);J=le([A("settings-dialog")],J);function Wi(e){return e instanceof Error?e.message:String(e)}var bm=Object.defineProperty,wm=Object.getOwnPropertyDescriptor,ce=(e,t,i,s)=>{for(var r=s>1?void 0:s?wm(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&&bm(t,i,r),r};let Q=class extends I{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.workspaceLabelItems=[],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(){const e=this.workspace;if(e===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`
1569
+ `;le([d({attribute:!1})],J.prototype,"section",2);le([d({attribute:!1})],J.prototype,"actions",2);le([d({attribute:!1})],J.prototype,"onNavigate",2);le([d({attribute:!1})],J.prototype,"onClose",2);le([d({attribute:!1})],J.prototype,"onConfigSaved",2);le([x()],J.prototype,"configResponse",2);le([x()],J.prototype,"pluginsResponse",2);le([x()],J.prototype,"loading",2);le([x()],J.prototype,"saving",2);le([x()],J.prototype,"error",2);le([x()],J.prototype,"savedMessage",2);J=le([A("settings-dialog")],J);function Wi(e){return e instanceof Error?e.message:String(e)}var Tm=Object.defineProperty,Cm=Object.getOwnPropertyDescriptor,ce=(e,t,i,s)=>{for(var r=s>1?void 0:s?Cm(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&&Tm(t,i,r),r};let Q=class extends I{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.workspaceLabelItems=[],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(){const e=this.workspace;if(e===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`
1562
1570
  <header>
1563
1571
  <div class=${this.workspaceHeaderFrameClass()}>
1564
1572
  <div class="workspace-header-strip" @scroll=${this.onWorkspaceHeaderScroll}>
@@ -1571,7 +1579,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1571
1579
  `})}
1572
1580
  </div>
1573
1581
  `}
1574
- <small>${Qo(e.label,this.workspaceLabelItems,e.path)}</small>
1582
+ <small>${sn(e.label,this.workspaceLabelItems,e.path)}</small>
1575
1583
  </div>
1576
1584
  </div>
1577
1585
  </header>
@@ -1589,31 +1597,31 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1589
1597
  <h2>${e.title}</h2>
1590
1598
  ${e.body===void 0?null:l`<p>${e.body}</p>`}
1591
1599
  </section>
1592
- `}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}};Q.styles=eh;ce([d({attribute:!1})],Q.prototype,"workspace",2);ce([d({attribute:!1})],Q.prototype,"panelContext",2);ce([d({attribute:!1})],Q.prototype,"emptyState",2);ce([d()],Q.prototype,"tool",2);ce([d({attribute:!1})],Q.prototype,"panels",2);ce([d({attribute:!1})],Q.prototype,"workspaceLabelItems",2);ce([d({type:Boolean})],Q.prototype,"hideToolTabs",2);ce([d({attribute:!1})],Q.prototype,"onSelectTool",2);ce([re(".workspace-header-strip")],Q.prototype,"workspaceHeaderStrip",2);ce([x()],Q.prototype,"workspaceHeaderCanScrollLeft",2);ce([x()],Q.prototype,"workspaceHeaderCanScrollRight",2);Q=ce([A("workspace-panel")],Q);var ym=Object.defineProperty,xm=Object.getOwnPropertyDescriptor,de=(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&&ym(t,i,r),r};let Z=class extends I{constructor(){super(...arguments),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=Sm(this.machine),t=$m(this.project),i=Tm(this.workspace),s=Im(this.session);return l`
1600
+ `}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}};Q.styles=lh;ce([d({attribute:!1})],Q.prototype,"workspace",2);ce([d({attribute:!1})],Q.prototype,"panelContext",2);ce([d({attribute:!1})],Q.prototype,"emptyState",2);ce([d()],Q.prototype,"tool",2);ce([d({attribute:!1})],Q.prototype,"panels",2);ce([d({attribute:!1})],Q.prototype,"workspaceLabelItems",2);ce([d({type:Boolean})],Q.prototype,"hideToolTabs",2);ce([d({attribute:!1})],Q.prototype,"onSelectTool",2);ce([re(".workspace-header-strip")],Q.prototype,"workspaceHeaderStrip",2);ce([x()],Q.prototype,"workspaceHeaderCanScrollLeft",2);ce([x()],Q.prototype,"workspaceHeaderCanScrollRight",2);Q=ce([A("workspace-panel")],Q);var Im=Object.defineProperty,Mm=Object.getOwnPropertyDescriptor,de=(e,t,i,s)=>{for(var r=s>1?void 0:s?Mm(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&&Im(t,i,r),r};let Z=class extends I{constructor(){super(...arguments),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=Am(this.machine),t=Em(this.project),i=_m(this.workspace),s=Lm(this.session);return l`
1593
1601
  <nav class=${this.contextBarClass()} aria-label="当前位置">
1594
1602
  <span class="context-bar-label">位置</span>
1595
1603
  <ol class="context-items" @scroll=${this.onContextScroll}>
1596
1604
  <li class="context-item">
1597
- <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${km(this.machine)} aria-label=${`机器:${e}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
1605
+ <button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${Rm(this.machine)} aria-label=${`机器:${e}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
1598
1606
  <span class="context-kind">机器</span>
1599
1607
  ${this.renderMachineActivity()}
1600
1608
  <span class="context-value">${e}</span>
1601
1609
  </button>
1602
1610
  </li>
1603
1611
  <li class="context-item">
1604
- <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${Pm(this.project)} aria-label=${`项目:${t}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
1612
+ <button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${Dm(this.project)} aria-label=${`项目:${t}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
1605
1613
  <span class="context-kind">项目</span>
1606
1614
  <span class="context-value">${t}</span>
1607
1615
  </button>
1608
1616
  </li>
1609
1617
  <li class="context-item">
1610
- <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${Cm(this.workspace)} aria-label=${`工作区:${i}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
1618
+ <button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${Om(this.workspace)} aria-label=${`工作区:${i}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
1611
1619
  <span class="context-kind">工作区</span>
1612
1620
  <span class="context-value">${i}</span>
1613
1621
  </button>
1614
1622
  </li>
1615
1623
  <li class="context-item">
1616
- <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${Mm(this.session)} aria-label=${`会话:${s}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
1624
+ <button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${Wm(this.session)} aria-label=${`会话:${s}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
1617
1625
  <span class="context-kind">会话</span>
1618
1626
  <span class="context-value">${s}</span>
1619
1627
  </button>
@@ -1657,7 +1665,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1657
1665
  .context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
1658
1666
  button { cursor: pointer; }
1659
1667
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
1660
- `;de([d({attribute:!1})],Z.prototype,"machine",2);de([d({attribute:!1})],Z.prototype,"machineActivityKind",2);de([d({attribute:!1})],Z.prototype,"project",2);de([d({attribute:!1})],Z.prototype,"workspace",2);de([d({attribute:!1})],Z.prototype,"session",2);de([d({attribute:!1})],Z.prototype,"refreshControl",2);de([d({attribute:!1})],Z.prototype,"onOpenSection",2);de([d({attribute:!1})],Z.prototype,"onShowActions",2);de([re(".context-items")],Z.prototype,"contextItems",2);de([x()],Z.prototype,"canScrollLeft",2);de([x()],Z.prototype,"canScrollRight",2);Z=de([A("app-context-bar")],Z);function Sm(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function km(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function $m(e){return e?.name??"未选择项目"}function Pm(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function Tm(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function Cm(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function Im(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 Mm(e){return e===void 0?"未选择会话":e.path}var Am=Object.defineProperty,Rm=Object.getOwnPropertyDescriptor,qe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Rm(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&&Am(t,i,r),r};let Pe=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`
1668
+ `;de([d({attribute:!1})],Z.prototype,"machine",2);de([d({attribute:!1})],Z.prototype,"machineActivityKind",2);de([d({attribute:!1})],Z.prototype,"project",2);de([d({attribute:!1})],Z.prototype,"workspace",2);de([d({attribute:!1})],Z.prototype,"session",2);de([d({attribute:!1})],Z.prototype,"refreshControl",2);de([d({attribute:!1})],Z.prototype,"onOpenSection",2);de([d({attribute:!1})],Z.prototype,"onShowActions",2);de([re(".context-items")],Z.prototype,"contextItems",2);de([x()],Z.prototype,"canScrollLeft",2);de([x()],Z.prototype,"canScrollRight",2);Z=de([A("app-context-bar")],Z);function Am(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function Rm(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function Em(e){return e?.name??"未选择项目"}function Dm(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function _m(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function Om(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function Lm(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 Wm(e){return e===void 0?"未选择会话":e.path}var jm=Object.defineProperty,Nm=Object.getOwnPropertyDescriptor,qe=(e,t,i,s)=>{for(var r=s>1?void 0:s?Nm(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&&jm(t,i,r),r};let Pe=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`
1661
1669
  <div class=${this.frameClass()}>
1662
1670
  <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
1663
1671
  ${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
@@ -1669,7 +1677,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1669
1677
  `})}
1670
1678
  </div>
1671
1679
  </div>
1672
- `}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>`:Ud(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}};Pe.styles=E`
1680
+ `}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>`:Xd(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}};Pe.styles=E`
1673
1681
  :host { flex: 0 0 auto; min-width: 0; }
1674
1682
  .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); }
1675
1683
  .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; }
@@ -1695,7 +1703,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1695
1703
  .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; }
1696
1704
  .tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
1697
1705
  }
1698
- `;qe([d({attribute:!1})],Pe.prototype,"tabs",2);qe([d({attribute:!1})],Pe.prototype,"selectedView",2);qe([d({attribute:!1})],Pe.prototype,"onSelect",2);qe([re(".mobile-tabs")],Pe.prototype,"mobileTabs",2);qe([x()],Pe.prototype,"canScrollLeft",2);qe([x()],Pe.prototype,"canScrollRight",2);Pe=qe([A("app-mobile-main-tabs")],Pe);var Em=Object.defineProperty,Dm=Object.getOwnPropertyDescriptor,T=(e,t,i,s)=>{for(var r=s>1?void 0:s?Dm(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&&Em(t,i,r),r};let P=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.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1}render(){return l`
1706
+ `;qe([d({attribute:!1})],Pe.prototype,"tabs",2);qe([d({attribute:!1})],Pe.prototype,"selectedView",2);qe([d({attribute:!1})],Pe.prototype,"onSelect",2);qe([re(".mobile-tabs")],Pe.prototype,"mobileTabs",2);qe([x()],Pe.prototype,"canScrollLeft",2);qe([x()],Pe.prototype,"canScrollRight",2);Pe=qe([A("app-mobile-main-tabs")],Pe);var Bm=Object.defineProperty,Fm=Object.getOwnPropertyDescriptor,T=(e,t,i,s)=>{for(var r=s>1?void 0:s?Fm(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&&Bm(t,i,r),r};let P=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.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1}render(){return l`
1699
1707
  <header>
1700
1708
  <strong>PI WEB</strong>
1701
1709
  <div class="header-actions">
@@ -1703,7 +1711,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1703
1711
  <button title="显示操作" aria-label="显示操作" @click=${()=>{this.onShowActions?.()}}>操作</button>
1704
1712
  </div>
1705
1713
  </header>
1706
- ${_m(this.machines)?l`
1714
+ ${zm(this.machines)?l`
1707
1715
  <machine-list
1708
1716
  .machines=${this.machines}
1709
1717
  .selected=${this.selectedMachine}
@@ -1774,7 +1782,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1774
1782
  :host([collapsible]) workspace-list[collapsed],
1775
1783
  :host([collapsible]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
1776
1784
  button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
1777
- `;T([d({attribute:!1})],P.prototype,"machines",2);T([d({attribute:!1})],P.prototype,"selectedMachine",2);T([d({attribute:!1})],P.prototype,"machineStatuses",2);T([d({attribute:!1})],P.prototype,"machineActivities",2);T([d({attribute:!1})],P.prototype,"projects",2);T([d({attribute:!1})],P.prototype,"selectedProject",2);T([d({attribute:!1})],P.prototype,"workspaces",2);T([d({attribute:!1})],P.prototype,"selectedWorkspace",2);T([d({attribute:!1})],P.prototype,"sessions",2);T([d({attribute:!1})],P.prototype,"selectedSession",2);T([d({attribute:!1})],P.prototype,"workspaceActivities",2);T([d({attribute:!1})],P.prototype,"sessionActivities",2);T([d({attribute:!1})],P.prototype,"sessionStatuses",2);T([d({attribute:!1})],P.prototype,"workspacesByProjectId",2);T([d({attribute:!1})],P.prototype,"deletingWorkspaceIds",2);T([d({attribute:!1})],P.prototype,"workspaceLabelItems",2);T([d({attribute:!1})],P.prototype,"refreshControl",2);T([d({type:Boolean,reflect:!0})],P.prototype,"collapsible",2);T([d({type:Boolean})],P.prototype,"machinesCollapsed",2);T([d({type:Boolean})],P.prototype,"projectsCollapsed",2);T([d({type:Boolean})],P.prototype,"workspacesCollapsed",2);T([d({type:Boolean})],P.prototype,"sessionsCollapsed",2);T([d({type:Boolean})],P.prototype,"canStartSession",2);T([d({attribute:!1})],P.prototype,"onShowActions",2);T([d({attribute:!1})],P.prototype,"onToggleMachines",2);T([d({attribute:!1})],P.prototype,"onToggleProjects",2);T([d({attribute:!1})],P.prototype,"onToggleWorkspaces",2);T([d({attribute:!1})],P.prototype,"onToggleSessions",2);T([d({attribute:!1})],P.prototype,"onSelectProject",2);T([d({attribute:!1})],P.prototype,"onCloseProject",2);T([d({attribute:!1})],P.prototype,"onSelectWorkspace",2);T([d({attribute:!1})],P.prototype,"onDeleteWorkspace",2);T([d({attribute:!1})],P.prototype,"onStartSession",2);T([d({attribute:!1})],P.prototype,"onSelectSession",2);T([d({attribute:!1})],P.prototype,"onArchiveSession",2);T([d({attribute:!1})],P.prototype,"onArchiveSessionWithDescendants",2);T([d({attribute:!1})],P.prototype,"onRestoreSession",2);T([d({attribute:!1})],P.prototype,"onDeleteCachedNewSession",2);T([d({attribute:!1})],P.prototype,"onDetachParentSession",2);T([d({attribute:!1})],P.prototype,"onArchivedCollapsed",2);T([d({attribute:!1})],P.prototype,"onSelectMachine",2);T([d({attribute:!1})],P.prototype,"onRemoveMachine",2);P=T([A("app-navigation-panel")],P);function _m(e){return e.length>1}var Om=Object.defineProperty,Lm=Object.getOwnPropertyDescriptor,Ve=(e,t,i,s)=>{for(var r=s>1?void 0:s?Lm(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&&Om(t,i,r),r};let Te=class extends I{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.controls="",this.expandLabel="展开面板",this.collapseLabel="折叠面板"}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
1785
+ `;T([d({attribute:!1})],P.prototype,"machines",2);T([d({attribute:!1})],P.prototype,"selectedMachine",2);T([d({attribute:!1})],P.prototype,"machineStatuses",2);T([d({attribute:!1})],P.prototype,"machineActivities",2);T([d({attribute:!1})],P.prototype,"projects",2);T([d({attribute:!1})],P.prototype,"selectedProject",2);T([d({attribute:!1})],P.prototype,"workspaces",2);T([d({attribute:!1})],P.prototype,"selectedWorkspace",2);T([d({attribute:!1})],P.prototype,"sessions",2);T([d({attribute:!1})],P.prototype,"selectedSession",2);T([d({attribute:!1})],P.prototype,"workspaceActivities",2);T([d({attribute:!1})],P.prototype,"sessionActivities",2);T([d({attribute:!1})],P.prototype,"sessionStatuses",2);T([d({attribute:!1})],P.prototype,"workspacesByProjectId",2);T([d({attribute:!1})],P.prototype,"deletingWorkspaceIds",2);T([d({attribute:!1})],P.prototype,"workspaceLabelItems",2);T([d({attribute:!1})],P.prototype,"refreshControl",2);T([d({type:Boolean,reflect:!0})],P.prototype,"collapsible",2);T([d({type:Boolean})],P.prototype,"machinesCollapsed",2);T([d({type:Boolean})],P.prototype,"projectsCollapsed",2);T([d({type:Boolean})],P.prototype,"workspacesCollapsed",2);T([d({type:Boolean})],P.prototype,"sessionsCollapsed",2);T([d({type:Boolean})],P.prototype,"canStartSession",2);T([d({attribute:!1})],P.prototype,"onShowActions",2);T([d({attribute:!1})],P.prototype,"onToggleMachines",2);T([d({attribute:!1})],P.prototype,"onToggleProjects",2);T([d({attribute:!1})],P.prototype,"onToggleWorkspaces",2);T([d({attribute:!1})],P.prototype,"onToggleSessions",2);T([d({attribute:!1})],P.prototype,"onSelectProject",2);T([d({attribute:!1})],P.prototype,"onCloseProject",2);T([d({attribute:!1})],P.prototype,"onSelectWorkspace",2);T([d({attribute:!1})],P.prototype,"onDeleteWorkspace",2);T([d({attribute:!1})],P.prototype,"onStartSession",2);T([d({attribute:!1})],P.prototype,"onSelectSession",2);T([d({attribute:!1})],P.prototype,"onArchiveSession",2);T([d({attribute:!1})],P.prototype,"onArchiveSessionWithDescendants",2);T([d({attribute:!1})],P.prototype,"onRestoreSession",2);T([d({attribute:!1})],P.prototype,"onDeleteCachedNewSession",2);T([d({attribute:!1})],P.prototype,"onDetachParentSession",2);T([d({attribute:!1})],P.prototype,"onArchivedCollapsed",2);T([d({attribute:!1})],P.prototype,"onSelectMachine",2);T([d({attribute:!1})],P.prototype,"onRemoveMachine",2);P=T([A("app-navigation-panel")],P);function zm(e){return e.length>1}var Um=Object.defineProperty,Hm=Object.getOwnPropertyDescriptor,Ve=(e,t,i,s)=>{for(var r=s>1?void 0:s?Hm(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&&Um(t,i,r),r};let Te=class extends I{constructor(){super(...arguments),this.side="navigation",this.collapsed=!1,this.controls="",this.expandLabel="展开面板",this.collapseLabel="折叠面板"}render(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
1778
1786
  <button
1779
1787
  type="button"
1780
1788
  class="edge-button"
@@ -1800,7 +1808,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1800
1808
  @media (max-width: 760px) {
1801
1809
  :host([side="navigation"]) { display: none; }
1802
1810
  }
1803
- `;Ve([d({reflect:!0})],Te.prototype,"side",2);Ve([d({type:Boolean,reflect:!0})],Te.prototype,"collapsed",2);Ve([d()],Te.prototype,"controls",2);Ve([d()],Te.prototype,"expandLabel",2);Ve([d()],Te.prototype,"collapseLabel",2);Ve([d({attribute:!1})],Te.prototype,"onToggle",2);Te=Ve([A("app-panel-edge-control")],Te);var Wm=Object.defineProperty,jm=Object.getOwnPropertyDescriptor,At=(e,t,i,s)=>{for(var r=s>1?void 0:s?jm(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&&Wm(t,i,r),r};const Nm=550,Kr="pi-web-app-refresh-menu-portal-style";let ze=class extends I{constructor(){super(...arguments),this.isRefreshing=!1,this.menuOpen=!1,this.menuStyle="",this.suppressNextClick=!1,this.onRefreshClick=e=>{if(e.stopPropagation(),this.suppressNextClick){this.suppressNextClick=!1;return}this.refresh()},this.onRefreshPointerDown=e=>{if(!e.isPrimary||e.button!==0)return;const t=e.currentTarget;t instanceof HTMLElement&&(this.clearLongPressTimer(),this.suppressNextClick=!1,this.longPressTimer=window.setTimeout(()=>{this.longPressTimer=void 0,this.suppressNextClick=!0,this.openMenu(t)},Nm))},this.onRefreshContextMenu=e=>{e.preventDefault(),e.stopPropagation(),this.clearLongPressTimer(),this.suppressNextClick=!0,this.openMenu(e.currentTarget)},this.onDocumentClick=e=>{const t=e.composedPath();t.includes(this)||this.menuPortal!==void 0&&t.includes(this.menuPortal)||this.closeMenu()},this.onDocumentKeyDown=e=>{e.key!=="Escape"||!this.menuOpen||(e.preventDefault(),e.stopPropagation(),this.closeMenu())},this.onPortalMenuClick=e=>{e.stopPropagation()}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick),document.addEventListener("keydown",this.onDocumentKeyDown)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),document.removeEventListener("keydown",this.onDocumentKeyDown),this.clearLongPressTimer(),this.removePortalMenu(),super.disconnectedCallback()}render(){const e=this.isRefreshing?"正在刷新应用数据。长按可打开重载选项。":"刷新应用数据。长按可打开重载选项。";return l`
1811
+ `;Ve([d({reflect:!0})],Te.prototype,"side",2);Ve([d({type:Boolean,reflect:!0})],Te.prototype,"collapsed",2);Ve([d()],Te.prototype,"controls",2);Ve([d()],Te.prototype,"expandLabel",2);Ve([d()],Te.prototype,"collapseLabel",2);Ve([d({attribute:!1})],Te.prototype,"onToggle",2);Te=Ve([A("app-panel-edge-control")],Te);var qm=Object.defineProperty,Vm=Object.getOwnPropertyDescriptor,At=(e,t,i,s)=>{for(var r=s>1?void 0:s?Vm(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&qm(t,i,r),r};const Km=550,Qr="pi-web-app-refresh-menu-portal-style";let ze=class extends I{constructor(){super(...arguments),this.isRefreshing=!1,this.menuOpen=!1,this.menuStyle="",this.suppressNextClick=!1,this.onRefreshClick=e=>{if(e.stopPropagation(),this.suppressNextClick){this.suppressNextClick=!1;return}this.refresh()},this.onRefreshPointerDown=e=>{if(!e.isPrimary||e.button!==0)return;const t=e.currentTarget;t instanceof HTMLElement&&(this.clearLongPressTimer(),this.suppressNextClick=!1,this.longPressTimer=window.setTimeout(()=>{this.longPressTimer=void 0,this.suppressNextClick=!0,this.openMenu(t)},Km))},this.onRefreshContextMenu=e=>{e.preventDefault(),e.stopPropagation(),this.clearLongPressTimer(),this.suppressNextClick=!0,this.openMenu(e.currentTarget)},this.onDocumentClick=e=>{const t=e.composedPath();t.includes(this)||this.menuPortal!==void 0&&t.includes(this.menuPortal)||this.closeMenu()},this.onDocumentKeyDown=e=>{e.key!=="Escape"||!this.menuOpen||(e.preventDefault(),e.stopPropagation(),this.closeMenu())},this.onPortalMenuClick=e=>{e.stopPropagation()}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick),document.addEventListener("keydown",this.onDocumentKeyDown)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),document.removeEventListener("keydown",this.onDocumentKeyDown),this.clearLongPressTimer(),this.removePortalMenu(),super.disconnectedCallback()}render(){const e=this.isRefreshing?"正在刷新应用数据。长按可打开重载选项。":"刷新应用数据。长按可打开重载选项。";return l`
1804
1812
  <button
1805
1813
  class=${`app-refresh-button${this.isRefreshing?" refreshing":""}`}
1806
1814
  title=${e}
@@ -1822,14 +1830,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1822
1830
  <path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
1823
1831
  <path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
1824
1832
  </svg>
1825
- `}openMenu(e){this.menuStyle=Pt(e,{constrainTo:"viewport"}),this.menuOpen=!0,this.renderPortalMenu()}closeMenu(){this.menuOpen=!1,this.suppressNextClick=!1,this.removePortalMenu()}refresh(){this.closeMenu(),this.onRefresh?.()}reload(){this.closeMenu(),this.onReload?.()}clearLongPressTimer(){this.longPressTimer!==void 0&&(window.clearTimeout(this.longPressTimer),this.longPressTimer=void 0)}renderPortalMenu(){const e=this.ownerDocument;Bm(e);const t=this.menuPortal??e.createElement("div");this.menuPortal=t,t.className="pi-web-app-refresh-menu-portal",t.setAttribute("role","menu"),t.setAttribute("style",this.menuStyle),t.replaceChildren(this.createPortalMenuButton("刷新应用数据",()=>{this.refresh()}),this.createPortalMenuButton("完整重载页面",()=>{this.reload()})),t.addEventListener("click",this.onPortalMenuClick),t.isConnected||e.body.append(t)}createPortalMenuButton(e,t){const i=this.ownerDocument.createElement("button");return i.type="button",i.setAttribute("role","menuitem"),i.textContent=e,i.addEventListener("click",s=>{s.stopPropagation(),t()}),i}removePortalMenu(){this.menuPortal?.removeEventListener("click",this.onPortalMenuClick),this.menuPortal?.remove(),this.menuPortal=void 0}};ze.styles=E`
1833
+ `}openMenu(e){this.menuStyle=Pt(e,{constrainTo:"viewport"}),this.menuOpen=!0,this.renderPortalMenu()}closeMenu(){this.menuOpen=!1,this.suppressNextClick=!1,this.removePortalMenu()}refresh(){this.closeMenu(),this.onRefresh?.()}reload(){this.closeMenu(),this.onReload?.()}clearLongPressTimer(){this.longPressTimer!==void 0&&(window.clearTimeout(this.longPressTimer),this.longPressTimer=void 0)}renderPortalMenu(){const e=this.ownerDocument;Gm(e);const t=this.menuPortal??e.createElement("div");this.menuPortal=t,t.className="pi-web-app-refresh-menu-portal",t.setAttribute("role","menu"),t.setAttribute("style",this.menuStyle),t.replaceChildren(this.createPortalMenuButton("刷新应用数据",()=>{this.refresh()}),this.createPortalMenuButton("完整重载页面",()=>{this.reload()})),t.addEventListener("click",this.onPortalMenuClick),t.isConnected||e.body.append(t)}createPortalMenuButton(e,t){const i=this.ownerDocument.createElement("button");return i.type="button",i.setAttribute("role","menuitem"),i.textContent=e,i.addEventListener("click",s=>{s.stopPropagation(),t()}),i}removePortalMenu(){this.menuPortal?.removeEventListener("click",this.onPortalMenuClick),this.menuPortal?.remove(),this.menuPortal=void 0}};ze.styles=E`
1826
1834
  :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; }
1827
1835
  :host, :host * { -webkit-user-select: none; user-select: none; }
1828
1836
  .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; }
1829
1837
  .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
1830
1838
  .app-refresh-button.refreshing .app-refresh-icon { animation: app-refresh-spin .8s linear infinite; }
1831
1839
  @keyframes app-refresh-spin { to { transform: rotate(360deg); } }
1832
- `;At([d({type:Boolean})],ze.prototype,"isRefreshing",2);At([d({attribute:!1})],ze.prototype,"onRefresh",2);At([d({attribute:!1})],ze.prototype,"onReload",2);At([x()],ze.prototype,"menuOpen",2);ze=At([A("app-refresh-control")],ze);function Bm(e){if(e.getElementById(Kr)!==null)return;const t=e.createElement("style");t.id=Kr,t.textContent=`
1840
+ `;At([d({type:Boolean})],ze.prototype,"isRefreshing",2);At([d({attribute:!1})],ze.prototype,"onRefresh",2);At([d({attribute:!1})],ze.prototype,"onReload",2);At([x()],ze.prototype,"menuOpen",2);ze=At([A("app-refresh-control")],ze);function Gm(e){if(e.getElementById(Qr)!==null)return;const t=e.createElement("style");t.id=Qr,t.textContent=`
1833
1841
  .pi-web-app-refresh-menu-portal {
1834
1842
  position: fixed;
1835
1843
  z-index: 2147483647;
@@ -1866,7 +1874,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1866
1874
  .pi-web-app-refresh-menu-portal button:focus {
1867
1875
  background: var(--pi-selection-bg);
1868
1876
  }
1869
- `,e.head.append(t)}var Fm=Object.defineProperty,zm=Object.getOwnPropertyDescriptor,Ee=(e,t,i,s)=>{for(var r=s>1?void 0:s?zm(t,i):t,o=e.length-1,n;o>=0;o--)(n=e[o])&&(r=(s?n(t,i,r):n(r))||r);return s&&r&&Fm(t,i,r),r};const Um=900*1e3,Gr={capture:!0},ji="auto:on",Jr="auto:off",jt="theme:",Ni=St("core:workspace.files"),Bi=St("core:workspace.git"),Nt=St("core:workspace.terminal");let we=class extends I{constructor(){super(...arguments),this.state=xl(),this.sessions=new Xc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.activity=new Sl(()=>this.state,e=>{this.setState(e)}),this.auth=new Pl(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new nd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions),this.projects=new Ol(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Dl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new Ml(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new El(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new ud,this.realtime=new pr,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new cd,this.terminalSelection=new pd,this.appShell=new Cp(this),this.panelCollapse=new _p(this),this.mobileNavigation=new Dp(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.plugins=Hm(),this.themePreference=xd()??bd,this.activeThemeId=ms,this.isRefreshingApp=!1,this.settingsSection=xr(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.keyboard.handle(e,this.getActions())&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,Gr),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.refreshPiWebStatus()},Um),this.refreshPiWebStatus(),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.loadExternalPlugins(),this.loadProjectsAndRestoreRoute()}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,Gr),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.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,super.disconnectedCallback()}setState(e){if(!Jm(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),Vm(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=yr();await this.machines.loadMachines(e.machineId);const t=this.state.error,i=this.routeForSelectedMachine(e);i!==e&&this.replaceRouteAndClearWorkspaceQuery(i),await this.projects.loadProjects(),t!==""&&this.state.error===""&&this.setState({error:t}),await this.withChatScrollTransition(()=>this.restoreRouteFor(i,!1)),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}async refreshPiWebStatus(){try{this.setState({piWebStatus:await uo.piWebStatus()})}catch(e){console.warn("Failed to refresh PI WEB status",e)}}async refreshWorkspaceActivity(e=m(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?[m(this.state)]:this.state.machines.filter(t=>vn(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 Qt.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()])}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(yr(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const r=e.projectId===void 0||e.projectId===""?Zr():i,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=r.selectedTerminalId;try{if(await this.restoreRouteMachine(e,!1),!this.isCurrentRouteRestore(o))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:s??e.view??this.defaultRouteView(),selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const n=this.state.projects.find(a=>a.id===e.projectId);if(!n){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(n,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0)}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?Zr():{selectedFilePath:$i(Ni,"file"),selectedDiffPath:$i(Bi,"diff"),selectedTerminalId:$i(Nt,"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){Ii(e,{replace:!0}),pe(Ni,"file",void 0,{replace:!0}),pe(Bi,"diff",void 0,{replace:!0}),pe(Nt,"terminal",void 0,{replace:!0})}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(r=>r.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e){this.chatView?.saveScrollPosition(),await e(),await this.updateComplete,await this.chatView?.updateComplete,await Ym(),this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),Ii({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView==="navigation"?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(hr(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(hr(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Ii(ur(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){pe(Ni,"file",e.selectedFilePath,{replace:!0}),pe(Bi,"diff",e.selectedDiffPath,{replace:!0}),pe(Nt,"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)??dd(e.id);if(await this.restoreRouteFor(ur(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==""}openWorkspaceTool(e){e==="core:workspace.terminal"&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool("core:workspace.terminal")}terminalCommandRunsForOrigin(e,t=m(this.state)){const i=Xr(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const r=Fp(e,{api:{runTerminalCommand:(o,n)=>Ye.runTerminalCommand(o,n,t),listCommandRuns:o=>Ye.listCommandRuns(o,t),getCommandRun:o=>Ye.getCommandRun(o,t)},openTerminal:(o,n)=>{this.openRuntimeTerminal(t,o,n)}});return this.terminalCommandRunRuntimes.set(i,r),r}async openRuntimeTerminal(e,t,i){if((m(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"),m(this.state)!==e)){this.setState({error:"未找到用于运行终端命令的机器"});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){pe(Nt,"terminal",e,t)}terminalWorkspaceKey(e){return`${m(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,Mi(e)}closeSettings(){this.settingsSection=void 0,Mi(void 0)}navigateSettings(e){this.settingsSection=e,Mi(e)}restoreSettingsRoute(){this.settingsSection=xr()}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()},m(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new pr;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=m(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>Km(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):Qm(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=m(this.state);try{const i=await Ye.terminals(e.projectId,e.id,t);if(m(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=Qr(e),s=Qr(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")&&(this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.git.updatePolling())}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.plugins.getWorkspaceLabelItems(this.state,e),s=e===void 0?this.workspacePanelEmptyState():void 0;return l`
1877
+ `,e.head.append(t)}var Jm=Object.defineProperty,Qm=Object.getOwnPropertyDescriptor,Ee=(e,t,i,s)=>{for(var r=s>1?void 0:s?Qm(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&&Jm(t,i,r),r};const Zm=900*1e3,Zr={capture:!0},ji="auto:on",Xr="auto:off",jt="theme:",Ni=St("core:workspace.files"),Bi=St("core:workspace.git"),Nt=St("core:workspace.terminal");let we=class extends I{constructor(){super(...arguments),this.state=Cl(),this.sessions=new rd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.activity=new Il(()=>this.state,e=>{this.setState(e)}),this.auth=new Rl(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new hd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions),this.projects=new Fl(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new Nl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new Ol(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new jl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new wd,this.realtime=new hr,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new md,this.terminalSelection=new vd,this.appShell=new Op(this),this.panelCollapse=new zp(this),this.mobileNavigation=new Fp(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<"u"&&"matchMedia"in window?window.matchMedia("(prefers-color-scheme: light)"):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.plugins=Xm(),this.themePreference=Cd()??$d,this.activeThemeId=gs,this.isRefreshingApp=!1,this.settingsSection=$r(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.keyboard.handle(e,this.getActions())&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,Zr),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.refreshPiWebStatus()},Zm),this.refreshPiWebStatus(),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.loadExternalPlugins(),this.loadProjectsAndRestoreRoute()}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,Zr),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.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,super.disconnectedCallback()}setState(e){if(!sg(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),eg(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=kr();await this.machines.loadMachines(e.machineId);const t=this.state.error,i=this.routeForSelectedMachine(e);i!==e&&this.replaceRouteAndClearWorkspaceQuery(i),await this.projects.loadProjects(),t!==""&&this.state.error===""&&this.setState({error:t}),await this.withChatScrollTransition(()=>this.restoreRouteFor(i,!1)),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}async refreshPiWebStatus(){try{this.setState({piWebStatus:await wo.piWebStatus()})}catch(e){console.warn("Failed to refresh PI WEB status",e)}}async refreshWorkspaceActivity(e=m(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?[m(this.state)]:this.state.machines.filter(t=>kn(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 Qt.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()])}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(kr(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const r=e.projectId===void 0||e.projectId===""?eo():i,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=r.selectedTerminalId;try{if(await this.restoreRouteMachine(e,!1),!this.isCurrentRouteRestore(o))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:s??e.view??this.defaultRouteView(),selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const n=this.state.projects.find(a=>a.id===e.projectId);if(!n){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(n,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:r.selectedFilePath,selectedDiffPath:r.selectedDiffPath,selectedTerminalId:r.selectedTerminalId}),r.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(r.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,r.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0)}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?eo():{selectedFilePath:$i(Ni,"file"),selectedDiffPath:$i(Bi,"diff"),selectedTerminalId:$i(Nt,"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){Ii(e,{replace:!0}),pe(Ni,"file",void 0,{replace:!0}),pe(Bi,"diff",void 0,{replace:!0}),pe(Nt,"terminal",void 0,{replace:!0})}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(r=>r.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e){this.chatView?.saveScrollPosition(),await e(),await this.updateComplete,await this.chatView?.updateComplete,await ag(),this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),Ii({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(ur(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(ur(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Ii(fr(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){pe(Ni,"file",e.selectedFilePath,{replace:!0}),pe(Bi,"diff",e.selectedDiffPath,{replace:!0}),pe(Nt,"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)??gd(e.id);if(await this.restoreRouteFor(fr(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=m(this.state)){const i=to(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const r=Jp(e,{api:{runTerminalCommand:(o,n)=>Ye.runTerminalCommand(o,n,t),listCommandRuns:o=>Ye.listCommandRuns(o,t),getCommandRun:o=>Ye.getCommandRun(o,t)},openTerminal:(o,n)=>{this.openRuntimeTerminal(t,o,n)}});return this.terminalCommandRunRuntimes.set(i,r),r}async openRuntimeTerminal(e,t,i){if((m(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"),m(this.state)!==e)){this.setState({error:"未找到用于运行终端命令的机器"});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){pe(Nt,"terminal",e,t)}terminalWorkspaceKey(e){return`${m(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,Mi(e)}closeSettings(){this.settingsSection=void 0,Mi(void 0)}navigateSettings(e){this.settingsSection=e,Mi(e)}restoreSettingsRoute(){this.settingsSection=$r()}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()},m(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new hr;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=m(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>tg(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):rg(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=m(this.state);try{const i=await Ye.terminals(e.projectId,e.id,t);if(m(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=Yr(e),s=Yr(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")&&(this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.git.updatePolling())}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.plugins.getWorkspaceLabelItems(this.state,e),s=e===void 0?this.workspacePanelEmptyState():void 0;return l`
1870
1878
  <workspace-panel
1871
1879
  id="workspace-panel"
1872
1880
  .workspace=${e}
@@ -1911,7 +1919,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1911
1919
  .workspacesByProjectId=${this.state.workspacesByProjectId}
1912
1920
  .workspaces=${this.state.workspaces}
1913
1921
  .selectedWorkspace=${this.state.selectedWorkspace}
1914
- .deletingWorkspaceIds=${_d(this.state.workspaceDeletionRuns)}
1922
+ .deletingWorkspaceIds=${Hd(this.state.workspaceDeletionRuns)}
1915
1923
  .sessions=${this.state.sessions}
1916
1924
  .sessionStatuses=${this.state.sessionStatuses}
1917
1925
  .sessionActivities=${this.state.sessionActivities}
@@ -1940,17 +1948,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error
1940
1948
  .onDeleteCachedNewSession=${i=>this.sessions.deleteCachedNewSession(i)}
1941
1949
  .onDetachParentSession=${i=>this.sessions.detachParent(i)}
1942
1950
  ></app-navigation-panel>
1943
- `}openNavigationSection(e){this.mobileNavigation.open(e,()=>{this.selectMainView("navigation")})}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}}createWorkspacePanelContext(e){const t=qm(this.state),i=t.id,s=r=>{const o=this.terminalCommandRunsForOrigin(r,i);return vp({machine:t,workspace:e,state:this.state,files:{readFile:n=>mo.workspaceFile(e.projectId,e.id,n,i)},terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>o.runCommand({...n,workspace:e})},host:{requestRender:()=>{this.requestUpdate()}},piWebUnstable:{terminalCommandRuns:o},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:n=>{this.files.expandDir(n)},onSelectFile:n=>{this.files.selectFile(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return jp(this.plugins.getActions(this.createPluginRuntimeContext()),this.shortcutConfig)}async loadExternalPlugins(){try{const e=await ap();for(const t of e)try{this.plugins.register(t)}catch(i){console.warn(`Failed to register PI WEB plugin ${t.id}`,i)}this.applyPreferredTheme(!1),this.requestUpdate()}catch(e){console.warn("Failed to load external PI WEB plugins",e)}}createPluginRuntimeContext(){const e=t=>gp({state:this.state,piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.promptEditor?.focusInput()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:()=>this.machines.refreshMachineHealth(),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(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!ad(e)){this.setState({error:"只能删除次级 Git worktree"});return}if(Wo(this.state,e))return;const t=e.branch??e.label;if(!confirm(`删除工作区 ${t}?
1951
+ `}openNavigationSection(e){this.mobileNavigation.open(e,()=>{this.selectMainView("navigation")})}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}}createWorkspacePanelContext(e){const t=Ym(this.state),i=t.id,s=r=>{const o=this.terminalCommandRunsForOrigin(r,i);return Pp({machine:t,workspace:e,state:this.state,files:{readFile:n=>xo.workspaceFile(e.projectId,e.id,n,i)},terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>o.runCommand({...n,workspace:e})},host:{requestRender:()=>{this.requestUpdate()}},piWebUnstable:{terminalCommandRuns:o},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:n=>{this.files.expandDir(n)},onSelectFile:n=>{this.files.selectFile(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return Vp(this.plugins.getActions(this.createPluginRuntimeContext()),this.shortcutConfig)}async loadExternalPlugins(){try{const e=await mp();for(const t of e)try{this.plugins.register(t)}catch(i){console.warn(`Failed to register PI WEB plugin ${t.id}`,i)}this.applyPreferredTheme(!1),this.requestUpdate()}catch(e){console.warn("Failed to load external PI WEB plugins",e)}}createPluginRuntimeContext(){const e=t=>$p({state:this.state,piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.promptEditor?.focusInput()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:()=>this.machines.refreshMachineHealth(),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(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!ud(e)){this.setState({error:"只能删除次级 Git worktree"});return}if(Uo(this.state,e))return;const t=e.branch??e.label;if(!confirm(`删除工作区 ${t}?
1944
1952
 
1945
1953
  这会运行 git worktree remove 并删除:
1946
1954
  ${e.path}
1947
1955
 
1948
- Git 分支不会被删除。`))return;const s=m(this.state);try{const r=await this.mainWorkspaceForProject(e.projectId);if(r===void 0){this.setState({error:"未找到项目主工作区"});return}if(m(this.state)!==s)return;const o=await this.terminalCommandRunsForOrigin("core",s).runCommand({workspace:r,title:`删除工作区:${t}`,command:`git worktree remove ${Zm(e.path)}`,open:!0,metadata:Rd(e)});this.recordWorkspaceDeletionRun(o.run,s),o.completed.then(n=>this.handleCompletedWorkspaceDeletionRun(n,s)).catch(n=>{m(this.state)===s&&this.setState({error:`工作区删除失败。请查看终端输出。${Yr(n)}`})})}catch(r){m(this.state)===s&&this.setState({error:`启动工作区删除失败:${Yr(r)}`})}}async mainWorkspaceForProject(e){let t=this.state.selectedProject?.id===e?this.state.workspaces:this.state.workspacesByProjectId[e];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e)),t.find(i=>i.isMain)??t[0]}recordWorkspaceDeletionRun(e,t){if(m(this.state)!==t)return;const i=Ki(e);i!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[i]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;const e=m(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(Ed(t.id));if(m(this.state)!==e)return;const s=Dd(i);this.setState({workspaceDeletionRuns:s});for(const r of Object.values(s))si(r)||await this.handleCompletedWorkspaceDeletionRun(r,e)}catch(i){console.warn("刷新工作区删除任务失败",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(si);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=m(this.state)){if(m(this.state)!==t)return;const i=Xr(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Ki(e);if(s!==void 0){if(this.handledWorkspaceDeletionRunIds.add(i),e.status==="succeeded"){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,s),m(this.state)!==t)return;this.setState({workspaceDeletionRuns:Xm(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})}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind==="local"||!window.confirm(`移除 ${e.name}?
1956
+ Git 分支不会被删除。`))return;const s=m(this.state);try{const r=await this.mainWorkspaceForProject(e.projectId);if(r===void 0){this.setState({error:"未找到项目主工作区"});return}if(m(this.state)!==s)return;const o=await this.terminalCommandRunsForOrigin("core",s).runCommand({workspace:r,title:`删除工作区:${t}`,command:`git worktree remove ${og(e.path)}`,open:!0,metadata:Fd(e)});this.recordWorkspaceDeletionRun(o.run,s),o.completed.then(n=>this.handleCompletedWorkspaceDeletionRun(n,s)).catch(n=>{m(this.state)===s&&this.setState({error:`工作区删除失败。请查看终端输出。${io(n)}`})})}catch(r){m(this.state)===s&&this.setState({error:`启动工作区删除失败:${io(r)}`})}}async mainWorkspaceForProject(e){let t=this.state.selectedProject?.id===e?this.state.workspaces:this.state.workspacesByProjectId[e];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e)),t.find(i=>i.isMain)??t[0]}recordWorkspaceDeletionRun(e,t){if(m(this.state)!==t)return;const i=Ki(e);i!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[i]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;const e=m(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(zd(t.id));if(m(this.state)!==e)return;const s=Ud(i);this.setState({workspaceDeletionRuns:s});for(const r of Object.values(s))si(r)||await this.handleCompletedWorkspaceDeletionRun(r,e)}catch(i){console.warn("刷新工作区删除任务失败",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(si);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=m(this.state)){if(m(this.state)!==t)return;const i=to(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=Ki(e);if(s!==void 0){if(this.handledWorkspaceDeletionRunIds.add(i),e.status==="succeeded"){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,s),m(this.state)!==t)return;this.setState({workspaceDeletionRuns:ng(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})}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind==="local"||!window.confirm(`移除 ${e.name}?
1949
1957
 
1950
- 这只会将它从当前 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?Jr:ji;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${jt}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开":"关"}`,description:this.autoThemeDescription(t)},...e.map(r=>({value:`${jt}${r.id}`,label:this.themeOptionLabel(r,i),description:this.themeOptionDescription(r)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===ji||e===Jr){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===ji},this.applyPreferredTheme(!0);return}if(!e.startsWith(jt))return;const t=e.slice(jt.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,kd(t),e&&Sd(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return $d({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return Do(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=>({value:i,label:`${ig(i)}${i===t?" ✓ 当前":""}`,description:tg(i)}))}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),eg(e)&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t){t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
1958
+ 这只会将它从当前 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?Xr:ji;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${jt}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开":"关"}`,description:this.autoThemeDescription(t)},...e.map(r=>({value:`${jt}${r.id}`,label:this.themeOptionLabel(r,i),description:this.themeOptionDescription(r)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===ji||e===Xr){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===ji},this.applyPreferredTheme(!0);return}if(!e.startsWith(jt))return;const t=e.slice(jt.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,Md(t),e&&Id(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Ad({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return No(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=>({value:i,label:`${dg(i)}${i===t?" ✓ 当前":""}`,description:cg(i)}))}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),lg(e)&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t){t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
1951
1959
  <app-context-bar
1952
1960
  .machine=${this.state.selectedMachine}
1953
- .machineActivityKind=${Gm(this.state)}
1961
+ .machineActivityKind=${ig(this.state)}
1954
1962
  .project=${this.state.selectedProject}
1955
1963
  .workspace=${this.state.selectedWorkspace}
1956
1964
  .session=${this.state.selectedSession}
@@ -1968,7 +1976,7 @@ Git 分支不会被删除。`))return;const s=m(this.state);try{const r=await th
1968
1976
  <div class=${this.panelCollapse.shellClass(e.mainView)}>
1969
1977
  <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel(!1)}</aside>
1970
1978
  ${this.renderNavigationPanelEdgeControl()}
1971
- <main class=${Uo(e.mainView)}>
1979
+ <main class=${Jo(e.mainView)}>
1972
1980
  ${this.renderContextBar()}
1973
1981
  ${this.renderMobileMainTabs()}
1974
1982
  ${e.error?l`<div class="error">${e.error}</div>`:null}
@@ -1991,4 +1999,4 @@ Git 分支不会被删除。`))return;const s=m(this.state);try{const r=await th
1991
1999
  ${e.themeDialog!==void 0?l`<command-picker title=${e.themeDialog.title} .options=${e.themeDialog.options} .selectedValue=${e.themeDialog.selectedValue} .onPick=${t=>{this.pickTheme(t)}} .onCancel=${()=>{this.setState({themeDialog:void 0})}}></command-picker>`:null}
1992
2000
  ${this.settingsSection!==void 0?l`<settings-dialog .section=${this.settingsSection} .actions=${this.getActions()} .onNavigate=${t=>{this.navigateSettings(t)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${t=>{this.applyClientConfig(t)}}></settings-dialog>`:null}
1993
2001
  </div>
1994
- `}};we.styles=Yp;Ee([x()],we.prototype,"state",2);Ee([re("chat-view")],we.prototype,"chatView",2);Ee([re("prompt-editor")],we.prototype,"promptEditor",2);Ee([x()],we.prototype,"activeThemeId",2);Ee([x()],we.prototype,"isRefreshingApp",2);Ee([x()],we.prototype,"settingsSection",2);Ee([x()],we.prototype,"shortcutConfig",2);we=Ee([A("pi-web-app")],we);function Hm(){const e=new fp;return e.register({id:"core",plugin:ip}),e.register({id:"themes",plugin:np}),e}function qm(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 Vm(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function Km(e,t){return vn(e,t)}function vn(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function Gm(e){const t=m(e),i=e.selectedMachine,s=e.machineStatuses[t]?.status??i?.status;if(!(s==="offline"||s==="error"))return qo(e.machineActivities[t])}function Jm(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function Qr(e){return pi(e.status,e.activity)}function Qm(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function Zr(){return{}}function Xr(e,t){return JSON.stringify([e,t])}function Zm(e){return`'${e.replaceAll("'","'\\''")}'`}function Yr(e){return e instanceof Error?e.message:String(e)}function Xm(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Ym(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function eg(e){return e==="off"||e==="minimal"||e==="low"||e==="medium"||e==="high"||e==="xhigh"}function tg(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)"}}function ig(e){switch(e){case"off":return"关闭";case"minimal":return"极简";case"low":return"低";case"medium":return"中";case"high":return"高";case"xhigh":return"超高"}}export{E as a,l as b,Ye as c,fg as d,re as e,hg as f,I as i,d as n,x as r,ug as s,A as t};
2002
+ `}};we.styles=ah;Ee([x()],we.prototype,"state",2);Ee([re("chat-view")],we.prototype,"chatView",2);Ee([re("prompt-editor")],we.prototype,"promptEditor",2);Ee([x()],we.prototype,"activeThemeId",2);Ee([x()],we.prototype,"isRefreshingApp",2);Ee([x()],we.prototype,"settingsSection",2);Ee([x()],we.prototype,"shortcutConfig",2);we=Ee([A("pi-web-app")],we);function Xm(){const e=new Sp;return e.register({id:"core",plugin:dp}),e.register({id:"themes",plugin:fp}),e}function Ym(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 eg(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function tg(e,t){return kn(e,t)}function kn(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function ig(e){const t=m(e),i=e.selectedMachine,s=e.machineStatuses[t]?.status??i?.status;if(!(s==="offline"||s==="error"))return Zo(e.machineActivities[t])}function sg(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function Yr(e){return pi(e.status,e.activity)}function rg(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function eo(){return{}}function to(e,t){return JSON.stringify([e,t])}function og(e){return`'${e.replaceAll("'","'\\''")}'`}function io(e){return e instanceof Error?e.message:String(e)}function ng(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function ag(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function lg(e){return e==="off"||e==="minimal"||e==="low"||e==="medium"||e==="high"||e==="xhigh"}function cg(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)"}}function dg(e){switch(e){case"off":return"关闭";case"minimal":return"极简";case"low":return"低";case"medium":return"中";case"high":return"高";case"xhigh":return"超高"}}export{E as a,l as b,Ye as c,Sg as d,re as e,yg as f,I as i,d as n,x as r,xg as s,A as t};